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            Some(residual_block)
178        } else {
179            None
180        }
181    }
182    pub fn fix_variable(&mut self, var_to_fix: &str, idx: usize) {
183        if let Some(var_mut) = self.fixed_variable_indexes.get_mut(var_to_fix) {
184            var_mut.insert(idx);
185        } else {
186            self.fixed_variable_indexes
187                .insert(var_to_fix.to_owned(), HashSet::from([idx]));
188        }
189    }
190    pub fn unfix_variable(&mut self, var_to_unfix: &str) {
191        self.fixed_variable_indexes.remove(var_to_unfix);
192    }
193    pub fn set_variable_bounds(
194        &mut self,
195        var_to_bound: &str,
196        idx: usize,
197        lower_bound: f64,
198        upper_bound: f64,
199    ) {
200        if lower_bound > upper_bound {
201            log::error!("lower bound is larger than upper bound");
202        } else if let Some(var_mut) = self.variable_bounds.get_mut(var_to_bound) {
203            var_mut.insert(idx, (lower_bound, upper_bound));
204        } else {
205            self.variable_bounds.insert(
206                var_to_bound.to_owned(),
207                HashMap::from([(idx, (lower_bound, upper_bound))]),
208            );
209        }
210    }
211    pub fn set_variable_manifold(
212        &mut self,
213        var_name: &str,
214        manifold: Arc<dyn Manifold + Sync + Send>,
215    ) {
216        self.variable_manifold
217            .insert(var_name.to_string(), manifold);
218    }
219    pub fn remove_variable_bounds(&mut self, var_to_unbound: &str) {
220        self.variable_bounds.remove(var_to_unbound);
221    }
222    pub fn initialize_parameter_blocks(
223        &self,
224        initial_values: &HashMap<String, na::DVector<f64>>,
225    ) -> HashMap<String, ParameterBlock> {
226        let parameter_blocks: HashMap<String, ParameterBlock> = initial_values
227            .iter()
228            .map(|(k, v)| {
229                let mut p_block = ParameterBlock::from_vec(v.clone());
230                if let Some(indexes) = self.fixed_variable_indexes.get(k) {
231                    p_block.fixed_variables = indexes.clone();
232                }
233                if let Some(bounds) = self.variable_bounds.get(k) {
234                    p_block.variable_bounds = bounds.clone();
235                }
236                if let Some(manifold) = self.variable_manifold.get(k) {
237                    p_block.manifold = Some(manifold.clone())
238                }
239
240                (k.to_owned(), p_block)
241            })
242            .collect();
243        parameter_blocks
244    }
245
246    pub fn compute_residuals(
247        &self,
248        parameter_blocks: &HashMap<String, ParameterBlock>,
249        with_loss_fn: bool,
250    ) -> faer::Mat<f64> {
251        let total_residual = Arc::new(Mutex::new(na::DVector::<f64>::zeros(
252            self.total_residual_dimension,
253        )));
254        self.residual_blocks
255            .par_iter()
256            .for_each(|(_, residual_block)| {
257                self.compute_residual_impl(
258                    residual_block,
259                    parameter_blocks,
260                    &total_residual,
261                    with_loss_fn,
262                )
263            });
264        let total_residual = Arc::try_unwrap(total_residual)
265            .unwrap()
266            .into_inner()
267            .unwrap();
268
269        total_residual.view_range(.., ..).into_faer().to_owned()
270    }
271
272    /// The cost the optimizers minimize: the sum of rho(||r_i||^2) over the
273    /// residual blocks, where rho is the block's loss function (rho(s) = s
274    /// without one).
275    pub fn compute_cost(&self, parameter_blocks: &HashMap<String, ParameterBlock>) -> f64 {
276        let costs: Vec<f64> = self
277            .residual_blocks
278            .par_iter()
279            .map(|(_, residual_block)| {
280                let params: Vec<&ParameterBlock> = residual_block
281                    .variable_key_list
282                    .iter()
283                    .filter_map(|var_key| parameter_blocks.get(var_key))
284                    .collect();
285                residual_block.cost(&params)
286            })
287            .collect();
288        // Sum sequentially, so the result does not depend on the thread schedule.
289        costs.iter().sum()
290    }
291
292    pub fn compute_residual_and_jacobian(
293        &self,
294        parameter_blocks: &HashMap<String, ParameterBlock>,
295        variable_name_to_col_idx_dict: &HashMap<String, usize>,
296        symbolic_structure: &SymbolicStructure,
297    ) -> (faer::Mat<f64>, SparseColMat<usize, f64>) {
298        // multi
299        let total_residual = Arc::new(Mutex::new(na::DVector::<f64>::zeros(
300            self.total_residual_dimension,
301        )));
302
303        let jacobian_lists: Vec<JacobianValue> = self
304            .residual_blocks
305            .par_iter()
306            .map(|(_, residual_block)| {
307                self.compute_residual_and_jacobian_impl(
308                    residual_block,
309                    parameter_blocks,
310                    variable_name_to_col_idx_dict,
311                    &total_residual,
312                )
313            })
314            .flatten()
315            .collect();
316
317        let total_residual = Arc::try_unwrap(total_residual)
318            .unwrap()
319            .into_inner()
320            .unwrap();
321
322        let residual_faer = total_residual.view_range(.., ..).into_faer().to_owned();
323        let jacobian_faer = SparseColMat::new_from_argsort(
324            symbolic_structure.pattern.clone(),
325            &symbolic_structure.order,
326            jacobian_lists.as_slice(),
327        )
328        .unwrap();
329        (residual_faer, jacobian_faer)
330    }
331
332    fn compute_residual_impl(
333        &self,
334        residual_block: &crate::ResidualBlock,
335        parameter_blocks: &HashMap<String, ParameterBlock>,
336        total_residual: &Arc<Mutex<na::DVector<f64>>>,
337        with_loss_fn: bool,
338    ) {
339        let mut params = Vec::new();
340        for var_key in &residual_block.variable_key_list {
341            if let Some(param) = parameter_blocks.get(var_key) {
342                params.push(param);
343            };
344        }
345        let res = residual_block.residual(&params, with_loss_fn);
346
347        {
348            let mut total_residual = total_residual.lock().unwrap();
349            total_residual
350                .rows_mut(
351                    residual_block.residual_row_start_idx,
352                    residual_block.dim_residual,
353                )
354                .copy_from(&res);
355        }
356    }
357
358    fn compute_residual_and_jacobian_impl(
359        &self,
360        residual_block: &crate::ResidualBlock,
361        parameter_blocks: &HashMap<String, ParameterBlock>,
362        variable_name_to_col_idx_dict: &HashMap<String, usize>,
363        total_residual: &Arc<Mutex<na::DVector<f64>>>,
364    ) -> Vec<JacobianValue> {
365        let mut params = Vec::new();
366        let mut variable_local_idx_size_list = Vec::<(usize, usize)>::new();
367        let mut count_variable_local_idx: usize = 0;
368        for var_key in &residual_block.variable_key_list {
369            if let Some(param) = parameter_blocks.get(var_key) {
370                params.push(param);
371                variable_local_idx_size_list.push((count_variable_local_idx, param.tangent_size()));
372                count_variable_local_idx += param.tangent_size();
373            };
374        }
375        let (res, jac) = residual_block.residual_and_jacobian(&params);
376        {
377            let mut total_residual = total_residual.lock().unwrap();
378            total_residual
379                .rows_mut(
380                    residual_block.residual_row_start_idx,
381                    residual_block.dim_residual,
382                )
383                .copy_from(&res);
384        }
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        local_jacobian_list
422    }
423}