Skip to content
Advertisement

How could constraints be dynamically constructed in gekko?

I’m a newbie in gekko, and want to use it in my linear programming problems.

I have variable names, costs, minimum and maximum bounds in separate dictionaries (my_vars, Cost, Min and Max) with variable names as their keys, and the objective is minimizing total cost with determining the amount of variables satisfying the constraints.

I did as below;

LP = GEKKO(remote=False)
vars = LP.Array(LP.Var, (len(my_vars)))
i=0
for xi in vars:
    xi.lower = Min[list(my_vars)[i]]
    xi.upper = Max[list(my_vars)[i]]
    i += 1

Here I’d like to use variable original names instead of xi, is there any way?

it continues as;

LP.Minimize(sum(float(Cost[list(my_vars)[i]])*vars[i] for i in range(len(my_vars))))
LP.Equation(sum(vars) == 100)

Also I have constraint’s left hand side (LHS) (coefficients of variables) and right hand side (RHS) numbers in two pandas data frame files, and like to construct equations using a for loop.

I don’t know how to do this?

Advertisement

Answer

Here is one way to use your dictionary values to construct the problem:

from gekko import GEKKO

# stored as list
my_vars = ['x1','x2']
# stored as dictionaries
Cost = {'x1':100,'x2':125}
Min = {'x1':0,'x2':0}
Max = {'x1':70,'x2':40}

LP = GEKKO(remote=False)
va = LP.Array(LP.Var, (len(my_vars)))  # array
vd = {}                                # dictionary
for i,xi in enumerate(my_vars):
    vd[xi] = va[i]
    vd[xi].lower = Min[xi]
    vd[xi].upper = Max[xi]

# Cost function
LP.Minimize(LP.sum([Cost[xi]*vd[xi] for xi in my_vars])) 
# Summation as an array
LP.Equation(LP.sum(va)==100)
# This also works as a dictionary
LP.Equation(LP.sum([vd[xi] for xi in my_vars])==100)
LP.solve(disp=True)

for xi in my_vars:
    print(xi,vd[xi].value[0])
print ('Cost: ' + str(LP.options.OBJFCNVAL))

This produces a solution:

EXIT: Optimal Solution Found.

 The solution was found.

 The final value of the objective function is  10750.00174236579
 
 ---------------------------------------------------
 Solver         :  IPOPT (v3.12)
 Solution time  :  0.012199999999999996 sec
 Objective      :  10750.00174236579
 Successful solution
 ---------------------------------------------------
 

x1 69.999932174
x2 30.0000682
Cost: 10750.001742

Here are a few examples of efficient linear programming with Gekko by exploiting problem sparsity.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement