Hi,
about calling java function in OPL . See https://github.com/AlexFleischerParis/oplscripting/blob/main/IloOplCallJava.mod
/*
IloOplCallJava : This function calls a Java method from a scripting block
*/
execute
{
var convert180toRadian = IloOplCallJava("java.lang.Math","toRadians", "", 180);
writeln("180 degrees in radian : ",convert180toRadian);
}
/*
180 degrees in radian : 3.141592654
*/
execute
{
var title="title";
var msg="hello";
IloOplCallJava("javax.swing.JOptionPane", "showMessageDialog",
"(Ljava/awt/Component;Ljava/lang/Object;Ljava/lang/String;I)V",
null, msg, title, 1);
}
execute{
writeln("5 random numbers");
var rnd = IloOplCallJava("java.util.Random", "<init>", "()");
rnd.setSeed(1);
for(var i=1;i<=5;i++)
{
var t = rnd.nextDouble();
writeln(t);
}
writeln("Gaussian");
for(var i=1;i<=5;i++)
{
var t = rnd.nextGaussian();
writeln(t);
}
}
about reading from an excel file, you can see many basic examples at https://www.linkedin.com/pulse/excel-rocket-science-optimization-alex-fleischer/
or a very basic one at https://github.com/AlexFleischerParis/zooopl/blob/master/zooexcel.mod
tuple param
{
int nbKids;
}
{param} params=...;
assert card(params)==1;
int nbKids=first(params).nbKids;
// a tuple is like a struct in C, a class in C++ or a record in Pascal
tuple bus
{
key int nbSeats;
float cost;
}
// This is a tuple set
{bus} buses=...;
// asserts help make sure data is fine
assert forall(b in buses) b.nbSeats>0;
assert forall(b in buses) b.cost>0;
// decision variable array
dvar int+ nbBus[buses];
// objective
minimize
sum(b in buses) b.cost*nbBus[b];
// constraints
subject to
{
sum(b in buses) b.nbSeats*nbBus[b]>=nbKids;
}
tuple result
{
key int nbSeats;
int nbBuses;
}
{result} results={<b.nbSeats,nbBus[b]> | b in buses};
/*
and in the .dat we have
SheetConnection s("zoo.xlsx");
params from SheetRead(s,"params!A2");
buses from SheetRead(s,"buses!A2:B3");
results to SheetWrite(s,"buses!E2:F3");
or if we prefer to rely on named range
SheetConnection s("zoonamedrange.xlsx");
params from SheetRead(s,"nbkids");
buses from SheetRead(s,"buses");
results to SheetWrite(s,"result");
*/
------------------------------
[Alex] [Fleischer]
[Data and AI Technical Sales]
[IBM]
------------------------------
Original Message:
Sent: Tue February 21, 2023 12:53 PM
From: Mohamed Awad
Subject: How to use Java function in OPL Model?
Hi,
I would like to use the following script to read from external excel file:
execute { var excelFile = "path/to/excel/file.xlsx"; var dataSource = new IloOplExcelDataSource(excelFile); dataSource.addTable("ProcessingTimes", "A1:D100"); thisOplModel.addDataSource(dataSource);}
However, when I run the model, I receive the following error:
Scripting runtime error: Element "IloOplExcelDataSource" does not exist in OPL model.
Could you please advise on that.
Best regards,
Mohamed
------------------------------
Mohamed Awad
------------------------------