这是由函数定义的约束:
def my_constraint(model, j):
a = sum(model.variable_1[i, j] for i in model.i) + sum(model.variable_2[o, j] for o in model.o if o != j)
b = model.variable_3[j]
# Apparently, the order matters !?
return a == b
# return b == a
model.my_constraint = pe.Constraint(model.j, rule=my_constraint)
我认为等式项的顺序并不重要,但如果我交换它们,我会得到不同的结果。
我不知道如何弄清楚这件事的真相。
生成的 .nl 文件略有不同,但我陷入了死胡同,因为我不知道如何解释它们。
调查 .nl 文件
两个三行集合有符号差异。
文件1:
[...]
24 1
32 -1
35 1
J78 3
25 1
33 -1
34 1
[...]
文件2:
[...]
24 -1
32 1
35 -1
J78 3
25 -1
33 1
34 -1
[...]
当将两个文件输入 ipopt 时,我得到文件 1 的“不可行”和文件 2 的解决方案。如果我编辑文件 1 来更改第一个或第二个三行集中的符号,我会得到收敛与文件 2 的结果相同。
因此表达式等式的顺序应该不重要,但在更改它时,我在 .nl 文件中得到了一个重要的符号差异。
演示术语顺序如何影响 .nl 文件的简单示例
from pyomo.environ import ConcreteModel, Set, Var, Constraint, Objective
from pyomo.opt import SolverFactory
model = ConcreteModel()
model.i = Set(initialize=['I1'])
model.j = Set(initialize=['J1'])
model.v1 = Var(model.i, model.j)
model.v2 = Var(model.i, model.j)
model.v3 = Var(initialize=0, bounds=(0, None))
def c1(model, i, j):
#return model.v2[i, j] == model.v1[i, j]
return model.v1[i, j] == model.v2[i, j]
model.c1 = Constraint(model.i, model.j, rule=c1)
def objective_rule(model):
return model.v3
model.objective = Objective(rule=objective_rule)
opt = SolverFactory('ipopt')
opt.solve(model, keepfiles=True)
根据约束 c1 中的项的顺序,我没有得到相同的 .nl 文件。
更具体地说,两个文件除了两行之外都是相同的:
g3 1 1 0 # problem unknown
3 1 1 0 1 # vars, constraints, objectives, ranges, eqns
0 0 0 0 0 0 # nonlinear constrs, objs; ccons: lin, nonlin, nd, nzlb
0 0 # network constraints: nonlinear, linear
0 0 0 # nonlinear vars in constraints, objectives, both
0 0 0 1 # linear network variables; functions; arith, flags
0 0 0 0 0 # discrete variables: binary, integer, nonlinear (b,c,o)
2 1 # nonzeros in Jacobian, obj. gradient
0 0 # max name lengths: constraints, variables
0 0 0 0 0 # common exprs: b,c,o,c1,o1
C0
n0
O0 0
n0
x1
2 0
r
4 0.0
b
3
3
2 0
k2
1
2
J0 2
0 -1 # The other file reads 0 1
1 1 # 1 -1
G0 1
2 1
求解时,我得到了相同的结果。可能是因为这个例子很垃圾。
最佳答案
理论上的解释是,您正在看到替代的最佳解决方案。根据问题的表述,您完全有可能获得不止一种具有最佳目标值的解决方案。您获得这些的顺序将对约束的顺序敏感。如果您使用 LP 求解器,您应该能够要求它为您提供所有最佳解决方案。
关于python - pyomo 等式表达式可交换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53872031/