CVXPY Python
Translate an optimization problem into CVXPY without changing its mathematics.
Make dimensions, domains, curvature, solver capability, status handling, and
numerical validation explicit.
Core objects
| Object |
Meaning |
Rule |
Variable |
Unknown decision value, optionally with structural attributes. |
Domain and shape belong here or in explicit constraints. |
Parameter |
Symbolic constant whose .value changes between solves. |
Use for repeated instances; it is never optimized. |
Expression |
Symbolic computation with shape, sign, and curvature. |
Use CVXPY atoms/operators, not NumPy evaluation on variables. |
Constraint |
Symbolic equality, inequality, or cone relation. |
Store explicit constraints when dual values matter. |
Objective |
Minimize(convex) or Maximize(concave) under DCP. |
Direction is part of the model. |
Problem |
Immutable objective plus constraint list. |
solve() canonicalizes, invokes a solver, and populates status/values. |
Model construction does not solve. solve() returns an objective value and
updates problem.status, problem.value, variable values, constraint duals,
and solver statistics when available. Problems are immutable; use Parameters
for data changes or construct a new Problem for mathematical changes. Read
the symbolic and curvature model.
Ordered workflow
- Write the mathematical sets, indices, units, decision variables, objective,
constraints, and allowed approximation before code.
- Determine shapes and domains; distinguish scalar
(), vector (n,), and
column (n, 1) deliberately.
- Build symbolic expressions using CVXPY atoms and
@ for matrix products.
- Check
problem.is_dcp() or the intended ruleset before solver selection. Use
is_dcp(dpp=True) for a repeated DCP parameterization.
- Select a solver from the problem class and locally installed capabilities;
pass only supported options.
- Solve, branch on status, and reject missing/nonfinite values before use.
- Independently validate primal feasibility, integrality, objective, and—when
needed—duality/KKT residuals at tolerances justified by scale.
Decision rules
- Use a
Parameter when coefficients or bounds change but the optimization
structure remains. Require DPP for claimed recompilation speedups.
- Use variable attributes (
nonneg, boolean, integer, PSD, sparsity) when
analyzer information or reduced representation matters. Use explicit
constraints when dual variables are required; attributes do not record their
own duals.
- Use
cp.sum, cp.sum_squares, cp.norm, cp.maximum, and other atoms on
expressions. Python sum or NumPy functions can be slow, object-typed, or
semantically wrong.
- Use separate constraints
x >= 0 and x <= 1; chained comparisons and strict
inequalities do not define valid CVXPY constraints.
- If a convex expression is marked unknown, rewrite it using a recognized atom
or equivalent formulation; never suppress DCP errors without proving a
different ruleset applies.
- Choose mixed-integer, conic, quadratic, or nonlinear solvers from installed
solver support and licensing. Solver name is deployment configuration, not a
universally portable constant.
Read modeling, solving, and validation for DCP/DPP,
status gates, tolerances, solver choice, and repeated solves.
Canonical anchor
import cvxpy as cp
import numpy as np
def bounded_least_squares(design: np.ndarray, target: np.ndarray) -> tuple[np.ndarray, float]:
coefficients = cp.Variable(design.shape[1])
problem = cp.Problem(
cp.Minimize(cp.sum_squares(design @ coefficients - target)),
[coefficients >= 0, coefficients <= 1],
)
if not problem.is_dcp():
raise ValueError("model must satisfy DCP")
value = problem.solve()
if problem.status not in {cp.OPTIMAL, cp.OPTIMAL_INACCURATE}:
raise RuntimeError(f"solve failed: {problem.status}")
if value is None or not np.isfinite(value):
raise RuntimeError("solver returned no finite objective")
if coefficients.value is None or not np.isfinite(coefficients.value).all():
raise RuntimeError("solver returned no finite primal solution")
return coefficients.value.copy(), float(value)
Production code must decide whether OPTIMAL_INACCURATE is acceptable and
validate residuals accordingly. Do not return .value before the status gate.
High-risk rules
- Do not multiply decision variables together in a DCP model. Inspect curvature
and use a recognized atom/formulation if the mathematics is convex.
/, *, and @ have different scalar/elementwise/matrix meanings. Assert
every expression shape; do not rely on accidental broadcasting.
- Do not read
variable.value or constraint.dual_value until a successful
solve and appropriate status check.
- Infeasible, unbounded, and
infeasible_or_unbounded are distinct outcomes.
Handle them separately; an infinite objective is not a usable solution.
OPTIMAL_INACCURATE is evidence of a solver tolerance/status, not equivalent
to exact optimality. Validate domain residuals.
- Warm start and Parameters do not guarantee DPP or speed. Check the compiled
model and measure repeated solves.
- Scaling affects numerical reliability. Normalize units or use solver options
based on diagnostics, not by accepting a loose tolerance until tests pass.
- Solver-specific options and availability drift. Query
cp.installed_solvers()
and inspect the environment.
Version grounding and completion
The official current tutorial documents DCP, DPP, solver status, variable
attributes, and performance guidance; CVXPY is not installed locally at this
authoring stage. Inspect version, installed solvers, atom/signature, and solver
options before execution. Read verification.
Completion requires the code to match the written mathematics; ruleset checks
to pass; solver capability to be explicit; all statuses to be handled; primal
values and residuals to be validated; repeated solve behavior to be tested when
claimed; and deterministic fixtures for feasible, infeasible, and boundary
instances.
References
- Symbolic and curvature model
- Modeling, solving, and validation
- Verification and grounding
1---2name: cvxpy-python3description: Use for writing, reviewing, debugging, testing, or optimizing Python CVXPY optimization models. Trigger on Variable, Parameter, Expression, Constraint, Objective, Problem, DCP, DPP, DGP, DQCP, solver selection/status, dual values, mixed-integer, cone, or repeated parametric solves. Do not use for scipy.optimize-only, PyMC inference, symbolic algebra without optimization, or hand-written solver implementations.4argument-hint: "[CVXPY model, mathematics, solver status, or error]"5metadata:6 source: https://skillmd.com/skills/schattenspiegel/cvxpy-python7---89# CVXPY Python1011Translate an optimization problem into CVXPY without changing its mathematics.12Make dimensions, domains, curvature, solver capability, status handling, and13numerical validation explicit.1415## Core objects1617| Object | Meaning | Rule |18|---|---|---|19| `Variable` | Unknown decision value, optionally with structural attributes. | Domain and shape belong here or in explicit constraints. |20| `Parameter` | Symbolic constant whose `.value` changes between solves. | Use for repeated instances; it is never optimized. |21| `Expression` | Symbolic computation with shape, sign, and curvature. | Use CVXPY atoms/operators, not NumPy evaluation on variables. |22| `Constraint` | Symbolic equality, inequality, or cone relation. | Store explicit constraints when dual values matter. |23| `Objective` | `Minimize(convex)` or `Maximize(concave)` under DCP. | Direction is part of the model. |24| `Problem` | Immutable objective plus constraint list. | `solve()` canonicalizes, invokes a solver, and populates status/values. |2526Model construction does not solve. `solve()` returns an objective value and27updates `problem.status`, `problem.value`, variable values, constraint duals,28and solver statistics when available. Problems are immutable; use Parameters29for data changes or construct a new Problem for mathematical changes. Read30[the symbolic and curvature model](references/object-model.md).3132## Ordered workflow33341. Write the mathematical sets, indices, units, decision variables, objective,35 constraints, and allowed approximation before code.362. Determine shapes and domains; distinguish scalar `()`, vector `(n,)`, and37 column `(n, 1)` deliberately.383. Build symbolic expressions using CVXPY atoms and `@` for matrix products.394. Check `problem.is_dcp()` or the intended ruleset before solver selection. Use40 `is_dcp(dpp=True)` for a repeated DCP parameterization.415. Select a solver from the problem class and locally installed capabilities;42 pass only supported options.436. Solve, branch on status, and reject missing/nonfinite values before use.447. Independently validate primal feasibility, integrality, objective, and—when45 needed—duality/KKT residuals at tolerances justified by scale.4647## Decision rules4849- Use a `Parameter` when coefficients or bounds change but the optimization50 structure remains. Require DPP for claimed recompilation speedups.51- Use variable attributes (`nonneg`, `boolean`, `integer`, `PSD`, sparsity) when52 analyzer information or reduced representation matters. Use explicit53 constraints when dual variables are required; attributes do not record their54 own duals.55- Use `cp.sum`, `cp.sum_squares`, `cp.norm`, `cp.maximum`, and other atoms on56 expressions. Python `sum` or NumPy functions can be slow, object-typed, or57 semantically wrong.58- Use separate constraints `x >= 0` and `x <= 1`; chained comparisons and strict59 inequalities do not define valid CVXPY constraints.60- If a convex expression is marked unknown, rewrite it using a recognized atom61 or equivalent formulation; never suppress DCP errors without proving a62 different ruleset applies.63- Choose mixed-integer, conic, quadratic, or nonlinear solvers from installed64 solver support and licensing. Solver name is deployment configuration, not a65 universally portable constant.6667Read [modeling, solving, and validation](references/operations.md) for DCP/DPP,68status gates, tolerances, solver choice, and repeated solves.6970## Canonical anchor7172```python73import cvxpy as cp74import numpy as np757677def bounded_least_squares(design: np.ndarray, target: np.ndarray) -> tuple[np.ndarray, float]:78 coefficients = cp.Variable(design.shape[1])79 problem = cp.Problem(80 cp.Minimize(cp.sum_squares(design @ coefficients - target)),81 [coefficients >= 0, coefficients <= 1],82 )83 if not problem.is_dcp():84 raise ValueError("model must satisfy DCP")85 value = problem.solve()86 if problem.status not in {cp.OPTIMAL, cp.OPTIMAL_INACCURATE}:87 raise RuntimeError(f"solve failed: {problem.status}")88 if value is None or not np.isfinite(value):89 raise RuntimeError("solver returned no finite objective")90 if coefficients.value is None or not np.isfinite(coefficients.value).all():91 raise RuntimeError("solver returned no finite primal solution")92 return coefficients.value.copy(), float(value)93```9495Production code must decide whether `OPTIMAL_INACCURATE` is acceptable and96validate residuals accordingly. Do not return `.value` before the status gate.9798## High-risk rules99100- Do not multiply decision variables together in a DCP model. Inspect curvature101 and use a recognized atom/formulation if the mathematics is convex.102- `/`, `*`, and `@` have different scalar/elementwise/matrix meanings. Assert103 every expression shape; do not rely on accidental broadcasting.104- Do not read `variable.value` or `constraint.dual_value` until a successful105 solve and appropriate status check.106- Infeasible, unbounded, and `infeasible_or_unbounded` are distinct outcomes.107 Handle them separately; an infinite objective is not a usable solution.108- `OPTIMAL_INACCURATE` is evidence of a solver tolerance/status, not equivalent109 to exact optimality. Validate domain residuals.110- Warm start and Parameters do not guarantee DPP or speed. Check the compiled111 model and measure repeated solves.112- Scaling affects numerical reliability. Normalize units or use solver options113 based on diagnostics, not by accepting a loose tolerance until tests pass.114- Solver-specific options and availability drift. Query `cp.installed_solvers()`115 and inspect the environment.116117## Version grounding and completion118119The official current tutorial documents DCP, DPP, solver status, variable120attributes, and performance guidance; CVXPY is not installed locally at this121authoring stage. Inspect version, installed solvers, atom/signature, and solver122options before execution. Read [verification](references/verification.md).123124Completion requires the code to match the written mathematics; ruleset checks125to pass; solver capability to be explicit; all statuses to be handled; primal126values and residuals to be validated; repeated solve behavior to be tested when127claimed; and deterministic fixtures for feasible, infeasible, and boundary128instances.129130## References131132- [Symbolic and curvature model](references/object-model.md)133- [Modeling, solving, and validation](references/operations.md)134- [Verification and grounding](references/verification.md)