0

I am solving a problem in Java using the CPLEX library. I use a class "Model" to create a CPLEX object, and add to it variables, objective function and multiple constraints. This is the basic model, and I call the constraints "basic constraints".

I use an algorithm that basically adds a constraint to "Model" and solves it iteratively until no more relevant constraints can be added. I call these constraints "imposed constraints".

To create a copy of the same model (with both basic and imposed constraints), I use the code below.

private Model duplicate(Model M) throws IloException {
        Model M2 = new Model(Q,k,dep,dLoc,N,cus,cLoc,D,lD,eps);     \\create cplex object, variables, basic constraints, objective function
        ArrayList<IloRange> constraints = M.getImposedConstraints(); \\list of imposed constraints
        IloCopyManager copymanager = new IloCopyManager(M.getCplex());
        Iterator iter = (Iterator) M.getCplex().rangeIterator();
        while (iter.hasNext()) {
            IloRange c = (IloRange) iter.next();
            M2.imposeConstraint((IloRange)c.makeCopy(copymanager));
        }
        return M2;
    }

However, the Model does not get copied properly. The imposed constraints are not the same (I think this is maybe because the variable references seem to change?), and so the result when solving models M and M2 is not the same. There does not seem to be a problem with the basic constraints, but definitely with the imposed constraints. Why is this happening, and how do I fix it? Any help is greatly appreciated, thanks!

1 Answers1

1

The problem probably is that in models M and M2 you have different instances of variables and IloConstraint.copy() cannot know which variable in M has to be mapped to which variable in M2. The result of copy() will still reference variables in M (and not in M2).

I don't see how you construct the basic constraints, but I guess you construct them from scratch in the Model constructor? That would explain why you get the correct variable references there.

To work around your problem don't store the imposed constraints as IloConstraint. Instead store them as a list of non-zero coefficients and the corresponding variable indices (not the variable objects). This way you can easily reconstruct the imposed constraints with the correct variable references when cloning the model.

Daniel Junglas
  • 5,830
  • 1
  • 5
  • 22