如何在 Gekko 中动态构建约束? [英] How could constraints be dynamically constructed in gekko?
问题描述
我是gekko的新手,想在我的线性编程问题中使用它.
I'm a newbie in gekko, and want to use it in my linear programming problems.
我在单独的词典(my_vars,Cost,Min和Max)中以变量名作为键,具有变量名,成本,最小和最大界限,目的是通过确定满足约束条件的变量数量来最大程度地降低总成本.
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.
我做了如下;
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
在这里,我想使用可变的原始名称代替xi,有什么办法吗?
Here I'd like to use variable original names instead of xi, is there any way?
它继续为;
LP.Minimize(sum(float(Cost[list(my_vars)[i]])*vars[i] for i in range(len(my_vars))))
LP.Equation(sum(vars) == 100)
我在两个熊猫数据帧文件中都有约束的左侧(LHS)(变量系数)和右侧(RHS)编号,并且喜欢使用for循环构造方程.
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.
我不知道该怎么做?
推荐答案
以下是使用字典值构造问题的一种方法:
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
以下是一些利用Gekko进行高效线性编程的示例.问题稀疏.
Here are a few examples of efficient linear programming with Gekko by exploiting problem sparsity.
这篇关于如何在 Gekko 中动态构建约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!