【问题标题】:ILOG OPL vs. PythonILOG OPL 与 Python
【发布时间】:2013-07-21 15:36:15
【问题描述】:

我正在尝试使用 Gurobi Python API 将我的 OPL 模型转换为 Python。我想知道 Python 中是否存在等效的 OPL 元组结构。最好举个例子:

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 和 Leg 是我的优化模型中的集合; Curr_Time、Min_Time、Max_Time 和 Cube 是在 Route 和 Leg 集上索引的参数。

在 OPL 中,由于我将 Route 和 Leg 定义为键,因此可以将它们视为集合,并且可以对参数进行索引。例如,要解决 Curr_Time,我可以这样做:

i.Curr_Time : i in set_Leg 

我一直在努力在 Python 中找到与此等效的东西。到目前为止,我在 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)

我不确定如何处理 Curr_Time 或 Min_Time?到目前为止,我有:

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

除了 dict 之外,还有更好的方法吗?我想知道是否还有其他选项可以让我以 OPL 允许的方式处理表字段。

【问题讨论】:

    标签: python dictionary mathematical-optimization ilog gurobi


    【解决方案1】:

    named tuples 类似于 opl 元组。

    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)
    

    dict 是一个很好的数据结构,用于通过 route、leg 访问 TupLeg 对象。您可以通过

    访问 curr_time
    tup_legs[(i,j)].curr_time
    

    itertools 模块包含许多算法,可让您以类似于您习惯使用 opl 的方式访问字典和其他集合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多