Search code examples
pythongekko

With Gekko, is it possible to create sub-model or merge models together?


An example would be 2 models (m1 & m2) that work and can be tested independently. One model have an exogenous variable, let say m2 and varX. For now varX = anyConstant

Then without having to copy paste all the code, I want the output of m1 to be the input for varX (which become endogenous) in m2. I now would have a unique model.


Solution

  • You can create two models and export values from the first model to be used in the second model. Here is an example that creates two models m1 and m2. The first model is solved to determine the value of x1 that is exported by assigning output_m1 to x1.value[0]. This is an input parameter of the second model with varX = m2.Param(value=output_m1).

    from gekko import GEKKO
    
    # Model 1 (m1)
    m1 = GEKKO(remote=False)
    x1 = m1.Var(value=1, lb=0)
    m1.Equation(x1**2 == 4)
    m1.solve(disp=False)
    output_m1 = x1.value[0]
    print(f"Output from m1: {output_m1}")
    
    # Model 2 (m2)
    m2 = GEKKO(remote=False)
    varX = m2.Param(value=output_m1)
    x2 = m2.Var(value=1)
    m2.Equation(2*x2 - varX == 0)
    m2.solve(disp=False)
    print(f"Output from m2: {x2.value[0]}")
    

    The output from this code is:

    Output from m1: 2.0000000929
    Output from m2: 1.0
    

    The value of varX can also be updated if there are multiple solutions such as with varX.value=output_m1.