A domain-specific language for modeling convex optimization problems in Python.
—
Classes for defining and solving optimization problems in CVXPY. These classes coordinate the objective function, constraints, and solver interface to enable problem solving.
The main class that represents an optimization problem, combining an objective with constraints and providing the interface for solving.
class Problem:
"""
An optimization problem.
Parameters:
- objective: Minimize or Maximize object representing the objective function
- constraints: list of Constraint objects (optional)
"""
def __init__(self, objective, constraints=None): ...
def solve(self, solver=None, verbose=False, gp=False, qcp=False,
requires_grad=False, enforce_dpp=False, ignore_dcp=False,
canon_backend=None, **kwargs):
"""
Solve the optimization problem.
Parameters:
- solver: str, name of solver to use (auto-selected if None)
- verbose: bool, whether to print solver output
- gp: bool, whether to parse as geometric program
- qcp: bool, whether to parse as quadratically constrained program
- requires_grad: bool, whether to compute gradients
- enforce_dpp: bool, whether to enforce disciplined parametrized programming
- ignore_dcp: bool, whether to ignore disciplined convex programming rules
- canon_backend: str, canonicalization backend to use
- **kwargs: additional solver-specific options
Returns:
- float: optimal objective value
"""
...
def is_dcp(self, dpp=False):
"""Check if problem follows disciplined convex programming rules."""
...
def is_dgp(self, dpp=False):
"""Check if problem follows disciplined geometric programming rules."""
...
def is_dqcp(self):
"""Check if problem is disciplined quasiconvex."""
...
@property
def objective(self):
"""The problem's objective."""
...
@property
def constraints(self):
"""List of the problem's constraints."""
...
@property
def status(self):
"""Status of the problem after solving."""
...
@property
def value(self):
"""Optimal objective value (None if not solved)."""
...
@property
def variables(self):
"""Variables in the problem."""
...
@property
def parameters(self):
"""Parameters in the problem."""
...
@property
def constants(self):
"""Constants in the problem."""
...
def get_problem_data(self, solver):
"""Get problem data in solver's format."""
...Usage examples:
import cvxpy as cp
import numpy as np
# Simple quadratic program
x = cp.Variable(2)
objective = cp.Minimize(cp.sum_squares(x))
constraints = [x >= 0, cp.sum(x) == 1]
problem = cp.Problem(objective, constraints)
# Solve the problem
problem.solve()
print(f"Status: {problem.status}")
print(f"Optimal value: {problem.value}")
print(f"Optimal x: {x.value}")
# Portfolio optimization example
n = 5
mu = np.random.randn(n) # expected returns
Sigma = np.random.randn(n, n)
Sigma = Sigma.T @ Sigma # covariance matrix
w = cp.Variable(n) # portfolio weights
risk = cp.quad_form(w, Sigma)
ret = mu.T @ w
# Minimize risk for target return
target_return = 0.1
objective = cp.Minimize(risk)
constraints = [cp.sum(w) == 1, w >= 0, ret >= target_return]
portfolio_problem = cp.Problem(objective, constraints)
portfolio_problem.solve()
print(f"Optimal portfolio: {w.value}")
print(f"Portfolio risk: {risk.value}")
print(f"Portfolio return: {ret.value}")
# Check problem properties
print(f"Is DCP: {portfolio_problem.is_dcp()}")
print(f"Variables: {[var.name() for var in portfolio_problem.variables()]}")Base class and specific implementations for optimization objectives.
class Objective:
"""
Base class for optimization objectives.
Parameters:
- expr: Expression to optimize
"""
def __init__(self, expr): ...
@property
def value(self):
"""Value of the objective expression."""
...
@property
def expr(self):
"""The objective expression."""
...
def is_dcp(self, dpp=False):
"""Check if objective follows DCP rules."""
...Creates a minimization objective for optimization problems.
class Minimize(Objective):
"""
Minimization objective.
Parameters:
- expr: Expression to minimize
"""
def __init__(self, expr): ...Usage examples:
import cvxpy as cp
x = cp.Variable()
# Minimize a quadratic function
obj1 = cp.Minimize(x**2 + 2*x + 1)
# Minimize L1 norm (for sparse solutions)
x_vec = cp.Variable(10)
obj2 = cp.Minimize(cp.norm(x_vec, 1))
# Minimize sum of squares (least squares)
A = cp.Parameter((5, 10))
b = cp.Parameter(5)
obj3 = cp.Minimize(cp.sum_squares(A @ x_vec - b))
# Minimize maximum element (infinity norm)
obj4 = cp.Minimize(cp.norm(x_vec, "inf"))Creates a maximization objective for optimization problems.
class Maximize(Objective):
"""
Maximization objective.
Parameters:
- expr: Expression to maximize
"""
def __init__(self, expr): ...Usage examples:
import cvxpy as cp
import numpy as np
# Maximize utility function
x = cp.Variable(3, nonneg=True)
utility = cp.log(x[0]) + cp.log(x[1]) + cp.log(x[2])
obj1 = cp.Maximize(utility)
# Maximize minimum element (max-min fairness)
obj2 = cp.Maximize(cp.minimum(x[0], cp.minimum(x[1], x[2])))
# Maximize expected return (portfolio optimization)
mu = np.array([0.1, 0.2, 0.15])
w = cp.Variable(3, nonneg=True)
expected_return = mu.T @ w
obj3 = cp.Maximize(expected_return)
# Create and solve maximization problem
constraints = [cp.sum(w) == 1] # weights sum to 1
problem = cp.Problem(obj3, constraints)
problem.solve()
print(f"Optimal weights: {w.value}")
print(f"Maximum return: {expected_return.value}")import cvxpy as cp
# Solve with specific solver
x = cp.Variable()
problem = cp.Problem(cp.Minimize(x**2), [x >= 1])
# Try different solvers
problem.solve(solver=cp.OSQP)
print(f"OSQP solution: {x.value}")
problem.solve(solver=cp.SCS)
print(f"SCS solution: {x.value}")
# Solver-specific options
problem.solve(solver=cp.OSQP, eps_abs=1e-8, eps_rel=1e-8, max_iter=10000)
# Get problem statistics
print(f"Solve time: {problem.solver_stats.solve_time}")
print(f"Setup time: {problem.solver_stats.setup_time}")
print(f"Iterations: {problem.solver_stats.num_iters}")
# Warm start (reuse previous solution)
problem.solve(warm_start=True)
# Check if problem is DCP compliant
if not problem.is_dcp():
print("Problem is not DCP compliant")
# Can try to solve anyway
problem.solve(ignore_dcp=True)Install with Tessl CLI
npx tessl i tessl/pypi-cvxpy