The following sections will get you started with OR-Tools for Java:
- What is an optimization problem?
- Solving an optimization problem in Java
- More Java examples
- Identifying the type of problem you wish to solve
What is an optimization problem?
The goal of optimization is to find the best solution to a problem out of a large set of possible solutions. (Sometimes you'll be satisfied with finding any feasible solution; OR-Tools can do that as well.)
Here's a typical optimization problem. Suppose that a shipping company delivers packages to its customers using a fleet of trucks. Every day, the company must assign packages to trucks, and then choose a route for each truck to deliver its packages. Each possible assignment of packages and routes has a cost, based on the total travel distance for the trucks, and possibly other factors as well. The problem is to choose the assignments of packages and routes that has the least cost.
Like all optimization problems, this problem has the following elements:
The objective—the quantity you want to optimize. In the example above, the objective is to minimize cost. To set up an optimization problem, you need to define a function that calculates the value of the objective for any possible solution. This is called the objective function. In the preceding example, the objective function would calculate the total cost of any assignment of packages and routes.
An optimal solution is one for which the value of the objective function is the best. ("Best" can be either a maximum or a minimum.)
The constraints—restrictions on the set of possible solutions, based on the specific requirements of the problem. For example, if the shipping company can't assign packages above a given weight to trucks, this would impose a constraint on the solutions.
A feasible solution is one that satisfies all the given constraints for the problem, without necessarily being optimal.
The first step in solving an optimization problem is identifying the objective and constraints.
Solving an optimization problem in Java
Next, we give an example of an optimization problem, and show how to set up and solve it in Java.
A linear optimization example
One of the oldest and most widely-used areas of optimization is linear optimization (or linear programming), in which the objective function and the constraints can be written as linear expressions. Here's a simple example of this type of problem.
Maximize 3x + y
subject to the following constraints:
- 0 ≤
x
≤ 1 - 0 ≤
y
≤ 2 x + y
≤ 2
The objective function in this example is 3x + y
.
Both the objective function and the constraints are given by linear expressions,
which makes this a linear problem.
Main steps in solving the problem
For each language, the basic steps for setting up and solving a problem are the same:
- Import the required libraries,
- Declare the solver,
- Create the variables,
- Define the constraints,
- Define the objective function,
- Invoke the solver and
- Display the results.
Java program<
This section walks through a Java program that sets up and solves the problem.
Here are the steps:
- Import the required libraries.
import com.google.ortools.Loader; import com.google.ortools.init.OrToolsVersion; import com.google.ortools.linearsolver.MPConstraint; import com.google.ortools.linearsolver.MPObjective; import com.google.ortools.linearsolver.MPSolver; import com.google.ortools.linearsolver.MPVariable;
- Declare the solver.
// Create the linear solver with the GLOP backend. MPSolver solver = MPSolver.createSolver("GLOP"); if (solver == null) { System.out.println("Could not create solver GLOP"); return; }
MPSolver
is a wrapper for solving any linear programming or mixed integer programming problems. - Create the variables.
// Create the variables x and y. MPVariable x = solver.makeNumVar(0.0, 1.0, "x"); MPVariable y = solver.makeNumVar(0.0, 2.0, "y"); System.out.println("Number of variables = " + solver.numVariables());
- Define the constraints.
The first two constraints,
0
≤x
≤1
and0
≤y
≤2
, are already set by the definitions of the variables. The following code defines the constraintx + y
≤2
: The methoddouble infinity = Double.POSITIVE_INFINITY; // Create a linear constraint, x + y <= 2. MPConstraint ct = solver.makeConstraint(-infinity, 2.0, "ct"); ct.setCoefficient(x, 1); ct.setCoefficient(y, 1); System.out.println("Number of constraints = " + solver.numConstraints());
setCoefficient
sets the coefficients ofx
andy
in the expression for the constraint. - Define the objective function.
The method// Create the objective function, 3 * x + y. MPObjective objective = solver.objective(); objective.setCoefficient(x, 3); objective.setCoefficient(y, 1); objective.setMaximization();
setMaximization
declares this to be a maximization problem. - Invoke the solver and display the results.
System.out.println("Solving with " + solver.solverVersion()); final MPSolver.ResultStatus resultStatus = solver.solve(); System.out.println("Status: " + resultStatus); if (resultStatus != MPSolver.ResultStatus.OPTIMAL) { System.out.println("The problem does not have an optimal solution!"); if (resultStatus == MPSolver.ResultStatus.FEASIBLE) { System.out.println("A potentially suboptimal solution was found"); } else { System.out.println("The solver could not solve the problem."); return; } } System.out.println("Solution:"); System.out.println("Objective value = " + objective.value()); System.out.println("x = " + x.solutionValue()); System.out.println("y = " + y.solutionValue());
Complete program
The complete program is shown below.
package com.google.ortools.linearsolver.samples;
import com.google.ortools.Loader;
import com.google.ortools.init.OrToolsVersion;
import com.google.ortools.linearsolver.MPConstraint;
import com.google.ortools.linearsolver.MPObjective;
import com.google.ortools.linearsolver.MPSolver;
import com.google.ortools.linearsolver.MPVariable;
/** Minimal Linear Programming example to showcase calling the solver. */
public final class BasicExample {
public static void main(String[] args) {
Loader.loadNativeLibraries();
System.out.println("Google OR-Tools version: " + OrToolsVersion.getVersionString());
// Create the linear solver with the GLOP backend.
MPSolver solver = MPSolver.createSolver("GLOP");
if (solver == null) {
System.out.println("Could not create solver GLOP");
return;
}
// Create the variables x and y.
MPVariable x = solver.makeNumVar(0.0, 1.0, "x");
MPVariable y = solver.makeNumVar(0.0, 2.0, "y");
System.out.println("Number of variables = " + solver.numVariables());
double infinity = Double.POSITIVE_INFINITY;
// Create a linear constraint, x + y <= 2.
MPConstraint ct = solver.makeConstraint(-infinity, 2.0, "ct");
ct.setCoefficient(x, 1);
ct.setCoefficient(y, 1);
System.out.println("Number of constraints = " + solver.numConstraints());
// Create the objective function, 3 * x + y.
MPObjective objective = solver.objective();
objective.setCoefficient(x, 3);
objective.setCoefficient(y, 1);
objective.setMaximization();
System.out.println("Solving with " + solver.solverVersion());
final MPSolver.ResultStatus resultStatus = solver.solve();
System.out.println("Status: " + resultStatus);
if (resultStatus != MPSolver.ResultStatus.OPTIMAL) {
System.out.println("The problem does not have an optimal solution!");
if (resultStatus == MPSolver.ResultStatus.FEASIBLE) {
System.out.println("A potentially suboptimal solution was found");
} else {
System.out.println("The solver could not solve the problem.");
return;
}
}
System.out.println("Solution:");
System.out.println("Objective value = " + objective.value());
System.out.println("x = " + x.solutionValue());
System.out.println("y = " + y.solutionValue());
System.out.println("Advanced usage:");
System.out.println("Problem solved in " + solver.wallTime() + " milliseconds");
System.out.println("Problem solved in " + solver.iterations() + " iterations");
}
private BasicExample() {}
}
Running the Java program
You can run the program above as follows:
- Copy and paste the code above into new file, and save it as
my_program.java
. - Open a command window at the top level of the directory where you installed
OR-Tools, and enter:
wheremake run SOURCE=relative/path/to/my_program.java
relative/path/to/
is the path to the directory where you saved the program.
The program returns the values of x
and y
that maximize the objective
function:
Solution:
x = 1.0
y = 1.0
To just compile the program without running it, enter:
make build SOURCE=relative/path/to/my_program.java
More Java examples
For more Java examples that illustrate how to solve various types of optimization problems, see Examples.
Identifying the type of problem you wish to solve
There are many different types of optimization problems in the world. For each type of problem, there are different approaches and algorithms for finding an optimal solution.
Before you can start writing a program to solve an optimization problem, you need to identify what type of problem you are dealing with, and then choose an appropriate solver — an algorithm for finding an optimal solution.
Below you will find a brief overview of the types of problems that OR-Tools solves, and links to the sections in this guide that explain how to solve each problem type.
- Linear optimization
- Constraint optimization
- Mixed-integer optimization
- Assignment
- Scheduling
- Packing
- Routing
- Network flows
Linear optimization
As you learned in the previous section, a linear optimization problem is one in which the objective function and the constraints are linear expressions in the variables.
The primary solver in OR-Tools for this type of problem is the linear optimization solver, which is actually a wrapper for several different libraries for linear and mixed-integer optimization, including third-party libraries.
Learn more about linear optimization
Mixed-integer optimization
A mixed integer optimization problem is one in which some or all of the variables are required to be integers. An example is the assignment problem, in which a group of workers needs be assigned to a set of tasks. For each worker and task, you define a variable whose value is 1 if the given worker is assigned to the given task, and 0 otherwise. In this case, the variables can only take on the values 0 or 1.
Learn more about mixed-integer optimization
Constraint optimization
Constraint optimization, or constraint programming (CP), identifies feasible solutions out of a very large set of candidates, where the problem can be modeled in terms of arbitrary constraints. CP is based on feasibility (finding a feasible solution) rather than optimization (finding an optimal solution) and focuses on the constraints and variables rather than the objective function. However, CP can be used to solve optimization problems, simply by comparing the values of the objective function for all feasible solutions.
Learn more about constraint optimization
Assignment
Assignment problems involve assigning a group of agents (say, workers or machines) to a set of tasks, where there is a fixed cost for assigning each agent to a specific task. The problem is to find the assignment with the least total cost. Assignment problems are actually a special case of network flow problems.
Packing
Bin packing is the problem of packing a set of objects of different sizes into containers with different capacities. The goal is to pack as many of the objects as possible, subject to the capacities of the containers. A special case of this is the Knapsack problem, in which there is just one container.
Scheduling
Scheduling problems involve assigning resources to perform a set of tasks at specific times. An important example is the job shop problem, in which multiple jobs are processed on several machines. Each job consists of a sequence of tasks, which must be performed in a given order, and each task must be processed on a specific machine. The problem is to assign a schedule so that all jobs are completed in as short an interval of time as possible.
Routing
Routing problems involve finding the optimal routes for a fleet of vehicles to traverse a network, defined by a directed graph. The problem of assigning packages to delivery trucks, described in What is an optimization problem ?, is one example of a routing problem. Another is the traveling salesperson problem.
Network flows
Many optimization problems can be represented by a directed graph consisting of nodes and directed arcs between them. For example, transportation problems, in which goods are shipped across a railway network, can be represented by a graph in which the arcs are rail lines and the nodes are distribution centers.
In the maximum flow problem, each arc has a maximum capacity that can be transported across it. The problem is to assign the amount of goods to be shipped across each arc so that the total quantity being transported is as large as possible.