cylp.cy.CyClpSimplex

class cylp.cy.CyClpSimplex.CyClpSimplex

CyClpSimplex is a Cython interface to CLP. Not all methods are available but they are being added gradually.

Its constructor can create an empty object if no argument is provided. However, if a CyLPModel object is given then the resulting CyClpSimplex object will be build from it. For an example of the latter case see cylp's modeling tool.

An easy example of how to read and solve an LP

>>> from cylp.cy.CyClpSimplex import CyClpSimplex, getMpsExample
>>> s = CyClpSimplex()
>>> f = getMpsExample()
>>> s.readMps(f)
0
>>> s.initialSolve()
'optimal'
CLP_addConstraint(self, numberInRow, ndarray columns, ndarray elements, rowLower, rowUpper)

Add a constraint to the problem, CLP style. See CLP documentation. Not commonly used in cylp. For cylp modeling tool see cylp.python.modeling.CyLPModel.

CLP_addVariable(self, numberInColumn, ndarray rows, ndarray elements, columnLower, columnUpper, objective)

Add a variable to the problem, CLP style. See CLP documentation. For cylp modeling tool see cylp.python.modeling.CyLPModel.

CLP_deleteConstraints(self, ndarray which)

Delete constraints indexed by which from the LP.

CLP_deleteVariables(self, ndarray which)

Delete variables indexed by which from the LP.

CLP_dualConstraintSolution(self)
CLP_getVarStatus(self, int sequence)

get the status of a variable

  • free : 0
  • basic : 1
  • atUpperBound : 2
  • atLowerBound : 3
  • superBasic : 4
  • fixed : 5
Return type:int
CLP_setVarStatus(self, int sequence, int status)

set the status of a variable

  • free : 0
  • basic : 1
  • atUpperBound : 2
  • atLowerBound : 3
  • superBasic : 4
  • fixed : 5
addConstraint(self, cons, name='', addMpsNames=True)

Adds constraints cons to the problem. Example for the value of cons is 0 <= A * x <= b where A is a Numpy matrix and b is a CyLPArray.

addConstraints(self, number, ndarray rowLower, ndarray rowUpper, ndarray rowStarts, ndarray columns, ndarray elements)

Add number constraints at once, CLP style. For cylp modeling tool see cylp.python.modeling.CyLPModel.

addVariable(self, varname, dim, isInt=False)

Add variable var to the problem.

addVariables(self, number, ndarray columnLower, ndarray columnUpper, ndarray objective, ndarray columnStarts, ndarray rows, ndarray elements)

Add number variables at once, CLP style. For cylp modeling tool see cylp.python.modeling.CyLPModel.

argWeightedMax(self, arr, arr_ind, w, w_ind)
checkVar(self, i)
coefMatrix

The coefficient matrix. A scipy sparse matrix.

constraintScale

Array of constraints’ scale factors

Return type:Numpy array
constraints

Constraints.

constraintsLower

Constraints lower bounds

Return type:Numpy array
constraintsUpper

Constraints upper bounds

Return type:Numpy array
copyInIntegerInformation(self, ndarray colType)

Take in a character array containing 0-1 specifying whether or not a variable is integer

cost

Return the cost vector.

Return type:Numpy array
dual(self, ifValuesPass=0, startFinishOptions=0, presolve=False)

Runs CLP dual simplex.

Usage Example

>>> from cylp.cy.CyClpSimplex import CyClpSimplex, getMpsExample
>>> s = CyClpSimplex()
>>> f = getMpsExample()
>>> s.readMps(f)
0
>>> s.dual()
'optimal'
dualConstraintSolution

Dual variables’ solution

Return type:Numpy array
dualVariableSolution

Variables’ reduced costs

Return type:Numpy array
dualWithPresolve(self, feasibilityTolerance=0.0, keepIntegers=0, numberPasses=5, dropNames=0, doRowObjective=0)
evaluateAt(self, x0)

Evaluate the objective function at x0

extractCyLPModel(self, fileName, keepNames=False, ignoreErrors=False)
filterVars(self, inds)
flagged(self, varInd)

Returns 1 if variable index varInd is flagged.

Return type:int \(\in \{0, 1\}\)
freeOrSuperBasicVarInds

The index set of variables that are free or superbasic.

getACol(self, int ncol, CyCoinIndexedVector colArray)

Gets column ncol of A and store it in colArray.

getBInvACol(self, col, ndarray cl)

Compute \(A_B^{-1}A_{col}\) and store the result in cl.

getBInvCol(self, col, ndarray cl)

Return \(A_B^{-1}_{col}\) and store the result in cl.

getBasisStatus(self)
getCbcModel(self)

Run initialSolve, return a CyCbcModel object that can be used to add cuts, run B&B and …

getCoinInfinity(self)
getComplementarityList(self)
getConstraintStatus(self, arg)

Get the status of a constraint.

getPivotVariable(self)

Return the index set of the basic variables.

Return type:Numpy array
getReducedCosts(self)
getRightHandSide(self, ndarray rhs)

Take a spare array, rhs, and store the current right-hand-side in it.

getStatusArray(self)
getStatusCode(self)

Get the probelm status as defined in CLP. Return value could be:

  • -1 - unknown e.g. before solve or if postSolve says not optimal
  • 0 - optimal
  • 1 - primal infeasible
  • 2 - dual infeasible
  • 3 - stopped on iterations or time
  • 4 - stopped due to errors
  • 5 - stopped by event handler (virtual int ClpEventHandler::event())
getStatusString(self)

Return the problem status in string using the code from getStatusCode()

getUseCustomPrimal(self)

Return the value of useCustomPrimal. See useCustomPrimal().

Return type:int \(\in \{0, 1\}\)
getVarByName(self, name)
getVarNameByIndex(self, ind)
getVariableNames(self)

Return the variable name. (e.g. that was set in the mps file)

getVariableStatus(self, arg)

Get the status of a variable.

gradientAt(self, x0)
initialDualSolve(self)

Run CLP’s initalPrimalSolve. The same as initalSolve() but force the use of dual Simplex.

Usage example

>>> from cylp.cy.CyClpSimplex import CyClpSimplex, getMpsExample
>>> s = CyClpSimplex()
>>> f = getMpsExample()
>>> s.readMps(f)
0
>>> s.initialDualSolve()
'optimal'
>>> round(s.objectiveValue, 4)
2520.5717
initialPrimalSolve(self)

Run CLP’s initalPrimalSolve. The same as initalSolve() but force the use of primal Simplex.

Usage example

>>> from cylp.cy.CyClpSimplex import CyClpSimplex, getMpsExample
>>> s = CyClpSimplex()
>>> f = getMpsExample()
>>> s.readMps(f)
0
>>> s.initialPrimalSolve()
'optimal'
>>> round(s.objectiveValue, 4)
2520.5717
initialSolve(self, presolve='on')

Run CLP’s initialSolve. It does a presolve and uses primal or dual Simplex to solve a problem.

Usage example

>>> from cylp.cy.CyClpSimplex import CyClpSimplex, getMpsExample
>>> s = CyClpSimplex()
>>> f = getMpsExample()
>>> s.readMps(f)
0
>>> s.initialSolve()
'optimal'
>>> round(s.objectiveValue, 4)
2520.5717
integerInformation

A binary list of size nVariables that specifies whether a variable is integer or not. (ClpModel::integerInformation())

Return type:Numpy array
isInteger(self, ind)

Returns True if the variable index ind is integer.

isPivotAcceptable(self)
iteration

Number of iterations.

largestDualError(self)
loadFromCyLPModel(self, cyLPModel)

Set the coefficient matrix, constraint bounds, and variable bounds based on the data in cyLPModel which should be and object of CyLPModel class.

This method is usually called from CyClpSimplex’s constructor. But in a case that the CyClpSimplex instance is created before we have the CyLPModel we use this method to load the LP, for example:

