获取线性pyomo约束的系数 [英] Get coefficients of a linear pyomo constraint

查看:206
本文介绍了获取线性pyomo约束的系数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to obtain the coefficients of a linear constraint c of a pyomo model m.

例如,对于

    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属性.

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?

推荐答案

获取线性表达式系数的最简单方法是利用规范表示"数据结构:

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]

这对于从4.0到5.3的任何版本的Pyomo均有效.

This should be valid for any version of Pyomo from 4.0 through at least 5.3.

这篇关于获取线性pyomo约束的系数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