回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我试图用Python中的GEKKO定义一个优化问题,我想使用一些带有预定义选择列表的设计变量。此外,每个选择都有一个相关的成本,约束条件是总成本应低于指定的限制</p>
<p>下面是一个常见的gekko示例(发现<a href="https://gekko.readthedocs.io/en/latest/examples.html" rel="nofollow noreferrer">here</a>),其修改为<code>x1</code>和<code>x2</code>是<code>sos1</code>。另外,通过对<code>x1</code>和<code>x2</code>所选值的索引,我从另一个列表中找到了它们的相关成本,它们的总和应该小于某个值(约束)</p>
<pre class="lang-python prettyprint-override"><code>from gekko import GEKKO
def test(x1,x2,x3,x4):
res = x1*x4*(x1+x2+x3)+x3
return res
def check(x1,x2):
tt = [1,2,3,4,5]
cost = [10,10,10,2,1]
if x1.value in tt:
y1 = tt.index(x1.value)
y2 = tt.index(x2.value)
C = cost[y1]+cost[y2]
return C
return 10
m = GEKKO() # Initialize gekko
m.options.SOLVER=1 # APOPT is an MINLP solver
# optional solver settings with APOPT
m.solver_options = ['minlp_maximum_iterations 500', \
# minlp iterations with integer solution
'minlp_max_iter_with_int_sol 10', \
# treat minlp as nlp
'minlp_as_nlp 0', \
# nlp sub-problem max iterations
'nlp_maximum_iterations 50', \
# 1 = depth first, 2 = breadth first
'minlp_branch_method 1', \
# maximum deviation from whole number
'minlp_integer_tol 0.05', \
# covergence tolerance
'minlp_gap_tol 0.01']
# Integer constraints for x3 and x4
x3 = m.Var(value=1,lb=1,ub=5,integer=True)
x4 = m.Var(value=2,lb=1,ub=5,integer=True)
x1 = m.sos1([1,2,3,4,5])
x2 = m.sos1([1,2,3,4,5])
# Equations
m.Equation(x1*x2*x3*x4>=25)
m.Equation(x1**2+x2**2+x3**2+x4**2==40)
m.Equation(check(x1,x2)<=5)
m.Obj(test(x1,x2,x3,x4)) # Objective
m.solve(disp=False) # Solve
print('Results')
print('x1: ' + str(x1.value))
print('x2: ' + str(x2.value))
print('x3: ' + str(x3.value))
print('x4: ' + str(x4.value))
print('Objective: ' + str(m.options.objfcnval))
</code></pre>
<p>注意:我必须在<code>check</code>函数中添加一个if块,作为<code>x1</code>的初始值,<code>x2</code>似乎为零</p>
<p>这段代码不工作,我得到以下错误</p>
<pre class="lang-python prettyprint-override"><code>> Exception has occurred: Exception
@error: Equation Definition
Equation without an equality (=) or inequality (>,<)
true
STOPPING...
</code></pre>
<p>我不知道是什么导致了这个错误。我应该如何重新制定模型以获得期望的结果</p>
<p>编辑:这个示例代码只是我试图重新创建错误。我的实际应用是设计一个工程系统。例如,假设系统有两个组件-电池和灯泡。我有两种电池选择,电池A重10公斤,可靠性为0.97;电池B重6公斤,可靠性为0.75。同样,灯泡也有不同的选择。我需要为电池和灯泡选择一个选项,以使总系统可靠性尽可能高(目标),总重量小于“x”kg(限制)。在上面的代码中,将<code>x1</code>和<code>x2</code>值视为组件的选定选项,我找到它们的索引以获取它们的相关重量/成本(如果选择了电池A和灯泡B,我获取它们的重量以检查总重量是否小于允许的限制)。现在,我的实际系统为每个组件提供了<code>n</code>个组件和<code>m</code>个选项。每个选择都有相关的权重、成本、可靠性等。我试图找到最佳组合,在系统权重、成本等约束条件下使系统可靠性最大化</p>