Search code examples
pythonoptimizationgekko

How to implement the segment function in GEKKO?


I am trying to model and solve a nonlinear optimization problem through GEKKO. The objective function is like:

m.Minimize(k*(w1*abs(x0-L10)+w2*abs(x1-L20))+β*Dindf[0]*(w1*alpha_beta(x0)+w2*alpha_beta(x1)+w1***alpha_beta**(x2)+w2*alpha_beta(x3)) +\
                k*(w1*abs(x2-x0) + w2*abs(x3-x1)+w1*abs(x4-x2) + w2*abs(x5-x3)))

The problem is I need the alpha_beta(x) function(wrt to the decision variables, shown as follows) to be a segment form, how can I code this function so that I can solve the problem?

def alpha_beta(x):
    a = 0.0019727939
    b = 0.0078887
    Lmin, Lnom, Lmax = 0.8035, 2.3811, 3.084
    return np.piecewise(x, [np.logical_and(Lmin <= x, x < Lnom),
                            np.logical_and(Lnom <= x, x <= Lmax)],
                        [lambda x: a * ((x - Lnom)**2) + 0.006226,
                         lambda x: b * ((x - Lnom)**2) + 0.006226, 0])

Thank you very much!


Solution

  • Use the m.if3() Gekko function to use a different function based on the value of x. Also, replace the abs() function in the objective function with the Gekko version of m.abs2() or m.abs3() (preferred). Here is an example script.

    from gekko import GEKKO
    
    m = GEKKO()
    x = m.Var(lb=0.8035,ub=3.084)
    
    def alpha_beta(x):
        a = 0.0019727939
        b = 0.0078887
        Lnom = 2.3811
        e1 = a*(x-Lnom)**2 + 0.006226
        e2 = b*(x-Lnom)**2 + 0.006226
        return m.if3(x-Lnom,e1,e2)
        
    m.Minimize(alpha_beta(x)+m.abs3(-x))
    
    m.solve()
    

    This produces the solution x=0.8035.

     Number of state variables:              9
     Number of total equations: -            6
     Number of slack variables: -            4
     ---------------------------------------
     Degrees of freedom       :             -1
     
     * Warning: DOF <= 0
     ----------------------------------------------
     Steady State Optimization with APOPT Solver
     ----------------------------------------------
    Iter: 1 I: 0 Tm: 0.00 NLPi: 3 Dpth: 0 Lvs: 0 Obj: 8.15E-01 Gap: 0.00E+00
     Successful solution
     
     ---------------------------------------------------
     Solver         :  APOPT (v1.0)
     Solution time  :   1.290000000153668E-002 sec
     Objective      :   0.814635932386315     
     Successful solution
     ---------------------------------------------------