Expressions (cpmpy.expressions)

Classes and functions that represent and create expressions (constraints and objectives)

List of submodules

variables

Integer and Boolean decision variables (as n-dimensional numpy objects)

core

globalconstraints

Global constraints conveniently express non-primitive constraints.

globalfunctions

Global functions conveniently express numerical global constraints in function form.

python_builtins

Overwrites a number of python built-ins, so that they work over variables as expected.

utils

Internal utilities for expression handling.

class cpmpy.expressions.Abs(expr: Expression)[source]

Computes the absolute value of the argument

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[Expression, list[Expression]][source]

Decomposition of Abs global function.

Can only be decomposed by introducing an auxiliary variable and enforcing its value to be positive,

based on the value of the given argument to the global function. I.e., if the argument is negative, the auxiliary variable will take the negated value of the argument, and otherwise it will take the argument itself.

Returns:

A tuple containing the expression representing the absolute value (may be the argument itself, its negation, or an auxiliary variable), and a list of constraints defining it (empty if no auxiliary variable is needed)

Return type:

tuple[Expression, list[Expression]]

decompose_comparison(cmp_op: str, cmp_rhs: Expression) tuple[list[Expression], list[Expression]]

DEPRECATED: returns a list of constraints representing the decomposed comparison of the global function (and any auxiliary variables introduced).

Parameters:
  • cmp_op (str) – Comparison operator

  • cmp_rhs (Expression) – Right-hand side expression for the comparison

Returns:

A tuple containing two lists: constraints representing the comparison, and constraints defining auxiliary variables

Return type:

tuple[list[Expression], list[Expression]]

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int][source]

Returns the lowest and highest possible absolute value

Returns:

A tuple of (lower bound, upper bound) for the absolute value

Return type:

tuple[int, int]

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool
Returns:

False, global functions are numeric

Return type:

bool

is_total() bool

Returns whether it is a total function. If true, its value is defined for all arguments

TODO: I do not find anywhere where we set it dynamically to False? TODO: REMOVE??

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() int | None[source]
Returns:

The absolute value of the argument, or None if the argument is not assigned

Return type:

Optional[int]

class cpmpy.expressions.AllDifferent(*args: Expression | int | integer | bool | Sequence[Expression | int | integer | bool] | ndarray)[source]

Enforces that all arguments have a different (distinct) value

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[list[Expression], list[Expression]][source]

Decomposition of the AllDifferent global constraint using pairwise disequality constraints.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_linear() tuple[list[Expression], list[Expression]][source]

Linear-friendly decomposition using sums over (arg[i] == val) expressions (which will become Boolean variables): at most one integer variable can take each value in the domain.

For use with integer linear programming and pb/sat solvers.

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.AllDifferentExcept0(*args: Expression | int | integer | bool | Sequence[Expression | int | integer | bool] | ndarray)[source]

Enforces that all arguments, except those equal to 0, have a different (distinct) value.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[list[Expression], list[Expression]]

Decomposition of the AllDifferentExceptN global constraint using pairwise constraints.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.AllDifferentExceptN(arr: Sequence[Expression | int | integer | bool] | ndarray, n: int | integer | list[int | integer])[source]

Enforces that all arguments, except those equal to a value in n, have a different (distinct) value.

Parameters:
  • arr (Sequence[Expression]) – List of expressions to be different from each other, except those equal to a value in n

  • n (int or list[int]) – Value or list of values that are excluded from satisfying the alldifferent condition

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[list[Expression], list[Expression]][source]

Decomposition of the AllDifferentExceptN global constraint using pairwise constraints.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.AllEqual(*args: Expression | int | integer | bool | Sequence[Expression | int | integer | bool] | ndarray)[source]

Enforces that all arguments have the same value

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[list[Expression], list[Expression]][source]

Decomposition of the AllEqual global constraint using cascaded equality constraints.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.AllEqualExceptN(arr: Sequence[Expression | int | integer | bool] | ndarray, n: int | integer | list[int | integer])[source]

Enforces that all arguments, except those equal to a value in n, have the same value.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[list[Expression], list[Expression]][source]

Decomposition of the AllEqualExceptN global constraint using pairwise constraints.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.Among(arr: Sequence[Expression | int | integer | bool] | ndarray, vals: Sequence[int | integer] | ndarray)[source]

The Among global function counts how many variables in an array take values that are in a given set of values.

This is similar to Count, but instead of counting occurrences of a single value, it counts occurrences of any value in a set. For example, Among([x1, x2, x3, x4], [1, 2]) returns the number of variables among x1, x2, x3, x4 that take the value 1 or 2.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[Expression, list[Expression]][source]

Decomposition of the Among global function.

Among is decomposed into a sum of Count global functions, one for each value in the set. For example, Among(arr, [1, 2, 3]) is decomposed as Count(arr, 1) + Count(arr, 2) + Count(arr, 3).

Returns:

A tuple containing the sum expression representing the total number of occurrences, and an empty list of constraints (no auxiliary variables needed)

Return type:

tuple[Expression, list[Expression]]

decompose_comparison(cmp_op: str, cmp_rhs: Expression) tuple[list[Expression], list[Expression]]

DEPRECATED: returns a list of constraints representing the decomposed comparison of the global function (and any auxiliary variables introduced).

Parameters:
  • cmp_op (str) – Comparison operator

  • cmp_rhs (Expression) – Right-hand side expression for the comparison

Returns:

A tuple containing two lists: constraints representing the comparison, and constraints defining auxiliary variables

Return type:

tuple[list[Expression], list[Expression]]

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int][source]

Returns the bounds of the global function

Returns:

A tuple of (lower bound, upper bound) for the among count value

Return type:

tuple[int, int]

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool
Returns:

False, global functions are numeric

Return type:

bool

is_total() bool

Returns whether it is a total function. If true, its value is defined for all arguments

TODO: I do not find anywhere where we set it dynamically to False? TODO: REMOVE??

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() int | None[source]
Returns:

The number of variables in arr that take a value present in vals, or None if any element in arr is not assigned

Return type:

Optional[int]

class cpmpy.expressions.BoolVal(arg: bool | bool)[source]

Wrapper for python or numpy BoolVals

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

has_subexpr() bool[source]

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree.

implies(other: Expression | bool | bool, simplify: bool = False) Expression[source]

Implication constraint: BoolVal -> other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – simplify the implication, even if it means other dissappears from user-view

Simplification rule:
  • BoolVal(False) -> other :: BoolVal(True)

Note: BoolVal(True).implies(other) will always return other

Returns:

the implication constraint or a BoolVal or other

Return type:

Expression

is_bool() bool

is it a Boolean (return type) Operator? Default: yes

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

cpmpy.expressions.BoolVar(shape=1, name=None)[source]

Deprecated since version 0.9.0: Please use boolvar() instead.

class cpmpy.expressions.Circuit(*args: Expression | int | integer | bool | Sequence[Expression | int | integer | bool] | ndarray)[source]

Enforces that the sequence of variables form a circuit, where x[i] = j means that node j is the successor of node i.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[list[Expression], list[Expression]][source]

Decomposition of the Circuit global constraint using auxiliary variables to reprsent the order in which we visit all the nodes. Auxiliary variables are defined in the defining part of the decomposition, which is alwasy enforced top-level.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_linear_positive() tuple[list[Expression], list[Expression]][source]

Linear decomposition of the Circuit global constraint, inspired by Miller-Tucker-Zemlin formulation for TSPs. This linear decomposition is only valid in positive context.

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.Count(arr: Sequence[Expression | int | integer | bool] | ndarray, val: Expression | int | integer | bool)[source]

The Count global function represents the number of occurrences of a value in an array

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[Expression, list[Expression]][source]

Decomposition of the Count global function.

Does not require the use of auxiliary variables, simply count the number of variables that take the given value.

Returns:

A tuple containing the sum expression representing the count, and an empty list of constraints (no auxiliary variables needed)

Return type:

tuple[Expression, list[Expression]]

decompose_comparison(cmp_op: str, cmp_rhs: Expression) tuple[list[Expression], list[Expression]]

DEPRECATED: returns a list of constraints representing the decomposed comparison of the global function (and any auxiliary variables introduced).

Parameters:
  • cmp_op (str) – Comparison operator

  • cmp_rhs (Expression) – Right-hand side expression for the comparison

Returns:

A tuple containing two lists: constraints representing the comparison, and constraints defining auxiliary variables

Return type:

tuple[list[Expression], list[Expression]]

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int][source]

Returns the bounds of the global function

Returns:

A tuple of (lower bound, upper bound) for the count value

Return type:

tuple[int, int]

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool
Returns:

False, global functions are numeric

Return type:

bool

is_total() bool

Returns whether it is a total function. If true, its value is defined for all arguments

TODO: I do not find anywhere where we set it dynamically to False? TODO: REMOVE??

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() int | None[source]
Returns:

The number of occurrences of val in arr, or None if val or any element in arr is not assigned

Return type:

Optional[int]

class cpmpy.expressions.Cumulative(start: Sequence[Expression | int | integer | bool] | ndarray, duration: Sequence[Expression | int | integer | bool] | ndarray, end: Sequence[Expression | int | integer | bool] | ndarray | None = None, demand: Sequence[Expression | int | integer | bool] | ndarray | Expression | int | integer | bool | None = None, capacity: Expression | int | integer | bool | None = None)[source]
Enforces that a set of tasks is scheduled such that the capacity of the resource is never exceeded and enforces:
  • duration >= 0

  • demand >= 0

  • start + duration == end

Equivalent to NoOverlap when demand and capacity are equal to 1. Supports both varying demand across tasks or equal demand for all jobs.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose(how: str = 'auto') tuple[list[Expression], list[Expression]][source]

Decompose the Cumulative constraint Support time-based decomposition or task-based decomposition. By default, we heuristically select the best decomposition based on the number of tasks and the horizon.

Parameters:

how (str) – how the cumulative constraint should be decomposed, can be “time”, “task”, or “auto” (default)

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.CumulativeOptional(start: Sequence[Expression | int | integer | bool] | ndarray, duration: Sequence[Expression | int | integer | bool] | ndarray, end: Sequence[Expression | int | integer | bool] | ndarray | None = None, demand: Sequence[Expression | int | integer | bool] | ndarray | Expression | int | integer | bool | None = None, capacity: Expression | int | integer | bool | None = None, is_present: Sequence[Expression | bool | bool] | ndarray | None = None)[source]

Generalization of the Cumulative constraint which allows for optional tasks. A task is only scheduled if the corresponing is_present variable is set to True.

If the task is present, the constraint enforces that: - duration >= 0 - demand >= 0 - start + duration == end

If the task is not present, the constraint does not enforce any of the above.

Equivalent to NoOverlapOptional when demand and capacity are equal to 1. Supports both varying demand across tasks or equal demand for all jobs.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose(how: str = 'auto') tuple[list[Expression], list[Expression]][source]

Decompose the Cumulative constraint Support time-based decomposition or task-based decomposition. By default, we heuristically select the best decomposition based on the number of tasks and the horizon.

Parameters:

how (str) – how the cumulative constraint should be decomposed, can be “time”, “task”, or “auto” (default)

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.Decreasing(*args: Expression | int | integer | bool | Sequence[Expression | int | integer | bool] | ndarray)[source]

Enforces that the expressions are assigned to (non-strictly) decreasing values.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[list[Expression], list[Expression]][source]

Decomposition of the Decreasing constraint.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.DecreasingStrict(*args: Expression | int | integer | bool | Sequence[Expression | int | integer | bool] | ndarray)[source]

Enforces that the expressions are assigned to strictly decreasing values.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[list[Expression], list[Expression]][source]

Decomposition of the DecreasingStrict constraint.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.DirectConstraint(name: str, arguments: tuple[Any, ...], novar: Sequence[int] | ndarray | None = None)[source]

A DirectConstraint will directly call a function of the underlying solver when added to a CPMpy solver

It can not be reified, it is not flattened, it can not contain other CPMpy expressions than variables. When added to a CPMpy solver, it will literally just directly call a function on the underlying solver, replacing CPMpy variables by solver variables along the way.

See the documentation of the solver (constructor) for details on how that solver handles them.

If you want/need to use what the solver returns (e.g. an identifier for use in other constraints), then use directvar() instead, or access the solver object from the solver interface directly.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

callSolver(CPMpy_solver: SolverInterface, Native_solver: Any) Any[source]

Call the directname() function of the native solver, with stored arguments replacing CPMpy variables with solver variables as needed.

SolverInterfaces will call this function when this constraint is added.

Parameters:
  • CPMpy_solver – a CPM_solver object, that has a solver_vars() function

  • Native_solver – the python interface to some specific solver

Returns:

the response of the solver when calling the function

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool[source]

is it a Boolean (return type) Operator?

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

class cpmpy.expressions.Division(x: Expression | int | integer | bool, y: Expression | int | integer | bool)[source]

Computes the integer division of the arguments, rounding towards zero: int(x/y)

Warning: this is different from the Python’s floor division operator //, which floors the result: floor(x/y)

The difference exposes itself with negative numbers: -7/3 = -2.333..;
  • integer division (ours): -7 div 3 = int(-7/3) = -2 (truncation)

  • floor division (Python): -7 // 3 = math.floor(-7/3) = -3

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose()[source]

Decomposition of Integer Division global function, rounding towards zero.

x div y = q implemented as x = y * q + r with r the remainder and |r| < |y| r can be positive or negative, so also ensure that |y| * |q| <= |x|

Returns:

A tuple containing the auxiliary variable representing the integer division, and a list of constraints defining it

Return type:

tuple[Expression, list[Expression]]

decompose_comparison(cmp_op: str, cmp_rhs: Expression) tuple[list[Expression], list[Expression]]

DEPRECATED: returns a list of constraints representing the decomposed comparison of the global function (and any auxiliary variables introduced).

