Vikas Gautam
Vikas Gautam

Reputation: 1

How to provide input to an OPL model in CPLEX using Python and then print the solution of the OPL model in Python?

We have five scenarios, each with a different set of damaged nodes. We want to input the set of damaged lines into the OPL model one scenario at a time, storing the result in Python for each scenario. We'll repeat this process for the other scenarios, storing each solution in Python.

Python code to provide the input (set of damage nodes for one scenario) to the OPL model and print the result--

from doopl.factory import create_opl_model

Damage_Nodes = [
(1, {8, 9, 12, 16, 19, 23, 24, 27, 30}),  
]

model_path = "C:/Users/VGFD/opl/MEG_Case3/MEG_Case3.mod"

with create_opl_model(model=model_path) as opl:

opl.set_input("damage_Nodes", Damage_Nodes)

opl.run()

decision_vars = opl.get_decision_variables()

for var in decision_vars:
    print(f"{var} = {decision_vars[var]}")

objective_value = opl.get_objective_value()
print("Objective value:", objective_value)`

The code for the OPL model to receive input from Python is provided below.

tuple damage_Node {
int scenario;
{int} value;
}


{damage_Node} damage_Nodes = ...;

I want to retrieve the set of damaged nodes and use it within a constraint.

forall (rc in Repaircrew){
  forall (n in damage_Nodes){
    forall (s in Slot:s<=N_T-1){
 StatusLine[rc][n][s]<= StatusLine[rc][n][s+1];
   }
  }
 }

ERROR - Windows fatal exception: access violation.

I want to run this OPL model in python for different scenarios. Different scenario represents different input (set of damage nodes) to the OPL model. And then store the solution for each scenario in Python.

Upvotes: 0

Views: 51

Answers (1)

Alex Fleischer
Alex Fleischer

Reputation: 10062

With doopl, as can be read at https://pypi.org/project/doopl/

with doopl, "Inputs can be tuple lists, panda’s dataframe, sql alchemy fetch statements."

So I would either change

Damage_Nodes = [
(1, {8, 9, 12, 16, 19, 23, 24, 27, 30}),  
]

into

Damage_Nodes = [
(1, 8,), (1,9,),(1,12,),(1,16,),(1,19,),(1,23,),(1,24,),(1,27,),(1,30,),  
]

and do the conversion in the OPL model or

write a .dat file from python that would look like

damage_Nodes = {<1,{8, 9, 12, 16, 19, 23, 24, 27, 30};

and then rely on that dat file like in the example https://github.com/IBMDecisionOptimization/doopl-examples/blob/master/examples/Mulprod.py

import os
from os.path import dirname, abspath, join

DATADIR = join(dirname(abspath(__file__)), 'data')
mod = join(DATADIR, "mulprod.mod")
dat = join(DATADIR, "mulprod.dat")

Upvotes: 0

Related Questions