pythongekkominimization

How to use gekko variables as componets of an array?


I need to solve a minimization problem that involves vectors, I am using cern's root and Gekko to try solving the problem. But I kind of need to build root four-vectors/three with Gekko variables to make the operations easier.

Suposse that I have x1,x2 and x3 as gekko variables. I want to build an array something like:

x = ( x1*sin(x2)cos(x3) , x1sin(x2)*sin(x3) , x1 )

Is that possible? And can I do operations with it? Like:

m.equation(x*x ==20)

Best regards.


Solution

  • Here is an example with the three variables, one equation, and a vector operation with the dot product:

    from gekko import GEKKO
    import numpy as np
    
    m = GEKKO(remote=False)
    x1,x2,x3 = m.Array(m.Var,3)
    x = [x1*m.sin(x2)*m.cos(x3), \
         x1*m.sin(x2)*m.sin(x3), \
         x1]
    m.Equation(np.dot(x,x)==0)
    m.solve(disp=True)
    print(x1.value,x2.value,x3.value)
    

    Gekko produces a solution [0,0,0] when the dot product is 0. It correctly reports an infeasible solution when the dot product is 20.

     ----------------------------------------------
     Steady State Optimization with APOPT Solver
     ----------------------------------------------
        1  0.00000E+00  0.00000E+00
     Successful solution
     
     ---------------------------------------------------
     Solver         :  IPOPT (v3.12)
     Solution time  :   7.099999987985939E-003 sec
     Objective      :   0.000000000000000E+000
     Successful solution
     ---------------------------------------------------
    

    The solution specifics aren't important here, but this is just a demonstration of using arrays and vector operations. Use m.sum() instead of sum() if the vector is very large. Likewise, use m.sum([xi**2 for xi in x]) instead of np.dot(x,x) for large x vectors.

    The CERN ROOT package is a nice complement to the optimization capabilities of gekko to visualize and explore solutions. The ROOT functions can help with pre-processing and post-processing of the optimization solutions but probably can't be used directly in Gekko expressions. Gekko performs automatic differentiation to give exact 1st and 2nd derivative information to gradient-based solvers. Most other packages aren't configured to provide that information or the interface that the solvers need with sparse matrices.