Home Reference Source

src/utils/ewma.ts

  1. /*
  2. * compute an Exponential Weighted moving average
  3. * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  4. * - heavily inspired from shaka-player
  5. */
  6.  
  7. class EWMA {
  8. private alpha_: number;
  9. private estimate_: number;
  10. private totalWeight_: number;
  11.  
  12. // About half of the estimated value will be from the last |halfLife| samples by weight.
  13. constructor (halfLife: number) {
  14. // Larger values of alpha expire historical data more slowly.
  15. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  16. this.estimate_ = 0;
  17. this.totalWeight_ = 0;
  18. }
  19.  
  20. sample (weight: number, value: number) {
  21. let adjAlpha = Math.pow(this.alpha_, weight);
  22. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  23. this.totalWeight_ += weight;
  24. }
  25.  
  26. getTotalWeight (): number {
  27. return this.totalWeight_;
  28. }
  29.  
  30. getEstimate (): number {
  31. if (this.alpha_) {
  32. let zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  33. return this.estimate_ / zeroFactor;
  34. } else {
  35. return this.estimate_;
  36. }
  37. }
  38. }
  39.  
  40. export default EWMA;