Parameters:
  • cmp_op (str) – Comparison operator

  • cmp_rhs (Expression) – Right-hand side expression for the comparison

Returns:

A tuple containing two lists: constraints representing the comparison, and constraints defining auxiliary variables

Return type:

tuple[list[Expression], list[Expression]]

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds()[source]

Returns the bounds of the Division global function

Returns:

A tuple of (lower bound, upper bound) for the integer division

Return type:

tuple[int, int]

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool
Returns:

False, global functions are numeric

Return type:

bool

is_total() bool

Returns whether it is a total function. If true, its value is defined for all arguments

TODO: I do not find anywhere where we set it dynamically to False? TODO: REMOVE??

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value()[source]
Returns:

The integer division of the arguments, or None if the arguments are not assigned

Return type:

int

class cpmpy.expressions.Element(arr: Sequence[Expression | int | integer | bool] | ndarray, idx: Expression)[source]

The Element(Arr, Idx) global function allows indexing into an array with a decision variable.

Its return value will be the value of the array element at the index specified by the decision variable’s value.

When you index into a NDVarArray (e.g. when creating a Arr=boolvar(shape=…) or Arr=intvar(lb,ub, shape=…) using boolvar() or intvar()), or index into a list wrapped as Arr = cpm_array(lst) using cpm_array(), then using standard Python indexing, e.g. Arr[Idx] with Idx an integer decision variable, will automatically create this Element(Arr, Idx) object.

Note: because Element is a numeric global function, the return type of the Element function is always numeric, even if Arr only contains Boolean variables.

Note: Element only supports 1D arrays; use NDElement for multi-dimensional indexing.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[Expression, list[Expression]][source]

Decomposition of Element global function.

The index variable must be within the bounds of the array.

This decomposition uses an auxiliary variable and implication constraints.

Returns:

A tuple containing the auxiliary variable representing the element value, and a list of constraints defining it

Return type:

tuple[Expression, list[Expression]]

decompose_comparison(cmp_op: str, cmp_rhs: Expression) tuple[list[Expression], list[Expression]]

DEPRECATED: returns a list of constraints representing the decomposed comparison of the global function (and any auxiliary variables introduced).

Parameters:
  • cmp_op (str) – Comparison operator

  • cmp_rhs (Expression) – Right-hand side expression for the comparison

Returns:

A tuple containing two lists: constraints representing the comparison, and constraints defining auxiliary variables

Return type:

tuple[list[Expression], list[Expression]]

decompose_linear() tuple[Expression, list[Expression]][source]

Decomposition of Element global function.

The index variable must be within the bounds of the array.

This decomposition uses a weighted sum over the array elements times Boolean indicator for the index.

Returns:

A tuple containing the expression representing the element value, and an empty list of constraints (no auxiliary variables needed)

Return type:

tuple[Expression, list[Expression]]

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int][source]

Returns the bounds of the global function

Returns:

A tuple of (lower bound, upper bound) for the element value

Return type:

tuple[int, int]

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool
Returns:

False, global functions are numeric

Return type:

bool

is_total() bool

Returns whether it is a total function. If true, its value is defined for all arguments

TODO: I do not find anywhere where we set it dynamically to False? TODO: REMOVE??

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() int | None[source]
Returns:

The value of the array element at the given index, or None if the index is not assigned or the array element is not assigned

Return type:

Optional[int]

class cpmpy.expressions.FloatSum(coeffs: Sequence[float | floating] | ndarray, vars: Sequence[_NumVarImpl] | ndarray, const: float | floating = 0.0)[source]

Objective-only weighted sum with float coefficients over decision variables.

Does not inherit from Expression because it is objective only and has float value().

Pass to solver s.minimize() / s.maximize() only. Supported solvers declare Expression | FloatSum on those methods (e.g. ortools, minizinc, z3, hexaly and the MIP solvers).

After solve, use value() for the objective value. s.objective_value() is None when the native result is not integral.

Accepts only (numpy) floats as coefficients, decision variables (including NegBoolView) as terms, and an optional float constant term (default 0.0).

components(allow_negbool=False) tuple[ndarray, NDVarArray, float][source]

Return (coeffs, vars, const)

if allow_negbool is False (default), we will eliminate all NegBoolView w * ~bv becomes w - w * bv (coeff -w on bv._bv, constant +w).

class cpmpy.expressions.GlobalCardinalityCount(vars: Sequence[Expression | int | integer | bool] | ndarray, vals: Sequence[int | integer] | ndarray, occ: Sequence[Expression | int | integer | bool] | ndarray, closed: bool = False)[source]

Enforces that the number of occurrences of each value vals[i] in the list of variables vars is equal to occ[i].

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[list[Expression], list[Expression]][source]

Decomposition of the GlobalCardinalityCount constraint. Uses a conjunction of Count global function constraints.

Same as the one MiniZinc uses: https://github.com/MiniZinc/libminizinc/blob/master/share/minizinc/std/fzn_global_cardinality.mzn

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.IfThenElse(condition: Expression | bool | bool, if_true: Expression | bool | bool, if_false: Expression | bool | bool)[source]

Enforces a conditional expression of the form: if condition then if_true else if_false. condition, if_true and if_false are be boolean expressions.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[list[Expression], list[Expression]][source]

Decomposition of the IfThenElse global constraint. Enforces that the condition is satisfied. ” :returns: A tuple containing the constraints representing the constraint value and the defining constraints :rtype: tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.InDomain(expr: Expression, arr: Iterable[int | integer])[source]

Enforces the expression is assigned to a value in the given domain.

property args: tuple[Expression, ndarray]

READ-ONLY, the well-tuped arguments of this global constraint

decompose() tuple[list[Expression], list[Expression]][source]

Decomposition of the InDomain global constraint. Enforces that the expression is assigned to a value in the given domain.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_linear() tuple[list[Expression], list[Expression]][source]

Linear decomposition of the InDomain global constraint. Avoids != constraints and instead decomposes into a large disjunction. If expr is a variable (the most common case), cpmpy.transformations.linearize.linearize_reified_varvals will then encode this variable with a direct encoding

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression[source]

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.Increasing(*args: Expression | int | integer | bool | Sequence[Expression | int | integer | bool] | ndarray)[source]

Enforces that the expressions are assigned to (non-strictly) increasing values.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[list[Expression], list[Expression]][source]

Decomposition of the Increasing constraint.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.IncreasingStrict(*args: Expression | int | integer | bool | Sequence[Expression | int | integer | bool] | ndarray)[source]

Enforces that the expressions are assigned to strictly increasing values.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[list[Expression], list[Expression]][source]

Decomposition of the IncreasingStrict constraint.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

cpmpy.expressions.IntVar(lb, ub, shape=1, name=None)[source]

Deprecated since version 0.9.0: Please use intvar() instead.

class cpmpy.expressions.Inverse(fwd: Sequence[Expression | int | integer | bool] | ndarray, rev: Sequence[Expression | int | integer | bool] | ndarray)[source]

