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
//! Library for using exponential moving averages that is generic over the underlying float type.
#![cfg_attr(
  not(test),
  deny(warnings, clippy::all, clippy::pedantic, clippy::cargo, missing_docs, missing_crate_level_docs)
)]
#![deny(unsafe_code)]
#![cfg_attr(not(test), no_std)]

use core::cmp::Ordering;
use core::convert::TryInto;
use core::time::Duration;
use num_traits::identities::{One, Zero};
use num_traits::Float;
use ordered_float::{FloatIsNan, NotNan};

/// A struct representing an exponential moving average
///
/// The weighting can be chosen for each accumulation. To have the weighting be part of the struct see [`StableEma`]
#[must_use]
#[derive(Clone)]
pub struct Ema<F>
where
  F: Float,
{
  mean: NotNan<F>,
  variance: NotNan<F>,
}

impl<F> PartialEq for Ema<F>
where
  F: Float,
{
  fn eq(&self, other: &Self) -> bool {
    self.mean.eq(&other.mean) && self.variance.eq(&other.variance)
  }
}

impl<F> Eq for Ema<F> where F: Float {}

impl<F> PartialOrd for Ema<F>
where
  F: Float,
{
  fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
    Some(self.cmp(other))
  }
}

impl<F> Ord for Ema<F>
where
  F: Float,
{
  fn cmp(&self, other: &Self) -> Ordering {
    self.mean.cmp(&other.mean).then_with(|| self.variance.cmp(&other.variance))
  }
}

impl<F> Ema<F>
where
  F: Float + TryInto<NotNan<F>>,
{
  /// Tries to create a new `Ema` struct from raw float values
  /// # Errors
  /// Fails if `mean` or `variance` are NaN
  pub fn try_new(
    mean: impl TryInto<NotNan<F>, Error = FloatIsNan>,
    variance: impl TryInto<NotNan<F>, Error = FloatIsNan>,
  ) -> Result<Self, FloatIsNan> {
    Ok(Self::new(mean.try_into()?, variance.try_into()?))
  }
}

impl<F> Ema<F>
where
  F: Float,
{
  /// Returns a new `Ema` struct with the mean and variance estimates already initialized.
  ///
  /// It is recommended to choose these values to be as close to expected as possible so that they can converge quickly
  pub fn new(mean: NotNan<F>, variance: NotNan<F>) -> Self {
    Self { mean, variance }
  }
  /// Accumulates a new value into this `Ema`. The mean and variance are adjusted by the `recent_weight`
  pub fn accumulate(&mut self, value: NotNan<F>, recent_weight: NotNan<F>) {
    let recent_weight = recent_weight.min(NotNan::one()).max(NotNan::zero());
    let mean = self.mean;
    let delta = value - mean;
    let new_mean = mean + recent_weight * delta;
    let new_variance = (NotNan::one() - recent_weight) * (self.variance + recent_weight * delta * delta);
    self.mean = new_mean;
    self.variance = new_variance;
  }
  /// Tries to accumulate raw flaot values.
  /// # Errors
  /// Fails if `value` or `recent_weight` are NaN
  pub fn try_accumulate(&mut self, value: F, recent_weight: F) -> Result<(), FloatIsNan> {
    let value = NotNan::new(value)?;
    let recent_weight = NotNan::new(recent_weight)?;
    self.accumulate(value, recent_weight);
    Ok(())
  }
  /// Returns the mean of this `Ema`
  #[must_use]
  #[inline]
  pub fn mean(&self) -> NotNan<F> {
    self.mean
  }
  /// Returns the variance of this `Ema`
  #[must_use]
  #[inline]
  pub fn variance(&self) -> NotNan<F> {
    self.variance
  }
  /// Returns the standard deviation of this `Ema`
  #[allow(clippy::missing_panics_doc)]
  #[must_use]
  #[inline]
  pub fn std_dev(&self) -> NotNan<F> {
    // Not using `unwrap` or `expect` because we don't want to force the associated type to be `Debug`
    NotNan::new(self.variance.sqrt()).unwrap_or_else(|_| panic!("sqrt won't return NaN if it didn't start with it"))
  }
  /// Returns the mean of this `Ema` as a duration in seconds. Useful when using an `Ema` to time events.
  #[must_use]
  #[inline]
  pub fn mean_duration(&self) -> Duration {
    Duration::from_secs_f64(self.mean().to_f64().unwrap_or(0.0).max(0.0))
  }
  /// Returns the standard deviation of this `Ema` as a duration in seconds. Useful when using an `Ema` to time events
  #[must_use]
  #[inline]
  pub fn std_dev_duration(&self) -> Duration {
    Duration::from_secs_f64(self.std_dev().to_f64().unwrap_or(0.0).max(0.0))
  }
}

