Skip to main content

tiny_solver/
residual_block.rs

1use nalgebra as na;
2
3use crate::corrector::Corrector;
4use crate::factors::{DualStride, FactorImpl, STRIDE};
5use crate::loss_functions::Loss;
6use crate::parameter_block::ParameterBlock;
7
8pub struct ResidualBlock {
9    pub residual_block_id: usize,
10    pub dim_residual: usize,
11    pub residual_row_start_idx: usize,
12    pub variable_key_list: Vec<String>,
13    pub factor: Box<dyn FactorImpl + Send>,
14    pub loss_func: Option<Box<dyn Loss + Send>>,
15}
16impl ResidualBlock {
17    pub fn new(
18        residual_block_id: usize,
19        dim_residual: usize,
20        residual_row_start_idx: usize,
21        variable_key_size_list: &[&str],
22        factor: Box<dyn FactorImpl + Send>,
23        loss_func: Option<Box<dyn Loss + Send>>,
24    ) -> Self {
25        ResidualBlock {
26            residual_block_id,
27            dim_residual,
28            residual_row_start_idx,
29            variable_key_list: variable_key_size_list
30                .iter()
31                .map(|s| s.to_string())
32                .collect(),
33            factor,
34            loss_func,
35        }
36    }
37
38    pub fn residual(&self, params: &[&ParameterBlock], with_loss_fn: bool) -> na::DVector<f64> {
39        let param_vec: Vec<_> = params.iter().map(|p| p.params.clone()).collect();
40        let mut residual = self.factor.residual_func_f64(&param_vec);
41        self.check_residual_count(residual.nrows());
42        let squared_norm = residual.norm_squared();
43        if with_loss_fn {
44            if let Some(loss_func) = self.loss_func.as_ref() {
45                let rho = loss_func.evaluate(squared_norm);
46                // let cost = 0.5 * rho[0];
47                let corrector = Corrector::new(squared_norm, &rho);
48                corrector.correct_residuals(&mut residual);
49            }
50        } else {
51            // let cost = 0.5 * squared_norm;
52        }
53        residual
54    }
55    /// The cost of this block: rho(||r||^2) with a loss function, ||r||^2
56    /// without one.
57    pub fn cost(&self, params: &[&ParameterBlock]) -> f64 {
58        let param_vec: Vec<_> = params.iter().map(|p| p.params.clone()).collect();
59        let squared_norm = self.factor.residual_func_f64(&param_vec).norm_squared();
60        match self.loss_func.as_ref() {
61            Some(loss_func) => loss_func.evaluate(squared_norm)[0],
62            None => squared_norm,
63        }
64    }
65    pub fn residual_and_jacobian(
66        &self,
67        params: &[&ParameterBlock],
68    ) -> (na::DVector<f64>, na::DMatrix<f64>) {
69        let dim_variable = params.iter().map(|x| x.tangent_size()).sum::<usize>();
70        let mut residual = na::DVector::<f64>::zeros(self.dim_residual);
71        let mut jacobian = na::DMatrix::<f64>::zeros(self.dim_residual, dim_variable);
72        // The pass at `first_direction` seeds the tangent directions
73        // [first_direction, first_direction + STRIDE), as Ceres' DynamicAutoDiffCostFunction
74        // does. One pass always runs, for the residual.
75        for first_direction in (0..dim_variable.max(1)).step_by(STRIDE) {
76            let mut offset = 0;
77            let inputs: Vec<na::DVector<DualStride>> = params
78                .iter()
79                .map(|param| {
80                    let tangent_size = param.tangent_size();
81                    let delta = na::DVector::from_fn(tangent_size, |index, _| {
82                        let direction = offset + index;
83                        if direction >= first_direction && direction < first_direction + STRIDE {
84                            DualStride::new(
85                                0.0,
86                                num_dual::Derivative::derivative_generic(
87                                    na::Const::<STRIDE>,
88                                    na::Const::<1>,
89                                    direction - first_direction,
90                                ),
91                            )
92                        } else {
93                            DualStride::from_re(0.0)
94                        }
95                    });
96                    offset += tangent_size;
97                    param.plus_dual(delta.as_view())
98                })
99                .collect();
100            let dual_residual = self.factor.residual_func_dual(&inputs);
101            self.check_residual_count(dual_residual.nrows());
102            for (row, dual) in dual_residual.iter().enumerate() {
103                residual[row] = dual.re;
104                let derivatives = dual.eps.unwrap_generic(na::Const::<STRIDE>, na::Const::<1>);
105                for lane in 0..STRIDE.min(dim_variable - first_direction) {
106                    jacobian[(row, first_direction + lane)] = derivatives[lane];
107                }
108            }
109        }
110        let squared_norm = residual.norm_squared();
111        if let Some(loss_func) = self.loss_func.as_ref() {
112            let rho = loss_func.evaluate(squared_norm);
113            // let cost = 0.5 * rho[0];
114            let corrector = Corrector::new(squared_norm, &rho);
115            corrector.correct_jacobian(&residual, &mut jacobian);
116            corrector.correct_residuals(&mut residual);
117        } else {
118            // let cost = 0.5 * squared_norm;
119        }
120        (residual, jacobian)
121    }
122
123    fn check_residual_count(&self, returned: usize) {
124        assert_eq!(
125            returned, self.dim_residual,
126            "residual block {}: the factor returned {} residuals, but was added with dim_residual = {}",
127            self.residual_block_id, returned, self.dim_residual
128        );
129    }
130}