Enforces that the forward and reverse arrays represent the inverse function of one another. I.e., fwd[i] == x <==> rev[x] == i

Also known as channeling / assignment constraint.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[list[Expression], list[Expression]][source]

Decomposition of the Inverse global constraint using Element global function constraints, and explicit safening.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.LexChainLess(X: Sequence[Sequence[Expression | int | integer | bool] | ndarray] | ndarray)[source]

Enforces that all rows of the matrix are lexicographically ordered.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[list[Expression], list[Expression]][source]

Decomposition of the LexChainLess constraint.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.LexChainLessEq(X: Sequence[Sequence[Expression | int | integer | bool] | ndarray] | ndarray)[source]

Enforces that all rows of the matrix are lexicographically ordered (less or equal)

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[list[Expression], list[Expression]][source]

Decompose to a series of LexLessEq constraints between subsequent rows

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.LexLess(list1: Sequence[Expression | int | integer | bool] | ndarray, list2: Sequence[Expression | int | integer | bool] | ndarray)[source]

Enforces that the first list is lexicographically smaller than the second list.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[list[Expression], list[Expression]][source]

Implementation inspired by Hakan Kjellerstrand (http://hakank.org/cpmpy/cpmpy_hakank.py)

The decomposition creates auxiliary Boolean variables and constraints that collectively ensure X is lexicographically less than Y The auxiliary boolean vars are defined to represent if the given lists are lexicographically ordered (less or equal) up to the given index. Decomposition enforces through the constraining part that the first boolean variable needs to be true, and thus through the defining part it is enforced that if it is not strictly lexicographically less in a given index, then next index must be lexicographically less or equal. It needs to be strictly less in at least one index.

The use of auxiliary Boolean variables bvar ensures that the constraints propagate immediately, maintaining arc-consistency. Each bvar[i] enforces the lexicographic ordering at each position, ensuring that every value in the domain of X[i] can be extended to a consistent value in the domain of $Y_i$ for all subsequent positions.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.LexLessEq(list1: Sequence[Expression | int | integer | bool] | ndarray, list2: Sequence[Expression | int | integer | bool] | ndarray)[source]

Enforces that the first list is lexicographically smaller than or equal to the second list.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[list[Expression], list[Expression]][source]

Implementation inspired by Hakan Kjellerstrand (http://hakank.org/cpmpy/cpmpy_hakank.py)

The decomposition creates auxiliary Boolean variables and constraints that collectively ensure X is lexicographically less than Y The auxiliary boolean vars are defined to represent if the given lists are lexicographically ordered (less or equal) up to the given index. Decomposition enforces through the constraining part that the first boolean variable needs to be true, and thus through the defining part it is enforced that if it is not strictly lexicographically less in a given index, then next index must be lexicographically less or equal.

The use of auxiliary Boolean variables bvar ensures that the constraints propagate immediately, maintaining arc-consistency. Each bvar[i] enforces the lexicographic ordering at each position, ensuring that every value in the domain of X[i] can be extended to a consistent value in the domain of $Y_i$ for all subsequent positions.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.MDD(array: Sequence[Expression] | ndarray, transitions: Sequence[tuple[int | str, int, int | str]] | ndarray, start: str | int | None = None, reduce: bool = True)[source]

An MDD is a Multi-valued Decision Diagram, represented as an acyclic layered graph, with a single root node, and a single accepting sink node. The constraint takes as input an array of n integer variables and an MDD with n+1 layers, represented through a table of “(from_node, value, to_node)” entries, one for every arc in the MDD. The MDD constraint is satisfied when the values in the array correspond to a path in the MDD starting from the root node, and where the first variable in the array takes the value of the first edge, the second from the second edge, etc., ending in the accepting sink node.

The transitions/edges are given by a n x 3 matrix, or more precisely a list of n tuples (node_id1, value, node_id2). A node_id is an integer or string representing a state in the MDD, and value is an integer representing the value of the variable in the sequence. If not given explicitly, the root node is the node_id1 of the first entry in the transition table (i.e., transitions[0][0]). The root node is at level 0, the sink node is the only node on level n.

Example: the following MDD accepts the solutions [1,1,1], [2,2,1] and [2,3,2] for the three variables x,y,z. The root node is “A” and the sink node is “F”. cp.MDD(array = [x,y,z],

transitions = [(“A”, 1, “B”),

(“A”, 2, “C”), (“B”, 1, “D”), (“C”, 2, “D”), (“C”, 3, “E”), (“D”, 1, “F”), (“E”, 2, “F”)])

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose(complete=True) tuple[list[Expression], list[Expression]][source]

Flow decomposition of the MDD global constraint. Enforces that the condition is satisfied, by ensuring that the flow in equals the flow out for every node. To do this, we introduce auxiliary boolean variables for every edge in the MDD, use them in flow constraints, and link them to all variable assignments in the array.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints.

Return type:

tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]][source]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.Maximum(arg_list: Sequence[Expression | int | integer | bool] | ndarray)[source]

Computes the maximum value of the arguments

property args: tuple[int | Expression, ...]

READ-ONLY, well-typed argument of this global function, no numpy ints

decompose() tuple[Expression, list[Expression]][source]

Decomposition of Maximum global function.

Can only be decomposed by introducing an auxiliary variable and enforcing it to be larger or equal than each variable, while at the same time not being larger than all (e.g. it needs to be (smaller or) equal to one of them)

Returns:

A tuple containing the auxiliary variable representing the maximum value, and a list of constraints defining it

Return type:

tuple[Expression, list[Expression]]

decompose_comparison(cmp_op: str, cmp_rhs: Expression) tuple[list[Expression], list[Expression]]

DEPRECATED: returns a list of constraints representing the decomposed comparison of the global function (and any auxiliary variables introduced).

Parameters:
  • cmp_op (str) – Comparison operator

  • cmp_rhs (Expression) – Right-hand side expression for the comparison

Returns:

A tuple containing two lists: constraints representing the comparison, and constraints defining auxiliary variables

Return type:

tuple[list[Expression], list[Expression]]

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int][source]

Returns the lowest and highest possible maximum value

Returns:

A tuple of (lower bound, upper bound) for the maximum value

Return type:

tuple[int, int]

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool
Returns:

False, global functions are numeric

Return type:

bool

is_total() bool

Returns whether it is a total function. If true, its value is defined for all arguments

TODO: I do not find anywhere where we set it dynamically to False? TODO: REMOVE??

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() int | None[source]
Returns:

The maximum value of the arguments, or None if any argument is not assigned

Return type:

Optional[int]

class cpmpy.expressions.Minimum(arg_list: Sequence[Expression | int | integer | bool] | ndarray)[source]

Computes the minimum value of the arguments

property args: tuple[int | Expression, ...]

READ-ONLY, well-typed argument of this global function, no numpy ints

decompose() tuple[Expression, list[Expression]][source]

Decomposition of Minimum global function.

Can only be decomposed by introducing an auxiliary variable and enforcing it to be smaller or equal than each variable, while at the same time not being smaller than all (e.g. it needs to be (larger or) equal to one of them)

Returns:

A tuple containing the auxiliary variable representing the minimum value, and a list of constraints defining it

Return type:

tuple[Expression, list[Expression]]

decompose_comparison(cmp_op: str, cmp_rhs: Expression) tuple[list[Expression], list[Expression]]

DEPRECATED: returns a list of constraints representing the decomposed comparison of the global function (and any auxiliary variables introduced).

Parameters:
  • cmp_op (str) – Comparison operator

  • cmp_rhs (Expression) – Right-hand side expression for the comparison

Returns:

A tuple containing two lists: constraints representing the comparison, and constraints defining auxiliary variables

Return type:

tuple[list[Expression], list[Expression]]

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int][source]

Returns the lowest and highest possible minimum value

Returns:

A tuple of (lower bound, upper bound) for the minimum value

Return type:

tuple[int, int]

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool
Returns:

False, global functions are numeric

Return type:

bool

is_total() bool

Returns whether it is a total function. If true, its value is defined for all arguments

TODO: I do not find anywhere where we set it dynamically to False? TODO: REMOVE??

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() int | None[source]
Returns:

The minimum value of the arguments, or None if any argument is not assigned

Return type:

Optional[int]

class cpmpy.expressions.Modulo(x: Expression | int | integer | bool, y: Expression | int | integer | bool)[source]

Computes the modulo of the arguments, the remainder with integer division (rounding towards zero): x - (y * (x div y))

Warning: this is different from the Python’s modulo operator %, which gives the remainder of the float division x / y

There is also a difference in sign when using negative numbers:
  • modulo (ours): 7 mod -5 = 2 because 7 div -5 = -1 and 7 - (-5*-1) = 2. Note how the sign of x is preserved.

  • modulo (Python): 7 % -5 = -3 because 7 // -5 = -2 and 7 - (-5*-2) = -3. Note how the sign of y is preserved.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose()[source]

Decomposition of Modulo global function, using integer division (rounding towards zero)

Decomposes x mod y = z as x = k * y + z with |z| < |y| and sign(x) = sign(z) https://en.wikipedia.org/wiki/Modulo https://marcelkliemannel.com/articles/2021/dont-confuse-integer-division-with-floor-division/

decompose_comparison(cmp_op: str, cmp_rhs: Expression) tuple[list[Expression], list[Expression]]

DEPRECATED: returns a list of constraints representing the decomposed comparison of the global function (and any auxiliary variables introduced).

Parameters:
  • cmp_op (str) – Comparison operator

  • cmp_rhs (Expression) – Right-hand side expression for the comparison

Returns:

A tuple containing two lists: constraints representing the comparison, and constraints defining auxiliary variables

Return type:

tuple[list[Expression], list[Expression]]

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds()[source]

Returns the bounds of the Modulo global function

Returns:

A tuple of (lower bound, upper bound) for the modulo

Return type:

tuple[int, int]

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool
Returns:

False, global functions are numeric

Return type:

bool

is_total() bool

Returns whether it is a total function. If true, its value is defined for all arguments

TODO: I do not find anywhere where we set it dynamically to False? TODO: REMOVE??

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value()[source]
Returns:

The modulo of the arguments, or None if the arguments are not assigned

Return type:

int

class cpmpy.expressions.Multiplication(x: Expression | int | integer | bool, y: Expression | int | integer | bool)[source]

Computes the product of two expressions: x * y.

Created when the user writes * with at least one variable (e.g. x * y, 2 * x). Supports decomposition into linear constraints for MIP solvers via decompose().

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[Expression, list[Expression]][source]

Decomposition of Multiplication into linear constraints (e.g. for MIP).

  • If is_lhs_num (const*expr): returns the wsum equivalent and no extra constraints.

  • If both args are Boolean (0/1): bv*bv equals bv&bv (logical AND), so returns that and no extra constraints.

  • If one bool and one int: introduces aux z = bv*iv with (bv -> z==iv) & (~bv -> z==0), returns (z, constraints).

  • If both int: take the factor with smallest domain, encode it with one bool per value, then decompose into b_i*other_int constraints and sum(i*z_i)

decompose_comparison(cmp_op: str, cmp_rhs: Expression) tuple[list[Expression], list[Expression]]

DEPRECATED: returns a list of constraints representing the decomposed comparison of the global function (and any auxiliary variables introduced).

Parameters:
  • cmp_op (str) – Comparison operator

  • cmp_rhs (Expression) – Right-hand side expression for the comparison

Returns:

A tuple containing two lists: constraints representing the comparison, and constraints defining auxiliary variables

Return type:

tuple[list[Expression], list[Expression]]

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int][source]

Bounds of the product from bounds of the factors.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool
Returns:

False, global functions are numeric

Return type:

bool

is_total() bool

Returns whether it is a total function. If true, its value is defined for all arguments

TODO: I do not find anywhere where we set it dynamically to False? TODO: REMOVE??

update_args(args)[source]

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

class cpmpy.expressions.NDElement(arr: Sequence[Expression | int | integer | bool] | ndarray, indices: Sequence[Expression] | ndarray)[source]

The NDElement(Arr, Indices) global function allows indexing into a multi-dimensional array with multiple decision variables.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[Expression, list[Expression]][source]

Decomposition of NDElement global function.

Rewritten as 1-D Element with a linear index into the flattened array (offset 0). Example: 2x3 array arr = [[10, 20, 30], [40, 50, 60]] and indices (1, 2) gives arr[1, 2] == 60. After Decomposing to 1-D Element, arr.reshape(-1) is [10, 20, 30, 40, 50, 60] and the linear index is 1*3 + 2 = 5.

Symbolically, for a AxB array and expression indices (x,y) the linear index is x*B + y.

More generally, for an N-dimensional array with sizes D1,D2,…,Dn and expression indices (X1,X2,...,Xn) the linear index is X1*(D2*...*Dn) + X2*(D3*...*Dn) + ... + X(n-1)*Dn + Xn.

Returns:

The Element expression and an empty list of defining constraints

Return type:

tuple[Expression, list[Expression]]

decompose_comparison(cmp_op: str, cmp_rhs: Expression) tuple[list[Expression], list[Expression]]

DEPRECATED: returns a list of constraints representing the decomposed comparison of the global function (and any auxiliary variables introduced).

Parameters:
  • cmp_op (str) – Comparison operator

  • cmp_rhs (Expression) – Right-hand side expression for the comparison

Returns:

A tuple containing two lists: constraints representing the comparison, and constraints defining auxiliary variables

Return type:

tuple[list[Expression], list[Expression]]

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int][source]

Returns the bounds of the global function

Returns:

A tuple of (lower bound, upper bound) for the element value

Return type:

tuple[int, int]

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool
Returns:

False, global functions are numeric

Return type:

bool

is_total() bool

Returns whether it is a total function. If true, its value is defined for all arguments

TODO: I do not find anywhere where we set it dynamically to False? TODO: REMOVE??

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() int | None[source]
Returns:

The value of the array element at the given indices, or None if any index is not assigned or the array element is not assigned

