engeom 0.5.0

Library for working with geometry with a focus on engineering metrology applications.
Documentation
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
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
use crate::common::vec_f64::sort_and_dedup;
use crate::common::{DiscreteDomain, Interval};
use crate::func1::{Func1, Line1};
use crate::{Point2, Result};
use serde::{Deserialize, Serialize};
use std::iter::Zip;
use std::slice::Iter;

/// Represents a contiguous series of data points in a 2d plane where the x values go from
/// smallest to largest and the y values are associated with the x value at the same index.
/// TODO: Assert that x is always sorted
/// TODO: Assert that x and y are the same length
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Series1 {
    pub x: DiscreteDomain,
    pub y: Vec<f64>,
}

impl Series1 {
    // ===========================================================================================
    // Creation and Initialization
    // ===========================================================================================

    /// Creates a new series from a pair of vectors, one for x values and one for y values. The two
    /// vectors must be the same length, and the x values must be sorted from smallest to largest.
    pub fn new(x: DiscreteDomain, y: Vec<f64>) -> Self {
        Self { x, y }
    }

    /// Try to create a new series from a pair of vectors, one for x values and one for y values.
    /// If  the two vectors are not the same length, an error will be returned. If the x values are
    /// not sorted from smallest to largest, an error will be returned.
    ///
    /// # Arguments
    ///
    /// * `x`: a vector of x values, matched in order to the y values
    /// * `y`: a vector of y values, matched in order to the x values
    ///
    /// returns: Result<Series1, Box<dyn Error, Global>>
    ///
    /// # Examples
    ///
    /// ```
    ///
    /// ```
    pub fn try_new(x: Vec<f64>, y: Vec<f64>) -> Result<Self> {
        if x.len() != y.len() {
            Err("x and y must be the same length".into())
        } else {
            Ok(Self {
                x: DiscreteDomain::try_from(x)?,
                y,
            })
        }
    }

    /// Create a new series from a `Func1` by sampling it at a series of domain values and
    /// combining the result into a series.
    ///
    /// # Arguments
    ///
    /// * `f`:
    /// * `xs`:
    ///
    /// returns: Series1
    ///
    /// # Examples
    ///
    /// ```
    ///
    /// ```
    pub fn from_sampled(f: &dyn Func1, xs: DiscreteDomain) -> Self {
        let ys = f.fs(&xs);
        Self::new(xs, ys)
    }

    // ===========================================================================================
    // X and Y Limits
    // ===========================================================================================

    /// Returns the smallest x value in the series, which also happens to be the first x value
    pub fn x_min(&self) -> f64 {
        self.x[0]
    }

    /// Finds and returns the largest x value in the series, which also happens to be last x value
    pub fn x_max(&self) -> f64 {
        self.x[self.x.len() - 1]
    }

    /// Finds and returns the smallest y value in the series
    pub fn y_min(&self) -> f64 {
        *self
            .y
            .iter()
            .min_by(|a, b| a.partial_cmp(b).unwrap())
            .unwrap()
    }

    /// Finds and returns the largest y value in the series
    pub fn y_max(&self) -> f64 {
        *self
            .y
            .iter()
            .max_by(|a, b| a.partial_cmp(b).unwrap())
            .unwrap()
    }

    // ===========================================================================================
    // Value lookups and interpolation
    // ===========================================================================================
    /// Return the interpolated y value at x. If the x value is outside the range of the series,
    /// NAN will be returned.
    pub fn interpolate(&self, x: f64) -> f64 {
        if x < self.x[0] || x > self.x[self.x.len() - 1] {
            f64::NAN
        } else {
            let search_result = self.x.binary_search_by(|v| v.partial_cmp(&x).unwrap());
            match search_result {
                Ok(actual_index) => self.y[actual_index],
                Err(index_after) => {
                    if index_after == 0 {
                        panic!("This should never happen")
                    } else {
                        let x0 = self.x[index_after - 1];
                        let x1 = self.x[index_after];
                        let y0 = self.y[index_after - 1];
                        let y1 = self.y[index_after];
                        let m = (y1 - y0) / (x1 - x0);
                        y0 + m * (x - x0)
                    }
                }
            }
        }
    }

