docplex.mp.model module

class docplex.mp.model.Model(name=None, context=None, **kwargs)[source]

Bases: object

This is the main class to embed modeling objects.

The Model class acts as a factory to create optimization objects, decision variables, and constraints. It provides various accessors and iterators to the modeling objects. It also manages solving operations and solution management.

The Model class is the context manager and can be used with the Python with statement:

with Model() as mdl:
  # start modeling...

When the with block is finished, the end() method is called automatically, and all resources allocated by the model are destroyed.

When a model is created without a specified context, a default Context is created and initialized as described in docplex.mp.context.Context.read_settings().

Example:

# Creates a model named 'my model' with default context
model = Model('my model')

In the following example, credentials for the solve service are looked up as described in docplex.mp.context.Context.read_settings():

# Creates a model with default ``context``, and override the ``agent``
# to solve on Decision Optimization on Cloud.
model = Model(agent='docloud')

In this example, we create a model to solve with just 2 threads:

context = Context.make_default_context()
context.cplex_parameters.threads = 2
model = Model(context=context)

Alternatively, this can be coded as:

model = Model()
model.context.cplex_parameters.threads = 2
Parameters:
  • name (optional) – The name of the model.
  • context (optional) – The solve context to be used. If no context is passed, a default context is created.
  • agent (optional) – The context.solver.agent is initialized with this string.
  • log_output (optional) – If True, solver logs are output to stdout. If this is a stream, solver logs are output to that stream object.
  • checker (optional) – If None, then checking is disabled everywhere. Turning off checking may improve performance but should be done only with extreme caution.
abs(e)[source]

Builds an expression equal to the absolute value of its argument.

Parameters:e – Accepts any object that can be transformed into an expression: decision variables, expressions, or numbers.
Returns:An expression that can be used in arithmetic operators and constraints.

Note

Building the expression generates auxiliary decision variables, including binary decision variables, and this may change the nature of the problem from a LP to a MIP.

add_constraint(ct, ctname=None)[source]

Adds a new linear constraint to the model.

Parameters:
  • ct – A linear constraint of the form <expr1> <op> <expr2>, where both expr1 and expr2 are linear expressions built from variables in the model, and <op> is a relational operator among <= (less than or equal), == (equal), and >= (greater than or equal).
  • ctname (string) – An optional string used to name the constraint.
Returns:

The newly added constraint.

add_constraints(cts, names=None)[source]

Adds a collection of linear constraints to the model in one operation.

Each constraint in the collection is added to the model, if it was not already added. If present, the names collection is used to set names to the constraints.

Note: The cts argument can be a collection of (constraint, name) tuples such as mdl.add_constraints([(x >=3, ‘ct0’), (x + y == 1, ‘ct1’)]).

Parameters:
  • cts – A collection of linear constraints or an iterator over a collection of linear constraints.
  • names – An optional collection or iterator on strings.
Returns:

A list of those constraints added to the model.

add_indicator(binary_var, linear_ct, active_value=1, name=None)[source]

Adds a new indicator constraint to the model.

An indicator constraint links (one-way) the value of a binary variable to the satisfaction of a linear constraint. If the binary variable equals the active value, then the constraint is satisfied, but otherwise the constraint may or may not be satisfied.

Parameters:
  • binary_var – The binary variable used to control the satisfaction of the linear constraint.
  • linear_ct – A linear constraint (EQ, LE, GE).
  • active_value – 0 or 1. The value used to trigger the satisfaction of the constraint. The default is 1.
  • name (string) – An optional name for the indicator constraint.
Returns:

The newly created indicator constraint.

add_kpi(kpi_arg, publish_name=None)[source]

Adds a Key Performance Indicator to the model.

Key Performance Indicators (KPIs) are objects that can be evaluated after a solve(). Typical use is with decision expressions, the evaluation of which return the expression’s solution value.

KPI values are displayed with the method report_kpis().

Parameters:
  • kpi_arg – Accepted arguments are either an expression, a lambda function with one argument or an instance of a subclass of abstract class KPI.
  • publish_name (string, optional) – The published name of the KPI.

Note

If no publish_name is provided, DOcplex will use the name of the argument. If none, it will use the string representation of the argument.

Example

model.add_kpi(x+y+z, “Total Profit”) adds the expression (x+y+z) as a KPI with the name “Total Profit”.

model.add_kpi(x+y+z) adds the expression (x+y+z) as a KPI with the name “x+y+z”, assumng variables x,y,z have names ‘x’, ‘y’, ‘z’ (resp.)

Returns:The newly added KPI instance.
add_mip_start(mip_start_sol)[source]

Adds a (possibly partial) solution to use as a starting point for a MIP.

This is valid only for models with binary or integer decision variables. The given solution must contain the value for at least one binary or integer variable.

This feature is also known as warm start.

Parameters:mip_start_sol (docplex.mp.solution.SolveSolution) – The solution object to use as a starting point.
add_range(lb, expr, ub, rng_name=None)[source]

Adds a new range constraint to the model.

A range constraint states that a linear expression has to stay within an interval [lb..ub]. Both lb and ub have to be float numbers with lb smaller than ub.

The method creates a new range constraint and adds it to the model.

Parameters:
  • lb (float) – A floating-point number.
  • expr – A linear expression, e.g. X+Y+Z.
  • ub (float) – A floating-point number, which should be greater than lb.
  • rng_name (string) – An optional name for the range constraint.
Returns:

The newly created range constraint.

Return type:

docplex.mp.constr.RangeConstraint

Raises:

An exception if lb is greater than ub.

add_sos(dvars, sos_arg, name=None)[source]

Adds an SOS to the model.

Parameters:
  • sos_arg – The SOS type. Valid values are numerical (1 and 2) or enumerated (SOSType.SOS1 and SOSType.SOS2).
  • dvars – The variables in the special ordered set. This method only accepts ordered sequences of variables or iterators. Unordered collections (dictionaries, sets) are not accepted.
  • name – An optional name.
Returns:

The newly added SOS.

add_sos1(dvars, name=None)[source]

Adds an SOS of type 1 to the model.

Parameters:
  • dvars – The variables in the special ordered set. This method only accepts ordered sequences of variables or iterators. Unordered collections (dictionaries, sets) are not accepted.
  • name – An optional name.
Returns:

The newly added SOS.

add_sos2(dvars, name=None)[source]

Adds an SOS of type 2 to the model.

Parameters:
  • dvars – The variables in the specially ordered set. This method only accepts ordered sequences of variables or iterators. Unordered collections (dictionaries, sets) are not accepted.
  • name – An optional name.
Returns:

The newly added SOS.

binary_var(name=None)[source]

Creates a new binary decision variable and stores it in the model.

Parameters:name (string) – An optional name for the variable.
Returns:A decision variable with type docplex.mp.vartype.BinaryVarType.
Return type:docplex.mp.linear.Var
binary_var_cube(keys1, keys2, keys3, name=None, key_format=None)[source]

