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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
use std::collections::BTreeMap;

use crate::result::CompilerResult;
use crate::test_binary::{SensorAction, SensorInstr};
use crate::test_descriptor::ast::{
    SensorBound, SensorBoundNumeric, SensorConstraint, SensorStatement,
};
use crate::test_descriptor::concrete_test::ConcreteTest;

/// Timeline of all sensor constraints over the whole test
/// endpoints vector gives the time window where the constraints
/// in the corresponding constraints array are active
/// instantaneous sensor checks are indicated by two adjacent endpoints that are equal
/// `endpoints[0]` gives the start and `endpoints[1]` gives the end time
/// for all sensor constraints in `constraints[0]`
#[derive(PartialEq, Debug)]
pub struct SensorsTimeline {
    pub sensor_timelines: BTreeMap<String, SensorTimeline>,
}

#[derive(PartialEq, Debug)]
pub struct SensorTimeline {
    // Time endpoints of sensor constraints
    pub endpoints: Vec<u32>,
    // Sensor constraints between two endpoints
    pub range_constraints: Vec<Vec<SensorConstraint>>,
    // Instantaneous sensor constraints at a single endpoint
    pub endpoint_constraints: Vec<Vec<SensorConstraint>>,
}

impl SensorsTimeline {
    pub fn new() -> Self {
        SensorsTimeline {
            sensor_timelines: BTreeMap::new(),
        }
    }

    pub fn add_sensor_statement(&mut self, statement: &SensorStatement) -> CompilerResult<()> {
        let statement_start_time = statement.time.get_start() as u32;
        let statement_end_time = statement.time.get_end() as u32;

        if statement_start_time == statement_end_time {
            self.add_endpoint_constraints(statement_start_time, statement.constraints.clone())
        } else {
            self.add_range_constraints(
                statement_start_time,
                statement_end_time,
                statement.constraints.clone(),
            )
        }
    }

    /// Adds all provided sensor constraints into the sensor timeline
    /// with the given start and end time and inserts endpoints if necessary
    fn add_range_constraints(
        &mut self,
        statement_start_time: u32,
        statement_end_time: u32,
        constraints: Vec<SensorConstraint>,
    ) -> CompilerResult<()> {
        let mut res =
            CompilerResult::status_only("Add range sensor constraints to sensor timeline");

        for sensor_constraint in &constraints {
            if !self.sensor_timelines.contains_key(&sensor_constraint.id) {
                self.sensor_timelines
                    .insert(sensor_constraint.id.clone(), SensorTimeline::new());
            }

            let sensor = check!(
                res,
                self.sensor_timelines.get_mut(&sensor_constraint.id),
                "Sensor entry in sensor_timelines not found"
            );
            sensor.add_sensor_range(statement_start_time, statement_end_time, sensor_constraint);
        }

        res
    }

    fn add_endpoint_constraints(
        &mut self,
        statement_time: u32,
        constraints: Vec<SensorConstraint>,
    ) -> CompilerResult<()> {
        let mut res =
            CompilerResult::status_only("Add endpoint sensor constraints to sensor timeline");

        // check if timeline exists for sensors in constraints
        // call add_sensor_instant in corresponding timeline

        for sensor_constraint in &constraints {
            if !self.sensor_timelines.contains_key(&sensor_constraint.id) {
                self.sensor_timelines
                    .insert(sensor_constraint.id.clone(), SensorTimeline::new());
            }

            let sensor = check!(
                res,
                self.sensor_timelines.get_mut(&sensor_constraint.id),
                "Sensor entry in sensor_timelines not found"
            );
            sensor.add_sensor_instant(statement_time, sensor_constraint);
        }

        res
    }