    /// Return the y value at index i. If i is outside the range of the series, None will be
    /// returned instead.
    fn y_at_index(&self, i: i32) -> Option<f64> {
        if i < 0 || i >= self.y.len() as i32 {
            None
        } else {
            Some(self.y[i as usize])
        }
    }

    /// Returns a zipped iterator over the x and y values of the series
    ///
    /// # Examples
    ///
    /// ```
    /// use engeom::Series1;
    /// let series = Series1::try_new(vec![0.0, 1.0, 2.0], vec![0.0, 1.0, 2.0])
    ///     .expect("Failed to create series");
    /// for (x, y) in series.xys() {
    ///    println!("x: {}, y: {}", x, y);
    /// }
    /// ```
    pub fn xys(&self) -> Zip<Iter<'_, f64>, Iter<'_, f64>> {
        self.x.values().iter().zip(self.y.iter())
    }
    // ===========================================================================================
    // Transformation operations
    // ===========================================================================================

    pub fn add(&self, rhs: &impl Func1) -> Self {
        self.add_sign(rhs, true)
    }

    pub fn sub(&self, rhs: &impl Func1) -> Self {
        self.add_sign(rhs, false)
    }

    fn add_sign(&self, rhs: &impl Func1, add: bool) -> Self {
        let mut ys = Vec::new();
        let signum = if add { 1.0 } else { -1.0 };

        if let Some(rhs_xs) = rhs.xs() {
            let mut all_xs = [self.x.to_vec(), rhs_xs.to_vec()].concat();
            sort_and_dedup(&mut all_xs, Some(1e-10));
            let new_xs = DiscreteDomain::try_from(all_xs).unwrap();
            for x in new_xs.values() {
                ys.push(f_or_zero(&self, *x) + signum * f_or_zero(rhs, *x));
            }
            Self::new(new_xs, ys)
        } else {
            for (x, y) in self.x.iter().zip(self.y.iter()) {
                ys.push(y + signum * f_or_zero(rhs, *x));
            }
            Self::new(self.x.clone(), ys)
        }
    }

    /// Returns a new series where the x values are the same as the original series, but the y
    /// values are the absolute value of the original y values
    pub fn abs(&self) -> Self {
        let ys = self.y.iter().map(|v| v.abs()).collect::<Vec<f64>>();
        Self::new(self.x.clone(), ys)
    }

    /// Return a new series with the x values scaled by `scale_x` and the y values scaled by
    /// `scale_y`
    pub fn scaled_by(&self, scale_x: f64, scale_y: f64) -> Self {
        let xs = self
            .x
            .values()
            .iter()
            .map(|v| v * scale_x)
            .collect::<Vec<f64>>();
        let ys = self.y.iter().map(|v| v * scale_y).collect::<Vec<f64>>();

        if scale_x < 0.0 {
            let new_xs =
                DiscreteDomain::try_from(xs.into_iter().rev().collect::<Vec<_>>()).unwrap();
            Self::new(new_xs, ys.into_iter().rev().collect())
        } else {
            let new_xs = DiscreteDomain::try_from(xs).unwrap();
            Self::new(new_xs, ys)
        }
    }

    /// Returns a new series with the y values scaled by the function `fy` evaluated at the
    /// corresponding x value
    pub fn scaled_y(&self, fy: &dyn Func1) -> Self {
        let scale = fy.fs(&self.x);
        let ys = self
            .y
            .iter()
            .zip(scale.iter())
            .map(|(y, s)| y * s)
            .collect::<Vec<f64>>();
        Self::new(self.x.clone(), ys)
    }

    /// Return a new series with the x values shifted by `shift_x` and the y values shifted by
    /// `shift_y`
    pub fn shift_by(&self, shift_x: f64, shift_y: f64) -> Self {
        let xs = self.x.iter().map(|v| v + shift_x).collect::<Vec<f64>>();
        let ys = self.y.iter().map(|v| v + shift_y).collect::<Vec<f64>>();
        let new_xs = DiscreteDomain::try_from(xs).unwrap();
        Self::new(new_xs, ys)
    }

    /// Concatenates two series together, returning a new series that contains all the x and y
    /// values from both series. This will only work if the minimum x value of the second series is
    /// greater than the maximum x value of the first series, otherwise it will return an Err.
    ///
    /// # Arguments
    ///
    /// * `other`: A reference to the other series to concatenate, which will be appended to the
    ///   end of the first series. The minimum x value of the second series must be greater than
    ///   the maximum x value of the first series.
    ///
    /// returns: Result<Series1, Box<dyn Error, Global>>
    ///
    /// # Examples
    ///
    /// ```
    /// use engeom::func1::Series1;
    /// let series1 = Series1::try_new(vec![0.0, 1.0, 2.0], vec![0.0, 1.0, 2.0]).unwrap();
    /// let series2 = Series1::try_new(vec![3.0, 4.0, 5.0], vec![3.0, 4.0, 5.0]).unwrap();
    /// let series3 = series1.concat(&series2).unwrap();
    /// assert_eq!(series3.x.to_vec(), vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0]);
    /// assert_eq!(series3.y, vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0]);
    /// ```
    pub fn concat(&self, other: &Self) -> Result<Self> {
        if other.x_min() <= self.x_max() {
            Err("other.x_min() must be greater than self.x_max()".into())
        } else {
            let mut xs = self.x.to_vec();
            xs.extend(other.x.iter());
            let mut ys = self.y.clone();
            ys.extend(other.y.iter());
            Self::try_new(xs, ys)
        }
    }

    /// Returns the series as a vector of `Point2` structs by zipping the x and y values together
    /// and converting them.  The order of the points will be from the smallest x value to the
    /// largest x value.
    pub fn as_points(&self) -> Vec<Point2> {
        self.xys()
            .map(|(x, y)| Point2::new(*x, *y))
            .collect::<Vec<_>>()
    }

    // ===========================================================================================
    // Non-finite value operations
    // ===========================================================================================

    pub fn remove_nan(&self) -> Self {
        let mut xs = Vec::new();
        let mut ys = Vec::new();
        for (x, y) in self.x.iter().zip(self.y.iter()) {
            if x.is_nan() || y.is_nan() {
                continue;
            }
            xs.push(*x);
            ys.push(*y);
        }
        let new_xs = DiscreteDomain::try_from(xs).unwrap();
        Self::new(new_xs, ys)
    }

    pub fn has_nan_between(&self, x0: f64, x1: f64) -> bool {
        for (x, y) in self.x.iter().zip(self.y.iter()) {
            if y.is_nan() && *x >= x0 && *x <= x1 {
                return true;
            }
        }
        false
    }

    pub fn has_nan(&self) -> bool {
        for y in self.y.iter() {
            if y.is_nan() {
                return true;
            }
        }
        false
    }

    // ===========================================================================================
    // Derivatives and integrals
    // ===========================================================================================

    /// Calculate and return the first derivative of the series
    pub fn dydx(&self) -> Self {
        let mut ys = Vec::new();
        for j in 0..self.y.len() {
            if j == 0 {
                ys.push((self.y[1] - self.y[0]) / (self.x[1] - self.x[0]));
            } else if j == self.y.len() - 1 {
                ys.push((self.y[j] - self.y[j - 1]) / (self.x[j] - self.x[j - 1]));
            } else {
                ys.push((self.y[j + 1] - self.y[j - 1]) / (self.x[j + 1] - self.x[j - 1]));
            }
        }

        Self::new(self.x.clone(), ys)
    }

    pub fn middle_reiemann_areas(&self) -> Vec<(f64, f64)> {
        let mut result = Vec::new();
        for i in 0..self.x.len() - 1 {
            let x0 = self.x[i];
            let x1 = self.x[i + 1];
            let y0 = self.y[i];
            let y1 = self.y[i + 1];
            result.push(((x1 + x0) * 0.5, (x1 - x0) * (y0 + y1) * 0.5));
        }
        result
    }

    /// Computes the area under the curve
    pub fn area_under(&self) -> f64 {
        self.middle_reiemann_areas()
            .into_iter()
            .map(|(_, a)| a)
            .sum()
    }

    // ===========================================================================================
    // Filtering and smoothing
    // ===========================================================================================

    /// Perform a Savitzky-Golay smoothing on the series with a 5-point window
    pub fn savitzky_golay(&self) -> Self {
        savitzky_golay_5(self)
    }

    pub fn mean_filtered(&self, window: f64) -> Self {
        let half_size = window / 2.0;
        let xs = self.x.to_vec();
        let mut ys = Vec::new();
        for x in &xs {
            let mut sum = 0.0;
            let mut count = 0.0;
            for i in 0..self.x.len() {
                if (self.x[i] - x).abs() <= half_size {
                    sum += self.y[i];
                    count += 1.0;
                }
            }
            ys.push(sum / count);
        }
        Self::try_new(xs, ys).expect("Xs should have been valid, what went wrong?")
    }

    // ===========================================================================================
    // Crossings and extrema
    // ===========================================================================================

    /// Return the x values of the places where the series crosses the y value `y_equals`. The
    /// values will be sorted from smallest to largest and will be unique.
    ///
    /// # Arguments
    ///
    /// * `y_equals`: the y value at which to find the corresponding x values
    ///
    /// returns: Vec<f64, Global>
    ///
    /// # Examples
    ///
    /// ```
    ///
    /// ```
    pub fn y_crossings(&self, y_equals: f64) -> Vec<f64> {
        let mut crossings = Vec::new();
        for j in 0..self.y.len() - 1 {
            let v0 = self.y[j];
            let v1 = self.y[j + 1];
            if v0 <= y_equals && v1 >= y_equals || v0 >= y_equals && v1 <= y_equals {
                let x0 = self.x[j];
                let x1 = self.x[j + 1];
                let m = (v1 - v0) / (x1 - x0);
                if !m.is_finite() {
                    continue;
                }
                let x = x0 + (y_equals - v0) / m;
                crossings.push(x);
            }
        }

        sort_and_dedup(&mut crossings, Some(1e-10));
        crossings
    }

    /// Calculates and returns a vector of the x (domain) location of all the local maxima in
    /// the series. A local maximum is defined as a point whose neighbors are both less than it.
    pub fn local_maxima_xs(&self) -> Vec<f64> {
        let mut maxima = Vec::new();
        for i in 0..self.x.len() {
            if i == 0 {
                if self.y[0] > self.y[1] {
                    maxima.push(self.x[0]);
                }
            } else if i == self.y.len() - 1 {
                if self.y[i] > self.y[i - 1] {
                    maxima.push(self.x[i]);
                }
            } else {
                let y0 = self.y[i - 1];
                let y1 = self.y[i];
                let y2 = self.y[i + 1];
                if y1 > y0 && y1 > y2 {
                    maxima.push(self.x[i]);
                }
            }
        }
        maxima
    }

    /// Calculates and returns the x and y location of the global maxima in the series. This is
    /// the x position of the y with the highest value. If there are multiple y values with the
    /// same maximum value, the one with the lowest x value is returned.
    pub fn global_maxima_xy(&self) -> (f64, f64) {
        let mut max_x = self.x[0];
        let mut max_y = self.y[0];
        for i in 1..self.x.len() {
            if self.y[i] > max_y {
                max_x = self.x[i];
                max_y = self.y[i];
            }
        }
        (max_x, max_y)
    }

    /// Calculates and returns the x and y location of the global minima in the series. This is
    /// the x position of the y with the lowest value. If there are multiple y values with the
    /// same minimum value, the one with the lowest x value is returned.
    pub fn global_minima_xy(&self) -> (f64, f64) {
        let mut min_x = self.x[0];
        let mut min_y = self.y[0];
        for i in 1..self.x.len() {
            if self.y[i] < min_y {
                min_x = self.x[i];
                min_y = self.y[i];
            }
        }
        (min_x, min_y)
    }

    /// Calculates the lower and upper x bounds of a plateau based on an x value assumed to be
    /// of a local maxima.  This works by finding the value of the maxima, subtracting the
    /// tolerance, and then finding the first x value to the left and right of the maxima that has
    /// the y value of the maxima - tolerance.
    pub fn plateau_at_maxima(&self, x: f64, tol: f64) -> Option<Interval> {
        let v = self.interpolate(x);
        if v.is_nan() {
            return None;
        }
        let y = v - tol;
        let mut crossings = self.y_crossings(y);

        // If the first y value is above the threshold or the last y value is below the threshold,
        // then those points are crossings
        if self.y[0] > y {
            crossings.insert(0, self.x[0]);
        }

        if self.y[self.y.len() - 1] > y {
            crossings.push(self.x[self.x.len() - 1]);
        }

        // TODO: This is a linear search, but it could be a binary search
        for xs in crossings.windows(2) {
            if xs[0] <= x && x <= xs[1] {
                return Some(Interval::new(xs[0], xs[1]));
            }
        }
        None
    }

    /// Return the index of the x value in the series which is either equal to or immediately
    /// after the given x value.  If the given x value is before the first x value in the series,
    /// 0 will be returned.  If the given x value is after the last x value in the series, the
    /// length of the series will be returned.
    pub fn index_of_x_after(&self, x: f64) -> usize {
        // TODO: this needs unit tests
        let search_result = self.x.binary_search_by(|v| v.partial_cmp(&x).unwrap());
        match search_result {
            Ok(actual_index) => actual_index,
            Err(index_after) => index_after,
        }
    }

    // ===========================================================================================
    // Splitting and clipping
    // ===========================================================================================

    /// Returns a new series that contains the region of the series between x0 and x1, including
    /// the end points. This breaks the regularity of the spacing
    pub fn between(&self, x0: f64, x1: f64) -> Option<Self> {
        let mut xs = Vec::new();
        let mut ys = Vec::new();

        // Find the first index that is >= x0
        let search_result = self.x.binary_search_by(|a| a.partial_cmp(&x0).unwrap());
        let mut i = match search_result {
            Ok(actual_index) => actual_index,
            Err(next_index) => {
                if next_index == 0 {
                    0
                } else {
                    xs.push(x0);
                    ys.push(self.interpolate(x0));
                    next_index
                }
            }
        };

        while i < self.x.len() && self.x[i] <= x1 {
            xs.push(self.x[i]);
            ys.push(self.y[i]);
            i += 1;
        }

        // If the last x value is less than x1, we will add it _if_ x1 is contained in the domain
        if xs.is_empty() {
            return None;
        }

        if xs[xs.len() - 1] < x1 {
            let y1 = self.interpolate(x1);
            if !y1.is_nan() {
                xs.push(x1);
                ys.push(y1);
            }
        }

        let new_xs = DiscreteDomain::try_from(xs).unwrap();
        Some(Self::new(new_xs, ys))
    }

    pub fn interval(&self) -> Interval {
        Interval::new(self.x_min(), self.x_max())
    }

    pub fn in_interval(&self, interval: Interval) -> Option<Self> {
        self.between(interval.min, interval.max)
    }

    /// Calculates a set of intervals which represent the regions of the series that are either
    /// above the y=0 line or below the y=0 line.
    ///
    /// returns: a vector of `Interval` structs, which will be ordered from the lowest x value to
    /// the highest x value. The intervals will be non-overlapping and will cover the entire
    /// domain of the series.
    pub fn bounds_at_y0(&self) -> Vec<Interval> {
        let mut x_bounds = [self.y_crossings(0.0), vec![self.x_min(), self.x_max()]].concat();
        sort_and_dedup(&mut x_bounds, Some(1e-10));

        let mut bounds = Vec::new();
        for w in x_bounds.windows(2) {
            bounds.push(Interval::new(w[0], w[1]));
        }

        bounds
    }

    /// Computes the least-squares line of best fit returning the slope and y-intercept (m and b)
    /// in that order as a tuple.
    pub fn best_fit_line(&self) -> Line1 {
        // TODO: Replace this with the polynomial least squares passthrough
        let n = self.x.len() as f64;
        let sum_x = self.x.iter().sum::<f64>();
        let sum_y = self.y.iter().sum::<f64>();
        let sum_xx = self.x.iter().map(|x| x * x).sum::<f64>();
        let sum_xy = self
            .x
            .iter()
            .zip(self.y.iter())
            .map(|(x, y)| x * y)
            .sum::<f64>();
        let m = (n * sum_xy - sum_x * sum_y) / (n * sum_xx - sum_x * sum_x);
        let b = (sum_y - m * sum_x) / n;
        Line1::new_mxb(m, b)
    }
    /// Attempts to split the series into two series at the given x value, with the first value
    /// in the return tuple consisting of the series below the x value and the second value in the
    /// tuple consisting of the series above the x value. If the x value is not in the domain of
    /// the series, then the corresponding value in the tuple will be None.
    pub fn split_at_x(&self, x: f64) -> (Option<Self>, Option<Self>) {
        if x > self.x_max() {
            (Some(self.clone()), None)
        } else if x < self.x_min() {
            (None, Some(self.clone()))
        } else {
            (self.between(self.x_min(), x), self.between(x, self.x_max()))
        }
    }
    // ===========================================================================================
    // Resampling
    // ===========================================================================================

    /// Resamples the series to have `n` evenly spaced points in the domain. The first and last
    /// points will be the same as the first and last points of the original series.
    ///
    /// # Arguments
    ///
    /// * `n`:
    ///
    /// returns: Series1
    ///
    /// # Examples
    ///
    /// ```
    /// use engeom::Series1;
    /// let series = Series1::try_new(vec![0.0, 1.0, 2.0], vec![0.0, 1.0, 2.0])
    ///     .expect("Failed to create series");
    /// let resampled = series.resampled_n(5);
    /// assert_eq!(resampled.x.values(), vec![0.0, 0.5, 1.0, 1.5, 2.0]);
    /// assert_eq!(resampled.y, vec![0.0, 0.5, 1.0, 1.5, 2.0]);
    /// ```
    pub fn resampled_n(&self, n: usize) -> Self {
        let step_size = (self.x_max() - self.x_min()) / (n as f64 - 1.0);
        // TODO: Make this linear rather than using the binary search
        let xs = (0..n)
            .map(|i| (self.x_min() + (i as f64) * step_size).min(self.x_max()))
            .collect::<Vec<_>>();
        let new_xs = DiscreteDomain::try_from(xs).unwrap();
        let ys = self.fs(&new_xs);

        Self::new(new_xs, ys)
    }

    /// Resamples the series to have roughly `x_spacing` between each point in the domain. The
    /// first and last points will be the same as the first and last points of the original series,
    /// and a number of evenly spaced points will be added in between.  The total number of points
    /// will be the length of the curve divided by `x_spacing` plus 1, rounded up to the nearest
    /// whole integer.
    ///
    /// # Arguments
    ///
    /// * `x_spacing`: the approximate spacing between points in the domain
    ///
    /// returns: Series1
    ///
    /// # Examples
    ///
    /// ```
    /// use engeom::Series1;
    /// let series = Series1::try_new(vec![0.0, 1.0, 2.0], vec![0.0, 1.0, 2.0])
    ///     .expect("Failed to create series");
    /// let resampled = series.resampled_x(0.5);
    /// assert_eq!(resampled.x.values(), vec![0.0, 0.5, 1.0, 1.5, 2.0]);
    /// assert_eq!(resampled.y, vec![0.0, 0.5, 1.0, 1.5, 2.0]);
    /// ```
    pub fn resampled_x(&self, x_spacing: f64) -> Self {
        let n = 1.0 + (self.x_max() - self.x_min()) / x_spacing;
        self.resampled_n(n.ceil() as usize)
    }

    // ===========================================================================================
    // Misc
    // ===========================================================================================

    /// Calculates and returns clusters of contiguous indices where the y value is within `d_tol`
    /// of the reference function and the x span of the cluster is at least `x_span`.  This is a
    /// specialized method used for identifying regions of a series that match to another series,
    /// but directly using the indices of the series rather than the x values.
    ///
    /// # Arguments
    ///
    /// * `reference`: a reference `Series1` to compare against
    /// * `d_tol`: the maximum allowable y difference between the reference and the series at any
    ///   point
    /// * `x_span`: the minimum allowable x span of any cluster
    ///
    /// returns: Vec<Vec<usize, Global>, Global>
    pub fn index_clusters_in_tol(
        &self,
        reference: &Series1,
        d_tol: f64,
        x_span: f64,
    ) -> Vec<Vec<usize>> {
        // First pass just collects everything within the tolerance
        let mut indices = Vec::new();
        for (i, (x, y)) in self.xys().enumerate() {
            if (reference.f(*x) - *y).abs() < d_tol {
                indices.push(i);
            }
        }

        let mut clusters = Vec::new();
        let mut current = Vec::new();
        for i in indices {
            if current.is_empty() {
                current.push(i);
            } else {
                let last = current.last().unwrap();
                if i - last == 1 {
                    current.push(i);
                } else {
                    clusters.push(current);
                    current = vec![i];
                }
            }
        }
        if !current.is_empty() {
            clusters.push(current);
        }

        // Now go through each cluster and if it is large enough, add all the indices to the
        // result vector
        let mut results = Vec::new();
        for cluster in clusters {
            if self.x[*cluster.last().unwrap()] - self.x[cluster[0]] >= x_span {
                results.push(cluster);
            }
        }

        results
    }
}

fn f_or_zero(f: &impl Func1, x: f64) -> f64 {
    let y = f.f(x);
    if y.is_nan() { 0.0 } else { y }
}

impl Func1 for Series1 {
    fn f(&self, x: f64) -> f64 {
        self.interpolate(x)
    }

    fn xs(&self) -> Option<&DiscreteDomain> {
        Some(&self.x)
    }
}

fn savitzky_golay_5(series: &Series1) -> Series1 {
    let mut ys = Vec::new();
    for j in 0..series.y.len() {
        let mut sum = 0.0;
        let mut total = 0.0;

        if let Some(v) = series.y_at_index(j as i32 - 2) {
            sum += v * -3.0;
            total += -3.0;
        }
        if let Some(v) = series.y_at_index(j as i32 - 1) {
            sum += v * 12.0;
            total += 12.0;
        }
        sum += series.y[j] * 17.0;
        total += 17.0;
        if let Some(v) = series.y_at_index(j as i32 + 1) {
            sum += v * 12.0;
            total += 12.0;
        }
        if let Some(v) = series.y_at_index(j as i32 + 2) {
            sum += v * -3.0;
            total += -3.0;
        }
        ys.push(sum / total);
    }

    Series1::new(series.x.clone(), ys)
}