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.
pip install cvxpyVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to solve a least-squares problem with box constraints using CVXPY. It defines variables, an objective function, and constraints, then solves the problem and prints the optimal variable values and duals.
Ensure your Python environment is 3.11 or newer and NumPy is >= 2.0.0. Upgrade with `pip install --upgrade python numpy` if necessary (after updating Python itself).
Upgrade to CVXPY 1.8.x or newer for continued support and bug fixes: `pip install --upgrade cvxpy`.
Update your code to use the `@` operator for matrix multiplication and `cp.multiply` for element-wise multiplication. Example: `A @ x` instead of `A * x` for matrix-vector product.
Instead of modifying `prob.objective` or `prob.constraints` directly, create a new `cp.Problem(new_objective, new_constraints)`.
Replace Python built-ins with their CVXPY equivalents, e.g., `cp.sum(expr)` instead of `sum(expr)`.
If specific solver behavior is critical, explicitly set the solver parameter: `prob.solve(solver='ECOS_BB')` or `prob.solve(solver='GLPK_MI')`, etc.
Ensure cvxpy is installed using `pip install cvxpy` and its recommended solvers like `pip install ecos osqp scs`. Verify that your development environment is using the correct Python interpreter.
Reformulate the objective function or constraints to comply with DCP rules. For example, bilinear terms (product of two variables) are generally not allowed and may require linearization or reformulation if the problem is a Quadratic Program (QP) using specific atoms like `cp.quad_form`.
Try using a different solver (e.g., `prob.solve(solver='ECOS')`, `prob.solve(solver='SCS')`, `prob.solve(solver='CLARABEL')`). Additionally, inspect the problem data for `NaN` values or poor scaling, and use `prob.solve(verbose=True)` to get more detailed output from the solver to diagnose the issue.
Ensure that the problem is not only DCP-compliant but also adheres to DPP rules. This often means parameters must enter expressions in affine ways or adhere to specific positivity/sign constraints in DGP. If DPP is not strictly needed for performance, you might use `cp.Constant` instead of `cp.Parameter` or manually re-construct the problem.
Replace `cvxpy.Bool(shape)` with `cvxpy.Variable(shape, boolean=True)` to declare boolean optimization variables.