cylp.cy.CyClpSimplex

class cylp.cy.CyClpSimplex.CyClpSimplex[source]

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[int32_t,ndim=1], ndarray[double_t,ndim=1], rowLower, rowUpper)[source]

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[int32_t,ndim=1], ndarray[double_t,ndim=1], columnLower, columnUpper, objective)[source]

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

CLP_deleteConstraints(self, ndarray[int32_t,ndim=1])[source]

Delete constraints indexed by which from the LP.

CLP_deleteVariables(self, ndarray[int32_t,ndim=1])[source]

Delete variables indexed by which from the LP.

CLP_dualConstraintSolution(self)[source]
CLP_getVarStatus(self, int sequence)[source]

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

set the status of a variable

  • free : 0

  • basic : 1

  • atUpperBound : 2

  • atLowerBound : 3

  • superBasic : 4

  • fixed : 5

Hessian[source]

The Hessian of the objective, i.e. \(Q\) in \(c^T x + \frac{1}{2} x^T Q x\), as a symmetric matrix. It can be set to any matrix that implements tocoo, such as a scipy sparse matrix. Only its symmetric part, \((Q + Q^T) / 2\), matters, and that is what is kept.

addConstraint(self, cons, name='', addMpsNames=True)[source]

Adds constraints cons to the problem. Example for the value of cons is 0 <= A @ x <= b where A is a 2-d NumPy array and b is a CyLPArray.

addConstraints(self, number, ndarray[double_t,ndim=1], ndarray[double_t,ndim=1], ndarray[int32_t,ndim=1], ndarray[int32_t,ndim=1], ndarray[double_t,ndim=1])[source]

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

addVariable(self, varname, dim, isInt=False)[source]

Add variable var to the problem.

addVariables(self, number, ndarray[double_t,ndim=1], ndarray[double_t,ndim=1], ndarray[double_t,ndim=1], ndarray[int32_t,ndim=1], ndarray[int32_t,ndim=1], ndarray[double_t,ndim=1])[source]

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

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

The coefficient matrix. A scipy sparse matrix.

constraintScale[source]

Array of constraints’ scale factors

Return type:

Numpy array

constraints[source]

Constraints.

constraintsLower[source]

Constraints lower bounds

Return type:

Numpy array

constraintsUpper[source]

Constraints upper bounds

Return type:

Numpy array

copyInIntegerInformation(self, ndarray[uint8_t,ndim=1])[source]

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

cost[source]

Return the cost vector.

Return type:

Numpy array

dual(self, ifValuesPass=0, startFinishOptions=0, presolve=False)[source]

Runs CLP dual simplex. It ignores the quadratic part of the objective, so use primal() or initialSolve() to solve a QP.

Usage Example

>>> from cylp.cy.CyClpSimplex import CyClpSimplex, getMpsExample
>>> s = CyClpSimplex()
>>> f = getMpsExample()
>>> s.readMps(f)
0
>>> s.dual()
'optimal'
dualColumnSolution[source]

Variables’ reduced costs as one array, in column order. Unlike dualVariableSolution, it is not split up by variable. A copy.

Return type:

Numpy array

dualConstraintSolution[source]

Dual variables’ solution

Return type:

Numpy array

dualVariableSolution[source]

Variables’ reduced costs

Return type:

Numpy array

dualWithPresolve(self, feasibilityTolerance=0.0, keepIntegers=0, numberPasses=5, dropNames=0, doRowObjective=0)[source]
evaluateAt(self, x0)[source]

Evaluate the objective function at x0

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

Returns 1 if variable index varInd is flagged.

Return type:

int \(\in \{0, 1\}\)

freeOrSuperBasicVarInds[source]

The index set of variables that are free or superbasic.

getACol(self, int ncol, CyCoinIndexedVector colArray)[source]

Gets column ncol of A and store it in colArray.

getBInvACol(self, col, ndarray[double_t,ndim=1])[source]

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

getBInvCol(self, col, ndarray[double_t,ndim=1])[source]

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

getBasisStatus(self)[source]
getCbcModel(self)[source]

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

getCoinInfinity(self)[source]
getComplementarityList(self)[source]
getConstraintStatus(self, arg)[source]

Get the status of a constraint.

getPivotVariable(self)[source]

Return the index set of the basic variables.

Return type:

Numpy array

getReducedCosts(self)[source]
getRightHandSide(self, ndarray[double_t,ndim=1])[source]

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

getStatusArray(self)[source]
getStatusCode(self)[source]

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

  • 10 - stopped, try another algorithm

getStatusString(self)[source]

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

getUseCustomPrimal(self)[source]

Return the value of useCustomPrimal. See useCustomPrimal().

Return type:

int \(\in \{0, 1\}\)

getVarByName(self, name)[source]
getVarNameByIndex(self, ind)[source]
getVariableNames(self)[source]

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

getVariableStatus(self, arg)[source]

Get the status of a variable.

gradientAt(self, x0)[source]
initialDualSolve(self)[source]

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

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')[source]

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[source]

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

Return type:

Numpy array

isInteger(self, ind)[source]

Returns True if the variable index ind is integer.

isPivotAcceptable(self)[source]
iteration[source]

Number of iterations.

largestDualError(self)[source]
loadFromCyLPModel(self, cyLPModel)[source]

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[double_t,ndim=1], ndarray[double_t,ndim=1], ndarray[double_t,ndim=1], ndarray[double_t,ndim=1], ndarray[double_t,ndim=1], ndarray[double_t,ndim=1]=np.array([]))[source]
loadProblemFromCyCoinModel(self, CyCoinModel modelObject, int tryPlusMinusOne=False)[source]
loadQuadraticObjective(self, CyCoinPackedMatrix matrix)[source]

Make \(\frac{1}{2} x^T Q x\) part of the objective, where matrix is one triangle of \(Q\), as in a QPS file: Clp counts each element off the diagonal twice. To give the whole of \(Q\) instead, set Hessian.

lower[source]

lower bounds (CLP’s lower_)

Return type:

Numpy array

matrix[source]

The coefficient matrix. A CyCoinPackedMatrix, or None if the model was never loaded.

nCols[source]

Number of columns, variables.

nConstraints[source]

Number of constraints, rows.

nRows[source]

Number of rows, constraints.

nVariables[source]

Number of variables, columns.

notBasicOrFixedOrFlaggedVarInds[source]

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

objective[source]

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

objectiveCoefficients[source]

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

objectiveOffset[source]

The constant value in the objective function. A float.

objectiveValue[source]

The objective value. Readonly.

partialPricing(self, start, end, ndarray[int32_t,ndim=1])[source]

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

pivotRow(self)[source]

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

Return type:

int

postSolve(self, updateStatus=True)[source]
preSolve(self, feasibilityTolerance=0.0, keepIntegers=0, numberPasses=5, dropNames=0, doRowObjective=0)[source]
primal(self, ifValuesPass=0, startFinishOptions=0, presolve=False)[source]

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

primalColumnSolution[source]

Solution to the primal variables as one array, in column order. Unlike primalVariableSolution, it is not split up by variable, which is much faster for large models. A copy.

Return type:

Numpy array

primalConstraintSolution[source]

Slack variables’ solution

Return type:

Numpy array

primalVariableSolution[source]

Solution to the primal variables.

Return type:

Numpy array

primalVariableSolutionAll[source]

Solution to the primal variables, followed by the slacks (the constraints’ activities), as one array. A copy.

Return type:

Numpy array

primalWithPresolve(self, feasibilityTolerance=0.0, keepIntegers=0, numberPasses=5, dropNames=0, doRowObjective=0)[source]
readLp(self, char *filename, epsilon=10 ** -5)[source]
readMps(self, filename, int keepNames=False, int ignoreErrors=False) → int[source]

Read an mps file. See this modeling example.

reducedCosts[source]

The reduced costs. A Numpy array.

Return type:

Numpy array

removeConstraint(self, name)[source]

Removes constraint named name from the problem.

removeVariable(self, name)[source]

Removes variable named name from the problem.

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

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

sequenceIn(self)[source]

Return the index of the entering variable.

Return type:

int

setBasisStatus(self, ndarray[int32_t,ndim=1], ndarray[int32_t,ndim=1])[source]
setColumnLower(self, ind, val)[source]

Set the lower bound of variable index ind to val.