Return type:

Optional[int]

class cpmpy.expressions.NValue(arr: Sequence[Expression | int | integer | bool] | ndarray)[source]

The NValue global function counts the number of distinct values in an array.

For example, if variables [x1, x2, x3, x4] take values [1, 2, 1, 3] respectively, then NValue([x1, x2, x3, x4]) returns 3 (the distinct values are 1, 2, and 3).

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[Expression, list[Expression]][source]

Decomposition of the NValue global function.

NValue is decomposed by checking, for each possible value in the domain range, whether at least one variable takes that value. The sum of these Boolean checks gives the number of distinct values.

Based on “simple decomposition” from:

Bessiere, Christian, et al. “Decomposition of the NValue constraint.” International Conference on Principles and Practice of Constraint Programming. Berlin, Heidelberg: Springer Berlin Heidelberg, 2010.

Returns:

A tuple containing the sum expression representing the number of distinct values, and an empty list of constraints (no auxiliary variables needed)

Return type:

tuple[Expression, list[Expression]]

decompose_comparison(cmp_op: str, cmp_rhs: Expression) tuple[list[Expression], list[Expression]]

DEPRECATED: returns a list of constraints representing the decomposed comparison of the global function (and any auxiliary variables introduced).

Parameters:
  • cmp_op (str) – Comparison operator

  • cmp_rhs (Expression) – Right-hand side expression for the comparison

Returns:

A tuple containing two lists: constraints representing the comparison, and constraints defining auxiliary variables

Return type:

tuple[list[Expression], list[Expression]]

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int][source]

Returns the bounds of the global function

Returns:

A tuple of (lower bound, upper bound) for the number of distinct values

Return type:

tuple[int, int]

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool
Returns:

False, global functions are numeric

Return type:

bool

is_total() bool

Returns whether it is a total function. If true, its value is defined for all arguments

TODO: I do not find anywhere where we set it dynamically to False? TODO: REMOVE??

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() int | None[source]
Returns:

The number of distinct values in the array, or None if any element in arr is not assigned

Return type:

Optional[int]

class cpmpy.expressions.NValueExcept(arr: Sequence[Expression | int | integer | bool] | ndarray, n: int | integer)[source]

The NValueExcept global function counts the number of distinct values in an array, excluding a specified value.

For example, if variables [x1, x2, x3, x4] take values [1, 2, 1, 0] respectively, then NValueExcept([x1, x2, x3, x4], 0) returns 2 (the distinct values are 1 and 2, excluding 0).

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[Expression, list[Expression]][source]

Decomposition of the NValueExcept global function.

NValueExcept is decomposed similarly to NValue, by checking for each possible value in the domain range (except the excluded value n) whether at least one variable takes that value, and counting for how many values that was the case.

Returns:

A tuple containing the sum expression representing the number of distinct values (excluding n), and an empty list of constraints (no auxiliary variables needed)

Return type:

tuple[Expression, list[Expression]]

decompose_comparison(cmp_op: str, cmp_rhs: Expression) tuple[list[Expression], list[Expression]]

DEPRECATED: returns a list of constraints representing the decomposed comparison of the global function (and any auxiliary variables introduced).

Parameters:
  • cmp_op (str) – Comparison operator

  • cmp_rhs (Expression) – Right-hand side expression for the comparison

Returns:

A tuple containing two lists: constraints representing the comparison, and constraints defining auxiliary variables

Return type:

tuple[list[Expression], list[Expression]]

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int][source]

Returns the bounds of the global function

Returns:

A tuple of (lower bound, upper bound) for the number of distinct values (excluding n)

Return type:

tuple[int, int]

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool
Returns:

False, global functions are numeric

Return type:

bool

is_total() bool

Returns whether it is a total function. If true, its value is defined for all arguments

TODO: I do not find anywhere where we set it dynamically to False? TODO: REMOVE??

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() int | None[source]
Returns:

The number of distinct values in the array, excluding value n, or None if any element in arr is not assigned

Return type:

Optional[int]

class cpmpy.expressions.NegativeTable(array: Sequence[Expression] | ndarray, table: Sequence[Sequence[int] | ndarray] | ndarray)[source]

The values of the variables in ‘array’ do not correspond to any row in ‘table’.

property args: tuple[Sequence[Expression] | ndarray, ndarray]

READ-ONLY, the well-tuped arguments of this global constraint

decompose() tuple[list[Expression], list[Expression]][source]

Decomposition of the NegativeTable global constraint. Enforces that the values of the variables in ‘array’ do not correspond to any row in ‘table’.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression[source]

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.NoOverlap(start: Sequence[Expression | int | integer | bool] | ndarray, duration: Sequence[Expression | int | integer | bool] | ndarray, end: Sequence[Expression | int | integer | bool] | ndarray | None = None)[source]
Enforces that a set of tasks are scheduled without overlapping, and enforces:
  • duration >= 0

  • start + duration == end

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[list[Expression], list[Expression]][source]

Decomposition of the NoOverlap constraint, using pairwise no-overlap constraints.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.NoOverlapOptional(start: Sequence[Expression | int | integer | bool] | ndarray, duration: Sequence[Expression | int | integer | bool] | ndarray, end: Sequence[Expression | int | integer | bool] | ndarray | None = None, is_present: Sequence[Expression | bool | bool] | ndarray | None = None)[source]

Generalization of the NoOverlap constraint which allows for optional tasks. A task is only scheduled if the corresponing is_present variable is set to True.

The constraint enforces that all present tasks are scheduled without overlapping, and for each present task, the constraint enforces that: - duration >= 0 - demand >= 0 - start + duration == end

if the task is not present, it does not enforce any of the above.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[list[Expression], list[Expression]][source]

