Skip to content

Units not consistent when differentiate returns zero #3258

Open
@dallan-keylogic

Description

@dallan-keylogic

Summary

When trying to use Pyomo's AD to avoid having the user provide derivative expressions, I discovered that, if the resulting derivative is zero, its units get lost and result in dimensional inconsistencies.

It might make sense to treat zero as having units compatible with everything, but I don't know whether that's possible.

Is there a workaround where I can check if the expression returned by differentiate is zero and provide appropriate units manually?

Steps to reproduce the issue

# diff_units.py
import pyomo.environ as pyo
from pyomo.core.expr.calculus.derivatives import Modes, differentiate
from pyomo.util.check_units import assert_units_equivalent

m = pyo.ConcreteModel()

m.temperature = pyo.Var(units=pyo.units.K, initialize=0)
m.density_param = pyo.Param(
    mutable=True,
    initialize=1000,
    units=pyo.units.kg / pyo.units.m ** 3
)

@m.Expression()
def density(blk):
    return blk.density_param


diff_expr = differentiate(
                expr=m.density,
                wrt=m.temperature,
                mode=Modes.reverse_symbolic
            )
print(diff_expr)
assert_units_equivalent(
    diff_expr,
    pyo.units.kg / pyo.units.m ** 3 / pyo.units.K
)

Error Message

Units between dimensionless and kilogram / kelvin / meter ** 3 are not consistent.
  File "C:\Users\[REDACTED]\Desktop\diff_units.py", line 25, in <module>
    assert_units_equivalent(
pyomo.core.base.units_container.UnitsError: Units between dimensionless and kilogram / kelvin / meter ** 3 are not consistent.

Information on your system

Pyomo version: 6.7.2a0
Python version: 3.10.14
Operating system: Windows 10
How Pyomo was installed (PyPI, conda, source): IDAES advanced user installation
Solver (if applicable): n/a

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