Class MPSolver
java.lang.Object
com.google.ortools.linearsolver.MPSolver
This mathematical programming (MP) solver class is the main class
though which users build and solve problems.
though which users build and solve problems.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic enum
Advanced usage: possible basis status values for a variable and the slack
variable of a linear constraint.static enum
The type of problems (LP or MIP) that will be solved and the underlying
solver (GLOP, GLPK, CLP, CBC or SCIP) that will solve them.static enum
The status of solving the problem. -
Field Summary
Fields -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotected
MPSolver
(long cPtr, boolean cMemoryOwn) MPSolver
(String name, MPSolver.OptimizationProblemType problem_type) Create a solver with the given name and underlying solver backend. -
Method Summary
Modifier and TypeMethodDescriptionvoid
clear()
Clears the objective (including the optimization direction), all variables
and constraints.double[]
Advanced usage: compute the "activities" of all constraints, which are the
sums of their linear terms.double
Advanced usage: computes the exact condition number of the current scaled
basis: L1norm(B) * L1norm(inverse(B)), where B is the scaled basis.
This method requires that a basis exists: it should be called after Solve.
It is only available for continuous problems.constraint
(int index) Returns the constraint at the given index.Returns the array of constraints handled by the MPSolver.
They are listed in the order in which they were created.Fills the solution found to a response proto and returns it.static MPSolver
createSolver
(String solver_id) Recommended factory method to create a MPSolver instance, especially in
non C++ languages.
It returns a newly created solver instance if successful, or a nullptr
otherwise.void
delete()
void
Enables solver logging.Export the loaded model in LP format.exportModelAsLpFormat
(boolean obfuscate) Export the loaded model in LP format.exportModelAsMpsFormat
(boolean fixed_format, boolean obfuscate) Export the loaded model in MPS format.Export the loaded model to proto and returns it.protected void
finalize()
protected static long
static double
infinity()
Infinity.
You can use -MPSolver::infinity() for negative infinity.boolean
Interrupts the Solve() execution to terminate processing if possible.
If the underlying interface supports interruption; it does that and returns
true regardless of whether there's an ongoing Solve() or not.boolean
isMip()
long
Returns the number of simplex iterations.loadModelFromProto
(MPModelProto input_model) Loads a model and returns the error message, which will be empty iff the
model is valid.loadModelFromProtoKeepNames
(MPModelProto input_model) Like loadModelFromProto(), but keeps the names and returns an error if
there are duplicate names.loadModelFromProtoWithUniqueNamesOrDie
(MPModelProto input_model) boolean
loadSolutionFromProto
(MPSolutionResponse response) Load a solution encoded in a protocol buffer onto this solver for easy
access via the MPSolver interface.
IMPORTANT: This may only be used in conjunction with ExportModel(),
following this example:
MPSolver my_solver; ... add variables and constraints ... MPModelProto model_proto; my_solver.ExportModelToProto(&model_proto); MPSolutionResponse solver_response; MPSolver::SolveWithProto(model_proto, &solver_response); if (solver_response.result_status() == MPSolutionResponse::OPTIMAL) { CHECK_OK(my_solver.LoadSolutionFromProto(solver_response)); ... inspect the solution using the usual API: solution_value(), etc... }
The response must be in OPTIMAL or FEASIBLE status.
Returns a false if a problem arised (typically, if it wasn't used
like it should be):
- loading a solution whose variables don't correspond to the solver's
current variables
- loading a solution with a status other than OPTIMAL / FEASIBLE.
Note: the objective value isn't checked.lookupConstraintOrNull
(String constraint_name) Looks up a constraint by name, and returns nullptr if it does not exist.
The first call has a O(n) complexity, as the constraint name index is
lazily created upon first use.lookupVariableOrNull
(String var_name) Looks up a variable by name, and returns nullptr if it does not exist.makeBoolVar
(String name) Creates a boolean variable.makeBoolVarArray
(int count) makeBoolVarArray
(int count, String var_name) Creates a constraint with -infinity and +infinity bounds.makeConstraint
(double lb, double ub) Creates a linear constraint with given bounds.
Bounds can be finite or +/- MPSolver::infinity().makeConstraint
(double lb, double ub, String name) Creates a named constraint with given bounds.makeConstraint
(String name) Creates a named constraint with -infinity and +infinity bounds.makeIntVar
(double lb, double ub, String name) Creates an integer variable.makeIntVarArray
(int count, double lb, double ub) makeIntVarArray
(int count, double lb, double ub, String var_name) makeNumVar
(double lb, double ub, String name) Creates a continuous variable.makeNumVarArray
(int count, double lb, double ub) makeNumVarArray
(int count, double lb, double ub, String var_name) Creates a variable with the given bounds, integrality requirement and
name.makeVarArray
(int count, double lb, double ub, boolean integer) Creates and returns an array of variables.makeVarArray
(int count, double lb, double ub, boolean integer, String var_name) Creates and returns an array of named variables.long
nodes()
Returns the number of branch-and-bound nodes evaluated during the solve.
Only available for discrete problems.int
Returns the number of constraints.int
Returns the number of variables.Returns the mutable objective object.Returns the optimization problem type set at construction.void
reset()
Advanced usage: resets extracted model to solve from scratch.
This won't reset the parameters that were set with
SetSolverSpecificParametersAsString() or set_time_limit() or even clear the
linear program.void
setHint
(MPVariable[] variables, double[] values) Sets a hint for solution.
If a feasible or almost-feasible solution to the problem is already known,
it may be helpful to pass it to the solver so that it can be used.boolean
setNumThreads
(int num_theads) Sets the number of threads to be used by the solver.boolean
setSolverSpecificParametersAsString
(String parameters) Advanced usage: pass solver specific parameters in text format.
The format is solver-specific and is the same as the corresponding solver
configuration file format.void
setTimeLimit
(long time_limit_milliseconds) solve()
Solves the problem using the default parameter values.solve
(MPSolverParameters param) Solves the problem using the specified parameter values.Returns a string describing the underlying solver and its version.static MPSolutionResponse
solveWithProto
(MPModelRequest model_request) Solves the given model proto and returns a response proto.static boolean
supportsProblemType
(MPSolver.OptimizationProblemType problem_type) Whether the given problem type is supported (this will depend on the
targets that you linked).void
Suppresses solver logging.protected static long
swigRelease
(MPSolver obj) variable
(int index) Returns the variable at position index.Returns the array of variables handled by the MPSolver.boolean
verifySolution
(double tolerance, boolean log_errors) Advanced usage: Verifies the *correctness* of the solution.
It verifies that all variables must be within their domains, all
constraints must be satisfied, and the reported objective value must be
accurate.
Usage:
- This can only be called after Solve() was called.
- "tolerance" is interpreted as an absolute error threshold.
- For the objective value only, if the absolute error is too large,
the tolerance is interpreted as a relative error threshold instead.
- If "log_errors" is true, every single violation will be logged.
- If "tolerance" is negative, it will be set to infinity().
Most users should just set the --verify_solution flag and not bother using
this method directly.long
wallTime()
void
Writes the model using the solver internal write function.boolean
writeModelToMpsFile
(String filename, boolean fixed_format, boolean obfuscate) Write the loaded model to file in MPS format.
-
Field Details
-
swigCMemOwn
protected transient boolean swigCMemOwn
-
-
Constructor Details
-
MPSolver
protected MPSolver(long cPtr, boolean cMemoryOwn) -
MPSolver
Create a solver with the given name and underlying solver backend.
-
-
Method Details
-
getCPtr
-
swigRelease
-
finalize
-
delete
public void delete() -
makeVarArray
Creates and returns an array of variables. -
makeVarArray
Creates and returns an array of named variables. -
makeNumVarArray
-
makeNumVarArray
-
makeIntVarArray
-
makeIntVarArray
-
makeBoolVarArray
-
makeBoolVarArray
-
createSolver
Recommended factory method to create a MPSolver instance, especially in
non C++ languages.
It returns a newly created solver instance if successful, or a nullptr
otherwise. This can occur if the relevant interface is not linked in, or if
a needed license is not accessible for commercial solvers.
Ownership of the solver is passed on to the caller of this method.
It will accept both string names of the OptimizationProblemType enum, as
well as a short version (i.e. "SCIP_MIXED_INTEGER_PROGRAMMING" or "SCIP").
solver_id is case insensitive, and the following names are supported:
- CLP_LINEAR_PROGRAMMING or CLP
- CBC_MIXED_INTEGER_PROGRAMMING or CBC
- GLOP_LINEAR_PROGRAMMING or GLOP
- BOP_INTEGER_PROGRAMMING or BOP
- SAT_INTEGER_PROGRAMMING or SAT or CP_SAT
- SCIP_MIXED_INTEGER_PROGRAMMING or SCIP
- GUROBI_LINEAR_PROGRAMMING or GUROBI_LP
- GUROBI_MIXED_INTEGER_PROGRAMMING or GUROBI or GUROBI_MIP
- CPLEX_LINEAR_PROGRAMMING or CPLEX_LP
- CPLEX_MIXED_INTEGER_PROGRAMMING or CPLEX or CPLEX_MIP
- XPRESS_LINEAR_PROGRAMMING or XPRESS_LP
- XPRESS_MIXED_INTEGER_PROGRAMMING or XPRESS or XPRESS_MIP
- GLPK_LINEAR_PROGRAMMING or GLPK_LP
- GLPK_MIXED_INTEGER_PROGRAMMING or GLPK or GLPK_MIP -
supportsProblemType
Whether the given problem type is supported (this will depend on the
targets that you linked). -
isMip
public boolean isMip() -
problemType
Returns the optimization problem type set at construction. -
clear
public void clear()Clears the objective (including the optimization direction), all variables
and constraints. All the other properties of the MPSolver (like the time
limit) are kept untouched. -
numVariables
public int numVariables()Returns the number of variables. -
variables
Returns the array of variables handled by the MPSolver. (They are listed in
the order in which they were created.) -
variable
Returns the variable at position index. -
lookupVariableOrNull
Looks up a variable by name, and returns nullptr if it does not exist. The
first call has a O(n) complexity, as the variable name index is lazily
created upon first use. Will crash if variable names are not unique. -
makeVar
Creates a variable with the given bounds, integrality requirement and
name. Bounds can be finite or +/- MPSolver::infinity(). The MPSolver owns
the variable (i.e. the returned pointer is borrowed). Variable names are
optional. If you give an empty name, name() will auto-generate one for you
upon request. -
makeNumVar
Creates a continuous variable. -
makeIntVar
Creates an integer variable. -
makeBoolVar
Creates a boolean variable. -
numConstraints
public int numConstraints()Returns the number of constraints. -
constraints
Returns the array of constraints handled by the MPSolver.
They are listed in the order in which they were created. -
constraint
Returns the constraint at the given index. -
lookupConstraintOrNull
Looks up a constraint by name, and returns nullptr if it does not exist.
The first call has a O(n) complexity, as the constraint name index is
lazily created upon first use. Will crash if constraint names are not
unique. -
makeConstraint
Creates a linear constraint with given bounds.
Bounds can be finite or +/- MPSolver::infinity(). The MPSolver class
assumes ownership of the constraint.
- Returns:
- a pointer to the newly created constraint.
-
makeConstraint
Creates a constraint with -infinity and +infinity bounds. -
makeConstraint
Creates a named constraint with given bounds. -
makeConstraint
Creates a named constraint with -infinity and +infinity bounds. -
objective
Returns the mutable objective object. -
solve
Solves the problem using the default parameter values. -
solve
Solves the problem using the specified parameter values. -
write
Writes the model using the solver internal write function. Currently only
available for Gurobi. -
computeConstraintActivities
public double[] computeConstraintActivities()Advanced usage: compute the "activities" of all constraints, which are the
sums of their linear terms. The activities are returned in the same order
as constraints(), which is the order in which constraints were added; but
you can also use MPConstraint::index() to get a constraint's index. -
verifySolution
public boolean verifySolution(double tolerance, boolean log_errors) Advanced usage: Verifies the *correctness* of the solution.
It verifies that all variables must be within their domains, all
constraints must be satisfied, and the reported objective value must be
accurate.
Usage:
- This can only be called after Solve() was called.
- "tolerance" is interpreted as an absolute error threshold.
- For the objective value only, if the absolute error is too large,
the tolerance is interpreted as a relative error threshold instead.
- If "log_errors" is true, every single violation will be logged.
- If "tolerance" is negative, it will be set to infinity().
Most users should just set the --verify_solution flag and not bother using
this method directly. -
reset
public void reset()Advanced usage: resets extracted model to solve from scratch.
This won't reset the parameters that were set with
SetSolverSpecificParametersAsString() or set_time_limit() or even clear the
linear program. It will just make sure that next Solve() will be as if
everything was reconstructed from scratch. -
interruptSolve
public boolean interruptSolve()Interrupts the Solve() execution to terminate processing if possible.
If the underlying interface supports interruption; it does that and returns
true regardless of whether there's an ongoing Solve() or not. The Solve()
call may still linger for a while depending on the conditions. If
interruption is not supported; returns false and does nothing.
MPSolver::SolverTypeSupportsInterruption can be used to check if
interruption is supported for a given solver type. -
setSolverSpecificParametersAsString
Advanced usage: pass solver specific parameters in text format.
The format is solver-specific and is the same as the corresponding solver
configuration file format. Returns true if the operation was successful. -
infinity
public static double infinity()Infinity.
You can use -MPSolver::infinity() for negative infinity. -
enableOutput
public void enableOutput()Enables solver logging. -
suppressOutput
public void suppressOutput()Suppresses solver logging. -
iterations
public long iterations()Returns the number of simplex iterations. -
nodes
public long nodes()Returns the number of branch-and-bound nodes evaluated during the solve.
Only available for discrete problems. -
solverVersion
Returns a string describing the underlying solver and its version. -
computeExactConditionNumber
public double computeExactConditionNumber()Advanced usage: computes the exact condition number of the current scaled
basis: L1norm(B) * L1norm(inverse(B)), where B is the scaled basis.
This method requires that a basis exists: it should be called after Solve.
It is only available for continuous problems. It is implemented for GLPK
but not CLP because CLP does not provide the API for doing it.
The condition number measures how well the constraint matrix is conditioned
and can be used to predict whether numerical issues will arise during the
solve: the model is declared infeasible whereas it is feasible (or
vice-versa), the solution obtained is not optimal or violates some
constraints, the resolution is slow because of repeated singularities.
The rule of thumb to interpret the condition number kappa is:
- o kappa <= 1e7: virtually no chance of numerical issues
- o 1e7 < kappa <= 1e10: small chance of numerical issues
- o 1e10 < kappa <= 1e13: medium chance of numerical issues
- o kappa > 1e13: high chance of numerical issues
The computation of the condition number depends on the quality of the LU
decomposition, so it is not very accurate when the matrix is ill
conditioned. -
setTimeLimit
public void setTimeLimit(long time_limit_milliseconds) -
wallTime
public long wallTime() -
loadModelFromProto
Loads a model and returns the error message, which will be empty iff the
model is valid. Clears all names (see also loadModelFromProtoKeepNames()). -
loadModelFromProtoKeepNames
Like loadModelFromProto(), but keeps the names and returns an error if
there are duplicate names. -
loadModelFromProtoWithUniqueNamesOrDie
-
exportModelToProto
Export the loaded model to proto and returns it. -
createSolutionResponseProto
Fills the solution found to a response proto and returns it. -
loadSolutionFromProto
Load a solution encoded in a protocol buffer onto this solver for easy
access via the MPSolver interface.
IMPORTANT: This may only be used in conjunction with ExportModel(),
following this example:
MPSolver my_solver; ... add variables and constraints ... MPModelProto model_proto; my_solver.ExportModelToProto(&model_proto); MPSolutionResponse solver_response; MPSolver::SolveWithProto(model_proto, &solver_response); if (solver_response.result_status() == MPSolutionResponse::OPTIMAL) { CHECK_OK(my_solver.LoadSolutionFromProto(solver_response)); ... inspect the solution using the usual API: solution_value(), etc... }
The response must be in OPTIMAL or FEASIBLE status.
Returns a false if a problem arised (typically, if it wasn't used
like it should be):
- loading a solution whose variables don't correspond to the solver's
current variables
- loading a solution with a status other than OPTIMAL / FEASIBLE.
Note: the objective value isn't checked. You can use VerifySolution() for
that. -
solveWithProto
Solves the given model proto and returns a response proto. -
exportModelAsLpFormat
Export the loaded model in LP format. -
exportModelAsLpFormat
Export the loaded model in LP format. -
exportModelAsMpsFormat
Export the loaded model in MPS format. -
writeModelToMpsFile
Write the loaded model to file in MPS format. -
setHint
Sets a hint for solution.
If a feasible or almost-feasible solution to the problem is already known,
it may be helpful to pass it to the solver so that it can be used. A
solver that supports this feature will try to use this information to
create its initial feasible solution.
Note that it may not always be faster to give a hint like this to the
solver. There is also no guarantee that the solver will use this hint or
try to return a solution "close" to this assignment in case of multiple
optimal solutions. -
setNumThreads
public boolean setNumThreads(int num_theads) Sets the number of threads to be used by the solver.
-