### Install and Run Test Suite Source: https://github.com/cvxgrp/cvxpygen/blob/master/README.md Instructions for installing the pytest dependency and executing the project test suite. ```bash conda install pytest cd tests pytest ``` -------------------------------- ### C/C++ Solver Compilation and Execution Example Source: https://github.com/cvxgrp/cvxpygen/blob/master/cvxpygen/template/README.html This section provides instructions for compiling and running the example executable generated by CVXPYgen. It includes environment activation and platform-specific commands for CMake to build the C/C++ solver and its example usage. ```Shell conda activate cpg_env cd $CODEDIR/c/build cmake .. cmake --build . --target cpg_example ./cpg_example ``` ```Shell cd $CODEDIR\c\build cmake .. cmake --build . --target cpg_example --config release Release\cpg_example ``` -------------------------------- ### Dynamics and Parameter Setup for ADP Source: https://github.com/cvxgrp/cvxpygen/blob/master/examples/ADP.ipynb Implements the system dynamics function and sets up the parameter values for the CVXPY problem. The dynamics function calculates discrete-time system matrices A and B based on the current state x. Parameter values for Rsqrt, f, and G are then assigned. ```python import numpy as np def dynamics(x): # continuous-time dynmaics A_cont = np.array([[0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1], [0, 0, 0, -x[3], 0, 0], [0, 0, 0, 0, -x[4], 0], [0, 0, 0, 0, 0, -x[5]]]) mass = 1 B_cont = np.concatenate((np.zeros((3,3)), (1/mass)*np.diag(x[3:])), axis=0) # discrete-time dynamics td = 0.1 A = np.eye(n)+td*A_cont B = td*B_cont return A, B # cost Rsqrt.value = np.sqrt(0.1)*np.eye(m) Psqrt = np.eye(n) x = np.array([2, 2, 2, -1, -1, 1]) A, B = dynamics(x) f.value = np.matmul(Psqrt, np.matmul(A, x)) G.value = np.matmul(Psqrt, B) val = problem.solve() ``` -------------------------------- ### Configure and Generate Code for OSQP Solver in Python Source: https://context7.com/cvxgrp/cvxpygen/llms.txt Generates code for a Quadratic Program (QP) using the OSQP solver, CVXPYgen's default. It demonstrates how to enable specific settings like verbose output and configure solver options such as warm starting. ```python import cvxpy as cp import numpy as np from cvxpygen import cpg n = 10 x = cp.Variable(n, name='x') P = cp.Parameter((n, n), name='P', PSD=True) q = cp.Parameter(n, name='q') A_eq = cp.Parameter((3, n), name='A_eq') b_eq = cp.Parameter(3, name='b_eq') problem = cp.Problem( cp.Minimize(0.5 * cp.quad_form(x, P) + q @ x), [A_eq @ x == b_eq, x >= -1, x <= 1] ) P.value = np.eye(n) q.value = np.random.randn(n) A_eq.value = np.random.randn(3, n) b_eq.value = np.random.randn(3) cpg.generate_code( problem, code_dir='osqp_qp', solver='OSQP', enable_settings=['verbose'], solver_opts={'warm_start': True} ) problem.solve( method='CPG', eps_abs=1e-6, eps_rel=1e-6, max_iter=10000, warm_start=True ) ``` -------------------------------- ### OSQP Solver Configuration Source: https://context7.com/cvxgrp/cvxpygen/llms.txt Configures CVXPYgen to generate code for the OSQP solver, the default for QPs, with options for warm starting and verbose output. ```APIDOC ## OSQP Solver Configuration ### Description Generates code for Quadratic Programs using the OSQP solver, which is the default. Supports efficient code generation and warm-starting. ### Method `cpg.generate_code()` ### Endpoint N/A (Code generation function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import cvxpy as cp import numpy as np from cvxpygen import cpg n = 10 x = cp.Variable(n, name='x') P = cp.Parameter((n, n), name='P', PSD=True) q = cp.Parameter(n, name='q') A_eq = cp.Parameter((3, n), name='A_eq') b_eq = cp.Parameter(3, name='b_eq') problem = cp.Problem( cp.Minimize(0.5 * cp.quad_form(x, P) + q @ x), [A_eq @ x == b_eq, x >= -1, x <= 1] ) P.value = np.eye(n) q.value = np.random.randn(n) A_eq.value = np.random.randn(3, n) b_eq.value = np.random.randn(3) cpg.generate_code( problem, code_dir='osqp_qp', solver='OSQP', enable_settings=['verbose'], solver_opts={'warm_start': True} ) problem.solve( method='CPG', eps_abs=1e-6, eps_rel=1e-6, max_iter=10000, warm_start=True ) ``` ### Response #### Success Response (200) N/A (Code generation process) #### Response Example N/A ``` -------------------------------- ### Define Optimization Problem with CVXPY Source: https://github.com/cvxgrp/cvxpygen/blob/master/examples/charging.ipynb Defines the variables, parameters, objective function, and constraints for the optimal charging problem. This setup is DPP-compliant to facilitate efficient solving and code generation. ```python import cvxpy as cp import numpy as np T = 1440 u = cp.Variable(T, name='u') q = cp.Variable(T+1, name='q') p = cp.Parameter(T, nonneg=True, name='p') s = cp.Parameter(T, nonneg=True, name='s') D = cp.Parameter(nonneg=True, name='D') C = cp.Parameter(nonneg=True, name='C') Q = cp.Parameter(nonneg=True, name='Q') gamma = cp.Parameter(nonneg=True, name='gamma') objective = cp.Minimize(p@u + s@cp.abs(u) + gamma*cp.sum_squares(u)) constraints = [q[1:] == q[:-1] + u, -D <= u, u<= C, 0 <= q, q <= Q, q[0] == 0, q[-1] == Q] problem = cp.Problem(objective, constraints) ``` -------------------------------- ### Assign Parameter Values and Solve Source: https://github.com/cvxgrp/cvxpygen/blob/master/README.md Assigns numerical values to the CVXPY parameters, including sparse matrices using scipy.sparse.coo_array, and performs an initial solve using the conventional CVXPY solver to verify the problem setup. ```python import numpy as np import scipy.sparse as sp np.random.seed(1) A.value_sparse = sp.coo_array((np.random.randn(3), A.sparse_idx), shape=(m, n)) b.value = np.random.randn(m) problem.solve() ``` -------------------------------- ### Configure CMake Build Environment for CVXPYgen Source: https://github.com/cvxgrp/cvxpygen/blob/master/cvxpygen/template/CMakeLists.txt This CMake script sets up the project environment, configures compiler flags for different operating systems, and detects Apple Silicon architecture. It also manages the inclusion of source directories and defines the build targets for the static library and example executable. ```cmake cmake_minimum_required (VERSION 3.5) project (cvxpygen) if (NOT ${CMAKE_SYSTEM_NAME} STREQUAL "Windows") set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O3") set (CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -O0 -g") set (CMAKE_C_STANDARD_LIBRARIES "${CMAKE_C_STANDARD_LIBRARIES} -lm") endif() if(${CMAKE_SYSTEM_NAME} STREQUAL "Darwin" AND ${CMAKE_SYSTEM_PROCESSOR} STREQUAL "arm64") message(STATUS "Apple Silicon detected: Configuring build for arm64") set(ARM64 TRUE) else() set(ARM64 FALSE) endif() set (CMAKE_POSITION_INDEPENDENT_CODE ON) set (LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/out) add_subdirectory (solver_code) include_directories (${cpg_include}) add_executable (cpg_example ${cpg_head} ${cpg_src} ${CMAKE_CURRENT_SOURCE_DIR}/src/cpg_example.c) add_library (cpg STATIC ${cpg_head} ${cpg_src}) ``` -------------------------------- ### Generate Code for SCS Solver for SOCP in Python Source: https://context7.com/cvxgrp/cvxpygen/llms.txt Generates code for a Second-Order Cone Program (SOCP) using the SCS solver via CVXPYgen. This snippet shows the basic setup for an SOCP and how to specify SCS as the solver. ```python import cvxpy as cp import numpy as np from cvxpygen import cpg n = 5 x = cp.Variable(n, name='x') c = cp.Parameter(n, name='c') A = cp.Parameter((3, n), name='A') b = cp.Parameter(3, name='b') problem = cp.Problem( cp.Minimize(c @ x), [cp.norm(A @ x) <= 1, x >= 0] ) c.value = np.random.randn(n) A.value = np.random.randn(3, n) b.value = np.random.randn(3) cpg.generate_code( problem, code_dir='scs_socp', solver='SCS' ) problem.solve( method='CPG', eps_abs=1e-4, eps_rel=1e-4, max_iters=5000 ) ``` -------------------------------- ### Generate Code for ECOS Solver for Conic Programs in Python Source: https://context7.com/cvxgrp/cvxpygen/llms.txt Generates code for a general conic optimization problem using the ECOS solver through CVXPYgen. This example illustrates defining a problem with conic constraints and using ECOS with specific solver settings. ```python import cvxpy as cp import numpy as np from cvxpygen import cpg n = 4 x = cp.Variable(n, name='x') c = cp.Parameter(n, name='c') problem = cp.Problem( cp.Minimize(c @ x), [cp.norm(x[:2]) <= x[2], x[3] >= 0, cp.sum(x) == 1] ) c.value = np.array([1, 2, 0, -1]) cpg.generate_code(problem, code_dir='ecos_code', solver='ECOS') problem.solve( method='CPG', feastol=1e-8, abstol=1e-8, maxit=100 ) ``` -------------------------------- ### Use Generated C Solver with Python Wrapper Source: https://github.com/cvxgrp/cvxpygen/blob/master/examples/MPC.ipynb Demonstrates how to load the serialized CVXPY problem, assign parameter values, and solve it using the generated C solver via a Python wrapper. It also includes a comparison with the conventional CVXPY solver's performance. ```python from MPC_code.cpg_solver import cpg_solve import numpy as np import pickle import time # load the serialized problem formulation with open('MPC_code/problem.pickle', 'rb') as f: prob = pickle.load(f) # assign parameter values prob.param_dict['A'].value = np.eye(n)+td*A_cont prob.param_dict['B'].value = td*B_cont prob.param_dict['Psqrt'].value = np.eye(n) prob.param_dict['Qsqrt'].value = np.eye(n) prob.param_dict['Rsqrt'].value = np.sqrt(0.1)*np.eye(m) prob.param_dict['x_init'].value = np.array([2, 2, 2, -1, -1, 1]) # solve problem conventionally t0 = time.time() # CVXPY chooses eps_abs=eps_rel=1e-5, max_iter=10000, polish=True by default, # however, we choose the OSQP default values here, as they are used for code generation as well val = prob.solve(eps_abs=1e-3, eps_rel=1e-3, max_iter=4000, polish=False) t1 = time.time() print('\nCVXPY\nSolve time: %.3f ms' % (1000 * (t1 - t0))) print('Objective function value: %.6f\n' % val) ``` -------------------------------- ### Generate Explicit Solver for Parametric QP in Python Source: https://context7.com/cvxgrp/cvxpygen/llms.txt Generates an explicit solver for a parametric Quadratic Program (QP) where the solution is a piecewise affine function of parameters. This allows for very fast online evaluation. It requires parameter bounds to be defined. ```python import cvxpy as cp import numpy as np from cvxpygen import cpg n = 3 x = cp.Variable(n, name='x') theta = cp.Parameter(n, name='theta') problem = cp.Problem( cp.Minimize(cp.sum_squares(x - theta)), [ x >= 0, cp.sum(x) <= 1, theta >= -1, # Parameter lower bound theta <= 1 # Parameter upper bound ] ) theta.value = np.zeros(n) cpg.generate_code( problem, code_dir='explicit_qp', solver='explicit', solver_opts={ 'dual': True, 'max_regions': 500, 'max_floats': 1e6, 'fp16': False } ) theta.value = np.array([0.5, -0.3, 0.1]) problem.solve(method='CPG') print(f'Solution: {x.value}') ``` -------------------------------- ### C API Solver Interaction Source: https://context7.com/cvxgrp/cvxpygen/llms.txt Demonstrates how to interface with generated C code to update problem parameters, execute the solver, and retrieve primal/dual solutions and solver metadata. ```c #include "cpg_workspace.h" #include "cpg_solve.h" int main() { cpg_update_param_name(1.5); cpg_update_A(0, 0.5); cpg_update_b(1, 2.3); cpg_solve(); printf("x[0] = %f\n", CPG_Result.prim->x[0]); printf("d0[0] = %f\n", CPG_Result.dual->d0[0]); printf("Objective: %f\n", CPG_Result.info->obj_val); printf("Iterations: %d\n", CPG_Result.info->iter); printf("Status: %s\n", CPG_Result.info->status); cpg_set_solver_default_settings(); cpg_set_solver_max_iter(1000); cpg_set_solver_eps_abs(1e-6); return 0; } ``` -------------------------------- ### C Code Interface - Building Executable Source: https://context7.com/cvxgrp/cvxpygen/llms.txt Instructions on how to compile and run the C code generated by CVXPYgen for embedded deployment, bypassing Python dependencies. ```APIDOC ## Building the C Executable ### Description After CVXPYgen generates C code, it can be compiled into a standalone executable for deployment in environments without Python. This process typically uses CMake. ### Method Command-line compilation using CMake. ### Endpoint N/A (Build process) ### Parameters None ### Request Example ```bash # Navigate to the generated code directory cd nonneg_LS/c/build # Configure with CMake cmake .. # Build the example executable cmake --build . --target cpg_example # Run the example ./cpg_example # On Windows: # cmake --build . --target cpg_example --config release # Release\cpg_example ``` ### Response #### Success Response (200) N/A (Build process output) #### Response Example N/A ``` -------------------------------- ### Compile and Run Generated C Code Source: https://github.com/cvxgrp/cvxpygen/blob/master/README.md Commands to compile and execute the generated C code for a quadratic program on Unix and Windows platforms using CMake. ```bash cd nonneg_LS/c/build cmake .. cmake --build . --target cpg_example ./cpg_example ``` ```bash cd nonneg_LS\c\build cmake .. cmake --build . --target cpg_example --config release Release\cpg_example ``` -------------------------------- ### MPC Problem Formulation and Code Generation Source: https://context7.com/cvxgrp/cvxpygen/llms.txt Shows how to define an MPC problem using CVXPY, generate a standalone C solver, and perform a simulation loop using the generated code. ```python import cvxpy as cp import numpy as np from cvxpygen import cpg n_state, n_input, N = 4, 2, 10 x = cp.Variable((n_state, N+1), name='x') u = cp.Variable((n_input, N), name='u') x0 = cp.Parameter(n_state, name='x0') x_ref = cp.Parameter((n_state, N+1), name='x_ref') A = cp.Parameter((n_state, n_state), name='A') B = cp.Parameter((n_state, n_input), name='B') Q, R = np.eye(n_state), 0.1 * np.eye(n_input) cost = sum(cp.quad_form(x[:, k] - x_ref[:, k], Q) + cp.quad_form(u[:, k], R) for k in range(N)) + cp.quad_form(x[:, N] - x_ref[:, N], Q) constraints = [x[:, 0] == x0] + [x[:, k+1] == A @ x[:, k] + B @ u[:, k] for k in range(N)] + [u >= -1, u <= 1] problem = cp.Problem(cp.Minimize(cost), constraints) cpg.generate_code(problem, code_dir='mpc_controller', solver='OSQP') for t in range(100): x0.value = np.random.randn(n_state) * 0.1 problem.solve(method='CPG', updated_params=['x0']) print(f't={t}: u = {u[:, 0].value}') ``` -------------------------------- ### Define Portfolio Optimization Problem in CVXPY Source: https://github.com/cvxgrp/cvxpygen/blob/master/examples/portfolio.ipynb Sets up the optimization variables, parameters, objective function, and constraints for a portfolio optimization model using the CVXPY library. ```python import cvxpy as cp import numpy as np n, m = 100, 10 w = cp.Variable(n, name='w') delta_w = cp.Variable(n, name='delta_w') f = cp.Variable(m, name='f') a = cp.Parameter(n, name='a') F = cp.Parameter((n, m), name='F') Sig_f_sqrt = cp.Parameter((m, m), name='Sig_f_sqrt') d_sqrt = cp.Parameter(n, name='d_sqrt') k_tc = cp.Parameter(n, nonneg=True, name='k_tc') k_sh = cp.Parameter(n, nonneg=True, name='k_sh') w_prev = cp.Parameter(n, name='w_prev') L = cp.Parameter(nonneg=True, name='L') objective = cp.Maximize(a@w - cp.sum_squares(Sig_f_sqrt@f) - cp.sum_squares(cp.multiply(d_sqrt, w)) - k_tc@cp.abs(delta_w) + k_sh@cp.minimum(0, w)) constraints = [f == F.T@w, np.ones(n)@w == 1, cp.norm(w, 1) <= L, delta_w == w-w_prev] problem = cp.Problem(objective, constraints) ``` -------------------------------- ### Solve Resource Allocation Problem with CVXPYgen Wrapper Source: https://github.com/cvxgrp/cvxpygen/blob/master/examples/resource.ipynb Demonstrates how to use the Python wrapper generated by CVXPYgen to solve the resource allocation problem. It loads the serialized problem, assigns parameter values, and compares the solve time and objective value against the standard CVXPY solver. ```python from resource_code.cpg_solver import cpg_solve import numpy as np import pickle import time # load the serialized problem formulation with open('resource_code/problem.pickle', 'rb') as f: prob = pickle.load(f) # assign parameter values np.random.seed(0) prob.param_dict['S'].value = 100*np.eye(n) prob.param_dict['W'].value = 0.8*np.ones((n, m)) + 0.2*np.random.rand(n, m) prob.param_dict['X_min'].value = np.zeros((n, m)) prob.param_dict['X_max'].value = np.ones((n, m)) prob.param_dict['r'].value = np.matmul(prob.param_dict['X_min'].value.T, np.ones(n)) + np.random.rand(m) # solve problem conventionally t0 = time.time() # CVXPY chooses eps_abs=eps_rel=1e-5, max_iter=10000, polish=True by default, # however, we choose the OSQP default values here, as they are used for code generation as well val = prob.solve() t1 = time.time() print('\nCVXPY\nSolve time: %.3f ms' % (1000 * (t1 - t0))) print('Objective function value: %.6f\n' % val) # solve problem with C code via python wrapper prob.register_solve('CPG', cpg_solve) t0 = time.time() val = prob.solve(method='CPG') t1 = time.time() print('\nCVXPYgen\nSolve time: %.3f ms' % (1000 * (t1 - t0))) print('Objective function value: %.6f\n' % val) ``` -------------------------------- ### Visualize Actuator Optimization Results Source: https://github.com/cvxgrp/cvxpygen/blob/master/examples/actuator.ipynb Generates an animation from the solved optimization problem and displays the resulting GIF in an IPython environment. It requires the visualization module and IPython display utilities. ```python from visualization.actuator import create_animation from IPython.display import Image create_animation(prob, 'actuator_animation') with open('actuator_animation.gif', 'rb') as f: display(Image(f.read())) ``` -------------------------------- ### Benchmark CVXPYgen Solver vs Standard CVXPY Source: https://github.com/cvxgrp/cvxpygen/blob/master/examples/network.ipynb Loads a serialized problem, assigns parameters, and compares the solve time between the standard CVXPY solver and the generated C-based solver. ```python from network_code.cpg_solver import cpg_solve import numpy as np import pickle import time with open('network_code/problem.pickle', 'rb') as f: prob = pickle.load(f) prob.register_solve('CPG', cpg_solve) val = prob.solve(method='CPG') ``` -------------------------------- ### Use Generated C Solver in Python Source: https://github.com/cvxgrp/cvxpygen/blob/master/examples/portfolio.ipynb Loads the serialized problem and uses the generated C solver wrapper to perform optimization. ```python from portfolio_code.cpg_solver import cpg_solve import pickle with open('portfolio_code/problem.pickle', 'rb') as f: prob = pickle.load(f) prob.param_dict['a'].value = alpha/gamma prob.param_dict['F'].value = np.round(np.random.randn(n, m)) prob.param_dict['Sig_f_sqrt'].value = np.diag(np.random.rand(m)) prob.param_dict['d_sqrt'].value = np.random.rand(n) prob.param_dict['k_tc'].value = kappa_tc/gamma prob.param_dict['k_sh'].value = kappa_sh/gamma prob.param_dict['w_prev'].value = np.zeros(n) prob.param_dict['L'].value = 1.6 ``` -------------------------------- ### Configure and Solve Optimization Problem with CVXPY and CVXPYgen Source: https://github.com/cvxgrp/cvxpygen/blob/master/examples/charging.ipynb This snippet shows how to assign values to CVXPY parameters, solve the problem using the OSQP solver, and utilize the CVXPYgen register_solve method to execute generated C code for faster performance. ```python import numpy as np import time # assign parameter values prob.param_dict['p'].value = np.concatenate((3*np.ones(3*60), 5*np.ones(7*60), 1*np.ones(14*60)), axis=0) eta = 0.1 prob.param_dict['s'].value = eta*prob.param_dict['p'].value prob.param_dict['Q'].value = 1 prob.param_dict['C'].value = 5*prob.param_dict['Q'].value/(24*60) prob.param_dict['D'].value = 2*prob.param_dict['C'].value # solve problem conventionally t0 = time.time() val = prob.solve(solver='OSQP', eps_abs=1e-3, eps_rel=1e-3, max_iter=4000, polish=False) t1 = time.time() print('\nCVXPY\nSolve time: %.3f ms' % (1000 * (t1 - t0))) print('Objective function value: %.6f\n' % val) # solve problem with C code via python wrapper prob.register_solve('CPG', cpg_solve) t0 = time.time() val = prob.solve(method='CPG') t1 = time.time() print('\nCVXPYgen\nSolve time: %.3f ms' % (1000 * (t1 - t0))) print('Objective function value: %.6f\n' % val) ``` -------------------------------- ### Explicit Solver Generation Source: https://context7.com/cvxgrp/cvxpygen/llms.txt Generates an explicit solver for parametric QPs where the solution is a piecewise affine function of parameters. This allows for very fast online evaluation. ```APIDOC ## Explicit Solver Generation ### Description Generates an explicit solver for parametric QPs. The solution map is evaluated directly, enabling fast online computation. ### Method `cpg.generate_code()` ### Endpoint N/A (Code generation function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import cvxpy as cp import numpy as np from cvxpygen import cpg n = 3 x = cp.Variable(n, name='x') theta = cp.Parameter(n, name='theta') problem = cp.Problem( cp.Minimize(cp.sum_squares(x - theta)), [ x >= 0, cp.sum(x) <= 1, theta >= -1, theta <= 1 ] ) theta.value = np.zeros(n) cpg.generate_code( problem, code_dir='explicit_qp', solver='explicit', solver_opts={ 'dual': True, 'max_regions': 500, 'max_floats': 1e6, 'fp16': False } ) theta.value = np.array([0.5, -0.3, 0.1]) problem.solve(method='CPG') print(f'Solution: {x.value}') ``` ### Response #### Success Response (200) N/A (This is a code generation process, not an API endpoint call) #### Response Example N/A ``` -------------------------------- ### Gradient Computation for QPs with CVXPYgen Source: https://context7.com/cvxgrp/cvxpygen/llms.txt Enables differentiation through quadratic programs generated by CVXPYgen, facilitating integration with machine learning frameworks like PyTorch via CVXPYlayers. Requires `gradient=True` during code generation. Dependencies include CVXPY, NumPy, and CVXPYlayers. ```python import cvxpy as cp import numpy as np from cvxpygen import cpg # Define a simple QP n = 5 x = cp.Variable(n, name='x') P = cp.Parameter((n, n), name='P', PSD=True) q = cp.Parameter(n, name='q') problem = cp.Problem(cp.Minimize(0.5 * cp.quad_form(x, P) + q @ x), [x >= 0]) # Set parameter values P.value = np.eye(n) q.value = np.ones(n) # Generate code with gradient support cpg.generate_code(problem, code_dir='qp_diff', solver='OSQP', gradient=True) # Use with CVXPYlayers for automatic differentiation from qp_diff.cpg_solver import forward, backward from cvxpylayers.torch import CvxpyLayer # Create differentiable layer layer = CvxpyLayer( problem, parameters=[P, q], variables=[x], custom_method=(forward, backward) ) ``` -------------------------------- ### Benchmark CVXPY and CVXPYgen Solvers Source: https://github.com/cvxgrp/cvxpygen/blob/master/examples/portfolio.ipynb This snippet compares the solve time and objective value of a convex optimization problem using the default OSQP solver in CVXPY and the generated C code via the CPG wrapper. It utilizes the time module to measure latency in milliseconds. ```python import time # Solve with default OSQP settings t0 = time.time() val = prob.solve(eps_abs=1e-3, eps_rel=1e-3, max_iter=4000, polish=False) t1 = time.time() print('\nCVXPY\nSolve time: %.3f ms' % (1000 * (t1 - t0))) print('Objective function value: %.6f\n' % val) # Solve problem with C code via python wrapper prob.register_solve('CPG', cpg_solve) t0 = time.time() val = prob.solve(method='CPG') t1 = time.time() print('\nCVXPYgen\nSolve time: %.3f ms' % (1000 * (t1 - t0))) print('Objective function value: %.6f\n' % val) ``` -------------------------------- ### Generate and Load C Code for Solver Source: https://github.com/cvxgrp/cvxpygen/blob/master/examples/charging.ipynb Uses cvxpygen to generate C source code for the defined problem and demonstrates how to load the serialized problem for use with the custom solver. ```python from cvxpygen import cpg from charging_code.cpg_solver import cpg_solve import pickle cpg.generate_code(problem, code_dir='charging_code') with open('charging_code/problem.pickle', 'rb') as f: prob = pickle.load(f) ``` -------------------------------- ### Solve and Visualize Charging Schedule Source: https://github.com/cvxgrp/cvxpygen/blob/master/examples/charging.ipynb Assigns numerical values to parameters, solves the optimization problem, and uses matplotlib to visualize the state-of-charge against price levels. ```python import matplotlib.pyplot as plt p.value = np.concatenate((3*np.ones(3*60), 5*np.ones(7*60), 1*np.ones(14*60)), axis=0) eta = 0.1 s.value = eta*p.value Q.value = 1 C.value = 3*Q.value/(24*60) D.value = 2*C.value gamma.value = 100 val = problem.solve() fig, ax1 = plt.subplots() ax1.plot(100*q.value, color='b') ax1.grid() ax1.set_xlabel('Time [min]') ax1.set_ylabel('SOC [%]', color='b') ax2 = ax1.twinx() ax2.plot(100*p.value / max(p.value), color='m') ax2.set_ylabel('Price Level [%]', color='m') ``` -------------------------------- ### Build C Executable from Generated CVXPYgen Code Source: https://context7.com/cvxgrp/cvxpygen/llms.txt Provides bash commands to compile and build a C executable from CVXPYgen generated code. This process involves navigating to the build directory, configuring with CMake, and then building the target executable. ```bash # Navigate to the generated code directory cd nonneg_LS/c/build # Configure with CMake cmake .. # Build the example executable cmake --build . --target cpg_example # Run the example ./cpg_example # On Windows: # cmake --build . --target cpg_example --config release # Release\cpg_example ``` -------------------------------- ### Visualize Resource Allocation Results Source: https://github.com/cvxgrp/cvxpygen/blob/master/examples/resource.ipynb Generates an animation to visualize the results of the resource allocation problem. This helps in understanding the dynamics and outcomes of the optimization, likely by plotting the allocation over time or iterations. ```python from visualization.resource import create_animation from IPython.display import Image create_animation(prob, 'resource_animation') with open('resource_animation.gif', 'rb') as f: display(Image(f.read())) ``` -------------------------------- ### Use Generated C Solver via Python Wrapper Source: https://github.com/cvxgrp/cvxpygen/blob/master/examples/actuator.ipynb This Python code demonstrates how to use the C solver generated by cvxpygen. It loads the serialized problem, assigns parameter values, and then calls the custom solver (cpg_solve) to solve the optimization problem, comparing its performance to the standard CVXPY solver. ```python from actuator_code.cpg_solver import cpg_solve import numpy as np import pickle import time # load the serialized problem formulation with open('actuator_code/problem.pickle', 'rb') as f: prob = pickle.load(f) # assign parameter values prob.param_dict['A'].value = np.array([[1, 0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1, 0, 1], [1, -1, 1, 1, -1, 1, -1, -1]]) prob.param_dict['w'].value = np.array([1, 1, 1]) prob.param_dict['lamb_sm'].value = 0.5 prob.param_dict['kappa'].value = 0.1*np.ones(8) prob.param_dict['u_prev'].value = np.zeros(8) prob.param_dict['u_min'].value = -np.ones(8) prob.param_dict['u_max'].value = np.ones(8) # solve problem conventionally t0 = time.time() # CVXPY chooses eps_abs=eps_rel=1e-5, max_iter=10000, polish=True by default, # however, we choose the OSQP default values here, as they are used for code generation as well val = prob.solve(eps_abs=1e-3, eps_rel=1e-3, max_iter=4000, polish=False) t1 = time.time() print('\nCVXPY\nSolve time: %.3f ms' % (1000 * (t1 - t0))) print('Objective function value: %.6f\n' % val) ``` -------------------------------- ### Solve CVXPY Problem with Generated C Code Source: https://context7.com/cvxgrp/cvxpygen/llms.txt Demonstrates solving a CVXPY problem using the custom C solver generated by CVXPYgen. This method is significantly faster than standard CVXPY solves, especially for smaller problems. It requires prior code generation with `wrapper=True`. Parameters can be updated efficiently. ```python import cvxpy as cp import numpy as np import scipy.sparse as sp import time from cvxpygen import cpg # Define and setup problem (same as before) m, n = 3, 2 x = cp.Variable(n, name='x') A = cp.Parameter((m, n), name='A', sparsity=((0, 0, 1), (0, 1, 1))) b = cp.Parameter(m, name='b') problem = cp.Problem(cp.Minimize(cp.sum_squares(A @ x - b)), [x >= 0]) # Set parameter values np.random.seed(1) A.value_sparse = sp.coo_array((np.random.randn(3), A.sparse_idx), shape=(m, n)) b.value = np.random.randn(m) # Generate code (registers 'CPG' solve method automatically when wrapper=True) cpg.generate_code(problem, code_dir='nonneg_LS', solver='OSQP') # Solve using standard CVXPY t0 = time.time() val_cvxpy = problem.solve(solver='OSQP') print(f'CVXPY solve time: {1000*(time.time()-t0):.3f} ms') print(f'Solution: x = {x.value}') # Solve using generated code (much faster) t0 = time.time() val_cpg = problem.solve(method='CPG', updated_params=['A', 'b']) print(f'CVXPYgen solve time: {1000*(time.time()-t0):.3f} ms') print(f'Solution: x = {x.value}') print(f'Dual solution: {problem.constraints[0].dual_value}') print(f'Objective value: {val_cpg}') # Only specify parameters that changed for faster updates b.value = np.array([1.0, 2.0, 3.0]) val_updated = problem.solve(method='CPG', updated_params=['b']) ``` -------------------------------- ### Configure CMake for CVXPYgen Integration Source: https://github.com/cvxgrp/cvxpygen/blob/master/cvxpygen/template/README.html This snippet demonstrates how to include the generated subdirectory and link the necessary source and header variables into your existing CMake project targets. ```cmake add_subdirectory() include_directories( ${$CPGCMAKELISTS_include}) # Add these variables to your target_sources or target_link_libraries # ${$CPGCMAKELISTS_head} # ${$CPGCMAKELISTS_src} ``` -------------------------------- ### Generate Differentiable Code and Integrate with CVXPYlayers Source: https://github.com/cvxgrp/cvxpygen/blob/master/README.md Configures CVXPYgen to generate code with gradient support and demonstrates how to wrap the resulting solver in a CvxpyLayer for use in PyTorch. ```python cpg.generate_code(problem, code_dir='code_diff', gradient=True) from code_diff.cpg_solver import forward, backward from cvxpylayers.torch import CvxpyLayer layer = CvxpyLayer(problem, parameters=[A, b], variables=[x], custom_method=(forward, backward)) ``` -------------------------------- ### generate_code Source: https://context7.com/cvxgrp/cvxpygen/llms.txt Generates a complete C solver implementation from a CVXPY problem object, with options for Python wrappers and gradient support. ```APIDOC ## generate_code ### Description The primary function to generate custom C code for a specific convex optimization problem. It compiles the problem into a solver-specific implementation optimized for performance. ### Method Python Function Call ### Parameters #### Arguments - **problem** (cvxpy.Problem) - Required - The CVXPY problem to generate code for. - **code_dir** (str) - Required - Directory path to store generated C files. - **solver** (str) - Optional - The canonical solver to use (e.g., 'OSQP', 'SCS', 'ECOS'). - **wrapper** (bool) - Optional - Whether to compile a Python wrapper for prototyping. - **gradient** (bool) - Optional - Whether to enable differentiation support for machine learning. ### Request Example ```python cpg.generate_code(problem, code_dir='solver_out', solver='OSQP', wrapper=True) ``` ### Response #### Success Response - **status** (void) - Generates files in the specified directory and registers the 'CPG' solve method if wrapper is enabled. ``` -------------------------------- ### Generate C Code with CVXPYGEN Source: https://github.com/cvxgrp/cvxpygen/blob/master/README.md Generates C code for the defined CVXPY problem using the cvxpygen library. The generated code is saved to a specified directory (`code_dir`) and utilizes a particular solver (e.g., 'OSQP'). Various options like solver settings, unrolling loops, and gradient computation can be configured. ```python from cvxpygen import cpg cpg.generate_code(problem, code_dir='nonneg_LS', solver='OSQP') ``` -------------------------------- ### Define CVXPY Problem and Parameters Source: https://github.com/cvxgrp/cvxpygen/blob/master/README.md Defines a convex optimization problem using CVXPY, specifying variables, parameters (including sparsity for matrices), and constraints. Parameters intended to change between solves should be defined as cp.Parameter, while constants should be cp.Constant. Naming variables and parameters is crucial for code generation. ```python import cvxpy as cp m, n = 3, 2 x = cp.Variable(n, name='x') A = cp.Parameter((m, n), name='A', sparsity=((0, 0, 1), (0, 1, 1))) b = cp.Parameter(m, name='b') problem = cp.Problem(cp.Minimize(cp.sum_squares(A @ x - b)), [x >= 0]) ``` -------------------------------- ### Generate C Code for MPC Solver with CVXPYgen Source: https://github.com/cvxgrp/cvxpygen/blob/master/examples/MPC.ipynb Uses the CVXPYgen library to generate C source code for the defined CVXPY problem. This allows for efficient, standalone execution of the optimization problem without requiring CVXPY at runtime. ```python from cvxpygen import cpg cpg.generate_code(problem, code_dir='MPC_code') ``` -------------------------------- ### Define Network Flow Optimization Problem in CVXPY Source: https://github.com/cvxgrp/cvxpygen/blob/master/examples/network.ipynb Sets up the optimization variables, parameters, objective function, and constraints for a network flow problem using the CVXPY library. ```python import cvxpy as cp import numpy as np n, m = 4, 5 f = cp.Variable(n, name='f') R = cp.Parameter((m, n), name='R') c = cp.Parameter(m, nonneg=True, name='c') w = cp.Parameter(n, nonneg=True, name='w') f_min = cp.Parameter(n, nonneg=True, name='f_min') f_max = cp.Parameter(n, nonneg=True, name='f_max') objective = cp.Maximize(w@f) constraints = [R@f <= c, f_min <= f, f <= f_max] problem = cp.Problem(objective, constraints) ``` -------------------------------- ### Solve Optimization Problem using CVXPYgen Source: https://github.com/cvxgrp/cvxpygen/blob/master/examples/MPC.ipynb This snippet registers the CPG solver with a CVXPY problem instance and executes the solve method. It measures the execution time in milliseconds and prints the resulting objective function value. ```python prob.register_solve('CPG', cpg_solve) t0 = time.time() val = prob.solve(method='CPG') t1 = time.time() print('\nCVXPYgen\nSolve time: %.3f ms' % (1000 * (t1 - t0))) print('Objective function value: %.6f\n' % val) ``` -------------------------------- ### Solve Portfolio Optimization Problem Source: https://github.com/cvxgrp/cvxpygen/blob/master/examples/portfolio.ipynb Assigns values to the defined CVXPY parameters and solves the optimization problem. ```python np.random.seed(0) gamma = 1 alpha = np.random.randn(n) kappa_tc = 0.01*np.ones(n) kappa_sh = 0.05*np.ones(n) a.value = alpha/gamma F.value = np.random.randn(n, m) Sig_f_sqrt.value = np.random.rand(m, m) d_sqrt.value = np.random.rand(n) k_tc.value = kappa_tc/gamma k_sh.value = kappa_sh/gamma w_prev_unnormalized = np.random.rand(n) w_prev.value = w_prev_unnormalized/np.linalg.norm(w_prev_unnormalized) L.value = 1.6 val = problem.solve() ``` -------------------------------- ### Solve Optimization Problem using CVXPYgen CPG Source: https://github.com/cvxgrp/cvxpygen/blob/master/examples/ADP.ipynb Registers the CPG solver with a CVXPY problem instance and executes the solve method. It measures the execution time and outputs the objective function value. ```python import time # Register the CPG solver prob.register_solve('CPG', cpg_solve) # Measure solve time t0 = time.time() val = prob.solve(method='CPG') t1 = time.time() # Output results print('\nCVXPYgen\nSolve time: %.3f ms' % (1000 * (t1 - t0))) print('Objective function value: %.6f\n' % val) ``` -------------------------------- ### Assign Parameters and Solve MPC Problem Source: https://github.com/cvxgrp/cvxpygen/blob/master/examples/MPC.ipynb Assigns numerical values to the parameters defined in the CVXPY problem, including system dynamics matrices (A, B), cost matrices (Psqrt, Qsqrt, Rsqrt), and initial state (x_init). It then solves the CVXPY problem. ```python import numpy as np # continuous-time dynmaics A_cont = np.concatenate((np.array([[0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1]]), np.zeros((3,6))), axis=0) mass = 1 B_cont = np.concatenate((np.zeros((3,3)), (1/mass)*np.diag(np.ones(3))), axis=0) # discrete-time dynamics td = 0.1 A.value = np.eye(n)+td*A_cont B.value = td*B_cont # cost Psqrt.value = np.eye(n) Qsqrt.value = np.eye(n) Rsqrt.value = np.sqrt(0.1)*np.eye(m) # measurement x_init.value = np.array([2, 2, 2, -1, -1, 1]) val = problem.solve() ``` -------------------------------- ### SCS Solver for Conic Programs Source: https://context7.com/cvxgrp/cvxpygen/llms.txt Generates code for Second-Order Cone Programs (SOCPs) using the SCS solver, which supports conic constraints. ```APIDOC ## SCS Solver for Conic Programs ### Description Generates code for Second-Order Cone Programs (SOCPs) using the SCS solver. This solver is suitable for problems involving conic constraints. ### Method `cpg.generate_code()` ### Endpoint N/A (Code generation function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import cvxpy as cp import numpy as np from cvxpygen import cpg n = 5 x = cp.Variable(n, name='x') c = cp.Parameter(n, name='c') A = cp.Parameter((3, n), name='A') b = cp.Parameter(3, name='b') problem = cp.Problem( cp.Minimize(c @ x), [cp.norm(A @ x) <= 1, x >= 0] ) c.value = np.random.randn(n) A.value = np.random.randn(3, n) b.value = np.random.randn(3) cpg.generate_code( problem, code_dir='scs_socp', solver='SCS' ) problem.solve( method='CPG', eps_abs=1e-4, eps_rel=1e-4, max_iters=5000 ) ``` ### Response #### Success Response (200) N/A (Code generation process) #### Response Example N/A ``` -------------------------------- ### CVXPY Problem Solving Interface Source: https://github.com/cvxgrp/cvxpygen/blob/master/cvxpygen/template/README.html This snippet demonstrates how to use the custom CVXPY solve method to solve an optimization problem. It involves loading a pickled problem object, updating parameters, registering the custom solver, and then solving the problem. The solution can then be inspected. ```Python import pickle from $CDPYTHON.cpg_solver import cpg_solve with open('$CODEDIR/problem.pickle', 'rb') as f: prob = pickle.load(f) prob.param_dict[''].value = prob.register_solve('CPG', cpg_solve) obj = prob.solve(method='CPG') print(prob.var_dict[''].value) ```