I am using ampl for modeling my optimization problem in python and I am beginner in ampl. My variable is a two dimensional array. This is my data:
data;
set USER := u1 u2 ;
set JOB := j1 j2 ;
param p:=
u1 j1 0.8022422666444835
u1 j2 0.8022422666444835
u2 j1 0.8022422666444835
u2 j2 0.8022422666444835
;
param o:=
u1 j1 0.268
u1 j2 0.544
u2 j1 0.234
u2 j2 0.964
;
and this is my ampl modeling:
set USER;
set JOB;
param p {USER,JOB}>=0;
param o {USER,JOB}>=0;
var t {i in USER, k in JOB}>=0;
maximize profit: sum{k in JOB} 50*log(1+(sum{i in USER} log(1+t[i,k]*o[i,k])))-sum{i in USER}sum{k in JOB} t[i,k]*p[i,k];
The result will be t
variable. I want to convert t
to a two dimensional array in python because I want to use the result of this optimization problem in my python code.
I ran this code in python:
time = ampl.getVariable('t')
for i in time:
print(i)
and the result is:
(('u1', 'j1'), <amplpy.variable.Variable object at 0x7f82b3b419d0>)
(('u1', 'j2'), <amplpy.variable.Variable object at 0x7f82b3b41d10>)
(('u2', 'j1'), <amplpy.variable.Variable object at 0x7f82b3b41b50>)
(('u2', 'j2'), <amplpy.variable.Variable object at 0x7f82b3b41b10>)
I don't know how can I convert this result to a two dimensional array in python. Could you help me pleas? Thanks for your helps in advance.
In python there are 2 things commonly used which are array like, lists
and tuples
. The main difference is that a tuple can not be altered, but a list can. For example you can append to the end of a list. But you can't add or delete items from a tuple.
The value of the time
variable you have in your python code is something that can be iterated over and which yields a tuple of two tuples at least for the output you have shown us. The first of the two tuples has two items.
Presuming the same pattern holds, and that you want a list of lists of the three items in each iteration over this time variable this should work:
time = ampl.getVariable('t')
list_of_lists = []
for param, ampl_var in time:
u_value, j_value = param
list_of_lists.append([u_value, j_value, ampl_var])
for sub_list in list_of_lists:
print(sub_list)