    pub fn to_instrs(
        &mut self,
        concrete: &ConcreteTest,
    ) -> CompilerResult<Vec<(u32, SensorInstr)>> {
        let mut res = CompilerResult::new("Convert sensors timeline into a vector of SensorInstr");
        let mut sensor_instructions: Vec<(u32, SensorInstr)> = Vec::new();
        // Vector of times used for binary search for inserting range constraints.
        let mut times: Vec<u32> = Vec::new();
        // Convert instantaneous sensor constraints into is_now_in sensor instructions

        // Convert all instantaneous constraints at time `min_endpoint` from all timelines
        for (_, timeline) in self.sensor_timelines.iter_mut() {
            for (idx, constraints_vec) in timeline.endpoint_constraints.iter().enumerate() {
                let time = timeline.endpoints[idx];
                for constraint in constraints_vec {
                    let time_inst_tuple = (
                        time,
                        check!(
                            res,
                            SensorInstr::try_from(concrete, &constraint, SensorAction::is_now_in)
                        ),
                    );

                    match times.binary_search(&time) {
                        // Do nothing to times because this time already exists in the time vec
                        // immediately insert the sensor instructin
                        Ok(time_idx) => {
                            times.insert(time_idx, time);
                            sensor_instructions.insert(time_idx, time_inst_tuple);
                        }
                        // This time doesn't exist, so we need to insert it first
                        Err(time_idx) => {
                            match time_idx >= times.len() {
                                // The new index is at the end of times, so we must push to times and instructions
                                true => {
                                    times.push(time);
                                    sensor_instructions.push(time_inst_tuple);
                                }
                                // The new index is not at the end, so we insert into times and instructions
                                false => {
                                    times.insert(time_idx, time);
                                    sensor_instructions.insert(time_idx, time_inst_tuple);
                                }
                            }
                        }
                    };
                }
            }

            for (idx, constraints_vec) in timeline.range_constraints.iter().enumerate() {
                for constraint in constraints_vec {
                    let start_time = timeline.endpoints[idx];
                    let stop_time = timeline.endpoints[idx + 1];
                    let start_inst_tuple = (
                        start_time,
                        check!(
                            res,
                            SensorInstr::try_from(
                                concrete,
                                constraint,
                                SensorAction::start_check_in
                            )
                        ),
                    );
                    let stop_inst_tuple = (
                        stop_time,
                        check!(
                            res,
                            SensorInstr::try_from(concrete, constraint, SensorAction::stop_check)
                        ),
                    );
                    match times.binary_search(&start_time) {
                        // Do nothing to times because this time already exists in the time vec
                        // immediately insert the sensor instructin
                        Ok(start_idx) => {
                            times.insert(start_idx, start_time);
                            sensor_instructions.insert(start_idx, start_inst_tuple);
                        }
                        // This time doesn't exist, so we need to insert it first
                        Err(start_idx) => {
                            match start_idx >= times.len() {
                                // The new index is at the end of times, so we must push to times and instructions
                                true => {
                                    times.push(start_time);
                                    sensor_instructions.push(start_inst_tuple);
                                }
                                // The new index is not at the end, so we insert into times and instructions
                                false => {
                                    times.insert(start_idx, start_time);
                                    sensor_instructions.insert(start_idx, start_inst_tuple);
                                }
                            }
                        }
                    };

                    match times.binary_search(&stop_time) {
                        // Do nothing to times because this time already exists in the time vec
                        // immediately insert the sensor instructin
                        Ok(stop_idx) => {
                            times.insert(stop_idx, stop_time);
                            sensor_instructions.insert(stop_idx, stop_inst_tuple);
                        }
                        // This time doesn't exist, so we need to insert it first
                        Err(stop_idx) => {
                            match stop_idx >= times.len() {
                                // The new index is at the end of times, so we must push to times and instructions
                                true => {
                                    times.push(stop_time);
                                    sensor_instructions.push(stop_inst_tuple);
                                }
                                // The new index is not at the end, so we insert into times and instructions
                                false => {
                                    times.insert(stop_idx, stop_time);
                                    sensor_instructions.insert(stop_idx, stop_inst_tuple);
                                }
                            }
                        }
                    };
                }
            }
        }

        res.with_value(sensor_instructions)
    }
}

impl SensorTimeline {
    pub fn new() -> Self {
        SensorTimeline {
            // Initial endpoints are 0 to signify start of timeline
            // and the u32 max value to signify end of timeline
            endpoints: vec![0, std::u32::MAX],
            range_constraints: vec![Vec::new()],
            endpoint_constraints: vec![Vec::new(), Vec::new()],
        }
    }

