不了解model.getAttr()的参数

时间:2019-01-30 13:39:11

标签: python gurobi

我是Python和Gurobi的新手,我正在阅读model.getAttr手册,并且我了解返回的参数是model.getAttr(attrname,objs = None)。

我不理解的是下面手册中提供的示例代码:

print(model.getAttr(“ Pi”,model.getConstrs()))

我的代码中attrname“ Pi”不在任何地方,为什么它仍然能够返回值?

请帮助!

 try:

    # Create a new model
    m = Model("simplelp")

    # Create variables
    x1 = m.addVar(ub = 10, name="x1")
    x2 = m.addVar(name="x2")
    x3 = m.addVar(name="x3")

    # Set objective
    m.setObjective(x1 + 2 * x2 + 5 * x3, GRB.MAXIMIZE)

    # Add constraint: 
    m.addConstr(-x1 + x2 + 3*x3 <= -5, "c0")

    # Add constraint: 
    m.addConstr(x1 + 3*x2 - 7*x3 >= 10, "c1")

    m.optimize()

    # print optimal solutions
    for v in m.getVars():                     #m.getVars() retrieves all the variables in the model, contains v 
        print('%s %g' % (v.varName, v.x))     #v.varName returns name, v.x returns value

    # print optimal value
    print('Obj: %g' % m.objVal)

    # print dual values to all constraints
    print(m.getAttr("Pi", m.getConstrs()))

except GurobiError as e:
    print('Error code ' + str(e.errno) + ": " + str(e))

except AttributeError:
    print('Encountered an attribute error')


1 个答案:

答案 0 :(得分:1)

我想你在误会什么。 “ Pi”是您使用m.addConstr()方法创建的线性约束对象属性。有关所有可用属性的概述,请参见here

让我们考虑一下

from gurobipy import Model, GRB

# Create a new model
m = Model("simplelp")

# Create variables
x1 = m.addVar(ub = 10, name="x1")
x2 = m.addVar(name="x2")
x3 = m.addVar(name="x3")

# Set objective
m.setObjective(x1 + 2 * x2 + 5 * x3, GRB.MAXIMIZE)

# Add constraint: 
con0 = m.addConstr(-x1 + x2 + 3*x3 <= -5, "c0")

# Add constraint: 
con1 = m.addConstr(x1 + 3*x2 - 7*x3 >= 10, "c1")

m.optimize()

然后m.getConstrs()返回一个包含所有约束对象的列表:

In [16]: print(m.getConstrs())                                                                                                                          
Out[16]: [<gurobi.Constr c0>, <gurobi.Constr c1>]

m.getAttr(attrname, objectslist)为对象列表中的所有对象返回属性attrname的值:

In [18]: print(m.getAttr("Pi", [con0, con1]))                                                                                                               
Out[18]: [2.0, 0.0]

In [19]: print(m.getAttr("Pi", m.getConstrs()))                                                                                                         
Out[19]: [2.0, 0.0]

In [20]: print([con0.Pi, con1.Pi])                                                                                                                          
Out[20]: [2.0, 0.0]