Module docplex.cp.solver.solver

This module implements appropriate software to solve a CPO model represented by a docplex.cp.model.CpoModel object.

It implements the following object classes:

  • CpoSolver contains the public interface allowing to make solving requests with a model.
  • CpoSolverAgent is an abstract class that is extended by the actual implementation(s) of the solving functions.

The CpoSolver identifies and creates the required CpoSolverAgent depending on the configuration parameter context.solver.agent that contains the name of the agent to be used. This name is used to access the configuration context context.solver.<agent> that contains the details about this agent.

For example, the default configuration refers to local as default solver agent, to solve model using local process CP Optimizer Interactive. This means that at least following configuration elements must be set:

context.solver.agent = 'local'
context.solver.local.execfile = <Name or path of the process 'CP Optimizer Interactive'>

The different methods that can be called on a CpoSolver object are:

  • solve() simply solve the model and returns a solve result, if any. For convenience reason, this method is also directly available on the CpoModel object (docplex.cp.model.CpoModel.solve()).
  • search_next() and end_search() allows to iterate on different solutions of the model.
  • refine_conflict() calls the conflict refiner that identifies a minimal conflict for the infeasibility of the model.
  • propagate() calls the propagation that communicates the domain reduction of a decision variable to all of the constraints that are stated over this variable.

Except solve(), these functions are only available with a local solver with release greater or equal to 12.7.0.0 When a method is not available, an exception CpoNotSupportedException is raised.

If the methods search_next() and end_search() are available in the underlying solver agent, the CpoSolver object acts as an iterator. All solutions are retrieved using a loop like:

solver = CpoSolver(mdl)
for sol in solver:
    sol.write()

A such solution iteration can be interrupted at any time by calling end_search() that returns a fail solution including the last solve status.

Detailed description

class docplex.cp.solver.solver.CpoSolver(model, **kwargs)[source]

Bases: object

This class represents the public API of the object allowing to solve a CPO model.

It create the appropriate CpoSolverAgent that actually implements solving functions, depending on the value of the configuration parameter context.solver.agent.

Constructor

All necessary solving parameters are taken from the solving context that is constructed from the following list of sources, each one overwriting the previous:

  • the default solving context that is defined in the module config
  • the user-specific customizations of the context that may be defined (see config for details),
  • the parameters that are set in the model itself,
  • the optional arguments of this method.

If an optional argument other than context or params is given to this method, it is searched in the context where its value is replaced by the new one. If not found, it is then considered as a solver parameter. In this case, only public parameters are allowed, except if the context attribute solver.enable_undocumented_params is set to True. This can be done directly when creating the solver, as for example:

slvr = CpoSolver(mdl, enable_undocumented_params=True, MyPrivateParam=MyValue)
Parameters:
  • context (Optional) – Complete solving context. If not given, solving context is the default one that is defined in the module config.
  • params (Optional) – Solving parameters (object of class CpoParameters) that overwrite those in the solving context.
  • (param) (Optional) – Any individual solving parameter as defined in class CpoParameters (for example TimeLimit, Workers, SearchType, etc).
  • (others) (Optional) – Any leaf attribute with the same name in the solving context (for example agent, trace_log, trace_cpo, etc).
  • (listeners) (Optional) – List of solution listeners
add_callback(cback)[source]

Add a CPO solver callback.

A solver callback is an object extending the class CpoCallback which provides multiple functions that are called to notify about the different solving steps.

Parameters:cback – Solver callback
add_listener(lstnr)[source]

Add a solver listener.

A solver listener is an object extending the class CpoSolverListener which provides multiple functions that are called to notify about the different solving steps.

Parameters:lstnr – Solver listener

End current search.

This function is available only with local CPO solver with release number greater or equal to 12.7.0.

Returns:Last model solution with last solve information, object of class CpoSolveResult.
Raises:CpoNotSupportedException – if method not available in the solver agent.
explain_failure(ltags=None)[source]

This method allows to explain solve failures.

If called with no arguments, this method invokes a solve of the model with appropriate parameters that enable, in the log, the print of a number tag for each solve failure.

If called with a list of failure tag to explain, the solver is invoked again in a way that it explains, in the log, the reason for the failure of the required failure tags.

This method sets the following solve parameters before calling the solver:

  • LogSearchTags = ‘On’
  • Workers = 1
  • LogPeriod = 1
  • SearchType = ‘DepthFirst’
Parameters:ltags – List of tag ids to explain. If empty or None, the solver is just invoked with appropriate solve parameters to make failure tags displayed in the log.
Returns:Solve result, object of class CpoSolveResult.
Raises:CpoNotSupportedException – method not available in this solver agent.
get_cpo_model_string()[source]

Get the CPO model as a string, as it is sent to the solver.

Result string is the exact string that is sent to solver, including all variations caused by configuration or changes made when creating the solver.

Returns:String containing the CPO model in CPO file format
get_last_result()[source]

Get the last result returned by this solver.

Calling this method can be useful to determine, for example, if the last solution returned by a sequence of start_search() and search_next(), or by a solution iterator, is optimal.

Returns:Solve result, object of class CpoSolveResult.
get_last_solution()[source]

Get the last result returned by this solver.

DEPRECATED. Use get_last_result instead.

Returns:Solve result, object of class CpoSolveResult.
get_model()[source]

Returns the model solved by this solver.

Returns:Model solved by this solver
get_model_format_version()[source]

If defined, returns the format version of the model.

Returns:Model format version, None if not defined.
get_parameters()[source]

Get the actual solver parameters, as modified by configuration or arguments.

Returns:Solver parameters, object of class CpoParameters.
get_solver_version()[source]

Returns, if available, the version of the underlying solver.

Returns:Solver version, None if not defined.
propagate()[source]

This method invokes the propagation on the current model.

Constraint propagation is the process of communicating the domain reduction of a decision variable to all of the constraints that are stated over this variable. This process can result in more domain reductions. These domain reductions, in turn, are communicated to the appropriate constraints. This process continues until no more variable domains can be reduced or when a domain becomes empty and a failure occurs. An empty domain during the initial constraint propagation means that the model has no solution.

The result is a object of class CpoSolveResult, the same than the one returned by solve() method. However, variable domains may not be completely defined.

This function is available only with local CPO solver with release number greater or equal to 12.7.0.

Returns:Propagation result, object of class CpoSolveResult.
Raises:CpoNotSupportedException – method not available in configured solver agent.
refine_conflict()[source]

This method identifies a minimal conflict for the infeasibility of the current model.

Given an infeasible model, the conflict refiner can identify conflicting constraints and variable domains within the model to help you identify the causes of the infeasibility. In this context, a conflict is a subset of the constraints and/or variable domains of the model which are mutually contradictory. Since the conflict is minimal, removal of any one of these constraints will remove that particular cause for infeasibility. There may be other conflicts in the model; consequently, repair of a given conflict does not guarantee feasibility of the remaining model.

Conflict refiner is controlled by the following parameters (that can be set at CpoSolver creation):

  • ConflictRefinerBranchLimit
  • ConflictRefinerFailLimit
  • ConflictRefinerIterationLimit
  • ConflictRefinerOnVariables
  • ConflictRefinerTimeLimit

that are described in module docplex.cp.parameters.

Note that the general TimeLimit parameter is used as a limiter for each conflict refiner iteration, but the global limitation in time must be set using ConflictRefinerTimeLimit that is infinite by default.

This function is available only with local CPO solver with release number greater or equal to 12.7.0.

Returns:List of constraints that cause the conflict, object of class CpoRefineConflictResult.
Raises:CpoNotSupportedException – if method not available in the solver agent.
remove_callback(cback)[source]

Remove a CPO solver callback. previously added with add_callback().

Parameters:cback – Callback to remove.
remove_listener(lstnr)[source]

Remove a solver listener previously added with add_listener().

Parameters:lstnr – Listener to remove.
run_seeds(nbrun)[source]

This method runs nbrun times the CP optimizer search with different random seeds and computes statistics from the result of these runs.

Result statistics are displayed on the log output that should be activated. If the appropriate configuration variable context.solver.add_log_to_solution is set to True (default), log is also available in the CpoRunResult result object, accessible as a string using the method get_solver_log()

Each run of the solver is stopped according to single solve conditions (TimeLimit for example). Total run time is then expected to take nbruns times the duration of a single run.

Parameters:nbrun – Number of runs with different seeds.
Returns:Run result, object of class CpoRunResult.
Raises:CpoNotSupportedException – method not available in configured solver agent.
search_next()[source]

Get the next available solution.

This method returns an object of class CpoSolveResult whose method is_solution() returns True if a new solution is found. This method returns False if there is no solution, or if the solution is the same than the previous one but the solve status has moved from Feasible to Optimal. In this last case, the optimality of the last solution can be checked using the following code:

optimal = slvr.get_last_result().is_solution_optimal()

This function is available with local CPO solver for release number greater or equal to 12.7.0.

Returns:Next solve result, object of class CpoSolveResult.
Raises:CpoNotSupportedException – if method not available in the solver agent.
set_solve_with_search_next(swsn)[source]

Set the flag indicating to solve with a search_next sequence instead of a single solve.

If this indicator is set, a call to method solve() will automatically call method solve_with_search_next() instead, allowing listeners to be warned about all intermediate solutions.

The same behavior is also obtained if the configuration attribute context.solver.solve_with_search_next is set to True.

Parameters:swsn – Solve wist start-next indicator
solve()[source]

Solve the model

This function solves the model using CP Optimizer’s built-in strategy. The built-in strategy is determined by setting the parameter SearchType (see docplex.cp.parameters). If the model contains an objective, then the optimal solution with respect to the objective will be calculated. Otherwise, a solution satisfying all problem constraints will be calculated.

The function returns an object of the class CpoSolveResult (see docplex.cp.solution) that contains the solution if exists, plus different information on the solving process.

If the context parameter solve_with_search_next (or config parameter context.solver.solve_with_search_next) is set to True, the call to solve() is replaced by loop of search_next() calls which returns the last solution found. Difference is that, if a solver listener has been added to the solver, it is warned of all intermediate solutions.

Returns:Solve result, object of class CpoSolveResult.
Raises:CpoException – (or derived) if error.
solve_with_search_next()[source]

Solve the model using a start/next loop instead of standard solve.

Returns:Last solve result
class docplex.cp.solver.solver.CpoSolverAgent(solver, context)[source]

Bases: object

This class is an abstract class that must be extended by every solver agent that intend to be called by CpoSolver to solve a CPO model.

Constructor

Parameters:
  • solver – Parent solver, object of type CpoSolver
  • context – Solver agent context
Raises:

CpoException if agent can not be created properly.

Abort current search. This method is designed to be called by a different thread than the one currently solving.

Raises:CpoNotSupportedException – method not available in this solver agent.
end()[source]

End solver agent and release all resources.

End current search.

Returns:Last (fail) solve result with last solve information, object of class CpoSolveResult.
Raises:CpoNotSupportedException – method not available in this solver agent.
propagate()[source]

This method invokes the propagation on the current model.

Constraint propagation is the process of communicating the domain reduction of a decision variable to all of the constraints that are stated over this variable. This process can result in more domain reductions. These domain reductions, in turn, are communicated to the appropriate constraints. This process continues until no more variable domains can be reduced or when a domain becomes empty and a failure occurs. An empty domain during the initial constraint propagation means that the model has no solution.

The result is a object of class CpoSolveResult, the same than the one returned by solve() method. However, in this case, variable domains may not be completely defined.

Returns:Propagation result, object of class CpoSolveResult.
Raises:CpoNotSupportedException – method not available in this solver agent.
refine_conflict()[source]

This method identifies a minimal conflict for the infeasibility of the current model.

Given an infeasible model, the conflict refiner can identify conflicting constraints and variable domains within the model to help you identify the causes of the infeasibility. In this context, a conflict is a subset of the constraints and/or variable domains of the model which are mutually contradictory. Since the conflict is minimal, removal of any one of these constraints will remove that particular cause for infeasibility. There may be other conflicts in the model; consequently, repair of a given conflict does not guarantee feasibility of the remaining model.

Returns:Conflict result, object of class CpoRefineConflictResult.
Raises:CpoNotSupportedException – method not available in this solver agent.
run_seeds(nbrun)[source]

This method runs nbrun times the CP optimizer search with different random seeds and computes statistics from the result of these runs.

Result statistics are displayed on the log output that should be activated. If the appropriate configuration variable context.solver.add_log_to_solution is set to True (default), log is also available in the CpoRunResult result object, accessible as a string using the method get_solver_log()

Each run of the solver is stopped according to single solve conditions (TimeLimit for example). Total run time is then expected to take nbruns times the duration of a single run.

Parameters:nbrun – Number of runs with different seeds.
Returns:Run result, object of class CpoRunResult.
Raises:CpoNotSupportedException – method not available in this solver agent.
search_next()[source]

Search the next available solution.

Returns:Next solve result, object of class CpoSolveResult.
Raises:CpoNotSupportedException – method not available in this solver agent.
set_explain_failure_tags(ltags)[source]

This method allows to set the list of failure tags to explain in the next solve.

The failure tags are displayed in the log when the parameter LogSearchTags is set to ‘On’. All existing failure tags previously set are cleared prior to set the new ones. Calling this method with an empty list is then equivalent to just clear tags.

Parameters:ltags – List of tag ids to explain
Raises:CpoNotSupportedException – method not available in this solver agent.
solve()[source]

Solve the model

Returns:Model solve result, object of class CpoSolveResult.
Raises:CpoNotSupportedException – method not available in this solver agent.

Start a new search. Solutions are retrieved using method search_next().

Raises:CpoNotSupportedException – method not available in this solver agent.
exception docplex.cp.solver.solver.CpoSolverException(msg)[source]

Bases: docplex.cp.utils.CpoException

Exceptions raised for problems related to solver.

Create a new exception :param msg: Error message

docplex.cp.solver.solver.get_solver_version()[source]

If the solver agent defined in the configuration enables this function, this method returns solver version number.

Returns:Solver version string, or None if not available.
docplex.cp.solver.solver.get_version_info()[source]

If the solver agent defined in the configuration enables this function, this method returns solver version information.

This method creates a CP solver using the default configuration parameters. It then retrieves this information, and close the solver. The returned value is a dictionary with various information, as in the following example:

{
“ProxyVersion” : 5, “SourceDate” : “Sep 12 2017”, “SolverVersion” : “12.8.0.0”, “IntMin” : -9007199254740991, “IntMax” : 9007199254740991, “IntervalMin” : -4503599627370494, “IntervalMax” : 4503599627370494,

}

Returns:Solver information dictionary, or empty dictionary if not available.