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. Variables that
110        // no residual block uses go last, in name order.
111        let mut ordered_names = Vec::with_capacity(parameter_blocks.len());
112        let mut used = HashSet::new();
113        for residual_block in self.residual_blocks.values() {
114            for var_key in &residual_block.variable_key_list {
115                if parameter_blocks.contains_key(var_key) && used.insert(var_key) {
116                    ordered_names.push(var_key);
117                }
118            }
119        }
120        let mut unused: Vec<_> = parameter_blocks
121            .keys()
122            .filter(|name| !used.contains(name))
123            .collect();
124        unused.sort_unstable();
125        if !unused.is_empty() {
126            log::warn!("no residual block uses these variables: {unused:?}");
127        }
128        ordered_names.extend(unused);
129
130        let mut count_col_idx = 0;
131        let mut variable_name_to_col_idx_dict = HashMap::new();
132        ordered_names
133            .into_iter()
134            .map(|param_name| (param_name, &parameter_blocks[param_name]))
135            .for_each(|(param_name, param_block)| {
136                variable_name_to_col_idx_dict.insert(param_name.to_owned(), count_col_idx);
137                let effective_size = if param_block.manifold.is_some() {
138                    param_block.tangent_size()
139                } else {
140                    param_block.tangent_size() - param_block.fixed_variables.len()
141                };
142                count_col_idx += effective_size;
143            });
144        variable_name_to_col_idx_dict
145    }
146    pub fn add_residual_block(
147        &mut self,
148        dim_residual: usize,
149        variable_key_size_list: &[&str],
150        factor: Box<dyn factors::FactorImpl + Send>,
151        loss_func: Option<Box<dyn loss_functions::Loss + Send>>,
152    ) -> ResidualBlockId {
153        self.residual_blocks.insert(
154            self.residual_id_count,
155            residual_block::ResidualBlock::new(
156                self.residual_id_count,
157                dim_residual,
158                self.total_residual_dimension,
159                variable_key_size_list,
160                factor,
161                loss_func,
162            ),
163        );
164        let block_id = self.residual_id_count;
165        self.residual_id_count += 1;
166
167        self.total_residual_dimension += dim_residual;
168
169        block_id
170    }
171    pub fn remove_residual_block(
172        &mut self,
173        block_id: ResidualBlockId,
174    ) -> Option<residual_block::ResidualBlock> {
175        if let Some(residual_block) = self.residual_blocks.remove(&block_id) {
176            self.total_residual_dimension -= residual_block.dim_residual;
177            // Close the gap: rows follow the blocks in id order, as when they were added.
178            let mut row_start = 0;
179            for block in self.residual_blocks.values_mut() {
180                block.residual_row_start_idx = row_start;
181                row_start += block.dim_residual;
182            }
183            Some(residual_block)
184        } else {
185            None
186        }
187    }
188    pub fn fix_variable(&mut self, var_to_fix: &str, idx: usize) {
189        if let Some(var_mut) = self.fixed_variable_indexes.get_mut(var_to_fix) {
190            var_mut.insert(idx);
191        } else {
192            self.fixed_variable_indexes
193                .insert(var_to_fix.to_owned(), HashSet::from([idx]));
194        }
195    }
196    pub fn unfix_variable(&mut self, var_to_unfix: &str) {
197        self.fixed_variable_indexes.remove(var_to_unfix);
198    }
199    pub fn set_variable_bounds(
200        &mut self,
201        var_to_bound: &str,
202        idx: usize,
203        lower_bound: f64,
204        upper_bound: f64,
205    ) {
206        if lower_bound > upper_bound {
207            log::error!("lower bound is larger than upper bound");
208        } else if let Some(var_mut) = self.variable_bounds.get_mut(var_to_bound) {
209            var_mut.insert(idx, (lower_bound, upper_bound));
210        } else {
211            self.variable_bounds.insert(
212                var_to_bound.to_owned(),
213                HashMap::from([(idx, (lower_bound, upper_bound))]),
214            );
215        }
216    }
217    pub fn set_variable_manifold(
218        &mut self,
219        var_name: &str,
220        manifold: Arc<dyn Manifold + Sync + Send>,
221    ) {
222        self.variable_manifold
223            .insert(var_name.to_string(), manifold);
224    }
225    pub fn remove_variable_bounds(&mut self, var_to_unbound: &str) {
226        self.variable_bounds.remove(var_to_unbound);
227    }
228    pub fn initialize_parameter_blocks(
229        &self,
230        initial_values: &HashMap<String, na::DVector<f64>>,
231    ) -> HashMap<String, ParameterBlock> {
232        let parameter_blocks: HashMap<String, ParameterBlock> = initial_values
233            .iter()
234            .map(|(k, v)| {
235                let mut p_block = ParameterBlock::from_vec(v.clone());
236                if let Some(indexes) = self.fixed_variable_indexes.get(k) {
237                    p_block.fixed_variables = indexes.clone();
238                }
239                if let Some(bounds) = self.variable_bounds.get(k) {
240                    p_block.variable_bounds = bounds.clone();
241                }
242                if let Some(manifold) = self.variable_manifold.get(k) {
243                    p_block.manifold = Some(manifold.clone())
244                }
245
246                (k.to_owned(), p_block)
247            })
248            .collect();
249        parameter_blocks
250    }
251
252    pub fn compute_residuals(
253        &self,
254        parameter_blocks: &HashMap<String, ParameterBlock>,
255        with_loss_fn: bool,
256    ) -> faer::Mat<f64> {
257        let total_residual = Arc::new(Mutex::new(na::DVector::<f64>::zeros(
258            self.total_residual_dimension,
259        )));
260        self.residual_blocks
261            .par_iter()
262            .for_each(|(_, residual_block)| {
263                self.compute_residual_impl(
264                    residual_block,
265                    parameter_blocks,
266                    &total_residual,
267                    with_loss_fn,
268                )
269            });
270        let total_residual = Arc::try_unwrap(total_residual)
271            .unwrap()
272            .into_inner()
273            .unwrap();
274
275        total_residual.view_range(.., ..).into_faer().to_owned()
276    }
277
278    /// The cost the optimizers minimize: the sum of rho(||r_i||^2) over the
279    /// residual blocks, where rho is the block's loss function (rho(s) = s
280    /// without one).
281    pub fn compute_cost(&self, parameter_blocks: &HashMap<String, ParameterBlock>) -> f64 {
282        let costs: Vec<f64> = self
283            .residual_blocks
284            .par_iter()
285            .map(|(_, residual_block)| {
286                let params: Vec<&ParameterBlock> = residual_block
287                    .variable_key_list
288                    .iter()
289                    .filter_map(|var_key| parameter_blocks.get(var_key))
290                    .collect();
291                residual_block.cost(&params)
292            })
293            .collect();
294        // Sum sequentially, so the result does not depend on the thread schedule.
295        costs.iter().sum()
296    }
297
298    pub fn compute_residual_and_jacobian(
299        &self,
300        parameter_blocks: &HashMap<String, ParameterBlock>,
301        variable_name_to_col_idx_dict: &HashMap<String, usize>,
302        symbolic_structure: &SymbolicStructure,
303    ) -> (faer::Mat<f64>, SparseColMat<usize, f64>) {
304        // multi
305        let total_residual = Arc::new(Mutex::new(na::DVector::<f64>::zeros(
306            self.total_residual_dimension,
307        )));
308
309        let jacobian_lists: Vec<JacobianValue> = self
310            .residual_blocks
311            .par_iter()
312            .map(|(_, residual_block)| {
313                self.compute_residual_and_jacobian_impl(
314                    residual_block,
315                    parameter_blocks,
316                    variable_name_to_col_idx_dict,
317                    &total_residual,
318                )
319            })
320            .flatten()
321            .collect();
322
323        let total_residual = Arc::try_unwrap(total_residual)
324            .unwrap()
325            .into_inner()
326            .unwrap();
327
328        let residual_faer = total_residual.view_range(.., ..).into_faer().to_owned();
329        let jacobian_faer = SparseColMat::new_from_argsort(
330            symbolic_structure.pattern.clone(),
331            &symbolic_structure.order,
332            jacobian_lists.as_slice(),
333        )
334        .unwrap();
335        (residual_faer, jacobian_faer)
336    }
337
338    fn compute_residual_impl(
339        &self,
340        residual_block: &crate::ResidualBlock,
341        parameter_blocks: &HashMap<String, ParameterBlock>,
342        total_residual: &Arc<Mutex<na::DVector<f64>>>,
343        with_loss_fn: bool,
344    ) {
345        let mut params = Vec::new();
346        for var_key in &residual_block.variable_key_list {
347            if let Some(param) = parameter_blocks.get(var_key) {
348                params.push(param);
349            };
350        }
351        let res = residual_block.residual(&params, with_loss_fn);
352
353        {
354            let mut total_residual = total_residual.lock().unwrap();
355            total_residual
356                .rows_mut(
357                    residual_block.residual_row_start_idx,
358                    residual_block.dim_residual,
359                )
360                .copy_from(&res);
361        }
362    }
363
364    fn compute_residual_and_jacobian_impl(
365        &self,
366        residual_block: &crate::ResidualBlock,
367        parameter_blocks: &HashMap<String, ParameterBlock>,
368        variable_name_to_col_idx_dict: &HashMap<String, usize>,
369        total_residual: &Arc<Mutex<na::DVector<f64>>>,
370    ) -> Vec<JacobianValue> {
371        let mut params = Vec::new();
372        let mut variable_local_idx_size_list = Vec::<(usize, usize)>::new();
373        let mut count_variable_local_idx: usize = 0;
374        for var_key in &residual_block.variable_key_list {
375            if let Some(param) = parameter_blocks.get(var_key) {
376                params.push(param);
377                variable_local_idx_size_list.push((count_variable_local_idx, param.tangent_size()));
378                count_variable_local_idx += param.tangent_size();
379            };
380        }
381        let (res, jac) = residual_block.residual_and_jacobian(&params);
382        {
383            let mut total_residual = total_residual.lock().unwrap();
384            total_residual
385                .rows_mut(
386                    residual_block.residual_row_start_idx,
387                    residual_block.dim_residual,
388                )
389                .copy_from(&res);
390        }
391
392        let mut local_jacobian_list = Vec::new();
393
394        for (i, var_key) in residual_block.variable_key_list.iter().enumerate() {
395            if variable_name_to_col_idx_dict.contains_key(var_key) {
396                let (variable_local_idx, var_size) = variable_local_idx_size_list[i];
397                let variable_jac = jac.view((0, variable_local_idx), (jac.shape().0, var_size));
398                let param = &params[i];
399                for row_idx in 0..jac.shape().0 {
400                    for col_idx in 0..var_size {
401                        if param.manifold.is_none() && param.fixed_variables.contains(&col_idx) {
402                            continue;
403                        }
404                        let j_value = variable_jac[(row_idx, col_idx)];
405                        if j_value.is_finite() {
406                            local_jacobian_list.push(j_value);
407                        } else {
408                            log::warn!(
409                                "Non-finite Jacobian value detected at residual block {}, variable {}, row {}, col {}. Setting to 0.0",
410                                residual_block.residual_block_id,
411                                var_key,
412                                row_idx,
413                                col_idx
414                            );
415                            local_jacobian_list.push(0.0);
416                        }
417                    }
418                }
419            } else {
420                panic!(
421                    "Missing key {} in variable-to-column-index mapping",
422                    var_key
423                );
424            }
425        }
426
427        local_jacobian_list
428    }
429}