Module docplex.cp.model

This module contains principally the class CpoModel that handles all the elements that compose a CPO model:

  • the variables of the domain (integer variables, interval variables, sequence variables and state functions),
  • the constraints of the model,
  • optional objective value(s),
  • optional search phases,
  • optional starting point (available for CPO solver release greater or equal to 12.7.0).

The model expressions, constraints, objective and search phases can be added using method add(). Variables that appear in the expressions are automatically added to the model.

A starting point can be added to the model using method set_starting_point()

The different model expressions and elements are created using services provided by modules:

The solving of the model is handled by an object of class CpoSolver that takes this model as parameter. However, most important solving functions are callable directly from this model to avoid explicit creation of the CpoSolver object:

All these methods are taking a variable number of optional parameters that allow to modify the solving context. The list of arguments is not limited. Each named argument is used to replace the leaf attribute that has the same name in the global context structure initialized in the module docplex.cp.config and its customizations.

The most important of these parameters are:

  • context sets a complete customized context to be used instead of the default one defined in the module docplex.cp.config,

  • params overwrites the solving parameters (object of class CpoParameters) that are defined in the context object,

  • agent forces the selection of a particular solving agent,

  • trace_cpo activates the printing of the model in CPO format before its solve,

  • any CP Optimizer solving parameter, as defined in module docplex.cp.parameters, such as:

    • TimeLimit indicates a limit in seconds in the time spent in the solve, or ConflictRefinerTimeLimit that does the same for conflict refiner,
    • LogVerbosity, with values in [‘Quiet’, ‘Terse’, ‘Normal’, ‘Verbose’],
    • Workers specifies the number of threads assigned to solve the model (default value is the number of cores),
    • SearchType, with value in [‘DepthFirst’, ‘Restart’, ‘MultiPoint’, ‘IterativeDiving’, ‘Neighborhood’, ‘Auto’], to select a particular solving algorithm,
    • RandomSeed changes the seed of the random generator,
    • and so on.

Detailed description

class docplex.cp.model.CpoModel(name=None, sfile=None, version=None)[source]

Bases: object

This class is the Python container of a CPO model.

Constructor

Parameters:
  • name – (Optional) Model name (source file name).
  • sfile – (Optional) Source file.
  • version – (Optional) Format version
add(*expr)[source]

Adds one or several expressions to the model.

This method adds one or more CPO expression to the model. A CPO expression is an object of class CpoExpr or derived, obtained by:

  • calling one of the factory method available in module docplex.cp.expression,
  • calling one of the modeling function available in module docplex.cp.modeler,
  • using an overloaded operator with at least one argument that is a CpoExpr or derived.

The argument expr can be:

  • a constraint,
  • a boolean expression, possibly constant,
  • an objective,
  • a search phase,
  • a variable (but variables that appear in expressions are automatically added to the model),
  • an iterable of expressions to add.

The order of the expressions that are added to the model is preserved when it is submitted for solving.

Parameters:expr – CPO expressions (constraint, boolean, objective, etc) to add to the model, or iterable of expressions to add to the model.
add_blackbox_function(bbf)[source]

Add a new blackbox function descriptor to this model.

Calling this function is mandatory before importing a CPO model that contains references to a blackbox function, if the context attribute context.parser.auto_blackbox is set to False (default).

If the context attribute context.parser.auto_blackbox is set to True, then an empty blackbox function descriptor is automatically generated for every unknown function in the model. As there is no implementation, the model can not be solved.

Parameters:bbf – Blackbox function descriptor, object of class CpoBlackboxFunction
add_constraint(expr)[source]

Adds a constraint to the model.

This method has been added for compatibility with docplex.mp. It is equivalent to method add()

Parameters:expr – Constraint expression to add to the model,
add_kpi(expr, name=None)[source]

Add a Key Performance Indicator to the model.

A Key Performance Indicators (KPI) is an expression whose value is considered as representative of the model solution and its quality.

For example, in a scheduling problem one may wish to minimize the makespan (date at which all tasks are completed), but other values may be of interest, like the average job completion time, or the maximum number of tasks executing in parallel over the horizon. One can identify such expressions in the model by marking them as KPIs.

For CPO solver version lower than 12.9, KPI expressions are limited to:

  • an integer variable,
  • a Python lambda expression that computes the value of the KPI from the solve result given as parameter.

Example of lambda expression used as KPI:

mdl = CpoModel()
a = integer_var(0, 3)
b = integer_var(0, 3)
mdl.add(a < b)
mdl.add_kpi(lambda res: (res[a] + res[b]) / 2, "Average")

For CPO solver version greater or equal to 12.9, KPI expressions can be any model expression. KPI values are automatically displayed in the log, can be queried after the solve or for each solution, and are exported to a CPO file when the model is exported.

If the model is solved in a cloud context, the KPIs are associated to the objective value in the solve details that are sent periodically to the client.

Parameters:
  • expr – Model variable to be used as KPI(s).
  • name (optional) – Name used to publish this KPI. If absent the expression name is used. If the expression has no name, an exception is raised.
add_parameters(**kwargs)[source]

Add parameters to this model.

This method adds parameters to the CpoParameters object currently associated to the model. If there is no such parameters object yet, a new CpoParameters is created.

Parameters:**kwargs (Optional) – List of parameters assignments.
add_search_phase(phase)[source]

Add a search phase to the list of search phases

This method is deprecated since release 2.3. Use set_search_phases() or add() instead.

Parameters:phase – Phase to add to the list
add_solver_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 by the solver engine to notify about the different solving steps.

Parameters:cback – Solver callback, object extending CpoCallback
add_solver_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
check_equivalence(other)[source]

Checks that this model is equivalent to another.

Variables and expressions are compared, but not names that may differ because of automatic naming.

Parameters:other – Other model to compare with.
Raises:CpoException – if models are not equivalent
clone()[source]

Create a copy of this model.

Result copy duplicates only the top-level attributes of the model, the list of expressions, and the parameters. It does not create a deep copy of the expressions, which means that a variable referenced by the expressions of this model is physically the same in the copy.

To completely duplicate the model and all its elements, use the standard function copy.deepcopy(…).

create_empty_solution()[source]

Create an empty model solution that can be filled to be used as a starting point.

New in version 2.9

Returns:New empty model solution, object of class CpoModelSolution
create_solver(**kwargs)[source]

Create a new solver instance attached to this model

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.
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).
Returns:

New solver properly initialized.

equals(other)[source]

Checks if this model is equal to another.

Parameters:other – Other model to compare with.
Returns:True if models are identical, False otherwise.
explain_failure(ltags=None, **kwargs)[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 (Optional) – 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.
  • (others) (Optional) – Any other solve attribute as it can be passed to method solve().
Returns:

Solve result, object of class CpoSolveResult.

Raises:
export_as_cpo(out=None, **kwargs)[source]

Deprecated form of method export_model().

export_model(out=None, **kwargs)[source]

Exports/prints the model in the standard CPO file format.

Except for the argument out, all other arguments are the same than those available in the solve() method., but However, only thoss that impact the CPO file format are useful, in particular, the solving parameters. For example:

mdl.export_model(Workers=1, TimeLimit=100)

Note that calling this method disables automatically all the settings that are set in the default configuration to change the format of the model:

  • context.model.length_for_alias that rename variables if name is too long,
  • context.model.name_all_constraints that force a name for each constraint.

These options are however possible if explicitly given as parameter of this method, as in:

mdl.export_model(length_for_alias=10)
Parameters:
  • out (Optional) – Target output, stream or file name. Default is sys.stdout.
  • 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.
  • add_source_location (Optional) – Add source location into generated text
  • length_for_alias (Optional) – Minimum name length to use shorter alias instead
  • (others) (Optional) – Any leaf attribute with the same name in the solving context
export_parameters_as_ops_file(outfile)[source]

Write parameters of this model to an OPL-style .ops file.

This method writes the non-default-valued parameters to an OPL-style .ops file.

Parameters:outfile – Either a file name or an open file object.
Returns:Nothing
get_all_expressions()[source]

Gets the list of all model expressions

Returns:List of model expressions including there location (if any). Each expression is a tuple (expr, loc) where loc is a tuple (source_file, line), or None if not set.
get_all_variables()[source]

Gets the list of all model variables.

This method goes across all model expressions to identify all variables that are pointed by them. Calling this method on a big model may be slow.

Returns:List of model variables.
get_blackbox_function(name)[source]

Gets a particular blackbox function from its name.

Parameters:name – Name of the blackbox function to search for
Returns:Blackbox function descriptor, None if not found
get_blackbox_functions()[source]

Gets the list of all blackbox functions registered in this model.

Returns:List of all blackbox functions occurring in this model, objects of class CpoBlackboxFunction
get_cpo_string(**kwargs)[source]

Compiles the model in CPO file format into a string.

Note that calling this method disables automatically all the settings that are set in the default configuration to change the format of the model:

  • context.model.length_for_alias that rename variables if name is too long,
  • context.model.name_all_constraints that force a name for each constraint.

These options are however possible if explicitly given as parameter of this method, as in:

mstr = mdl.get_cpo_string(length_for_alias=10)
Parameters:
  • context – Global solving context. If not given, context is the default context that is set in config.py.
  • params – Solving parameters (CpoParameters) that overwrites those in solving context
  • add_source_location – Add source location into generated text
  • length_for_alias – Minimum name length to use shorter alias instead
  • (others) – All other context parameters that can be changed
Returns:

String containing the model.

get_format_version()[source]

Gets the version of the CPO format.

This information is set only when parsing an existing CPO model that contains explicitly a version of the format. It is usually not set when creating a new model. It can be set explicitly using set_format_version() if a specific CPO format is expected.

Returns:String containing the version of the CPO format. None for default.
get_kpis()[source]

Returns the dictionary of this model KPIs.

Returns:Ordered dictionary of KPIs. Key is publish name, value is kpi as a tuple (expr, loc) where loc is a tuple (source_file, line). Keys are sorted in the order the KPIs have been defined.
get_modeling_duration()[source]

Get the time spent in modeling.

The time is computes as difference between the last time an expression has been added and the model object creation time.

Returns:Modeling duration in seconds
get_name()[source]

Gets the name of the model.

If the name is not explicitly defined, the name is the source file name without its extension. If source file name is also undefined, name is None.

Returns:Name of the model, None if undefined.
get_named_expressions_dict()[source]

Gets a dictionary of all named expressions.

This method goes across all model expressions to identify all named expressions. Calling this method on a big model may be slow.

Returns:Dictionary of all named expressions. Key is expression name, value is expression.
get_objective()[source]

Gets the objective expression (maximization or minimization).

Returns:Objective expression, None if satisfaction problem.
get_objective_expression()[source]

Gets the objective expression (maximization or minimization).

Returns:Objective expression, None if satisfaction problem.
get_optimization_expression()[source]

Gets the optimization expression (maximization or minimization).

DEPRECATED. Use get_objective() instead.

Returns:Optimization expression, None if satisfaction problem.
get_parameters()[source]

Get the solving parameters associated to this model.

Returns:Solving parameters, object of class CpoParameters, or None if not defined.
get_source_file()[source]

Gets the name of the source file from which model has been created.

Returns:Python source file name. None if undefined.
get_starting_point()[source]

Get the model starting point

Returns:Model starting point, None if none
get_statistics()[source]

Get statistics on the model

This methods compute statistics on the model.

Returns:Model statistics, object of class class CpoModelStatistics.
import_model(file)[source]

Import a model from a file containing a model expressed in CPO, FZN or LP format.

FZN and LP formats are supported with restrictions to integer variables. The full list of supported FZN predicates is given in the documentation of module fzn_parser.

Source files can also be provided compressed, in zip or gzip format.

Parameters:file – Name of the input file, with extension “.cpo”, “.fzn” or “.lp”, optionally followed by “.gz” or “.zip”
import_model_string(cpostr, **kwargs)[source]

Import in this model a model contained in a string in CPO format.

Parameters:
  • cpostr – Model in CPO format given as a string.
  • **kwargs – (Optional) context changes
is_maximization()[source]

Check if this model represents a maximization problem.

Returns:True if this model represents a maximization problem.
is_minimization()[source]

Check if this model represents a minimization problem.

Returns:True if this model represents a minimization problem.
is_satisfaction()[source]

Check if this model represents a satisfaction problem.

Returns:True if this model represents a satisfaction problem.
maximize(expr)[source]

Add an objective expression to maximize.

DEPRECATED: use add(maximize()) instead.

Parameters:expr – Expression to maximize.
Returns:Maximization expression that has been added
merge_with_parameters(params)[source]

Merge parameters of this model with external parameters.

The model parameters (if any) are overwritten by the given parameters. If parameters are defined at model level, they are cloned, and the parameters given as argument are added to it and then returned. If no parameters are defined, the parameters given as argument are returned as they are.

Returns:Merged solving parameters, object of class CpoParameters.
minimize(expr)[source]

Add an objective expression to minimize.

DEPRECATED: use add(minimize()) instead.

Parameters:expr – Expression to minimize.
Returns:Minimization expression that has been added
print_information(out=None)[source]

Prints model information.

DEPRECATED. Use write_information() instead.

Parameters:out – Output stream or file name, default is sys.stdout.
propagate(cnstr=None, **kwargs)[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 the method solve(). However, variable domains may not be completely defined.

This method creates a new CpoSolver with given arguments, and then call its method propagate(). The class CpoSolver contains the actual implementation of this method, but also some others functions allowing to invoke more specialized functions. An advanced programming may require to explicitly create a CpoSolver instead of calling function at model level. Please refer to this class for more details.

This function is available on Watson Machine Learning and with local CPO solver with release number greater or equal to 12.7.0.

Parameters:
  • cnstr (Optional) – Optional constraint to be added to the model before invoking propagation. If not given, solving context is the default one that is defined in the module
  • 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).
Returns:

Propagation result (object of class CpoSolveResult)

Raises:
read_ops_file(infile)[source]

Load and set parameters of this model from an OPL-style .ops file.

This method loads parameters from an OPL-style .ops file. Any existing parameter settings which are not overridden by the settings from the file will take their default values.

Parameters:infile – Either a file name or an open file object.
Returns:The loaded parameters, now associated with this model.
refine_conflict(**kwargs)[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 as parameters of this method:

  • 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 method creates a new CpoSolver with given arguments, and then call its method refine_conflict(). The class CpoSolver contains the actual implementation of this method, but also some others functions allowing to invoke more specialized functions. An advanced programming may require to explicitly create a CpoSolver instead of calling function at model level. Please refer to this class for more details.

This function is available on Watson Machine Learning and with local CPO solver with release number greater or equal to 12.7.0.

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).
Returns:

List of constraints that cause the conflict (object of class CpoRefineConflictResult)

Raises:
remove(*expr)[source]

Remove one or several expressions from the model.

This method removes one or more CPO expression from the model.

The argument expr can be:

  • any expression previously added to the model using method add()
  • an iterable of such expressions.

Expressions are removed from the top-level expressions of the model. There is no attempst to search for sub-expressions.

The expressions to remove are compared to existing ones using their id. If an expression is not found, it is ignored.

Parameters:expr – CPO expressions (constraint, boolean, objective, etc) to remove from the model, or iterable of expressions to remove from the model.
Returns:Number of expressions actually removed from the model.
remove_all_kpis()[source]

Remove all KPIs from this model.

remove_expressions(lexpr)[source]

Remove a list of expressions from the model.

DEPRECATED: use directly remove() instead, as it supports multiple or lists of expressions to remove.

This method removes from the model all occurrences of the expressions given in the list. It removes only expressions at the top-level, those added in the model using the method add(), it does not remove the expressions that are used as sub-expression of another expression.

This method is more efficient than calling remove() multiple times.

Parameters:lexpr – List of expressions to remove from the model.
Returns:Number of expressions actually removed from the model
remove_kpi(kpi)[source]

Remove a Key Performance Indicator from the model.

Parameters:kpi – KPI expression, or KPI name
remove_solver_callback(cback)[source]

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

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

Remove a solver listener previously added with add_listener().

Parameters:lstnr – Listener to remove.
replace_expression(oexpr, nexpr)[source]

In all model expressions, replace an expression by another.

This method goes across all model expressions tree and replace each occurrence of the expression to replace by the new expression. The comparison of the expression to replace is done by reference (it must be the same object)

Parameters:
  • oexpr – Expression to replace
  • nexpr – Expression to put instead
Returns:

Number of replacements done in the model

run_seeds(nbrun, **kwargs)[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.

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

Parameters:
  • nbrun – Number of runs with different seeds.
  • 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).
Returns:

Run result, object of class CpoRunResult.

Raises:
set_format_version(ver)[source]

Set the expected version of the CPO format.

If the version is None (default), the model is generated with the most recent version. If the solver is not the most recent, the model may be rejected at solve time if a recent feature has been used. If the version is set, available features are checket at modeling time.

Parameters:ver – CPO format version
set_parameters(params=None, **kwargs)[source]

Set the solving parameters associated to this model.

The argument params can be either:

  • An object of the class CpoParameters. The parameters object is cloned and replaces the existing parameters associated to the model, if any.
  • A standard Python dictionary where keys are parameter names, and values parameter values. In this case, a CpoParameters object is created from the dictionary and then associated to the model.
  • None, to release the parameters of this model.

If optional named arguments are added to this method, they are considered as additions to the parameters given in params, that is cloned prior to be modified. If params is None, a new CpoParameters is created.

Parameters:
  • params (Optional) – Solving parameters, object of class CpoParameters, or a dictionary of parameters, or None to remove all parameters.
  • **kwargs (Optional) – Optional changes to the parameters.
Returns:

The new CpoParameters object associated to this model.

set_search_phases(phases)[source]

Set a list of search phases

Parameters:phases – Array of search phases, or single phase
set_starting_point(stpoint)[source]

Set a model starting point.

A starting point specifies a (possibly partial) solution that could be used by CP Optimizer to start the search. This starting point is represented by an object of class CpoModelSolution, with the following restrictions:

  • Only integer and interval variables are taken into account. If present, all other elements are simply ignored.
  • In integer variable, if the domain is not fixed to a single value, only a single range of values is allowed. If the variable domain is sparse, the range domain_min..domain_max is used.

An empty starting point can be created using method create_empty_solution(), and then filled using dedicated methods add_integer_var_solution() and add_interval_var_solution(), or using indexed assignment as in the following example:

mdl = CpoModel()
a = integer_var(0, 3)
b = interval_var(length=(1, 4))
. . .
stp = mdl.create_empty_solution()
stp[a] = 2
stp[b] = (2, 3, 4)
mdl.set_starting_point(stp)

Starting point is available for CPO solver release greater or equal to 12.7.0.

Parameters:stpoint – Starting point, object of class CpoModelSolution
solve(**kwargs)[source]

Solves the model.

This method solves the model using the appropriate CpoSolver created according to default solving context, possibly modified by the parameters of this method.

The class CpoSolver contains the actual implementation of this method, but also some others functions allowing to invoke more specialized functions. An advanced programming may require to explicitly create a CpoSolver instead of calling function at model level. Please refer to this class for more details.

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 calling this method, as for example:

mdl.solve(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).
Returns:

Model solve result (object of class CpoSolveResult).

Raises:

CpoException – (or derived) if error.

Start a new search sequence to retrieve multiple solutions of the model.

This method returns a new CpoSolver object that acts as an iterator of the different solutions of the model. All solutions can be retrieved using a loop like:

lsols = mdl.start_search()
for sol in lsols:
    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.

Note that, to be sure to retrieve all solutions and only once each, recommended parameters are start_search(SearchType=’DepthFirst’, Workers=1)

Optional arguments are the same than those available in the method solve()

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).
Returns:

Object of class CpoSolver allowing to iterate over the different solutions.

Raises:

CpoException – (or derived) if error.

write_information(out=None)[source]

Write various information about the model.

This method calls the method get_statistics() to retrieve information on the model, and then print it with source file name and modeling time.

Parameters:out – Output stream or file name, default is sys.stdout.
class docplex.cp.model.CpoModelStatistics(model=None, json=None)[source]

Bases: object

This class represents model statistics information.

Constructor

Can be created either by giving source model, or json object.

Parameters:
  • model – (Optional) Source model
  • json – (Optional) Json representation of this object
add(other)[source]

Add other model statistics to this one

Parameters:other – Other model statistics, object of class CpoModelStatistics
get_number_of_constraints()[source]

Return the number of constraints.

Returns:Number of constraints.
get_number_of_expressions()[source]

Return the total number of root expressions.

Returns:Number of model root expressions.
get_number_of_variables()[source]

Return the total number of variables.

The total number of variables includes:

  • integer variables
  • interval variables
  • sequence variables
  • state functions
  • float variables
Returns:Total number of variables
to_json()[source]

Build a json object from this statistics

Note: Not all attributes are present, was just for DOcloud usage.

Returns:JSON object
write(out=None, prefix='')[source]

Write the statistics

Parameters:
  • out (Optional) – Target output, as stream or file name. sys.stdout if not given
  • prefix (Optional) – Prefix added at the beginning of each line