impl<F> Default for Ema<F>
where
  F: Float,
{
  fn default() -> Self {
    Self {
      mean: NotNan::zero(),
      variance: NotNan::zero(),
    }
  }
}

impl<F> core::fmt::Debug for Ema<F>
where
  F: Float + core::fmt::Debug,
{
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("EMA")
      .field("mean", &*self.mean)
      .field("variance", &*self.variance)
      .finish()
  }
}

/// A stable [Ema] where the `recent_weight` is set at initialization and the same value is always used.
#[derive(Clone)]
#[must_use]
pub struct StableEma<F>
where
  F: Float,
{
  ema: Ema<F>,
  recent_weight: NotNan<F>,
}

impl<F> PartialEq for StableEma<F>
where
  F: Float,
{
  fn eq(&self, other: &Self) -> bool {
    self.ema.eq(&other.ema) && self.recent_weight.eq(&other.recent_weight)
  }
}

impl<F> Eq for StableEma<F> where F: Float {}

impl<F> PartialOrd for StableEma<F>
where
  F: Float,
{
  fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
    Some(self.cmp(other))
  }
}

impl<F> Ord for StableEma<F>
where
  F: Float,
{
  fn cmp(&self, other: &Self) -> Ordering {
    self.ema.cmp(&other.ema).then_with(|| self.recent_weight.cmp(&other.recent_weight))
  }
}

impl<F> Default for StableEma<F>
where
  F: Float,
{
  fn default() -> Self {
    Self {
      ema: Ema::default(),
      // Doing panics and stuff to avoid trait bounds.
      recent_weight: NotNan::new(F::from(0.1).unwrap_or_else(|| panic!("cannot fail"))).unwrap_or_else(|_| panic!("inner is a number")),
    }
  }
}

impl<F> StableEma<F>
where
  F: Float,
{
  /// Returns a new `StableEma` with the `mean`, `variance`, and `recent_weight` all initialized.
  ///
  /// It is recommended to choose the `mean` and `variance` to be as close to expected as possible so that they can converge quickly
  pub fn new(mean: NotNan<F>, variance: NotNan<F>, recent_weight: NotNan<F>) -> Self {
    Self {
      ema: Ema::new(mean, variance),
      recent_weight,
    }
  }

  /// Tries to create a new `StableEma` from raw float values.
  /// # Errors
  /// Fails if `mean`, `variance`, or `recent_weight` are NaN
  pub fn try_new<T: TryInto<NotNan<F>, Error = FloatIsNan>>(mean: T, variance: T, recent_weight: T) -> Result<Self, FloatIsNan> {
    Ok(Self::new(mean.try_into()?, variance.try_into()?, recent_weight.try_into()?))
  }

  /// Accumulates the value to this `StableEma`
  pub fn accumulate(&mut self, value: NotNan<F>) {
    self.ema.accumulate(value, self.recent_weight)
  }

  /// Tries to accumulate a raw float value
  /// # Errors
  /// Fails if `value` is NaN
  pub fn try_accumulate(&mut self, value: F) -> Result<(), FloatIsNan> {
    self.accumulate(NotNan::new(value)?);
    Ok(())
  }

  /// Returns the mean of this `StableEma`
  #[inline]
  #[must_use]
  pub fn mean(&self) -> NotNan<F> {
    self.ema.mean()
  }

  /// Returns the variance of this `StableEma`
  #[inline]
  #[must_use]
  pub fn variance(&self) -> NotNan<F> {
    self.ema.variance()
  }

  /// Returns the standard deviation of this `StableEma`
  #[inline]
  #[must_use]
  pub fn std_dev(&self) -> NotNan<F> {
    self.ema.std_dev()
  }

  /// Returns the recent weight that this `StableEma` uses to accumulate values
  #[must_use]
  pub fn recent_weight(&self) -> NotNan<F> {
    self.recent_weight
  }

  /// Returns the mean of this `StableEma` as a duration in seconds. Useful when using an `Ema` to time events.
  #[inline]
  #[must_use]
  pub fn mean_duration(&self) -> Duration {
    self.ema.mean_duration()
  }

  /// Returns the standard deviation of this `StableEma` as a duration in seconds. Useful when using an `Ema` to time events.
  #[inline]
  #[must_use]
  pub fn std_dev_duration(&self) -> Duration {
    self.ema.std_dev_duration()
  }

  /// Change the recent weight.
  /// # Safety
  /// This is not unsafe to call, but it violates the notion that this has
  /// a stable recent weight
  #[allow(unsafe_code)]
  pub unsafe fn set_recent_weight(&mut self, recent_weight: NotNan<F>) {
    self.recent_weight = recent_weight;
  }
}

