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