FragezeichenPython
FragezeichenPython

Reputation: 31

Formulate a nonlinear optimization problem in Python (gekko) and with m.Equations

I would like to solve an optimization problem with Gekko. The non-linear constraints are generated in a function and passed on as a vector. Since there are vectors, I use m.Equations and m.Array. To make it as simple as possible, I have simplified my problem so that the code remains short and simple. I think my mistake is in how I use m.Equations. The error message is:

Exception: @error: Equation Definition An equation without equality (=) or inequality (>,<) false STOPPING...

This is my code:

import numpy as np
from gekko import GEKKO

def powerf(x):
    U = np.array([[x[2]], [x[3] * m.exp(x[4] * 1j)]])
    G = np.array([[x[0] + x[1] * 1j], [0]])
    L = np.array([[0],[1]])

    y = np.array([[-18.8301*1j, 18.8566*1j], [18.8566*1j, -18.8301*1j]])
    I = np.matmul(y, U)
    Iconj = np.real(I) - np.imag(I) * 1j

    S = np.matmul(np.diagflat(Iconj), U)
    P = np.real(S) - np.real(G) + np.real(L)
    Q = np.imag(S) - np.imag(G) + np.imag(L)
    return np.concatenate((P,Q)).reshape(4,)

m = GEKKO()
x =  m.Array(m.Var,5)
ig = [0,  0,    1,    1,      0]
lb = [0, -2, 0.95, 0.95, -np.pi]
ub = [5,  2, 1.10, 1.10,  np.pi]

for i in range(len(x)):
    x[i].value = ig[i]
    x[i].lower = lb[i]
    x[i].upper = ub[i]

m.Equations([powerf(x) == np.zeros(4,)])
m.Obj(x[0])

m.solve()

Upvotes: 3

Views: 206

Answers (1)

John Hedengren
John Hedengren

Reputation: 14376

The m.Equations() function needs a list of equations. Here is one way to pose those:

y = powerf(x)
m.Equations([y[i]==0 for i in range(4)])

The resulting model can be viewed with m.open_folder().

Model
Variables
    v1 = 0, <= 5, >= 0
    v2 = 0, <= 2, >= -2
    v3 = 1, <= 1.1, >= 0.95
    v4 = 1, <= 1.1, >= 0.95
    v5 = 0, <= 3.141592653589793, >= -3.141592653589793
End Variables
Equations
    ((((((((((-0-18.8301j))*(v3))+((18.8566j)*(((v4)*(exp(((v5)*(1j))))))))-0j))*(v3))+((0)*(((v4)*(exp(((v5)*(1j))))))))-(v1+((v2)*(1j))))+0)=0
    (((((0)*(v3))+((((((18.8566j)*(v3))+(((-0-18.8301j))*(((v4)*(exp(((v5)*(1j))))))))-0j))*(((v4)*(exp(((v5)*(1j))))))))-0)+1)=0
    True
    True
    minimize v1
End Equations

End Model

Equations 3 and 4 from the list do not appear to have Gekko variables so they return True. One other thing to consider is that Gekko doesn't currently support imaginary numbers natively so the problem needs to reformed into separate variables for imaginary value and real values such as x_real[i] and x_im[i]. A more readable form of the objective is m.Minimize(x[0]).

Upvotes: 2

Related Questions