Search code examples
javalinear-programmingojalgo

How to get variables values from Optimisation.Result in ojAlgo?


I use ojAlgo lib in version 51.4.1. I ve got:

protected final ExpressionsBasedModel model = new ExpressionsBasedModel();
protected Variable[] result;

and some other variables. Each variable is added to the model, same as constrains. When i run:

Optimisation.Result result = model.minimise();

I can get each result value using:

private static double[] getVariablesValues(Variable[] variables) {
    double[] values = new double[variables.length];
    for (int i = 0; i < variables.length; i++) {
        values[i] = variables[i].getValue().doubleValue();
    }
    return values;
}

And now my problem: I want to force optimizer to use ConvexSolver so instead model.minimise() i write:

ConvexSolver solver = new ConvexSolver.ModelIntegration().build(model);
Optimisation.Result result = solver.solve();

Solver returns OPTIMAL solution, but i cannot get variable values as a did before. Is there a possibility to get these values from solver or result? I couldn't find any helpfull resolution with google or chatGPT. I was thinking about getting values by index, but result has other values indexes than model variables.


Solution

  • There is no need for you to create a new model integration new ConvexSolver.ModelIntegration(). Instead just use the ConvexSolver.INTEGRATION instance.

    There are two ways you can use it:

    1. Create a new Optimisation.Integration that simply delegate to that instance except that the isCapable method always returns true. Add this new integration using ExpressionsBasedModel.addIntegration and use model.minimise() the usual way.
    2. Take the Optimisation.Result returned by the solver and feed it to the toModelState method of that integration. This will translate the variable indices to match the model variables.

    I think (1) is the better alternative.

    Why do you want to force use the ConvexSolver?