A domain-specific language for modeling convex optimization problems in Python.
—
Exception classes for different types of optimization and solver errors, plus warning control functions for managing CVXPY's diagnostic output.
CVXPY-specific exceptions that indicate problems with problem formulation or solving.
class DCPError(Exception):
"""
Disciplined Convex Programming (DCP) rule violation.
Raised when:
- Non-convex objective in minimization problem
- Non-concave objective in maximization problem
- Non-convex constraint expressions
- Invalid composition of atoms that breaks convexity
"""
pass
class DGPError(Exception):
"""
Disciplined Geometric Programming (DGP) rule violation.
Raised when:
- Invalid geometric programming formulation
- Non-log-convex expressions in geometric programs
- Incorrect monomial/posynomial structure
"""
pass
class DPPError(Exception):
"""
Disciplined Parametrized Programming (DPP) rule violation.
Raised when:
- Parameter appears in invalid position for DPP
- Parameterized expressions violate disciplined rules
- Invalid parameter-dependent problem structure
"""
pass
class SolverError(Exception):
"""
Solver encountered an error during optimization.
Raised when:
- Solver fails to find solution
- Numerical issues prevent convergence
- Solver-specific errors occur
- Invalid solver options provided
"""
passFunctions to control CVXPY's warning system for diagnostic messages.
def disable_warnings():
"""
Disable CVXPY warning messages.
Suppresses warnings about:
- DCP rule violations (when ignore_dcp=True)
- Solver selection and performance
- Parameter value issues
- Numerical precision concerns
"""
...
def enable_warnings():
"""
Enable CVXPY warning messages (default state).
Shows warnings about potential issues that don't
prevent problem solving but may affect results.
"""
...
def warnings_enabled():
"""
Check if CVXPY warnings are currently enabled.
Returns:
- bool: True if warnings are enabled, False otherwise
"""
...import cvxpy as cp
import numpy as np
# Example 1: DCP violation in objective
x = cp.Variable()
y = cp.Variable()
try:
# This violates DCP: minimizing concave function
problem = cp.Problem(cp.Minimize(cp.log(x)), [x >= 1])
problem.solve()
except cp.DCPError as e:
print(f"DCP Error: {e}")
# Solution: use Maximize instead or reformulate
correct_problem = cp.Problem(cp.Maximize(cp.log(x)), [x >= 1])
correct_problem.solve()
print(f"Corrected solution: x = {x.value}")
# Example 2: DCP violation in constraints
try:
# This violates DCP: convex function <= 0 (should be >= 0)
problem = cp.Problem(cp.Minimize(x), [cp.square(x) <= 1])
problem.solve()
except cp.DCPError as e:
print(f"DCP Error in constraint: {e}")
# Solution: flip constraint or use sqrt
correct_problem = cp.Problem(cp.Minimize(x), [cp.abs(x) <= 1])
correct_problem.solve()
print(f"Corrected solution: x = {x.value}")
# Example 3: Ignore DCP rules (use with caution)
x = cp.Variable(pos=True)
try:
# Non-convex problem: minimize x^1.5 (neither convex nor concave)
nonconvex_obj = cp.power(x, 1.5)
problem = cp.Problem(cp.Minimize(nonconvex_obj), [x >= 0.1, x <= 10])
# This will raise DCPError
problem.solve()
except cp.DCPError:
print("Problem is not DCP compliant")
# Try solving anyway (solver may still succeed for some problems)
try:
problem.solve(ignore_dcp=True)
if problem.status == cp.OPTIMAL:
print(f"Non-convex optimization succeeded: x = {x.value}")
else:
print(f"Solver status: {problem.status}")
except cp.SolverError as e:
print(f"Solver failed on non-convex problem: {e}")import cvxpy as cp
# DGP requires positive variables and specific structure
x = cp.Variable(pos=True)
y = cp.Variable(pos=True)
try:
# Invalid DGP: negative coefficient
problem = cp.Problem(cp.Minimize(-x * y), [x + y <= 1])
problem.solve(gp=True)
except cp.DGPError as e:
print(f"DGP Error: {e}")
# Solution: use proper geometric programming form
correct_problem = cp.Problem(cp.Minimize(x * y), [x + y <= 1])
correct_problem.solve(gp=True)
print(f"Corrected GP solution: x={x.value}, y={y.value}")
# Valid geometric program
try:
# Minimize surface area subject to volume constraint
# min 2(xy + xz + yz) s.t. xyz >= V, x,y,z > 0
x, y, z = cp.Variable(pos=True), cp.Variable(pos=True), cp.Variable(pos=True)
V = 1.0 # required volume
surface_area = 2 * (x*y + x*z + y*z)
volume_constraint = x * y * z >= V
gp_problem = cp.Problem(cp.Minimize(surface_area), [volume_constraint])
gp_problem.solve(gp=True)
print(f"Optimal box dimensions: x={x.value:.3f}, y={y.value:.3f}, z={z.value:.3f}")
print(f"Minimum surface area: {surface_area.value:.3f}")
except cp.DGPError as e:
print(f"Geometric programming error: {e}")import cvxpy as cp
import numpy as np
def robust_solve(problem, solvers=None, **kwargs):
"""
Attempt to solve problem with multiple solvers.
"""
if solvers is None:
solvers = [cp.CLARABEL, cp.OSQP, cp.SCS, cp.ECOS]
last_error = None
for solver in solvers:
if solver not in cp.installed_solvers():
continue
try:
result = problem.solve(solver=solver, **kwargs)
if problem.status in [cp.OPTIMAL, cp.OPTIMAL_INACCURATE]:
return result
else:
last_error = f"{solver}: {problem.status}"
except cp.SolverError as e:
last_error = f"{solver}: {e}"
continue
except Exception as e:
last_error = f"{solver}: unexpected error {e}"
continue
raise cp.SolverError(f"All solvers failed. Last error: {last_error}")
# Example: ill-conditioned problem
n = 100
A = np.random.randn(n, n)
A = A @ A.T + 1e-12 * np.eye(n) # Nearly singular
b = np.random.randn(n)
x = cp.Variable(n)
problem = cp.Problem(cp.Minimize(cp.sum_squares(A @ x - b)))
try:
result = robust_solve(problem, verbose=False)
print(f"Problem solved successfully: {result:.6f}")
except cp.SolverError as e:
print(f"All solvers failed: {e}")
# Try with different tolerances
try:
result = robust_solve(problem, eps_abs=1e-12, eps_rel=1e-12)
print(f"Solved with tighter tolerances: {result:.6f}")
except cp.SolverError:
print("Problem is likely ill-conditioned")
# Example: infeasible problem detection
x = cp.Variable()
infeasible_problem = cp.Problem(cp.Minimize(x), [x >= 1, x <= 0])
try:
infeasible_problem.solve()
if infeasible_problem.status == cp.INFEASIBLE:
print("Problem is infeasible (expected)")
else:
print(f"Unexpected status: {infeasible_problem.status}")
except cp.SolverError as e:
print(f"Solver error on infeasible problem: {e}")
# Example: unbounded problem detection
y = cp.Variable()
unbounded_problem = cp.Problem(cp.Minimize(y)) # No constraints
try:
unbounded_problem.solve()
if unbounded_problem.status == cp.UNBOUNDED:
print("Problem is unbounded (expected)")
else:
print(f"Status: {unbounded_problem.status}")
except cp.SolverError as e:
print(f"Solver error on unbounded problem: {e}")import cvxpy as cp
import numpy as np
# Check initial warning state
print(f"Warnings enabled: {cp.warnings_enabled()}")
# Example with warnings
x = cp.Variable()
problem = cp.Problem(cp.Minimize(x**2), [x >= 1])
# Solve with warnings (may show solver selection info)
problem.solve()
print(f"Solution with warnings: {x.value}")
# Disable warnings for cleaner output
cp.disable_warnings()
print(f"Warnings enabled: {cp.warnings_enabled()}")
# Solve without warnings
problem.solve()
print(f"Solution without warnings: {x.value}")
# Re-enable warnings
cp.enable_warnings()
print(f"Warnings enabled: {cp.warnings_enabled()}")
# Example: Parameter without value warning
p = cp.Parameter() # No initial value
x = cp.Variable()
try:
# This might generate warnings about unset parameter
problem = cp.Problem(cp.Minimize(x + p), [x >= 0])
problem.solve() # Will fail because p has no value
except Exception as e:
print(f"Expected error with unset parameter: {e}")
# Set parameter value and retry
p.value = 1.0
problem.solve()
print(f"Solution with parameter set: {x.value}")
# Example: Numerical precision warnings
# Create nearly infeasible problem
epsilon = 1e-15
x = cp.Variable()
nearly_infeasible = cp.Problem(
cp.Minimize(x),
[x >= 1, x <= 1 + epsilon]
)
try:
nearly_infeasible.solve()
if nearly_infeasible.status == cp.OPTIMAL_INACCURATE:
print("Solution found but may be inaccurate due to numerical precision")
print(f"Solution: {x.value}")
except cp.SolverError as e:
print(f"Numerical precision caused solver error: {e}")import cvxpy as cp
import numpy as np
def safe_optimization(objective, constraints, **solve_kwargs):
"""
Safely solve optimization problem with comprehensive error handling.
"""
try:
# Create problem
problem = cp.Problem(objective, constraints)
# Check DCP compliance
if not problem.is_dcp():
print("Warning: Problem is not DCP compliant")
solve_kwargs['ignore_dcp'] = True
# Attempt to solve
result = problem.solve(**solve_kwargs)
# Check solution status
if problem.status == cp.OPTIMAL:
return result, "optimal"
elif problem.status == cp.OPTIMAL_INACCURATE:
return result, "optimal_inaccurate"
elif problem.status == cp.INFEASIBLE:
return None, "infeasible"
elif problem.status == cp.UNBOUNDED:
return None, "unbounded"
else:
return None, f"solver_issue_{problem.status}"
except cp.DCPError as e:
return None, f"dcp_error: {e}"
except cp.DGPError as e:
return None, f"dgp_error: {e}"
except cp.SolverError as e:
return None, f"solver_error: {e}"
except Exception as e:
return None, f"unexpected_error: {e}"
# Example usage
x = cp.Variable(2)
A = np.random.randn(3, 2)
b = np.random.randn(3)
result, status = safe_optimization(
cp.Minimize(cp.sum_squares(x)),
[A @ x == b, x >= 0],
solver=cp.OSQP
)
print(f"Optimization result: {result}")
print(f"Status: {status}")
if result is not None:
print(f"Optimal x: {x.value}")
else:
print("Optimization failed")Install with Tessl CLI
npx tessl i tessl/pypi-cvxpy