>>> import numpy as np
>>> from cylp.cy.CyClpSimplex import CyClpSimplex, getModelExample
>>>
>>> s = CyClpSimplex()
>>> model = getModelExample()
>>> s.loadFromCyLPModel(model)
>>>
>>> s.primal()
'optimal'
>>> sol_x = s.primalVariableSolution['x']
>>> (abs(sol_x -
...     np.array([0.2, 2, 1.1]) ) <= 10**-6).all()
True
loadProblem(self, CyCoinPackedMatrix matrix, ndarray collb, ndarray colub, ndarray obj, ndarray rowlb, ndarray rowub, ndarray rowObjective=np.array([]))
loadProblemFromCyCoinModel(self, CyCoinModel modelObject, int tryPlusMinusOne=False)
loadQuadraticObjective(self, CyCoinPackedMatrix matrix)
lower

lower bounds (CLP’s lower_)

Return type:Numpy array
matrix

The coefficient matrix. A CyCoinPackedMatrix.

nCols

Number of columns, variables.

nConstraints

Number of constraints, rows.

nRows

Number of rows, constraints.

nVariables

Number of variables, columns.

notBasicOrFixedOrFlaggedVarInds

The index set of variables that are not basic or fixed.

objective

Set the objective function using this property. See the modeling example.

objectiveCoefficients

An alternative to self.objective, with a more meaningful name in a more general context. Sets and gets a numpy array.

objectiveOffset

The constant value in the objective function. A float.

objectiveValue

The objective value. Readonly.

partialPricing(self, start, end, ndarray numberWanted)

Perform partial pricing from variable start to variable end. Stop when numberWanted variables good variable checked.

pivotRow(self)

Return the index of the constraint corresponding to the (basic) leaving variable.

Return type:int
postSolve(self, updateStatus=True)
preSolve(self, feasibilityTolerance=0.0, keepIntegers=0, numberPasses=5, dropNames=0, doRowObjective=0)
primal(self, ifValuesPass=0, startFinishOptions=0, presolve=False)

Solve the problem using the primal simplex algorithm. See this usage example.

startFinishOptions is a string containing one or more of the following characters: ‘x’: do not delete work areas ‘f’: use old factorization if possible ‘s’: skip initialization of work areas So one might call self.primal(startFinishOptions='sx')

primalConstraintSolution

Slack variables’ solution

Return type:Numpy array
primalVariableSolution

Solution to the primal variables.

Return type:Numpy array
primalVariableSolutionAll

Solution to the primal variables. Including the slacks.

Return type:Numpy array
primalWithPresolve(self, feasibilityTolerance=0.0, keepIntegers=0, numberPasses=5, dropNames=0, doRowObjective=0)
readLp(self, char *filename, epsilon=10 ** -5)
readMps(self, filename, int keepNames=False, int ignoreErrors=False) → int

Read an mps file. See this modeling example.

reducedCosts

The reduced costs. A Numpy array.

Return type:Numpy array
removeConstraint(self, name)

Removes constraint named name from the problem.

removeVariable(self, name)

Removes variable named name from the problem.

replaceMatrix(self, CyCoinPackedMatrix matrix, deleteCurrent=False)
resize(self, newNumberRows, newNumberColumns)

Resize the problem. After a call to resize the problem will have newNumberRows constraints and newNumberColumns variables.

sequenceIn(self)

Return the index of the entering variable.

Return type:int
setBasisStatus(self, ndarray cstat, ndarray rstat)
setColumnLower(self, ind, val)

Set the lower bound of variable index ind to val.

setColumnLowerArray(self, ndarray columnLower)

columnLower should have n+m elements. The method only does a pointer assignment. If you only want to set the first n elements use setColumnLowerFirstElements().

setColumnLowerFirstElements(self, ndarray columnLower)

Run a loop in C++ and set the first n elements of variables’ lowerbounds

setColumnLowerSubset(self, ndarray indicesOfIndices, ndarray indices, ndarray columnLower)

This method is defined for a very specific purpose. It’s only to be used to speed up self.addConstraint()

setColumnUpper(self, ind, val)

Set the upper bound of variable index ind to val.

setColumnUpperArray(self, ndarray columnUpper)

columnUpper should have n+m elements. The method only does a pointer assignment. If you only want to set the first n elements use setColumnUpperFirstElements().

setColumnUpperFirstElements(self, ndarray columnUpper)

