简体   繁体   English

如何在PuLP问题中仅访问特定变量?

[英]How do I access only specific variables in a PuLP problem?

In an LP model that I solve with PuLP in python I have two sets of decision variables, for example 在我用python中的PuLP解决的LP模型中,我有两组决策变量,例如

#Variables x 
x = LpVariable.dicts("Decision_x",(range(3),range(3)),0,1,LpInteger)
#Variables y 
y = LpVariable.dicts("Decision_y",(range(3),range(3)),0,1,LpInteger)

After solving the model I am only interested in those variables where x[i][j] takes value 1. I know that with 求解模型后,我只对x [i] [j]取值为1的那些变量感兴趣。

for v in prob.variables():
    if v.varValue == 1:
        print(v)

I can print all variables with their value equal to one. 我可以打印所有值等于1的变量。 Hence, all x and all y variables with their value equal to 1 are printed. 因此,将打印所有x和y值等于1的变量。 How can I manage to access only the x variables so that the y variables do not get printed? 我如何设法仅访问x变量,以便不打印y变量? I tried prob.variables(x) , or prob.variables()[x] but nothing has worked so far. 我尝试了prob.variables(x)prob.variables()[x]但到目前为止没有任何效果。

Then in a next step I would like to extract the indices of the x variables for which x is equal to 1. For example, if x[1][3] == 1 then I want to find those indices 1 and 3. Is their any clever way in PuLP to achieve this? 然后在下一步中,我想提取x等于1的x变量的索引。例如,如果x[1][3] == 1那么我想找到那些索引1和3。他们在PuLP中实现这一目标的任何巧妙方法?

x is a dict. x是一个字典。 Given two indices i,j at x[i][j] you have a pulp.LpVariable . 给定x[i][j]处的两个索引i,j ,则有一个pulp.LpVariable
You know in advance the indices of you x variable, so one way is for example the following 您预先知道了x变量的索引,因此一种方法例如

for i,j in itertools.product(range(3),range(3)):
    if x[i][j].varValue > 0:
        print((i,j), x[i][j].name, x[i][j].varValue)

or if you prefer to keep the indices: 或者,如果您希望保留索引:

x_vars_indices = [(i,j) for i,j in itertools.product(range(3),range(3)) if x[i][j].varValue > 0]

Another way is to iterate the nested dictionary x and get the variables, which are the values in the last layers of the dict. 另一种方法是迭代嵌套字典x并获取变量,这些变量是dict最后一层中的值。

x = {0: {0: Decision_x_0_0, 1: Decision_x_0_1, 2: Decision_x_0_2},...
                ^                  ^                   ^
                |                  |                   |
                              LpVariable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM