Package com.google.ortools.linearsolver
Class MPSolver
- java.lang.Object
-
- com.google.ortools.linearsolver.MPSolver
-
public class MPSolver extends java.lang.ObjectThis mathematical programming (MP) solver class is the main class
though which users build and solve problems.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classMPSolver.BasisStatusAdvanced usage: possible basis status values for a variable and the slack
variable of a linear constraint.static classMPSolver.OptimizationProblemTypeThe 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 classMPSolver.ResultStatusThe status of solving the problem.
-
Field Summary
Fields Modifier and Type Field Description protected booleanswigCMemOwn
-
Constructor Summary
Constructors Modifier Constructor Description protectedMPSolver(long cPtr, boolean cMemoryOwn)MPSolver(java.lang.String name, MPSolver.OptimizationProblemType problem_type)Create a solver with the given name and underlying solver backend.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description voidclear()Clears the objective (including the optimization direction), all variables
and constraints.double[]computeConstraintActivities()Advanced usage: compute the "activities" of all constraints, which are the
sums of their linear terms.doublecomputeExactConditionNumber()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.MPConstraintconstraint(int index)Returns the constraint at the given index.MPConstraint[]constraints()Returns the array of constraints handled by the MPSolver.
They are listed in the order in which they were created.MPSolutionResponsecreateSolutionResponseProto()Fills the solution found to a response proto and returns it.static MPSolvercreateSolver(java.lang.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.voiddelete()voidenableOutput()Enables solver logging.java.lang.StringexportModelAsLpFormat()Export the loaded model in LP format.java.lang.StringexportModelAsLpFormat(MPModelExportOptions options)Export the loaded model in LP format.java.lang.StringexportModelAsMpsFormat()Export the loaded model in MPS format.java.lang.StringexportModelAsMpsFormat(MPModelExportOptions options)Export the loaded model in MPS format.MPModelProtoexportModelToProto()Export the loaded model to proto and returns it.protected voidfinalize()protected static longgetCPtr(MPSolver obj)static doubleinfinity()Infinity.
You can use -MPSolver::infinity() for negative infinity.booleaninterruptSolve()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.booleanisMip()longiterations()Returns the number of simplex iterations.java.lang.StringloadModelFromProto(MPModelProto input_model)Loads a model and returns the error message, which will be empty iff the
model is valid.java.lang.StringloadModelFromProtoKeepNames(MPModelProto input_model)Like loadModelFromProto(), but keeps the names and returns an error if
there are duplicate names.java.lang.StringloadModelFromProtoWithUniqueNamesOrDie(MPModelProto input_model)booleanloadSolutionFromProto(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.MPConstraintlookupConstraintOrNull(java.lang.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.MPVariablelookupVariableOrNull(java.lang.String var_name)Looks up a variable by name, and returns nullptr if it does not exist.MPVariablemakeBoolVar(java.lang.String name)Creates a boolean variable.MPVariable[]makeBoolVarArray(int count)MPVariable[]makeBoolVarArray(int count, java.lang.String var_name)MPConstraintmakeConstraint()Creates a constraint with -infinity and +infinity bounds.MPConstraintmakeConstraint(double lb, double ub)Creates a linear constraint with given bounds.
Bounds can be finite or +/- MPSolver::infinity().MPConstraintmakeConstraint(double lb, double ub, java.lang.String name)Creates a named constraint with given bounds.MPConstraintmakeConstraint(java.lang.String name)Creates a named constraint with -infinity and +infinity bounds.MPVariablemakeIntVar(double lb, double ub, java.lang.String name)Creates an integer variable.MPVariable[]makeIntVarArray(int count, double lb, double ub)MPVariable[]makeIntVarArray(int count, double lb, double ub, java.lang.String var_name)MPVariablemakeNumVar(double lb, double ub, java.lang.String name)Creates a continuous variable.MPVariable[]makeNumVarArray(int count, double lb, double ub)MPVariable[]makeNumVarArray(int count, double lb, double ub, java.lang.String var_name)MPVariablemakeVar(double lb, double ub, boolean integer, java.lang.String name)Creates a variable with the given bounds, integrality requirement and
name.MPVariable[]makeVarArray(int count, double lb, double ub, boolean integer)Creates and returns an array of variables.MPVariable[]makeVarArray(int count, double lb, double ub, boolean integer, java.lang.String var_name)Creates and returns an array of named variables.longnodes()Returns the number of branch-and-bound nodes evaluated during the solve.
Only available for discrete problems.intnumConstraints()Returns the number of constraints.intnumVariables()Returns the number of variables.MPObjectiveobjective()Returns the mutable objective object.MPSolver.OptimizationProblemTypeproblemType()Returns the optimization problem type set at construction.voidreset()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.voidsetHint(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.booleansetNumThreads(int num_theads)Sets the number of threads to be used by the solver.booleansetSolverSpecificParametersAsString(java.lang.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.voidsetTimeLimit(long time_limit_milliseconds)MPSolver.ResultStatussolve()Solves the problem using the default parameter values.MPSolver.ResultStatussolve(MPSolverParameters param)Solves the problem using the specified parameter values.java.lang.StringsolverVersion()Returns a string describing the underlying solver and its version.static MPSolutionResponsesolveWithProto(MPModelRequest model_request)Solves the given model proto and returns a response proto.static booleansupportsProblemType(MPSolver.OptimizationProblemType problem_type)Whether the given problem type is supported (this will depend on the
targets that you linked).voidsuppressOutput()Suppresses solver logging.protected static longswigRelease(MPSolver obj)MPVariablevariable(int index)Returns the variable at position index.MPVariable[]variables()Returns the array of variables handled by the MPSolver.booleanverifySolution(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.longwallTime()
-
-
-
Constructor Detail
-
MPSolver
protected MPSolver(long cPtr, boolean cMemoryOwn)
-
MPSolver
public MPSolver(java.lang.String name, MPSolver.OptimizationProblemType problem_type)Create a solver with the given name and underlying solver backend.
-
-
Method Detail
-
getCPtr
protected static long getCPtr(MPSolver obj)
-
swigRelease
protected static long swigRelease(MPSolver obj)
-
finalize
protected void finalize()
- Overrides:
finalizein classjava.lang.Object
-
delete
public void delete()
-
makeVarArray
public MPVariable[] makeVarArray(int count, double lb, double ub, boolean integer)
Creates and returns an array of variables.
-
makeVarArray
public MPVariable[] makeVarArray(int count, double lb, double ub, boolean integer, java.lang.String var_name)
Creates and returns an array of named variables.
-
makeNumVarArray
public MPVariable[] makeNumVarArray(int count, double lb, double ub)
-
makeNumVarArray
public MPVariable[] makeNumVarArray(int count, double lb, double ub, java.lang.String var_name)
-
makeIntVarArray
public MPVariable[] makeIntVarArray(int count, double lb, double ub)
-
makeIntVarArray
public MPVariable[] makeIntVarArray(int count, double lb, double ub, java.lang.String var_name)
-
makeBoolVarArray
public MPVariable[] makeBoolVarArray(int count)
-
makeBoolVarArray
public MPVariable[] makeBoolVarArray(int count, java.lang.String var_name)
-
createSolver
public static MPSolver createSolver(java.lang.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. 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
public static boolean supportsProblemType(MPSolver.OptimizationProblemType problem_type)
Whether the given problem type is supported (this will depend on the
targets that you linked).
-
isMip
public boolean isMip()
-
problemType
public MPSolver.OptimizationProblemType 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
public MPVariable[] variables()
Returns the array of variables handled by the MPSolver. (They are listed in
the order in which they were created.)
-
variable
public MPVariable variable(int index)
Returns the variable at position index.
-
lookupVariableOrNull
public MPVariable lookupVariableOrNull(java.lang.String var_name)
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
public MPVariable makeVar(double lb, double ub, boolean integer, java.lang.String name)
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
public MPVariable makeNumVar(double lb, double ub, java.lang.String name)
Creates a continuous variable.
-
makeIntVar
public MPVariable makeIntVar(double lb, double ub, java.lang.String name)
Creates an integer variable.
-
makeBoolVar
public MPVariable makeBoolVar(java.lang.String name)
Creates a boolean variable.
-
numConstraints
public int numConstraints()
Returns the number of constraints.
-
constraints
public MPConstraint[] constraints()
Returns the array of constraints handled by the MPSolver.
They are listed in the order in which they were created.
-
constraint
public MPConstraint constraint(int index)
Returns the constraint at the given index.
-
lookupConstraintOrNull
public MPConstraint lookupConstraintOrNull(java.lang.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. Will crash if constraint names are not
unique.
-
makeConstraint
public MPConstraint makeConstraint(double lb, double ub)
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
public MPConstraint makeConstraint()
Creates a constraint with -infinity and +infinity bounds.
-
makeConstraint
public MPConstraint makeConstraint(double lb, double ub, java.lang.String name)
Creates a named constraint with given bounds.
-
makeConstraint
public MPConstraint makeConstraint(java.lang.String name)
Creates a named constraint with -infinity and +infinity bounds.
-
objective
public MPObjective objective()
Returns the mutable objective object.
-
solve
public MPSolver.ResultStatus solve()
Solves the problem using the default parameter values.
-
solve
public MPSolver.ResultStatus solve(MPSolverParameters param)
Solves the problem using the specified parameter values.
-
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
public boolean setSolverSpecificParametersAsString(java.lang.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. 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
public java.lang.String 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
public java.lang.String loadModelFromProto(MPModelProto input_model)
Loads a model and returns the error message, which will be empty iff the
model is valid. Clears all names (see also loadModelFromProtoKeepNames()).
-
loadModelFromProtoKeepNames
public java.lang.String loadModelFromProtoKeepNames(MPModelProto input_model)
Like loadModelFromProto(), but keeps the names and returns an error if
there are duplicate names.
-
loadModelFromProtoWithUniqueNamesOrDie
public java.lang.String loadModelFromProtoWithUniqueNamesOrDie(MPModelProto input_model)
-
exportModelToProto
public MPModelProto exportModelToProto()
Export the loaded model to proto and returns it.
-
createSolutionResponseProto
public MPSolutionResponse createSolutionResponseProto()
Fills the solution found to a response proto and returns it.
-
loadSolutionFromProto
public 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. You can use VerifySolution() for
that.
-
solveWithProto
public static MPSolutionResponse solveWithProto(MPModelRequest model_request)
Solves the given model proto and returns a response proto.
-
exportModelAsLpFormat
public java.lang.String exportModelAsLpFormat(MPModelExportOptions options)
Export the loaded model in LP format.
-
exportModelAsLpFormat
public java.lang.String exportModelAsLpFormat()
Export the loaded model in LP format.
-
exportModelAsMpsFormat
public java.lang.String exportModelAsMpsFormat(MPModelExportOptions options)
Export the loaded model in MPS format.
-
exportModelAsMpsFormat
public java.lang.String exportModelAsMpsFormat()
Export the loaded model in MPS format.
-
setHint
public 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. 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.
-
-