1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
use crate::prelude::*;
use dyn_clone::DynClone;
use sophus_core::linalg::VecF64;
use sophus_lie::Isometry2;
use sophus_lie::Isometry3;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::fmt::Debug;

/// Variable kind
#[derive(PartialEq, Debug, Clone, Copy)]
pub enum VarKind {
    /// free variable (will be updated during optimization)
    Free,
    /// conditioned variable (will not be fixed during optimization)
    Conditioned,
    /// marginalized variable (will be updated during using the Schur complement trick)
    Marginalized,
}

///A decision variables
pub trait IsVariable: Clone + Debug {
    /// number of degrees of freedom
    const DOF: usize;

    /// update the variable in-place (called during optimization)
    fn update(&mut self, delta: nalgebra::DVectorView<f64>);
}

/// Tuple of variables (one for each argument of the cost function)
pub trait IsVarTuple<const NUM_ARGS: usize> {
    /// number of degrees of freedom for each variable
    const DOF_T: [usize; NUM_ARGS];

    /// Tuple variable families
    type VarFamilyTupleRef<'a>;

    /// reference to the variable family tuple
    fn ref_var_family_tuple(
        families: &VarPool,
        names: [String; NUM_ARGS],
    ) -> Self::VarFamilyTupleRef<'_>;

    /// extract the variables from the family tuple
    fn extract(family_tuple: &Self::VarFamilyTupleRef<'_>, ids: [usize; NUM_ARGS]) -> Self;

    /// return the variable kind for each variable (one for each argument of the cost function)
    fn var_kind_array(families: &VarPool, names: [String; NUM_ARGS]) -> [VarKind; NUM_ARGS];
}

impl<M0: IsVariable + 'static> IsVarTuple<1> for M0 {
    const DOF_T: [usize; 1] = [M0::DOF];
    type VarFamilyTupleRef<'a> = &'a VarFamily<M0>;

    fn var_kind_array(families: &VarPool, names: [String; 1]) -> [VarKind; 1] {
        [families.families.get(&names[0]).unwrap().get_var_kind()]
    }

    fn ref_var_family_tuple(families: &VarPool, names: [String; 1]) -> Self::VarFamilyTupleRef<'_> {
        families.get::<VarFamily<M0>>(names[0].clone())
    }

    fn extract(family_tuple: &Self::VarFamilyTupleRef<'_>, ids: [usize; 1]) -> Self {
        family_tuple.members[ids[0]].clone()
    }
}

impl<M0: IsVariable + 'static, M1: IsVariable + 'static> IsVarTuple<2> for (M0, M1) {
    const DOF_T: [usize; 2] = [M0::DOF, M1::DOF];
    type VarFamilyTupleRef<'a> = (&'a VarFamily<M0>, &'a VarFamily<M1>);

    fn var_kind_array(families: &VarPool, names: [String; 2]) -> [VarKind; 2] {
        [
            families.families.get(&names[0]).unwrap().get_var_kind(),
            families.families.get(&names[1]).unwrap().get_var_kind(),
        ]
    }

    fn ref_var_family_tuple(families: &VarPool, names: [String; 2]) -> Self::VarFamilyTupleRef<'_> {
        (
            families.get::<VarFamily<M0>>(names[0].clone()),
            families.get::<VarFamily<M1>>(names[1].clone()),
        )
    }

    fn extract(family_tuple: &Self::VarFamilyTupleRef<'_>, ids: [usize; 2]) -> Self {
        (
            family_tuple.0.members[ids[0]].clone(),
            family_tuple.1.members[ids[1]].clone(),
        )
    }
}

impl<M0: IsVariable + 'static, M1: IsVariable + 'static, M2: IsVariable + 'static> IsVarTuple<3>
    for (M0, M1, M2)
{
    const DOF_T: [usize; 3] = [M0::DOF, M1::DOF, M2::DOF];
    type VarFamilyTupleRef<'a> = (&'a VarFamily<M0>, &'a VarFamily<M1>, &'a VarFamily<M2>);

    fn var_kind_array(families: &VarPool, names: [String; 3]) -> [VarKind; 3] {
        [
            families.families.get(&names[0]).unwrap().get_var_kind(),
            families.families.get(&names[1]).unwrap().get_var_kind(),
            families.families.get(&names[2]).unwrap().get_var_kind(),
        ]
    }

    fn ref_var_family_tuple(families: &VarPool, names: [String; 3]) -> Self::VarFamilyTupleRef<'_> {
        (
            families.get::<VarFamily<M0>>(names[0].clone()),
            families.get::<VarFamily<M1>>(names[1].clone()),
            families.get::<VarFamily<M2>>(names[2].clone()),
        )
    }

    fn extract(family_tuple: &Self::VarFamilyTupleRef<'_>, ids: [usize; 3]) -> Self {
        (
            family_tuple.0.members[ids[0]].clone(),
            family_tuple.1.members[ids[1]].clone(),
            family_tuple.2.members[ids[2]].clone(),
        )
    }
}

impl<const N: usize> IsVariable for VecF64<N> {
    const DOF: usize = N;

    fn update(&mut self, delta: nalgebra::DVectorView<f64>) {
        for d in 0..Self::DOF {
            self[d] += delta[d];
        }
    }
}

impl IsVariable for Isometry2<f64, 1> {
    const DOF: usize = 3;

    fn update(&mut self, delta: nalgebra::DVectorView<f64>) {
        let mut delta_vec = VecF64::<3>::zeros();
        for d in 0..<Self as IsVariable>::DOF {
            delta_vec[d] = delta[d];
        }
        self.set_params(
            (Isometry2::<f64, 1>::group_mul(&Isometry2::<f64, 1>::exp(&delta_vec), &self.clone()))
                .params(),
        );
    }
}

impl IsVariable for Isometry3<f64, 1> {
    const DOF: usize = 6;

    fn update(&mut self, delta: nalgebra::DVectorView<f64>) {
        let mut delta_vec = VecF64::<6>::zeros();
        for d in 0..<Self as IsVariable>::DOF {
            delta_vec[d] = delta[d];
        }
        self.set_params(
            (Isometry3::<f64, 1>::group_mul(&Isometry3::<f64, 1>::exp(&delta_vec), &self.clone()))
                .params(),
        );
    }
}

/// A generic family of variables
///
/// A list of variables of the same nature (e.g., a list of 3D points, a list of 2D isometries, etc.)
#[derive(Debug, Clone)]
pub struct VarFamily<Var: IsVariable> {
    kind: VarKind,
    /// members of the family
    pub members: Vec<Var>,
    constant_members: HashMap<usize, ()>,
    start_indices: Vec<i64>,
}

impl<Var: IsVariable> VarFamily<Var> {
    /// create a new variable family a variable kind (free, conditioned, ...) and a list of members
    pub fn new(kind: VarKind, members: Vec<Var>) -> Self {
        Self::new_with_const_ids(kind, members, HashMap::new())
    }

    /// Create a new variable family a variable kind (free, conditioned, ...), a list of members and a list of constant members
    ///
    /// The constant members are not updated during optimization (no matter the variable kind)
    pub fn new_with_const_ids(
        kind: VarKind,
        members: Vec<Var>,
        constant_members: HashMap<usize, ()>,
    ) -> Self {
        VarFamily {
            kind,
            members,
            constant_members,
            start_indices: vec![],
        }
    }

    fn c(&self) -> VarKind {
        self.kind
    }
}

/// A family of variables
pub trait IsVarFamily: as_any::AsAny + Debug + DynClone {
    /// update variables in-place (called during optimization)
    fn update(&mut self, delta: nalgebra::DVectorView<f64>);

    /// update the ith variable in-place (called during optimization)
    fn update_i(&mut self, i: usize, delta: nalgebra::DVector<f64>);

    /// total number of free scalars (#free variables * #DOF)
    fn num_free_scalars(&self) -> usize;

    /// start indices in linear system of equations
    fn calc_start_indices(&mut self, offset: &mut usize);

    /// total number of marginalized scalars (#marginalized variables * #DOF)
    fn num_marg_scalars(&self) -> usize;

    /// start indices in linear system of equations
    fn get_start_indices(&self) -> &Vec<i64>;

    /// number of members in the family
    fn len(&self) -> usize;

    /// is empty
    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// returns 0 if variable is conditioned, DOF otherwise
    fn free_or_marg_dof(&self) -> usize;

    /// variable kind (free, conditioned, ...)
    fn get_var_kind(&self) -> VarKind;
}

