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
use std::collections::HashMap;
use bayes_estimate::estimators::sir;
use bayes_estimate::estimators::sir::SampleState;
use bayes_estimate::models::{KalmanEstimator, KalmanState};
use bayes_estimate::noise::CorrelatedNoise;
use nalgebra::{allocator::Allocator, Const, DefaultAllocator, Dim, Dynamic, OMatrix, OVector, RealField, U1};
use num_traits::{ToPrimitive, FromPrimitive};
pub struct FastSLAM<N: RealField, DL: Dim, const DF: usize>
where DefaultAllocator: Allocator<N, DL, DL> + Allocator<N, DL> + Allocator<N, Const<DF>, Const<DF>> + Allocator<N, Const<DF>>
{
pub loc: SampleState<N, DL>,
pub map: FeatureMap<N, Const<DF>>,
}
pub type Feature<N, DF> = KalmanState<N, DF>;
pub type FeatureCondMap<N, DF> = Vec<Feature<N, DF>>;
type FeatureMap<N, DF> = HashMap<u32, FeatureCondMap<N, DF>>;
impl<N: RealField + Copy + FromPrimitive + ToPrimitive, DL: Dim, const DF: usize> FastSLAM<N, DL, DF>
where DefaultAllocator: Allocator<N, DL, DL> + Allocator<N, DL> + Allocator<N, Const<DF>, Const<DF>> + Allocator<N, U1, Const<DF>> + Allocator<N, Const<DF>>
{
pub fn new_equal_likelihood(loc: SampleState<N, DL>) -> Self {
FastSLAM {
loc,
map: FeatureMap::new(),
}
}
pub fn observe_new(&mut self, feature: u32, obs_model: impl Fn(&OVector<N, DL>) -> Feature<N, Const<DF>>) {
let fmap: FeatureCondMap<N, Const<DF>> = self.loc.s.iter().map(|s| obs_model(s)).collect();
self.map.insert(feature, fmap);
}
pub fn observe<DZ: Dim>(&mut self, feature: u32,
innovation_model: impl Fn(&OVector<N, DL>, &OVector<N, Const<DF>>) -> (OVector<N, DZ>, CorrelatedNoise<N, DZ>),
hx: &OMatrix<N, DZ, Const<DF>>)
where DefaultAllocator: Allocator<N, U1, Const<DF>> +
Allocator<N, DZ, DZ> + Allocator<N, DZ, Const<DF>> + Allocator<N, Const<DF>, DZ> + Allocator<N, DZ>
{
let afm = self.map.get_mut(&feature).unwrap();
let nsamples = self.loc.s.len();
for si in 0..nsamples {
let m1 = &mut afm[si];
let loc = &self.loc.s[si];
let (innov, noise) = innovation_model(loc, &m1.x);
let mut cov = noise.Q.clone();
cov.quadform_tr(N::one(), hx, &m1.X, N::one());
let s_cholesky = cov.clone().cholesky().unwrap();
let sinv = s_cholesky.inverse();
let sinv_diagonal = s_cholesky.l_dirty().iter().step_by(innov.nrows()+1);
let determinate_sinv = sinv_diagonal.fold(N::one(), |prod: N, n: &N| prod * *n).to_f32().unwrap();
let logl = innov.dot(&(&sinv * &innov)).to_f32().unwrap();
self.loc.w[si] *= (logl.exp() * determinate_sinv).powf(-0.5);
let w = &m1.X * hx.transpose() * &sinv;
m1.x += &w * &innov;
m1.X.quadform_tr(-N::one(), &w, &cov, N::one());
}
}
pub fn forget(&mut self, feature: u32) -> Option<FeatureCondMap<N, Const<DF>>>
{
self.map.remove(&feature)
}
pub fn update_resample(&mut self, resampler: &mut bayes_estimate::estimators::sir::Resampler,
roughener: &mut sir::Roughener<N, DL>) -> Result<(u32, f32), &'static str>
{
let (resamples, unqiue, lcond) = resampler(&mut self.loc.w, &mut self.loc.rng)?;
sir::live_samples(&mut self.loc.s, &resamples);
self.loc.w.fill(1.);
let nsamples = self.loc.s.len();
for (_feature, fm) in self.map.iter_mut() {
let mut fmr = FeatureCondMap::with_capacity(nsamples);
for fmi in fm.iter().enumerate() {
for _res in 0..resamples[fmi.0] {
fmr.push(fmi.1.clone());
}
}
*fm = fmr;
}
roughener(&mut self.loc.s, &mut self.loc.rng);
Ok((unqiue, lcond))
}
fn feature_statistics(&self, kstat: &mut KalmanState<N, Dynamic>,
fs: usize, fm: &FeatureCondMap<N, Const<DF>>,
fi: &mut dyn Iterator<Item = &FeatureCondMap<N, Const<DF>>>)
{
let nl = self.loc.s.first().unwrap().nrows();
let nsamples = N::from_usize(self.loc.s.len()).unwrap();
let mean_f = fm.iter().map(|f| &f.x).sum::<OVector<N, Const<DF>>>() / nsamples;
kstat.x.fixed_rows_mut::<DF>(fs).copy_from(&mean_f);
let nf = mean_f.shape_generic().0;
let mut var_f = OMatrix::zeros_generic(nf, nf);
for fp in fm.iter() {
let xx = &fp.x - &mean_f;
var_f += &fp.X + &xx * xx.transpose();
}
var_f /= nsamples;
kstat.X.fixed_slice_mut::<DF,DF>(fs,fs).copy_from(&var_f);
for ls in 0..nl {
let mut cov = OVector::zeros_generic(nf, Const::<1>);
let mean_si = kstat.x[ls];
for fp in fm.iter().enumerate() {
cov += (&fp.1.x - &mean_f) * (self.loc.s[fp.0][ls] - mean_si);
}
cov /= nsamples;
kstat.X.fixed_slice_mut::<DF, 1>(ls, fs).copy_from(&cov);
}
let mut fjs = nl;
for fj in fi {
let mut cov = OMatrix::zeros_generic(nf, nf);
let mut fpj = fj.iter();
let mean_fi = kstat.x.fixed_rows::<DF>(fjs);
for fp in fm.iter() {
cov += (&fp.x - &mean_f) * (&fpj.next().unwrap().x - &mean_fi).transpose();
}
cov /= nsamples as N;
kstat.X.fixed_slice_mut::<DF, DF>(fjs, fs).copy_from(&cov);
fjs += DF;
}
}
pub fn statistics_compressed(&self, kstat: &mut KalmanState<N, Dynamic>)
where DefaultAllocator: Allocator<N, U1, DL>
{
let nl = self.loc.s.first().unwrap().shape_generic().0;
assert!(nl.value() + self.map.len() <= kstat.x.nrows(), "kstat to small to hold location and features");
kstat.x.fill(N::zero());
kstat.X.fill(N::zero());
let loc_state = KalmanEstimator::<N, DL>::kalman_state(&self.loc).unwrap();
kstat.x.rows_generic_mut(0,nl).copy_from(&loc_state.x);
kstat.X.generic_slice_mut((0, 0), (nl,nl)).copy_from(&loc_state.X);
let mut fs = nl.value();
for f in self.map.iter() {
let mut until_fi = self.map.iter().take_while(|it| {it.0 != f.0}).map(|it| {it.1});
self.feature_statistics(kstat, fs, f.1, &mut until_fi);
fs += DF;
}
kstat.X.fill_lower_triangle_with_upper_triangle();
}
pub fn statistics_sparse(&self, kstat: &mut KalmanState<N, Dynamic>)
where DefaultAllocator: Allocator<N, U1, DL>
{
let nl = self.loc.s.first().unwrap().shape_generic().0;
assert!(nl.value() + self.map.len() <= kstat.x.nrows(), "kstat to small to hold location and features");
kstat.x.fill(N::zero());
kstat.X.fill(N::zero());
let loc_state = KalmanEstimator::<N,DL>::kalman_state(&self.loc).unwrap();
kstat.x.rows_generic_mut(0,nl).copy_from(&loc_state.x);
kstat.X.generic_slice_mut((0, 0), (nl,nl)).copy_from(&loc_state.X);
let mut orderd_features = self.map.iter().map(|m| { *m.0 }).collect::<Vec<_>>();
orderd_features.sort();
for fi in orderd_features.iter().cloned() {
let fs = nl.value() + DF * fi as usize;
let mut until_fi = orderd_features.iter().take_while(|it| {**it != fi}).map(|it| {self.map.get(it).unwrap()});
self.feature_statistics(kstat, fs, self.map.get(&fi).unwrap(), &mut until_fi);
}
kstat.X.fill_lower_triangle_with_upper_triangle();
}
}