我在gekkopython中定义max函数时遇到了问题。你知道吗
sum函数工作正常,但当我创建另一个函数时,它只是用max替换sum,然后抛出以下错误:
这是对我使用的脚本的描述(包括模型、一些数据和结果)
#Model
import numpy as np
from gekko import GEKKO
import numpy as np
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
m = GEKKO() # Initialize gekko
m.options.SOLVER = 3 # IPOPT is an NLP solver
m.options.MAX_ITER = 10000 # maximum number of iterations
m.options.MAX_MEMORY = 6 # (2-10) memory allocation
R_sect_bin = {'W1': {'S1': 1}, 'W2': {'S1': 1, 'S2': 1, 'S4': 1}, 'W3': {'S1': 1, 'S2': 1, 'S3': 1, 'S4': 1, 'S5': 1, 'S6': 1}, 'W4': {'S4': 1}, 'W5': {'S4': 1, 'S5': 1, 'S6': 1}, 'W6': {'S6': 1}}
Input_Services_nonZero = {'S1': {'L1': 1, 'L3': 1}, 'S2': {'L2': 1}, 'S3': {'L4': 1}, 'S4': {'L1': 1}, 'S5': {'L3': 1}, 'S6': {'L1': 1, 'L2': 1}}
V = {}
for w in R_sect_bin:
V[w] = {}
for s in R_sect_bin[w]:
V[w][s] = {}
for l in Input_Services_nonZero[s]:
V[w][s][l] = m.Var(value=10, lb=0, ub=100)
#functions:
sum_Vws1 = {}
def VWS1():
global sum_Vws1
for w in R_sect_bin:
sum_Vws1[w] = {}
for s in R_sect_bin[w]:
sum_Vws1[w][s] = m.Intermediate(sum([V[w][s][l] for l in Input_Services_nonZero[s]]))
return sum_Vws1
vws1 = VWS1()
sum_Vws2 = {}
def VWS2():
global sum_Vws2
for w in R_sect_bin:
sum_Vws2[w] = {}
for s in R_sect_bin[w]:
sum_Vws2[w][s] = m.Intermediate(max([V[w][s][l] for l in Input_Services_nonZero[s]]))
return sum_Vws2
vws2 = VWS2()
TypeError Traceback (most recent call last)
<ipython-input-225-b48377242060> in <module>
89 sum_Vws2[w][s] = m.Intermediate(max([V[w][s][l] for l in Input_Services_nonZero[s]]))
90 return sum_Vws2
---> 91 vws2 = VWS2()
92
93 #sum_Vws = {}
<ipython-input-225-b48377242060> in VWS2()
87 sum_Vws2[w] = {}
88 for s in R_sect_bin[w]:
---> 89 sum_Vws2[w][s] = m.Intermediate(max([V[w][s][l] for l in Input_Services_nonZero[s]]))
90 return sum_Vws2
91 vws2 = VWS2()
~\Anaconda3\lib\site-packages\gekko\gk_operators.py in __len__(self)
23 return self.name
24 def __len__(self):
---> 25 return len(self.value)
26 def __getitem__(self,key):
27 return self.value[key]
~\Anaconda3\lib\site-packages\gekko\gk_operators.py in __len__(self)
132
133 def __len__(self):
--> 134 return len(self.value)
135
136 def __getitem__(self,key):
TypeError: object of type 'int' has no len()
何登仁教授的回答是:
您需要使用内置的GEKKO
max2
或max3
函数。否则,Python函数将创建一个没有连续的一阶或二阶导数的表达式,并且基于梯度的解算器很可能无法找到解决方案。你知道吗要使用
max2
或max3
gekko函数,您需要使用pip install gekko==0.2rc6升级到最新的gekko版本(>;0.2rc5)。你知道吗下面是
max2
或max3
的源代码,您也可以在Gekko source中找到。你知道吗max2函数使用MPCC,而max3使用二进制变量。这些函数通过使用函数调用帮助使用这些更复杂的建模形式。您只能用max2或max3比较两个值,因此如果您有一个列表,则需要执行以下操作:
等等
下面是关于why you need to use MPCCs or binary variables的附加信息。还有一个additional example here。你知道吗
相关问题 更多 >
编程相关推荐