• Stars
    star
    119
  • Rank 289,257 (Top 6 %)
  • Language
    Python
  • License
    Apache License 2.0
  • Created about 3 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Code generation with CVXPY

CVXPYgen - Code generation with CVXPY

CVXPYgen takes a convex optimization problem family modeled with CVXPY and generates a custom solver implementation in C. This generated solver is specific to the problem family and accepts different parameter values. In particular, this solver is suitable for deployment on embedded systems. In addition, CVXPYgen creates a Python wrapper for prototyping and desktop (non-embedded) applications.

An overview of CVXPYgen can be found in our manuscript.

CVXPYgen accepts CVXPY problems that are compliant with Disciplined Convex Programming (DCP). DCP is a system for constructing mathematical expressions with known curvature from a given library of base functions. CVXPY uses DCP to ensure that the specified optimization problems are convex. In addition, problems need to be modeled according to Disciplined Parametrized Programming (DPP). Solving a DPP-compliant problem repeatedly for different values of the parameters can be much faster than repeatedly solving a new problem.

For now, CVXPYgen is a separate module, until it will be integrated into CVXPY. As of today, CVXPYgen works with linear, quadratic, and second-order cone programs.

This package has similar functionality as the package cvxpy_codegen, which appears to be unsupported.

Important: When generating code with the ECOS solver, the generated code is licensed under the GNU General Public License v3.0.

Installation

  1. Install cvxpygen (on Windows preferably with Python 3.9).

    pip install cvxpygen
    
  2. On Linux or Mac, install the GCC compiler. On Windows, install Microsoft Visual Studio with the 'Desktop development with C++' workload. CVXPYgen is tested with Visual Studio 2019 and 2022, older versions might work as well.

  3. Optional: If you wish to use the example notebooks located in examples/, install ipykernel, jupyter, matplotlib, and register a new kernel spec with Jupyter.

    pip install ipykernel jupyter matplotlib
    ipython kernel install --user --name=cvxpygen
    

If you wish to use the Clarabel solver, you need to install Rust and Eigen.

Example

We define a simple 'nonnegative least squares' problem, generate code for it, and solve the problem with example parameter values.

1. Generate Code

Let's step through the first part of examples/main.py. Define a convex optimization problem the way you are used to with CVXPY. Everything that is described as cp.Parameter() is assumed to be changing between multiple solves. For constant properties, use cp.Constant().

import cvxpy as cp

m, n = 3, 2
x = cp.Variable(n, name='x')
A = cp.Parameter((m, n), name='A', sparsity=[(0, 0), (0, 1), (1, 1)])
b = cp.Parameter(m, name='b')
problem = cp.Problem(cp.Minimize(cp.sum_squares(A @ x - b)), [x >= 0])

Specify the name attribute for variables and parameters to recognize them after generating code. The attribute sparsity is a list of 2-tuples that indicate the coordinates of nonzero entries of matrix A. Parameter sparsity is only taken into account for matrices.

Assign parameter values and test-solve.

import numpy as np

np.random.seed(0)
A.value = np.zeros((m, n))
A.value[0, 0] = np.random.randn()
A.value[0, 1] = np.random.randn()
A.value[1, 1] = np.random.randn()
b.value = np.random.randn(m)
problem.solve()

Generating C code for this problem is as simple as,

from cvxpygen import cpg

cpg.generate_code(problem, code_dir='nonneg_LS', solver='SCS')

where the generated code is stored inside nonneg_LS and the SCS solver is used. Next to the positional argument problem, all keyword arguments for the generate_code() method are summarized below.

Argument Meaning Type Default
code_dir directory for code to be stored in String 'CPG_code'
solver canonical solver to generate code with String CVXPY default
solver_opts options passed to canonical solver Dict None
enable_settings enabled settings that are otherwise locked by embedded solver List of Strings []
unroll unroll loops in canonicalization code Bool False
prefix prefix for unique code symbols when dealing with multiple problems String ''
wrapper compile Python wrapper for CVXPY interface Bool True

You can find an overview of the code generation result in nonneg_LS/README.html.

2. Solve & Compare

As summarized in the second part of examples/main.py, after assigning parameter values, you can solve the problem both conventionally and via the generated code, which is wrapped inside the custom CVXPY solve method cpg_solve.

import time
import sys

# import extension module and register custom CVXPY solve method
from nonneg_LS.cpg_solver import cpg_solve
problem.register_solve('cpg', cpg_solve)

# solve problem conventionally
t0 = time.time()
val = problem.solve(solver='SCS')
t1 = time.time()
sys.stdout.write('\nCVXPY\nSolve time: %.3f ms\n' % (1000*(t1-t0)))
sys.stdout.write('Primal solution: x = [%.6f, %.6f]\n' % tuple(x.value))
sys.stdout.write('Dual solution: d0 = [%.6f, %.6f]\n' % tuple(problem.constraints[0].dual_value))
sys.stdout.write('Objective function value: %.6f\n' % val)

