Solving your first model in Java¶
LocalSolver is implemented in C++ language. Nevertheless, object-oriented APIs are provided for Java 5.0 (or superior), allowing a full integration of LocalSolver in your Java business applications. LocalSolver’s APIs are lightweight, with only a few classes to manipulate. Remind that LocalSolver is a black-box math programming solver: having instantiated the model, no additional code has to be written in order to run the solver.
Below is given the Java code for solving the knapsack toy instance introduced
during the Quick tour of LocalSolver’s modeler.
The corresponding source file can be retrieved in examples/toy
.
A small example¶
/********** Toy.java **********/
import localsolver.*;
public class Toy {
public static void main(String [] args) {
int[] weights = {10, 60, 30, 40, 30, 20, 20, 2};
int[] values = {1, 10, 15, 40, 60, 90, 100, 15};
/* Declares the optimization model. */
LocalSolver localsolver = new LocalSolver();
LSModel model = localsolver.getModel();
// 0-1 decisions
LSExpression[] x = new LSExpression[8];
for (int i = 0; i < 8; i++) {
x[i] = model.boolVar();
}
// knapsackWeight <- 10*x0 + 60*x1 + 30*x2 + 40*x3 + 30*x4 + 20*x5 + 20*x6 + 2*x7;
LSExpression knapsackWeight = model.sum();
for (int i = 0; i < 8; i++) {
knapsackWeight.addOperand(model.prod(weights[i], x[i]));
}
// knapsackWeight <= 102;
model.constraint(model.leq(knapsackWeight, 102));
// knapsackValue <- 1*x0 + 10*x1 + 15*x2 + 40*x3 + 60*x4 + 90*x5 + 100*x6 + 15*x7;
LSExpression knapsackValue = model.sum();
for (int i = 0; i < 8; i++) {
knapsackValue.addOperand(model.prod(values[i], x[i]));
}
// maximize knapsackValue;
model.maximize(knapsackValue);
// close model, then solve
model.close();
/* Parameterizes the solver. */
LSPhase phase = localsolver.createPhase();
phase.setTimeLimit(1);
localsolver.solve();
}
}
You can observe that the structure of the Java program follows the structure of corresponding LSP. First, we read input data. Then, we declare the knapsack model by creating some expressions. Once the model is closed, we can parameterize the search before launching the solver.
Compiling and running the Java program¶
For compiling, Java Development Kit 5.0 (or superior) must be installed on your computer. On Windows, the above program is compiled and launched using the following lines:
javac Toy.java -cp %LS_HOME%\bin\localsolver.jar
java -cp %LS_HOME%\bin\localsolver.jar;. -Djava.library.path=%LS_HOME%\bin\ Toy
On Linux or Mac OS, the above program is compiled and launched using the following lines:
javac Toy.java -cp /opt/localsolver_XXX/bin/localsolver.jar
java -cp /opt/localsolver_XXX/bin/localsolver.jar:. -Djava.library.path=/opt/localsolver_XXX/bin/ Toy
If you have some troubles in compiling or launching the program, please have a look to the Installation & licensing. We invite users willing to go further with APIs to consult the Java API Reference.