获取线性 pyomo 约束的系数

Get coefficients of a linear pyomo constraint

我想获得 pyomo 模型 m 的线性约束 c 的系数。

例如,

    m= ConcreteModel()
    m.x_1 = Var()
    m.x_2 = Var()
    m.x_3 = Var(within = Integers)
    m.x_4 = Var(within = Integers)
    m.c= Constraint(expr=2*m.x_1 + 5*m.x_2 + m.x_4 <= 2)

我想得到数组c_coef = [2,5,0,1]

的答案解释了如何获取线性约束中出现的所有变量,我可以轻松地使用它来为不出现在约束中的变量创建零系数。但是,我正在努力处理非零系数。我当前的方法使用 private 属性 _coef,即我可能不应该使用的 c_nzcoef = m.c.body._coef

获得非零系数的正确方法是什么?

获取线性表达式系数的最简单方法是使用 "Canonical Representation" 数据结构:

from pyomo.repn import generate_canonical_repn
# verify that the expression is linear
if m.c.body.polynominal_degree() == 1:
    repn = generate_canonical_repn(m.c.body)
    for i, coefficient in enumerate(repn.linear or []):
        var = repn.variables[i]

这应该适用于从 4.0 到至少 5.3 的任何 Pyomo 版本。