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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! M1 and M2 segments center of pressure, forces and moments

use crate::Vector;
use crate::{Exertion, Monitors, MonitorsLoader};
#[cfg(feature = "plot")]
use plotters::prelude::*;
use std::{
    collections::{BTreeMap, VecDeque},
    fs::File,
    path::Path,
};

/// Mirror data loader
pub struct MirrorLoader<P: AsRef<Path>> {
    mirror: Mirror,
    path: P,
    time_range: (f64, f64),
    net_force: bool,
}
impl<P: AsRef<Path>> MirrorLoader<P> {
    fn new(mirror: Mirror, path: P) -> Self {
        MirrorLoader {
            mirror,
            path,
            time_range: (0f64, f64::INFINITY),
            net_force: false,
        }
    }
    pub fn start_time(self, time: f64) -> Self {
        Self {
            time_range: (time, self.time_range.1),
            ..self
        }
    }
    pub fn end_time(self, time: f64) -> Self {
        Self {
            time_range: (self.time_range.0, time),
            ..self
        }
    }
    pub fn net_force(self) -> Self {
        Self {
            net_force: true,
            ..self
        }
    }
    pub fn load(self) -> Result<Mirror, Box<dyn std::error::Error>> {
        let mut mirror = self.mirror;
        let (filename, time, force) = match &mut mirror {
            Mirror::M1 { time, force } => ("center_of_pressure.csv", time, force),
            Mirror::M2 { time, force } => ("M2_segments_force.csv", time, force),
        };
        let path = Path::new(self.path.as_ref());
        if let Ok(csv_file) = File::open(&path.join(filename)) {
            let mut rdr = csv::Reader::from_reader(csv_file);
            for result in rdr.deserialize() {
                let record: (f64, Vec<([f64; 3], ([f64; 3], [f64; 3]))>) = result?;
                let t = record.0;
                if t < self.time_range.0 - 1. / 40. || t > self.time_range.1 + 1. / 40. {
                    continue;
                };
                let mut record_iter = record.1.into_iter();
                if let Some(t_b) = time.back() {
                    if t >= *t_b {
                        time.push_back(t);
                        for fm in force.values_mut() {
                            fm.push_back(record_iter.next().unwrap().into())
                        }
                    } else {
                        if let Some(index) = time.iter().rposition(|&x| x < t) {
                            time.insert(index + 1, t);
                            for fm in force.values_mut() {
                                fm.insert(index + 1, record_iter.next().unwrap().into())
                            }
                        } else {
                            time.push_front(t);
                            for fm in force.values_mut() {
                                fm.push_front(record_iter.next().unwrap().into())
                            }
                        }
                    }
                } else {
                    time.push_back(t);
                    for fm in force.values_mut() {
                        fm.push_back(record_iter.next().unwrap().into())
                    }
                }
            }
            if self.net_force {
                if let Mirror::M1 { time, force } = &mut mirror {
                    let ts = *time.front().unwrap();
                    let te = *time.back().unwrap();
                    let monitors = MonitorsLoader::<2021>::default()
                        .data_path(path)
                        .header_filter("M1cell".to_string())
                        .start_time(ts)
                        .end_time(te)
                        .load()?;
                    let m1_cell = &monitors.forces_and_moments["M1cell"];
                    assert_eq!(
                        time.len(),
                        m1_cell.len(),
                        "{:?} {:?}/{:?}: M1 segments and M1 cell # of sample do not match",
                        (ts, te),
                        (monitors.time[0], monitors.time.last().unwrap()),
                        path
                    );
                    for v in force.values_mut() {
                        for (e, cell) in v.iter_mut().zip(m1_cell) {
                            let mut f = &mut e.force;
                            f += &(&cell.force / 7f64).unwrap();
                            let mut m = &mut e.moment;
                            m += &(&cell.moment / 7f64).unwrap();
                        }
                    }
                }
            }
            Ok(mirror)
        } else {
            Err(format!("Cannot open {:?}", &path).into())
        }
    }
}

/// Mirror type
#[derive(Debug)]
pub enum Mirror {
    M1 {
        time: VecDeque<f64>,
        force: BTreeMap<String, VecDeque<Exertion>>,
    },
    M2 {
        time: VecDeque<f64>,
        force: BTreeMap<String, VecDeque<Exertion>>,
    },
}
impl Mirror {
    pub fn m1<P: AsRef<Path>>(path: P) -> MirrorLoader<P> {
        let mut force: BTreeMap<String, VecDeque<Exertion>> = BTreeMap::new();
        (1..=7).for_each(|k| {
            force.entry(format!("S{}", k)).or_default();
        });
        MirrorLoader::new(
            Mirror::M1 {
                time: VecDeque::new(),
                force,
            },
            path,
        )
    }
    pub fn m2<P: AsRef<Path>>(path: P) -> MirrorLoader<P> {
        let mut force: BTreeMap<String, VecDeque<Exertion>> = BTreeMap::new();
        (1..=7).for_each(|k| {
            force.entry(format!("S{}", k)).or_default();
        });
        MirrorLoader::new(
            Mirror::M2 {
                time: VecDeque::new(),
                force,
            },
            path,
        )
    }
    /// Keeps only the last `period` seconds of the monitors
    pub fn keep_last(&mut self, period: usize) -> &mut Self {
        let i = self.len() - period * crate::FORCE_SAMPLING_FREQUENCY as usize;
        let _: Vec<_> = self.time_mut().drain(..i).collect();
        for value in self.exertion_mut() {
            let _: Vec<_> = value.drain(..i).collect();
        }
        self
    }
    pub fn summary(&self) {
        let (mirror, time, force) = match self {
            Mirror::M1 { time, force } => ("M1", time, force),
            Mirror::M2 { time, force } => ("M2", time, force),
        };
        println!("{} SUMMARY:", mirror);
        println!(" - # of records: {}", time.len());
        println!(
            " - time range: [{:8.3}-{:8.3}]s",
            time.front().unwrap(),
            time.back().unwrap()
        );
        println!("    {:^16}: [{:^12}], [{:^12}])", "ELEMENT", "MEAN", "STD");
        for (key, value) in force.iter() {
            let force: Vec<Vector> = value.iter().map(|e| e.force.clone()).collect();
            Monitors::display(key, &force);
        }
    }
    pub fn len(&self) -> usize {
        self.time().len()
    }
    pub fn time(&self) -> &VecDeque<f64> {
        match self {
            Mirror::M1 { time, .. } => time,
            Mirror::M2 { time, .. } => time,
        }
    }
    pub fn time_mut(&mut self) -> &mut VecDeque<f64> {
        match self {
            Mirror::M1 { time, .. } => time,
            Mirror::M2 { time, .. } => time,
        }
    }
    pub fn forces_and_moments(&self) -> &BTreeMap<String, VecDeque<Exertion>> {
        match self {
            Mirror::M1 { force, .. } => force,
            Mirror::M2 { force, .. } => force,
        }
    }
    pub fn forces_and_moments_mut(&mut self) -> &mut BTreeMap<String, VecDeque<Exertion>> {
        match self {
            Mirror::M1 { force, .. } => force,
            Mirror::M2 { force, .. } => force,
        }
    }
    pub fn exertion(&self) -> impl Iterator<Item = &VecDeque<Exertion>> {
        match self {
            Mirror::M1 { force, .. } => force.values(),
            Mirror::M2 { force, .. } => force.values(),
        }
    }
    pub fn exertion_mut(&mut self) -> impl Iterator<Item = &mut VecDeque<Exertion>> {
        match self {
            Mirror::M1 { force, .. } => force.values_mut(),
            Mirror::M2 { force, .. } => force.values_mut(),
        }
    }
    /// Return a latex table with force monitors summary
    pub fn force_latex_table(&self, stats_duration: f64) -> Option<String> {
        let max_value = |x: &[f64]| x.iter().cloned().fold(std::f64::NEG_INFINITY, f64::max);
        let min_value = |x: &[f64]| x.iter().cloned().fold(std::f64::INFINITY, f64::min);
        let minmax = |x: &[f64]| (min_value(x), max_value(x));
        let stats = |x: &[f64]| {
            let n = x.len() as f64;
            let mean = x.iter().sum::<f64>() / n;
            let std = (x.iter().map(|x| x - mean).fold(0f64, |s, x| s + x * x) / n).sqrt();
            (mean, std)
        };
        if self.forces_and_moments().is_empty() {
            None
        } else {
            let duration = self.time().back().unwrap();
            let time_filter: Vec<_> = self
                .time()
                .iter()
                .map(|t| t - duration + stats_duration - crate::FORCE_SAMPLING > 0f64)
                .collect();
            let data: Vec<_> = self
                .forces_and_moments()
                .iter()
                .map(|(key, value)| {
                    let force_magnitude: Option<Vec<f64>> = value
                        .iter()
                        .zip(time_filter.iter())
                        .filter(|(_, t)| **t)
                        .map(|(e, _)| e.force.magnitude())
                        .collect();
                    match force_magnitude {
                        Some(ref value) => {
                            let (mean, std) = stats(value);
                            let (min, max) = minmax(value);
                            format!(
                                " {:} & {:.3} & {:.3} & {:.3} & {:.3} \\\\",
                                key.replace("_", " "),
                                mean,
                                std,
                                min,
                                max
                            )
                        }
                        None => format!(" {:} \\\\", key.replace("_", " ")),
                    }
                })
                .collect();
            Some(data.join("\n"))
        }
    }
    /// Return a latex table with moment monitors summary
    pub fn moment_latex_table(&self, stats_duration: f64) -> Option<String> {
        let max_value = |x: &[f64]| x.iter().cloned().fold(std::f64::NEG_INFINITY, f64::max);
        let min_value = |x: &[f64]| x.iter().cloned().fold(std::f64::INFINITY, f64::min);
        let minmax = |x: &[f64]| (min_value(x), max_value(x));
        let stats = |x: &[f64]| {
            let n = x.len() as f64;
            let mean = x.iter().sum::<f64>() / n;
            let std = (x.iter().map(|x| x - mean).fold(0f64, |s, x| s + x * x) / n).sqrt();
            (mean, std)
        };
        if self.forces_and_moments().is_empty() {
            None
        } else {
            let duration = self.time().back().unwrap();
            let time_filter: Vec<_> = self
                .time()
                .iter()
                .map(|t| t - duration + stats_duration - crate::FORCE_SAMPLING > 0f64)
                .collect();
            let data: Vec<_> = self
                .forces_and_moments()
                .iter()
                .map(|(key, value)| {
                    let moment_magnitude: Option<Vec<f64>> = value
                        .iter()
                        .zip(time_filter.iter())
                        .filter(|(_, t)| **t)
                        .map(|(e, _)| e.moment.magnitude())
                        .collect();
                    match moment_magnitude {
                        Some(ref value) => {
                            let (mean, std) = stats(value);
                            let (min, max) = minmax(value);
                            format!(
                                " {:} & {:.3} & {:.3} & {:.3} & {:.3} \\\\",
                                key.replace("_", " "),
                                mean,
                                std,
                                min,
                                max
                            )
                        }
                        None => format!(" {:} \\\\", key.replace("_", " ")),
                    }
                })
                .collect();
            Some(data.join("\n"))
        }
    }
    #[cfg(feature = "plot")]
    pub fn plot_forces(&self, filename: Option<&str>) {
        if self.forces_and_moments().is_empty() {
            println!("Empty mirror");
            return;
        }

        let max_value = |x: &[f64]| -> f64 {
            x.iter()
                .cloned()
                .rev()
                .take(400 * 20)
                .fold(std::f64::NEG_INFINITY, f64::max)
        };
        let min_value = |x: &[f64]| -> f64 {
            x.iter()
                .cloned()
                .rev()
                .take(400 * 20)
                .fold(std::f64::INFINITY, f64::min)
        };

        let plot =
            BitMapBackend::new(filename.unwrap_or("FORCE.png"), (768, 512)).into_drawing_area();
        plot.fill(&WHITE).unwrap();

        let (min_values, max_values): (Vec<_>, Vec<_>) = self
            .forces_and_moments()
            .values()
            .map(|values| {
                let force_magnitude: Option<Vec<f64>> =
                    values.iter().map(|e| e.force.magnitude()).collect();
                (
                    min_value(force_magnitude.as_ref().unwrap()),
                    max_value(force_magnitude.as_ref().unwrap()),
                )
            })
            .unzip();
        let xrange = (*self.time().front().unwrap(), *self.time().back().unwrap());
        let minmax_padding = 0.1;
        let mut chart = ChartBuilder::on(&plot)
            .set_label_area_size(LabelAreaPosition::Left, 60)
            .set_label_area_size(LabelAreaPosition::Bottom, 40)
            .margin(10)
            .build_cartesian_2d(
                xrange.0..xrange.1 * (1. + 1e-2),
                min_value(&min_values) * (1. - minmax_padding)
                    ..max_value(&max_values) * (1. + minmax_padding),
            )
            .unwrap();
        chart
            .configure_mesh()
            .x_desc("Time [s]")
            .y_desc("Force [N]")
            .draw()
            .unwrap();

        let mut colors = colorous::TABLEAU10.iter().cycle();

        for (key, values) in self.forces_and_moments().iter() {
            let color = colors.next().unwrap();
            let rgb = RGBColor(color.r, color.g, color.b);
            chart
                .draw_series(LineSeries::new(
                    self.time()
                        .iter()
                        .zip(values.iter())
                        //.skip(10 * 20)
                        .map(|(&x, y)| (x, y.force.magnitude().unwrap())),
                    &rgb,
                ))
                .unwrap()
                .label(key)
                .legend(move |(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], &rgb));
        }
        chart
            .configure_series_labels()
            .border_style(&BLACK)
            .background_style(&WHITE.mix(0.8))
            .position(SeriesLabelPosition::UpperRight)
            .draw()
            .unwrap();
    }
    #[cfg(feature = "plot")]
    pub fn plot_moments(&self, filename: Option<&str>) {
        if self.forces_and_moments().is_empty() {
            println!("Empty mirror");
            return;
        }

        let max_value = |x: &[f64]| -> f64 {
            x.iter()
                .cloned()
                .rev()
                .take(400 * 20)
                .fold(std::f64::NEG_INFINITY, f64::max)
        };
        let min_value = |x: &[f64]| -> f64 {
            x.iter()
                .cloned()
                .rev()
                .take(400 * 20)
                .fold(std::f64::INFINITY, f64::min)
        };

        let plot =
            BitMapBackend::new(filename.unwrap_or("MOMENT.png"), (768, 512)).into_drawing_area();
        plot.fill(&WHITE).unwrap();

        let (min_values, max_values): (Vec<_>, Vec<_>) = self
            .forces_and_moments()
            .values()
            .map(|values| {
                let moment_magnitude: Option<Vec<f64>> =
                    values.iter().map(|e| e.moment.magnitude()).collect();
                (
                    min_value(moment_magnitude.as_ref().unwrap()),
                    max_value(moment_magnitude.as_ref().unwrap()),
                )
            })
            .unzip();
        let xrange = (*self.time().front().unwrap(), *self.time().back().unwrap());
        let minmax_padding = 0.1;
        let mut chart = ChartBuilder::on(&plot)
            .set_label_area_size(LabelAreaPosition::Left, 60)
            .set_label_area_size(LabelAreaPosition::Bottom, 40)
            .margin(10)
            .build_cartesian_2d(
                xrange.0..xrange.1 * (1. + 1e-2),
                min_value(&min_values) * (1. - minmax_padding)
                    ..max_value(&max_values) * (1. + minmax_padding),
            )
            .unwrap();
        chart
            .configure_mesh()
            .x_desc("Time [s]")
            .y_desc("Force [N]")
            .draw()
            .unwrap();

        let mut colors = colorous::TABLEAU10.iter().cycle();

        for (key, values) in self.forces_and_moments().iter() {
            let color = colors.next().unwrap();
            let rgb = RGBColor(color.r, color.g, color.b);
            chart
                .draw_series(LineSeries::new(
                    self.time()
                        .iter()
                        .zip(values.iter())
                        //.skip(10 * 20)
                        .map(|(&x, y)| (x, y.moment.magnitude().unwrap())),
                    &rgb,
                ))
                .unwrap()
                .label(key)
                .legend(move |(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], &rgb));
        }
        chart
            .configure_series_labels()
            .border_style(&BLACK)
            .background_style(&WHITE.mix(0.8))
            .position(SeriesLabelPosition::UpperRight)
            .draw()
            .unwrap();
    }
}