Skip to main content

tiny_solver/
problem.rs

1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::sync::{Arc, Mutex};
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 total_residual = Arc::new(Mutex::new(na::DVector::<f64>::zeros(
274            self.total_residual_dimension,
275        )));
276        self.residual_blocks
277            .par_iter()
278            .for_each(|(_, residual_block)| {
279                self.compute_residual_impl(
280                    residual_block,
281                    parameter_blocks,
282                    &total_residual,
283                    with_loss_fn,
284                )
285            });
286        let total_residual = Arc::try_unwrap(total_residual)
287            .unwrap()
288            .into_inner()
289            .unwrap();
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        // multi
321        let total_residual = Arc::new(Mutex::new(na::DVector::<f64>::zeros(
322            self.total_residual_dimension,
323        )));
324
325        let jacobian_lists: Vec<JacobianValue> = self
326            .residual_blocks
327            .par_iter()
328            .map(|(_, residual_block)| {
329                self.compute_residual_and_jacobian_impl(
330                    residual_block,
331                    parameter_blocks,
332                    variable_name_to_col_idx_dict,
333                    &total_residual,
334                )
335            })
336            .flatten()
337            .collect();
338
339        let total_residual = Arc::try_unwrap(total_residual)
340            .unwrap()
341            .into_inner()
342            .unwrap();
343
344        let residual_faer = total_residual.view_range(.., ..).into_faer().to_owned();
345        let jacobian_faer = SparseColMat::new_from_argsort(
346            symbolic_structure.pattern.clone(),
347            &symbolic_structure.order,
348            jacobian_lists.as_slice(),
349        )
350        .unwrap();
351        (residual_faer, jacobian_faer)
352    }
353
354    fn compute_residual_impl(
355        &self,
356        residual_block: &crate::ResidualBlock,
357        parameter_blocks: &HashMap<String, ParameterBlock>,
358        total_residual: &Arc<Mutex<na::DVector<f64>>>,
359        with_loss_fn: bool,
360    ) {
361        let mut params = Vec::new();
362        for var_key in &residual_block.variable_key_list {
363            if let Some(param) = parameter_blocks.get(var_key) {
364                params.push(param);
365            };
366        }
367        let res = residual_block.residual(&params, with_loss_fn);
368
369        {
370            let mut total_residual = total_residual.lock().unwrap();
371            total_residual
372                .rows_mut(
373                    residual_block.residual_row_start_idx,
374                    residual_block.dim_residual,
375                )
376                .copy_from(&res);
377        }
378    }
379
380    fn compute_residual_and_jacobian_impl(
381        &self,
382        residual_block: &crate::ResidualBlock,
383        parameter_blocks: &HashMap<String, ParameterBlock>,
384        variable_name_to_col_idx_dict: &HashMap<String, usize>,
385        total_residual: &Arc<Mutex<na::DVector<f64>>>,
386    ) -> Vec<JacobianValue> {
387        let mut params = Vec::new();
388        let mut variable_local_idx_size_list = Vec::<(usize, usize)>::new();
389        let mut count_variable_local_idx: usize = 0;
390        for var_key in &residual_block.variable_key_list {
391            if let Some(param) = parameter_blocks.get(var_key) {
392                params.push(param);
393                variable_local_idx_size_list.push((count_variable_local_idx, param.tangent_size()));
394                count_variable_local_idx += param.tangent_size();
395            };
396        }
397        let (res, jac) = residual_block.residual_and_jacobian(&params);
398        {
399            let mut total_residual = total_residual.lock().unwrap();
400            total_residual
401                .rows_mut(
402                    residual_block.residual_row_start_idx,
403                    residual_block.dim_residual,
404                )
405                .copy_from(&res);
406        }
407
408        let mut local_jacobian_list = Vec::new();
409
410        for (i, var_key) in residual_block.variable_key_list.iter().enumerate() {
411            if variable_name_to_col_idx_dict.contains_key(var_key) {
412                let (variable_local_idx, var_size) = variable_local_idx_size_list[i];
413                let variable_jac = jac.view((0, variable_local_idx), (jac.shape().0, var_size));
414                let param = &params[i];
415                for row_idx in 0..jac.shape().0 {
416                    for col_idx in 0..var_size {
417                        if param.manifold.is_none() && param.fixed_variables.contains(&col_idx) {
418                            continue;
419                        }
420                        let j_value = variable_jac[(row_idx, col_idx)];
421                        if j_value.is_finite() {
422                            local_jacobian_list.push(j_value);
423                        } else {
424                            log::warn!(
425                                "Non-finite Jacobian value detected at residual block {}, variable {}, row {}, col {}. Setting to 0.0",
426                                residual_block.residual_block_id,
427                                var_key,
428                                row_idx,
429                                col_idx
430                            );
431                            local_jacobian_list.push(0.0);
432                        }
433                    }
434                }
435            } else {
436                panic!(
437                    "Missing key {} in variable-to-column-index mapping",
438                    var_key
439                );
440            }
441        }
442
443        local_jacobian_list
444    }
445}