This example shows how to define a simple unconstrained optimization problem using ordinary C++ functions.
This example shows how to define a simple unconstrained optimization problem using ordinary C++ functions.
The problem is the unconstrained minimization of the Rosenbrock function:
\[ \begin{aligned}
& \underset{x, y}{\text{minimize}} && (a - x)^2 + b (y - x^2)^2 \\
\end{aligned} \]
Only the inner solver (Inner solvers) is used, without an augmented Lagrangian outer solver.
1#include <alpaqa/example-util.hpp>
15 real_t a = 2, b = 100;
18 real_t eval_f(crvec xy)
const {
19 auto x =
xy(0), y =
xy(1);
20 return sq(a - x) + b *
sq(y -
sq(x));
24 void eval_grad_f(crvec xy, rvec grad)
const {
25 auto x =
xy(0), y =
xy(1);
26 grad(0) = (2 * x) - (2 * a) - (4 * b * x * y) + (4 * b * x *
sq(x));
27 grad(1) = 2 * b * (y -
sq(x));
31 static real_t
sq(real_t x) {
return x * x; }
39 RosenbrockProblem problem;
49 Solver::Params panocparam;
50 panocparam.max_iter = 500;
51 panocparam.print_interval = 1;
53 Direction::AcceleratorParams lbfgsparam;
54 lbfgsparam.memory = 2;
57 Solver solver{panocparam, lbfgsparam};
63 auto stats = solver(counted_problem, {.tolerance = 1e-8}, x);
67 std::cout <<
'\n' << *counted_problem.evaluations <<
'\n';
68 std::cout <<
"status: " << stats.status <<
'\n'
69 <<
"f = " << problem.eval_f(x) <<
'\n'
70 <<
"iterations: " << stats.iterations <<
'\n'
71 <<
"ε = " << stats.ε <<
'\n'
73 << std::chrono::duration<double>{stats.elapsed_time}.count()
75 <<
"x = " << x.transpose() <<
'\n'
76 <<
"avg τ = " << (stats.sum_τ / stats.count_τ) <<
'\n'
77 <<
"L-BFGS rejected = " << stats.lbfgs_rejected <<
'\n'
78 <<
"L-BFGS failures = " << stats.lbfgs_failures <<
'\n'
79 <<
"Line search failures = " << stats.linesearch_failures <<
'\n'
int main(int argc, const char *argv[])
Implements common problem functions for minimization problems without constraints.
#define USING_ALPAQA_CONFIG(Conf)
auto problem_with_counters_ref(Problem &p)
Wraps the given problem into a ProblemWithCounters and keeps track of how many times each function is...