A domain-specific language for modeling convex optimization problems in Python.
—
Constraint types that define the feasible region of optimization problems in CVXPY. These constraints ensure that solutions satisfy specified mathematical relationships and belong to appropriate geometric sets.
class Constraint:
"""
Base class for all constraints.
"""
@property
def value(self):
"""Value of the constraint expression (for checking feasibility)."""
...
@property
def violation(self):
"""Amount by which the constraint is violated."""
...
@property
def dual_value(self):
"""Dual variable value associated with this constraint."""
...
def is_dcp(self, dpp=False):
"""Check if constraint follows disciplined convex programming rules."""
...
def is_dgp(self, dpp=False):
"""Check if constraint follows disciplined geometric programming rules."""
...Equality constraints of the form expr == 0.
class Zero(Constraint):
"""
Equality constraint: expr == 0
Parameters:
- expr: Expression that should equal zero
"""
def __init__(self, expr): ...Usage examples:
import cvxpy as cp
x = cp.Variable(3)
A = cp.Parameter((2, 3))
b = cp.Parameter(2)
# Linear equality constraints: Ax = b
equality_constraint = (A @ x == b)
# Sum constraint: sum of x equals 1
sum_constraint = (cp.sum(x) == 1)
# Individual element constraints
element_constraint = (x[0] == 2 * x[1])
# Multiple equality constraints
constraints = [A @ x == b, cp.sum(x) == 1, x[0] + x[1] == x[2]]Non-negativity constraints of the form expr >= 0.
class NonNeg(Constraint):
"""
Non-negativity constraint: expr >= 0
Parameters:
- expr: Expression that should be non-negative
"""
def __init__(self, expr): ...Usage examples:
import cvxpy as cp
x = cp.Variable(5)
# Simple non-negativity
nonneg_constraint = (x >= 0)
# Element-wise non-negativity
A = cp.Variable((3, 4))
matrix_nonneg = (A >= 0)
# Expression non-negativity
expr = 2*x[0] - x[1] + 3
expr_nonneg = (expr >= 0)Non-positivity constraints of the form expr <= 0.
class NonPos(Constraint):
"""
Non-positivity constraint: expr <= 0
Parameters:
- expr: Expression that should be non-positive
"""
def __init__(self, expr): ...Usage examples:
import cvxpy as cp
x = cp.Variable(3)
# Upper bound constraints
upper_bound = (x <= 1)
# Resource constraints (consumption <= capacity)
consumption = cp.sum(x)
capacity = 10
resource_constraint = (consumption <= capacity)Positive semidefinite constraints for symmetric matrices.
class PSD(Constraint):
"""
Positive semidefinite constraint: expr >= 0 (matrix sense)
Parameters:
- expr: Symmetric matrix expression that should be PSD
"""
def __init__(self, expr): ...Usage examples:
import cvxpy as cp
import numpy as np
# PSD matrix variable
n = 4
X = cp.Variable((n, n), symmetric=True)
psd_constraint = (X >> 0) # X is PSD
# Linear matrix inequality (LMI)
A = [np.random.randn(n, n) for _ in range(3)]
x = cp.Variable(3)
lmi = (sum(x[i] * A[i] for i in range(3)) >> 0)
# Covariance matrix constraint
Sigma = cp.Variable((n, n), symmetric=True)
mu = cp.Variable(n)
# Ensure covariance matrix is PSD
constraints = [Sigma >> 0, cp.trace(Sigma) <= 1]
# Semidefinite program example
C = np.random.randn(n, n)
objective = cp.Minimize(cp.trace(C @ X))
problem = cp.Problem(objective, [X >> 0, cp.trace(X) == 1])Second-order cone (Lorentz cone) constraints of the form ||x||_2 <= t.
class SOC(Constraint):
"""
Second-order cone constraint: ||X||_2 <= t
Parameters:
- t: scalar expression (upper bound)
- X: vector expression (should be in the cone)
"""
def __init__(self, t, X): ...Usage examples:
import cvxpy as cp
# Basic SOC constraint: ||x||_2 <= t
x = cp.Variable(3)
t = cp.Variable()
soc_constraint = cp.SOC(t, x)
# Equivalent using norm
norm_constraint = (cp.norm(x, 2) <= t)
# Quadratic constraint: x^T P x <= t^2 (if P is PSD)
P = cp.Parameter((3, 3), PSD=True)
quadratic_soc = cp.SOC(t, cp.psd_wrap(P.value) @ x)
# Portfolio risk constraint
n = 5
w = cp.Variable(n) # portfolio weights
Sigma = cp.Parameter((n, n), PSD=True) # covariance matrix
risk_limit = 0.1
# ||Sigma^{1/2} w||_2 <= risk_limit
L = cp.Parameter((n, n)) # Cholesky factor of Sigma
risk_constraint = cp.SOC(risk_limit, L.T @ w)Exponential cone constraints for problems involving exponential and logarithmic functions.
class ExpCone(Constraint):
"""
Exponential cone constraint: (x, y, z) in exp cone
Equivalently: y * exp(x/y) <= z, y > 0
Parameters:
- x, y, z: scalar expressions
"""
def __init__(self, x, y, z): ...
class OpRelEntrConeQuad(Constraint):
"""
Operator relative entropy cone constraint.
"""
def __init__(self, X, Y, Z): ...
class RelEntrConeQuad(Constraint):
"""
Relative entropy cone constraint.
"""
def __init__(self, x, y, z): ...Usage examples:
import cvxpy as cp
# Exponential cone constraint
x = cp.Variable()
y = cp.Variable()
z = cp.Variable()
exp_constraint = cp.ExpCone(x, y, z)
# Logarithmic constraint using exponential cone
# log(x) >= y is equivalent to exp(y) <= x
log_constraint = cp.ExpCone(y, 1, x)
# Entropy maximization
n = 5
p = cp.Variable(n) # probability distribution
entropy_constraint = [cp.ExpCone(-cp.entr(p[i]), 1, 1) for i in range(n)]
constraints = [p >= 0, cp.sum(p) == 1] + entropy_constraintPower cone constraints for problems involving power functions.
class PowCone3D(Constraint):
"""
3D power cone constraint: (x, y, z) in pow cone
Equivalently: |x|^alpha * |y|^(1-alpha) >= |z|, x >= 0, y >= 0
Parameters:
- x, y, z: scalar expressions
- alpha: power parameter in (0, 1)
"""
def __init__(self, x, y, z, alpha): ...
class PowConeND(Constraint):
"""
N-dimensional power cone constraint.
Parameters:
- x: vector expression
- y: scalar expression
- alpha: vector of power parameters
"""
def __init__(self, x, y, alpha): ...Usage examples:
import cvxpy as cp
# 3D power cone
x = cp.Variable()
y = cp.Variable()
z = cp.Variable()
alpha = 0.3
pow_constraint = cp.PowCone3D(x, y, z, alpha)
# Geometric mean constraint using power cone
# (x * y)^(1/2) >= z is equivalent to power cone constraint
geo_mean_constraint = cp.PowCone3D(x, y, z, 0.5)
# P-norm minimization using power cones
n = 10
x = cp.Variable(n)
p = 1.5 # between 1 and 2
# Minimize ||x||_p using power cone formulationConstraints that restrict variables to finite discrete sets.
class FiniteSet(Constraint):
"""
Finite set membership constraint.
Parameters:
- expr: expression that should be in the set
- values: list or array of allowed values
"""
def __init__(self, expr, values): ...Usage examples:
import cvxpy as cp
# Binary variable constraint
x = cp.Variable()
binary_constraint = cp.FiniteSet(x, [0, 1])
# Multi-valued discrete constraint
y = cp.Variable()
discrete_constraint = cp.FiniteSet(y, [-1, 0, 1, 2])
# Vector finite set constraint
z = cp.Variable(2)
vector_set_constraint = cp.FiniteSet(z, [[0, 0], [1, 0], [0, 1], [1, 1]])import cvxpy as cp
import numpy as np
# Complex optimization problem with multiple constraint types
n = 4
x = cp.Variable(n)
X = cp.Variable((n, n), symmetric=True)
t = cp.Variable()
constraints = [
# Equality constraints
cp.sum(x) == 1,
X[0, 0] == 1,
# Inequality constraints
x >= 0,
t >= 0,
# Second-order cone
cp.norm(x, 2) <= t,
# PSD constraint
X >> 0,
# Linear matrix inequality
cp.bmat([[X, x.reshape((-1, 1))],
[x.reshape((1, -1)), t]]) >> 0
]
# Portfolio optimization with multiple constraint types
w = cp.Variable(n) # weights
mu = cp.Parameter(n) # expected returns
Sigma = cp.Parameter((n, n), PSD=True) # covariance
portfolio_constraints = [
w >= 0, # long-only
cp.sum(w) == 1, # fully invested
cp.quad_form(w, Sigma) <= 0.01, # risk constraint
mu.T @ w >= 0.05 # return constraint
]
objective = cp.Maximize(mu.T @ w - 0.5 * cp.quad_form(w, Sigma))
portfolio_problem = cp.Problem(objective, portfolio_constraints)Install with Tessl CLI
npx tessl i tessl/pypi-cvxpy