Skip to content

Bug when using set_value with pint Quantity #2494

Open
@andrewlee94

Description

@andrewlee94

Summary

When trying to assign a value to a Pyomo Var using set_value with a pint Quantity as the argument, the following error is returned: pyomo.core.base.units_container.UnitsError: Cannot convert None to m. Units are not compatible. (see below for example and full stack trace).

Steps to reproduce the issue

import pyomo.environ as pyo
import pint

m = pyo.ConcreteModel()
m.v = pyo.Var(initialize=1, units=pyo.units.m)

ureg = pint.UnitRegistry()
Q = 3 * ureg.meter

m.v.set_value(Q)

Error Message

WARNING: Dynamically registering the following numeric type:
Quantity
Dynamic registration is supported for convenience, but there are known
limitations to this approach. We recommend explicitly registering numeric
types using the following functions:
RegisterNumericType(), RegisterIntegerType(), RegisterBooleanType().
Traceback (most recent call last):
File "/home/andrew/idaes/testing/issue_test.py", line 10, in
m.v.set_value(Q)
File "/home/andrew/pyomo/pyomo/pyomo/core/base/var.py", line 371, in set_value
val = units.convert_value(
File "/home/andrew/pyomo/pyomo/pyomo/core/base/units_container.py", line 1289, in convert_value
raise UnitsError(
pyomo.core.base.units_container.UnitsError: Cannot convert None to m. Units are not compatible.

Additional information

The root cause of the issue appears be in units.get_value. Line 370 in var.py (_src_units = units.get_units(val)) is returning None when provided with a pint Quantity, rather than the desired units from the Quantity. This then causes the error checking in units.convert_value to fail with the observed error due to the apparent inconsistent units, hence the Cannot convert None to m.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions