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 = problem.compute_cost(&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                // rho is the ratio between the actual reduction in cost and the reduction
173                // in cost if the problem were linear. The cost is the sum of the loss
174                // functions, not the squared norm of the loss-corrected residuals: those
175                // only give the linear model.
176                let actual_cost_change = current_error - problem.compute_cost(&new_param_blocks);
177                trace!("actual_cost_change {}", actual_cost_change);
178                let linear_residual_change: faer::Mat<f64> =
179                    lm_step.transpose().mul(2.0 * &jtr - &jtj * &lm_step);
180                let rho = actual_cost_change / linear_residual_change[(0, 0)];
181
182                if rho > 0.0 {
183                    // The linear model appears to be fitting, so accept (x + dx) as the new x.
184                    parameter_blocks = new_param_blocks;
185
186                    // Increase the trust region by reducing u
187                    let tmp = 2.0 * rho - 1.0;
188                    u *= (1.0_f64 / 3.0).max(1.0 - tmp * tmp * tmp);
189                } else {
190                    // If there's too much divergence, reduce the trust region and try again with the same parameters.
191                    u *= 2.0;
192                    trace!("u {}", u);
193                    // The parameters did not change, so the error did not either:
194                    // skip the convergence checks, which would otherwise stop here.
195                    continue;
196                }
197            } else {
198                log::debug!("solve ax=b failed");
199                return None;
200            }
201
202            current_error = problem.compute_cost(&parameter_blocks);
203            trace!("iter:{} total err:{}", i, current_error);
204
205            if current_error < opt_option.min_error_threshold {
206                trace!("error too low");
207                break;
208            } else if current_error.is_nan() {
209                log::debug!("solve ax=b failed, current error is nan");
210                return None;
211            }
212
213            if (last_err - current_error).abs() < opt_option.min_abs_error_decrease_threshold {
214                trace!("absolute error decrease low");
215                break;
216            } else if (last_err - current_error).abs() / last_err
217                < opt_option.min_rel_error_decrease_threshold
218            {
219                trace!("relative error decrease low");
220                break;
221            }
222        }
223        let params = parameter_blocks
224            .iter()
225            .map(|(k, v)| (k.to_owned(), v.params.clone()))
226            .collect();
227        Some(params)
228    }
229}