CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-cvxpy

A domain-specific language for modeling convex optimization problems in Python.

Pending
Overview
Eval results
Files

expressions.mddocs/

Core Expressions

Fundamental building blocks for optimization problems in CVXPY. These classes represent mathematical expressions that can be combined using standard arithmetic operations to build optimization objectives and constraints.

Capabilities

Variables

Optimization variables represent the unknowns in an optimization problem. Variables can be scalars, vectors, or matrices with various properties like non-negativity, symmetry, or being integer-valued.

class Variable:
    """
    Optimization variable.
    
    Parameters:
    - shape: int or tuple, shape of the variable (default: scalar)
    - name: str, optional name for the variable  
    - nonneg: bool, whether variable is constrained to be non-negative
    - nonpos: bool, whether variable is constrained to be non-positive
    - symmetric: bool, whether variable is constrained to be symmetric
    - diag: bool, whether variable is constrained to be diagonal
    - PSD: bool, whether variable is constrained to be positive semidefinite
    - NSD: bool, whether variable is constrained to be negative semidefinite
    - hermitian: bool, whether variable is constrained to be Hermitian
    - boolean: bool, whether variable is constrained to be boolean
    - integer: bool, whether variable is constrained to be integer
    - pos: bool, whether variable is constrained to be positive
    - neg: bool, whether variable is constrained to be negative
    """
    def __init__(self, shape=(), name=None, **kwargs): ...
    
    @property
    def value(self):
        """Get the optimal value of the variable after solving."""
        ...
    
    @property 
    def grad(self):
        """Get gradient with respect to this variable."""
        ...

Usage examples:

import cvxpy as cp

# Scalar variable
x = cp.Variable()

# Vector variable
y = cp.Variable(5)  # 5-element vector

# Matrix variable  
Z = cp.Variable((4, 4))  # 4x4 matrix

# Non-negative vector
w = cp.Variable(3, nonneg=True)

# Positive semidefinite matrix
P = cp.Variable((3, 3), PSD=True)

# Integer variable
n = cp.Variable(integer=True)

# Named variable for debugging
alpha = cp.Variable(name="alpha")

Parameters

Parameters represent known data in optimization problems that can be updated without rebuilding the problem structure. This enables efficient resolving with different parameter values.

class Parameter:
    """
    Problem parameter that can be updated without rebuilding.
    
    Parameters:
    - shape: int or tuple, shape of the parameter (default: scalar)
    - name: str, optional name for the parameter
    - value: array-like, initial value for the parameter
    - nonneg: bool, whether parameter values must be non-negative
    - nonpos: bool, whether parameter values must be non-positive  
    - symmetric: bool, whether parameter must be symmetric
    - diag: bool, whether parameter must be diagonal
    - PSD: bool, whether parameter must be positive semidefinite
    - NSD: bool, whether parameter must be negative semidefinite
    - hermitian: bool, whether parameter must be Hermitian
    - boolean: bool, whether parameter must be boolean
    - integer: bool, whether parameter must be integer
    - pos: bool, whether parameter must be positive
    - neg: bool, whether parameter must be negative
    - imag: bool, whether parameter can have imaginary values
    - complex: bool, whether parameter can be complex-valued
    """
    def __init__(self, shape=(), name=None, value=None, **kwargs): ...
    
    @property
    def value(self):
        """Get the current value of the parameter."""
        ...
        
    @value.setter  
    def value(self, val):
        """Set the value of the parameter."""
        ...
        
    @property
    def grad(self):
        """Get gradient with respect to this parameter."""
        ...

Usage examples:

import cvxpy as cp
import numpy as np

# Scalar parameter with initial value
lam = cp.Parameter(value=1.0, nonneg=True)

# Vector parameter  
c = cp.Parameter(5, value=np.random.randn(5))

# Matrix parameter
A = cp.Parameter((4, 5), value=np.random.randn(4, 5))

# Update parameter values
lam.value = 2.0
c.value = np.ones(5)
A.value = np.eye(4, 5)

# Parameters in optimization problems
x = cp.Variable(5)
objective = cp.Minimize(cp.quad_form(x, A.T @ A) + lam * cp.norm(x, 1))
problem = cp.Problem(objective)

# Solve for different parameter values
for lam_val in [0.1, 1.0, 10.0]:
    lam.value = lam_val
    problem.solve()
    print(f"lambda={lam_val}, x={x.value}")

Callback Parameters

Special parameters that use callback functions to compute their values dynamically during problem solving.

class CallbackParam:
    """
    Parameter with a callback function for dynamic value computation.
    
    Parameters:  
    - callback: callable, function that returns the parameter value
    - shape: int or tuple, shape of the parameter
    - name: str, optional name for the parameter
    """
    def __init__(self, callback, shape=(), name=None): ...
    
    @property
    def value(self):
        """Get value by calling the callback function."""
        ...

Constants

Constants represent fixed numerical values in optimization problems. CVXPY automatically converts Python numbers and NumPy arrays to Constants.

class Constant:
    """
    Constant value in an optimization problem.
    
    Parameters:
    - value: scalar, array-like, or sparse matrix
    """
    def __init__(self, value): ...
    
    @property
    def value(self):
        """Get the constant value."""
        ...
        
    @property
    def grad(self):
        """Constants have zero gradient."""
        ...

Usage examples:

import cvxpy as cp
import numpy as np

# Scalar constant (usually automatic)
c1 = cp.Constant(3.14)
# Equivalent to just using: 3.14

# Vector constant
c2 = cp.Constant([1, 2, 3])
# Equivalent to: np.array([1, 2, 3])

# Matrix constant  
c3 = cp.Constant(np.eye(3))

# Constants are created automatically
x = cp.Variable()
expr = 2 * x + 5  # 2 and 5 become Constants automatically

Expression Base Class

The base class for all mathematical expressions in CVXPY, providing arithmetic operations and properties.

class Expression:
    """
    Base class for all mathematical expressions.
    """
    
    # Arithmetic operations
    def __add__(self, other): ...
    def __radd__(self, other): ...
    def __sub__(self, other): ...
    def __rsub__(self, other): ...
    def __mul__(self, other): ...
    def __rmul__(self, other): ...
    def __truediv__(self, other): ...
    def __rtruediv__(self, other): ...
    def __pow__(self, other): ...
    def __neg__(self): ...
    def __pos__(self): ...
    
    # Comparison operations  
    def __eq__(self, other): ...
    def __le__(self, other): ...
    def __lt__(self, other): ...
    def __ge__(self, other): ...  
    def __gt__(self, other): ...
    
    # Matrix operations
    def __matmul__(self, other): ...
    def __rmatmul__(self, other): ...
    
    # Indexing
    def __getitem__(self, key): ...
    
    @property
    def value(self):
        """Numeric value of the expression (None if not evaluated)."""
        ...
        
    @property
    def grad(self):
        """Gradient of the expression."""
        ...
        
    @property  
    def shape(self):
        """Shape of the expression as a tuple."""
        ...
        
    @property
    def size(self):
        """Total number of elements in the expression."""
        ...
        
    @property
    def ndim(self):
        """Number of dimensions."""
        ...
        
    @property
    def T(self):
        """Transpose of the expression."""
        ...
        
    def flatten(self):
        """Flatten the expression to a vector."""
        ...
        
    def reshape(self, shape):
        """Reshape the expression."""
        ...

Usage examples:

import cvxpy as cp

# Create variables
x = cp.Variable(3)
y = cp.Variable(3)

# Arithmetic operations
expr1 = x + y
expr2 = 2 * x - 3 * y
expr3 = x @ y  # dot product
expr4 = x[0] + x[1]  # indexing

# Properties
print(f"Shape: {expr1.shape}")
print(f"Size: {expr1.size}")

# After solving a problem
problem = cp.Problem(cp.Minimize(cp.sum_squares(x)), [x >= 0, cp.sum(x) == 1])
problem.solve()
print(f"Optimal x: {x.value}")
print(f"Objective value: {expr1.value}")

Install with Tessl CLI

npx tessl i tessl/pypi-cvxpy

docs

atoms.md

constraints.md

errors.md

expressions.md

index.md

problems.md

solvers.md

transforms.md

tile.json