codykarcher / pyomo

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

Units can fail silently when parsing numpy array inputs #16

Open codykarcher opened 2 months ago

codykarcher commented 2 months ago

This code produces an error in parse_inputs that is not reflective of the true issue: the model has been defined in feet and the user is passing a dimensionless parameter. Need to fix this.

import pyomo
import numpy as np
import pyomo.environ as pyo
from pyomo.environ import units
from pyomo.contrib.edi import Formulation, ediprint
# from pyomo.contrib.edi import Formulation, BlackBoxFunctionModel, ediprint
from pyomo.common.formatting import tostr
from pyomo.environ import units as pyomo_units

class Parabola(BlackBoxFunctionModel):
    def __init__(self):
        super(Parabola, self).__init__()
        self.description = 'This model evaluates the function: y = x**2'
        self.inputs.append(
            name='x', size=3, units='ft', description='The x variable'
        )
        self.outputs.append(
            name='y', size=3, units='ft**2', description='The y variable'
        )
        self.availableDerivative = 1
        self.post_init_setup(len(self.inputs))

    def BlackBox(self, *args, **kwargs):  # The actual function that does things
        runCases, remainingKwargs = self.parseInputs(*args, **kwargs)

        x = self.sanitizeInputs(runCases[0]['x'])
        x = np.array([pyo.value(xval) for xval in x], dtype=np.float64)

        y = x**2  # Compute y
        dydx = 2 * x  # Compute dy/dx

        y = y * units.ft**2
        dydx = np.diag(dydx)
        dydx = dydx * units.ft  # units.ft**2 / units.ft

        return y, [dydx]  # return z, grad(z), hess(z)...

bb = Parabola()
bbo = bb.BlackBox(np.array([1,1,1]))
ediprint(bbo)
bbs = bb.BlackBox_Standardized(np.array([1,1,1]))