pulp: Pulp classes

LpProblem([name, sense])

An LP Problem

LpVariable(name[, lowBound, upBound, cat, e])

This class models an LP Variable with the specified associated parameters

LpAffineExpression([e, constant, name])

A linear combination of LpVariables.

LpConstraint([e, sense, name, rhs])

An LP constraint

LpConstraint.makeElasticSubProblem(*args, ...)

Builds an elastic subproblem by adding variables to a hard constraint

FixedElasticSubProblem(constraint[, ...])

Contains the subproblem generated by converting a fixed constraint \(\sum_{i}a_i x_i = b\) into an elastic constraint.

Todo

LpFractionConstraint, FractionElasticSubProblem

The LpProblem Class

class pulp.LpProblem(name='NoName', sense=1)

Bases: object

An LP Problem

Creates an LP Problem

This function creates a new LP Problem with the specified associated parameters

Parameters:
  • name – name of the problem used in the output .lp file

  • sense – of the LP problem objective. Either LpMinimize (default) or LpMaximize.

Returns:

An LP Problem

Three important attributes of the problem are:

objective

The objective of the problem, an LpAffineExpression

constraints

An ordered dictionary of constraints of the problem - indexed by their names.

status

The return status of the problem from the solver.

Some of the more important methods:

solve(solver=None, **kwargs)

Solve the given Lp problem.

This function changes the problem to make it suitable for solving then calls the solver.actualSolve() method to find the solution

Parameters:

solver – Optional: the specific solver to be used, defaults to the default solver.

Side Effects:
  • The attributes of the problem object are changed in actualSolve() to reflect the Lp solution

roundSolution(epsInt=1e-05, eps=1e-07)

Rounds the lp variables

Inputs:
  • none

Side Effects:
  • The lp variables are rounded

setObjective(obj)

Sets the input variable as the objective function. Used in Columnwise Modelling

Parameters:

obj – the objective function of type LpConstraintVar

Side Effects:
  • The objective function is set

writeLP(filename, writeSOS=1, mip=1, max_length=100)

Write the given Lp problem to a .lp file.

This function writes the specifications (objective function, constraints, variables) of the defined Lp problem to a file.

Parameters:

filename (str) – the name of the file to be created.

Returns:

variables

Side Effects:
  • The file is created

writeMPS(filename, mpsSense=0, rename=0, mip=1, with_objsense: bool = False)

Writes an mps files from the problem information

Parameters:
  • filename (str) – name of the file to write

  • mpsSense (int) –

  • rename (bool) – if True, normalized names are used for variables and constraints

  • mip – variables and variable renames

Returns:

Side Effects:
  • The file is created

toJson(filename, *args, **kwargs)

Creates a json file from the LpProblem information

Parameters:
  • filename (str) – filename to write json

  • args – additional arguments for json function

  • kwargs – additional keyword arguments for json function

Returns:

None

classmethod fromJson(filename)

Creates a new Lp Problem from a json file with information

Parameters:

filename (str) – json file name

Returns:

a tuple with a dictionary of variables and an LpProblem

Return type:

(dict, LpProblem)

variables()

Returns the problem variables

Returns:

A list containing the problem variables

Return type:

(list, LpVariable)

Variables and Expressions

class pulp.LpElement(name)

Base class for LpVariable and LpConstraintVar


class pulp.LpVariable(name, lowBound=None, upBound=None, cat='Continuous', e=None)

This class models an LP Variable with the specified associated parameters

Parameters:
  • name – The name of the variable used in the output .lp file

  • lowBound – The lower bound on this variable’s range. Default is negative infinity

  • upBound – The upper bound on this variable’s range. Default is positive infinity

  • cat – The category this variable is in, Integer, Binary or Continuous(default)

  • e – Used for column based modelling: relates to the variable’s existence in the objective function and constraints

addVariableToConstraints(e)

adds a variable to the constraints indicated by the LpConstraintVars in e

classmethod dicts(name, indices=None, lowBound=None, upBound=None, cat='Continuous', indexStart=[])

This function creates a dictionary of LpVariable with the specified associated parameters.

