Class MPSolver

java.lang.Object
com.google.ortools.linearsolver.MPSolver

public class MPSolver extends Object
This 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 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
    Modifier and Type
    Field
    Description
    protected boolean
     
  • Constructor Summary

    Constructors
    Modifier
    Constructor
    Description
    protected
    MPSolver(long cPtr, boolean cMemoryOwn)
     
     
    Create a solver with the given name and underlying solver backend.
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    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
     
    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
     
    protected static long
     
    static double
    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
     
    long
    Returns the number of simplex iterations.
    Loads a model and returns the error message, which will be empty iff the
    model is valid.
    Like loadModelFromProto(), but keeps the names and returns an error if
    there are duplicate names.
     
    boolean
    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.
    Looks up a variable by name, and returns nullptr if it does not exist.
    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.
    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)
     
    makeVar(double lb, double ub, boolean integer, String 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
    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
    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
    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)
     
    Solves the problem using the default parameter values.
    Solves the problem using the specified parameter values.
    Returns a string describing the underlying solver and its version.
    Solves the given model proto and returns a response proto.
    static boolean
    Whether the given problem type is supported (this will depend on the
    targets that you linked).
    void
    Suppresses solver logging.
    protected static long
     
    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
     
    void
    write(String file_name)
    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.

    Methods inherited from class java.lang.Object

    clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Field Details

    • swigCMemOwn

      protected transient boolean swigCMemOwn
  • Constructor Details

    • MPSolver

      protected MPSolver(long cPtr, boolean cMemoryOwn)
    • MPSolver

      public MPSolver(String name, MPSolver.OptimizationProblemType problem_type)
      Create a solver with the given name and underlying solver backend.
  • Method Details

    • getCPtr

      protected static long getCPtr(MPSolver obj)
    • swigRelease

      protected static long swigRelease(MPSolver obj)
    • finalize

      protected void finalize()
      Overrides:
      finalize in class 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, 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, String var_name)
    • makeIntVarArray

      public MPVariable[] makeIntVarArray(int count, double lb, double ub)
    • makeIntVarArray

      public MPVariable[] makeIntVarArray(int count, double lb, double ub, String var_name)
    • makeBoolVarArray

      public MPVariable[] makeBoolVarArray(int count)
    • makeBoolVarArray

      public MPVariable[] makeBoolVarArray(int count, String var_name)
    • createSolver

      public 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. 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(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, 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, String name)
      Creates a continuous variable.
    • makeIntVar

      public MPVariable makeIntVar(double lb, double ub, String name)
      Creates an integer variable.
    • makeBoolVar

      public MPVariable makeBoolVar(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(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, String name)
      Creates a named constraint with given bounds.
    • makeConstraint

      public MPConstraint makeConstraint(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

      Solves the problem using the specified parameter values.
    • write

      public void write(String file_name)
      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

      public 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. 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 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 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 String loadModelFromProtoKeepNames(MPModelProto input_model)
      Like loadModelFromProto(), but keeps the names and returns an error if
      there are duplicate names.
    • loadModelFromProtoWithUniqueNamesOrDie

      public 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 String exportModelAsLpFormat(boolean obfuscate)
      Export the loaded model in LP format.
    • exportModelAsLpFormat

      public String exportModelAsLpFormat()
      Export the loaded model in LP format.
    • exportModelAsMpsFormat

      public String exportModelAsMpsFormat(boolean fixed_format, boolean obfuscate)
      Export the loaded model in MPS format.
    • writeModelToMpsFile

      public boolean writeModelToMpsFile(String filename, boolean fixed_format, boolean obfuscate)
      Write the loaded model to file 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.