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