or run

tessl search
Log in

Version

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/ecos@2.0.x

docs

api-reference.mdexamples.mdindex.mdtroubleshooting.mdtypes-and-formats.md
tile.json

tessl/pypi-ecos

tessl install tessl/pypi-ecos@2.0.1

Python interface to ECOS, a numerical solver for convex second-order cone programs.

index.mddocs/

ECOS - Quick Reference

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.

Installation

pip install ecos

Essential Import

import ecos
import numpy as np
import scipy.sparse as sp

Quick Start Patterns

Pattern 1: Linear Programming (Most Common)

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

Pattern 2: Linear Programming with Equality Constraints

# 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']

Pattern 3: Second-Order Cone Constraints

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

Pattern 4: Mixed-Integer Programming

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

Core API

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:

  • G and A MUST be scipy.sparse.csc_matrix (use sp.csc_matrix())
  • Provide A and b together (both or neither)
  • dims['l'] must be non-negative integer
  • dims['q'] must be list (can be empty [])

Common Solver Options

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 Structure

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

Problem Formulation Reference

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:

  • Positive orthant (R₊): Linear inequalities, specified by dims['l']
  • Second-order cones (Q_n): Constraints like ||x|| ≤ t, specified by dims['q']
  • Exponential cones (optional): Specified by dims['e']

Cone Dimensions Examples

# 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}

Critical Error Prevention

Matrix Format Errors

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 array

Dimension Mismatch Errors

Problem: 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 count

Constraint/Dimension Mismatch

Problem: 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 ✗

Type Validation Errors

Common type requirements:

  • max_iters, nitref, mi_max_iters: Must be integers
  • feastol, abstol, reltol, tolerances: Must be positive floats
  • verbose, mi_verbose: Must be booleans
  • bool_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 bool

Version Information

ecos.__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__}")

Integration with CVXPY

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)

When to Use ECOS

Best For:

  • Linear programs with moderate size
  • Second-order cone programs (SOCP)
  • Problems with L2 norm constraints
  • Mixed-integer convex optimization
  • When you need a lightweight, embedded solver

Not Suitable For:

  • Semidefinite programs (use SCS or MOSEK)
  • Non-convex problems
  • Very large-scale problems (millions of variables)
  • Problems requiring high precision (1e-12 or better)

Package Information

  • Package Name: ecos
  • Package Type: PyPI
  • Language: Python (wraps C implementation)
  • Installation: pip install ecos
  • License: GPLv3
  • Documentation Version: 2.0.14

Additional Resources

For more detailed information, see:

  • API Reference - Complete API documentation with all parameters and error types
  • Examples - Extended examples organized by complexity
  • Types and Formats - Detailed type specifications and data structures
  • Troubleshooting - Common issues, errors, and solutions