英文:
Access decision variable value in function outside objective function Gekko
问题
我需要在目标函数之外访问决策变量。我有以下内容。
tc_var = {}
for index in index_f_a:
tc_var[index] = m.Var(value=25, name='tc_var_{}'.format(index), lb=15, ub=45, integer=False)
def k1(i, z, j, a):
a_dif = tce[(i, z, j, a)] - tc_var[(i, j)].VALUE
return a_dif if a_dif > 0 else 0
m.Minimize(m.sum([k1(i, z, j, a)*KCA for i, z, j, a in index_f_h_a_v]))
在另一个问题中,有人告诉我在目标函数中使用.value
只使用初始值。我应该如何正确地做到这一点(访问决策的值)?
谢谢。
如果我不使用.value
,我会收到以下错误:
已解决
def k1(i, z, j, a):
d = m.Var(lb=0)
s = m.Var(lb=0)
m.Minimize(1e-3*s)
m.Equation(d == (tce[(i, z, j, a)] - tc_var[(i, j)])*KCA + s)
return d
m.Minimize(
m.sum([k1(i, z, j, a) for i, z, j, a in index_f_h_a_v]))
英文:
I need to access the decision variable outside the objective function. I have the following.
tc_var = {}
for index in index_f_a:
tc_var[index] = m.Var(value=25, name='tc_var_{}'.format(index), lb=15, ub=45, integer=False)
def k1(i, z, j, a):
a_dif = tce[(i, z, j, a)] - tc_var[(i, j)].VALUE
return a_dif if a_dif > 0 else 0
m.Minimize(m.sum([k1(i, z, j, a)*KCA for i, z, j, a in index_f_h_a_v]))
In another question, it was told that using .value in the objective only uses the initial value. How can I do this the correct way (access the value decision)?
Thank you.
If I do not use .value, I get the following error:
SOLVED With
def k1(i, z, j, a):
d = m.Var(lb=0)
s = m.Var(lb=0)
m.Minimize(1e-3*s)
m.Equation(d == (tce[(i, z, j, a)] - tc_var[(i, j)])*KCA + s)
return d
m.Minimize(
m.sum([k1(i, z, j, a) for i, z, j, a in index_f_h_a_v]))
答案1
得分: 1
对于条件语句,请使用m.if3()
函数,例如:
def k1(i, z, j, a):
d = m.Intermediate(tce[(i, z, j, a)] - tc_var[(i, j)])
a_dif = m.if3(d, 0, d)
return a_dif
这会添加一个二进制决策变量,因此必须使用APOPT
求解器(m.options.SOLVER=1
)来解决混合整数解决方案。如果有很多二进制决策变量,解决方案可能需要更长的时间。另一种方法是使用松弛变量s
,以便d
保持正数,例如:
def k1(i, z, j, a):
d = m.Var(lb=0)
s = m.Var(lb=0)
m.Minimize(1e-3*s)
m.Equation(d == tce[(i, z, j, a)] - tc_var[(i, j)] + s)
return d
这种方法的问题是对s
的最小化可能会干扰其他竞争性目标。可以调整1e-3
来调整优化问题。
英文:
For conditional statements, use the m.if3()
function such as:
def k1(i, z, j, a):
d = m.Intermediate(tce[(i, z, j, a)] - tc_var[(i, j)])
a_dif = m.if3(d,0,d)
return a_dif
This adds a binary decision variable so the APOPT
solver (m.options.SOLVER=1
)must be used to solve the Mixed Integer solution. If there are many binary decision variables, the solution can take much longer. An alternative method is to use a slack variable s
so that d
remains positive such as:
def k1(i, z, j, a):
d = m.Var(lb=0)
s = m.Var(lb=0)
m.Minimize(1e-3*s)
m.Equation(d==tce[(i, z, j, a)] - tc_var[(i, j)]+s)
return d
The problem with this approach is that the minimization of s
may interfere with other competing objectives. The 1e-3
can be adjusted to tune the optimization problem.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论