tiny_solver/optimizer/
levenberg_marquardt_optimizer.rs

1use log::trace;
2use std::ops::Mul;
3use std::{collections::HashMap, time::Instant};
4
5use faer::sparse::Triplet;
6use faer_ext::IntoNalgebra;
7
8use crate::common::OptimizerOptions;
9use crate::linear;
10use crate::optimizer;
11use crate::parameter_block::ParameterBlock;
12use crate::sparse::LinearSolverType;
13use crate::sparse::SparseLinearSolver;
14
15const DEFAULT_MIN_DIAGONAL: f64 = 1e-6;
16const DEFAULT_MAX_DIAGONAL: f64 = 1e32;
17const DEFAULT_INITIAL_TRUST_REGION_RADIUS: f64 = 1e4;
18
19#[derive(Debug)]
20pub struct LevenbergMarquardtOptimizer {
21    min_diagonal: f64,
22    max_diagonal: f64,
23    initial_trust_region_radius: f64,
24}
25
26impl LevenbergMarquardtOptimizer {
27    pub fn new(min_diagonal: f64, max_diagonal: f64, initial_trust_region_radius: f64) -> Self {
28        Self {
29            min_diagonal,
30            max_diagonal,
31            initial_trust_region_radius,
32        }
33    }
34}
35
36impl Default for LevenbergMarquardtOptimizer {
37    fn default() -> Self {
38        Self {
39            min_diagonal: DEFAULT_MIN_DIAGONAL,
40            max_diagonal: DEFAULT_MAX_DIAGONAL,
41            initial_trust_region_radius: DEFAULT_INITIAL_TRUST_REGION_RADIUS,
42        }
43    }
44}
45
46impl optimizer::Optimizer for LevenbergMarquardtOptimizer {
47    fn optimize(
48        &self,
49        problem: &crate::problem::Problem,
50        initial_values: &std::collections::HashMap<String, nalgebra::DVector<f64>>,
51        optimizer_option: Option<OptimizerOptions>,
52    ) -> Option<HashMap<String, nalgebra::DVector<f64>>> {
53        let mut parameter_blocks: HashMap<String, ParameterBlock> =
54            problem.initialize_parameter_blocks(initial_values);
55
56        let variable_name_to_col_idx_dict =
57            problem.get_variable_name_to_col_idx_dict(&parameter_blocks);
58        let total_variable_dimension = parameter_blocks.values().map(|p| p.tangent_size()).sum();
59
60        let opt_option = optimizer_option.unwrap_or_default();
61        let mut linear_solver: Box<dyn SparseLinearSolver> = match opt_option.linear_solver_type {
62            LinearSolverType::SparseCholesky => Box::new(linear::SparseCholeskySolver::new()),
63            LinearSolverType::SparseQR => Box::new(linear::SparseQRSolver::new()),
64        };
65
66        // On the first iteration, we'll generate a diagonal matrix of the jacobian.
67        // Its shape will be (total_variable_dimension, total_variable_dimension).
68        // With LM, rather than solving A * dx = b for dx, we solve for (A + lambda * diag(A)) dx = b.
69        let mut jacobi_scaling_diagonal: Option<faer::sparse::SparseColMat<usize, f64>> = None;
70
71        let symbolic_structure = problem.build_symbolic_structure(
72            &parameter_blocks,
73            total_variable_dimension,
74            &variable_name_to_col_idx_dict,
75        );
76
77        // Damping parameter (a.k.a lambda / Marquardt parameter)
78        let mut u = 1.0 / self.initial_trust_region_radius;
79
80        let mut last_err;
81        let mut current_error = self.compute_error(problem, &parameter_blocks);
82        for i in 0..opt_option.max_iteration {
83            last_err = current_error;
84
85            let (residuals, mut jac) = problem.compute_residual_and_jacobian(
86                &parameter_blocks,
87                &variable_name_to_col_idx_dict,
88                &symbolic_structure,
89            );
90
91            if i == 0 {
92                // On the first iteration, generate the diagonal of the jacobian.
93                let cols = jac.shape().1;
94                let jacobi_scaling_vec: Vec<Triplet<usize, usize, f64>> = (0..cols)
95                    .map(|c| {
96                        let v = jac.val_of_col(c).iter().map(|&i| i * i).sum::<f64>().sqrt();
97                        Triplet::new(c, c, 1.0 / (1.0 + v))
98                    })
99                    .collect();
100
101                jacobi_scaling_diagonal = Some(
102                    faer::sparse::SparseColMat::<usize, f64>::try_new_from_triplets(
103                        cols,
104                        cols,
105                        &jacobi_scaling_vec,
106                    )
107                    .unwrap(),
108                );
109            }
110
111            // Scale the current jacobian by the diagonal matrix
112            jac = jac * jacobi_scaling_diagonal.as_ref().unwrap();
113
114            // J^T * J = Matrix of shape (total_variable_dimension, total_variable_dimension)
115            let jtj = jac
116                .as_ref()
117                .transpose()
118                .to_col_major()
119                .unwrap()
120                .mul(jac.as_ref());
121
122            // J^T * -r = Matrix of shape (total_variable_dimension, 1)
123            let jtr = jac.as_ref().transpose().mul(-&residuals);
124
125            // Regularize the diagonal of jtj between the min and max diagonal values.
126            let mut jtj_regularized = jtj.clone();
127            for i in 0..total_variable_dimension {
128                jtj_regularized[(i, i)] +=
129                    u * (jtj[(i, i)].max(self.min_diagonal)).min(self.max_diagonal);
130            }
131
132            let start = Instant::now();
133            if let Some(lm_step) = linear_solver.solve_jtj(&jtr, &jtj_regularized) {
134                let duration = start.elapsed();
135                let dx = jacobi_scaling_diagonal.as_ref().unwrap() * &lm_step;
136
137                trace!("Time elapsed in solve Ax=b is: {:?}", duration);
138
139                let dx_na = dx.as_ref().into_nalgebra().column(0).clone_owned();
140
141                let mut new_param_blocks = parameter_blocks.clone();
142
143                self.apply_dx2(
144                    &dx_na,
145                    &mut new_param_blocks,
146                    &variable_name_to_col_idx_dict,
147                );
148
149                // Compute residuals of (x + dx)
150                let new_residuals = problem.compute_residuals(&new_param_blocks, true);
151
152                // rho is the ratio between the actual reduction in error and the reduction
153                // in error if the problem were linear.
154                let actual_residual_change =
155                    residuals.as_ref().squared_norm_l2() - new_residuals.as_ref().squared_norm_l2();
156                trace!("actual_residual_change {}", actual_residual_change);
157                let linear_residual_change: faer::Mat<f64> =
158                    lm_step.transpose().mul(2.0 * &jtr - &jtj * &lm_step);
159                let rho = actual_residual_change / linear_residual_change[(0, 0)];
160
161                if rho > 0.0 {
162                    // The linear model appears to be fitting, so accept (x + dx) as the new x.
163                    parameter_blocks = new_param_blocks;
164
165                    // Increase the trust region by reducing u
166                    let tmp = 2.0 * rho - 1.0;
167                    u *= (1.0_f64 / 3.0).max(1.0 - tmp * tmp * tmp);
168                } else {
169                    // If there's too much divergence, reduce the trust region and try again with the same parameters.
170                    u *= 2.0;
171                    trace!("u {}", u);
172                }
173            } else {
174                log::debug!("solve ax=b failed");
175                return None;
176            }
177
178            current_error = self.compute_error(problem, &parameter_blocks);
179            trace!("iter:{} total err:{}", i, current_error);
180
181            if current_error < opt_option.min_error_threshold {
182                trace!("error too low");
183                break;
184            } else if current_error.is_nan() {
185                log::debug!("solve ax=b failed, current error is nan");
186                return None;
187            }
188
189            if (last_err - current_error).abs() < opt_option.min_abs_error_decrease_threshold {
190                trace!("absolute error decrease low");
191                break;
192            } else if (last_err - current_error).abs() / last_err
193                < opt_option.min_rel_error_decrease_threshold
194            {
195                trace!("relative error decrease low");
196                break;
197            }
198        }
199        let params = parameter_blocks
200            .iter()
201            .map(|(k, v)| (k.to_owned(), v.params.clone()))
202            .collect();
203        Some(params)
204    }
205}