Search code examples
pythonlinear-programmingcplex

Importing cplex linear program file into python


I have written my linear program using cplex IBM studio to .mod file as follows:

int I = ...;
int J = ...;
int ds[1..I]=...;
int maxnint[1..J]=...;
dvar int E[1..I][1..J][1..6];
dvar boolean V[1..I];
minimize sum(i in 1..I)(E[i,J,maxnint[J]]-ds[i]*V[i]);

subject to{
forall(i in 1..I, j in 1..J, mu in 1..maxnint[j]) E[i,j,mu]>=0;
forall(i in 1..I)( t_max*V[i]     >=E[i,J,maxnint[J]]-ds[i]);
forall(i in 1..I)(-t_max*(1-V[i]) <=E[i,J,maxnint[J]]-ds[i]);
}

I want to import this file into python and solve it using the data I read in python. The data should be something like :

import numpy as np
I = range(10)
J = range(6)
ra = np.array([240, 400, 264, 390, 200, 440])
maxnint = np.array([1, 1, 3, 3, 1, 4])
ds = np.array([14, 19, 16, 21, 28,
               14, 21, 19, 15, 14
               ])

Is it anyway possible? I try to avoid to write constraints in python because I have many constraints and many indexes that should be harder to implement in python.


Solution

  • you can use doopl. Small example https://github.com/AlexFleischerParis/zoodocplex/blob/master/zoocallopl.py

    from doopl.factory import *
    # Data
    Buses=[
            (40,500),
            (30,400)
            ]
    
    # Create an OPL model from a .mod file
    with create_opl_model(model="zootupleset.mod") as opl:
        # tuple can be a list of tuples, a pandas dataframe...
        opl.set_input("buses", Buses)
    
        # Generate the problem and solve it.
        opl.run()
    
        # Get the names of post processing tables
        print("Table names are: "+ str(opl.output_table_names))
    
        # Get all the post processing tables as dataframes.
        for name, table in iteritems(opl.report):
            print("Table : " + name)
        for t in table.itertuples(index=False):
                print(t)
    
        # nicer display
        for t in table.itertuples(index=False):
            print(t[0]," buses ",t[1], "seats")
    

    or if you do not want to use doopl you can call oplrun from python as can be seen at https://github.com/AlexFleischerParis/howtowithopl/blob/master/callexternalprogram.mod

    See also

    https://github.com/AlexFleischerParis/zoodocplex/blob/master/zooimportoplmodelandaddpythonobjectiveandconstraint.py