Pyomo / pyomo

An object-oriented algebraic modeling language in Python for structured optimization problems.
https://www.pyomo.org
Other
1.95k stars 504 forks source link

ExternalFunction evaluate_fgh doesn't work correctly with string arguments #2528

Closed eslickj closed 1 year ago

eslickj commented 1 year ago

Summary

When you have an ExternalFunction that expects string arguments, the evaluate_fgh method includes the string arguments when counting how big the gradient and hessian arrays are. This means that you get the gradient and hessian but they are larger than they should be and padded with random junk from memory at the end.

Steps to reproduce the issue

Run the example below (requires IDAES). If you have an example function that uses string args that will work too.

# example.py
import pyomo.environ as pyo
from idaes.models.properties.general_helmholtz.helmholtz_functions import (
    add_helmholtz_external_functions,
    HelmholtzParameterBlock,
    HelmholtzThermoExpressions,
    AmountBasis,
)

m = pyo.ConcreteModel()
m.param_block = HelmholtzParameterBlock(
    pure_component="r134a", amount_basis=AmountBasis.MASS
)

te = HelmholtzThermoExpressions(m, m.param_block)

add_helmholtz_external_functions(m, "tau_func")

y, g, h = m.tau_func.evaluate_fgh(args=("r134a", 529.47, 100))
print(f"T = {374.18/y}")
print(g)
print(h)

Error Message

There is no error message.

Information on your system

Pyomo version: Pyomo 6.4.2 (devel {typing-overload}) (CPython 3.10.4 on Darwin 21.6.0)

jsiirola commented 1 year ago

@eslickj: what do you think the expected behavior should be? Should fgh only return the gradient / Hessian for the numeric arguments (like the ASL), or should it return the "full" gradient / hessian with 0's inserted at the correct indices. I tend to favor the latter (especially since the pyomo side doesn't have the indirection that the ASL ra / at interface enforces).

eslickj commented 1 year ago

0's is totally fine with me. It makes sense. As long as it's documented and everything works right in Pyomo.