moving-average 0.3.3

A simple moving average library
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
//! # Moving Average Library
//!
//! `moving_average` is a library for calculating the moving average on a stream of data.
//!
//! ## Features
//!
//! - Calculate moving average in an ergonomic way.
//!
//! ## Usage
//!
//! First, add this to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! moving_average = "0.1.0"
//! ```
//!
//! Then, add this to your crate root:
//!
//! ```rust
//! extern crate moving_average;
//! ```
//!
//! ### Basic Operations
//!
//! You can create a new `Moving` instance and add or subtract values from it:
//!
//! ```rust
//! use moving_average::Moving;
//!
//! let mut moving_average: Moving<usize> = Moving::new();
//! moving_average.add(10);
//! moving_average.add(20);
//! assert_eq!(moving_average, 15);
//! ```

use num_traits::ToPrimitive;
use std::{
    cell::RefCell,
    collections::HashMap,
    fmt::Display,
    marker::PhantomData,
    ops::{AddAssign, Deref},
};

use ordered_float::OrderedFloat;

#[derive(Debug, Clone)]
pub struct Value(f64);

impl Deref for Value {
    type Target = f64;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Display for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

macro_rules! impl_partial_eq {
    ($($ty:ty), *) => {
        $(
            impl PartialEq<$ty> for Value {
                fn eq(&self, other: &$ty) -> bool {
                    self.0 == *other as f64
                }
            }
        )*
    };
    () => {

    };
}

impl_partial_eq!(usize, i8, i16, i32, i64, i128, u8, u16, u32, u64, u128, f32, f64);

macro_rules! utilities {
    ($($ty:ty),*) => {
        $(
            impl AddAssign<$ty> for Moving<$ty> {
                fn add_assign(&mut self, other: $ty) {
                    let _ = self.add(other);
                }
            }

            impl PartialEq<$ty> for Moving<$ty> {
                fn eq(&self, other: &$ty) -> bool {
                    self.mean() == *other as f64
                }
            }

            impl PartialOrd<$ty> for Moving<$ty> {
                fn partial_cmp(&self, other: &$ty) -> Option<std::cmp::Ordering> {
                    self.mean().partial_cmp(&(*other as f64))
                }
            }

            impl PartialEq<Moving<$ty>> for $ty {
                fn eq(&self, other: &Moving<$ty>) -> bool {
                    *self as f64 == other.mean()
                }
            }

            impl PartialOrd<Moving<$ty>> for $ty {
                fn partial_cmp(&self, other: &Moving<$ty>) -> Option<std::cmp::Ordering> {
                    (*self as f64).partial_cmp(&other.mean())
                }
            }
        )*
    };
}

macro_rules! partial_non {
    ($($ty:ty), *) => {
        $(
        impl PartialEq<f32> for Moving<$ty> {
            fn eq(&self, other: &f32) -> bool {
                self.mean() == *other as f64
            }
        }

        impl PartialEq<f64> for Moving<$ty> {
            fn eq(&self, other: &f64) -> bool {
                self.mean() == *other
            }
        }
    )*

    };
}

macro_rules! signed {
    ($($ty:ty), *) => {
        $(
        impl Sign for $ty {
            fn signed() -> bool {
               true
            }
        }
        )*
    };
}
macro_rules! unsigned {
    ($($ty:ty), *) => {
    $(
        impl Sign for $ty {
            fn signed() -> bool {
               false
            }
        }
    )*
    };
}

utilities!(usize, i8, i16, i32, i64, i128, u8, u16, u32, u64, u128, f32, f64);
partial_non!(usize, i8, i16, i32, i64, i128, u8, u16, u32, u64, u128);
signed!(i8, i16, i32, i64, i128, f32, f64);
unsigned!(usize, u8, u16, u32, u64, u128);

pub trait Sign {
    fn signed() -> bool;
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// Represents the possible errors that can occur in the `Moving` struct.
pub enum MovingError {
    /// Error indicating that a negative value was attempted to be added to an unsigned type.
    NegativeValueToUnsignedType,

    /// Error indicating that an overflow occurred during an operation.
    /// Note: This is unlikely to occur with floating-point operations.
    Overflow,

    /// Error indicating that an underflow occurred during an operation.
    Underflow,

    /// Error indicating that the count of values has overflowed.
    CountOverflow,

    /// Error indicating that a value has reached or exceeded the specified threshold.
    ///
    /// This error is triggered when a value added to the `Moving` instance meets or exceeds
    /// the threshold value specified during the creation of the instance. This can be used
    /// to signal that a certain limit has been reached, which might require special handling
    /// or termination of further processing.
    ThresholdReached,
}

/// `Moving<T>` provides an ergonomic way to compute the moving average, mode, and count
/// for a sequence of values of type `T`. It supports both signed and unsigned numeric types,
/// and can enforce a threshold to stop accepting new values when the mean reaches or exceeds it.
///
/// Internally, it tracks:
/// - The number of values added (`count`)
/// - The current mean (`mean`)
/// - The frequency of each value for mode calculation (`mode`)
/// - An optional threshold (`threshold`)
///
/// # Type Parameters
///
/// - `T`: The numeric type of the values (e.g., `usize`, `i32`, `f64`).
///
/// # Examples
///
/// ```
/// use moving_average::Moving;
///
/// let moving = Moving::new();
/// moving.add(10);
/// moving.add(10);
/// moving.add(10);
/// moving.add(20);
/// assert_eq!(moving.mean(), 12.5);
/// assert_eq!(moving.count(), 4);
/// assert_eq!(moving.mode(), 10.0);
/// ```
#[derive(Debug, Default)]
pub struct Moving<T> {
    count: RefCell<usize>,
    mean: RefCell<f64>,
    mode: RefCell<HashMap<OrderedFloat<f64>, usize>>,
    threshold: f64,
    phantom: std::marker::PhantomData<T>,
}

impl<T> Moving<T>
where
    T: Sign + ToPrimitive,
{
    /// Creates a new [`Moving<T>`] instance with default values.
    ///
    /// # Returns
    ///
    /// A new instance of [`Moving<T>`].
    /// Values can ge added to this instance to calculate the moving average.
    pub fn new() -> Self {
        Self {
            count: RefCell::new(0),
            mean: RefCell::new(0.0),
            mode: RefCell::new(HashMap::new()),
            threshold: f64::MAX,
            phantom: PhantomData,
        }
    }

    /// Creates a new [`Moving<T>`] instance with a specified threshold.
    ///
    /// This method initializes the `count` to 0, `mean` to 0.0, `is_error` to `false`,
    /// and `threshold` to the provided value.
    ///
    /// # Parameters
    ///
    /// - `threshold`: The threshold value to be used for the new instance.
    ///
    /// # Returns
    ///
    /// A new instance of [`Moving<T>`] with the specified threshold.
    /// Values can be added to this instance to calculate the moving average.
    /// When values are greater than or equal to the threshold, the [`MovingResults::ThresholdReached`] variant is returned and no further values are added.
    pub fn new_with_threshold(threshold: f64) -> Self {
        Self {
            count: RefCell::new(0),
            mean: RefCell::new(0.0),
            mode: RefCell::new(HashMap::new()),
            threshold,
            phantom: PhantomData,
        }
    }
    /// Adds a value to the current statistical collection, updating the mean accordingly.
    ///
    /// This function converts the input value to an `f64` and then updates the mean of the collection
    /// based on the new value.
    ///
    /// # Returns
    /// If the mean is less than the threshold, the [`MovingResults::Value`] variant is returned with the new mean.
    ///
    /// # Panics
    ///
    /// Panics if the type `T` is unsigned and a negative value is attempted to be added. This is because
    /// negative values are not allowed for unsigned types. If negative values are needed, it is recommended
    /// to use signed types instead.
    pub fn add_with_result(&self, value: T) -> Result<f64, MovingError> {
        let value_f64: f64 = value.to_f64().unwrap();
        if !T::signed() && value_f64 < 0.0 {
            return Err(MovingError::NegativeValueToUnsignedType);
        }
        let mut count = self.count.borrow_mut();
        let mut mean = self.mean.borrow_mut();
        let mut mode = self.mode.borrow_mut();
        mode.entry(OrderedFloat(value_f64))
            .and_modify(|e| *e += 1)
            .or_insert(1);

        *count += 1;
        *mean += (value_f64 - *mean) / *count as f64;

        if *mean >= self.threshold {
            return Err(MovingError::ThresholdReached);
        }

        Ok(*mean)
    }

    /// Adds a value to the current statistical collection, ignoring the result.
    ///
    /// This method calls the `add` method and ignores any errors that occur.
    pub fn add(&self, value: T) {
        let _ = self.add_with_result(value);
    }

    /// Returns the mean value of the moving average
    pub fn mean(&self) -> f64 {
        *self.mean.borrow()
    }

    /// Returns the statistical mode of the values added so far.
    ///
    /// The **mode** is the value that appears most frequently in the data set.
    ///
    /// # Behavior
    ///
    /// - If **no values** have been added, returns `0.0`.
    /// - If **all values are unique** (no repeats), returns the current mean.
    /// - If **one value** occurs more frequently than any other, returns that value as the mode.
    /// - If **multiple values** are tied for the highest frequency (i.e., a multi-modal distribution),
    ///   returns the value among the tied modes that is **closest to the mean**.
    ///
    /// # Examples
    ///
    /// ```
    /// use moving_average::Moving;
    /// let moving = Moving::new();
    /// moving.add(10);
    /// moving.add(20);
    /// moving.add(10);
    /// assert_eq!(moving.mode(), 10.0); // 10 appears most frequently
    ///
    /// let moving = Moving::new();
    /// moving.add(1);
    /// moving.add(2);
    /// moving.add(3);
    /// assert_eq!(moving.mode(), moving.mean()); // all unique, returns mean
    ///
    /// let moving = Moving::new();
    /// moving.add(10);
    /// moving.add(20);
    /// moving.add(10);
    /// moving.add(20);
    /// // Ensure the mean is lowered
    /// moving.add(1);
    /// // Both 10 and 20 appear twice, closest to mean is returned
    /// let mode = moving.mode();
    /// assert_eq!(mode, 10.0); // 10 is closer to the mean than 20
    /// ```
    pub fn mode(&self) -> f64 {
        let mode_map = self.mode.borrow();
        if mode_map.is_empty() {
            return 0.0;
        }
        // Find the maximum count
        let max_count = match mode_map.values().max() {
            Some(&max) if max > 1 => max,
            // If all values are unique, return the mean
            _ => return self.mean(),
        };
        // Collect all values with the maximum count
        let modes: Vec<_> = mode_map
            .iter()
            .filter(|&(_, &count)| count == max_count)
            .collect();
        // If there's a tie return the mode closest to the mean
        if modes.len() != 1 {
            let mean = self.mean();
            let closest = modes
                .iter()
                .min_by_key(|&&(value, _)| (value.0 - mean).abs() as i64)
                .unwrap();
            return closest.0.into_inner();
        }
        // Otherwise, return the mode value
        modes[0].0.into_inner()
    }

    /// Returns the count of events added
    ///
    /// # Examples
    ///
    /// ```
    /// use moving_average::Moving;
    /// let moving = Moving::new();
    /// moving.add(3);
    /// assert_eq!(moving.count(), 1);
    /// moving.add(3);
    /// assert_eq!(moving.count(), 2);
    /// assert_eq!(moving.mean(), 3.0);
    /// ```
    pub fn count(&self) -> usize {
        *self.count.borrow()
    }
}

impl<T> std::fmt::Display for Moving<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.mean.borrow())
    }
}

