简体   繁体   English

提取古罗比溶液指数

[英]Extracting Gurobi Solution Index

I have a bunch of gurobi variables y[0],y[1],...,y[n] x[0],x[1],...,x[m]. 我有一堆gurobi变量y [0],y [1],...,y [n] x [0],x [1],...,x [m]。 I would like to be able to figure out the indices of the optimal y's that are not zero. 我希望能够找出不为零的最优y的索引。 In other words, if the optimal solution is y[0]=0, y[1]=5, y[2]=0, y[3]=1, I would like to return [1,3]. 换句话说,如果最优解为y [0] = 0,y [1] = 5,y [2] = 0,y [3] = 1,我想返回[1,3]。 So far, I have 到目前为止,我有

F = []
for v in model.getVars():
   if v.varName[0]=='y' and v.x>0:
     F.append[v.varName]

This, in the above example, would give me ['y[1]', 'y[3]']. 在上面的示例中,这将给我['y [1]','y [3]']。 Since this output is a string, I'm not sure how I can get the 1 and 3 out of it. 由于此输出是字符串,因此我不确定如何从中获取1和3。 Please help. 请帮忙。

Thanks in advance! 提前致谢!

I am using the following which works: 我正在使用以下有效的方法:

Index_List = []
for v in m.getVars():
       if v.varName[0] == 'y' and v.x>0:

           Index = int(v.varName[2]) 

           for j in range(3,3+100)):
               BOOL = False 
               try:
                   IndexNEW =int(v.varName[j])
                   Index = 10*Index+IndexNEW
                   BOOL = True
               except ValueError:
                   ()
               if not BOOL:
                   break
       Index_List.append(Index)

The resulting Index_List is as desired. 结果Index_List是所需的。 There must be a better way though. 当然,必须有更好的方法。

Assuming 假设

from gurobipy import *
m = Model()

If you create a gurobi tupledict for your variables with 如果您使用以下命令为变量创建Gurobi元组

x = m.addVars(nx, vtype=GRB.INTEGER, name="x")
y = m.addVars(ny, vtype=GRB.INTEGER, name="y")
# ...your constraints and objective here..

then you can directly call the attributes for your variables (in your case the .X attribute for the variable value in the current solution). 那么您可以直接调用变量的属性(在当前情况下,是变量值的.X属性)。 Using a list comprehension it could be done with: 使用列表推导可以做到:

m.optimize()
if m.status == GRB.OPTIMAL:
    indices = [i for i in range(ny) if y[i].X > 0]

where nx and ny are the number of your variables. 其中nxny是您的变量数。

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

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