impl<Var: IsVariable + 'static> IsVarFamily for VarFamily<Var> {
    fn update(&mut self, delta: nalgebra::DVectorView<f64>) {
        let dof = self.free_or_marg_dof();

        assert_eq!(self.start_indices.len(), self.members.len());

        for i in 0..self.start_indices.len() {
            let start_idx = self.start_indices[i];
            if start_idx == -1 {
                continue;
            }
            let start_idx = start_idx as usize;
            self.members[i].update(delta.rows(start_idx, dof));
        }
    }

    fn len(&self) -> usize {
        self.members.len()
    }

    fn num_free_scalars(&self) -> usize {
        match self.get_var_kind() {
            VarKind::Free => (self.members.len() - self.constant_members.len()) * Var::DOF,
            VarKind::Conditioned => 0,
            VarKind::Marginalized => 0,
        }
    }

    fn num_marg_scalars(&self) -> usize {
        match self.get_var_kind() {
            VarKind::Free => 0,
            VarKind::Conditioned => 0,
            VarKind::Marginalized => (self.members.len() - self.constant_members.len()) * Var::DOF,
        }
    }

    // returns -1 if variable is not free
    fn calc_start_indices(&mut self, inout_offset: &mut usize) {
        assert_eq!(
            self.start_indices.len(),
            0,
            "This function must only called once"
        );

        match self.get_var_kind() {
            VarKind::Free => {
                let mut indices = vec![];
                let mut idx: usize = *inout_offset;
                for i in 0..self.members.len() {
                    if self.constant_members.contains_key(&i) {
                        indices.push(-1);
                    } else {
                        indices.push(idx as i64);
                        idx += Var::DOF;
                    }
                }
                *inout_offset = idx;

                assert_eq!(indices.len(), self.members.len());
                self.start_indices = indices;
            }
            VarKind::Conditioned => {
                let mut indices = vec![];

                for _i in 0..self.members.len() {
                    indices.push(-1);
                }
                assert_eq!(indices.len(), self.members.len());
                self.start_indices = indices;
            }
            VarKind::Marginalized => {
                let mut indices = vec![];

                for _i in 0..self.members.len() {
                    indices.push(-2);
                }
                assert_eq!(indices.len(), self.members.len());
                self.start_indices = indices;
            }
        }
    }

    fn free_or_marg_dof(&self) -> usize {
        match self.get_var_kind() {
            VarKind::Free => Var::DOF,
            VarKind::Conditioned => 0,
            VarKind::Marginalized => Var::DOF,
        }
    }

    fn get_var_kind(&self) -> VarKind {
        self.c()
    }

    fn get_start_indices(&self) -> &Vec<i64> {
        &self.start_indices
    }

    fn update_i(&mut self, i: usize, delta: nalgebra::DVector<f64>) {
        self.members[i].update(delta.as_view());
    }
}

dyn_clone::clone_trait_object!(IsVarFamily);

/// Builder for the variable pool
#[derive(Debug, Clone)]
pub struct VarPoolBuilder {
    families: std::collections::BTreeMap<String, Box<dyn IsVarFamily>>,
}

impl Default for VarPoolBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl VarPoolBuilder {
    /// create a new variable pool builder
    pub fn new() -> Self {
        Self {
            families: BTreeMap::new(),
        }
    }

    /// add a family of variables to the pool
    pub fn add_family<S: Into<String>, Var: IsVariable + 'static>(
        mut self,
        name: S,
        family: VarFamily<Var>,
    ) -> Self {
        self.families.insert(name.into(), Box::new(family));
        self
    }

    /// build the variable pool
    pub fn build(self) -> VarPool {
        VarPool::new(self)
    }
}

/// A pool of variable families
#[derive(Debug, Clone)]
pub struct VarPool {
    pub(crate) families: std::collections::BTreeMap<String, Box<dyn IsVarFamily>>,
}

impl VarPool {
    fn new(mut builder: VarPoolBuilder) -> Self {
        let mut offset = 0;
        for (_name, family) in builder.families.iter_mut() {
            family.calc_start_indices(&mut offset);
        }

        Self {
            families: builder.families,
        }
    }
}

impl VarPool {
    /// total number of free scalars
    pub fn num_free_params(&self) -> usize {
        let mut num = 0;

        for f in self.families.iter() {
            num += f.1.num_free_scalars();
        }

        num
    }

    /// total number of marginalized scalars
    pub fn num_of_kind(&self, var_kind: VarKind) -> usize {
        let mut num = 0;

        for f in self.families.iter() {
            num += if f.1.get_var_kind() == var_kind { 1 } else { 0 }
        }

        num
    }

    /// update the variables in-place (called during optimization)
    pub(crate) fn update(&self, delta: nalgebra::DVector<f64>) -> VarPool {
        let mut updated = self.clone();
        for family in updated.families.iter_mut() {
            family.1.update(delta.as_view());
        }
        updated
    }

    /// retrieve a variable family by name
    ///
    /// Panics if the family does not exist, or the specified type is not correct
    pub fn get<T: IsVarFamily>(&self, name: String) -> &T {
        as_any::Downcast::downcast_ref::<T>(self.families.get(&name).unwrap().as_ref()).unwrap()
    }

    /// retrieve family members by family name
    ///
    /// Panics if the family does not exist, or the specified type is not correct
    pub fn get_members<T: IsVariable + 'static>(&self, name: String) -> Vec<T> {
        as_any::Downcast::downcast_ref::<VarFamily<T>>(self.families.get(&name).unwrap().as_ref())
            .unwrap()
            .members
            .clone()
    }
}