pyomo
pyomo copied to clipboard
Kernel: a==x triggers exception when type(a) is numpy.float64
Description
This code snippet generates an error
a = np.float64(45.3)
x = variable()
expr = a==x
Error Message
AttributeError Traceback (most recent call last)
<ipython-input-185-b00bbc2baf1a> in <module>
1 a = np.float64(45.3)
2 x = variable()
----> 3 expr = a==x
pyomo\core\expr\numvalue.pyx in pyomo.core.expr.numvalue.NumericValue.__eq__()
pyomo\core\expr\logical_expr.pyx in pyomo.core.expr.logical_expr._generate_relational_expression()
AttributeError: 'numpy.ndarray' object has no attribute 'is_expression_type'
Additional information
These other snippets don't generat errors:
a = float(45.3)
x = variable()
expr = a==x
a = np.float64(45.3)
x = variable()
expr = x==a
What versions of Pyomo and Numpy are you using?
I'm unable to recreate this error using the latest version of Pyomo and Numpy 1.17.3.
>>> from pyomo.environ import *
>>> import numpy as np
>>> m = ConcreteModel()
>>> m.x = Var()
>>> a = np.float64(45.3)
>>> e = a == m.x
>>> print(e)
x == 45.3
>>> e = m.x == a
>>> print(e)
x == 45.3
>>> a = float(45.3)
>>> e = m.x == a
>>> print(e)
x == 45.3
>>> e = a == m.x
>>> print(e)
x == 45.3
Thanks for you answer! I am using pyomo 6.0 and numpy 1.20.2. Based on your test, I made a few more tests that you can check below. From these, I have the feeling this is related to my usage of pyomo.kernel objects (block and variable). I like these objects especially because block can be sub-classed. Thanks again Michel
Works:
from pyomo.environ import *
from pyomo.kernel import *
import numpy as np
a = np.float64(45.3)
b = ConcreteModel()
b.x = Var()
expr = a==b.x
Doesn't work:
from pyomo.environ import *
from pyomo.kernel import *
import numpy as np
a = np.float64(45.3)
b = ConcreteModel()
b.x = variable()
expr = a==b.x
Doesn't work:
from pyomo.environ import *
from pyomo.kernel import *
import numpy as np
a = np.float64(45.3)
b = block()
b.x = Var()
expr = a==b.x
Doesn't work:
from pyomo.environ import *
from pyomo.kernel import *
import numpy as np
a = np.float64(45.3)
b = ConcreteModel()
b.x = variable()
expr = a==b.x
Your first two examples have worked correctly since Pyomo 6.1 (Aug 2021). The last two examples mix the core AML and the Kernel library, which is not supported (so exceptions are expected).