一般来说,我对优化非常陌生,尤其是pyomo,所以我为任何新手的错误提前道歉。
我定义了一个简单的单元promise练习(示例3.1从[1])使用[2]作为起点。我得到了正确的结果,我的代码运行,但我有一些关于如何访问东西的问题。
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import shutil
import sys
import os.path
import pyomo.environ as pyo
import pyomo.gdp as gdp #necessary if you use booleans to select active and innactive units
def bounds_rule(m, n, param='Cap_MW'):
# m because it pases the module
# n because it needs a variable from each set, in this case there was only m.N
return (0, Gen[n][param]) #returns lower and upper bounds.
def unit_commitment():
m = pyo.ConcreteModel()
m.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT_EXPORT)
N=Gen.keys()
m.N = pyo.Set(initialize=N)
m.Pgen = pyo.Var(m.N, bounds = bounds_rule) #amount of generation
m.Rgen = pyo.Var(m.N, bounds = bounds_rule) #amount of generation
# m.OnOff = pyo.Var(m.N, domain=pyo.Binary) #boolean on/off marker
# objective
m.cost = pyo.Objective(expr = sum( m.Pgen[n]*Gen[n]['energy_$MWh'] + m.Rgen[n]*Gen[n]['res_$MW'] for n in m.N), sense=pyo.minimize)
# demand
m.demandP = pyo.Constraint(rule=lambda m: sum(m.Pgen[n] for n in N) == Demand['ener_MWh'])
m.demandR = pyo.Constraint(rule=lambda m: sum(m.Rgen[n] for n in N) == Demand['res_MW'])
# machine production limits
# m.lb = pyo.Constraint(m.N, rule=lambda m, n: Gen[n]['Cap_min']*m.OnOff[n] <= m.Pgen[n]+m.Rgen[n] )
# m.ub = pyo.Constraint(m.N, rule=lambda m, n: Gen[n]['Cap_MW']*m.OnOff[n] >= m.Pgen[n]+m.Rgen[n])
m.lb = pyo.Constraint(m.N, rule=lambda m, n: Gen[n]['Cap_min'] <= m.Pgen[n]+m.Rgen[n] )
m.ub = pyo.Constraint(m.N, rule=lambda m, n: Gen[n]['Cap_MW'] >= m.Pgen[n]+m.Rgen[n])
m.rc = pyo.Suffix(direction=pyo.Suffix.IMPORT)
return m
Gen = {
'GenA' : {'Cap_MW': 100, 'energy_$MWh': 10, 'res_$MW': 0, 'Cap_min': 0},
'GenB' : {'Cap_MW': 100, 'energy_$MWh': 30, 'res_$MW': 25, 'Cap_min': 0},
} #starting data
Demand = {
'ener_MWh': 130, 'res_MW': 20,
} #starting data
m = unit_commitment()
pyo.SolverFactory('glpk').solve(m).write()
m.display()
df = pd.DataFrame.from_dict([m.Pgen.extract_values(), m.Rgen.extract_values()]).T.rename(columns={0: "P", 1: "R"})
print(df)
print("Cost Function result: " + str(m.cost.expr()) + "$.")
print(m.rc.display())
print(m.dual.display())
print(m.dual[m.demandR])
da= {'duals': m.dual[m.demandP],
'uslack': m.demandP.uslack(),
'lslack': m.demandP.lslack(),
}
db= {'duals': m.dual[m.demandR],
'uslack': m.demandR.uslack(),
'lslack': m.demandR.lslack(),
}
duals = pd.DataFrame.from_dict([da, db]).T.rename(columns={0: "demandP", 1: "demandR"})
print(duals)
我的问题来了。
根据定义,影子价格是约束的对偶变量(m.demandP和m.demandR)。有没有一种方法可以访问这些值并将它们放入数据框,而不必做我做的“糟糕”的事情?我的意思是手动定义da和db,然后在两个字典连接时创建数据框?我想做一些更干净的事情,比如保存系统中每个生成器的P和R结果的df。
2-通常,在机组组合问题中,使用二进制变量来“标记”或“选择”有功和非有功机组。因此使用了“m.OnOff”变量(注释行)。我在[3]中发现,包含二进制变量的模型中不存在对偶。之后,我重写了这个问题,没有包含二进制代码。在这个所有单元都运行的过于简单的练习中,这不是一个问题,但对于更大的单元来说,这是一个问题。我需要能够让优化决定哪些单位会和不会运行,我仍然需要影子价格。在包含二进制变量的问题中,有没有办法获得影子价格/对偶?我让基于二进制变量的约束定义也存在,以防有人发现它有用。
注意:代码也使用二进制变量运行并得到正确的结果,但是我不知道如何获得影子价格。这就是我的问题。
[1] 莫拉莱斯,J.M.,科内乔,A.J.,马德森,H.,品森,P。,
[2]https://jckantor.github.io/ND-Pyomo-Cookbook/04.06-Unit-Commitment.html
[3] 双变量在Pyomo中不返回任何内容
为了回答1,您可以使用model.component_objects(pyo.约束)
,它将返回约束的迭代器,这将使您不必对约束名称进行硬编码。对于索引变量来说,这变得很棘手,因为您必须执行额外的步骤来获取每个索引的松弛,而不仅仅是约束对象。对于对偶,您可以遍历key
属性以检索这些值。
duals_dict = {str(key):m.dual[key] for key in m.dual.keys()}
u_slack_dict = {
# uslacks for non-indexed constraints
**{str(con):con.uslack() for con in m.component_objects(pyo.Constraint)
if not con.is_indexed()},
# indexed constraint uslack
# loop through the indexed constraints
# get all the indices then retrieve the slacks for each index of constraint
**{k:v for con in m.component_objects(pyo.Constraint) if con.is_indexed()
for k,v in {'{}[{}]'.format(str(con),key):con[key].uslack()
for key in con.keys()}.items()}
}
l_slack_dict = {
# lslacks for non-indexed constraints
**{str(con):con.lslack() for con in m.component_objects(pyo.Constraint)
if not con.is_indexed()},
# indexed constraint lslack
# loop through the indexed constraints
# get all the indices then retrieve the slacks for each index of constraint
**{k:v for con in m.component_objects(pyo.Constraint) if con.is_indexed()
for k,v in {'{}[{}]'.format(str(con),key):con[key].lslack()
for key in con.keys()}.items()}
}
# combine into a single df
df = pd.concat([pd.Series(d,name=name)
for name,d in {'duals':duals_dict,
'uslack':u_slack_dict,
'lslack':l_slack_dict}.items()],
axis='columns')
关于2,我同意@Erwin关于用二进制变量求解得到最优解的评论,然后取消二进制限制,但将变量固定为最优值,得到一些对偶变量值。