[Python] How to solve boolean logic with Pyomo

Discussão em 'Python' iniciado por Stack, Maio 22, 2025.

  1. Stack

    Stack Membro Participativo

    I need to include a calculation in Pyomo optimization but I receive a message that it becomes boolean logic. I am using glpk which is suitable for linear programming. Is there an alternative to include this calculation in the optimization? Below is a very simplified example.

    spread_min_150 = 0.01
    spread_150_max = 0.05

    SPOT = 600
    avg = 10
    h = 730


    def price(SPOT, POSITION, spread_min_150, spread_150_max):
    if SPOT < 150:
    spread_price = SPOT * (1 + spread_min_150) if POSITION >= 0 else SPOT * (1 - spread_min_150)
    else:
    spread_price = SPOT * (1 + spread_150_max) if POSITION >= 0 else SPOT * (1 - spread_150_max)
    return spread_price

    model = pyo.ConcreteModel()
    model.a = pyo.Var(domain=pyo.NonNegativeReals)
    model.b = pyo.Var(domain=pyo.NonNegativeReals)

    mcp = avg * 730 - (model.a*730 + model.b*730)

    B = mcp * price(SPOT, mcp, spread_min_150, spread_150_max)

    model.obj = pyo_Objective(expr=B, sense=pyo.minimize)

    model.obj.pprint()

    opt = pyo.SolverFactory('glpk') # ('glpk', executable='/usr/bin/glpsol')
    result = opt.solve(model)
    print(result)
    model.display()


    The error message is below.

    ---------------------------------------------------------------------------
    PyomoException Traceback (most recent call last)
    <ipython-input-5-c3d5ce23abb2> in <cell line: 22>()
    20 mcp = avg * 730 - (model.a*730 + model.b*730)
    21
    ---> 22 B = mcp * price(SPOT, mcp, spread_min_150, spread_150_max)
    23
    24 model.obj = pyo_Objective(expr=B, sense=pyo.minimize)

    1 frames
    /usr/local/lib/python3.10/dist-packages/pyomo/core/expr/relational_expr.py in __bool__(self)
    46 if self.is_constant():
    47 return bool(self())
    ---> 48 raise PyomoException(
    49 """
    50 Cannot convert non-constant Pyomo expression (%s) to bool.

    PyomoException: Cannot convert non-constant Pyomo expression (0 <= 7300 - (730*a + 730*b)) to bool.
    This error is usually caused by using a Var, unit, or mutable Param in a
    Boolean context such as an "if" statement, or when checking container
    membership or equality. For example,
    >>> m.x = Var()
    >>> if m.x >= 1:
    ... pass
    and
    >>> m.y = Var()
    >>> if m.y in [m.x, m.y]:
    ... pass
    would both cause this exception.

    Continue reading...

Compartilhe esta Página