tessl install tessl/pypi-ecos@2.0.1Python interface to ECOS, a numerical solver for convex second-order cone programs.
ECOS (Embedded Conic Solver) is a numerical solver for convex second-order cone programs (SOCPs). This guide provides fast access to the most common patterns for coding agents.
pip install ecosimport ecos
import numpy as np
import scipy.sparse as spMinimize a linear objective subject to linear inequality constraints.
import ecos
import numpy as np
import scipy.sparse as sp
# minimize c'*x subject to G*x <= h
c = np.array([-1.0]) # Objective coefficients
G = sp.csc_matrix([[1.0], [-1.0]]) # MUST be CSC format
h = np.array([4.0, 0.0]) # RHS values
dims = {'l': 2, 'q': []} # 2 linear constraints, no SOCs
solution = ecos.solve(c, G, h, dims, verbose=False)
optimal_x = solution['x']
optimal_value = np.dot(c, optimal_x)# minimize c'*x subject to A*x = b AND G*x <= h
c = np.array([-1.0])
G = sp.csc_matrix([[1.0]]) # Inequality constraints
h = np.array([4.0])
A = sp.csc_matrix([[1.0]]) # Equality constraints (MUST be CSC)
b = np.array([3.0])
dims = {'l': 1, 'q': []}
solution = ecos.solve(c, G, h, dims, A, b)
optimal_x = solution['x']# Constraints like ||x|| <= t (L2 norm bound)
c = np.array([-1.0, 0.0])
G = sp.csc_matrix([[1.0, 0.0], [0.0, 1.0]])
h = np.array([0.0, 0.0])
dims = {'l': 0, 'q': [2]} # One SOC of dimension 2
solution = ecos.solve(c, G, h, dims)# With boolean or integer variables
c = np.array([-1.0, -1.0])
G = sp.csc_matrix([[2.0, 1.0], [3.0, 4.0]])
h = np.array([4.0, 12.0])
dims = {'l': 2, 'q': []}
# Specify variable types by index
solution = ecos.solve(
c, G, h, dims,
bool_vars_idx=[1], # x[1] is boolean
int_vars_idx=[], # No integer vars in this example
verbose=False
)def solve(c, G, h, dims, A=None, b=None, **kwargs):
"""
Solve convex second-order cone program.
minimize c'*x
subject to A*x = b (equality constraints)
G*x <=_K h (cone constraints)
Required Parameters:
- c: Objective coefficients (numpy.ndarray, shape (n,))
- G: Inequality constraint matrix (scipy.sparse.csc_matrix, shape (m, n))
- h: Inequality RHS vector (numpy.ndarray, shape (m,))
- dims: Cone dimensions (dict)
- 'l': Number of linear inequalities (int)
- 'q': List of second-order cone dimensions (list of ints)
- 'e': Number of exponential cones (int, optional)
Optional Parameters:
- A: Equality constraint matrix (scipy.sparse.csc_matrix, shape (p, n))
- b: Equality RHS vector (numpy.ndarray, shape (p,))
Returns:
- dict with keys: 'x', 'y', 's', 'z', 'info'
"""Critical Requirements:
sp.csc_matrix())[])solution = ecos.solve(
c, G, h, dims,
# Tolerances (all must be positive floats)
feastol=1e-8, # Feasibility tolerance
abstol=1e-8, # Absolute convergence tolerance
reltol=1e-8, # Relative convergence tolerance
# Iteration limits (non-negative integers)
max_iters=100, # Maximum solver iterations
nitref=9, # Iterative refinement steps
# Output control (booleans)
verbose=True, # Show solver progress
mi_verbose=False, # Show mixed-integer progress
# Mixed-integer options
bool_vars_idx=[], # Indices of boolean variables
int_vars_idx=[], # Indices of integer variables
mi_max_iters=1000, # Max branch-and-bound iterations
mi_abs_eps=1e-6, # Absolute gap tolerance
mi_rel_eps=1e-3, # Relative gap tolerance
)solution = {
'x': np.ndarray, # Primal solution, shape (n,)
'y': np.ndarray, # Dual for equality constraints, shape (p,) or empty
's': np.ndarray, # Slack variables, shape (m,)
'z': np.ndarray, # Dual for cone constraints, shape (m,)
'info': dict # Solver statistics (iterations, status, timing)
}
# Access results
optimal_x = solution['x']
optimal_value = np.dot(c, optimal_x)
solver_status = solution['info']ECOS solves problems of the form:
minimize c'*x
subject to A*x = b (equality constraints)
G*x <=_K h (generalized inequality)The cone K is a Cartesian product of:
dims['l']||x|| ≤ t, specified by dims['q']dims['e']# Only linear inequalities
dims = {'l': 5, 'q': []}
# Only second-order cones (two cones: Q₃ and Q₄)
dims = {'l': 0, 'q': [3, 4]}
# Mixed: 2 linear + one Q₃ cone + one Q₅ cone
dims = {'l': 2, 'q': [3, 5]}
# With exponential cones
dims = {'l': 2, 'q': [3], 'e': 1}Problem: TypeError: G must be a sparse matrix
Solution: Always convert to CSC format:
# Correct
G = sp.csc_matrix([[1.0, 2.0], [3.0, 4.0]])
# Also correct (from dense array)
G_dense = np.array([[1.0, 2.0], [3.0, 4.0]])
G = sp.csc_matrix(G_dense)
# Wrong - will cause error
G = [[1.0, 2.0], [3.0, 4.0]] # Plain list
G = np.array([[1.0, 2.0], [3.0, 4.0]]) # Dense arrayProblem: TypeError: columns of A and G don't match
Solution: Ensure consistent variable count:
n = 3 # Number of variables
G = sp.csc_matrix(np.random.randn(5, n)) # m=5 constraints, n=3 vars
A = sp.csc_matrix(np.random.randn(2, n)) # p=2 constraints, SAME n=3 vars
h = np.zeros(5) # Must match G rows
b = np.zeros(2) # Must match A rows
c = np.zeros(n) # Must match variable countProblem: ValueError: dims don't match constraint dimensions
Solution: Total cone dimensions must equal G rows:
# If G has 7 rows:
G = sp.csc_matrix(np.random.randn(7, 3))
h = np.zeros(7)
# dims must sum to 7
dims = {'l': 3, 'q': [4]} # 3 + 4 = 7 ✓
dims = {'l': 2, 'q': [2, 3]} # 2 + 2 + 3 = 7 ✓
dims = {'l': 7, 'q': []} # 7 + 0 = 7 ✓
# Wrong
dims = {'l': 5, 'q': []} # 5 ≠ 7 ✗Common type requirements:
max_iters, nitref, mi_max_iters: Must be integersfeastol, abstol, reltol, tolerances: Must be positive floatsverbose, mi_verbose: Must be booleansbool_vars_idx, int_vars_idx: Must be lists of integers# Correct
solution = ecos.solve(c, G, h, dims, max_iters=100, verbose=True)
# Wrong - will cause TypeError
solution = ecos.solve(c, G, h, dims, max_iters=100.5) # Float instead of int
solution = ecos.solve(c, G, h, dims, verbose="true") # String instead of boolecos.__version__ # Python package version (str)
ecos.__solver_version__ # C solver version (str)Example:
import ecos
print(f"ECOS Python: {ecos.__version__}")
print(f"ECOS Solver: {ecos.__solver_version__}")ECOS is a default solver in CVXPY (convex optimization modeling):
import cvxpy as cp
x = cp.Variable(2)
objective = cp.Minimize(cp.norm(x, 2) + cp.norm(x, 1))
constraints = [x >= 2]
problem = cp.Problem(objective, constraints)
# Solve with ECOS
problem.solve(solver=cp.ECOS)
print("Optimal value:", problem.value)
print("Optimal x:", x.value)Best For:
Not Suitable For:
pip install ecosFor more detailed information, see: