Python Wrapper for Embedded Conic Solver (ECOS)
ECOS is a lightweight numerical solver for convex second-order cone programs (SOCPs) designed for embedded systems. This library provides its Python interface. It is actively maintained, with version 2.0.14 released in June 2024, and receives regular updates to its Python wrapper.
Warnings
- breaking Starting with version 2.0.8, the `ecos-python` wrapper officially dropped support for Python 2.7. Users on older Python versions must upgrade to Python 3 or use an older `ecos` version.
- gotcha The 2.0.7 release had issues with version syncing, leading to its removal and re-upload as a post-release (e.g., `2.0.7.post1`). Strict dependency pinning to `2.0.7` might fail.
- gotcha Installing `ecos` from source on Windows can be challenging due to compiler requirements, especially for older Python versions. The official documentation suggests using Miniconda to minimize pain.
- gotcha The `CVXPY` library, which often uses ECOS as a solver, changed its default solver from ECOS to Clarabel in version 1.5 and plans to remove ECOS as a default dependency in 1.6. Users relying on ECOS via CVXPY should be aware.
- gotcha The `ecos.solve` function expects sparse matrices `G` and `A` to be in `scipy.sparse.csr_matrix` format. While it attempts to convert other formats, providing them in CSR format is more efficient and avoids potential conversion overhead or unexpected behavior.
Install
-
pip install ecos
Imports
- ecos
import ecos
Quickstart
import numpy as np
from scipy import sparse
import ecos
# Define a simple Linear Program (LP) as an SOCP
# Minimize: x[0] + x[1]
# Subject to: x[0] >= 0, x[1] >= 0, x[0] + x[1] >= 1
# Objective vector c: Minimize x[0] + x[1]
c = np.array([1., 1.])
# Inequality constraints Gx <= h (linear cone part)
# -x[0] <= 0
# -x[1] <= 0
# -x[0] - x[1] <= -1 (equivalent to x[0] + x[1] >= 1)
G = sparse.csr_matrix([
[-1., 0.],
[0., -1.],
[-1., -1.]
])
h = np.array([0., 0., -1.])
# Dimensions of the cones
dims = {
'l': 3, # Number of linear inequality constraints
'q': [], # List of second-order cone dimensions
'e': 0 # Number of exponential cone constraints
}
# Solve the problem
solution = ecos.solve(c, G, h, dims)
# Print the optimal solution
print(f"Optimal x: {solution['x']}")
print(f"Optimal value: {solution['info']['pcost']}")