lparray#
Module provides objects that can be used to manipulate linear programming problems.
The module provides a set of classes and functions that can be used to manipulate linear programming problems. These objects are:
lparray
: Numpy array with homogeneous LpVariables, LpAffineExpression or LpConstraints.lp_minmax
: Get the minimum or maximum from a list of linear expressions.addAbs
: Add absolute value constraints to a linear programming problem.lp_multiply
: Multiplication of a binary and continuous variables.
- class wip.modules.lparray.HasShape(*args, **kwargs)[source]#
Bases:
Protocol
Protocol for objects that have a shape attribute.
This protocol defines a contract that classes can adhere to without having to inherit from a common base class. It’s useful when writing functions or classes that expect an object with a specific attribute, in this case,
shape
.- Variables
shape (
Tuple[int
,]
) – Tuple indicating the dimensions of the object. e.g., (2, 3) for a 2x3 matrix.
Notes
The
HasShape
protocol can be used in type annotations to indicate that a function or method expects an object with ashape
attribute.
- wip.modules.lparray.add_abs(prob: pulp.LpProblem, var: pulp.LpVariable | pulp.LpAffineExpression, big_m: float | int = 100000, abs_var_name: str | None = None) pulp.LpVariable [source]#
Create an LP variable with the absolute value of a variable or expression.
This function introduces an auxiliary variable to the linear programming problem that represents the absolute value of a provided variable or expression. It also adds the necessary constraints to ensure this auxiliary variable correctly captures the absolute value.
- Parameters
prob (
pulp.LpProblem
) – The optimization problem to which the absolute value variable is added.var (
pulp.LpVariable | pulp.LpAffineExpression
) – The variable or expression whose absolute value is to be represented.big_m (
float | int
, default100000
) – A large constant required to create the auxiliary constraints needed to create the variable that equals the absolute value of :param:`var`. The value needs to be greater than any value that :param:`var` can have.abs_var_name (
str | None
, optional) – The name for the absolute value variable. If None, a name is generated automatically.
- Returns
The auxiliary variable representing the absolute value of the provided variable or expression.
- Return type
pulp.LpVariable
Examples
The following example demonstrates how the
add_abs()
can be used, to find the absolute value for thex
variable, that has a range of: -10 \leq{} \text{x} \leq{} 0:>>> prob = pulp.LpProblem("MyProblem", sense=pulp.LpMaximize) >>> x = pulp.LpVariable("x", lowBound=-10, upBound=0) >>> abs_x = add_abs(prob, x) >>> prob.setObjective(abs_x)
>>> print(pulp.LpStatus[prob.solve(pulp.PULP_CBC_CMD(msg=False))]) 'Optimal'
>>> print(f"Objective Value: {prob.objective.value():.0f}") 'Objective Value: 10'
>>> for name, lpvar in prob.variablesDict().items(): ... print(f"{name} = {lpvar.value():.0f}") abs(x) = 10 x = -10 binary_var(x) = 0
- wip.modules.lparray.count_out(iterable: Iterable[Any]) List[int] [source]#
Return indices of items in the given iterable.
Given some iterable, this function generates a list of indices corresponding to each item in the iterable.
- Parameters
iterable (
Iterable[Any]
) – Input iterable of any type.- Returns
List of indices for each item in the input iterable.
- Return type
List[int]
Examples
>>> count_out(["a", "b", "c"]) [0, 1, 2] >>> count_out((1, 2, 3, 4)) [0, 1, 2, 3]
- wip.modules.lparray.find_unique_name(prob: LpProblem, name: str) str [source]#
Find a unique variable name for the problem.
If a variable with the given name exists, append ‘_<number>’ to it, where <number> starts from 1 and increases until a unique name is found.
- wip.modules.lparray.lp_define_or_constraint(prob: pulp.LpProblem, lp_expression: pulp.LpVariable | pulp.LpAffineExpression, lp_binary_var: pulp.LpVariable, low_bound: float, up_bound: float)[source]#
Define or constrain a linear programming problem in PuLP.
This function adds constraints to a given linear programming (LP) problem based on a specified LP expression, some specified boundary conditions and a binary variable. It uses the binary variable to impose the lower and upper bounds on the LP expression, or set it to 0, otherwise. The function handles both single
pulp.LpVariables
andpulp.LpAffineExpressions
.- Parameters
prob (
pulp.LpProblem
) – The linear programming problem to which the constraints will be added.lp_expression (
pulp.LpVariable | pulp.LpAffineExpression
) – The linear programming expression (either a variable or an affine expression) that is to be constrained.lp_binary_var (
pulp.LpVariable
) – The binary variable to link with the expression, to constraint the expression from :param:`lp_expression` to be equal to 0, when this binary variable is also 0, or a value between :param:`low_bound` and :param:`up_bound` otherwise.low_bound (
float
) – The lower bound for the LP expression. The expression will be constrained to be greater than or equal to this value times a binary auxiliary variable.up_bound (
float
) – The upper bound for the LP expression. The expression will be constrained to be less than or equal to this value times a binary auxiliary variable.
Examples
>>> prob = pulp.LpProblem("Example_Problem", pulp.LpMaximize) >>> x = pulp.LpVariable("x", 0, 3) >>> xb = pulp.LpVariable("xb", cat=pulp.LpBinary) >>> lp_define_or_constraint(prob, x, xb, 0.8, 1)
This example adds constraints to the problem ‘prob’ that enforce variable ‘x’ to be between 0.8 and 1 when a certain condition (represented by the binary auxiliary variable) is true.
- wip.modules.lparray.lp_minmax(lp_expression, prob: LpProblem, name: str, which, cat, lb=None, ub=None, bigM=1000)[source]#
- Parameters
prob (LpProblem) –
name (str) –
- wip.modules.lparray.lp_multiply(bin_lpvar: pulp.LpVariable, cont_lpvar: pulp.LpVariable, prob: pulp.LpProblem, big_m: int | float = 100000) pulp.LpProblem [source]#
Multiply a binary with a continuous
pulp.LpVariable
.Introduces constraints to a given
pulp.LpProblem
that represent the multiplication between a binary and a continuouspulp.LpVariable
, and returns the modifiedpulp.LpProblem
.- Parameters
bin_lpvar (
pulp.LpVariable
) – Binary linear programming variable.cont_lpvar (
pulp.LpVariable
) – Continuous linear programming variable, which should have both its lower- and upper-bounds set.prob (
pulp.LpProblem
) – The linear programming problem to which the multiplication constraints will be added.big_m (
int | float
, default100_000
) – A value that is greater than the lower and upper bounds ofcont_lpvar
.
- Returns
The modified
pulp.LpProblem
with the added constraints.- Return type
pulp.LpProblem
Examples
To illustrate how to use the function with pulp:
>>> import pulp >>> prob = pulp.LpProblem("ExampleProblem", pulp.LpMaximize) >>> bin_var = pulp.LpVariable("binary", 0, 1, pulp.LpBinary) >>> cont_var = pulp.LpVariable("continuous", 0, 10) >>> prob = lp_multiply(bin_var, cont_var, prob) >>> prob += bin_var == 0 >>> prob.setObjective(cont_var) >>> prob.solve(pulp.PULP_CBC_CMD(msg=False)) >>> print(cont_var.value()) 0.0
- class wip.modules.lparray.lparray[source]#
-
Numpy array with homogeneous LpVariables, LpAffineExpression or LpConstraints.
All variables in the array will have the same:
Lp* type
(intrinsic) upper bound
(intrinsic) lower bound
Also, all vectorized operations will preserve this invariant. External manipulations that break this invariant will lead to wrong behavior.
All variables in an array are named, and share the same base name, which is extended by indexes into a collection of index sets whose product spans the elements of the array. These index sets can be named or anonymous – anonymous index sets are int ranges.
Implements vectorized versions of various LP of LpConstraint-type lparrays support the
constrain
method, which will bind the constraints to an LpProblem.In addition, a number of more sophisticated mathematical operations are supported, many of which involve the creation of auxiliary lparrays with variables behind the scenes.
- Attributes
T
View of the transposed array.
base
Base object if memory is from some other object.
ctypes
An object to simplify the interaction of the array with the ctypes module.
data
Python buffer object pointing to the start of the array’s data.
dtype
Data-type of the array’s elements.
flags
Information about the memory layout of the array.
flat
A 1-D iterator over the array.
imag
The imaginary part of the array.
itemsize
Length of one array element in bytes.
nbytes
Total bytes consumed by the elements of the array.
ndim
Number of array dimensions.
real
The real part of the array.
shape
Tuple of array dimensions.
size
Number of elements in the array.
strides
Tuple of bytes to step in each dimension when traversing an array.
values
Return the underlying values of the PuLP variables.
Methods
abs
(prob, name, **kwargs)Return variable equal to |self|.
abs_decompose
(prob, name, *[, bigM])Constraint that generates two arrays, xp and xm, that sum to abs(self).
all
([axis, out, keepdims, where])Returns True if all elements evaluate to True.
any
([axis, out, keepdims, where])Returns True if any of the elements of
a
evaluate to True.argmax
([axis, out, keepdims])Return indices of the maximum values along the given axis.
argmin
([axis, out, keepdims])Return indices of the minimum values along the given axis.
argpartition
(kth[, axis, kind, order])Returns the indices that would partition this array.
argsort
([axis, kind, order])Returns the indices that would sort this array.
astype
(dtype[, order, casting, subok, copy])Copy of the array, cast to a specified type.
byteswap
([inplace])Swap the bytes of the array elements
choose
(choices[, out, mode])Use an index array to construct a new array from a set of choices.
clip
([min, max, out])Return an array whose values are limited to
[min, max]
.compress
(condition[, axis, out])Return selected slices of this array along given axis.
conj
()Complex-conjugate all elements.
conjugate
()Return the complex conjugate, element-wise.
constrain
(prob, name)Apply the constraints contained in
lparray
to the problem.copy
([order])Return a copy of the array.
create
(name, index_sets, *[, lowBound, ...])Creates a lparray with shape from a cartesian product of index sets.
create_anon
(name, shape, **kwargs)Create a lparray with a given shape and nameless index sets.
create_like
(name, like, **kwargs)Create a lparray with the same shape as the passed array.
cumprod
([axis, dtype, out])Return the cumulative product of the elements along the given axis.
cumsum
([axis, dtype, out])Return the cumulative sum of the elements along the given axis.
diagonal
([offset, axis1, axis2])Return specified diagonals.
dump
(file)Dump a pickle of the array to the specified file.
dumps
()Returns the pickle of the array as a string.
fill
(value)Fill the array with a scalar value.
flatten
([order])Return a copy of the array collapsed into one dimension.
getfield
(dtype[, offset])Returns a field of the given array as a certain type.
item
(*args)Copy an element of an array to a standard Python scalar and return it.
itemset
(*args)Insert scalar into an array (scalar is cast to array's dtype, if possible)
logical_clip
(prob, name[, bigM])Assumes self is an integer >= 0.
lp_bin_and
(prob, name, *ins)Constrain the array using logical AND operation of binary inputs.
lp_bin_max
(prob, name, **kwargs)Return an array corresponding to the maximum value along an axis.
lp_bin_min
(prob, name, **kwargs)Return an array corresponding to the minimum value along an axis.
lp_bin_or
(prob, name, *ins)Constrain the array using the logical OR operation of binary inputs
lp_int_max
(prob, name, lb, ub, **kwargs)Return an array corresponding to the maximum value along an axis.
lp_int_min
(prob, name, lb, ub, **kwargs)Return an array corresponding to the maximum value along an axis.
lp_real_max
(prob, name, **kwargs)Return an array corresponding to the maximum value along an axis.
lp_real_min
(prob, name, **kwargs)Return an array corresponding to the minimum value along an axis.
max
([axis, out, keepdims, initial, where])Return the maximum along a given axis.
mean
([axis, dtype, out, keepdims, where])Returns the average of the array elements along given axis.
min
([axis, out, keepdims, initial, where])Return the minimum along a given axis.
newbyteorder
([new_order])Return the array with the same data viewed with a different byte order.
nonzero
()Return the indices of the elements that are non-zero.
partition
(kth[, axis, kind, order])Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array.
prod
([axis, dtype, out, keepdims, initial, ...])Return the product of the array elements over the given axis
ptp
([axis, out, keepdims])Peak to peak (maximum - minimum) value along a given axis.
put
(indices, values[, mode])Set
a.flat[n] = values[n]
for alln
in indices.ravel
([order])Return a flattened array.
repeat
(repeats[, axis])Repeat elements of an array.
reshape
(shape[, order])Returns an array containing the same data with a new shape.
resize
(new_shape[, refcheck])Change shape and size of array in-place.
round
([decimals, out])Return
a
with each element rounded to the given number of decimals.searchsorted
(v[, side, sorter])Find indices where elements of v should be inserted in a to maintain order.
setfield
(val, dtype[, offset])Put a value into a specified place in a field defined by a data-type.
setflags
([write, align, uic])Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY, respectively.
sort
([axis, kind, order])Sort an array in-place.
squeeze
([axis])Remove axes of length one from
a
.std
([axis, dtype, out, ddof, keepdims, where])Returns the standard deviation of the array elements along given axis.
sum
([axis, dtype, out, keepdims, initial, where])Return the sum of the array elements over the given axis.
sumit
(*args, **kwargs)Equivalent to
self.sum().item()
.swapaxes
(axis1, axis2)Return a view of the array with
axis1
andaxis2
interchanged.take
(indices[, axis, out, mode])Return an array formed from the elements of
a
at the given indices.tobytes
([order])Construct Python bytes containing the raw data bytes in the array.
tofile
(fid[, sep, format])Write array to a file as text or binary (default).
tolist
()Return the array as an
a.ndim
-levels deep nested list of Python scalars.tostring
([order])A compatibility alias for
tobytes
, with exactly the same behavior.trace
([offset, axis1, axis2, dtype, out])Return the sum along diagonals of the array.
transpose
(*axes)Returns a view of the array with axes transposed.
var
([axis, dtype, out, ddof, keepdims, where])Returns the variance of the array elements, along given axis.
view
([dtype][, type])New view of array with the same data.
dot
- _lp_int_minmax(prob: LpProblem, name: str, which: Literal['min', 'max'], lb: int, ub: int, **kwargs: Any) lparray[LpVariable] [source]#
Internal method for
lparray.lp_int_max
.
- _lp_minmax(prob: LpProblem, name: str, which: Literal['min', 'max'], cat: Literal['Binary', 'Integer', 'Continuous'], *, lb: Optional[Union[int, float]] = None, ub: Optional[Union[int, float]] = None, bigM: Union[int, float] = 1000, axis: Optional[Union[int, tuple[int, ...]]] = None) lparray[LpVariable] [source]#
Return lparray with its min/max along an axis.
The Axis can be multidimensional.
- Parameters
prob (
LpProblem
) – Problem instance to which to apply the constraints.name (
str
) – Base LpVariable name for the min/max output array.which (
Literal[``
”min”, ``"max"
]
) – Choice of operation. Can be either “min” or “max” – determines the operationcat (
LpVarType
) – LpCategory of the output lparraylb (
Optional[Number]
) – Lower bound on the output arrayub (
Optional[Number]
) – Upper bound on the output arraybigM (
Number
) – big M value used for auxiliary variable inequalities. It Should be larger than any value that can appear in self in a feasible solution.axis (
Optional[Union[int
,tuple[int
,]]]
) – Axes along which to take the maximum
- Returns
lparray with min/max along a given axis.
- Return type
lparray[LpVariable]
- Raises
If
axis
is None andself
is a scalar.If
self.ndim
is not equal tolen(axis)
.If
cat
is not “Binary” andlb
andub
are not provided.If
which
is not “min” or “max”.
TypeError – If
axis
values are not integers.
- abs(prob: LpProblem, name: str, **kwargs: Any) lparray[LpAffineExpression] [source]#
Return variable equal to |self|.
Thin wrapper around
abs_decompose
- abs_decompose(prob: LpProblem, name: str, *, bigM: Union[int, float] = 1000.0, **kwargs: Any) Tuple[lparray[LpVariable], lparray[LpVariable]] [source]#
Constraint that generates two arrays, xp and xm, that sum to abs(self).
Constraint uses the following properties:
\begin{array}{} xp \geq 0 \\ xm \geq 0 \\ xp == 0 \or xm == 0 \\ \Sum_{i=1}^{n} (xp_i + xm_i) = |self| = X \\ \text{where:} \\ xp \rightarrow \text{Positive half of X} \\ xm \rightarrow \text{Negative half of X} \\ \end{array} xp >= 0 xm >= 0 xp == 0 XOR xm == 0
Use the big M method. Generates
2 * self.size
visible new variables. Generates1 * self.size
binary auxiliary variables.- Parameters
- Returns
Arrays, xp and xm, that sum to |self|
- Return type
Tuple[lparray[LpVariable]
,lparray[LpVariable]]
Examples
Let xb == binary variable (domain: {0, 1}) and x == integer expression comprised of multiple variables with (domain: {-1000, 1000})
If we create the following constraints:
x <= 10000 * (1 - xb) -> c_lb x >= -10000 * xb -> c_ub
If x is negative, then both c_lb and c_ub constraints will only be True, when xb == 1
On the other hand, if x is positive, xb must be equal to 0.
- constrain(prob: LpProblem, name: str) None [source]#
Apply the constraints contained in
lparray
to the problem.- Parameters
prob (
LpProblem
) – Lp Problem to add thelp_constraints
to.name (
str
) – Name of to thelp_constraints
...Versionadded: – 0.4.0: Add “try/except” clause that adds lp_constraints to prob instance without using the specified name if name is already taken.
- Return type
None
- classmethod create(name: str, index_sets: tuple[Collection[Any], ...], *, lowBound: Optional[Union[int, float]] = None, upBound: Optional[Union[int, float]] = None, cat: Literal['Binary', 'Integer', 'Continuous'] = 'Continuous') lparray[LpVariable] [source]#
Creates a lparray with shape from a cartesian product of index sets.
Each LpVariable in the array at an index [i_0, …, i_n] will be named as “{name}_(ix_sets[0][i_0], …, ix_sets[n][i_n])”
- Parameters
name (
str
) – Base names for the underlying LpVariablesindex_sets (
tuple[Collection[Any]
,]
) – An iterable of iterables containing the dimension names for the array.lowBound (
Optional[Number]
) – Passed to LpVariable, uniform for an arrayupBound (
Optional[Number]
) – Passed as toLpVariable
, uniform for the arraycat (
LpVarType
) – Passed toLpVariable
, uniform for an array defining the category of eachLpVariable
. Defaults to “Integer”
- Returns
Array of LP Variables
- Return type
lparray[LpVariable]
- classmethod create_anon(name: str, shape: Tuple[int, ...], **kwargs: Any) lparray[LpVariable] [source]#
Create a lparray with a given shape and nameless index sets.
- Parameters
name (
str
) – Base names for the underlying LpVariablesshape (
tuple[int
,]
) – Array shape, same as for numpy arrays**kwargs (
Any
) – Pulp LpVariable extra arguments that you want to define
- Returns
Array of LpVariables
- Return type
lparray[LpVariable]
- classmethod create_like(name: str, like: HasShape, **kwargs: Any) lparray[LpVariable] [source]#
Create a lparray with the same shape as the passed array.
- logical_clip(prob: LpProblem, name: str, bigM: Union[int, float] = 1000) lparray[LpVariable] [source]#
Assumes self is an integer >= 0.
Returns an array of the same shape as self-containing:
Generates
self.size
new variables.- Parameters
prob (
LpProblem
) – Problem to bind aux variables toname (
str
) – Base names for generated variablesbigM (
Number
) – The -lower and upper bound on self to assume. Default value = 1000.0
- Returns
lparray[LpVariable]
– Array of the same shape as self-containing max value between problem variables and 1.warning::
– It is extremely important to correctly configure the value for bigM. This value should be greater than the module of every lpVariable, to be compared. If the problem variables have values in range of -100,000,000 to 50,000,000, then bigM must be AT LEAST equal to 100,000,001.On the other hand, setting bigM to values far greater than the variables’ range might result in considerable processing time.
- Return type
lparray[LpVariable]
- lp_bin_and(prob: LpProblem, name: str, *ins: Union[lparray[LpVariable], lparray[LpAffineExpression], ndarray]) lparray[LPV] [source]#
Constrain the array using logical AND operation of binary inputs.
- lp_bin_max(prob: LpProblem, name: str, **kwargs: Any) lparray[LpVariable] [source]#
Return an array corresponding to the maximum value along an axis.
Binary variable type.
- Parameters
prob (
LpProblem
) – Problem instance to which to apply the constraints.name (
str
) – Base-name for the output array.**kwargs (
Any
) –
- Returns
Array with the max along one of the axes.
- Return type
lparray[LpVariable]
- lp_bin_min(prob: LpProblem, name: str, **kwargs: Any) lparray[LpVariable] [source]#
Return an array corresponding to the minimum value along an axis.
Binary variable type.
- Parameters
prob (
LpProblem
) – Problem instance to which to apply the constraints.name (
str
) – Base-name for the output array,**kwargs (
Any
) –
- Returns
Array with min along one of the axes.
- Return type
lparray[LpVariable]
- lp_bin_or(prob: LpProblem, name: str, *ins: Union[lparray[LpVariable], lparray[LpAffineExpression], ndarray]) lparray[LPV] [source]#
Constrain the array using the logical OR operation of binary inputs
- lp_int_max(prob: LpProblem, name: str, lb: int, ub: int, **kwargs: Any) lparray[LpVariable] [source]#
Return an array corresponding to the maximum value along an axis.
The array corresponds to the maximum value along specified axes.
- lp_int_min(prob: LpProblem, name: str, lb: int, ub: int, **kwargs: Any) lparray[LpVariable] [source]#
Return an array corresponding to the maximum value along an axis.
The Method can be used on Integer variables.
- Parameters
- Returns
Array with min along one of the axes.
- Return type
lparray[LpVariable]
- lp_real_max(prob: LpProblem, name: str, **kwargs: Any) lparray[LpVariable] [source]#
Return an array corresponding to the maximum value along an axis.
Continuous variable type.
- Parameters
prob (
LpProblem
) – Problem instance to which to apply the constraints.name (
str
) – Base name for the output array**kwargs (
Any
) –
- Returns
Array with max along one of the axes.
- Return type
lparray[LpVariable]
- lp_real_min(prob: LpProblem, name: str, **kwargs: Any) lparray[LpVariable] [source]#
Return an array corresponding to the minimum value along an axis.
Continuous variable type.
- Parameters
prob (
LpProblem
) – Problem instance to which to apply the constraints.name (
str
) – Base name for the output array**kwargs (
Any
) –
- Returns
Array with min along one of the axes.
- Return type
lparray[LpVariable]