Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting large array variables (type = object) to CSV files

Tags:

python

gekko

I have used Gekko from APM in Python to solve an optimization problem. The two main decision variables (DVs) are large arrays. The problem has converged successfully, however, I need the results of these tables in an excel worksheet for further work.

An example variable name is 's'. Since the arrays created within Gekko are GKVariable/Object variable types I cannot simply use:

pd.DataFrame(s).to_csv(r'C:\Users\...\s.csv')

because the result gives every cell of the array the label of each variable defined in the model (i.e. v1, v2, etc.)

Using print 's' within the kernel will show the numbers of the array from the optimization results but in a format that doesn't guarantee that each line is a new row of the matrix because of the many columns.

Is there another solution to copy just the resulting value of the DV 's' so it becomes a normal np.array instead of the object type variable? Open to any ideas for this.

like image 452
em_cee Avatar asked Nov 07 '22 14:11

em_cee


1 Answers

You can use s[i].value[0]`` for steady state problems (IMODE=1orIMODE=3) ors[i].value[:]``` to access the array of values for all other IMODE options. Here is a simple example with writing the results to a file with pandas and numpy.

import numpy as np
from gekko import GEKKO
import pandas as pd

m = GEKKO(remote=False)

# Random 3x3
A = np.random.rand(3,3)
# Random 3x1
b = np.random.rand(3,1)

# Ax = b
y = m.axb(A,b)
m.solve()

yn = [y[i].value[0] for i in range(3)]

print(yn)
pd.DataFrame(yn).to_csv(r'y1.csv')
np.savetxt('y2.csv',yn,delimiter=',',comments='')
like image 165
John Hedengren Avatar answered Nov 14 '22 21:11

John Hedengren