# solve problem with C code via python wrapper
t0 = time.time()
val = problem.solve(method='cpg', updated_params=['A', 'b'], verbose=False)
t1 = time.time()
sys.stdout.write('\nCVXPYgen\nSolve time: %.3f ms\n' % (1000 * (t1 - t0)))
sys.stdout.write('Primal solution: x = [%.6f, %.6f]\n' % tuple(x.value))
sys.stdout.write('Dual solution: d0 = [%.6f, %.6f]\n' % tuple(problem.constraints[0].dual_value))
sys.stdout.write('Objective function value: %.6f\n' % val)

The argument updated_params specifies which user-defined parameter values are new. If the argument is omitted, all parameter values are assumed to be new. If only a subset of the user-defined parameters have new values, use this argument to speed up the solver.

Most solver settings can be specified as keyword arguments like without code generation. Here, we use verbose=False to suppress printing. The list of changeable settings differs by solver and is documented in <code_dir>/README.html after code generation.

Comparing the standard and codegen methods for this example, both the solutions and objective values are close. Especially for smaller problems like this, the new solve method 'cpg' is significantly faster than solving without code generation.

3. Executable

In the C code, all of your parameters and variables are stored as vectors via Fortran-style flattening (vertical index moves fastest). For example, the (i, j)-th entry of the original matrix with height h will be the i+j*h-th entry of the flattened matrix in C. For sparse parameters, i.e. matrices, the k-th entry of the C array is the k-th nonzero entry encountered when proceeding through the parameter column by column.

Before compiling the example executable, make sure that CMake 3.5 or newer is installed.

On Unix platforms, run the following commands in your terminal to compile and run the program:

cd nonneg_LS/c/build
cmake ..
cmake --build . --target cpg_example
./cpg_example

On Windows, type:

cd nonneg_LS\c\build
cmake ..
cmake --build . --target cpg_example --config release
Release\cpg_example

Tests

To run tests, install pytest via

conda install pytest

and execute:

cd tests
pytest

More Repositories

1

cvxpylayers

Differentiable convex optimization layers
Python
1,718
star
2

cvxportfolio

Portfolio optimization and back-testing.
Python
782
star
3

scs

Splitting Conic Solver
C
523
star
4

pymde

Minimum-distortion embedding with PyTorch
Python
516
star
5

cvxbook_additional_exercises

Additional exercises and data for EE364a. No solutions; for public consumption.
Julia
435
star
6

cvx_short_course

Materials for a short course on convex optimization.
Jupyter Notebook
310
star
7

CVXR

An R modeling language for convex optimization problems.
R
195
star
8

proximal

Sample implementations of proximal operators
MATLAB
181
star
9

dccp

A CVXPY extension for convex-concave programming
Python
122
star
10

qcqp

A CVXPY extension for handling nonconvex QCQP via Suggest-and-Improve framework
Python
103
star
11

GGS

Greedy Gaussian Segmentation
Python
90
star
12

diffcp

Differentiation through cone programs
Python
86
star
13

cocp

Source code for the examples accompanying the paper "Learning convex optimization control policies."
Jupyter Notebook
78
star
14

ncvx

Python
69
star
15

cvxflow

Python
66
star
16

signal-decomposition

A simple and general framework for signal decomposition
Jupyter Notebook
55
star
17

auto_ks

Repository for "Fitting a Kalman Smoother to Data"
Python
51
star
18

cvxpower

Power Network Optimization and Simulation.
Python
47
star
19

cov_pred_finance

Jupyter Notebook
45
star
20

dmcp

A CVXPY extension for multi-convex programming
Python
43
star
21

CVXcanon

C++
42
star
22

qcml

A Python parser for generating Python/C/Matlab solver interfaces
Python
41
star
23

miqp_admm

ADMM for Mixed-Integer Quadratic Programming
C
39
star
24

vwap_opt_exec

Volume Weighted Average Price Optimal Execution
Jupyter Notebook
33
star
25

simulator

Tool to support backtests
Jupyter Notebook
32
star
26

a2dr

Anderson accelerated Douglas-Rachford splitting
Python
29
star
27

cptopt

Portfolio Optimization with Cumulative Prospect Theory Utility via Convex Optimization
Python
27
star
28

fastpathplanning

A fast algorithm for finding an optimal path in a collection of safe boxes
Python
27
star
29

strat_models

A distributed method for fitting Laplacian regularized stratified models.
Python
25
star
30

kelly_code

Code and examples for the project on risk-constrained Kelly gambling
Jupyter Notebook
24
star
31

dsp

A CVXPY extension for saddle problems
Python
21
star
32

osc

C package performing operator splitting for control
C
19
star
33

pdos

Primal-Dual Operator Splitting Method for Conic Optimization
C
19
star
34

nonexp_global_aa1

Globally Convergent Type-I Anderson Acceleration for Non-Smooth Fixed-Point Iterations
MATLAB
18
star
35

covpred

Covariance prediction via convex optimization
Python
18
star
36

aa

Anderson Acceleration
Jupyter Notebook
18
star
37

l1_ls

This is the repository for the l1_ls, a simple Matlab solver for l1-regularized least squares problems.
MATLAB
16
star
38

exp_util_gm_portfolio_opt

Minimal entropic value at risk (EVaR) portfolio construction under a Gaussian mixture model of returns.
Python
16
star
39

rsw

rsw: optimal representative sample weighting.
Python
15
star
40

cvxpyrepair

Code for "Automatic repair of convex optimization problems".
Python
14
star
41

osmm

oracle-structured minimization method
Python
13
star
42

cvx_opt_risk_neutral

Convex optimization over risk-neutral probabilities.
Jupyter Notebook
12
star
43

cvxstatarb

Jupyter Notebook
12
star
44

lrsm_portfolio

Portfolio Construction using Stratified Models
Jupyter Notebook
12
star
45

cvxmarkowitz

Jupyter Notebook
11
star
46

mkvchain

Fitting Feature-Dependent Markov Chains
Jupyter Notebook
10
star
47

cone_prog_refine

Cone program refinement
Python
9
star
48

icqm

MATLAB script for approximating the solution to the integer convex quadratic minimization problem
MATLAB
9
star
49

subgradpy

Subgradient calculator for Python
Python
8
star
50

PrincipalTimeSeries

MATLAB
8
star
51

torch_linops

A library to define abstract linear operators, and associated algebra and matrix-free algorithms, that works with pyTorch Tensors.
Python
8
star
52

vgi

Value-gradient iteration for convex stochastic control
Python
8
star
53

robust_bond_portfolio

Robust Bond Portfolio Construction via Convex-Concave Saddle Point Optimization
Python
8
star
54

sigopt

Solvers for sigmoidal programming problems
Python
7
star
55

cvxcla

critical line algorithm for efficient frontier
Jupyter Notebook
7
star
56

qss

QSS: Quadratic-Separable Solver
Jupyter Notebook
7
star
57

OSBDO

Oracle-Structured Bundle Distributed Optimization (OSBDO)
Python
7
star
58

SURE-CR

Tractable evaluation of Stein's Unbiased Risk Estimator on convexly regularized estimators
Python
7
star
59

mlr_fitting

Factor Fitting, Rank Allocation, and Partitioning in Multilevel Low Rank Matrices
Jupyter Notebook
6
star
60

WaveOperators.jl

Building matrices in physics is hard; that's why this package exists.
Julia
6
star
61

markowitz-reference

Python
6
star
62

l1_tf

This is the repository for the l1_tf, software for l1 trend filtering.
C
6
star
63

cvx-docker

Docker image containing CVXPY and other cvxgrp libraries
6
star
64

spcqe

Smooth periodic consistent quantile estimation
Jupyter Notebook
6
star
65

low_rank_forecasting_code

Code for "Low Rank Forecasting" paper.
Jupyter Notebook
5
star
66

lass

Linear algebra for structured sparse matrices
Python
5
star
67

sccf

Repository for "Minimizing a sum of clipped convex functions" paper
Python
5
star
68

cvxrisk

Compile risk with cvxpy
Jupyter Notebook
5
star
69

graph_isom

Python
4
star
70

conda-recipes

Anaconda recipes for cvxgrp python packages
Shell
4
star
71

lfd_lqr

Code for "Fitting a Linear Control Policy to Demonstrations with a Kalman Constraint"
Jupyter Notebook
4
star
72

mm_dist_lapl

Python
4
star
73

multi_period_liability_clearing

Code for the paper "Multi-period liability clearing via convex optimal control"
Python
4
star
74

ls-spa

Python
4
star
75

l1_logreg

This is the repository for the l1_logreg, l1-regularized logistic regression problem solver.
C
3
star
76

resalloc

Efficient allocation of fungible resources
Jupyter Notebook
3
star
77

joint-lrsm

Joint graph learning and model fitting in Laplacian Regularized Stratified Models
Python
3
star
78

n-queens

Python
2
star
79

PhysicalBounds.jl

Julia
2
star
80

boolprob

A Python tool to analyze joint distributions of boolean random variables
Python
2
star
81

cvxcli

Example cli using fire, poetry and pipx
Python
2
star
82

cvxbson

dealing with json and bson files
Python
2
star
83

opt_cap_res

Solves the problem of reserving link capacity in a network in such a way that any of a given set of flow scenarios can be supported.
Python
2
star
84

rerm_code

Public code for Robust Empirical Risk Minimization Paper
Python
1
star
85

ls-spa-benchmark

Python
1
star
86

extquadcontrol

Python
1
star
87

convexjl

A julia package for disciplined convex programming.
1
star
88

boilerplate

We use this repo to automate and avoid boilerplate issue
Python
1
star
89

incre_prox_mf_mpc

code for the paper Incremental Proximal Multi-Forecast Model Predictive Control
Jupyter Notebook
1
star
90

home-energy-management

Home energy management with dynamic tariffs and tiered peak power charges.
Jupyter Notebook
1
star
91

cvx_stat_arb

Jupyter Notebook
1
star
92

cvxbacktest

Python
1
star
93

coneos

C package that solves convex cone problems via operator splitting (DEPRECATED, new project https://github.com/cvxgrp/scs)
C
1
star
94

pd-heuristics-and-bounds

Julia
1
star