Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions pyomo/contrib/viewer/tests/test_data_model_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,14 @@
from pyomo.core.base.units_container import pint_available


class Fake_numpy:
class float64(float):
pass

class int64(int):
pass


@unittest.skipIf(not pint_available, "Pyomo units are not available")
class TestDataModelItem(unittest.TestCase):
def setUp(self):
Expand All @@ -66,6 +74,8 @@ def setUp(self):
m.b1.e3 = Expression(expr=m.x[3] * m.x[1])
m.b1.e4 = Expression(expr=log(m.x[2]))
m.b1.e5 = Expression(expr=log(m.x[2] - 2))
m.b1.e6 = Expression(expr=Fake_numpy.float64(3.2))
m.b1.e7 = Expression(expr=Fake_numpy.int64(3))

def blackbox(a, b):
return sin(a - b)
Expand Down Expand Up @@ -125,6 +135,24 @@ def test_expr_calc_log_neg(self):
cdi.ui_data.calculate_expressions()
self.assertIsNone(cdi.get("value"))

def test_expr_calc_numpy_float(self):
cdi = ComponentDataItem(
parent=None, ui_data=UIData(model=self.m), o=self.m.b1.e6
)
cdi.ui_data.calculate_expressions()
self.assertIsInstance(pyo.value(self.m.b1.e6), Fake_numpy.float64)
self.assertAlmostEqual(cdi.get("value"), 3.2)
self.assertNotIsInstance(cdi.get("value"), Fake_numpy.float64)

def test_expr_calc_numpy_int(self):
cdi = ComponentDataItem(
parent=None, ui_data=UIData(model=self.m), o=self.m.b1.e7
)
cdi.ui_data.calculate_expressions()
self.assertIsInstance(pyo.value(self.m.b1.e7), Fake_numpy.int64)
self.assertEqual(cdi.get("value"), 3)
self.assertNotIsInstance(cdi.get("value"), Fake_numpy.int64)

def test_expr_calc_value_None(self):
cdi = ComponentDataItem(
parent=None, ui_data=UIData(model=self.m), o=self.m.b1.e3
Expand Down
4 changes: 4 additions & 0 deletions pyomo/contrib/viewer/ui_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,10 @@ def calculate_expressions(self):
for o in self.model.component_data_objects(pyo.Expression, active=True):
try:
self.value_cache[o] = pyo.value(o, exception=False)
if "numpy.float" in str(type(self.value_cache[o])):
self.value_cache[o] = float(self.value_cache[o])
elif "numpy.int" in str(type(self.value_cache[o])):
self.value_cache[o] = int(self.value_cache[o])
except ZeroDivisionError:
self.value_cache[o] = "Divide_by_0"
try:
Expand Down
Loading