循环的情况下检索

循环的情况下检索

本文介绍了在不使用 for 循环的情况下检索 Pyomo 解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力寻找一种有效的方法来检索优化问题的解决方案.该解决方案由大约 200K 个变量组成,我希望在 Pandas DataFrame 中使用这些变量.在网上搜索之后,我发现访问变量的唯一方法是通过一个看起来像这样的 for 循环:

I am struggling to find an efficient way of retrieving the solution to an optimization problem. The solution consists of around 200K variables that I would like in a pandas DataFrame. After searching online the only approaches I found for accessing the variables was through a for loop which looks something like this:

instance = M.create_instance('input.dat') # reading in a datafile
results = opt.solve(instance, tee=True)
results.write()
instance.solutions.load_from(results)

for v in instance.component_objects(Var, active=True):
    print ("Variable",v)
    varobject = getattr(instance, str(v))
    for index in varobject:
        print ("   ",index, varobject[index].value)

我知道我可以使用这个 for 循环将它们存储在数据帧中,但这效率很低.我发现了如何使用

I know I can use this for loop to store them in a dataframe but this is pretty inefficient.I found out how to access the indexes by using

import pandas as pd
index = pd.DataFrame(instance.component_objects(Var, active=True))

但我不知道如何得到解决方案

But I dont know how to get the solution

推荐答案

其实有一个非常简单优雅的解决方案,使用方法 pandas.DataFrame.from_dict 结合 Var.extract_values() 方法.

There is actually a very simple and elegant solution, using the method pandas.DataFrame.from_dict combined with the Var.extract_values() method.

from pyomo.environ import *
import pandas as pd
m = ConcreteModel()
m.N = RangeSet(5)
m.x = Var(m.N, rule=lambda _, el: el**2)  # x = [1,4,9,16,25]

df = pd.DataFrame.from_dict(m.x.extract_values(), orient='index', columns=[str(m.x)])
print(df)

收益

    x
1   1
2   4
3   9
4  16
5  25

请注意,对于 Var,我们可以同时使用 get_values()extract_values(),它们的作用似乎相同.对于 Param,只有 extract_values().

Note that for Var we can use both get_values() and extract_values(), they seem to do the same. For Param there is only extract_values().

这篇关于在不使用 for 循环的情况下检索 Pyomo 解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:15