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 a 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. If the model is not created with the with keyword, then the end() method should be called to free all CPLEX resources.

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 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.
  • 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 off, then checking is disabled everywhere. Turning off checking may improve performance but should be done only with extreme caution. Possible values for the checker keyword argument are:

    • default (or std, or on): detects modeling errors, but does not check numerical values for infinities or NaNs. This is the default value.
    • numeric: checks that numerical arguments are valid numbers, neither NaN nor math.infinity. This option should be used when data are not trusted.
    • full: performs all possible checks (This is the union of std and numeric checks).
    • off: no typechecking is performed. This options must be used when the model has been thoroughly tested and numerical data are trusted.
  • cts_by_name (optional) – a flag which control whether the constraint name dictionary is enabled. Default is False.
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_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.

Note

This method does the same as docplex.mp.model.Model.add_constraint() except that it has no return value.

See also

add_constraint()

add_constraints(cts, names=None)[source]

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

Each constraint from the cts iterable is added to the model. If present, the names iterable is used to set names to the constraints.

Example

# list >>> m.add_constraints([x >= 1, y<= 3], [“c1”, “c2”]) # comprehension >>> m.add_constraints((xs[i] >= i for i in range(N)))

Parameters:
  • cts – An iterable of linear constraints; can be a list, a set or a comprehensions. Any Python object, which can be iterated on and yield consttraint objects.
  • names – An optional iterable on strings. ANy Python object which can be iterated on and yield strings. The default value is None, meaning no names are set.
Returns:

A list of the newly added constraints.

Note

This method handles only linear constraints (including range constraints). To add

multiple quadratic constraints, see add_quadratic_constraints()

add_constraints_(cts, names=None)[source]

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

Same as docplex.model.Model.add_constraints() except that is does not return anything.

add_equivalence(binary_var, linear_ct, true_value=1, name=None)[source]

Adds a new equivalence constraint to the model.

An equivalence constraints links two-way the value of a binary variable to the satisfaction of a discrete linear constraint. If the binary variable equals the true value, then the constraint is satisfied, conversely if the constraint is satisfied, the binary variable is equal to the true value.

Parameters:
  • binary_var – The binary variable used to control the satisfaction of the linear constraint.
  • linear_ct – A linear constraint (EQ, LE, GE).
  • true_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 equivalence constraint.
Returns:

The newly created equivalence constraint.

add_equivalence_constraints(eqcts)[source]

Adds a batch of equivalence constraints to the model

Parameters:eqcts – an iterable returning equivalence constraints.
add_equivalence_constraints_(eqcts)

Adds a batch of equivalence constraints to the model

Parameters:eqcts – an iterable returning equivalence constraints.
add_equivalences(binary_vars, cts, true_values=1, names=None)[source]

Adds a batch of equivalence constraints to the model.

This method adds a batch of equivalence constraints to the model.

Parameters:
  • binary_vars – a sequence of binary variables.
  • cts – a sequence of discrete linear constraints
  • true_values – the true values to use. Accepts either 1, 0 or a sequence of {0, 1} values.
  • names – an optional sequence of names

All sequences must have the same length.

Returns:a list of equivalence constraints.
add_if_then(if_ct, then_ct, negate=False)[source]

Creates a new if-then constraint and adds it to the model

Parameters:
  • if_ct – a linear constraint, the satisfaction of which governs the satisfaction of the then_ct
  • then_ct – a linear constraint, which becomes satisfied as soon as if_ct is satisfied (or when it is not, depending on the negate flag).
  • negate – an optional boolean flag (default is False). If True, then_ct is satisfied when if_ct is not satisfied.
Returns:

an instance of IfThenConstraint.

Note

This constraint relies on the status of the if_ct constraint, so this constraint must be discrete, otherwise an exception will be raised. On the opposite, the then_ct constraint may be non-discrete.

Also note that this construct relies on the status variable of the if_ct, so one extra binary variable is generated.

New in 2.16: when if_ct is of the form bvar == 1 or bvar ==0, where bvar is a binary variable,
, no extra variable is generated, and a plain indicator constraint is generated.

An alternative syntax is to use the >> operator on linear constraints:

>>> m.add(c1 >> c2)

is exactly equivalent to:

>>> m.add_if_then(c1, c2)
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_indicator_constraints(indcts)[source]

Adds a batch of indicator constraints to the model

Parameters:indcts – an iterable returning indicator constraints.
add_indicator_constraints_(indcts)

Adds a batch of indicator constraints to the model

Parameters:indcts – an iterable returning indicator constraints.
add_indicators(binary_vars, cts, true_values=1, names=None)[source]

Adds a batch of indicator constraints to the model.

This method adds a batch of indicator constraints to the model.

Parameters:
  • binary_vars – a sequence of binary variables.
  • cts – a sequence of discrete linear constraints
  • true_values – the true values to use. Accepts either 1, 0 or a sequence of {0, 1} values.
  • names – an optional sequence of names

All sequences must have the same length.

Returns:a list of indicator constraints.
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 two arguments (model + solution) 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 try to access a ‘name’ attribute of the argument; if none exists, it will use the string representation of the argument , as returned by str().
  • expression KPIs are seperate from the model. In other terms, adding KPIs does not change the model (and matrix) being solved.

Examples

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”, assuming variables x,y,z have names ‘x’, ‘y’, ‘z’ (resp.)

Returns:The newly added KPI instance.
add_lazy_constraint(lazy_ct, name=None)[source]

Adds one lazy constraint to the problem.

This method expects a linear constraint.

Parameters:
  • lazy_ct – a linear constraints (ranges are not accepted)
  • name – an optional string, used to set the name of the lazy constraint.

New in version 2.10

add_lazy_constraints(lazy_cts, names=None)[source]

Adds lazy constraints to the problem.

This method expects an iterable returning linear constraints (ranges are not accepted).

Parameters:
  • lazy_cts – an iterable returning linear constraints (not ranges)
  • names – an optional iterable returning strings, used to set names for lazy constraints.

New in version 2.10

