CVXPY
CVXPY is a Python-embedded modeling language for convex optimization problems. It allows users to express optimization problems in a natural way that follows mathematical notation, automatically transforming them into standard form, calling a solver, and unpacking the results. It is actively maintained with frequent patch releases, and major versions (e.g., 1.8.x) are supported with bugfixes while the next major release (e.g., 1.9) is under development, with older major versions no longer officially supported.
Warnings
- breaking CVXPY 1.8.0 dropped support for Python 3.10 and NumPy versions older than 2.0.0.
- deprecated CVXPY 1.7 and older major versions are no longer officially supported since the release of CVXPY 1.8.
- gotcha Matrix multiplication behavior changed: `*` is deprecated for matrix-matrix or matrix-vector multiplication. Use `@` for matrix multiplication and dot products. Use `*` for scalar multiplication. For element-wise multiplication, use `cp.multiply`.
- gotcha Problems in CVXPY are immutable. If you need to change an objective or constraints (e.g., for parametric programming), you must construct a new `cp.Problem` instance.
- gotcha For atoms like `cp.sum`, `cp.sum_squares`, `cp.maximum`, `cp.minimum`, always use the CVXPY versions from the `cp` module instead of Python's built-in `sum()`, `max()`, `min()`. The built-in functions do not integrate with CVXPY's modeling language.
- gotcha CVXPY 1.8 changed the default solver for Mixed-Integer Linear Programs (MILPs) from ECOS_BB (or similar) to HiGHS. If you relied on the behavior or performance of a specific default solver, explicitly specify it using `prob.solve(solver='ECOS_BB')`.
Install
-
pip install cvxpy -
pip install cvxpy clarabel osqp scs highspy -
pip install cvxpy[full]
Imports
- cp
import cvxpy as cp
- np
import numpy as np
Quickstart
import cvxpy as cp
import numpy as np
# Problem data.
m = 30
n = 20
np.random.seed(1)
A = np.random.randn(m, n)
b = np.random.randn(m)
# Construct the problem.
x = cp.Variable(n)
objective = cp.Minimize(cp.sum_squares(A @ x - b))
constraints = [0 <= x, x <= 1]
prob = cp.Problem(objective, constraints)
# The optimal objective value is returned by `prob.solve()`.
result = prob.solve()
# The optimal value for x is stored in `x.value`.
print("Optimal x:\n", x.value)
# The optimal Lagrange multiplier for a constraint is stored in
# `constraint.dual_value`.
print("Dual value for 0 <= x constraint:\n", constraints[0].dual_value)