How to create a parameter using onEmbeddedCode Python

set ii /1*5/;
parameter cc(ii);

$onEmbeddedCode Python:
listA = [1, 3, 6, 9, 10]
gams.set['cc', listA]
$offEmbeddedCode cc

For the above code, I attempted to create the parameter cc by using a list defined in the python embedded code. However, the code returns an error that the listA is not tuple. Could you help me to make the code work? Thank you very much.

Hi Daniel,

You need to match each set element with a value. You can write it as follows:

set ii /1*5/;
parameter cc(ii);

$onEmbeddedCode Python:
listA = [('1', 1), ('2', 3), ('3', 6), ('4', 9), ('5', 10)]
gams.set('cc', listA)
$offEmbeddedCode cc

Here is a slightly different solution. Key is that the gams.set expects a list of tuples that are made of labels and a value:

set ii /1*5/;
parameter cc(ii);

$onEmbeddedCode Python:
listA = [1, 3, 6, 9, 10]
gams.set('cc', [(k,v) for k,v in zip(gams.get('ii'), listA)])
$offEmbeddedCode cc

-Michael

set exp /1*15/;
parameter quantity /#exp, 0.8/;

$onEmbeddedCode Python:
gams.printLog(f"{list(gams.get(‘quantity’))}")
df = pd.DataFrame(list(gams.get(‘quantity’)), columns=[‘exp’, ‘quantity’])
$offEmbeddedCode

The above code works well. However, I am stuggled to get quantity when it must be defined dynamically. For example, I have to define the parameter

quantity(exp) = solution(exp)

where solution(exp) are the results from a GAMS model solution. Could you help me revise the code so it works as well to get parameter quantity(exp) when it is defined dynamically? Appreciate your help.

Thank you so much. This is very helpful.

You need to understand the difference between compile and execution time in GAMS. $XYZ commands are done by the compiler. But your solve statement is executed at execution time. So a $on/offEmbeddedCode does not help. You need to use the execution time equivalent:

set exp /1*15/;
parameter quantity /#exp 0.8/;

quantity(exp) = uniform(0,1);

EmbeddedCode Python:
import pandas as pd
gams.printLog(f"{list(gams.get('quantity'))}")
df = pd.DataFrame(list(gams.get('quantity')), columns=['exp', 'quantity'])
gams.printLog(f"{df=}")
endEmbeddedCode

Hope this helps,
-Michael

Thanks Michael. Appreciate it.