2

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 Answers1

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.

jsiirola
  • 2,259
  • 2
  • 9
  • 12
  • How about newer versions of Pyomo (I would like to make use of numerical derivatives which seems to be available in newer pyomo versions)? When I update, it seems that I also have to replace `identify variables` and `clone_expression`. If this is too much to add to your post, I can also post a separate question. – Christoph Neumann May 28 '19 at 14:16