    /// Adds all provided sensor constraint into the sensor timeline
    /// with the given start and end time and inserts endpoints if necessary
    pub fn add_sensor_range(
        &mut self,
        statement_start_time: u32,
        statement_end_time: u32,
        constraint: &SensorConstraint,
    ) -> CompilerResult<()> {
        let res = CompilerResult::status_only("Add range sensor constraint to sensor timeline");

        let range_start_idx = match self.endpoints.binary_search(&statement_start_time) {
            Ok(exact_idx) => exact_idx,
            Err(one_above_idx) => {
                self.split_range(one_above_idx, statement_start_time);
                one_above_idx
            }
        };

        let range_end_idx = match self.endpoints.binary_search(&statement_end_time) {
            Ok(exact_idx) => exact_idx,
            Err(one_above_idx) => {
                self.split_range(one_above_idx, statement_end_time);
                one_above_idx
            }
        };

        // Add all constraints in sensor statement to constraint vectors
        // between range_start_idx - 1 and range_end.idx - 1
        for idx in range_start_idx..range_end_idx {
            self.range_constraints[idx].push(constraint.clone());
        }

        res
    }

    /// Adds all provided sensor constraints into the sensor timeline
    /// at the given time and inserts an endpoint if necessary
    fn add_sensor_instant(
        &mut self,
        statement_time: u32,
        constraint: &SensorConstraint,
    ) -> CompilerResult<()> {
        let res = CompilerResult::status_only("Add instant sensor constraints to sensor timeline");

        let range_start_idx = match self.endpoints.binary_search(&statement_time) {
            Ok(exact_idx) => exact_idx,
            Err(one_above_idx) => {
                self.split_range(one_above_idx, statement_time);
                one_above_idx
            }
        };
        self.endpoint_constraints[range_start_idx].push(constraint.clone());

        res
    }

    /// Splits a range between two timeline endpoints by inserting the given time_of_split
    /// into the endpoints vector at idx_to_split. Clones the range constraints for the
    /// range that was split, so they exist on both sides of the split.
    /// Empty endpoint constraints vec is inserted at idx_to_split.
    fn split_range(&mut self, idx_to_split: usize, time_of_split: u32) {
        //Insert end time
        self.endpoints.insert(idx_to_split, time_of_split);

        // Clone constraint vec at end_idx - 1 to end_idx
        // since we are inserting a new endpoint in the middle
        self.range_constraints.insert(
            idx_to_split,
            self.range_constraints[idx_to_split - 1].clone(),
        );
        // Insert empty endpoint constraints vector at idx_to_split
        // since we are inserting a new endpoint before
        self.endpoint_constraints.insert(idx_to_split, Vec::new())
    }

    /// Reduce sensor constraints throughout the sensor timeline
    /// to combine constraints active at the same time for the same sensor
    pub fn reduce(&mut self) -> CompilerResult<()> {
        let mut res = CompilerResult::status_only("Reduce sensor constraints throughout timeline");
        let mut new_range_constraints: Vec<Vec<SensorConstraint>> = Vec::new();
        let mut new_endpoint_constraints: Vec<Vec<SensorConstraint>> = Vec::new();

        // Iterate through every vec of sensor constraints
        for timeline_idx in 0..(self.endpoints.len()) {
            // Iterate through all endpoint constraints in this interval
            // endpoint constraints need to be combined with both endpoint and range constraints
            let mut reduced_constraint = self.endpoint_constraints[timeline_idx].get(0).cloned();

            // reduce with all endpoint constraints at this same time
            for constraint_idx in 1..(self.endpoint_constraints[timeline_idx].len()) {
                let cur_constraint = self.endpoint_constraints[timeline_idx]
                    .get(constraint_idx)
                    .cloned();

                reduced_constraint = Some(check!(
                    res,
                    self.reduce_two_constraints(reduced_constraint, cur_constraint)
                ));
            }

            // reduce with all range constraints at this time
            if let Some(mut new_endpoint_constraint) = reduced_constraint {
                // time is inclusive exclusive, so the range constraints that should be checked are the range that starts at this endpoint
                if let Some(range_constraints) = self.range_constraints.get(timeline_idx) {
                    // iterate over every range constraint at this time
                    for constraint_idx in 0..range_constraints.len() {
                        let cur_constraint = range_constraints.get(constraint_idx).cloned();

                        new_endpoint_constraint = check!(
                            res,
                            self.reduce_two_constraints(
                                Some(new_endpoint_constraint),
                                cur_constraint
                            )
                        );
                    }
                }

                new_endpoint_constraints.push(vec![new_endpoint_constraint]);
            }
            // if we didn't have any endpoint constraints push an empty vector
            else {
                new_endpoint_constraints.push(vec![]);
            }

            if timeline_idx != self.endpoints.len() - 1 {
                // Iterate through all range constraints in this interval
                // Range constraints need to be combined with other range constraints
                // There are only n - 1 range constraints so stop 1 before the last endpoint
                let mut reduced_constraint = self.range_constraints[timeline_idx].get(0).cloned();
                for constraint_idx in 1..(self.range_constraints[timeline_idx].len()) {
                    let cur_constraint = self.range_constraints[timeline_idx]
                        .get(constraint_idx)
                        .cloned();

                    reduced_constraint = Some(check!(
                        res,
                        self.reduce_two_constraints(reduced_constraint, cur_constraint)
                    ));
                }

                // Only add n - 1 range constraints
                if let Some(new_range_constraint) = reduced_constraint {
                    new_range_constraints.push(vec![new_range_constraint]);
                } else {
                    new_range_constraints.push(vec![]);
                }
            }
        }

        self.range_constraints = new_range_constraints;
        self.endpoint_constraints = new_endpoint_constraints;

        res
    }

    /// Reduce the two provided sensor constraints into a single sensor constraint
    /// or provide a compiler error
    fn reduce_two_constraints(
        &self,
        constraint_opt1: Option<SensorConstraint>,
        constraint_opt2: Option<SensorConstraint>,
    ) -> CompilerResult<SensorConstraint> {
        let mut res = CompilerResult::new("Reducing two sensor constraints");
        match (constraint_opt1, constraint_opt2) {
            (None, None) => {
                res.error("Tried to reduce an empty SensorConstraint value(s).");
                res
            }
            (Some(constraint1), None) => {
                res.set_value(constraint1);
                res
            }
            (None, Some(constraint2)) => {
                res.set_value(constraint2);
                res
            }
            (Some(constraint1), Some(constraint2)) => {
                // Ensure both constraints reference same abort
                if !constraint1.abort.eq(&constraint2.abort) {
                    // TODO instead of "see next message"
                    // combine the following two messages into a single codespan with two labels
                    res.error((constraint1.metadata, "See next message "));
                    res.error((
                        constraint2.metadata,
                        "Tried to reduce two sensor constraints with differing aborts",
                    ));
                }

                let numeric_bound1: &SensorBoundNumeric;
                let numeric_bound2: &SensorBoundNumeric;
                // Ensure both constraints have numeric bounds
                match (&constraint1.sensor_bound, &constraint2.sensor_bound) {
                    // If both constraints are numeric do nothing
                    (SensorBound::Numeric(bound1), SensorBound::Numeric(bound2)) => {
                        numeric_bound1 = bound1;
                        numeric_bound2 = bound2;
                    }
                    // In any other case return an error
                    _ => {
                        res.error((constraint1.metadata, "See next message"));
                        res.error((
                            constraint2.metadata,
                            "Tried to reduce two non-numeric constraints",
                        ));
                        return res;
                    }
                }

                let mut new_constraint = (constraint1).clone();
                let mut new_left: f64;
                let mut new_right: f64;

                // Reducing two sensor constraints is just making a new constraint
                // using the largest left value and the smallest right value.
                // Then checking the new right value is greater than the new left.

                // Use largest left value
                new_left = numeric_bound1.left;
                if numeric_bound2.left > numeric_bound1.left {
                    new_left = numeric_bound2.left;
                }

                // Use smallest right value
                new_right = numeric_bound1.right;
                if numeric_bound2.right < numeric_bound1.right {
                    new_right = numeric_bound2.right;
                }

                // If there was no overlap between both constraints
                if new_right <= new_left {
                    // TODO instead of "see next message"
                    // combine the following two messages into a single codespan with two labels
                    res.error((constraint1.metadata, "See next message"));
                    res.error((
                        constraint2.metadata,
                        "No overlap between two sensor constraints",
                    ));
                    return res;
                }

                let mut new_bound = numeric_bound1.clone();
                new_bound.left = new_left;
                new_bound.right = new_right;

                new_constraint.sensor_bound = SensorBound::Numeric(new_bound);
                res.set_value(new_constraint);
                res
            }
        }
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::result::diagnostic::Location;
    use crate::result::Status;
    use crate::test_descriptor::ast::SensorTime::{Instant, Interval};
    use crate::test_descriptor::ast::{SensorBound, SensorBoundNumeric, SensorConstraint};

    #[test]
    fn construct_sensor_timeline() {
        let empty_location = Location::from_raw(0, 0, 0);

        let constraint1 = SensorConstraint {
            id: "1".to_string(),
            sensor_bound: SensorBound::Numeric(SensorBoundNumeric {
                left: 20.0,
                right: 30.0,
                unit: "c".to_string(),
            }),
            abort: "abort1".to_string(),
            metadata: empty_location,
        };
        let constraint2 = SensorConstraint {
            id: "2".to_string(),
            sensor_bound: SensorBound::Numeric(SensorBoundNumeric {
                left: 30.0,
                right: 40.0,
                unit: "c".to_string(),
            }),
            abort: "abort1".to_string(),
            metadata: empty_location,
        };
        let endpoint_constraints: Vec<Vec<SensorConstraint>> = vec![vec![], vec![], vec![]];

        let range_constraints_one: Vec<Vec<SensorConstraint>> =
            vec![vec![constraint1.clone()], vec![]];

        let range_constraints_two: Vec<Vec<SensorConstraint>> =
            vec![vec![constraint2.clone()], vec![]];

        let statement1 = SensorStatement {
            time: Interval { start: 0, end: 1 },
            constraints: vec![constraint1.clone()],
            abort: "abort1".to_string(),
            metadata: empty_location,
        };
        let statement2 = SensorStatement {
            time: Interval { start: 0, end: 2 },
            constraints: vec![constraint2.clone()],
            abort: "abort1".to_string(),
            metadata: empty_location,
        };

        let endpoints_one: Vec<u32> = vec![0, 1, u32::MAX];
        let endpoints_two: Vec<u32> = vec![0, 2, u32::MAX];

        let simple_timeline_one = SensorTimeline {
            endpoints: endpoints_one,
            endpoint_constraints: endpoint_constraints.clone(),
            range_constraints: range_constraints_one,
        };

        let simple_timeline_two = SensorTimeline {
            endpoints: endpoints_two,
            endpoint_constraints,
            range_constraints: range_constraints_two,
        };

        let mut timeline_map = BTreeMap::new();
        timeline_map.insert("1".to_string(), simple_timeline_one);
        timeline_map.insert("2".to_string(), simple_timeline_two);

        let simple_timeline_wrap = SensorsTimeline {
            sensor_timelines: timeline_map,
        };

        let mut timeline_sensor = SensorsTimeline::new();
        timeline_sensor.add_sensor_statement(&statement1);
        timeline_sensor.add_sensor_statement(&statement2);
        assert_eq!(timeline_sensor, simple_timeline_wrap);
    }

    #[test]
    fn reduce_sensor_timeline() {
        let empty_location = Location::from_raw(0, 0, 0);

        let constraint1 = SensorConstraint {
            id: "1".to_string(),
            sensor_bound: SensorBound::Numeric(SensorBoundNumeric {
                left: 10.0,
                right: 30.0,
                unit: "c".to_string(),
            }),
            abort: "abort1".to_string(),
            metadata: empty_location,
        };
        let constraint2 = SensorConstraint {
            id: "1".to_string(),
            sensor_bound: SensorBound::Numeric(SensorBoundNumeric {
                left: 20.0,
                right: 40.0,
                unit: "c".to_string(),
            }),
            abort: "abort1".to_string(),
            metadata: empty_location,
        };
        let constraint3 = SensorConstraint {
            id: "2".to_string(),
            sensor_bound: SensorBound::Numeric(SensorBoundNumeric {
                left: 5.0,
                right: 10.0,
                unit: "c".to_string(),
            }),
            abort: "abort2".to_string(),
            metadata: empty_location,
        };
        let constraint4 = SensorConstraint {
            id: "1".to_string(),
            sensor_bound: SensorBound::Numeric(SensorBoundNumeric {
                left: 50.0,
                right: 60.0,
                unit: "c".to_string(),
            }),
            abort: "abort1".to_string(),
            metadata: empty_location,
        };
        let constraint_reduced = SensorConstraint {
            id: "1".to_string(),
            sensor_bound: SensorBound::Numeric(SensorBoundNumeric {
                left: 20.0,
                right: 30.0,
                unit: "c".to_string(),
            }),
            abort: "abort1".to_string(),
            metadata: empty_location,
        };

        let endpoint_constraints_reduced: Vec<Vec<SensorConstraint>> =
            vec![vec![], vec![], vec![], vec![]];
        let endpoint_constraints_two: Vec<Vec<SensorConstraint>> = vec![vec![], vec![], vec![]];

        let range_constraints_reduced: Vec<Vec<SensorConstraint>> = vec![
            vec![constraint_reduced.clone()],
            vec![constraint2.clone()],
            vec![],
        ];

        let range_constraints_two: Vec<Vec<SensorConstraint>> =
            vec![vec![constraint3.clone()], vec![]];

        let statement1 = SensorStatement {
            time: Interval { start: 0, end: 1 },
            constraints: vec![constraint1.clone()],
            abort: "abort1".to_string(),
            metadata: empty_location,
        };
        let statement2 = SensorStatement {
            time: Interval { start: 0, end: 2 },
            constraints: vec![constraint2.clone()],
            abort: "abort1".to_string(),
            metadata: empty_location,
        };
        let statement3 = SensorStatement {
            time: Interval { start: 0, end: 3 },
            constraints: vec![constraint3.clone()],
            abort: "abort2".to_string(),
            metadata: empty_location,
        };
        let statement4 = SensorStatement {
            time: Instant { time: 1 },
            constraints: vec![constraint4.clone()],
            abort: "abort1".to_string(),
            metadata: empty_location,
        };

        let endpoints_one: Vec<u32> = vec![0, 1, 2, u32::MAX];
        let endpoints_two: Vec<u32> = vec![0, 3, u32::MAX];

        let simple_timeline_reduced = SensorTimeline {
            endpoints: endpoints_one,
            endpoint_constraints: endpoint_constraints_reduced,
            range_constraints: range_constraints_reduced,
        };

        let simple_timeline_two = SensorTimeline {
            endpoints: endpoints_two,
            endpoint_constraints: endpoint_constraints_two,
            range_constraints: range_constraints_two,
        };

        // Expected
        let mut simple_timeline_map = BTreeMap::new();
        simple_timeline_map.insert("1".to_string(), simple_timeline_reduced);
        simple_timeline_map.insert("2".to_string(), simple_timeline_two);

        let simple_timeline_wrap = SensorsTimeline {
            sensor_timelines: simple_timeline_map,
        };

        // Actual
        let mut timeline_sensor = SensorsTimeline::new();
        timeline_sensor.add_sensor_statement(&statement1);
        timeline_sensor.add_sensor_statement(&statement2);
        timeline_sensor.add_sensor_statement(&statement3);

        for (_, timeline) in timeline_sensor.sensor_timelines.iter_mut() {
            timeline.reduce();
        }
        assert_eq!(simple_timeline_wrap, timeline_sensor);

        // Add statement4 and ensure it fails
        timeline_sensor.add_sensor_statement(&statement4);
        let res_fail = timeline_sensor
            .sensor_timelines
            .get_mut("1")
            .unwrap()
            .reduce();
        assert_eq!(res_fail.get_status(), Status::Failed);
    }

    #[test]
    fn reduce_constraints() {
        let empty_location = Location::from_raw(0, 0, 0);

        let constraint1 = SensorConstraint {
            id: "1".to_string(),
            sensor_bound: SensorBound::Numeric(SensorBoundNumeric {
                left: 10.0,
                right: 30.0,
                unit: "c".to_string(),
            }),
            abort: "abort1".to_string(),
            metadata: empty_location,
        };
        let constraint2 = SensorConstraint {
            id: "1".to_string(),
            sensor_bound: SensorBound::Numeric(SensorBoundNumeric {
                left: 20.0,
                right: 40.0,
                unit: "c".to_string(),
            }),
            abort: "abort1".to_string(),
            metadata: empty_location,
        };
        let constraint_no_overlap = SensorConstraint {
            id: "1".to_string(),
            sensor_bound: SensorBound::Numeric(SensorBoundNumeric {
                left: 50.0,
                right: 51.0,
                unit: "c".to_string(),
            }),
            abort: "abort1".to_string(),
            metadata: empty_location,
        };

        let constraint3 = SensorConstraint {
            id: "1".to_string(),
            sensor_bound: SensorBound::Numeric(SensorBoundNumeric {
                left: 20.0,
                right: 30.0,
                unit: "c".to_string(),
            }),
            abort: "abort1".to_string(),
            metadata: empty_location,
        };
        let timeline: SensorTimeline = SensorTimeline {
            endpoints: vec![],
            range_constraints: vec![],
            endpoint_constraints: vec![],
        };

        let res = timeline.reduce_two_constraints(Some(constraint1.clone()), Some(constraint2));
        let res_fail =
            timeline.reduce_two_constraints(Some(constraint1), Some(constraint_no_overlap));

        assert_eq!(constraint3, res.to_option().unwrap());
        assert_eq!(res_fail.get_status(), Status::Failed);
    }
}