Skip to main content

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