Run a loop in C++ and set the first n elements of variables’ upperbounds

setColumnUpperSubset(self, ndarray indicesOfIndices, ndarray indices, ndarray columnUpper)

This method is defined for a very specific purpose. It’s only to be used to speed up self.addConstraint()

setComplement(self, var1, var2)

Set var1 as the complementary variable of var2. These arguments may be integers signifying indices, or CyLPVars.

setComplementarityList(self, ndarray cl)
setConstraintName(self, constInd, name)

Set the name of constraint index constInd to name.

Parameters:
  • constInd (integer) – constraint index
  • name (string) – desired name for the constraint
setConstraintStatus(self, arg, status)

Set the status of a constraint.

Parameters:
  • arg – Specifies the constraint to change (name or index)
  • status (string) – ‘basic’, ‘atUpperBound’, ‘atLowerBound’, ‘superBasic’, ‘fixed’
>>> from cylp.cy.CyClpSimplex import CyClpSimplex
>>> s = CyClpSimplex()
>>> x = s.addVariable('x', 4)
>>> s.addConstraint(0 <= x[0] + x[1] <= 1, 'const1')
>>> # Using constraint name:
>>> s.setConstraintStatus('const1', 'atUpperBound')
>>> s.getConstraintStatus('const1')
'atUpperBound'
>>> # Using constraint index directly
>>> s.setConstraintStatus(0, 'atLowerBound')
>>> s.getConstraintStatus('const1')
'atLowerBound'
setDualPivotMethod(self, dualPivotMethodObject)

Takes a python object and sets it as the dual pivot rule. dualPivotObjectMethod should implement DualPivotPythonBase. See how to use custom dual Python pivots to solve LPs.

setFlagged(self, varInd)

Set variables index varInd flagged.

setInteger(self, arg)

if arg is an integer: mark variable index arg as integer. if arg is a CyLPVar object: mark variable arg as integer. Here is an example of the latter:

>>> import numpy as np
>>> from cylp.cy import CyClpSimplex
>>> from cylp.py.modeling.CyLPModel import CyLPModel, CyLPArray
>>> model = CyLPModel()
>>>
>>> x = model.addVariable('x', 3)
>>> y = model.addVariable('y', 2)
>>>
>>> A = np.matrix([[1., 2., 0],[1., 0, 1.]])
>>> B = np.matrix([[1., 0, 0], [0, 0, 1.]])
>>> D = np.matrix([[1., 2.],[0, 1]])
>>> a = CyLPArray([5, 2.5])
>>> b = CyLPArray([4.2, 3])
>>> x_u= CyLPArray([2., 3.5])
>>>
>>> model += A*x <= a
>>> model += 2 <= B * x + D * y <= b
>>> model += y >= 0
>>> model += 1.1 <= x[1:3] <= x_u
>>>
>>> c = CyLPArray([1., -2., 3.])
>>> model.objective = c * x + 2 * y.sum()
>>>
>>>
>>> s = CyClpSimplex(model)
>>> s.setInteger(x[1:3])
>>>
>>> cbcModel = s.getCbcModel()
>>> cbcModel.solve()
0
>>> print(cbcModel.status)
'solution'
>>>
>>> sol_x = cbcModel.primalVariableSolution['x']
>>> (abs(sol_x -
...     np.array([0.5, 2, 2]) ) <= 10**-6).all()
True
>>> sol_y = cbcModel.primalVariableSolution['y']
>>> (abs(sol_y -
...     np.array([0, 0.75]) ) <= 10**-6).all()
True
setObjectiveArray(self, ndarray objective)
setObjectiveCoefficient(self, elementIndex, elementValue)

Set the objective coefficients using sparse vector elements elementIndex and elementValue.

setPerturbation(self, value)

Perturb the problem by value.

setPivotMethod(self, pivotMethodObject)

Takes a python object and sets it as the primal simplex pivot rule. pivotObjectMethod should implement PivotPythonBase. See how to use custom Python pivots to solve LPs.

setPivotRow(self, v)

Set the v’th variable of the basis as the leaving variable.

