问题
I would like to obtain the coefficients of a linear constraint c
of a pyomo model m
.
For instance, for
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)
I would like to get the array c_coef = [2,5,0,1]
.
The answer to this question explains how to obtain all variables occurring in a linear constraint and I can easily use this to create the zero-coefficients for variables which don't occur in a constraint. However, I am struggling with the nonzero-coefficients. My current approach uses the private attribute _coef
, that is c_nzcoef = m.c.body._coef
which I probably should not use.
What would be the proper way to obtain the nonzero coefficients?
回答1:
The easiest way to get the coefficients for a linear expression is to make use of the "Canonical Representation" data structure:
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]
This should be valid for any version of Pyomo from 4.0 through at least 5.3.
来源:https://stackoverflow.com/questions/48749651/get-coefficients-of-a-linear-pyomo-constraint