Decision Optimization

Decision Optimization

Delivers prescriptive analytics capabilities and decision intelligence to improve decision-making.

 View Only

How to convert an OPL tuple set into a python tuple list ?

  • 1.  How to convert an OPL tuple set into a python tuple list ?

    Posted Fri January 19, 2018 02:00 PM

    Hi,

     

    since I wrote 2 articles where I used IloOplExec to call Python code from OPL

     

    How to display 2D arrays in OPL by calling python / matplotlib

    How to turn CSV files into dat files that can be read by OPL ?

     

    I was asked more, namely how to convert any OPL tuple set to Python

     

    So let me show you.

     

    tuple user
    {
        string name;
        int age;
        string city;
        float speed;
    }

    {user}  users={<"Alice",30,"Paris",1.2>,<"Bob",40,"London",4.6>};

    execute
    {

    function getPythonListOfTuple(tupleSet)
    {

    var quote="\"";
    var nextline="\\\n";

    var nbFields=tupleSet.getNFields();
    var res="[";
    for(var i in tupleSet)
    {
    res+="{";
    for(var j=0;j<nbFields;j++)
    {
    res+=quote+tupleSet.getFieldName(j)+quote;
    res+=":";
    var value=i[tupleSet.getFieldName(j)];
    if (typeof(value)=="string") res+=quote;
    res+=value;
    if (typeof(value)=="string") res+=quote;
    res+=",";
    res+=nextline;
    }
    res+="},";
    }
    res+="]";
    return res;
    }


    writeln(getPythonListOfTuple(users));

    }

     

    gives

     

    [{"name":"Alice",\
    "age":30,\
    "city":"Paris",\
    "speed":1.2,\
    },{"name":"Bob",\
    "age":40,\
    "city":"London",\
    "speed":4.6,\
    },]

    which can then be used in Python:

     

    data=[{"name":"Alice",\
    "age":30,\
    "city":"Paris",\
    "speed":1.2,\
    },{"name":"Bob",\
    "age":40,\
    "city":"London",\
    "speed":4.6,\
    },]

    for i in data:
        print(i)

    gives

     

    {'name': 'Alice', 'age': 30, 'city': 'Paris', 'speed': 1.2}
    {'name': 'Bob', 'age': 40, 'city': 'London', 'speed': 4.6}

    regards


    #DecisionOptimization
    #OPLusingCPLEXOptimizer