-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.cpp
More file actions
65 lines (55 loc) · 2.21 KB
/
Copy pathexample.cpp
File metadata and controls
65 lines (55 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* @brief Example usage of the C++ API of `marinholab-solvers-osqp`.
*
* Builds a small quadratic program and solves it with
* `marinholab::solvers::osqp::Solver`, mirroring the Python quickstart in the
* README.
*
* Build and run it with the `BUILD_EXAMPLES` option (OFF by default so the
* normal `pip install .` build is unaffected):
*
* cmake -B build -GNinja -DBUILD_EXAMPLES=ON
* cmake --build build
* ./build/example/example_osqp
*/
#include <iostream>
#include <marinholab/solvers/osqp.h>
namespace osqp = marinholab::solvers::osqp;
int main()
{
// 1. Configure the solver. Only a couple of fields are set here; the rest
// keep their defaults (which mirror OSQP's own defaults for a standard
// double-precision, direct-solver build; see osqp_set_default_settings()).
osqp::Configuration config;
config.eps_abs = 1.0e-9; // tighter absolute tolerance
config.eps_rel = 1.0e-9; // tighter relative tolerance
osqp::Solver solver(config);
// 2. The problem:
//
// min_x 0.5 * x' H x + f' x
// s.t. A x <= b
// Aeq x = beq
//
// H = I, f = [-1, -1], x[0] <= 0.2, plus one trivially-satisfied equality.
Eigen::MatrixXd H = Eigen::MatrixXd::Identity(2, 2);
Eigen::VectorXd f(2);
f << -1.0, -1.0;
Eigen::MatrixXd A(1, 2);
A << 1.0, 0.0;
Eigen::VectorXd b(1);
b << 0.2;
Eigen::MatrixXd Aeq = Eigen::MatrixXd::Zero(1, 2);
Eigen::VectorXd beq = Eigen::VectorXd::Zero(1);
// 3. Solve. The Solver keeps the underlying OSQP problem, so repeated
// calls on the same instance are warm-started by default
// (`Configuration.use_hotstart = true` / `warm_starting = 1`).
Eigen::VectorXd x = solver.solve_quadratic_program(H, f, A, b, Aeq, beq);
// 4. Inspect the result and the solution quality. `.transpose()` makes
// Eigen print the (column) vector as a single horizontal line.
std::cout << "x = " << x.transpose() << "\n";
const osqp::Solver::Info info = solver.get_info();
std::cout << "obj_val = " << info.obj_val << "\n";
std::cout << "prim_res = " << info.prim_res << "\n";
std::cout << "dual_res = " << info.dual_res << "\n";
return 0;
}