quadratic/
quadratic.rs

1use nalgebra::{DMatrix, DVector};
2use optimization_solvers::{FuncEvalMultivariate, LineSearchSolver, MoreThuente, Tracer, BFGS};
3
4fn main() {
5    // Setting up log verbosity and _
6    std::env::set_var("RUST_LOG", "debug");
7    let _ = Tracer::default().with_normal_stdout_layer().build();
8
9    // Setting up the oracle
10    let matrix = DMatrix::from_vec(2, 2, vec![1., 0., 0., 1.]);
11    let f_and_g = |x: &DVector<f64>| -> FuncEvalMultivariate {
12        let f = x.dot(&(&matrix * x));
13        let g = 2. * &matrix * x;
14        FuncEvalMultivariate::new(f, g)
15    };
16
17    // Setting up the line search
18    let mut ls = MoreThuente::default();
19    // Setting up the main solver, with its parameters and the initial guess
20    let tol = 1e-6;
21    let x0 = DVector::from_vec(vec![1., 1.]);
22    let mut solver = BFGS::new(tol, x0);
23
24    // Running the solver
25    let max_iter_solver = 100;
26    let max_iter_line_search = 10;
27    let callback = None;
28    solver
29        .minimize(
30            &mut ls,
31            f_and_g,
32            max_iter_solver,
33            max_iter_line_search,
34            callback,
35        )
36        .unwrap();
37    // Printing the result
38    let x = solver.x();
39    let eval = f_and_g(x);
40    println!("x: {:?}", x);
41    println!("f(x): {}", eval.f());
42    println!("g(x): {:?}", eval.g());
43    assert_eq!(eval.f(), &0.0);
44}