impl<F> core::fmt::Debug for StableEma<F>
where
  F: Float + core::fmt::Debug,
{
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("StableEMA")
      .field("mean", &*self.ema.mean)
      .field("variance", &*self.ema.variance)
      .field("recent_weight", &*self.recent_weight)
      .finish()
  }
}

#[cfg(test)]
mod test {
  use super::*;

  fn test_ema<F: Float + num_traits::FromPrimitive + core::fmt::Debug>(iters: u32, mean_epsilon: F, variance_epsilon: F) {
    let mut ema = StableEma::<F>::new(NotNan::one(), NotNan::zero(), NotNan::new(F::from_f64(0.2).unwrap()).unwrap());
    assert_eq!(*ema.mean(), F::one());
    assert_eq!(*ema.variance(), F::zero());
    assert_eq!(*ema.std_dev(), F::zero());
    assert_eq!(ema.mean_duration(), Duration::from_secs(1));
    assert_eq!(ema.std_dev_duration(), Duration::from_secs(0));
    assert_eq!(*ema.recent_weight(), F::from_f64(0.2).unwrap());
    (0..10000).for_each(|_| ema.accumulate(NotNan::one()));
    assert_eq!(ema.mean(), NotNan::one());
    assert_eq!(ema.variance(), NotNan::zero());

    (1..=iters).for_each(|i| {
      ema.accumulate(NotNan::new(F::from(i as f64).unwrap()).unwrap());
      if i > iters / 2 {
        assert!(
          (ema.mean() - F::from((i - 4) as f64).unwrap()).abs() <= mean_epsilon,
          "mean: {:?}",
          ema.mean()
        );
        assert!(
          (ema.variance() - F::from(20.0).unwrap()).abs() <= variance_epsilon,
          "variance: {:?}",
          ema.variance()
        );
        assert!(
          (ema.std_dev() - F::from(20.0.sqrt()).unwrap()).abs() <= variance_epsilon,
          "std_dev: {:?}",
          ema.std_dev()
        );
      }
    });
  }

  #[test]
  fn test_types() {
    use half::{bf16, f16};
    test_ema::<f32>(10000, 1e-7, 1e-5);
    let mut ema = StableEma::<f32>::default();
    ema.try_accumulate(f32::NAN).unwrap_err();
    test_ema::<f64>(100000, 1e-7, 1e-5);
    let mut ema = StableEma::<f64>::default();
    ema.try_accumulate(f64::NAN).unwrap_err();
    test_ema::<bf16>(250, bf16::from_f32(1e-7), bf16::from_f32(0.25));
    let mut ema = Ema::<bf16>::default();
    ema.try_accumulate(bf16::from_f32(f32::NAN), bf16::from_f32(0.5)).unwrap_err();
    test_ema::<f16>(500, f16::from_f32(1e-7), f16::from_f32(0.125));
    let mut ema = Ema::<f16>::default();
    ema.try_accumulate(f16::from_f32(f32::NAN), f16::from_f32(0.5)).unwrap_err();
  }
}