add_mip_start(mip_start_sol, effort_level=None, write_level=None, complete_vars=False, eps_zero=1e-06)[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’.

The solution passed in input is copied into a new instance of docplex.mp.SolveSolution. Depending on the “write_level” argument, some filtering operations can be performed: by default (no explicit write level) only discrete variables are copied. When an explicit level is passed, the level controls whether zero values are passed ore not: for example “WiteLevel.NonZeroDiscreteVars” specifies only copying non zero values for discrete variables.

Parameters:
  • mip_start_sol (docplex.mp.solution.SolveSolution) – The solution object to use as a starting point.
  • write_level – an optional enumerated value from class docplex.mp.constants.WriteLevel, controlling which variables are copied to the MIP start solution. By default, only discrete variables are copied.
  • complete_vars – optinal flag. If False (default), only variables mentioned in the solution are copied. If True, all variables in the model are copied to the MIP start.
  • effort_level – an optional enumerated value of class docplex.mp.constants.EffortLevel, or None.
Returns:

an instance of doplex.mp.SolveSolution, different from the one passed in input if the conversion succeeds, else None (typically for LP models).

Examples

The default values correspond to copying only variables explicitly mentioned in the passed solution, copying only discrete variables, including zeros. To exclude zeros, use

>>> mdl.add_mip_start(sol, write_level=WriteLevel.NonZeroDiscreteVars)

To include all variables in the model, wincluding continuous ones, use:

>>> mdl.add_mip_start(sol, write_level=WriteLevel.AllVars, complete_vars=True)
add_progress_listener(listener)[source]

Adds a progress listener to the model.

A progress listener is a subclass of :class:~docplex.mp.ProgressListener:

Parameters:listener
add_quadratic_constraints(qcs)[source]

Adds a batch of quadratic contraints in one call.

Parameters:qcs – an iterable on a quadratic constraints.

Note

The Model.add_constraints method handles only linear constraints.

New in version 2.16*

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, weights=None, 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, e.g. lists, numpy arrays, pandas Series. Unordered iterables (e.g. dictionaries or sets) are not accepted.
  • weights – optional weights. Accepts None (no weights) or a list of numbers, with the same size as number of variables.
  • 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 iterables (e.g. dictionaries or 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 iterables (e.g. dictionaries or sets) are not accepted.
  • name – An optional name.
Returns:

The newly added SOS.

add_user_cut_constraint(cut_ct, name=None)[source]

Adds one user cut constraint to the problem.

This method expects a linear constraint.

Parameters:
  • cut_ct – a linear constraints (ranges are not accepted)
  • name – an optional string, used to set the name for the cut constraint.

New in version 2.10

add_user_cut_constraints(cut_cts, names=None)[source]

Adds user cut constraints to the problem.

This method expects an iterable returning linear constraints (ranges are not accepted).

Parameters:
  • cut_cts – an iterable returning linear constraints (not ranges)
  • names – an optional iterable returning strings, used to set names for user cut constraints.

New in version 2.10

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.dvar.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.dvar.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. The returned dictionary should not be modified.

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.dvar.Var objects with type docplex.mp.vartype.BinaryVarType indexed by the objects in keys.

binary_var_list(keys, lb=None, ub=None, name=<class '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.dvar.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.dvar.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.

blended_objective_values

This property returns the list of values of the blended objective expressions based on the decreasing order of priorities in the solution of the last solve.

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

New in version 2.9.

build_multiobj_paramsets(timelimits=None, mipgaps=None)[source]
Creates a sequence containing pre-filled ParameterSet objects to be used with multi objective optimization
only.
Parameters:
  • lex_timelimits (optional) – a sequence of time limits
  • lex_mipgaps (optional) – a sequence of mip gaps
change_var_lower_bounds(dvars, lbs, check_bounds=True)[source]

Changes lower bounds for a collection of variables in one call.

Parameters:
  • dvars – an iterable over decision variables (a list, or a comprehension)
  • lbs – accepts either an iterable over numbers, a single number, in which case the new bound is applied to all variables, or None. If passed None, the lower bound of each variable is reset to its type’s default.
  • check_bounds – an optional flag to enable or disable checking of new lower bounds (default is True: check)

The logic for checking new lower bounds is as follows: new bounds are checked if and only if check is True and the model checker is not ‘off’.

Example

>>> ivars = m.integer_var_list(3, lb=7)
>>> m.change_var_lower_bounds(ivars, [1,2,3]) # sets lower bounds to 1,2,3 resp.

New in 2.20

change_var_upper_bounds(dvars, ubs, check_bounds=True)[source]

Changes upper bounds for a collection of variables in one call.

Parameters:
  • dvars – an iterable over decision variables (a list, or a comprehension)
  • ubs – accepts either an iterable over numbers, a single number, in which case the new bound is applied to all variables, or None. If passed None, the upper bound of each variable is reset to its type’s default.
  • check_bounds – an optional flag to enable or disable checking of new upper bounds (default is True: check)

The logic for checking new upper bounds is as follows: new bounds are checked if and only if check is True and the model checker is not ‘off’.

Example

>>> ivars = m.integer_var_list(3, lb=7)
>>> m.change_var_upper_bounds(ivars, [101,102,103]) # sets upper bounds to 1,01,102,103 resp.

New in 2.20

clear()[source]

Clears the model of all modeling objects.

clear_constraints()[source]

This method removes all constraints from the model.

clear_kpis()[source]

Clears all KPIs defined in the model.

clear_lazy_constraints()[source]

Clears all lazy constraints from the model.

New in version 2.10

clear_mip_starts()[source]

Clears all MIP starts associated with the model.

Note: this clears only MIP starts provided by the user via the Model.add_mip_start method. This does not remove interbal solutions found by previous solves. To run a fresh solve, nd forget all about previous solves, use the clean_before_solve=True keyword argument for solv()

clear_multi_objective()[source]

Clears everything related to multi-objective, if any.

If the model had previously defined multi-objectives, resets the model with an objective of zero. If the model had not defined multi-objectives, this method does nothing.

New in version 2.10

clear_progress_listeners()[source]

Remove all progress listeners from the model.

clear_sos()[source]

Clears all SOS sets in the model.

clear_user_cut_constraints()[source]

Clears all user cut constraints from the model.

New in version 2.10

clone(new_name=None, **clone_kwargs)[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.dvar.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. The returned dictionary should not be modified.

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.dvar.Var objects (with type ContinuousVarType) indexed by the objects in keys.

continuous_var_list(keys, lb=None, ub=None, name=<class '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.dvar.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.

cplex

Returns the instance of Cplex used by the model, if any.

In case no local installation of CPLEX can be found, this method raises an exception.,

Returns:a Cplex instance.

New in version 2.15

create_parameter_sets()[source]

Creates a sequence containing empty ParameterSet objects to be used with multi objective optimization only.

dot(terms, coefs)[source]

Synonym for scal_prod().

dotf(var_dict, coef_fn, assume_alldifferent=True)[source]

Creates a scalar product from a dictionary of variables and a function.

This method is a functional variant of dot. I takes as asrgument a dictionary of variables, as returned by xxx_var_dict or xx_var_var_matrix (where xxx is a type), and a function.

Parameters:
  • var_dict – a dictionary of variables, as returned by all the xxx_var_dict methods (e.g. integer_var_dict), but also multi-dimensional dictionaries, such as xxx_var_matrix (or var_cube).
  • coef_fn – A function that takes one dictionary key and returns anumber. One-dimension dictionaries (such as integer_var_dict) have plain object as keys, but multi-dimensional dictionaries have tuples keys. For example, a binary_var_matrix returns a dictionary, the keys of which are 2-tuples.
  • assume_alldifferent – an optional flag whichi ndicates whether variables values in the dictionary can be assumed to be all different. This is true when the dicitonary has been built by Docplex’s Model.xxx_var-dict(), and thi sis the default behavior. For a custom-built dictionary, set the flag to False. A wrong flag value may yield incorrect results.
Returns:

an expression, built as a scalar product of all variables in the dictionay, multiplied by the result of the function.

Examples

>>> m1 = m.binary_var_matrix(keys1=range(1,3), keys2=range(1,3), name='b')
>>> s = m.dotf(m1, lambda keys: keys[0] + keys[1])

returns 2 b_1_1 + 3 b_1_2 +3 b_2_1 + 4 b_2_2

dual_values(cts)[source]

Returns the dual values of a sequence of linear constraints.

Note: the model must a pure LP: no integer or binary variable, no piecewise, no SOS. The model must also be solved successfully before calling this method.

Parameters:cts – a sequence of linear constraints.
Returns:a sequence of float numbers
dump_as_sav(path=None, basename=None)

Exports a model in CPLEX SAV format.

Exporting to SAV format requires that CPLEX is installed and available in PYTHONPATH. If the CPLEX runtime 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().
Returns:

The full path of the generated file, or None if an error occured.

Examples

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

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. This method must be called when you don’t need a CPLEX engine anymore to free resources, unless the docplex.Model was created with the with keyword.

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.

equivalence_constraint(binary_var, linear_ct, true_value=1, name=None)[source]

Creates and returns a new equivalence constraint.

The newly created equivalence constraint is not added to the model.

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

The newly created equivalence constraint.

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

The full path of the generated file, or None if an error occured.

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_mps(path=None, basename=None)[source]

Exports a model in MPS format.

Exporting to MPS format requires that CPLEX is installed and available in PYTHONPATH. If the CPLEX runtime 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().
Returns:

The full path of the generated file, or None if an error occured.

Examples

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

export_as_mps_string()[source]

Exports the model to a string in MPS format.

Returns:A string, containing the model exported in MPS format.

New in version 2.13

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

The full path of the generated file, or None if an error occured.

Examples

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

export_as_sav_string()[source]

Exports the model to a string of bytes in SAV format.

Returns:A string of bytes..

New in version 2.13

export_as_savgz(path=None, basename=None)[source]

Exports a model in compressed SAV format.

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

Arguments ‘path’ and ‘basename’ have similar usage as for export_as_lp().

Returns:The full path of the generated file, or None if an error occured.

Examples

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

New In 2.19

export_priority_order_file(path=None, basename=None)[source]

Exports a CPLEX priority order file.

This method requires the CPLEX runtime.

Parameters:
  • basename – Controls the basename with which the file 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.
  • 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().
Returns:

The full path of the written file, if successful,, else None.

New in version 2.10

export_to_stream(stream, hide_user_names=False, format_spec='lp')[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.
find_matching_linear_constraints(pattern, match_case=False)[source]

Finds all linear constraints whose name contain a given string

This method searches for all linear constraints whose name is not empty and contains the passed pattern string. Anonymous linear constraints are not considered.

Parameters:
  • pattern – a non-empty string.
  • match_case – optional flag to match case (or not). Default is to not match case.
Returns:

A list of linear constraints.

New in version 2.9

find_matching_quadratic_constraints(pattern, match_case=False)[source]

Finds all quadratic constraints whose name contain a given string

This method searches for all quadratic constraints whose name is not empty and contains the passed pattern string. Anonymous constraints are not considered.

Parameters:
  • pattern – a non-empty string.
  • match_case – optional flag to match case (or not). Default is to not match case.
Returns:

A list of quadratic constraints.

New in version 2.23

find_matching_vars(pattern, match_case=False)[source]

Finds all variables whose name contain a given string

This method searches for all variables whose name is not null and contains the passed pattern string. Anonymous variables are not considered.

Parameters:
  • pattern – a non-empty string.
  • match_case – optional flag to match case (or not). Default is to not match case.
Returns:

A list of decision variables.

find_re_matching_vars(regexpr)[source]

Finds all variables whose name match a regular expression.

This method searches for all variables with a name that matches the given regular expression. Anonymous variables are not counted as matching.

Parameters:regexpr – a regular expression, as define din module re
Returns:A list of decision variables.

New in version 2.9

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_index(idx)[source]

Searches for a linear constraint from an index.

Returns the linear constraint with idx as index, or None. This function will not raise an exception if no constraint with this index is found.

Note: remember that linear constraints, logical constraints, and quadratic constraints each have separate index spaces.

Parameters:idx – a valid index (greater than 0).
Returns:A linear constraint, or None.
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.

Note

The constraint name dicitonary in class Model is disabled by default. However, calling get_constraint_by_name will compute one dicitonary on the fly, but without warning for duplicate names. To enable the constraint name dicitonary from the start (and get duplicate constraint messages), add the cts_by_name keyword argument when creating the model, as in

>>> m = Model(name='my_model', cts_by_name=True)

This enables the constraint name dicitonary, and checks for duplicates when a named constraint is added.

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

Returns the instance of Cplex used by the model, if any.

In case no local installation of CPLEX can be found, this method either raises an exception, if parameter do_raise is True, or else returns None.

Parameters:do_raise – An optional flag: if True, raise an exception when no Cplex instance is available, otherwise return None.

See also

the ‘cplex’ property calls get_cplex() with do_raise=True.

Returns:an instance of Cplex, or None.
get_cuts()[source]

Returns the number of cuts under the form of a dict(type -> number).

Note: The model must also be solved successfully before calling this method.

Returns:the number of cuts under the form of a dict(type -> number).
get_num_cuts(cut_type)[source]

Returns the number of cuts for a specific type.

Note: The model must also be solved successfully before calling this method.

Parameters:cut_type – a cut type.
Returns:the number of cuts associated to this type of cut.
get_objective_expr()[source]

This method returns the expression used as the model objective.

Note

The default objective is a constant zero expression.

Returns:an expression.
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_quadratic_constraint_by_index(idx)[source]

Searches for a quadratic constraint from an index.

Returns the quadratic constraint with idx as index, or None. This function will not raise an exception if no constraint with this index is found.

Note: remember that linear constraints, logical constraints, and quadratic constraints each have separate index spaces. Therefore, a model can contain both a linear constraint and a quadratic constrait having index 0

Parameters:idx – a valid index (greater than 0).
Returns:A quadratic constraint, or None.
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 enumerated value of type docplex.utils.JobSolveStatus

Note: The status returned by Cplex is stored as status in the solve_details of the model.

>>> m.solve_details.status

See also

docplex.mp.SolveDetails.status() to get the Cplex status as a string (eg. “optimal”) docplex.mp.SolveDetails.status_code() to get the Cplex status as an integer code..

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.dvar.Var) or None.
has_basis()[source]

returns True if the model contains basis information.

New in version 2.9

has_multi_objective()[source]

Returns True if the model has multi objectives defined

New in version 2.10

if_then(if_ct, then_ct, negate=False)[source]

Creates and returns an if-then constraint.

An if-then constraint links two constraints ct1, ct2 such that when ct1 is satisfied then ct2 is also satisfied.

Parameters:
  • if_ct – a linear constraint, the satisfaction of which governs the satisfaction of the then_ct
  • then_ct – a linear constraint, which becomes satisfied as soon as if_ct is satisfied (or when it is not, depending on the negate flag).
  • negate – an optional boolean flag (default is False). If True, then_ct is satisfied when if_ct is not satisfied.
Returns:

an instance of IfThenConstraint, that is not added to the model. Use Model.add_constraint() or Model.add() to add it to the model.

Note

This constraint relies on the status of the if_ct constraint, so this constraint must be discrete, otherwise an exception will be raised.

ignore_names

This property is used to ignore all names in the model.

This flag indicates whether names are used or not. When set to True, all names are ignored. This could lead to performance improvements when building large models. The default value of this flag is False. To change its value, add it as keyword argument when creating the Model instance as in:

>>> m = Model(name="my_model", ignore_names=True)

Note

Once a model instance has been created with ignore_names=True, there is no way to restore its names. This flag only allows to enable or disable name generation while building the model.

import_solution(source_solution, match='auto', error='raise')[source]

Imports a solution from another model.

There must a a way to map variables from the solution model to the target model, either by name, index or some other custom manner. The simplest case is where the other model is a clone of the target model. In that case, an index-based mapping is used.

Parameters:
  • source_solution – the imported solution, built on some othe rmodel, different from target model.
  • match – described the mapping used for variables, accepts either a string for predefined mappings: “index” for index mapping, “name” for name mapping, or “auto” for automatic. Also accepts a function taking two arguments: the source variable, and the target model, returning th eimage of the source variable in the target model.
  • error – A string describing how errors are handled. Accepts “raise”, “warn”, or “ignore”
Returns:

A solution object, instance of SolveSolution, built on the target model, from values and variables mapped from the source model to the target model.

New in version 2.21

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

Creates and returns a new indicator constraint.

The indicator constraint is not added to the model.

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.

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.dvar.Var class with type IntegerVarType.

Return type:

docplex.mp.dvar.Var

integer_var_cube(keys1, keys2, keys3, lb=None, ub=None, name=<class '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. The returned dictionary should not be modified.

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.dvar.Var objects (with type IntegerVarType) indexed by the objects in keys.

See also

infinity

integer_var_list(keys, lb=None, ub=None, name=<class '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.

Example

>>> m.integer_var_list(3, name="ij")
returns a list of three integer variables from 0 to 1e+20, named ij_0, ij_1, ij_2.
The default behavior, when a string argument is passed as name,
is to concatenate the string , a "-" separator and a string representation
of the key; this allows to build arbitrary name strings from keys.
>>> m.integer_var_list(3, name=lambda i: "__name_{}__".format(i))
uses a functional name argument, producing names: "__name_0__",
 "__name_1__", "_name__2__".
>>> m.integer_var_list(3, name="q", lb=1, ub=100)
returns a list of three integer variables from 1 to 100, named q_0, q_1, q_3
>>> m.integer_var_list([1,2,3], name="q", lb=lambda k: k, ub=lambda k: k*k+1)
returns a list of three integer variables q_1[1,1**1 +1], q2[2, 2*2+1], q3[3, 3*3+1]

The last example use the functional lb and ub, to compute bounds that depend on the keys.

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_maximized()[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_minimized()[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_constraints()[source]

Returns an iterator on the binary constraints (expr1 <op> expr2) of the model. This does not include range constraints.

Returns:An iterator object.
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_equivalence_constraints()[source]

Returns an iterator on equivalence constraints in 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_lazy_constraints()[source]

Returns an iterator on the model’s lazy constraints

Returns:an iterator on lazy constraints.

New in version 2.10

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_mip_starts()[source]
This property returns an iterator on the MIP starts associated with

the model.

It returns tuples of size 2:

New in version 2.10

iter_progress_listeners()[source]

Returns an iterator on the progress listeners attached to the model.

Returns:an iterator.
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_range_constraints()[source]

Returns an iterator on the range 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_user_cut_constraints()[source]

Returns an iterator on the model’s user cut constraints

Returns:an iterator on user cut constraints.

New in version 2.10

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, solution=None, try_match=True, match_case=False)[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.
  • solution – an optional solution. If not present, assume the model is solved and use the model solution.
  • 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.

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

KPIs require a solution to be evaluated. This solution can be passed explicitly as a parameter, or the model is assumed to be solved with a valid solution.

Returns:The KPI value.
Return type:float

See also

docplex.mp.solution.SolveSolution new_solution()

kpis_as_dict(solution=None, kpi_filter=None, objective_key=None, use_names=True)[source]

Returns KPI values in a solution as a dictionary.

Each KPI has a value in the solution. This method returns a dictionary of KPI values, indexed by KPI objects.

Parameters:
  • solution – an instance of solution, as returned by solve(). If not passed, will use the model’s solution. If no solution is present, an exception is raised.
  • kpi_filter – an optional predicate to filter some kpis. If provided, accepts a function taking one KPI as argument and returning a boolean. By default, all KPIs are returned.
  • objective_key – an optional string key for th eobjective value. If present, the value of the objective is added to the dictionary, with this key. By default, this parameter is None and the objective is not appended to the dictionary.
  • use_names – a flag which determines whether keys in the resulting dict are KPI objects or kpi names. Default is to use KPI names.
Returns:

A dictionary mapping KPIs, or KPI names to values.

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_constraint_basis_statuses(lcts)[source]

Returns basis status for a batch of linear constraints.

Parameters:lcts – an iterable returning linear constraints.
Returns:a list of basis status, of type docplex.mp.constants.BasisStatus. The order of the list is the order in which constraints were returned by the iterable.

New in version 2.10

linear_expr(arg=None, constant=0, 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.
Returns:An instance of docplex.mp.linear.LinearExpr.
logical_and(*args)[source]

Builds an expression equal to the logical AND value of its arguments.

This method takes a variable number of arguments, and accepts binary variables, other logical expressions, or discrete constraints.

Parameters:args – A variable list of logical operands.

Note

If passed an empty number of arguments, this method an expression equal to 1.

Returns:An expression, equal to 1 if and only if all of its arguments are equal to 1, else equal to 0.

Example:

# return logical XOR or two binary variables.
def logxor(m, b1, b2):
    return m.logical_and(m.logical_or(b1, b2), m.logical_not(m.logical_and(b1, b2)))
logical_not(arg)[source]

Builds an expression equal to the logical negation of its argument.

This method accepts either a binary variable, or another logical expression.

Parameters:arg – A binary variable, or a logical expression, e.g. an expression built by logical_and, logical_or, logical_not
Returns:An expression, equal to 1 if its argument is 0, else 0.
logical_or(*args)[source]

Builds an expression equal to the logical OR value of its arguments.

This method takes a variable number of arguments, and accepts
binary variables, other logical expressions, or discrete constraints.
Parameters:args – A variable list of logical operands.

Note

If passed an empty number of arguments, this method a zero expression.

Returns:
An expression, equal to 1 if and only if at least one of its
arguments is equal to 1, else equal to 0.

New in version 2.11

lp_line_length

This property lets you get or set the maximum line length of LP files generated by DOcplex. The default is 80.

New in version 2.11
lp_string

This property returns a string encoding the model in LP format.

New in version 2.16

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.dvar.Var class), linear expressions (instances of docplex.mp.linear.LinearExpr), or numbers.

Parameters:expr – A linear expression or a variable.
maximize_static_lex(exprs, abstols=None, reltols=None, objnames=None)[source]

Sets a list of expressions to be maximized in a lexicographic solve. exprs defines an ordered sequence of objective functions that are maximized.

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

Warning

This method requires CPLEX 12.9 or higher

Parameters:
  • exprs – a list of linear expressions or variables
  • abstols – if defined, a list of absolute tolerances having the same size as the exprs argument.
  • reltols – if defined, a list of relative tolerances having the same size as the exprs argument.
  • objnames – if defined, a list of names for objectives having the same size as the exprs argument.

New in version 2.9

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.dvar.Var class), linear expressions (instances of docplex.mp.linear.LinearExpr), or numbers.

Parameters:expr – A linear expression or a variable.
minimize_static_lex(exprs, abstols=None, reltols=None, objnames=None)[source]

Sets a list of expressions to be minimized in a lexicographic solve. exprs must be an ordered sequence of objective functions, that are minimized.

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

Warning

This method requires CPLEX 12.9 or higher

Parameters:
  • exprs – a list of linear expressions or variables
  • abstols – if defined, a list of absolute tolerances having the same size as the exprs argument.
  • reltols – if defined, a list of relative tolerances having the same size as the exprs argument.
  • objnames – if defined, a list of names for objectives having the same size as the exprs argument.

New in version 2.9

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.

multi_objective_values

This property returns the list of values of the objective expressions in the solution of the last solve.

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

New in version 2.9

name

This property is used to get or set the model name.

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_equivalence_constraints

This property returns the number of equivalence constraints in 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_lazy_constraints

Returns the number of lazy constraints present in 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_mip_starts

This property returns the number of MIP start associated with the model.

New in version 2.10

number_of_progress_listeners

Returns the number of progress listeners attached to the model.

Returns:an integer
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_user_constraints

This property returns the total number of constraints that were explicitly added tothe model, not including generated constraints.

The number includes all types of constraints.

number_of_user_cut_constraints

Returns the number of user cut constraints present in the model

New in version 2.10

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 is used to get or set the expression used as the model objective.

objective_sense

This property is used to get or set the direction of the optimization as an instance of docplex.mp.basic.ObjectiveSense, either Minimize or Maximize.

This property also accepts strings as arguments: ‘min’ for minimize and ‘max’ for maximize.

objective_value

This property returns the value of the objective expression in the solution of the last solve. In case of a multi-objective, only the value of the first objective is returned

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 hierarchy. 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.
populate(**kwargs)

Populates and return a solution pool.

returns either a solutiion pool object, or None if the model solve fails.

This method accepts the same keyword arguments as Model.solve(). See the documentation of Model.solve() for more details.

Returns:an instance of docplex.mp.solution.SolutionPool, or None.

New in version 2.16

populate_solution_pool(**kwargs)[source]

Populates and return a solution pool.

returns either a solutiion pool object, or None if the model solve fails.

This method accepts the same keyword arguments as Model.solve(). See the documentation of Model.solve() for more details.

Returns:an instance of docplex.mp.solution.SolutionPool, or None.

New in version 2.16

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, solution_header_fmt=None, 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.
  • solution_header_fmt – a solution header string in format syntax, or None. This format will be passed to docplex.mp.solution.SolveSolution.display().
  • var_value_fmt – A format string to format the variable name and value. Again, the default uses the automatically computed precision.

See also

docplex.mp.solution.SolveSolution.display()

problem_type

Returns a string describing the type of problem.

This method requyires that CPLEX is installed and available in PYTHONPATH. If the CPLEX runtime cannot be found, an exception is raised.

Possible values: LP, MILP, QP, MIQP, QCP, MIQCP,

New in version 2.20
quad_expr(name=None)[source]

Returns a new empty quadratic expression.

Returns:An empty instance of docplex.mp.quad.QuadExpr.
quadratic_dual_slacks(*args)[source]

Returns quadratic dual slacks as a dict of dicts.

Can be called in two forms: either with no arguments, in which case it returns quadratic dual slacks for all quadratic constraints in the model, or with a list of quadratic constraints. In this case it returns only quadratic dual slacks for those constraints

Parameters:args – accepts either no arguments,or a list of quadratic constraints.
Returns:a Python dictionary, whose keys are quadratic constraints, and values are dictionaries from variables to quadratic dual slacks.

New in version 2.15

quality_metrics

This flag controls whether CPLEX quality metrics are stored into the solve details. The default is not to store quality metrics.

New in version 2.10

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.

read_basis_file(bas_path)[source]

Read a CPLEX basis status file.

This method requires the CPLEX runtime.

Parameters:bas_path – the path of a basis file (extension is ‘.bas’)

New in version 2.10

read_mip_starts(mst_path)[source]

Read MIP starts from a file.

Reads the file and returns a list of (solution, effort_level) tuples.

Parameters:mst_path – the path to mip start file (in CPLEX MST file format)
Returns:a list of tuples of size 2; the first element is an instance of SolveSolution and the second element is an enumerated value of type EffortLevel
  • New in version 2.10*
read_priority_order_file(ord_path)[source]

Read a CPLEX priority order file.

This method requires the CPLEX runtime.

Parameters:ord_path – the path of a priority order file (extension is ‘.ord’)

New in version 2.10

reduced_costs(dvars)[source]

Returns the reduced costs for a variable iterable.

Note: the model must a pure LP: no integer or binary variable, no piecewise, no SOS. The model must also be solved successfully before calling this method.
Parameters:dvars – a sequence of variables.
Returns:a list of float numbers, in the same order as the variable sequence.
remove(removed)[source]

This method removes a constraint or a collection of constraints from the model.

Parameters:removed – accapts either a constraint or an iterable on constraints (linear, range, quadratic, indicators)
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_constraints(cts=None, error='warn')[source]

This method removes a batch of constraints from the model.

Parameters:cts – an iterable of constraints (linear, range, quadratic, indicators)
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_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.

remove_progress_listener(listener)[source]

Remove a progress listener from the model.

Parameters:listener
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(solution=None, selected_kpis=None, kpi_format='* KPI: {1:<{0}} = ')[source]

Prints the values of the KPIs.

KPIs require a solution to be evaluated. This solution can be passed explicitly as a parameter, or the model is assumed to be solved with a valid solution.

Parameters:
  • solution – an instance of SolveSolution. If not passed, the model solution is queried. If the model has no solution, an exception is raised.
  • selected_kpis – an optional iterable returning the KPIs to print. The default behavior is to print all kpis.
  • kpi_format – an optional format to print the KPi name and its value.

See also

docplex.mp.solution.SolveSolution new_solution()

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()

round_solution

This flag controls whether integer and discrete variable values are rounded in solutions, or not. If not rounded, it may happen that solution value for a binary variable returns 0.99999. The default is not to round discrete values.

New in version 2.15

scal_prod(terms, coefs)[source]

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

This method accepts different types of input for both arguments. terms can be any iterable returning expressions or variables, and coefs is usually an iterable returning numbers. cal_prod also accept one number as coefs, in which case the scalar product reduces to a sum times this coefficient.

Parameters:
  • terms – An iterable returning variables or expressions.
  • coefs – An iterable returning numbers, or a number.

Note

  • both iterables are iterated at the same time, so the order in which terms and numbers are returned must be consistent: using unordered collections (e.g. sets) could lead to unexpected results.
  • Iteration stops as soon as one iterable stops. If both iterables are empty, the method returns 0.
Returns:A linear expression or 0.
scal_prod_f(var_dict, coef_fn, assume_alldifferent=True)

Creates a scalar product from a dictionary of variables and a function.

This method is a functional variant of dot. I takes as asrgument a dictionary of variables, as returned by xxx_var_dict or xx_var_var_matrix (where xxx is a type), and a function.

Parameters:
  • var_dict – a dictionary of variables, as returned by all the xxx_var_dict methods (e.g. integer_var_dict), but also multi-dimensional dictionaries, such as xxx_var_matrix (or var_cube).
  • coef_fn – A function that takes one dictionary key and returns anumber. One-dimension dictionaries (such as integer_var_dict) have plain object as keys, but multi-dimensional dictionaries have tuples keys. For example, a binary_var_matrix returns a dictionary, the keys of which are 2-tuples.
  • assume_alldifferent – an optional flag whichi ndicates whether variables values in the dictionary can be assumed to be all different. This is true when the dicitonary has been built by Docplex’s Model.xxx_var-dict(), and thi sis the default behavior. For a custom-built dictionary, set the flag to False. A wrong flag value may yield incorrect results.
Returns:

an expression, built as a scalar product of all variables in the dictionay, multiplied by the result of the function.

Examples

>>> m1 = m.binary_var_matrix(keys1=range(1,3), keys2=range(1,3), name='b')
>>> s = m.dotf(m1, lambda keys: keys[0] + keys[1])

returns 2 b_1_1 + 3 b_1_2 +3 b_2_1 + 4 b_2_2

scal_prod_vars_all_different(terms, coefs)[source]

Fastly creates a scalar product from a dictionary of variables and a list of coefficients or a coefficient. :param terms: An iterable returning variables or expressions. :param coefs: An iterable returning numbers, or a number.

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.dvar.Var

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

Creates a dictionary of semi-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. The returned dictionary should not be modified.

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.
  • 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.dvar.Var objects (with type SemiIntegerVarType) indexed by the objects in keys.

See also

infinity

semicontinuous_var_list(keys, lb, ub=None, name=<class '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.dvar.Var objects with type docplex.mp.vartype.SemiContinuousVarType.

See also

infinity

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

Creates a dictionary of semicontinuous 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 semiinteger_var_dict().

New in version 2.9

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.dvar.Var

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

Creates a dictionary of semi-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. The returned dictionary should not be modified.

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.
  • 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.dvar.Var objects (with type SemiIntegerVarType) indexed by the objects in keys.

See also

infinity

semiinteger_var_list(keys, lb, ub=None, name=<class '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.dvar.Var objects with type docplex.mp.vartype.SemiIntegerVarType.

See also

infinity

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

Creates a dictionary of semiinteger 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 semiinteger_var_dict().

New in version 2.9

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_lex_multi_objective(sense, exprs, abstols=None, reltols=None, names=None)[source]

Sets a list of objectives to be solved in a lexicographic fashion.

Objective expressions are listed in decreasing priority.

Warning

This method requires CPLEX 12.9 or higher

Parameters:
  • sense – Either an instance of docplex.mp.basic.ObjectiveSense (Minimize or Maximize), or a string: “min” or “max”.
  • exprs – Is converted to a list of expressions. Accepted types for this list items are variables, linear expressions or numbers.
  • abstols – if defined, a list of absolute tolerances having the same size as the exprs argument.
  • reltols – if defined, a list of relative tolerances having the same size as the exprs argument.
  • names – if defined, a list of names for objectives having the same size as the exprs argument.

Note

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

New in version 2.9.

set_lp_start_basis(dvar_stats, lct_stats)[source]

Provides an initial basis for a LP problem.

Parameters:
  • dvar_stats – an ordered sequence (list) of basis status objects, one for each decision variable in the model.
  • lct_stats – an ordered sequence (list) of basis status objects, one for each linear constraint in the model

Note

Basis status are values of the enumerated type docplex.mp.constants.BasisStatus.

  • New in version 2.10*
set_multi_objective(sense, exprs, priorities=None, weights=None, abstols=None, reltols=None, names=None)[source]

Sets a list of objectives.

Warning

This method requires CPLEX 12.9 or higher

Parameters:
  • sense – Either an instance of docplex.mp.basic.ObjectiveSense (Minimize or Maximize), or a string: “min” or “max”.
  • exprs – Is converted to a list of expressions. Accepted types for this list items are variables, linear expressions or numbers.
  • priorities – a list of priorities having the same size as the exprs argument. Priorities define how objectives are grouped together into sub-problems, and in which order these sub-problems are solved (in decreasing order of priorities). If not defined, allexpressions are assumed to share the same priority, and are combined with weights.
  • weights – if defined, a list of weights having the same size as the exprs argument. Weights define how objectives with same priority are blended together to define the associated sub-problem’s objective that is optimized. If not defined, weights are assumed to be all equal to 1.
  • abstols – if defined, a list of absolute tolerances having the same size as the exprs argument.
  • reltols – if defined, a list of relative tolerances having the same size as the exprs argument.
  • names – if defined, a list of names for objectives having the same size as the exprs argument.

Note

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

New in version 2.9.

set_multi_objective_abstols(abstols)[source]

Changes absolute tolerances for multiple objectives.

Parameters:abstols – new absolute tolerances. Can be either a number (applies to all objectives), or a sequence of numbers. A sequence must have the same length as the number of objectives.

New in version 2.16

set_multi_objective_exprs(exprs, priorities=None, weights=None, abstols=None, reltols=None, names=None)[source]

Defines a list of blended objectives.

Objectives with the same priority are combined using weights. Then, objectives are optimized in a lexicographic fashion by decreasing priority.

Parameters:
  • exprs – Is converted to a list of linear expressions. Accepted types for this list items are variables, linear expressions or numbers.
  • priorities – if defined, a list of priorities having the same size as the exprs argument. Priorities define how objectives are grouped together into sub-problems, and in which order these sub-problems are solved (in decreasing order of priorities).
  • weights – if defined, a list of weights having the same size as the exprs argument. Weights define how objectives with same priority are blended together to define the associated sub-problem objective that is optimized.
  • abstols – if defined, a list of absolute tolerances having the same size as the exprs argument.
  • reltols – if defined, a list of relative tolerances having the same size as the exprs argument.
  • names – if defined, a list of names for objectives having the same size as the exprs argument.

Note

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

New in version 2.9.

set_multi_objective_reltols(reltols)[source]

Changes relative tolerances for multiple objectives.

Parameters:reltols – new relative tolerances. Can be either a number (applies to all objectives), or a sequence of numbers. A sequence must have the same length as the number of objectives.

New in version 2.16

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.
slack_values(cts)[source]

Return the slack values for a sequence of constraints.

Slack values are available for linear, quadratic and indicator constraints. The model must be solved successfully before calling this method.

Parameters:cts – a sequence of constraints.
Returns:a list of float values, in the same order as the constraints.
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.

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. Accepts either a RootParameterGroup object (obtained by cloning the model’s parameters), or a dict of path-like names and values.
  • checker (optional) – a string which controls which type of checking is performed. Possible values are: - ‘std’ (the default) performs type checks on arguments to methods; checks that numerical arguments are numbers, but will not check for NaN or infinity. - ‘numeric’ checks that numerical arguments are valid numbers, neither NaN nor math.infinity - ‘full’ performs all possible checks, the union of ‘std’ and ‘numeric’ checks. - ‘off’ performs no checking at all. Disabling all checks might improve performance, but only when it is safe to do so.
  • 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.
  • clean_before_solve (optional) – a boolean (default is False). Solve normally picks up where the previous solve left, but if this flag is set to True, a fresh solve is started, forgetting all about previous solves..
  • parameter_sets (optional) – See create_parameter_sets()
Returns:

A docplex.mp.solution.SolveSolution object if the solve operation managed to create a feasible solution, else None. The reason why solve returned None includes not only errors, but also proper cases of infeasibilties or unboundedness. When solve returns None, use Model.solve_details to check the status of the latest solve operation: Model.solve_details always returns a docplex.mp.sdetails.SolveDetails object, whether or not a solution has been found. This object contains detailed information about the latest solve operation, such as status, elapsed time, and for MILP problems, number of nodes processed and final gap.

solve_details

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

When the latest solve did return a Solution instance, this property returns the solve details corresponding to the solution; when no solution has been found (in other terms, the latest solve operation returned None), it still returns a SolveDetails object, containing a CPLEX code identifying the reason why no solution could be found (for example, infeasibility or unboundedness).

solve_status

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.
solve_with_goals(goals, senses='min', abstols=None, reltols=None, goal_names=None, write_pass_files=False, solution_callbackfn=None, **kwargs)[source]

Performs a solve from an ordered collection of goals.

Parameters:
  • goals – An ordered collection of linear expressions.
  • senses – Accepts ither an ordered sequence 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”.
  • abstols – if defined, accepts either a number or a list of numbers having the same size as the exprs argument, interpreted as absolute tolerances. If passed asingle number, this tolerance number will be used for all passes.
  • reltols – if defined, accepts either a number or a list of numbers having the same size as the exprs argument, interpreted as absolute tolerances. If passed asingle number, this tolerance number will be used for all passes.

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 constraint the first goal to be no greater than 102 if minimizing, or no less than 98, if maximizing.

If one pass fails, return the previous pass’ solution. If the solve fails at the first goal, then return None.

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.
str_use_space
This boolean property controls the use of space separators when displaying the str()

representation of expressions (especially in constraints). With str_use_space=False a constraint is printed as : 2x+3y+5z <= 7

With str_use_space=True the same constraint is printed as : 2 x + 3 y + 5 z <= 7

The default is False, that is print a compact representation.

Returns:True if space separator is used for string representations of expressions.
sum(args)[source]

Creates an expression summing over an iterable over expressions or variables. This method expects an iterable over any type of expression: quadrayic expression, linear expression, variables, constants.

Note

The returned expression is quadratic as soon as the result is quadratic, otherwise it returns a linear expression, or 0 if the iterable is empty.

Parameters:args – An iterable over expressions (quadratic or linear), variables, or constants.
Returns:A Docplex expression.
sum_squares(args)

Creates a quadratic expression summing squares of expressions.

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 – An iterable returning linear expressions, variables or numbers.
Returns:A quadratic expression (possibly constant).
sum_vars(dvars)[source]

Creates a linear expression that sums variables.

This method is faster than Model.sum() but accepts only variables.

Parameters:dvars – an iterable returning variables.
Returns:a linear expression equal to the sum of the variables.

New in version 2.10

sum_vars_all_different(terms)[source]

Creates a linear expression equal to sum of a list of decision variables. The variable sequence is a list or an iterator of variables.

This method is faster than the standard generic summation method due to the fact that it takes only variables and does not take expressions as arguments.

Parameters:terms – A list or an iterator on variables only, with no duplicates.
Returns:a linear expression equal to the sum of the variables.

Note

If the variable iteration contains duplicates, this function returns an incorrect result.

sums(*args)[source]

Same as Model.sum() but accepts a variable number of arguments.

Parameters:args – A variable number of expressions (quadratic or linear), variables, or constants.
Returns:A Docplex expression.

Example

Assuming x is a variable. >>> m.sums(x**2, x, 1) is identical to >> m.sum([x**2, x, 1])

Both return a quadratic expression “x^2+x+1”

New in version 2.22

sumsq(args)[source]

Creates a quadratic expression summing squares of expressions.

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 – An iterable returning linear expressions, variables or numbers.
Returns:A quadratic expression (possibly constant).
time_limit

This property is used to get/set the time limit for this model.

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.dvar.Var

Note

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

var_basis_statuses(dvars)[source]

Returns basis status for a batch of variables.

Parameters:dvars – an iterable returning variables.
Returns:a list of basis status, of type docplex.mp.constants.BasisStatus. The order of the list is the order in which variables were returned by the iterable.

New in version 2.10

var_hypercube(vartype_spec, seq_of_keys, lb=None, ub=None, name=None, key_format=None)[source]

Creates a dictionary of decision variables, indexed by tuples of arbitrary size.

Arguments are analogous to methods of the type xxx_var_matrix, except a type argument has to be passed.

Parameters:
  • vartype_spec

    type specificsation: accepts either an instance of class docplex.mp.VarType, or a string that can be translated into a vartype. Possible strings are:

    • cplex type codes, e.g. B,I,C,N,S or type short names (e.g.: binary, integer, continuous, semicontinuous, semiinteger)
  • seq_of_keys – a sequence of sequence of keys. Typically of length >= 4, as other dimensions are handled by the ‘list’, ‘matrix’ and ‘cube’ series of methods. Variables are indexed by tuples formed by the cartesian product of elements form the sequences; all sequences of keys must be non-empty.

All other arguments have the same meaning as for all the “xx_var_matrix” family of methods.

Example

>>> hc = Model().var_hypercube(vartype_spec='B', seq_of_keys=[[1,2], [3], ['a','b'], [1,2,3,4]]
>>> len(hc)
16
returns a dict of 2x2x4 = 16 variables indexed by tuples formed by the cartesian product
of the four lists, for example (1,3,'a',4)is a valid key for the hypercube.

New in 2.19