Skip to main content

tiny_solver/
problem.rs

1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::sync::Arc;
3
4use faer::sparse::{Argsort, Pair, SparseColMat, SymbolicSparseColMat};
5use faer_ext::IntoFaer;
6use nalgebra as na;
7use rayon::prelude::*;
8
9use crate::manifold::Manifold;
10use crate::parameter_block::ParameterBlock;
11use crate::{factors, loss_functions, residual_block};
12
13type ResidualBlockId = usize;
14
15pub struct Problem {
16    pub total_residual_dimension: usize,
17    residual_id_count: usize,
18    // Ordered by id, i.e. in insertion order, so the residual rows do not
19    // depend on hash order.
20    residual_blocks: BTreeMap<ResidualBlockId, residual_block::ResidualBlock>,
21    pub fixed_variable_indexes: HashMap<String, HashSet<usize>>,
22    pub variable_bounds: HashMap<String, HashMap<usize, (f64, f64)>>,
23    pub variable_manifold: HashMap<String, Arc<dyn Manifold + Sync + Send>>,
24}
25impl Default for Problem {
26    fn default() -> Self {
27        Self::new()
28    }
29}
30
31pub struct SymbolicStructure {
32    pattern: SymbolicSparseColMat<usize>,
33    order: Argsort<usize>,
34}
35
36type JacobianValue = f64;
37
38impl Problem {
39    pub fn new() -> Problem {
40        Problem {
41            total_residual_dimension: 0,
42            residual_id_count: 0,
43            residual_blocks: BTreeMap::new(),
44            fixed_variable_indexes: HashMap::new(),
45            variable_bounds: HashMap::new(),
46            variable_manifold: HashMap::new(),
47        }
48    }
49
50    pub fn build_symbolic_structure(
51        &self,
52        parameter_blocks: &HashMap<String, ParameterBlock>,
53        total_variable_dimension: usize,
54        variable_name_to_col_idx_dict: &HashMap<String, usize>,
55    ) -> SymbolicStructure {
56        let mut indices = Vec::<Pair<usize, usize>>::new();
57
58        self.residual_blocks.iter().for_each(|(_, residual_block)| {
59            let mut variable_local_idx_size_list = Vec::<(usize, usize)>::new();
60            let mut count_variable_local_idx: usize = 0;
61            for var_key in &residual_block.variable_key_list {
62                if let Some(param) = parameter_blocks.get(var_key) {
63                    variable_local_idx_size_list
64                        .push((count_variable_local_idx, param.tangent_size()));
65                    count_variable_local_idx += param.tangent_size();
66                };
67            }
68            for (i, var_key) in residual_block.variable_key_list.iter().enumerate() {
69                if let Some(variable_global_idx) = variable_name_to_col_idx_dict.get(var_key) {
70                    let (_, var_size) = variable_local_idx_size_list[i];
71                    for row_idx in 0..residual_block.dim_residual {
72                        let mut current_var_col_offset = 0;
73                        for col_idx in 0..var_size {
74                            if let Some(param) = parameter_blocks.get(var_key)
75                                && param.manifold.is_none()
76                                && param.fixed_variables.contains(&col_idx)
77                            {
78                                continue;
79                            }
80                            let global_row_idx = residual_block.residual_row_start_idx + row_idx;
81                            let global_col_idx = variable_global_idx + current_var_col_offset;
82                            indices.push(Pair::new(global_row_idx, global_col_idx));
83                            current_var_col_offset += 1;
84                        }
85                    }
86                }
87            }
88        });
89        let start = std::time::Instant::now();
90        let (s, o) = SymbolicSparseColMat::try_new_from_indices(
91            self.total_residual_dimension,
92            total_variable_dimension,
93            &indices,
94        )
95        .unwrap();
96        log::trace!("Built symbolic matrix: {:?}", start.elapsed());
97        SymbolicStructure {
98            pattern: s,
99            order: o,
100        }
101    }
102
103    pub fn get_variable_name_to_col_idx_dict(
104        &self,
105        parameter_blocks: &HashMap<String, ParameterBlock>,
106    ) -> HashMap<String, usize> {
107        // Like ceres, which lays out parameter blocks in the order they are added,
108        // assign columns in the order the residual blocks first use each
109        // variable, so the layout does not depend on hash order. As in ceres,
110        // variables that no residual block uses get no columns and stay unchanged.
111        let mut ordered_names = Vec::with_capacity(parameter_blocks.len());
112        let mut used = HashSet::new();
113        for (block_id, residual_block) in &self.residual_blocks {
114            for var_key in &residual_block.variable_key_list {
115                assert!(
116                    parameter_blocks.contains_key(var_key),
117                    "residual block {block_id} uses variable '{var_key}', which has no initial value"
118                );
119                if used.insert(var_key) {
120                    ordered_names.push(var_key);
121                }
122            }
123        }
124        let mut unused: Vec<_> = parameter_blocks
125            .keys()
126            .filter(|name| !used.contains(name))
127            .collect();
128        unused.sort_unstable();
129        if !unused.is_empty() {
130            log::warn!("no residual block uses these variables, they stay unchanged: {unused:?}");
131        }
132        let fixed_on_manifold: Vec<_> = parameter_blocks
133            .iter()
134            .filter(|(_, p)| p.manifold.is_some() && !p.fixed_variables.is_empty())
135            .map(|(name, _)| name)
136            .collect();
137        assert!(
138            fixed_on_manifold.is_empty(),
139            "fix_variable does not work on variables with a manifold: {fixed_on_manifold:?}. To \
140             hold such a variable constant, don't set its manifold and fix all of its coordinates."
141        );
142
143        let mut count_col_idx = 0;
144        let mut variable_name_to_col_idx_dict = HashMap::new();
145        ordered_names
146            .into_iter()
147            .map(|param_name| (param_name, &parameter_blocks[param_name]))
148            .for_each(|(param_name, param_block)| {
149                variable_name_to_col_idx_dict.insert(param_name.to_owned(), count_col_idx);
150                let effective_size = if param_block.manifold.is_some() {
151                    param_block.tangent_size()
152                } else {
153                    param_block.tangent_size() - param_block.fixed_variables.len()
154                };
155                count_col_idx += effective_size;
156            });
157        variable_name_to_col_idx_dict
158    }
159    pub fn add_residual_block(
160        &mut self,
161        dim_residual: usize,
162        variable_key_size_list: &[&str],
163        factor: Box<dyn factors::FactorImpl + Send>,
164        loss_func: Option<Box<dyn loss_functions::Loss + Send>>,
165    ) -> ResidualBlockId {
166        self.residual_blocks.insert(
167            self.residual_id_count,
168            residual_block::ResidualBlock::new(
169                self.residual_id_count,
170                dim_residual,
171                self.total_residual_dimension,
172                variable_key_size_list,
173                factor,
174                loss_func,
175            ),
176        );
177        let block_id = self.residual_id_count;
178        self.residual_id_count += 1;
179
180        self.total_residual_dimension += dim_residual;
181
182        block_id
183    }
184    pub fn remove_residual_block(
185        &mut self,
186        block_id: ResidualBlockId,
187    ) -> Option<residual_block::ResidualBlock> {
188        if let Some(residual_block) = self.residual_blocks.remove(&block_id) {
189            self.total_residual_dimension -= residual_block.dim_residual;
190            // Close the gap: rows follow the blocks in id order, as when they were added.
191            let mut row_start = 0;
192            for block in self.residual_blocks.values_mut() {
193                block.residual_row_start_idx = row_start;
194                row_start += block.dim_residual;
195            }
196            Some(residual_block)
197        } else {
198            None
199        }
200    }
201    /// Fixes coordinate `idx` of variable `var_to_fix`. This doesn't work on a variable with a
202    /// manifold, and the solve panics: to hold one constant, don't set its manifold and fix all
203    /// of its coordinates.
204    pub fn fix_variable(&mut self, var_to_fix: &str, idx: usize) {
205        if let Some(var_mut) = self.fixed_variable_indexes.get_mut(var_to_fix) {
206            var_mut.insert(idx);
207        } else {
208            self.fixed_variable_indexes
209                .insert(var_to_fix.to_owned(), HashSet::from([idx]));
210        }
211    }
212    pub fn unfix_variable(&mut self, var_to_unfix: &str) {
213        self.fixed_variable_indexes.remove(var_to_unfix);
214    }
215    pub fn set_variable_bounds(
216        &mut self,
217        var_to_bound: &str,
218        idx: usize,
219        lower_bound: f64,
220        upper_bound: f64,
221    ) {
222        if lower_bound > upper_bound {
223            log::error!("lower bound is larger than upper bound");
224        } else if let Some(var_mut) = self.variable_bounds.get_mut(var_to_bound) {
225            var_mut.insert(idx, (lower_bound, upper_bound));
226        } else {
227            self.variable_bounds.insert(
228                var_to_bound.to_owned(),
229                HashMap::from([(idx, (lower_bound, upper_bound))]),
230            );
231        }
232    }
233    pub fn set_variable_manifold(
234        &mut self,
235        var_name: &str,
236        manifold: Arc<dyn Manifold + Sync + Send>,
237    ) {
238        self.variable_manifold
239            .insert(var_name.to_string(), manifold);
240    }
241    pub fn remove_variable_bounds(&mut self, var_to_unbound: &str) {
242        self.variable_bounds.remove(var_to_unbound);
243    }
244    pub fn initialize_parameter_blocks(
245        &self,
246        initial_values: &HashMap<String, na::DVector<f64>>,
247    ) -> HashMap<String, ParameterBlock> {
248        let parameter_blocks: HashMap<String, ParameterBlock> = initial_values
249            .iter()
250            .map(|(k, v)| {
251                let mut p_block = ParameterBlock::from_vec(v.clone());
252                if let Some(indexes) = self.fixed_variable_indexes.get(k) {
253                    p_block.fixed_variables = indexes.clone();
254                }
255                if let Some(bounds) = self.variable_bounds.get(k) {
256                    p_block.variable_bounds = bounds.clone();
257                }
258                if let Some(manifold) = self.variable_manifold.get(k) {
259                    p_block.manifold = Some(manifold.clone())
260                }
261
262                (k.to_owned(), p_block)
263            })
264            .collect();
265        parameter_blocks
266    }
267
268    pub fn compute_residuals(
269        &self,
270        parameter_blocks: &HashMap<String, ParameterBlock>,
271        with_loss_fn: bool,
272    ) -> faer::Mat<f64> {
273        let per_block: Vec<na::DVector<f64>> = self
274            .residual_blocks
275            .par_iter()
276            .map(|(_, residual_block)| {
277                self.compute_residual_impl(residual_block, parameter_blocks, with_loss_fn)
278            })
279            .collect();
280
281        let mut total_residual = na::DVector::<f64>::zeros(self.total_residual_dimension);
282        for ((_, residual_block), res) in self.residual_blocks.iter().zip(&per_block) {
283            total_residual
284                .rows_mut(
285                    residual_block.residual_row_start_idx,
286                    residual_block.dim_residual,
287                )
288                .copy_from(res);
289        }
290
291        total_residual.view_range(.., ..).into_faer().to_owned()
292    }
293
294    /// The cost the optimizers minimize: the sum of rho(||r_i||^2) over the
295    /// residual blocks, where rho is the block's loss function (rho(s) = s
296    /// without one).
297    pub fn compute_cost(&self, parameter_blocks: &HashMap<String, ParameterBlock>) -> f64 {
298        let costs: Vec<f64> = self
299            .residual_blocks
300            .par_iter()
301            .map(|(_, residual_block)| {
302                let params: Vec<&ParameterBlock> = residual_block
303                    .variable_key_list
304                    .iter()
305                    .filter_map(|var_key| parameter_blocks.get(var_key))
306                    .collect();
307                residual_block.cost(&params)
308            })
309            .collect();
310        // Sum sequentially, so the result does not depend on the thread schedule.
311        costs.iter().sum()
312    }
313
314    pub fn compute_residual_and_jacobian(
315        &self,
316        parameter_blocks: &HashMap<String, ParameterBlock>,
317        variable_name_to_col_idx_dict: &HashMap<String, usize>,
318        symbolic_structure: &SymbolicStructure,
319    ) -> (faer::Mat<f64>, SparseColMat<usize, f64>) {
320        let per_block: Vec<(na::DVector<f64>, Vec<JacobianValue>)> = self
321            .residual_blocks
322            .par_iter()
323            .map(|(_, residual_block)| {
324                self.compute_residual_and_jacobian_impl(
325                    residual_block,
326                    parameter_blocks,
327                    variable_name_to_col_idx_dict,
328                )
329            })
330            .collect();
331        let mut total_residual = na::DVector::<f64>::zeros(self.total_residual_dimension);
332        let mut jacobian_lists: Vec<JacobianValue> = Vec::new();
333        for ((_, residual_block), (res, jac)) in self.residual_blocks.iter().zip(per_block) {
334            total_residual
335                .rows_mut(
336                    residual_block.residual_row_start_idx,
337                    residual_block.dim_residual,
338                )
339                .copy_from(&res);
340            jacobian_lists.extend(jac);
341        }
342
343        let residual_faer = total_residual.view_range(.., ..).into_faer().to_owned();
344        let jacobian_faer = SparseColMat::new_from_argsort(
345            symbolic_structure.pattern.clone(),
346            &symbolic_structure.order,
347            jacobian_lists.as_slice(),
348        )
349        .unwrap();
350        (residual_faer, jacobian_faer)
351    }
352
353    fn compute_residual_impl(
354        &self,
355        residual_block: &crate::ResidualBlock,
356        parameter_blocks: &HashMap<String, ParameterBlock>,
357        with_loss_fn: bool,
358    ) -> na::DVector<f64> {
359        let mut params = Vec::new();
360        for var_key in &residual_block.variable_key_list {
361            if let Some(param) = parameter_blocks.get(var_key) {
362                params.push(param);
363            };
364        }
365        residual_block.residual(&params, with_loss_fn)
366    }
367
368    fn compute_residual_and_jacobian_impl(
369        &self,
370        residual_block: &crate::ResidualBlock,
371        parameter_blocks: &HashMap<String, ParameterBlock>,
372        variable_name_to_col_idx_dict: &HashMap<String, usize>,
373    ) -> (na::DVector<f64>, Vec<JacobianValue>) {
374        let mut params = Vec::new();
375        let mut variable_local_idx_size_list = Vec::<(usize, usize)>::new();
376        let mut count_variable_local_idx: usize = 0;
377        for var_key in &residual_block.variable_key_list {
378            if let Some(param) = parameter_blocks.get(var_key) {
379                params.push(param);
380                variable_local_idx_size_list.push((count_variable_local_idx, param.tangent_size()));
381                count_variable_local_idx += param.tangent_size();
382            };
383        }
384        let (res, jac) = residual_block.residual_and_jacobian(&params);
385
386        let mut local_jacobian_list = Vec::new();
387
388        for (i, var_key) in residual_block.variable_key_list.iter().enumerate() {
389            if variable_name_to_col_idx_dict.contains_key(var_key) {
390                let (variable_local_idx, var_size) = variable_local_idx_size_list[i];
391                let variable_jac = jac.view((0, variable_local_idx), (jac.shape().0, var_size));
392                let param = &params[i];
393                for row_idx in 0..jac.shape().0 {
394                    for col_idx in 0..var_size {
395                        if param.manifold.is_none() && param.fixed_variables.contains(&col_idx) {
396                            continue;
397                        }
398                        let j_value = variable_jac[(row_idx, col_idx)];
399                        if j_value.is_finite() {
400                            local_jacobian_list.push(j_value);
401                        } else {
402                            log::warn!(
403                                "Non-finite Jacobian value detected at residual block {}, variable {}, row {}, col {}. Setting to 0.0",
404                                residual_block.residual_block_id,
405                                var_key,
406                                row_idx,
407                                col_idx
408                            );
409                            local_jacobian_list.push(0.0);
410                        }
411                    }
412                }
413            } else {
414                panic!(
415                    "Missing key {} in variable-to-column-index mapping",
416                    var_key
417                );
418            }
419        }
420
421        (res, local_jacobian_list)
422    }
423}