setColumnLowerArray(self, ndarray[double_t,ndim=1])[source]

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[double_t,ndim=1])[source]

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

setColumnLowerSubset(self, ndarray[int32_t,ndim=1], ndarray[int32_t,ndim=1], ndarray[double_t,ndim=1])[source]

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

setColumnUpper(self, ind, val)[source]

Set the upper bound of variable index ind to val.

setColumnUpperArray(self, ndarray[double_t,ndim=1])[source]

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[double_t,ndim=1])[source]

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

setColumnUpperSubset(self, ndarray[int32_t,ndim=1], ndarray[int32_t,ndim=1], ndarray[double_t,ndim=1])[source]

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

setComplement(self, var1, var2)[source]

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

setComplementarityList(self, ndarray[int32_t,ndim=1])[source]
setConstraintName(self, constInd, name)[source]

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

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

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

Set variables index varInd flagged.

setInteger(self, arg)[source]

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.array([[1., 2., 0],[1., 0, 1.]])
>>> B = np.array([[1., 0, 0], [0, 0, 1.]])
>>> D = np.array([[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
>>>
>>> # Several solutions are optimal, but they all have the same
>>> # objective value, and x[1:3] = [2, 2]
>>> round(cbcModel.objectiveValue, 6)
4.0
>>> sol_x = cbcModel.primalVariableSolution['x']
>>> (abs(sol_x[1:3] - np.array([2, 2])) <= 10**-6).all()
True
setObjectiveArray(self, ndarray[double_t,ndim=1])[source]
setObjectiveCoefficient(self, elementIndex, elementValue)[source]

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

setPerturbation(self, value)[source]

Perturb the problem by value.

setPivotMethod(self, pivotMethodObject)[source]

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

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

setPrimalColumnPivotAlgorithmToPE(self)[source]

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

setPrimalColumnPivotAlgorithmToWolfe(self)[source]

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

setRowLower(self, ind, val)[source]

Set the lower bound of constraint index ind to val.

setRowLowerArray(self, ndarray[double_t,ndim=1])[source]
setRowUpper(self, ind, val)[source]

Set the upper bound of constraint index ind to val.

setRowUpperArray(self, ndarray[double_t,ndim=1])[source]
setSequenceIn(self, v)[source]

Set the variable index v as the entering variable.

setVariableName(self, varInd, name)[source]

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

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[source]

Return the current point.

Return type:

Numpy array

status[source]

A Numpy array of all the variables’ status

transposeTimes(self, scalar, CyCoinIndexedVector x, CyCoinIndexedVector y, CyCoinIndexedVector z)[source]

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

transposeTimesSubset(self, number, ndarray[int64_t,ndim=1], ndarray[double_t,ndim=1], ndarray[double_t,ndim=1])[source]

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

transposeTimesSubsetAll(self, ndarray[int64_t,ndim=1], ndarray[double_t,ndim=1], ndarray[double_t,ndim=1])[source]

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

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

upper bounds (CLP’s upper_)

Return type:

Numpy array

useCustomPrimal(self, customPrimal)[source]

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[source]

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

varIsAtUpperBound[source]

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

varIsBasic[source]

The index set of variables that are basic.

varIsFixed[source]

The index set of variables that are fixed.

varIsFlagged[source]

The index set of variables that are flagged.

varIsFree[source]

The index set of variables that are free.

varIsSuperBasic[source]

The index set of variables that are superbasic.

varNotAtLowerBound[source]

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

varNotAtUpperBound[source]

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

varNotBasic[source]

The index set of variables that are NOT basic.

varNotFixed[source]

The index set of variables that are NOT fixed.

varNotFlagged[source]

The index set of variables that are NOT flagged.

varNotFree[source]

The index set of variables that are NOT free.

varNotSuperBasic[source]

The index set of variables that are NOT superbasic.

variableNames[source]

variable names

variableScale[source]

Array of variables’ scale factors

Return type:

Numpy array

variables[source]

Variables.

variablesLower[source]

Variables lower bounds

Return type:

Numpy array

variablesUpper[source]

Variables upper bounds

Return type:

Numpy array

vectorTimesB_1(self, CyCoinIndexedVector vec)[source]

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)[source]
writeMps(self, filename, formatType=0, numberAcross=2, objSense=0)[source]