setPrimalColumnPivotAlgorithmToPE(self)

Set primal simplex’s pivot rule to the Cython implementation of positive edge

setPrimalColumnPivotAlgorithmToWolfe(self)

Set primal simplex’s pivot rule to the Cython implementation of Wolfe’s rule used to solve QPs.

setRowLower(self, ind, val)

Set the lower bound of constraint index ind to val.

setRowLowerArray(self, ndarray rowLower)
setRowUpper(self, ind, val)

Set the upper bound of constraint index ind to val.

setRowUpperArray(self, ndarray rowUpper)
setSequenceIn(self, v)

Set the variable index v as the entering variable.

setVariableName(self, varInd, name)

Set the name of variable index varInd to name.

Parameters:
  • varInd (integer) – variable index
  • name (string) – desired name for the variable
setVariableStatus(self, arg, status)

Set the status of a variable.

Parameters:
  • arg – Specifies the variable to change (a CyLPVar, or an index)
  • status (string) – ‘basic’, ‘atUpperBound’, ‘atLowerBound’, ‘superBasic’, ‘fixed’

Example:

>>> from cylp.cy.CyClpSimplex import CyClpSimplex
>>> s = CyClpSimplex()
>>> x = s.addVariable('x', 4)
>>> # Using CyLPVars:
>>> s.setVariableStatus(x[1:3], 'basic')
>>> s.getVariableStatus(x[1])
'basic'
>>> # Using a variable index directly
>>> s.setVariableStatus(1, 'atLowerBound')
>>> s.getVariableStatus(x[1])
'atLowerBound'
solution

Return the current point.

Return type:Numpy array
status

A Numpy array of all the variables’ status

transposeTimes(self, scalar, CyCoinIndexedVector x, CyCoinIndexedVector y, CyCoinIndexedVector z)

Compute \(x * scalar * A + y\) and store the result in z.

transposeTimesSubset(self, number, ndarray which, ndarray pi, ndarray y)

Compute \(y_{which} - pi^{T}A_{which}\) where which is a variable index set. Store the result in y.

transposeTimesSubsetAll(self, ndarray which, ndarray pi, ndarray y)

Same as transposeTimesSubset() but here which can also address slack variables.

updateColumnFT(self, CyCoinIndexedVector spare, CyCoinIndexedVector updatedColumn)
updateColumnTranspose(self, CyCoinIndexedVector regionSparse1, CyCoinIndexedVector regionSparse2)
upper

upper bounds (CLP’s upper_)

Return type:Numpy array
useCustomPrimal(self, customPrimal)

Determines if cylp.python.pivot.PivotPythonBase.isPivotAcceptable() should be called just before each pivot is performed (right after the entering and leaving variables are obtained.

varIsAtLowerBound

The index set of variables that are at their lower bound.

varIsAtUpperBound

The index set of variables that are at their upper bound.

varIsBasic

The index set of variables that are basic.

varIsFixed

The index set of variables that are fixed.

varIsFlagged

The index set of variables that are flagged.

varIsFree

The index set of variables that are free.

varIsSuperBasic

The index set of variables that are superbasic.

varNotAtLowerBound

The index set of variables that are NOT at their lower bound.

varNotAtUpperBound

The index set of variables that are NOT at their upper bound.

varNotBasic

The index set of variables that are NOT basic.

varNotFixed

The index set of variables that are NOT fixed.

varNotFlagged

The index set of variables that are NOT flagged.

varNotFree

The index set of variables that are NOT free.

varNotSuperBasic

The index set of variables that are NOT superbasic.

variableNames

variable names

variableScale

Array of variables’ scale factors

Return type:Numpy array
variables

Variables.

variablesLower

Variables lower bounds

Return type:Numpy array
variablesUpper

Variables upper bounds

Return type:Numpy array
vectorTimesB_1(self, CyCoinIndexedVector vec)

Compute \(vec A_B^{-1}\) and store it in vec.

writeLp(self, filename, extension='', epsilon=10 ** -5, numberAcross=10, decimals=5, objSense=0.0, useRowNames=1)
writeMps(self, filename, formatType=0, numberAcross=2, objSense=0)