Decomposition of the NoOverlap constraint, using pairwise no-overlap constraints.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[Sequence[Expression], Sequence[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.Power(base: Expression | int | integer | bool, exponent: int | integer)[source]

Computes the power of the arguments, the base raised to the exponent: base ** exponent

Only non-negative constant integer exponents are supported.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose()[source]

Decomposition of Power global function, using integer multiplication.

Decomposes base ** exp = _pow as _pow = base * base * … * base (exp times)

Returns:

A tuple containing the auxiliary variable representing the power, and a list of constraints defining it

Return type:

tuple[Expression, list[Expression]]

decompose_comparison(cmp_op: str, cmp_rhs: Expression) tuple[list[Expression], list[Expression]]

DEPRECATED: returns a list of constraints representing the decomposed comparison of the global function (and any auxiliary variables introduced).

Parameters:
  • cmp_op (str) – Comparison operator

  • cmp_rhs (Expression) – Right-hand side expression for the comparison

Returns:

A tuple containing two lists: constraints representing the comparison, and constraints defining auxiliary variables

Return type:

tuple[list[Expression], list[Expression]]

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds()[source]

Returns the bounds of the Power global function

Returns:

A tuple of (lower bound, upper bound) for the power

Return type:

tuple[int, int]

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool
Returns:

False, global functions are numeric

Return type:

bool

is_total() bool

Returns whether it is a total function. If true, its value is defined for all arguments

TODO: I do not find anywhere where we set it dynamically to False? TODO: REMOVE??

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value()[source]
Returns:

The power of the arguments, or None if the arguments are not assigned

Return type:

int

class cpmpy.expressions.Precedence(vars: Sequence[Expression | int | integer | bool] | ndarray, precedence: Sequence[int | integer] | ndarray)[source]

Enforces a precedence relationship between a set of variables. Given an array of variables X and a list of values P, values in P must appear in X in the order specified by P. I.e., if X[i] = P[j+1], then there exists a X[i’] = P[j] with i’ < i

Examples

  • X = [1,2,1,3] satisfies the precedence [1,2,3].

  • X = [4,1,2,1,3] also satisfies the precedence, as values not appearing in P can appear in any order.

  • X = [2,1,3] does not satisfy the precedence, as 1 does not appear before 2.

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[list[Expression], list[Expression]][source]

Decomposition based on: Law, Yat Chiu, and Jimmy HM Lee. “Global constraints for integer and set value precedence.” Principles and Practice of Constraint Programming–CP 2004: 10th International Conference, CP 2004

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.Regular(array: Sequence[Expression] | ndarray, transitions: Sequence[tuple[int | str, int, int | str]] | ndarray, start: int | str, accepting: Sequence[int | str] | ndarray)[source]

Regular-constraint (or Automaton-constraint) Takes as input a sequence of variables and a automaton representation using a transition table. The constraint is satisfied if the sequence of variables corresponds to an accepting path in the automaton.

The automaton is defined by a list of transitions, a starting node and a list of accepting nodes. The transitions are represented as a list of tuples, where each tuple is of the form (id1, value, id2). An id is an integer or string representing a state in the automaton, and value is an integer representing the value of the variable in the sequence. The starting node is an integer or string representing the starting state of the automaton. The accepting nodes are a list of integers or strings representing the accepting states of the automaton.

Example: an automaton that accepts the language 0*10* (exactly 1 variable taking value 1) is defined as:
cp.Regular(array = cp.intvar(0,1, shape=4),

transitions = [(“A”,0,”A”), (“A”,1,”B”), (“B”,0,”C”), (“C”,0,”C”)], start = “A”, accepting = [“C”])

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose(complete=True) tuple[list[Expression], list[Expression]][source]

Decomposition of the Regular global constraint. Encodes the automaton by encoding the transition table into class:cpmpy.expressions.globalconstraints.Table constraints. Then enforces that the last state is accepting.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_linear(complete=True) tuple[list[Expression], list[Expression]][source]

Deterministic Finite Automata (DFA) MIP decomposition using flow constraints based on Côté et al. (2007): “Modeling the Regular Constraint with Integer Programming”

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]][source]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.ShortTable(array: Sequence[Expression] | ndarray, table: Sequence[Sequence[int | Literal['*']] | ndarray] | ndarray)[source]

Extension of the Table constraint where the table matrix may contain wildcards (STAR), meaning there are no restrictions for the corresponding variable in that tuple.

property args: tuple[Sequence[Expression] | ndarray, ndarray]

READ-ONLY, the well-tuped arguments of this global constraint

decompose() tuple[list[Expression], list[Expression]][source]

Decomposition of the ShortTable global constraint. Enforces at least one row of the table is assigned to the array.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]][source]

Positive decomposition of the ShortTable global constraint.

Similar to element from Gleb’s paper: “Improved Linearization of Constraint Programming Models”

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.Table(array: Sequence[Expression] | ndarray, table: Sequence[Sequence[int] | ndarray] | ndarray)[source]

Enforces that the values of the variables in ‘array’ correspond to a row in ‘table’.

property args: tuple[Sequence[Expression] | ndarray, ndarray]

READ-ONLY, the well-tuped arguments of this global constraint

decompose() tuple[list[Expression], list[Expression]][source]

Decomposition of the Table global constraint. Enforces at least one row of the table is assigned to the array.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_linear(heuristic: str = 'domain') tuple[list[Expression], list[Expression]][source]

Linear-friendly decomposition of the Table global constraint using an MDD, which is subsequently decomposed into linear flow constraints. Based on:

Bierlee, H., Piessens, W., Stuckey, P., & Guns, T. (CP 2026). Table Constraints for Integer Programming. In Leibniz International Proceedings in Informatics. Schloss Dagstuhl – Leibniz-Zentrum fuer Informatik.

Returns:

tuple[list[Expression], list[Expression]]: A tuple containing the constraints representing the constraint value and the defining constraints

decompose_positive() tuple[list[Expression], list[Expression]][source]

Positive decomposition of the Table global constraint.

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression[source]

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

value() bool | None[source]
Returns:

True if the global constraint is satisfied, False otherwise, or None if any argument is not assigned

Return type:

Optional[bool]

class cpmpy.expressions.Xor(arg_list: Sequence[Expression | bool | bool] | ndarray)[source]

Enforces the exclusive-or relation of the arguments. Supports n-ary xor-constraints, which are treated as cascaed binary xor-constraints. Equivalent to sum(args) % 2 == 1

property args: tuple[Any, ...]

READ-ONLY access to the expression’s arguments. Use update_args() to update the arguments.

Subclasses can override this property to return a more precisely typed tuple.

decompose() tuple[list[Expression], list[Expression]][source]

Decomposition of the Xor global constraint. Recursively decomposes the constraint into a chain of sums. E.g., xor(a,b,c) :: (((a + b) == 1) + c) == 1

Returns:

A tuple containing the constraints representing the constraint value and the defining constraints

Return type:

tuple[list[Expression], list[Expression]]

decompose_positive() tuple[list[Expression], list[Expression]]

Positive decomposition of the global constraint, only valid when the constraint is posted toplevel or occurs in a positive nested context. Defaults to the standard decomposition, but subclasses can implement a better version.

deepcopy(memodict={})

DEPRECATED: use copy.deepcopy() instead

Will be removed in stable version.

get_bounds() tuple[int, int]

Returns the bounds of a Boolean global constraint. Numerical global constraints should reimplement this.

has_subexpr() bool

Does it contain nested Expressions (anything other than a _NumVarImpl or a constant)? Is of importance when deciding whether certain transformations are needed along particular paths of the expression tree. Results are cached for future calls and reset when the expression changes (in-place argument update).

implies(other: Expression | bool | bool, simplify: bool = False) Expression

Implication constraint: self -> other.

Python does not offer relevant syntax for implication, call this method instead. For double reification (<->), use equivalence self == other.

Parameters:
  • other (BoolExprLike) – the right-hand-side of the implication

  • simplify (bool) – if True, simplify by eliminating True/False constants (might remove expressions & their variables from user-view)

Returns:

the implication constraint or a BoolVal if simplified

Return type:

Expression

Simplification rules:
  • self -> True :: BoolVal(True)

  • self -> False :: ~self (Boolean inversion)

is_bool() bool

