Search code examples
pythonpyomoipopt

How to write a multi-conditional nonlinear piecewise function as the objective function in Pyomo?


I am struggling to write a nonlinear piecewise function inside of the objective function in Pyomo. this function is defined as follows:

def U3(xph,Hz,omega,U_alpha3,landah,n):
       Ucost=0
       for h in range(Hz):
              h=int(h)
              x=xph[0,h]
              omega=landah[n,h]
              if x<=omega/U_alpha3:
                     u3=omega*x-U_alpha3/2*x**2
              else: 
                     u3=0.5*omega**2/U_alpha3
              Ucost=Ucost+u3
       return Ucost

in this code my decision variable is xph and the other parameters are constant. the problem in this code is that it cannot compare x<=omega/U_alpha3 statement and the following error appears:

TypeError: '<=' not supported between instances of 'IndexedComponent_slice' and 'numpy.float64'

this function actually has more than 2 conditions so I couldn't use Expr_If expression class.


Solution

  • The error belongs to this conditional line of code:

    if x<=omega/U_alpha3:
    

    in this condition, x is 'IndexedComponent_slice' type, while omega/U_alpha3 is 'numpy.float64' so the Pyomo can not compare them. I realized that if I substitute x with value(x), the error disappears.