Originally posted by: ArnaudS
Hi,
You should write the custom constraint in Java and add it to your model
in the main block (see flow control in the doc) using external java calls:
.mod file:
using CP;
int n = 5; dvar
int x[0..n] in 1..123465; dvar
int y[0..n]; constraints
{ allDifferent(x);
} main
{ thisOplModel.generate(); IloOplImportJava(
"E:/workspace-OPL/CustomConstraint/bin");
// add custom constraint to the model IloOplCallJava(
"mypackage.MyClass",
// class name
"addConstraint",
// method name
"",
// signature omitted, no ambiguity thisOplModel,
"x",
"y",thisOplModel.n+1);
// parameters
if ( cp.solve() )
{ thisOplModel.postProcess(); writeln(
"x: ", thisOplModel.x); writeln(
"y: ", thisOplModel.y);
}
else
{ writeln(
"No solution!");
}
}
Java class:
package mypackage;
import ilog.concert.IloConstraint;
import ilog.concert.IloException;
import ilog.concert.IloIntVar;
import ilog.concert.IloIntVarMap;
import ilog.cp.IloCP;
import ilog.cp.IloCustomConstraint;
import ilog.opl.IloOplModel;
public
class MyClass
{
static
public
class MyCustomConstraint
extends IloCustomConstraint
{
private
final IloIntVar _x;
private
final IloIntVar _y;
public MyCustomConstraint(IloCP cp, IloIntVar x, IloIntVar y)
throws IloException
{
super(cp); _x = x; _y = y; this.addVar(x); this.addVar(y);
}
public
void execute()
{ setRange(_y, getMin(_x) * 2, getMax(_x) * 2);
}
}
public
static
void addConstraint(IloOplModel model, String intMap1, String intMap2,
int size)
throws IloException
{ IloIntVarMap xArr = model.getElement(intMap1).asIntVarMap(); IloIntVarMap yArr = model.getElement(intMap2).asIntVarMap(); IloCP cp = model.getCP();
for (
int i = 0; i < size; i++)
{ IloIntVar x = xArr.get(i); IloIntVar y = yArr.get(i); IloConstraint ct =
new MyClass.MyCustomConstraint(cp, x, y); cp.add(ct);
}
}
}
Hope this helps.
Bye,
Arnaud
#CPOptimizer#DecisionOptimization