impl<T> PartialEq for Moving<T> {
    fn eq(&self, other: &Self) -> bool {
        *self.mean.borrow() == *other.mean.borrow()
    }
}

impl<T> PartialOrd for Moving<T> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.mean.borrow().partial_cmp(&*other.mean.borrow())
    }
}

impl std::fmt::Display for MovingError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

#[cfg(test)]
mod tests {
    use crate::Moving;

    #[test]
    fn mode() {
        let moving = Moving::new();
        moving.add(10);
        moving.add(20);
        moving.add(10);
        assert_eq!(moving.mode(), 10.0);
    }

    #[test]
    fn big_mode() {
        let moving = Moving::new();
        for i in 0..10000 {
            moving.add(i);
        }
        assert_eq!(moving.mode(), moving.mean());
        moving.add(9999);
        assert_eq!(moving.mode(), 9999.0);
    }

    #[test]
    fn double_mode() {
        let moving = Moving::new();
        moving.add(10);
        moving.add(20);
        moving.add(10);
        moving.add(20);
        moving.add(1);
        assert_eq!(moving.mode(), 10.0);
        moving.add(3000);
        assert_eq!(moving.mode(), 20.0);
    }

    #[test]
    fn partial_order() {
        let m1 = Moving::new();
        let m2 = Moving::new();
        m1.add(10);
        m2.add(20);
        assert!(m1 < m2);
    }

