Skip to content

Cannot use indexed parameter constructed from numpy array in expression  #2033

@QuriousCube

Description

@QuriousCube

Summary

I try to construct an expression with a pyo.Param that is initialized with values in a numpy array. But that leads to an error. A workaround is to convert the numpy's dtype into python float/int.

Steps to reproduce the issue

$ conda install -c conda-forge pyomo
$ python3 test.py
# test.py
import pyomo.environ as pyo
import numpy as np

m = pyo.ConcreteModel()

m.ix_set = pyo.RangeSet(2)

p_init = np.array([0, 1])
def init_workaround(model, i):
    return p_init[i - 1]  # workaround: use .item() method here.

m.p = pyo.Param(m.ix_set, initialize=init_workaround)
m.v = pyo.Var(m.ix_set)

expr = m.p[1] > m.v[1]

Error Message

Traceback (most recent call last):
  File "<...>/test_constraint_ix.py", line 15, in <module>
    expr = m.p[1] > m.v[1]
  File "pyomo/core/expr/logical_expr.pyx", line 170, in 
    pyomo.core.expr.logical_expr.InequalityExpression.__bool__
    pyomo.common.errors.PyomoException:
        Cannot convert non-constant expression to bool.
        This error is usually caused by using an expression in a boolean
        context such as an if statement. For example, 
            m.x = Var()
            if m.x <= 0:
            ...
        would cause this exception.

Information on your system

Pyomo version: 6.0.1
Python version: 3.9.5
Operating system: Fedora 33
How Pyomo was installed (PyPI, conda, source): conda-forge
Solver (if applicable): not applicable

Additional information

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions