如何在GEKKO中实现分段功能?

How to implement the segment function in GEKKO?

我正在尝试通过 GEKKO 建模和求解非线性优化问题。 objective 函数如下:

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)))

问题是我需要 alpha_beta(x) 函数(wrt to the decision variables, shown as follows)是一个段形式,我该如何编写这个函数才能解决这个问题?

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])

非常感谢!

使用 m.if3() Gekko 函数根据 x 的值使用不同的函数。另外,将 objective 函数中的 abs() 函数替换为 m.abs2()m.abs3() 的 Gekko 版本(首选)。这是一个示例脚本。

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()

这将生成解决方案 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
 ---------------------------------------------------