    #[test]
    fn thresholds() {
        let moving_threshold = Moving::new_with_threshold(10.0);
        let result = moving_threshold.add_with_result(9);
        assert_eq!(result.unwrap(), 9.0);
        let result = moving_threshold.add_with_result(15);
        assert!(result.is_err(), "{:?}", result);
        assert_eq!(result.unwrap_err(), crate::MovingError::ThresholdReached);
    }

    #[test]
    fn never_overflow() {
        let moving_average: Moving<usize> = Moving::new();
        let result = moving_average.add_with_result(usize::MAX);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), usize::MAX as f64);
        let result = moving_average.add_with_result(usize::MAX);
        assert!(result.is_ok());

        assert_eq!(result.unwrap(), usize::MAX as f64);
    }

    #[test]
    fn add_moving_average() {
        let moving_average: Moving<usize> = Moving::new();
        moving_average.add(10);
        assert_eq!(moving_average, 10);
        moving_average.add(20);
        assert_eq!(moving_average, 15);
    }

    #[test]
    fn float_moving_average() {
        let moving_average: Moving<f32> = Moving::new();
        moving_average.add(10.0);
        moving_average.add(20.0);
        assert_eq!(moving_average, 15.0);
    }

    #[test]
    fn assign_add() {
        let mut moving_average: Moving<usize> = Moving::new();
        moving_average.add(10);
        moving_average += 20;
        assert_eq!(moving_average, 15);
    }

    #[test]
    fn assign_add_float() {
        let mut moving_average: Moving<f32> = Moving::new();
        moving_average.add(10.0);
        moving_average += 20.0;
        assert_eq!(moving_average, 15.0);
    }

    #[test]
    fn assign_add_i64() {
        let mut moving_average: Moving<i64> = Moving::new();
        moving_average.add(10);
        moving_average += 20;
        assert_eq!(moving_average, 15);
    }
    #[test]
    fn default_works() {
        let moving_average: Moving<usize> = Default::default();
        assert_eq!(moving_average, 0);
        let moving_average: Moving<f32> = Default::default();
        assert_eq!(moving_average, 0.0);
    }

    #[test]
    fn binary_operations() {
        let moving_average: Moving<usize> = Moving::new();
        moving_average.add(10);
        moving_average.add(20);
        assert!(moving_average < usize::MAX)
    }

    #[test]
    fn binary_operations_float() {
        let moving_average: Moving<f32> = Moving::new();
        moving_average.add(10.0);
        moving_average.add(20.0);
        assert!(moving_average < f32::MAX)
    }

    #[test]
    fn many_operations() {
        let moving_average: Moving<_> = Moving::new();
        for i in 0..1000 {
            moving_average.add(i);
        }
        assert_eq!(moving_average, 999.0 / 2.0);
    }
}