CVXPY Base

1.8.2 · active · verified Fri Apr 17

CVXPY is a domain-specific language (DSL) for modeling convex optimization problems in Python. The `cvxpy-base` package provides the core functionality without bundling default solvers. It is currently at version 1.8.2 and follows a regular release cadence with major versions released periodically and patch releases for bug fixes and solver updates.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to define variables, an objective function, and constraints to form a convex optimization problem using CVXPY. It then attempts to solve it, highlighting the necessity of having a solver installed, especially when using `cvxpy-base`.

import cvxpy as cp
import numpy as np

# Define variables
x = cp.Variable()
y = cp.Variable()

# Define objective function
objective = cp.Minimize((x - y)**2 + 1)

# Define constraints
constraints = [x + y >= 0, x - y >= 0, x <= 3]

# Formulate the problem
problem = cp.Problem(objective, constraints)

# Solve the problem (requires a solver to be installed)
try:
    problem.solve()
    if problem.status == cp.OPTIMAL or problem.status == cp.OPTIMAL_INACCURATE:
        print(f"Problem status: {problem.status}")
        print(f"Optimal value: {problem.value:.4f}")
        print(f"Optimal x: {x.value:.4f}")
        print(f"Optimal y: {y.value:.4f}")
    else:
        print(f"Problem did not solve to optimality. Status: {problem.status}")
except cp.error.SolverError as e:
    print(f"Solver Error: {e}")
    print("\nHint: To solve problems with `cvxpy-base`, you must install a compatible solver separately. ")
    print("For example: `pip install ecos` or `pip install osqp`. ")
    print("Alternatively, install the full `cvxpy` package: `pip install cvxpy`.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →