如何使用 pyomo 从 class 解决方案访问我的结果?

How can I acces to my results from a class solution with pyomo?

我只是想解释一下,我是 python 的超级新手 我想访问我的问题的结果:

我有这个,还有它运行我只想访问我的结果,以便我可以比较我拥有的两种类型的电池 我怎样才能得到正在解决的 B1 和 B2 的结果?

这是我声明的变量之一:

model.ach = Var(model.t , domain=NonNegativeReals, bounds=(0,1)) #Rate of charging

这里是构建需求的词典

demand = Jan[:24*4*5]
t = range(len(demand))
demand_dict = {}
for tt, dd in zip(t, demand):
demand_dict[tt] = dd

这里声明固定值:

 cosP = 12.34
 cosE=0.0606
 cosF=0.02673   

在我的抽象模型中声明了我的 objective 函数后,我使用 class 来拥有不同种类的电池:

class Battery:
      def __init__(self, n, Emax, Emin, cap):
      self.n=n
      self.Emax=Emax
      self.Emin=Emin
     self.cap=cap


B1=Battery(0.8,3800,400,500)
B2=Battery(0.8,7600,800,1000)
Batts=[B1,B2]

现在我正在通过两个 classes 我的模型进行交互

Results=[]
Instance=[]
for b in Batts:
        data = {None: {'cosP': {None: cosP},
               't': {None: t},
               'cosE': {None: cosE},
               'cosF':{None:cosF},
               'n':{None: b.n},
               'Emax':{None:b.Emax}, #kWh max capacity
               'Emin':{None:b.Emin}, #kWh min capacity
               'cap':{None:b.cap},
               'dem': demand_dict
              }
        }
        instance=model.create_instance(data)
        opt=SolverFactory('glpk')
        results = opt.solve(instance)
Results.append(results)
Instance.append(instance)

我正在尝试访问一个以前指定的值,我试过这个:

for t in instance.t:
    ach.append(instance.ach[t].value)

但这只能让我访问最后一个小程序,即 Battery 中的 b2。假设我可能有倍数 b's

,我该如何访问其他值

当您想获得其中一个变量的结果时,只需执行

print(instance.X[indice1, indice2].value) #for indexed var objects

print(instance.X.value) #for non-indexed var objects

其中 indice1indice2 是作为变量索引一部分的索引,其中 X 是变量的名称。

使用print只是为了显示结果,如果不使用print,您变量的值可以直接在Python中使用。

编辑:如果你想访问所有变量的值,我推荐你下面的问题: