### MATLAB/Octave OCP QP Solver Example Source: https://context7.com/giaf/hpipm/llms.txt Example of setting up and solving an OCP QP problem using the HPIPM MATLAB/Octave interface. This includes defining system dynamics, cost matrices, constraints, configuring solver arguments, and plotting the results. ```APIDOC ## MATLAB/Octave OCP QP Solver ### Description This example demonstrates how to use the HPIPM MATLAB/Octave interface to solve an Optimal Control Problem (OCP) formulated as a Quadratic Program (QP). ### Method N/A (Script Execution) ### Endpoint N/A (Local Execution) ### Parameters N/A ### Request Example ```matlab % Define problem dimensions N = 20; nx = 2; nu = 1; % System dynamics A = [0.9, -0.01; -0.2, 0.3]; B = [0.2; 0.1]; % Cost matrices Q = 100 * eye(nx); S = zeros(nu, nx); R = 1e-3 * eye(nu); q = [1; 1]; % Initial state Jx = eye(nx); x0 = [-1; 3]; % Create dimension object dim = hpipm_ocp_qp_dim(N); dim.set('nx', nx, 0, N); dim.set('nu', nu, 0, N-1); dim.set('nbx', nx, 0); % Create QP problem qp = hpipm_ocp_qp(dim); qp.set('A', A, 0, N-1); qp.set('B', B, 0, N-1); qp.set('Q', Q, 0, N); qp.set('S', S, 0, N-1); qp.set('R', R, 0, N-1); qp.set('q', q, 0, N); qp.set('Jbx', Jx, 0); qp.set('lbx', x0, 0); qp.set('ubx', x0, 0); % Create solution object sol = hpipm_ocp_qp_sol(dim); % Configure solver arg = hpipm_ocp_qp_solver_arg(dim, 'speed'); arg.set('mu0', 1e4); arg.set('iter_max', 20); arg.set('tol_stat', 1e-4); arg.set('tol_eq', 1e-5); arg.set('tol_ineq', 1e-5); arg.set('tol_comp', 1e-5); arg.set('reg_prim', 1e-12); % Create and run solver solver = hpipm_ocp_qp_solver(dim, arg); solver.solve(qp, sol); % Get statistics status = solver.get('status'); iter = solver.get('iter'); res_stat = solver.get('max_res_stat'); fprintf('Status: %d, Iterations: %d\n', status, iter); % Extract solution x = sol.get('x', 0, N); x = reshape(x, nx, N+1); u = sol.get('u', 0, N-1); u = reshape(u, nu, N); % Plot results figure(); subplot(2,1,1); plot(0:N, x); title('State trajectory'); ylabel('x'); grid on; subplot(2,1,2); stairs(1:N, u'); title('Control inputs'); ylabel('u'); xlabel('Stage'); grid on; ``` ### Response #### Success Response (200) N/A (Script Execution) #### Response Example ``` Status: 0, Iterations: 15 ``` ``` -------------------------------- ### C API: OCP QP Setup and Solve Source: https://context7.com/giaf/hpipm/llms.txt Demonstrates the complete workflow for setting up an OCP QP, configuring the IPM solver, executing the solve, and extracting the solution. ```APIDOC ## C API: OCP QP Setup and Solve ### Description This endpoint/workflow describes how to initialize dimensions, allocate memory for the QP structure, set problem data (A, B, Q, R matrices), configure IPM solver arguments, and execute the solver. ### Method C Function Call ### Endpoint `d_ocp_qp_ipm_solve` ### Parameters #### Request Body - **N** (int) - Required - Horizon length - **nx** (int[]) - Required - Number of states per stage - **nu** (int[]) - Required - Number of inputs per stage - **A, B, Q, R** (double[]) - Required - QP problem matrices ### Response #### Success Response (0) - **status** (int) - Returns 0 on successful convergence - **qp_sol** (struct) - Contains the computed optimal control sequence and state trajectory ### Response Example { "status": 0, "iter": 12, "u": [0.5], "x": [1.0, 0.0] } ``` -------------------------------- ### Python OCP QP Solver Example Source: https://context7.com/giaf/hpipm/llms.txt Example of creating and solving an OCP QP problem using the HPIPM Python interface. This includes defining the problem dimensions, setting up the QP problem, configuring the solver, and retrieving the solution and status. ```APIDOC ## Python OCP QP Solver ### Description This example demonstrates how to use the HPIPM Python interface to solve an Optimal Control Problem (OCP) formulated as a Quadratic Program (QP). ### Method N/A (Script Execution) ### Endpoint N/A (Local Execution) ### Parameters N/A ### Request Example ```python # Assuming 'hpipm' library is installed and imported as 'hpipm_ocp_qp' # and 'numpy' is imported as 'np' # Define problem dimensions dim = hpipm_ocp_qp_dim(N) dim.set('nx', nx, 0, N) dim.set('nu', nu, 0, N-1) # Create QP problem object qp = hpipm_ocp_qp(dim) # ... (set system dynamics, costs, constraints, etc.) ... # Create solution object sol = hpipm_ocp_qp_sol(dim) # Configure solver arguments arg = hpipm_ocp_qp_solver_arg(dim, 'speed') arg.set('mu0', 1e1) arg.set('iter_max', 30) # Create and run the solver solver = hpipm_ocp_qp_solver(dim, arg) solver.solve(qp, sol) # Retrieve solution and status xN = sol.get('x', N) status = solver.get('status') print(f'Solver status: {status}') ``` ### Response #### Success Response (200) N/A (Script Execution) #### Response Example ``` Solver status: 0 ``` ``` -------------------------------- ### Setup and Solve OCP QP with HPIPM C API Source: https://context7.com/giaf/hpipm/llms.txt Demonstrates the complete workflow for setting up and solving an OCP QP using the HPIPM C API. This includes memory allocation for dimensions, QP, solution, arguments, and workspace, followed by solving the QP and extracting results like status, iterations, residuals, and the feedback gain. ```c #include #include #include #include #include #include int main() { int N = 5; // horizon int nx[] = {2, 2, 2, 2, 2, 2}; // states at each stage int nu[] = {1, 1, 1, 1, 1, 0}; // inputs at each stage int nbx[] = {2, 0, 0, 0, 0, 0}; // state bounds int nbu[] = {0, 0, 0, 0, 0, 0}; // input bounds int ng[] = {0, 0, 0, 0, 0, 0}; // general constraints int ns[] = {0, 0, 0, 0, 0, 0}; // soft constraints // Allocate dimension structure hpipm_size_t dim_size = d_ocp_qp_dim_memsize(N); void *dim_mem = malloc(dim_size); struct d_ocp_qp_dim dim; d_ocp_qp_dim_create(N, &dim, dim_mem); d_ocp_qp_dim_set_all(nx, nu, nbx, nbu, ng, ns, &dim); // Allocate QP structure hpipm_size_t qp_size = d_ocp_qp_memsize(&dim); void *qp_mem = malloc(qp_size); struct d_ocp_qp qp; d_ocp_qp_create(&dim, &qp, qp_mem); // Set QP data (example: set dynamics matrix A at stage 0) double A[] = {1.0, 0.0, 1.0, 1.0}; // column-major d_ocp_qp_set_A(0, A, &qp); double B[] = {0.0, 1.0}; d_ocp_qp_set_B(0, B, &qp); double Q[] = {1.0, 0.0, 0.0, 1.0}; d_ocp_qp_set_Q(0, Q, &qp); double R[] = {1.0}; d_ocp_qp_set_R(0, R, &qp); // Allocate solution structure hpipm_size_t sol_size = d_ocp_qp_sol_memsize(&dim); void *sol_mem = malloc(sol_size); struct d_ocp_qp_sol qp_sol; d_ocp_qp_sol_create(&dim, &qp_sol, sol_mem); // Configure IPM arguments hpipm_size_t arg_size = d_ocp_qp_ipm_arg_memsize(&dim); void *arg_mem = malloc(arg_size); struct d_ocp_qp_ipm_arg arg; d_ocp_qp_ipm_arg_create(&dim, &arg, arg_mem); d_ocp_qp_ipm_arg_set_default(SPEED, &arg); // mode: SPEED, BALANCE, ROBUST double mu0 = 1e4; int iter_max = 30; double tol_stat = 1e-4; d_ocp_qp_ipm_arg_set_mu0(&mu0, &arg); d_ocp_qp_ipm_arg_set_iter_max(&iter_max, &arg); d_ocp_qp_ipm_arg_set_tol_stat(&tol_stat, &arg); // Allocate workspace hpipm_size_t ws_size = d_ocp_qp_ipm_ws_memsize(&dim, &arg); void *ws_mem = malloc(ws_size); struct d_ocp_qp_ipm_ws workspace; d_ocp_qp_ipm_ws_create(&dim, &arg, &workspace, ws_mem); // Solve QP d_ocp_qp_ipm_solve(&qp, &qp_sol, &arg, &workspace); // Get solver status and statistics int status; d_ocp_qp_ipm_get_status(&workspace, &status); int iter; d_ocp_qp_ipm_get_iter(&workspace, &iter); double res_stat, res_eq; d_ocp_qp_ipm_get_max_res_stat(&workspace, &res_stat); d_ocp_qp_ipm_get_max_res_eq(&workspace, &res_eq); printf("Status: %d, Iterations: %d\n", status, iter); printf("Residuals - stat: %e, eq: %e\n", res_stat, res_eq); // Extract solution double u[1], x[2]; d_ocp_qp_sol_get_u(0, &qp_sol, u); d_ocp_qp_sol_get_x(0, &qp_sol, x); printf("u[0] = %f, x[0] = [%f, %f]\n", u[0], x[0], x[1]); // Get Riccati feedback gain K (u = K*x + k) double K[2]; // nu x nx d_ocp_qp_ipm_get_ric_K(&qp, &arg, &workspace, 0, K); printf("Feedback gain K = [%f, %f]\n", K[0], K[1]); // Free memory free(dim_mem); free(qp_mem); free(sol_mem); free(arg_mem); free(ws_mem); return status; } ``` -------------------------------- ### Configure HPIPM Library Build and Installation Source: https://github.com/giaf/hpipm/blob/master/CMakeLists.txt This snippet collects source files for tree-based OCP QP solvers, auxiliary functions, and simulation cores. It then defines the library target, sets include directories, links against BLASFEO, and specifies installation rules for the library and headers. ```cmake file(GLOB TREE_OCP_QP_SRC ${PROJECT_SOURCE_DIR}/tree_ocp_qp/*.c) file(GLOB AUXILIARY_SRC ${PROJECT_SOURCE_DIR}/auxiliary/*.c) file(GLOB SIM_SRC ${PROJECT_SOURCE_DIR}/sim_core/*.c) file(GLOB INTERFACES_SRC ${PROJECT_SOURCE_DIR}/interfaces/c/*.c) set(HPIPM_SRC ${TREE_OCP_QP_SRC} ${AUXILIARY_SRC} ${SIM_SRC} ${INTERFACES_SRC}) add_library(hpipm ${HPIPM_SRC}) target_include_directories(hpipm PUBLIC $ $) target_link_libraries(hpipm blasfeo) install(TARGETS hpipm EXPORT hpipmConfig LIBRARY DESTINATION lib ARCHIVE DESTINATION lib RUNTIME DESTINATION bin) install(EXPORT hpipmConfig DESTINATION cmake) file(GLOB_RECURSE HPIPM_HEADERS "include/*.h") install(FILES ${HPIPM_HEADERS} DESTINATION ${HPIPM_HEADERS_INSTALLATION_DIRECTORY}) ``` -------------------------------- ### Setup OCP QP Dimensions (Python) Source: https://context7.com/giaf/hpipm/llms.txt Defines the dimensions for an optimal control problem (OCP) QP using the `hpipm_ocp_qp_dim` class. It specifies the prediction horizon, number of states, inputs, and constraints at each stage. This setup is crucial before defining the QP problem itself. ```python from hpipm_python import * import numpy as np # Define problem horizon and dimensions N = 5 # prediction horizon nx = 2 # number of states nu = 1 # number of inputs bx = 2 # number of box constraints on states # Create dimension object for OCP QP dim = hpipm_ocp_qp_dim(N) # Set dimensions for all stages dim.set('nx', nx, 0, N) # states at stages 0 to N dim.set('nu', nu, 0, N-1) # inputs at stages 0 to N-1 dim.set('nbx', bx, 0) # state bounds at stage 0 (initial condition) dim.set('nbx', bx, N) # state bounds at terminal stage dim.set('nbxe', nx, 0) # equality constraints on initial state # Print dimension structure (optional) dim.print_C_struct() # Codegen for C usage (optional) dim.codegen('ocp_qp_data.c', 'w') ``` -------------------------------- ### Solve OCP QCQP with HPIPM (Python) Source: https://context7.com/giaf/hpipm/llms.txt This example demonstrates solving an Optimal Control Problem (OCP) with Quadratically-Constrained Quadratic Programming (QCQP) using HPIPM. It involves setting up dimensions for a finite horizon, defining system dynamics (A, B), cost matrices (Q, R), and initial conditions. It also includes defining and applying quadratic constraints at the terminal stage. ```python from hpipm_python import * import numpy as np # Problem setup N = 5 nx = 2 nu = 1 nq = 1 # number of quadratic constraints # Create QCQP dimension dim = hpipm_ocp_qcqp_dim(N) dim.set('nx', nx, 0, N) dim.set('nu', nu, 0, N-1) dim.set('nbx', nx, 0) dim.set('nq', nq, N) # quadratic constraint at terminal stage # System dynamics A = np.array([[1.0, 1.0], [0.0, 1.0]]) B = np.array([[0.0], [1.0]]) # Cost matrices Q = np.eye(nx) R = np.eye(nu) q = np.array([[1.0], [1.0]]) # Initial state constraint Jx = np.eye(nx) x0 = np.array([[1.0], [1.0]]) # Quadratic constraint: 0.5 * x' * Qq * x <= uq Qq = 2.0 * np.eye(nx) # quadratic constraint matrix uq = np.array([0.1]) # quadratic constraint upper bound # Create QCQP problem qp = hpipm_ocp_qcqp(dim) qp.set('A', A, 0, N-1) qp.set('B', B, 0, N-1) qp.set('Q', Q, 0, N) qp.set('R', R, 0, N-1) qp.set('q', q, 0, N) qp.set('Jx', Jx, 0) qp.set('lx', x0, 0) qp.set('ux', x0, 0) qp.set('Qq', Qq, N) # quadratic constraint Hessian qp.set('uq', uq, N) # quadratic constraint bound ``` -------------------------------- ### Initialize Solver Argument in Python Source: https://context7.com/giaf/hpipm/llms.txt Initializes the solver argument for the HPIPM OCP QP solver in 'balance' mode. This is a common setup step when configuring the solver for general use within an MPC context. ```python arg = hpipm_ocp_qp_solver_arg(dim, 'balance') ``` -------------------------------- ### Solve Dense QP with HPIPM (Python) Source: https://context7.com/giaf/hpipm/llms.txt This snippet demonstrates how to set up and solve a dense Quadratic Program (QP) using the HPIPM Python interface. It covers defining problem dimensions, cost matrices (H, g), and constraints (C, d, A, b), configuring solver arguments, and extracting the optimal solution vector 'v' and dual variables. ```python from hpipm_python import * import numpy as np # Problem dimensions nv = 3 # number of decision variables ne = 1 # number of equality constraints nb = 0 # number of box constraints ng = 3 # number of general inequality constraints # Create dimension object dim = hpipm_dense_qp_dim() dim.set('nv', nv) dim.set('ne', ne) dim.set('nb', nb) dim.set('ng', ng) # Define QP data: min 0.5*v'*H*v + g'*v # subject to: A*v = b, C*v <= d M = np.array([[1.0, 2.0, 0.0], [-8.0, 3.0, 2.0], [0.0, 1.0, 1.0]]) H = np.dot(M.T, M) g = np.dot(np.array([3.0, 2.0, 3.0]), M) # Inequality constraints: C*v <= d C = np.array([[1.0, 2.0, 1.0], [2.0, 0.0, 1.0], [-1.0, 2.0, -1.0]]) d = np.array([3.0, 2.0, -2.0]) # Equality constraint: A*v = b A = np.array([[1.0, 1.0, 1.0]]) b = np.array([1.0]) # Create and populate QP qp = hpipm_dense_qp(dim) qp.set('H', H) qp.set('g', g) qp.set('C', C) qp.set('ug', d) # upper bound on C*v qp.set('lg', d) # lower bound (set equal for one-sided) qp.set('lg_mask', np.zeros(3)) # disable lower bound with mask qp.set('A', A) qp.set('b', b) # Create solution object qp_sol = hpipm_dense_qp_sol(dim) # Configure and create solver arg = hpipm_dense_qp_solver_arg(dim, 'speed') arg.set('mu0', 1e4) arg.set('iter_max', 30) arg.set('tol_stat', 1e-4) arg.set('tol_eq', 1e-5) arg.set('tol_ineq', 1e-5) arg.set('tol_comp', 1e-5) solver = hpipm_dense_qp_solver(dim, arg) # Solve solver.solve(qp, qp_sol) # Extract solution v = qp_sol.get('v') # optimal decision variable pi = qp_sol.get('pi') # equality constraint multiplier lam_lg = qp_sol.get('lam_lg') # lower inequality multiplier lam_ug = qp_sol.get('lam_ug') # upper inequality multiplier print(f'Optimal v = {v.flatten()}') print(f'Equality multiplier pi = {pi.flatten()}') # Check solver status status = solver.get('status') if status == 0: print('QP solved successfully!') ``` -------------------------------- ### Solve OCP QCQP in Python with HPIPM Source: https://context7.com/giaf/hpipm/llms.txt This Python snippet demonstrates how to set up and solve an Optimal Control Problem (OCP) with Quadratic Constraints (QCQP) using the HPIPM library. It involves creating solver arguments, configuring solver options like maximum iterations and initial regularization, and then solving the problem. The output includes checking constraint satisfaction and retrieving the solver status. ```python qp_sol = hpipm_ocp_qcqp_sol(dim) arg = hpipm_ocp_qcqp_solver_arg(dim, 'speed') arg.set('mu0', 1e1) arg.set('iter_max', 30) solver = hpipm_ocp_qcqp_solver(dim, arg) solver.solve(qp, qp_sol) xN = qp_sol.get('x', N) quad_value = 0.5 * np.dot(xN.T, np.dot(Qq, xN)) print(f'Quadratic constraint value: {quad_value[0,0]:.6f} <= {uq[0]}') status = solver.get('status') print(f'Solver status: {status}') ``` -------------------------------- ### Configure OCP QP Solver (Python) Source: https://context7.com/giaf/hpipm/llms.txt Configures the parameters for the HPIPM OCP QP solver using the `hpipm_ocp_qp_solver_arg` class. This allows customization of tolerances, maximum iterations, and algorithm modes (e.g., 'speed', 'balance', 'robust') to optimize performance and accuracy. ```python from hpipm_python import * # Assuming dim is already created dim = hpipm_ocp_qp_dim(5) dim.set('nx', 2, 0, 5) dim.set('nu', 1, 0, 4) # Solver modes: 'speed_abs', 'speed', 'balance', 'robust' mode = 'speed' # Create solver arguments with default settings for mode arg = hpipm_ocp_qp_solver_arg(dim, mode) # Configure solver parameters arg.set('mu0', 1e4) # initial barrier parameter arg.set('iter_max', 30) # maximum IPM iterations arg.set('tol_stat', 1e-4) # stationarity tolerance arg.set('tol_eq', 1e-5) # equality constraint tolerance arg.set('tol_ineq', 1e-5) # inequality constraint tolerance arg.set('tol_comp', 1e-5) # complementarity tolerance arg.set('reg_prim', 1e-12) # primal regularization arg.set('warm_start', 0) # 0: cold start, 1: warm start primal # For predictor-corrector algorithm arg.set('pred_corr', 1) # enable Mehrotra predictor-corrector ``` -------------------------------- ### Solve OCP QP and Extract Solution (Python) Source: https://context7.com/giaf/hpipm/llms.txt Solves the configured optimal control problem (OCP) QP using the `hpipm_ocp_qp_solver` class and provides methods to retrieve the optimal states, inputs, and solver statistics. This step executes the interior point method to find the optimal trajectory. ```python from hpipm_python import * import numpy as np import time # Setup problem (abbreviated) N = 5 nx, nu = 2, 1 dim = hpipm_ocp_qp_dim(N) dim.set('nx', nx, 0, N) dim.set('nu', nu, 0, N-1) dim.set('nbx', nx, 0) dim.set('nbxe', nx, 0) # Define and populate QP (see previous examples) qp = hpipm_ocp_qp(dim) # ... (QP definition and solver argument setup would go here) ... # Create solver instance # solver = hpipm_ocp_qp_solver(dim, arg) # Solve the QP # start_time = time.time() # solver.solve(qp) # end_time = time.time() # Extract solution (example) # opt_x = qp.get('x', 0) # opt_u = qp.get('u', 0) # Print solver statistics # print(f"Solver finished in {end_time - start_time:.4f} seconds") # print(f"Number of iterations: {solver.get('iter')}") ``` -------------------------------- ### Solve QP and Extract Results with HPIPM (Python) Source: https://context7.com/giaf/hpipm/llms.txt This snippet shows how to solve a Quadratic Program (QP) using HPIPM and then extract various results, including the optimal trajectory, dual variables, and solver status. It covers creating the solution object, solver arguments, and the solver itself, followed by calling the solve method and retrieving information like solve time, status, iterations, and residuals. ```python # ... set A, B, Q, R, etc. # Create solution object qp_sol = hpipm_ocp_qp_sol(dim) # Create solver arguments arg = hpipm_ocp_qp_solver_arg(dim, 'speed') arg.set('iter_max', 30) arg.set('tol_stat', 1e-4) # Create solver solver = hpipm_ocp_qp_solver(dim, arg) # Solve QP start_time = time.time() solver.solve(qp, qp_sol) solve_time = time.time() - start_time print(f'Solve time: {solve_time:.6e} s') # Get solver status status = solver.get('status') # 0=success, 1=max_iter, 2=min_step, 3=nan iters = solver.get('iter') # number of iterations res_stat = solver.get('max_res_stat') # stationarity residual res_eq = solver.get('max_res_eq') # equality residual res_ineq = solver.get('max_res_ineq') # inequality residual res_comp = solver.get('max_res_comp') # complementarity residual print(f'Status: {status}, Iterations: {iters}') print(f'Residuals - stat: {res_stat:.2e}, eq: {res_eq:.2e}, ineq: {res_ineq:.2e}') # Extract optimal trajectory u = qp_sol.get('u', 0, N) # inputs u[0] to u[N] for i in range(N): x = qp_sol.get('x', i) print(f'Stage {i}: x = {x.flatten()}, u = {u[i].flatten()}') # Terminal state x_N = qp_sol.get('x', N) print(f'Stage {N}: x = {x_N.flatten()}') # Get dual variables (Lagrange multipliers) for i in range(N): pi = qp_sol.get('pi', i) # dynamics multiplier lam_lbx = qp_sol.get('lam_lbx', i) # lower bound multiplier lam_ubx = qp_sol.get('lam_ubx', i) # upper bound multiplier ``` -------------------------------- ### Solve OCP QP in MATLAB/Octave with HPIPM Source: https://context7.com/giaf/hpipm/llms.txt This MATLAB/Octave snippet illustrates how to define and solve an Optimal Control Problem (OCP) with Quadratic Programming (QP) using the HPIPM library. It covers setting up system dynamics, cost matrices, initial conditions, and problem dimensions. The code then configures the solver with specific arguments for speed and numerical tolerances, solves the QP problem, and extracts solution statistics and trajectories for plotting. ```matlab % Define problem dimensions N = 20; nx = 2; nu = 1; % System dynamics A = [0.9, -0.01; -0.2, 0.3]; B = [0.2; 0.1]; % Cost matrices Q = 100 * eye(nx); S = zeros(nu, nx); R = 1e-3 * eye(nu); q = [1; 1]; % Initial state Jx = eye(nx); x0 = [-1; 3]; % Create dimension object dim = hpipm_ocp_qp_dim(N); dim.set('nx', nx, 0, N); dim.set('nu', nu, 0, N-1); dim.set('nbx', nx, 0); % Create QP problem qp = hpipm_ocp_qp(dim); qp.set('A', A, 0, N-1); qp.set('B', B, 0, N-1); qp.set('Q', Q, 0, N); qp.set('S', S, 0, N-1); qp.set('R', R, 0, N-1); qp.set('q', q, 0, N); qp.set('Jbx', Jx, 0); qp.set('lbx', x0, 0); qp.set('ubx', x0, 0); % Create solution object sol = hpipm_ocp_qp_sol(dim); % Configure solver arg = hpipm_ocp_qp_solver_arg(dim, 'speed'); arg.set('mu0', 1e4); arg.set('iter_max', 20); arg.set('tol_stat', 1e-4); arg.set('tol_eq', 1e-5); arg.set('tol_ineq', 1e-5); arg.set('tol_comp', 1e-5); arg.set('reg_prim', 1e-12); % Create and run solver solver = hpipm_ocp_qp_solver(dim, arg); solver.solve(qp, sol); % Get statistics status = solver.get('status'); iter = solver.get('iter'); res_stat = solver.get('max_res_stat'); fprintf('Status: %d, Iterations: %d\n', status, iter); % Extract solution x = sol.get('x', 0, N); x = reshape(x, nx, N+1); u = sol.get('u', 0, N-1); u = reshape(u, nu, N); % Plot results figure(); subplot(2,1,1); plot(0:N, x); title('State trajectory'); ylabel('x'); grid on; subplot(2,1,2); stairs(1:N, u'); title('Control inputs'); ylabel('u'); xlabel('Stage'); grid on; ``` -------------------------------- ### Define OCP QP Problem (Python) Source: https://context7.com/giaf/hpipm/llms.txt Defines the quadratic program data for an optimal control problem (OCP) using the `hpipm_ocp_qp` class. This includes setting system dynamics (A, B matrices), cost matrices (Q, R, S), constraint bounds, and initial conditions. ```python from hpipm_python import * import numpy as np # Problem dimensions N = 5 nx = 2 nu = 1 # Create dimension object dim = hpipm_ocp_qp_dim(N) dim.set('nx', nx, 0, N) dim.set('nu', nu, 0, N-1) dim.set('nbx', nx, 0) dim.set('nbxe', nx, 0) # Define system dynamics: x_{k+1} = A*x_k + B*u_k A = np.array([[1.0, 1.0], [0.0, 1.0]]) B = np.array([[0.0], [1.0]]) # Define cost matrices: min sum_{k=0}^{N} (x'Qx + u'Ru + q'x) Q = np.array([[1.0, 0.0], [0.0, 1.0]]) R = np.array([[1.0]]) S = np.array([[0.0, 0.0]]) # cross term (nu x nx) q = np.array([[1.0], [1.0]]) # Initial condition constraint Jx = np.array([[1.0, 0.0], [0.0, 1.0]]) # selection matrix x0 = np.array([[1.0], [1.0]]) # initial state # Create QP problem qp = hpipm_ocp_qp(dim) # Set dynamics for stages 0 to N-1 qp.set('A', A, 0, N-1) qp.set('B', B, 0, N-1) # Set cost for all stages qp.set('Q', Q, 0, N) qp.set('R', R, 0, N-1) qp.set('S', S, 0, N-1) qp.set('q', q, 0, N) # Set initial state constraint (lx <= Jx*x <= ux) qp.set('Jx', Jx, 0) qp.set('lx', x0, 0) qp.set('ux', x0, 0) # Print QP structure qp.print_C_struct() ``` -------------------------------- ### Configuring HPIPM Solver Modes in Python Source: https://context7.com/giaf/hpipm/llms.txt Shows how to select different solver modes in Python for HPIPM, allowing users to balance between speed and robustness. The available modes include 'speed_abs', 'speed', 'balance', and 'robust', each suited for different problem characteristics. ```python # Available modes # 'speed_abs' - Focus on speed, absolute IPM formulation # 'speed' - Focus on speed, relative IPM formulation (default) # 'balance' - Balanced mode, relative IPM formulation # 'robust' - Focus on robustness, relative IPM formulation # Speed mode for well-conditioned problems arg = hpipm_ocp_qp_solver_arg(dim, 'speed') # Robust mode for ill-conditioned problems arg = hpipm_ocp_qp_solver_arg(dim, 'robust') ``` -------------------------------- ### HPIPM Solver Status Check in Python Source: https://context7.com/giaf/hpipm/llms.txt Illustrates how to check the solver status in Python after an optimization run. It maps the integer status codes to human-readable messages, providing feedback on the success or failure of the solver. ```python # Python status check status = solver.get('status') if status == 0: print("QP solved successfully") elif status == 1: print("Maximum iterations reached") elif status == 2: print("Minimum step length reached") elif status == 3: print("NaN in solution detected") else: print(f"Unknown status: {status}") ``` -------------------------------- ### Set Include Directories (CMake) Source: https://github.com/giaf/hpipm/blob/master/test_problems/CMakeLists.txt This CMake command specifies the include directories for the HPIPM executables. It ensures that the compiler can find header files from HPIPM and BLASFEO. The PRIVATE keyword indicates that these directories are only used for compiling the target. ```cmake target_include_directories(d_cond PRIVATE "${HPIPM_INCLUDE_DIR}" "${BLASFEO_INCLUDE_DIR}") target_include_directories(d_part_cond PRIVATE "${HPIPM_INCLUDE_DIR}" "${BLASFEO_INCLUDE_DIR}") target_include_directories(d_dense_qp PRIVATE "${HPIPM_INCLUDE_DIR}" "${BLASFEO_INCLUDE_DIR}") target_include_directories(d_ocp_qp PRIVATE "${HPIPM_INCLUDE_DIR}" "${BLASFEO_INCLUDE_DIR}") target_include_directories(d_tree_ocp_qp PRIVATE "${HPIPM_INCLUDE_DIR}" "${BLASFEO_INCLUDE_DIR}") ``` -------------------------------- ### Define Executable Targets (CMake) Source: https://github.com/giaf/hpipm/blob/master/test_problems/CMakeLists.txt This snippet defines the executable targets for different components of the HPIPM project. It specifies the source files required for each executable. These commands are typically found in a CMakeLists.txt file. ```cmake add_executable(d_cond test_d_cond.c d_tools.c) add_executable(d_part_cond test_d_part_cond.c d_tools.c) add_executable(d_dense_qp test_d_dense.c) add_executable(d_ocp_qp test_d_ocp.c d_tools.c) add_executable(d_tree_ocp_qp test_d_tree_ocp.c d_tools.c) ``` -------------------------------- ### Link Libraries (CMake) Source: https://github.com/giaf/hpipm/blob/master/test_problems/CMakeLists.txt This CMake snippet links the necessary libraries to the HPIPM executables. It conditionally links the math library ('m') based on the C compiler ID. It always links against 'hpipm' and 'blasfeo'. ```cmake if(CMAKE_C_COMPILER_ID MATCHES MSVC) # no explicit math library target_link_libraries(d_cond hpipm blasfeo) target_link_libraries(d_part_cond hpipm blasfeo) target_link_libraries(d_dense_qp hpipm blasfeo) target_link_libraries(d_ocp_qp hpipm blasfeo) target_link_libraries(d_tree_ocp_qp hpipm blasfeo) else() # add explicit math library target_link_libraries(d_cond hpipm blasfeo m) target_link_libraries(d_part_cond hpipm blasfeo m) target_link_libraries(d_dense_qp hpipm blasfeo m) target_link_libraries(d_ocp_qp hpipm blasfeo m) target_link_libraries(d_tree_ocp_qp hpipm blasfeo m) endif() ``` -------------------------------- ### Solver Status Codes Source: https://context7.com/giaf/hpipm/llms.txt Reference for HPIPM solver status codes returned after a solve operation. ```APIDOC ## Solver Status Codes ### Description Provides the mapping of integer status codes returned by the solver to their respective meanings. ### Status Codes - **0 (SUCCESS)** - Solution found within tolerance - **1 (MAX_ITER)** - Maximum iterations reached - **2 (MIN_STEP)** - Minimum step length reached - **3 (NAN_SOL)** - NaN detected in solution - **4 (INCONS_EQ)** - Inconsistent equality constraints ``` -------------------------------- ### HPIPM Solver Status Codes in C Source: https://context7.com/giaf/hpipm/llms.txt Defines the possible status codes returned by HPIPM solvers, indicating the outcome of the optimization process. These codes should be checked after each solve call to understand if a solution was found, if maximum iterations were reached, or if other issues occurred. ```c // C enum from hpipm_common.h enum hpipm_status { SUCCESS, // 0: Solution found within tolerance MAX_ITER, // 1: Maximum iterations reached MIN_STEP, // 2: Minimum step length reached NAN_SOL, // 3: NaN detected in solution INCONS_EQ, // 4: Inconsistent equality constraints }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.