Creates a dictionary of binary decision variables, indexed by triplets.

Same as binary_var_matrix(), except that variables are indexed by triplets of the form (k1, k2, k3) with k1 in keys1, k2 in keys2, k3 in keys3.

Returns:A dictionary of docplex.mp.linear.Var objects (with type docplex.mp.vartype.BinaryVarType) indexed by triplets.
binary_var_dict(keys, lb=None, ub=None, name=None, key_format=None)[source]

Creates a dictionary of binary decision variables, indexed by key objects.

Creates a dictionary that allows retrieval of variables from business model objects. Keys can be either a Python collection, an iterator, or a generator.

A key can be any Python object, with the exception of None. Keys are used in the naming of variables.

Note

If keys is empty, this method returns an empty dictionary.

Parameters:
  • keys – Either a sequence of objects, an iterator, or a positive integer. If passed an integer, it is interpreted as the number of variables to create.
  • name (string) – Used to name variables. Accepts either a string or a function. If given a string, the variable name is formed by appending the string to the string representation of the key object (if keys is a sequence) or the index of the variable within the range, if an integer argument is passed.
  • key_format – A format string or None. This format string describes how keys contribute to variable names. The default is “_%s”. For example if name is “x” and each key object is represented by a string like “k1”, “k2”, ... then variables will be named “x_k1”, “x_k2”,...
Returns:

A dictionary of docplex.mp.linear.Var objects with type docplex.mp.vartype.BinaryVarType indexed by the objects in keys.

binary_var_list(keys, lb=None, ub=None, name=<type 'str'>, key_format=None)[source]

Creates a list of binary decision variables and stores them in the model.

Parameters:
  • keys – Either a sequence of objects or an integer.
  • name – Used to name variables. Accepts either a string or a function. If given a string, the variable name is formed by appending the string to the string representation of the key object (if keys is a sequence) or the index of the variable within the range, if an integer argument is passed.
  • key_format – A format string or None. This format string describes how keys contribute to variable names. The default is “_%s”. For example if name is “x” and each key object is represented by a string like “k1”, “k2”, ... then variables will be named “x_k1”, “x_k2”,...

Example

If you want each key string to be surrounded by {}, use a special key_format: “_{%s}”, the %s denotes where the key string will be formatted and appended to name.

Returns:A list of docplex.mp.linear.Var objects with type doc.mp.vartype.BinaryVarType.

Example

mdl.binary_var_list(3, “z”) returns a list of size 3 containing three binary decision variables with names z_0, z_1, z_2.

binary_var_matrix(keys1, keys2, name=None, key_format=None)[source]

Creates a dictionary of binary decision variables, indexed by pairs of key objects.

Creates a dictionary that allows the retrieval of variables from a tuple of two keys, the first one from keys1, the second one from keys2. In short, variables are indexed by the Cartesian product of the two key sets.

A key can be any Python object, with the exception of None. Keys are used in the naming of variables.

Note

If either of keys1 or keys2 is empty, this method returns an empty dictionary.

Parameters:
  • keys1 – Either a sequence of objects, an iterator, or a positive integer. If passed an integer N, it is interpreted as a range from 0 to N-1.
  • keys2 – Same as keys1.
  • name – Used to name variables. Accepts either a string or a function. If given a string, the variable name is formed by appending the string to the string representation of the key object (if keys is a sequence) or the index of the variable within the range, if an integer argument is passed.
  • key_format – A format string or None. This format string describes how keys contribute to variable names. The default is “_%s”. For example if name is “x” and each key object is represented by a string like “k1”, “k2”, ... then variables will be named “x_k1”, “x_k2”,...
Returns:

A dictionary of docplex.mp.linear.Var objects with type docplex.mp.vartype.BinaryVarType indexed by all couples (k1, k2) with k1 in keys1 and k2 in keys2.

binary_vartype

This property returns an instance of docplex.mp.vartype.BinaryVarType.

This type instance is used to build all binary decision variable collections of the model.

clear()[source]

Clears the model of all modeling objects.

clear_kpis()[source]

Clears all KPIs defined in the model.

clear_mip_starts()[source]

Clears all MIP start solutions associated with the model.

clear_sos()[source]

Clears all SOS sets in the model.

clone(new_name=None)[source]

Makes a deep copy of the model, possibly with a new name. Decision variables, constraints, and objective are copied.

Parameters:new_name (string) – The new name to use. If None is provided, returns a “Copy of xxx” where xxx is the original model name.
Returns:A new model.
Return type:docplex.mp.model.Model
continuous_var(lb=None, ub=None, name=None)[source]

Creates a new continuous decision variable and stores it in the model.

Parameters:
  • lb – The lower bound of the variable, or None. The default is 0.
  • ub – The upper bound of the variable, or None, to use the default. The default is model infinity.
  • name (string) – An optional name for the variable.
Returns:

A decision variable with type docplex.mp.vartype.ContinuousVarType.

Return type:

docplex.mp.linear.Var

continuous_var_cube(keys1, keys2, keys3, lb=None, ub=None, name=None, key_format=None)[source]

Creates a dictionary of continuous decision variables, indexed by triplets of key objects.

Same as continuous_var_matrix(), except that variables are indexed by triplets of the form (k1, k2, k3) with k1 in keys1, k2 in keys2, k3 in keys3.

continuous_var_dict(keys, lb=None, ub=None, name=None, key_format=None)[source]

Creates a dictionary of continuous decision variables, indexed by key objects.

Creates a dictionary that allows retrieval of variables from business model objects. Keys can be either a Python collection, an iterator, or a generator.

A key can be any Python object, with the exception of None. Keys are used in the naming of variables.

Note

If keys is empty, this method returns an empty dictionary.

Parameters:
  • keys – Either a sequence of objects, an iterator, or a positive integer. If passed an integer, it is interpreted as the number of variables to create.
  • lb – Lower bounds of the variables. Accepts either a floating-point number, a list of numbers, or a function. Use a number if all variables share the same lower bound. Otherwise either use an explicit list of numbers or use a function if lower bounds vary depending on the key, in which case, the function will be called on each key in keys. None means the default lower bound (0) is used.
  • ub – Upper bounds of the variables. Accepts either a floating-point number, a list of numbers, a function, or None. Use a number if all variables share the same upper bound. Otherwise either use an explicit list of numbers or use a function if upper bounds vary depending on the key, in which case, the function will be called on each key in keys. None means the default upper bound (model infinity) is used.
  • name – Used to name variables. Accepts either a string or a function. If given a string, the variable name is formed by appending the string to the string representation of the key object (if keys is a sequence) or the index of the variable within the range, if an integer argument is passed. If passed a function, this function is called on each key object to generate a name. The default behavior is to call str() on each key object.
  • key_format – A format string or None. This format string describes how keys contribute to variable names. The default is “_%s”. For example if name is “x” and each key object is represented by a string like “k1”, “k2”, ... then variables will be named “x_k1”, “x_k2”,...
Returns:

A dictionary of docplex.mp.linear.Var objects (with type ContinuousVarType) indexed by the objects in keys.

continuous_var_list(keys, lb=None, ub=None, name=<type 'str'>, key_format=None)[source]

Creates a list of continuous decision variables with type docplex.mp.vartype.ContinuousVarType, stores them in the model, and returns the list.

Parameters:
  • keys – Either a sequence of objects or a positive integer. If passed an integer, it is interpreted as the number of variables to create.
  • lb – Lower bounds of the variables. Accepts either a floating-point number, a list of numbers, a function, or None. Use a number if all variables share the same lower bound. Otherwise either use an explicit list of numbers or use a function if lower bounds vary depending on the key, in which case, the function will be called on each key in keys. None means using the default lower bound (0) is used.
  • ub – Upper bounds of the variables. Accepts either a floating-point number, a list of numbers, a function, or None. Use a number if all variables share the same upper bound. Otherwise either use an explicit list of numbers or use a function if upper bounds vary depending on the key, in which case, the function will be called on each key in keys. None means the default upper bound (model infinity) is used.
  • name – Used to name variables. Accepts either a string or a function. If given a string, the variable name is formed by appending the string to the string representation of the key object (if keys is a sequence) or the index of the variable within the range, if an integer argument is passed. If passed a function, this function is called on each key object to generate a name. The default behavior is to call str() on each key object.
  • key_format – A format string or None. This format string describes how keys contribute to variable names. The default is “_%s”. For example if name is “x” and each key object is represented by a string like “k1”, “k2”, ... then variables will be named “x_k1”, “x_k2”,...

Note

When keys is either an empty list or the integer 0, an empty list is returned.

Returns:A list of docplex.mp.linear.Var objects with type docplex.mp.vartype.ContinuousVarType.

See also

infinity()

continuous_var_matrix(keys1, keys2, lb=None, ub=None, name=None, key_format=None)[source]

Creates a dictionary of continuous decision variables, indexed by pairs of key objects.

Creates a dictionary that allows retrieval of variables from a tuple of two keys, the first one from keys1, the second one from keys2. In short, variables are indexed by the Cartesian product of the two key sets.

A key can be any Python object, with the exception of None.

Arguments lb, ub, name, and key_format are interpreted the same as in integer_var_dict().

continuous_vartype

This property returns an instance of docplex.mp.vartype.ContinuousVarType.

This type instance is used to build all continuous variable collections of the model.

dot(terms, coefs)[source]

Synonym for scal_prod().

end()[source]

Terminates a model instance.

Since this method destroys the objects associated with the model, you must not use the model after you call this member function.

eq_constraint(lhs, rhs, name=None)[source]

Creates an equality constraint.

Note

This method returns a constraint object that is not added to the model. To add it to the model, use the add_constraint() method.

Parameters:
  • lhs – An object that can be converted to a linear expression, typically a variable, a member of an expression.
  • rhs – An object that can be converted to a linear expression, typically a variable, a member of an expression.
  • name – An optional string to name the constraint.
Returns:

An instance of docplex.mp.linear.LinearConstraint.

export_as_lp(path=None, basename=None, hide_user_names=False)[source]

Exports a model in LP format.

Parameters:
  • basename – Controls the basename with which the model is printed. Accepts None, a plain string, or a string format. if None, uses the model’s name; if passed a plain string, the string is used in place of the model’s name; if passed a string format (either with %s or {0}, it is used to format the model name to produce the basename of the written file.
  • path – A path to write file, expects a string path or None. can be either a directory, in which case the basename that was computed with the basename argument, is appended to the directory to produce the file. If given a full path, the path is directly used to write the file, and the basename argument is not used. If passed None, the output directory will be tempfile.gettempdir().
  • hide_user_names – A Boolean indicating whether or not to keep user names for variables and constraints. If True, all names are replaced by x1, x2, ... for variables, and c1, c2, ... for constraints.

Examples

Assuming the model’s name is mymodel:

>>> m.export_as_lp()

will write mymodel.lp in gettempdir().

>>> m.export_as_lp(basename="foo")

will write foo.lp in gettempdir().

>>> m.export_as_lp(basename="foo", path="e:/home/docplex")

will write file e:/home/docplex/foo.lp.

>>> m.export_as_lp("e/home/docplex/bar.lp")

will write file e:/home/docplex/bar.lp.

>>> m.export_as_lp(basename="docplex_%s", path="e/home/")

will write file e:/home/docplex/docplex_mymodel.lp.

export_as_lp_string(hide_user_names=False)[source]

Exports the model to a string in LP format.

The output string contains the model in LP format.

Parameters:hide_user_names – An optional Boolean indicating whether or not to keep user names for variables and constraints. If True, all names are replaced by x1, x2, ... for variables, and c1, c2, ... for constraints. Default is to keep user names.
Returns:A string, containing the model exported in LP format.
export_as_sav(path=None, basename=None)[source]

Exports a model in CPLEX SAV format.

Exporting to SAV format requires that CPLEX is installed and available in PYTHONPATH. If the CPLEX DLL cannot be found, an exception is raised.

Parameters:
  • basename – Controls the basename with which the model is printed. Accepts None, a plain string, or a string format. If None, the model’s name is used. If passed a plain string, the string is used in place of the model’s name. If passed a string format (either with %s or {0}), it is used to format the model name to produce the basename of the written file.
  • path – A path to write the file, expects a string path or None. Can be a directory, in which case the basename that was computed with the basename argument, is appended to the directory to produce the file. If given a full path, the path is directly used to write the file, and the basename argument is not used. If passed None, the output directory will be tempfile.gettempdir().

Examples

See the documentation of export_as_lp() for examples of pathname generation. The logic is identical for both methods.

export_to_stream(stream, hide_user_names=False, exchange_format=LP_format)[source]

Export the model to an output stream in LP format.

A stream can be one of:
  • a string, interpreted as a system path,
  • None, interpreted as stdout, or
  • a Python file-type object (e.g. a StringIO() instance).
Parameters:
  • stream – An object defining where the output will be sent.
  • hide_user_names – An optional Boolean indicating whether or not to keep user names for variables and constraints. If True, all names are replaced by x1, x2, ... for variables, and c1, c2, ,... for constraints. Default is to keep user names.
float_precision

This property is used to get or set the float precision of the model.

The float precision is an integer number of digits, used in printing the solution and objective. This number of digits is used for variables and expressions which are not discrete. Discrete variables and objectives are printed with no decimal digits.

ge_constraint(lhs, rhs, name=None)[source]

Creates a “greater than or equal to” linear constraint.

Note

This method returns a constraint object that is not added to the model. To add it to the model, use the add_constraint() method.

Parameters:
  • lhs – An object that can be converted to a linear expression, typically a variable, a member of an expression.
  • rhs – An object that can be converted to a linear expression, typically a variable, a number of an expression.
  • name (string) – An optional string to name the constraint.
Returns:

An instance of docplex.mp.linear.LinearConstraint.

get_constraint_by_name(name)[source]

Searches for a constraint from a name.

Returns the constraint if it finds a constraint with exactly this name, or None if no constraint has this name.

This function will not raise an exception if the named constraint is not found.

Parameters:name (str) – The name of the constraint being searched for.
Returns:A constraint or None.
get_float_precision()[source]

This property is used to get or set the float precision of the model.

The float precision is an integer number of digits, used in printing the solution and objective. This number of digits is used for variables and expressions which are not discrete. Discrete variables and objectives are printed with no decimal digits.

get_parameter_from_id(parameter_cpx_id)[source]

Finds a parameter from a CPLEX id code.

Parameters:parameter_cpx_id – A CPLEX parameter id (positive integer, for example, 2009 is mipgap).
Returns:An instance of docplex.mp.params.parameters.Parameter if found, else None.
get_solve_details()[source]

This property returns detailed information about the last solve, an instance of docplex.mp.solution.SolveDetails.

Note

Detailed information is returned whether or not the solve succeeded.

get_solve_status()[source]

Returns the solve status of the last successful solve.

If the model has been solved successfully, returns the status stored in the model solution. Otherwise returns None`.

Returns:The solve status of the last successful solve, a string, or None.
get_statistics()[source]

Returns statistics on the model.

Returns:A new instance of docplex.mp.model_stats.ModelStatistics.
get_time_limit()[source]
Returns:The time limit for the model.
get_var_by_name(name)[source]

Searches for a variable from a name.

Returns a variable if it finds one with exactly this name, or None.

Parameters:name (str) – The name of the variable being searched for.
Returns:A variable (instance of docplex.mp.linear.Var) or None.
infinity

This property returns the numerical value used as the upper bound for continuous decision variables.

Note

CPLEX usually sets this limit to 1e+20.

static init_numpy()[source]

Static method to customize numpy for DOcplex.

This method makes numpy aware of DOcplex. All numpy arrays with DOcplex objects will be printed by their string representations as returned by str() instead of repr() as with standard numpy behavior.

All customizations can be removed by calling the restore_numpy() method.

Note

This method does nothing if numpy is not present.

See also

restore_numpy()

integer_var(lb=None, ub=None, name=None)[source]

Creates a new integer variable and stores it in the model.

Parameters:
  • lb – The lower bound of the variable, or None. The default is 0.
  • ub – The upper bound of the variable, or None, to use the default. The default is model infinity.
  • name – An optional name for the variable.
Returns:

An instance of the docplex.mp.linear.Var class with type IntegerVarType.

Return type:

docplex.mp.linear.Var

integer_var_cube(keys1, keys2, keys3, lb=None, ub=None, name=<type 'str'>)[source]

Creates a dictionary of integer decision variables, indexed by triplets.

Same as integer_var_matrix(), except that variables are indexed by triplets of the form (k1, k2, k3) with k1 in keys1, k2 in keys2, k3 in keys3.

integer_var_dict(keys, lb=None, ub=None, name=None, key_format=None)[source]

Creates a dictionary of integer decision variables, indexed by key objects.

Creates a dictionary that allows retrieval of variables from business model objects. Keys can be either a Python collection, an iterator, or a generator.

A key can be any Python object, with the exception of None. Keys are used in the naming of variables.

Note

If keys is empty, this method returns an empty dictionary.

Parameters:
  • keys – Either a sequence of objects, an iterator, or a positive integer. If passed an integer, it is interpreted as the number of variables to create.
  • lb – Lower bounds of the variables. Accepts either a floating-point number, a list of numbers, or a function. Use a number if all variables share the same lower bound. Otherwise either use an explicit list of numbers or use a function if lower bounds vary depending on the key, in which case, the function will be called on each key in keys. None means the default lower bound (0) is used.
  • ub – Upper bounds of the variables. Accepts either a floating-point number, a list of numbers, a function, or None. Use a number if all variables share the same upper bound. Otherwise either use an explicit list of numbers or use a function if upper bounds vary depending on the key, in which case, the function will be called on each key in keys. None means the default upper bound (model infinity) is used.
  • name – Used to name variables. Accepts either a string or a function. If given a string, the variable name is formed by appending the string to the string representation of the key object (if keys is a sequence) or the index of the variable within the range, if an integer argument is passed. If passed a function, this function is called on each key object to generate a name. The default behavior is to call str() on each key object.
  • key_format – A format string or None. This format string describes how keys contribute to variable names. The default is “_%s”. For example if name is “x” and each key object is represented by a string like “k1”, “k2”, ... then variables will be named “x_k1”, “x_k2”,...
Returns:

A dictionary of docplex.mp.linear.Var objects (with type IntegerVarType) indexed by the objects in keys.

See also

infinity()

integer_var_list(keys, lb=None, ub=None, name=<type 'str'>, key_format=None)[source]

Creates a list of integer decision variables with type IntegerVarType, stores them in the model, and returns the list.

Parameters:
  • keys – Either a sequence of objects or a positive integer. If passed an integer, it is interpreted as the number of variables to create.
  • lb – Lower bounds of the variables. Accepts either a floating-point number, a list of numbers with the same size as keys, a function (which will be called on each key argument), or None.
  • ub – Upper bounds of the variables. Accepts either a floating-point number, a list of numbers with the same size as keys, a function (which will be called on each key argument), or None.
  • name – Used to name variables. Accepts either a string or a function. If given a string, the variable name is formed by appending the string to the string representation of the key object (if keys is a sequence) or the index of the variable within the range, if an integer argument is passed.
  • key_format – A format string or None. This format string describes how keys contribute to variable names. The default is “_%s”. For example if name is “x” and each key object is represented by a string like “k1”, “k2”, ... then variables will be named “x_k1”, “x_k2”,...

Note

Using None as the lower bound means the default lower bound (0) is used. Using None as the upper bound means the default upper bound (the model’s positive infinity) is used.

Returns:A list of doc.mp.linear.Var objects with type IntegerVarType.
integer_var_matrix(keys1, keys2, lb=None, ub=None, name=None, key_format=None)[source]

Creates a dictionary of integer decision variables, indexed by pairs of key objects.

Creates a dictionary that allows the retrieval of variables from a tuple of two keys, the first one from keys1, the second one from keys2. In short, variables are indexed by the Cartesian product of the two key sets.

A key can be any Python object, with the exception of None.

Arguments lb, ub, name, and key_format are interpreted as in integer_var_dict().

integer_vartype

This property returns an instance of docplex.mp.vartype.IntegerVarType.

This type instance is used to build all integer variable collections of the model.

is_maximize()[source]

Checks whether the model is a maximization model.

Note

This returns True even if the expression to maximize is a constant. To check whether the model has a non-constant objective, use is_optimized().

Returns:True if the model is a maximization model.
Return type:Boolean
is_minimize()[source]

Checks whether the model is a minimization model.

Note

This returns True even if the expression to minimize is a constant. To check whether the model has a non-constant objective, use is_optimized().

Returns:True if the model is a minimization model.
Return type:Boolean
is_optimized()[source]

Checks whether the model has a non-constant objective expression.

A model with a constant objective will only search for a feasible solution when solved. This happens either if no objective has been assigned to the model, or if the objective has been removed with remove_objective().

Returns:True, if the model has a non-constant objective expression.
Return type:Boolean
iter_binary_vars()[source]

Iterates over all binary decision variables in the model.

Returns the variables in the order they were added to the model.

Returns:An iterator object.
iter_constraints()[source]

Iterates over all constraints (linear, ranges, indicators).

Returns:An iterator object over all constraints in the model.
iter_continuous_vars()[source]

Iterates over all continuous decision variables in the model.

Returns the variables in the order they were added to the model.

Returns:An iterator object.
iter_indicator_constraints()[source]

Returns an iterator on indicator constraints in the model.

Returns:An iterator object.
iter_integer_vars()[source]

Iterates over all integer decision variables in the model.

Returns the variables in the order they were added to the model.

Returns:An iterator object.
iter_kpis()[source]

Returns an iterator over all KPIs in the model.

Returns:An iterator object.
iter_linear_constraints()[source]

Returns an iterator on the linear constraints of the model. This includes binary linear constraints and ranges but not indicators.

Returns:An iterator object.
iter_pwl_constraints()[source]

Iterates over all PWL constraints in the model.

Returns:An iterator object.
iter_pwl_functions()[source]

Iterates over all the piecewise linear functions in the model.

Returns the PWL functions in the order they were added to the model.

Returns:An iterator object.
iter_quadratic_constraints()[source]

Returns an iterator on the quadratic constraints of the model.

Returns:An iterator object.
iter_semicontinuous_vars()[source]

Iterates over all semi-continuous decision variables in the model.

Returns the variables in the order they were added to the model.

Returns:An iterator object.
iter_semiinteger_vars()[source]

Iterates over all semi-integer decision variables in the model.

Returns the variables in the order they were added to the model.

Returns:An iterator object.
iter_sos()[source]

Iterates over all SOS sets in the model.

Returns:An iterator object.
iter_sos1()[source]

Iterates over all SOS1 sets in the model.

Returns:An iterator object.
iter_sos2()[source]

Iterates over all SOS2 sets in the model.

Returns:An iterator object.
iter_variables()[source]

Iterates over all the variables in the model.

Returns the variables in the order they were added to the model, regardless of their type.

Returns:An iterator object.
kpi_by_name(name, try_match=True, match_case=False, do_raise=True)[source]

Fetches a KPI from a string.

This method fetches a KPI from a string, using either exact naming or trying to match a substring of the KPI name.

Parameters:
  • name (string) – The string to be matched.
  • try_match (Boolean) – If True, returns KPI whose name is not equal to the argument, but contains it. Default is True.
  • match_case – If True, looks for a case-exact match, else ignores case. Default is False.
  • do_raise – If True, raise an exception when no KPI is found.

Example

If the KPI name is “Total CO2 Cost” then fetching with argument co2 and match_case to False will succeed. If match_case is True, then no KPI will be returned.

Returns:The KPI expression if found. If the search fails, either raises an exception or returns a dummy constant expression with 0.
kpi_value_by_name(name, try_match=True, match_case=False, do_raise=True)[source]

Returns a KPI value from a KPI name.

This method fetches a KPI value from a string, using either exact naming or trying to match a substring of the KPI name.

Parameters:
  • name (str) – The string to be matched.
  • try_match (Bool) – If True, returns KPI whose name is not equal to the argument, but contains it. Default is True.
  • match_case – If True, looks for a case-exact match, else ignores case. Default is False.
  • do_raise – If True, raise an exception when no KPI is found.

Example

If the KPI name is “Total CO2 Cost” then fetching with argument co2 and match_case to False will succeed. If match_case is True, then no KPI will be returned.

Note

Expression KPIs require a valid solution to be computed. Make sure that the model contains a valid solution before computing an expression-based KPI, otherwise an exception will be raised. Functional KPIs do not require a valid solution.

Returns:The KPI value.
Return type:float
le_constraint(lhs, rhs, name=None)[source]

Creates a “less than or equal to” linear constraint.

Note

This method returns a constraint object, that is not added to the model. To add it to the model, use the add_constraint() method.

Parameters:
  • lhs – An object that can be converted to a linear expression, typically a variable, a member of an expression.
  • rhs – An object that can be converted to a linear expression, typically a variable, a member of an expression.
  • name (string) – An optional string to name the constraint.
Returns:

An instance of docplex.mp.linear.LinearConstraint.

linear_constraint(lhs, rhs, ctsense, name=None)[source]

Creates a linear constraint.

Note

This method returns a constraint object that is not added to the model. To add it to the model, use the add_constraint() method.

Parameters:
  • lhs – An object that can be converted to a linear expression, typically a variable, a member of an expression.
  • rhs – An object that can be converted to a linear expression, typically a variable, a number of an expression.
  • ctsense – A constraint sense; accepts either a value of type ComparisonType or a string (e.g ‘le’, ‘eq’, ‘ge’).
  • name (string) – An optional string to name the constraint.
Returns:

An instance of docplex.mp.linear.LinearConstraint.

linear_expr(arg=None, name=None)[source]

Returns a new empty linear expression.

Parameters:
  • arg – an optional argument to convert to a linear expression. Detailt is None, in which case, an empty expression is returned.
  • name – An optional string to name the expression.
Returns:

An instance of docplex.mp.linear.LinearExpr.

max(*args)[source]

Builds an expression equal to the maximum value of its arguments.

This method accepts a variable number of arguments.

Parameters:args – A variable list of arguments, each of which is either an expression, a variable, or a container.

If passed a container or an iterator, this container or iterator must be the unique argument.

If passed one dictionary, returns the maximum of the dictionary values.

If no arguments are provided, returns negative infinity (see infinity()).

Example

model.max() -> returns -model.infinity.

model.max(e) -> returns e.

model.max(e1, e2, e3) -> returns a new expression equal to the maximum of the values of e1, e2, e3.

model.max([x1,x2,x3]) where x1, x2 .. are variables or expressions -> returns the maximum of these expressions.

model.max([]) -> returns -model.infinity.

Note

Building the expression generates auxiliary variables, including binary decision variables, and this may change the nature of the problem from a LP to a MIP.

maximize(expr)[source]

Sets an expression as the expression to be maximized.

The argument is converted to a linear expression. Accepted types are variables (instances of docplex.mp.linear.Var class), linear expressions (instances of docplex.mp.linear.LinearExpr), or numbers.

Parameters:expr – A linear expression or a variable.
min(*args)[source]

Builds an expression equal to the minimum value of its arguments.

This method accepts a variable number of arguments.

If no arguments are provided, returns positive infinity (see infinity()).

Parameters:args – A variable list of arguments, each of which is either an expression, a variable, or a container.

If passed a container or an iterator, this container or iterator must be the unique argument.

If passed one dictionary, returns the minimum of the dictionary values.

Returns:An expression that can be used in arithmetic operators and constraints.

Example

model.min() -> returns model.infinity.

model.min(e) -> returns e.

model.min(e1, e2, e3) -> returns a new expression equal to the minimum of the values of e1, e2, e3.

model.min([x1,x2,x3]) where x1, x2 .. are variables or expressions -> returns the minimum of these expressions.

model.min([]) -> returns model.infinity.

Note

Building the expression generates auxiliary variables, including binary decision variables, and this may change the nature of the problem from a LP to a MIP.

minimize(expr)[source]

Sets an expression as the expression to be minimized.

The argument is converted to a linear expression. Accepted types are variables (instances of docplex.mp.linear.Var class), linear expressions (instances of docplex.mp.linear.LinearExpr), or numbers.

Parameters:expr – A linear expression or a variable.
mip_starts

This property returns the list of MIP start solutions (a list of instances of docplex.mp.solution.SolveSolution) attached to the model if MIP starts have been defined, possibly an empty list.

number_of_binary_variables

This property returns the total number of binary decision variables added to the model.

number_of_constraints

This property returns the total number of constraints that were added to the model.

The number includes linear constraints, range constraints, and indicator constraints.

number_of_continuous_variables

This property returns the total number of continuous decision variables added to the model.

number_of_indicator_constraints

This property returns the number of indicator constraints in the model.

number_of_integer_variables

This property returns the total number of integer decision variables added to the model.

number_of_linear_constraints

This property returns the total number of linear constraints added to the model.

This counts binary linear constraints (<=, >=, or ==) and range constraints.

number_of_pwl_constraints

This property returns the total number of PWL constraints in the model.

number_of_quadratic_constraints

This property returns the number of quadratic constraints in the model.

number_of_range_constraints

This property returns the total number of range constraints added to the model.

number_of_semicontinuous_variables

This property returns the total number of semi-continuous decision variables added to the model.

number_of_semiinteger_variables

This property returns the total number of semi-integer decision variables added to the model.

number_of_sos

This property returns the total number of SOS sets in the model.

number_of_sos1

This property returns the total number of SOS1 sets in the model.

number_of_sos2

This property returns the total number of SOS2 sets in the model.

number_of_variables

This property returns the total number of decision variables, all types combined.

objective_coef(dvar)[source]

Returns the objective coefficient of a variable.

The objective coefficient is the coefficient of the given variable in the model’s objective expression. If the variable is not explicitly mentioned in the objective, it returns 0.

Parameters:dvar – The decision variable for which to compute the objective coefficient.
Returns:The objective coefficient of the variable.
Return type:float
objective_expr

This property returns the current expression used as the model objective.

objective_sense

This property returns the direction of the optimization as an instance of docplex.mp.basic.ObjectiveSense, either Minimize or Maximize.

objective_value

This property returns the value of the objective expression in the solution of the last solve.

Raises an exception if the model has not been solved successfully.

parameters

This property returns the root parameter group of the model.

The root parameter group models the parameter hirerachy. It is the way to access any CPLEX parameter and get or set its value.

Examples

model.parameters.mip.tolerances.mipgap

Returns the parameter itself, an instance of the Parameter class.

To get the value of the parameter, use the get() method, as in:

model.parameters.mip.tolerances.mipgap.get()
>>> 0.0001

To change the value of the parameter, use a standard Python assignment:

 model.parameters.mip.tolerances.mipgap = 0.05
 model.parameters.mip.tolerances.mipgap.get()
>>> 0.05

Assignment is equivalent to the set() method:

model.parameters.mip.tolerances.mipgap.set(0.02)
model.parameters.mip.tolerances.mipgap.get()
>>> 0.02
Returns:The root parameter group, an instance of the ParameterGroup class.
piecewise(preslope, breaksxy, postslope, name=None)[source]

Adds a piecewise linear function (PWL) to the model, using breakpoints to specify the function.

Parameters:
  • preslope – Before the first segment of the PWL function there is a half-line; its slope is specified by this argument.
  • breaksxy – A list (x[i], y[i]) of coordinate pairs defining segments of the PWL function.
  • postslope – After the last segment of the the PWL function there is a half-line; its slope is specified by this argument.
  • name – An optional name.

Example:

# Creates a piecewise linear function whose value if '0' if the `x_value` is `0`, with a slope
# of -1 for negative values and +1 for positive value
model = Model('my model')
model.piecewise(-1, [(0, 0)], 1)

# Note that a PWL function may be discontinuous. Here is an example of a step function:
model.piecewise(0, [(0, 0), (0, 1)], 0)
Returns:The newly added piecewise linear function.
piecewise_as_slopes(slopebreaksx, lastslope, anchor=(0, 0), name=None)[source]

Adds a piecewise linear function (PWL) to the model, using a list of slopes and x-coordinates.

Parameters:
  • slopebreaksx – A list of tuple pairs (slope[i], breakx[i]) of slopes and x-coordinates defining the slope of the piecewise function between the previous breakpoint (or minus infinity if there is none) and the breakpoint with x-coordinate breakx[i]. For representing a discontinuity, two consecutive pairs with the same value for breakx[i] are used. The value of slope[i] in the second pair is the discontinuity gap.
  • lastslope – The slope after the last specified breakpoint.
  • anchor – The coordinates of the ‘anchor point’. The purpose of the anchor point is to ground the piecewise linear function specified by the list of slopes and breakpoints.
  • name – An optional name.

Example:

# Creates a piecewise linear function whose value if '0' if the `x_value` is `0`, with a slope
# of -1 for negative values and +1 for positive value
model = Model('my model')
model.piecewise_as_slopes([(-1, 0)], 1, (0, 0))

# Here is the definition of a step function to illustrate the case of a discontinuous PWL function:
model.piecewise_as_slopes([(0, 0), (0, 1)], 0, (0, 0))
Returns:The newly added piecewise linear function.
print_information()[source]

Prints general informational statistics on the model.

Prints the number of variables and their breakdown by type. Prints the number of constraints and their breakdown by type.

print_solution(print_zeros=False, objective_fmt='objective: {0:.{prec}f}', var_value_fmt=None, **kwargs)[source]

Prints the values of the model variables after a solve.

Only valid after a successful solve. If the model has not been solved successfully, an exception is raised.

Parameters:
  • print_zeros (Boolean) – If False, only non-zero values are printed. Default is False.
  • objective_fmt – A format string in format syntax. The default printout is objective: xx where xx is formatted as a float with prec digits. The value of prec is computed automatically by DOcplex, either 0 if the objective expression is discrete or the model’s float precision.
  • var_value_fmt – A format string to format the variable name and value. Again, the default uses the automatically computed precision.
progress_listeners

This property returns the list of progress listeners.

quad_expr(name=None)[source]

Returns a new empty quadratic expression.

Parameters:name – An optional string to name the expression.
Returns:An instance of docplex.mp.quad.QuadExpr.
range_constraint(lb, expr, ub, rng_name=None)[source]

Creates a new range constraint but does not add it to the model.

A range constraint states that a linear expression has to stay within an interval [lb..ub]. Both lb and ub have to be floating-point numbers with lb smaller than ub.

The method creates a new range constraint but does not add it to the model.

Parameters:
  • lb – A floating-point number.
  • expr – A linear expression, e.g. X+Y+Z.
  • ub – A floating-point number, which should be greater than lb.
  • rng_name – An optional name for the range constraint.
Returns:

The newly created range constraint.

Raises:

An exception if lb is greater than ub.

remove_constraint(ct_arg)[source]

Removes a constraint from the model.

Parameters:ct_arg – The constraint to remove. Accepts either a constraint object or a string. If passed a string, looks for a constraint with that name.
remove_kpi(kpi_arg)[source]

Removes a Key Performance Indicator from the model.

Parameters:kpi_arg – A KPI instance that was previously added to the model. Accepts either a KPI object or a string. If passed a string, looks for a KPI with that name.
remove_mip_start(mipstart)[source]

Removes one MIP start solution from the list of MIP starts associated with the model.

Parameters:mipstart – A MIP start solution, an instance of docplex.mp.solution.SolveSolution.
remove_objective()[source]

Clears the current objective.

This is equivalent to setting “minimize 0”. Any subsequent solve will look only for a feasible solution. You can detect this state by calling has_objective() on the model.

report()[source]

Prints the value of the objective and the KPIs. Only valid after a successful solve, otherwise states that the model is not solved.

report_kpis(selected_kpis=None, kpi_header_format='* KPI: {1:<{0}} = ')[source]

Prints the values of the KPIs. Only valid after a successful solve.

static restore_numpy()[source]

Static method to restore numpy to its default state.

This method is a companion method to init_numpy(). It restores numpy to its original state, undoing all customizations that were done for DOcplex.

Note

This method does nothing if numpy is not present.

See also

init_numpy()

scal_prod(terms, coefs)[source]

Creates a linear expression equal to the scalar product of a list of decision variables and a sequence of coefficients.

This method accepts different types of input for both arguments. The variable sequence can be either a list or an iterator of objects that can be converted to linear expressions, that is, variables, expressions, or numbers. The most usual case is variables. The coefficients can be either a list of numbers, an iterator over numbers, or a number. In this last case the scalar product reduces to a sum times this coefficient.

Parameters:
  • terms – A list or an iterator on variables or expressions.
  • coefs – A list or an iterator on numbers, or a number.

Note

If either list or iterator is empty, this method returns zero.

Returns:A linear expression or 0.
semicontinuous_var(lb, ub=None, name=None)[source]

Creates a new semi-continuous decision variable and stores it in the model.

Parameters:
  • lb – The lower bound of the variable (which must be strictly positive).
  • ub – The upper bound of the variable, or None, to use the default. The default is model infinity.
  • name (string) – An optional name for the variable.
Returns:

A decision variable with type docplex.mp.vartype.SemiContinuousVarType.

Return type:

docplex.mp.linear.Var

semicontinuous_var_list(keys, lb, ub=None, name=<type 'str'>, key_format=None)[source]

Creates a list of semi-continuous decision variables with type docplex.mp.vartype.SemiContinuousVarType, stores them in the model, and returns the list.

Parameters:
  • keys – Either a sequence of objects or a positive integer. If passed an integer, it is interpreted as the number of variables to create.
  • lb – Lower bounds of the variables. Accepts either a floating-point number, a list of numbers, or a function. Use a number if all variables share the same lower bound. Otherwise either use an explicit list of numbers or use a function if lower bounds vary depending on the key, in which case, the function will be called on each key in keys. Note that the lower bound of a semi-continuous variable must be strictly positive.
  • ub – Upper bounds of the variables. Accepts either a floating-point number, a list of numbers, a function, or None. Use a number if all variables share the same upper bound. Otherwise either use an explicit list of numbers or use a function if upper bounds vary depending on the key, in which case, the function will be called on each key in keys. None means the default upper bound (model infinity) is used.
  • name – Used to name variables. Accepts either a string or a function. If given a string, the variable name is formed by appending the string to the string representation of the key object (if keys is a sequence) or the index of the variable within the range, if an integer argument is passed. If passed a function, this function is called on each key object to generate a name. The default behavior is to call str() on each key object.
  • key_format – A format string or None. This format string describes how keys contribute to variable names. The default is “_%s”. For example if name is “x” and each key object is represented by a string like “k1”, “k2”, ... then variables will be named “x_k1”, “x_k2”,...

Note

When keys is either an empty list or the integer 0, an empty list is returned.

Returns:A list of docplex.mp.linear.Var objects with type docplex.mp.vartype.SemiContinuousVarType.

See also

infinity()

semicontinuous_vartype

This property returns an instance of docplex.mp.vartype.SemiContinuousVarType.

This type instance is used to build all semi-continuous variable collections of the model.

semiinteger_var(lb, ub=None, name=None)[source]

Creates a new semi-integer decision variable and stores it in the model.

Parameters:
  • lb – The lower bound of the variable (which must be strictly positive).
  • ub – The upper bound of the variable, or None, to use the default. The default is model infinity.
  • name (string) – An optional name for the variable.
Returns:

A decision variable with type docplex.mp.vartype.SemiIntegerVarType.

Return type:

docplex.mp.linear.Var

semiinteger_var_list(keys, lb, ub=None, name=<type 'str'>, key_format=None)[source]

Creates a list of semi-integer decision variables with type docplex.mp.vartype.SemiIntegerVarType, stores them in the model, and returns the list.

Parameters:
  • keys – Either a sequence of objects or a positive integer. If passed an integer, it is interpreted as the number of variables to create.
  • lb – Lower bounds of the variables. Accepts either a floating-point number, a list of numbers, or a function. Use a number if all variables share the same lower bound. Otherwise either use an explicit list of numbers or use a function if lower bounds vary depending on the key, in which case, the function will be called on each key in keys. Note that the lower bound of a semi-integer variable must be strictly positive.
  • ub – Upper bounds of the variables. Accepts either a floating-point number, a list of numbers, a function, or None. Use a number if all variables share the same upper bound. Otherwise either use an explicit list of numbers or use a function if upper bounds vary depending on the key, in which case, the function will be called on each key in keys. None means the default upper bound (model infinity) is used.
  • name – Used to name variables. Accepts either a string or a function. If given a string, the variable name is formed by appending the string to the string representation of the key object (if keys is a sequence) or the index of the variable within the range, if an integer argument is passed. If passed a function, this function is called on each key object to generate a name. The default behavior is to call str() on each key object.
  • key_format – A format string or None. This format string describes how keys contribute to variable names. The default is “_%s”. For example if name is “x” and each key object is represented by a string like “k1”, “k2”, ... then variables will be named “x_k1”, “x_k2”,...

Note

When keys is either an empty list or the integer 0, an empty list is returned.

Returns:A list of docplex.mp.linear.Var objects with type docplex.mp.vartype.SemiIntegerVarType.

See also

infinity()

semiinteger_vartype

This property returns an instance of docplex.mp.vartype.SemiIntegerType.

This type instance is used to build all semi-integer variable collections of the model.

set_objective(sense, expr)[source]

Sets a new objective.

Parameters:
  • sense – Either an instance of docplex.mp.basic.ObjectiveSense (Minimize or Maximize), or a string: “min” or “max”.
  • expr – Is converted to an expression. Accepted types are variables, linear expressions, quadratic expressions or numbers.

Note

When using a number, the search will not optimize but only look for a feasible solution.

set_time_limit(time_limit)[source]

Set a time limit for solve operations.

Parameters:time_limit – The new time limit; must be a positive number.
solution

This property returns the current solution of the model or None if the model has not yet been solved or if the last solve has failed.

solve(**kwargs)[source]

Starts a solve operation on the model.

If CPLEX is available, the solve operation will be performed using the native CPLEX. If CPLEX is not available, the solve operation will be started on DOcplexcloud. The DOcplexcloud connection parameters are looked up in the following order:

  • if kwargs contains valid url and key values, they are used.
  • if kwargs contains a context and that context contains
    valid solver.docloud.url and solver.docloud.key values, those values are used. Other attributes of solver.docloud can also be used. See docplex.mp.context.Context
  • finally, the model’s attribute context is used. This context
    is set at model creation time.

If CPLEX is not available and the model has no valid credentials, an error is raised, as there is no way to perform the solve.

Note that if url and key parameters are present and the values of the parameters are not in the ignored url or key list, the solve operation will be started on DOcplexcloud even if CPLEX is available.

Example:

# forces the solve on DOcplexcloud with the specified url and keys
model.solve(url='https://foo.com', key='bar')

Example:

# set some DOcplexcloud credentials, but depend on another
# method to decide if solve is local or not
ctx.solver.docloud.url = 'https://foo.com'
ctx.solver.docloud.key = 'bar'
agent = 'local' if method_that_decides_if_solve_is_local() or 'docloud'
model.solve(context=ctx, agent=agent)
Parameters:
  • context (optional) – An instance of context to be used in instead of the context this model was built with.
  • cplex_parameters (optional) – A set of CPLEX parameters to use instead of the parameters defined as context.cplex_parameters.
  • agent (optional) –

    Changes the context.solver.agent parameter. Supported agents include:

    • docloud: forces the solve operation to use DOcplexcloud
    • local: forces the solve operation to use native CPLEX
  • url (optional) – Overwrites the URL of the DOcplexcloud service defined by context.solver.docloud.url.
  • key (optional) – Overwrites the authentication key of the DOcplexcloud service defined by context.solver.docloud.key.
  • log_output (optional) – if True, solver logs are output to stdout. If this is a stream, solver logs are output to that stream object. Overwrites the context.solver.log_output parameter.
  • proxies (optional) – a dict with the proxies mapping.
Returns:

A docplex.mp.solution.SolveSolution object if the solve operation succeeded. None if the solve operation failed.

solve_details

This property returns detailed information about the last solve, an instance of docplex.mp.solution.SolveDetails.

Note

Detailed information is returned whether or not the solve succeeded.

solve_lexicographic(goals, senses=<ObjectiveSense.Minimize: 1>, tolerances=None, **kwargs)[source]

Performs a lexicographic solve from an ordered collection of goals.

Parameters:
  • goals – An ordered collection of linear expressions.
  • senses – Either an ordered collection of senses, one sense, or None. The default is None, in which case the solve uses a Minimize sense. Each sense can be either a sense object, that is either ObjectiveSense.Minimize or Maximize, or a string “min” or “max”.
  • tolerances – A tuple of two numbers or a sequence of such tuples. The first number is

used as absolute tolerance, the second number is a relative tolerance. Accepts None, in which case, default tolerances are used (absolute=1e-6, relative=1e-4).

Note

tolerances are used at each step to constraint the previous objective value to be be ‘no worse’ than the value found in the last pass. For example, if relative tolerance is 2% and pass #1 has found an objective of 100, then pass #2 will comstraint the first goal to be no greater than 102 if minimizing, or no less than 98, if maximizing.

Returns:If successful, returns a tuple with all pass solutions, reversed else None. The current solution of the model is the first solution in the tuple.
statistics

Returns statistics on the model.

Returns:A new instance of docplex.mp.model_stats.ModelStatistics.
sum(args)[source]

Creates a linear expression summing over a sequence.

Note

This method returns 0 if the argument is an empty list or iterator.

Parameters:args – A list of objects that can be converted to linear expressions, that is, linear expressions, decision variables, or numbers.
Returns:A linear expression or 0.
sumsq(args)[source]

Creates a quadratic expression summing squares over a sequence.

Each element of the list is squared and added to the result. Quadratic expressions are not accepted, as they cannot be squared.

Note

This method returns 0 if the argument is an empty list or iterator.

Parameters:args – A list of objects that can be converted to linear expressions, that is, linear expressions, decision variables, or numbers. Each item is squared and added to the result.
Returns:A quadratic expression (possibly constant).
var(vartype, lb=None, ub=None, name=None)[source]

Creates a decision variable and stores it in the model.

Parameters:
  • vartype – The type of the decision variable; This field expects a concrete instance of the abstract class docplex.mp.vartype.VarType.
  • lb – The lower bound of the variable; either a number or None, to use the default. The default lower bound for all three variable types is 0.
  • ub – The upper bound of the variable domain; expects either a number or None to use the type’s default. The default upper bound for Binary is 1, otherwise positive infinity.
  • name – An optional string to name the variable.
Returns:

The newly created decision variable.

Return type:

docplex.mp.linear.Var

Note

The model holds local instances of BinaryVarType, IntegerVarType, ContinuousVarType which are accessible by properties (resp. binary_vartype, integer_vartype, continuous_vartype).