问题
Seeking for ways to save my Pyomo results took my 2 hours :(
I need to save my optimal variable values and dual variable values after successfully solving a problem. Let's start from the optimal variables.
I have three variables in my model, 120 'P' variables with 3 indices, 120 'I' variables with 3 indices and 576 'F' variables with 3 indices. Their indices are different. The following is my solve statements:
solver = pyomo.opt.SolverFactory('gurobi')
results = solver.solve(m, tee=True, keepfiles=True)
m.display()
results.write()
m.solutions.load_from(results)
Everything seems to be fine here, and I have obtained a m.solutions
as type of <pyomo.core.base.PyomoModel.ModelSolutions at 0xa23c7bcf8>
. Then I tried the next thing:
list_of_vars = [v for v in m.component_objects(ctype=pe.Var, active=True, descend_into=True)]
print(list_of_vars)
Afterwards, I got another list_of_vars
object as type of a list with 3 elements as '', which is also reasonable.
Then what do I need to do in the next step? How can I transform the m.solutions
or list_of_vars
to a dataframe or list or csv files? Thanks a lot!
Gabriel
回答1:
OK let me answer my own question :)
I found two ways to efficiently tackle this problem.
1). Manually write into CSV files
Denote the variable as P, the model name as m, then after the solution, i.e. executing the following command,
results = solver.solve(m, tee=True)
we will obtain the optimal variable values in tuple, e.g. m.P
. The indexed value of the tuple can be retrieved by just using their indices. Take my three-index case as example, to save it to a csv file:
with open('P.csv', 'w') as f:
f.write('index1, index2, index3, value\n')
for (n1,n2,n3) in index_set:
f.write('%s, %s, %s, %s\n' % (n1, n2, n3, m.P[(n1,n2,n3)].value))
2). Tuple-to-array Transformation
This way is somehow more tricky, when we need to first divide the indices and values from the optimal results, by using broadcasting in the OOP theory. Pyomo developers might forget to write an iterative way to directly import them from their constructed format for saving the optimal solutions, so we have to use it:
ind = list(m.P)
val = list(m.P[:,:,:].value)
Then use a zip to link them:
result_P = [ i + tuple([j]) for i,j in zip(ind, val)]
Now we obtain the tuple result_P
with all the indices and values that we want. Afterwards it is trivial to convert this tuple to array, then to CSV:
result_P = np.asarray(result_P)
np.savetxt('result_P.csv', result_P, delimiter=',')
Gabriel
来源:https://stackoverflow.com/questions/54374454/pyomo-save-results-to-csv-files