Returns whether the global constraint is a Boolean (return type) Operator.

Returns:

True, global constraints are Boolean

Return type:

bool

negate() Expression[source]

Returns the negation of this global constraint. Defaults to ~self, but subclasses can implement a better version, > Fages, François, and Sylvain Soliman. Reifying global constraints. Diss. INRIA, 2012.

update_args(args: Iterable[Any], has_subexpr: bool | None = None) None

Allows in-place update of the expression’s arguments. Resets all cached computations which depend on the expression tree.

  • args (Iterable[Any]): new arguments

  • has_subexpr (Optional[bool]): provide this if you know the answer already, to avoid computing it

cpmpy.expressions.abs(element)[source]

abs() overwrites the python built-in to support decision variables.

if the element given is not a CPMpy expression, the built-in is called else an Absolute functional global constraint is constructed.

cpmpy.expressions.all(iterable)[source]

all() overwrites python built-in, if iterable contains any Expression, then returns an Operator(“and”, iterable) otherwise returns whether all of the arguments are true

cpmpy.expressions.any(iterable)[source]

any() overwrites python built-in, if iterable contains an Expression, then returns an Operator(“or”, iterable) otherwise returns whether any of the arguments is true

cpmpy.expressions.boolvar(shape: Literal[1] = 1, name: str | None = None) _BoolVarImpl[source]
cpmpy.expressions.boolvar(shape: int | integer | tuple[int | integer, ...] = 1, name: str | Sequence[str] | ndarray | None = None) NDVarArray

Create Boolean decision variables that take either the value True or False.

Parameters:
  • shape (int or tuple of int, optional) – The shape of the n-dimensional array of variables. Default is 1.

  • name (str, list of str, tuple of str, or None, optional) –

    Name(s) to assign to the variables. Default is None.

    • If name is None, a name of the form BV<unique number> will be assigned to the variables.

    • If name is a string, it will be used as the suffix of the variable names.

    • If name is a list/tuple/array of strings, it must match the shape of the variables,

      and they will be assigned to the variable names accordingly.

Notes

  • If shape is not 1, each element of the array will have its specific location appended to its name.

  • Examples:
    • boolvar(shape=3, name="x") will create the variables [x[0], x[1], x[2]].

    • boolvar(shape=3, name=list("xyz")) will create the variables [x, y, z].

Examples

Creating a single Boolean variable:

x = boolvar()              # auto name BV<n> (unique counter)
x = boolvar(name="x")      # user-chosen name

Creating a vector of Boolean variables:

x = boolvar(shape=3, name="x")

# Assigning them to individual variables:
e, x, a, m, p, l = boolvar(shape=6, name=list("exampl"))

Creating a matrix or higher-order tensor of Boolean variables:

matrix = boolvar(shape=(9, 9), name="matrix")
matrix2 = boolvar(shape=(2, 2), name=[['a', 'b'], ['c', 'd']])
tensor = boolvar(shape=(3, 8, 7), name="tensor")
cpmpy.expressions.cparray(arr)[source]

Deprecated since version 0.9.0: Please use cpm_array() instead.

cpmpy.expressions.cpm_array(arr: Sequence[Expression | int | integer | bool | Any] | ndarray) NDVarArray[source]

N-dimensional wrapper, to wrap standard numpy arrays or lists.

In CP modeling languages, indexing an array by an integer variable is common, e.g. [1,2,3,4][var1] == var2. This is called an element constraint. Python does not allow expressing it on standard arrays, but CPMpy-numpy arrays do allow it, so you first have to wrap the array.

Note that arr will be transformed to vector and indexed as such, 2-dimensional indexing is not supported (yet?).

# Transforming a given numpy-array **m** into a cparray

iv1, iv2 = intvar(0, 9, shape=2)

data = [1, 2, 3, 4]
data = cpm_array(data)

Model([ data[iv1] == iv2 ])

As an alternative, you can also write the Element constraint directly on data:

Element(data, iv1) == iv2
cpmpy.expressions.intvar(lb: int, ub: int, shape: Literal[1] = 1, name: str | None = None) _IntVarImpl[source]
cpmpy.expressions.intvar(lb: int, ub: int, shape: int | integer | tuple[int | integer, ...] = 1, name: str | Sequence[str] | ndarray | None = None) NDVarArray

Integer decision variables are constructed by specifying the lowest (lb) value the decision variable can take, as well as the highest value (ub).

Parameters:
  • lb (int) – Lower bound on the values the variable can take.

  • ub (int) – Upper bound on the values the variable can take.

  • shape (int or tuple of int, optional) – The shape of the n-dimensional array of variables. Default is 1.

  • name (str, list of str, tuple of str, or None, optional) –

    Name(s) to assign to the variables. Default is None.

    • If name is None, a name of the form IV<unique number> will be assigned to the variables.

    • If name is a string, it will be used as the suffix of the variable names.

    • If name is a list/tuple/array of strings, they will be assigned to the variable names accordingly.

Notes

The range of values between lb..ub is called the domain of the integer variable. All variables in an array start from the same domain. Specific values in the domain of individual variables can be forbidden with constraints.

If shape is not 1, each element of the array will have its specific location appended to its name.

  • intvar(0, 2, shape=3, name="x") will create the variables [x[0], x[1], x[2]].

If shape is not 1 and a list of names has been provided (with the same length as the array), each decision variable will receive its respective name.

  • intvar(0, 2, shape=3, name=list("xyz")) will create the variables [x, y, z].

Examples

Creation of a single (unit-sized or scalar) integer variable with a given lower bound (lb) of 3 and upper bound (ub) of 8. Variable x can thus take values 3, 4, 5, 6, 7, 8 (upper bound included!).

# creation of a unit integer variable with lowerbound of 3 and upperbound of 8
x = intvar(3, 8, name="x")

Creation of a vector of integer variables with all having the same given lower bound and upper bound:

# creation of a vector Boolean of 5 variables with lowerbound of 3 and upperbound of 8
x = intvar(3, 8, shape=5, name="x")

# Python's unpacking can assign multiple intermediate variables at once
e, x, a, m, p, l = intvar(3, 8, shape=6, name=list("exampl"))

Creation of a 4D-array/tensor (of dimensions 100 x 100 x 100 x 100) of integer variables.

arrx s= intvar(3, 8, shape=(100, 100, 100, 100), name="arrx")
cpmpy.expressions.max(*iterable, **kwargs)[source]

max() overwrites the python built-in to support decision variables.

if iterable does not contain CPMpy expressions, the built-in is called else a Maximum functional global constraint is constructed; no keyword arguments are supported in that case

cpmpy.expressions.min(*iterable, **kwargs)[source]

min() overwrites the python built-in to support decision variables.

if iterable does not contain CPMpy expressions, the built-in is called else a Minimum functional global constraint is constructed; no keyword arguments are supported in that case

cpmpy.expressions.sum(iterable, **kwargs)[source]

sum() overwrites the python built-in to support decision variables.

if iterable does not contain CPMpy expressions, the built-in is called checks if all constants and uses built-in sum() in that case