Parameters:
  • name – The prefix to the name of each LP variable created

  • indices – A list of strings of the keys to the dictionary of LP variables, and the main part of the variable name itself

  • lowBound – The lower bound on these variables’ range. Default is negative infinity

  • upBound – The upper bound on these variables’ range. Default is positive infinity

  • cat – The category these variables are in, Integer or Continuous(default)

Returns:

A dictionary of LpVariable

fixValue()

changes lower bound and upper bound to the initial value if exists. :return: None

classmethod fromDict(dj=None, varValue=None, **kwargs)

Initializes a variable object from information that comes from a dictionary (kwargs)

Parameters:
  • dj – shadow price of the variable

  • varValue (float) – the value to set the variable

  • kwargs – arguments to initialize the variable

Returns:

a LpVariable

Return type:

:LpVariable

classmethod from_dict(dj=None, varValue=None, **kwargs)

Initializes a variable object from information that comes from a dictionary (kwargs)

Parameters:
  • dj – shadow price of the variable

  • varValue (float) – the value to set the variable

  • kwargs – arguments to initialize the variable

Returns:

a LpVariable

Return type:

:LpVariable

isFixed()
Returns:

True if upBound and lowBound are the same

Return type:

bool

setInitialValue(val, check=True)

sets the initial value of the variable to val May be used for warmStart a solver, if supported by the solver

Parameters:
  • val (float) – value to set to variable

  • check (bool) – if True, we check if the value fits inside the variable bounds

Returns:

True if the value was set

Raises:

ValueError – if check=True and the value does not fit inside the bounds

toDict()

Exports a variable into a dictionary with its relevant information

Returns:

a dictionary with the variable information

Return type:

dict

to_dict()

Exports a variable into a dictionary with its relevant information

Returns:

a dictionary with the variable information

Return type:

dict

Example:

>>> x = LpVariable('x',lowBound = 0, cat='Continuous')
>>> y = LpVariable('y', upBound = 5, cat='Integer')

gives \(x \in [0,\infty)\), \(y \in (-\infty, 5]\), an integer.


class pulp.LpAffineExpression(e=None, constant=0, name=None)

Bases: OrderedDict

A linear combination of LpVariables. Can be initialised with the following:

  1. e = None: an empty Expression

  2. e = dict: gives an expression with the values being the coefficients of the keys (order of terms is undetermined)

  3. e = list or generator of 2-tuples: equivalent to dict.items()

  4. e = LpElement: an expression of length 1 with the coefficient 1

  5. e = other: the constant is initialised as e

Examples:

>>> f=LpAffineExpression(LpElement('x'))
>>> f
1*x + 0
>>> x_name = ['x_0', 'x_1', 'x_2']
>>> x = [LpVariable(x_name[i], lowBound = 0, upBound = 10) for i in range(3) ]
>>> c = LpAffineExpression([ (x[0],1), (x[1],-3), (x[2],4)])
>>> c
1*x_0 + -3*x_1 + 4*x_2 + 0

In brief, \(\textsf{LpAffineExpression([(x[i],a[i]) for i in I])} = \sum_{i \in I} a_i x_i\) where (note the order):

  • x[i] is an LpVariable

  • a[i] is a numerical coefficient.

addInPlace(other, sign=1)
Parameters:

sign (int) – the sign of the operation to do other. if we add other => 1 if we subtract other => -1

asCplexLpAffineExpression(name, constant=1)

returns a string that represents the Affine Expression in lp format

asCplexVariablesOnly(name)

helper for asCplexLpAffineExpression

copy()

Make a copy of self except the name which is reset

sorted_keys()

returns the list of keys sorted by name

toDict()

exports the LpAffineExpression into a list of dictionaries with the coefficients it does not export the constant

Returns:

list of dictionaries with the coefficients

Return type:

list

to_dict()

exports the LpAffineExpression into a list of dictionaries with the coefficients it does not export the constant

Returns:

list of dictionaries with the coefficients

Return type:

list


pulp.lpSum(vector)

Calculate the sum of a list of linear expressions

Parameters:

vector – A list of linear expressions

Constraints

class pulp.LpConstraint(e=None, sense=0, name=None, rhs=None)

Bases: LpAffineExpression

An LP constraint

Parameters:
  • e – an instance of LpAffineExpression

  • sense – one of LpConstraintEQ, LpConstraintGE, LpConstraintLE (0, 1, -1 respectively)

  • name – identifying string

  • rhs – numerical value of constraint target

addInPlace(other, sign=1)
Parameters:

sign (int) – the sign of the operation to do other. if we add other => 1 if we subtract other => -1

asCplexLpConstraint(name)

Returns a constraint as a string

changeRHS(RHS)

alters the RHS of a constraint so that it can be modified in a resolve

copy()

Make a copy of self

classmethod fromDict(_dict)

Initializes a constraint object from a dictionary with necessary information

Parameters:

_dict (dict) – dictionary with data

Returns:

a new LpConstraint

classmethod from_dict(_dict)

Initializes a constraint object from a dictionary with necessary information

Parameters:

_dict (dict) – dictionary with data

Returns:

a new LpConstraint

makeElasticSubProblem(*args, **kwargs)

Builds an elastic subproblem by adding variables to a hard constraint

uses FixedElasticSubProblem

toDict()

exports constraint information into a dictionary

Returns:

dictionary with all the constraint information

class pulp.FixedElasticSubProblem(constraint, penalty=None, proportionFreeBound=None, proportionFreeBoundList=None)

Bases: LpProblem

Contains the subproblem generated by converting a fixed constraint \(\sum_{i}a_i x_i = b\) into an elastic constraint.

Parameters:
  • constraint – The LpConstraint that the elastic constraint is based on

  • penalty – penalty applied for violation (+ve or -ve) of the constraints

  • proportionFreeBound – the proportional bound (+ve and -ve) on constraint violation that is free from penalty

  • proportionFreeBoundList – the proportional bound on constraint violation that is free from penalty, expressed as a list where [-ve, +ve]

Creates an LP Problem

This function creates a new LP Problem with the specified associated parameters

Parameters:
  • name – name of the problem used in the output .lp file

  • sense – of the LP problem objective. Either LpMinimize (default) or LpMaximize.

Returns:

An LP Problem

alterName(name)

Alters the name of anonymous parts of the problem

deElasticize()

de-elasticize constraint

findDifferenceFromRHS()

The amount the actual value varies from the RHS (sense: LHS - RHS)

findLHSValue()

for elastic constraints finds the LHS value of the constraint without the free variable and or penalty variable assumes the constant is on the rhs

isViolated()

returns true if the penalty variables are non-zero

reElasticize()

Make the Subproblem elastic again after deElasticize

Combinations and Permutations

pulp.combination(iterable, r)

Return successive r-length combinations of elements in the iterable.

combinations(range(4), 3) –> (0,1,2), (0,1,3), (0,2,3), (1,2,3)

pulp.allcombinations(orgset, k)

returns all combinations of orgset with up to k items

Parameters:
  • orgset – the list to be iterated

  • k – the maxcardinality of the subsets

Returns:

an iterator of the subsets

example:

>>> c = allcombinations([1,2,3,4],2)
>>> for s in c:
...     print(s)
(1,)
(2,)
(3,)
(4,)
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
pulp.permutation(iterable, r=None)

Return successive r-length permutations of elements in the iterable.

permutations(range(3), 2) –> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)

pulp.allpermutations(orgset, k)

returns all permutations of orgset with up to k items

Parameters:
  • orgset – the list to be iterated

  • k – the maxcardinality of the subsets

Returns:

an iterator of the subsets

example:

>>> c = allpermutations([1,2,3,4],2)
>>> for s in c:
...     print(s)
(1,)
(2,)
(3,)
(4,)
(1, 2)
(1, 3)
(1, 4)
(2, 1)
(2, 3)
(2, 4)
(3, 1)
(3, 2)
(3, 4)
(4, 1)
(4, 2)
(4, 3)
pulp.value(x)

Returns the value of the variable/expression x, or x if it is a number