Domanda

I am trying to convert my OPL model to Python using the Gurobi Python API. I wanted to know if there is an equivalent of OPL tuple structure in Python. Best to show an example:

tuple tup_Leg
{
    key string Route;
    key string Leg;
    int Curr_Time;
    int Max_Time;
    int Min_Time;
    float Cube;
}

{tup_Leg} set_Leg = DBRead(db,"Exec SPROC ?")(Param);'

Route and Leg are sets in my optimization model; Curr_Time, Min_Time, Max_Time and Cube are parameters indexed over the sets Route and Leg.

In OPL, since I am defining Route and Leg as keys, they can be treated as sets and the parameters can be indexed over them. For example, to address Curr_Time, I can do:

i.Curr_Time : i in set_Leg 

I have been trying hard to find an equivalent of this in Python. So far I have the following in Python:

import pyodbc 
Param = 123
con = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server Native Client     10.0}', server = 'Server', database='db')
cur = con.cursor()
cur.execute("execute SPROC @Param =%d" %Param)
result = cur.fetchall()
tup_Leg = dict(((Route, Leg), [Curr_Time, Min_Time, Max_Time, Cube]) for Route, Leg, Curr_Time, Min_Time, Max_Time, Cube in result)

I am not sure how can I address Curr_Time or Min_Time? So far I have:

for i,j in tup_Leg:
    Curr_Time, Min_Time, Max_Time, Cube = tup_Leg[(i,j)]

Is there a better way to do this other than a dict? I am wondering if there are other options which lets me address the table fields the way OPL allows to.

È stato utile?

Soluzione

named tuples resemble the opl tuples.

from collections import namedtuple
TupLeg = namedtuple('TupLeg', ['route', 'leg', 
                               'curr_time', 'min_time', 'max_time' 'cube'])

tup_legs = dict((result[0], result[1]), TupLeg(*result) for result in cur)

A dict is a good data structure for accessing the TupLeg objects by route, leg. You can access curr_time by

tup_legs[(i,j)].curr_time

The itertools module contains a lot of algorithms that will allow you to access dictionaries and other collections in ways similar to what you are used to having opl.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top