Linear programming
To solve a linear program, simply build the matrices that define it and call
the solve_lp()
function:
from numpy import array
from lpsolvers import solve_lp
c = array([1., 2., 3.])
G = array([[1., 2., -1.], [2., 0., 1.], [1., 2., 1.], [-1., -1., -1.]])
h = array([4., 1., 3., 2.])
x = solve_lp(c, G, h)
print(f"LP solution: x = {x}")
This example outputs the solution [0.30769231, -0.69230769, 1.38461538]
.
The solve_qp()
function accepts a solver
keyword argument to select
the backend solver:
- lpsolvers.solve_lp(c, G, h, A=None, b=None, solver=None, **kwargs)
Solve a linear program using one of the available LP solvers.
The linear program is defined as:
\[\begin{split}\begin{split}\begin{array}{ll} \mbox{minimize} & c^T x \\ \mbox{subject to} & G x \leq h \\ & A x = b \end{array}\end{split}\end{split}\]- Parameters:
c (
ndarray
) – Linear cost vector.G (
ndarray
) – Linear inequality constraint matrix.h (
ndarray
) – Linear inequality constraint vector.A (
Optional
[ndarray
]) – Linear equality constraint matrix.b (
Optional
[ndarray
]) – Linear equality constraint vector.solver (
Optional
[str
]) – Name of the LP solver to choose inlpsolvers.available_solvers
.
- Return type:
ndarray
- Returns:
Optimal solution if found,
None
otherwise.- Raises:
ValueError – If the LP is not feasible.
SolverNotFound – If the requested LP solver is not found.
Notes
Extra keyword arguments given to this function are forwarded to the underlying solver. For example, we can call ProxQP with a custom absolute feasibility tolerance by
solve_lp(c, G, h, solver='proxqp', eps_abs=1e-8)
.
Installed solvers are listed in:
- lpsolvers.available_solvers = ['cdd', 'cvxopt', 'cvxpy', 'pdlp', 'proxqp']
Built-in mutable sequence.
If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.
See the examples/
folder in the repository for other use cases. For more
context you can also check out this post on linear programming in Python.