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            .iter()
62            .filter(|(name, _)| variable_name_to_col_idx_dict.contains_key(*name))
63            .map(|(_, p)| {
64                if p.manifold.is_some() {
65                    p.tangent_size()
66                } else {
67                    p.tangent_size() - p.fixed_variables.len()
68                }
69            })
70            .sum();
71
72        let opt_option = optimizer_option.unwrap_or_default();
73        let mut linear_solver: Box<dyn SparseLinearSolver> = match opt_option.linear_solver_type {
74            LinearSolverType::SparseCholesky => Box::new(linear::SparseCholeskySolver::new()),
75            LinearSolverType::SparseQR => Box::new(linear::SparseQRSolver::new()),
76        };
77
78        // On the first iteration, we'll generate a diagonal matrix of the jacobian.
79        // Its shape will be (total_variable_dimension, total_variable_dimension).
80        // With LM, rather than solving A * dx = b for dx, we solve for (A + lambda * diag(A)) dx = b.
81        let mut jacobi_scaling_diagonal: Option<faer::sparse::SparseColMat<usize, f64>> = None;
82
83        let symbolic_structure = problem.build_symbolic_structure(
84            &parameter_blocks,
85            total_variable_dimension,
86            &variable_name_to_col_idx_dict,
87        );
88
89        // Damping parameter (a.k.a lambda / Marquardt parameter)
90        let mut u = 1.0 / self.initial_trust_region_radius;
91        // Like ceres, each consecutive rejected or invalid step raises u twice as much.
92        let mut v = 2.0;
93        let mut warned_solve_failed = false;
94
95        let mut last_err;
96        let mut current_error = problem.compute_cost(&parameter_blocks);
97        for i in 0..opt_option.max_iteration {
98            last_err = current_error;
99
100            let (residuals, mut jac) = problem.compute_residual_and_jacobian(
101                &parameter_blocks,
102                &variable_name_to_col_idx_dict,
103                &symbolic_structure,
104            );
105
106            if i == 0 {
107                // On the first iteration, generate the diagonal of the jacobian.
108                let cols = jac.shape().1;
109                let jacobi_scaling_vec: Vec<Triplet<usize, usize, f64>> = (0..cols)
110                    .map(|c| {
111                        let v = jac.val_of_col(c).iter().map(|&i| i * i).sum::<f64>().sqrt();
112                        Triplet::new(c, c, 1.0 / (1.0 + v))
113                    })
114                    .collect();
115
116                jacobi_scaling_diagonal = Some(
117                    faer::sparse::SparseColMat::<usize, f64>::try_new_from_triplets(
118                        cols,
119                        cols,
120                        &jacobi_scaling_vec,
121                    )
122                    .unwrap(),
123                );
124            }
125
126            // Scale the current jacobian by the diagonal matrix
127            jac = jac * jacobi_scaling_diagonal.as_ref().unwrap();
128
129            // J^T * J = Matrix of shape (total_variable_dimension, total_variable_dimension)
130            let jtj = jac
131                .as_ref()
132                .transpose()
133                .to_col_major()
134                .unwrap()
135                .mul(jac.as_ref());
136
137            // J^T * -r = Matrix of shape (total_variable_dimension, 1)
138            let jtr = jac.as_ref().transpose().mul(-&residuals);
139
140            // Regularize the diagonal of jtj between the min and max diagonal values.
141            let mut jtj_regularized = jtj.clone();
142            for i in 0..total_variable_dimension {
143                jtj_regularized[(i, i)] +=
144                    u * (jtj[(i, i)].max(self.min_diagonal)).min(self.max_diagonal);
145            }
146
147            let start = Instant::now();
148            if let Some(lm_step) = linear_solver.solve_jtj(&jtr, &jtj_regularized) {
149                let duration = start.elapsed();
150                let dx = jacobi_scaling_diagonal.as_ref().unwrap() * &lm_step;
151
152                trace!("Time elapsed in solve Ax=b is: {:?}", duration);
153
154                let dx_na = dx.as_ref().into_nalgebra().column(0).clone_owned();
155
156                // A step this small can no longer change the parameters, whether it
157                // would be accepted or not, e.g. at a point where the gradient is zero.
158                let x_norm = parameter_blocks
159                    .values()
160                    .map(|p| p.params.norm_squared())
161                    .sum::<f64>()
162                    .sqrt();
163                if dx_na.norm() <= RELATIVE_STEP_THRESHOLD * (x_norm + RELATIVE_STEP_THRESHOLD) {
164                    trace!("relative step size low");
165                    break;
166                }
167
168                let mut new_param_blocks = parameter_blocks.clone();
169
170                self.apply_dx2(
171                    &dx_na,
172                    &mut new_param_blocks,
173                    &variable_name_to_col_idx_dict,
174                );
175
176                // rho is the ratio between the actual reduction in cost and the reduction
177                // in cost if the problem were linear. The cost is the sum of the loss
178                // functions, not the squared norm of the loss-corrected residuals: those
179                // only give the linear model.
180                let actual_cost_change = current_error - problem.compute_cost(&new_param_blocks);
181                trace!("actual_cost_change {}", actual_cost_change);
182                let linear_residual_change: faer::Mat<f64> =
183                    lm_step.transpose().mul(2.0 * &jtr - &jtj * &lm_step);
184                let rho = actual_cost_change / linear_residual_change[(0, 0)];
185
186                if rho > 0.0 {
187                    // The linear model appears to be fitting, so accept (x + dx) as the new x.
188                    parameter_blocks = new_param_blocks;
189
190                    // Increase the trust region by reducing u
191                    let tmp = 2.0 * rho - 1.0;
192                    u *= (1.0_f64 / 3.0).max(1.0 - tmp * tmp * tmp);
193                    v = 2.0;
194                } else {
195                    // If there's too much divergence, reduce the trust region and try again with the same parameters.
196                    u *= v;
197                    v *= 2.0;
198                    trace!("u {}", u);
199                    // The parameters did not change, so the error did not either:
200                    // skip the convergence checks, which would otherwise stop here.
201                    continue;
202                }
203            } else {
204                // Like ceres, treat a failed solve as a rejected step: retry
205                // with more damping.
206                if !warned_solve_failed {
207                    warned_solve_failed = true;
208                    log::warn!(
209                        "the linear solve failed, retrying with more damping; \
210                         some parameters may not change the cost, e.g. no pose is fixed"
211                    );
212                }
213                u *= v;
214                v *= 2.0;
215                trace!("solve ax=b failed, u {}", u);
216                continue;
217            }
218
219            current_error = problem.compute_cost(&parameter_blocks);
220            trace!("iter:{} total err:{}", i, current_error);
221
222            if current_error < opt_option.min_error_threshold {
223                trace!("error too low");
224                break;
225            } else if current_error.is_nan() {
226                log::debug!("solve ax=b failed, current error is nan");
227                return None;
228            }
229
230            if (last_err - current_error).abs() < opt_option.min_abs_error_decrease_threshold {
231                trace!("absolute error decrease low");
232                break;
233            } else if (last_err - current_error).abs() / last_err
234                < opt_option.min_rel_error_decrease_threshold
235            {
236                trace!("relative error decrease low");
237                break;
238            }
239        }
240        let params = parameter_blocks
241            .iter()
242            .map(|(k, v)| (k.to_owned(), v.params.clone()))
243            .collect();
244        Some(params)
245    }
246}