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
use std::convert::TryFrom;

use serde::{Deserialize, Serialize};

use crate::Duration;

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Statistic {
    Min,
    Mean,
    P50,
    P90,
    P99,
    Max,
}

impl Statistic {
    pub fn all() -> Vec<Statistic> {
        vec![
            Statistic::Min,
            Statistic::Mean,
            Statistic::P50,
            Statistic::P90,
            Statistic::P99,
            Statistic::Max,
        ]
    }
}

impl std::fmt::Display for Statistic {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Statistic::Min => write!(f, "minimum"),
            Statistic::Mean => write!(f, "mean"),
            Statistic::P50 => write!(f, "50%ile"),
            Statistic::P90 => write!(f, "90%ile"),
            Statistic::P99 => write!(f, "99%ile"),
            Statistic::Max => write!(f, "maximum"),
        }
    }
}

pub trait HgramValue<T>: Copy + std::cmp::Ord + std::fmt::Display {
    // TODO Weird name because I can't figure out associated type mess in FanChart
    fn hgram_zero() -> T;
    fn to_u64(self) -> u64;
    fn from_u64(x: u64) -> T;
}

impl HgramValue<Duration> for Duration {
    fn hgram_zero() -> Duration {
        Duration::ZERO
    }
    fn to_u64(self) -> u64 {
        self.to_u64()
    }
    fn from_u64(x: u64) -> Duration {
        Duration::from_u64(x)
    }
}

impl HgramValue<u16> for u16 {
    fn hgram_zero() -> u16 {
        0
    }
    fn to_u64(self) -> u64 {
        self as u64
    }
    fn from_u64(x: u64) -> u16 {
        u16::try_from(x).unwrap()
    }
}

impl HgramValue<usize> for usize {
    fn hgram_zero() -> usize {
        0
    }
    fn to_u64(self) -> u64 {
        self as u64
    }
    fn from_u64(x: u64) -> usize {
        x as usize
    }
}

// TODO Maybe consider having a type-safe NonEmptyHistogram.
#[derive(Clone)]
pub struct Histogram<T: HgramValue<T>> {
    count: usize,
    histogram: histogram::Histogram,
    min: T,
    max: T,
}

impl<T: HgramValue<T>> Default for Histogram<T> {
    fn default() -> Histogram<T> {
        Histogram {
            count: 0,
            histogram: Default::default(),
            min: T::hgram_zero(),
            max: T::hgram_zero(),
        }
    }
}

impl<T: HgramValue<T>> Histogram<T> {
    pub fn new() -> Histogram<T> {
        Default::default()
    }

    pub fn add(&mut self, x: T) {
        if self.count == 0 {
            self.min = x;
            self.max = x;
        } else {
            self.min = self.min.min(x);
            self.max = self.max.max(x);
        }
        self.count += 1;
        self.histogram
            .increment(x.to_u64())
            .map_err(|err| format!("Can't add {}: {}", x, err))
            .unwrap();
    }

    pub fn remove(&mut self, x: T) {
        // TODO This doesn't update min/max! Why are we tracking that ourselves? Do we not trust
        // the lossiness of the underlying histogram?
        self.count -= 1;
        self.histogram
            .decrement(x.to_u64())
            .map_err(|err| format!("Can't remove {}: {}", x, err))
            .unwrap();
    }

    pub fn describe(&self) -> String {
        if self.count == 0 {
            return "no data yet".to_string();
        }

        format!(
            "{} count, 50%ile {}, 90%ile {}, 99%ile {}, min {}, mean {}, max {}",
            abstutil::prettyprint_usize(self.count),
            self.select(Statistic::P50).unwrap(),
            self.select(Statistic::P90).unwrap(),
            self.select(Statistic::P99).unwrap(),
            self.select(Statistic::Min).unwrap(),
            self.select(Statistic::Mean).unwrap(),
            self.select(Statistic::Max).unwrap(),
        )
    }

    /// None if empty
    pub fn percentile(&self, p: f64) -> Option<T> {
        if self.count == 0 {
            return None;
        }
        Some(T::from_u64(self.histogram.percentile(p).unwrap()))
    }

    pub fn select(&self, stat: Statistic) -> Option<T> {
        if self.count == 0 {
            return None;
        }
        let raw = match stat {
            Statistic::P50 => self.histogram.percentile(50.0).unwrap(),
            Statistic::P90 => self.histogram.percentile(90.0).unwrap(),
            Statistic::P99 => self.histogram.percentile(99.0).unwrap(),
            Statistic::Min => {
                return Some(self.min);
            }
            Statistic::Mean => self.histogram.mean().unwrap(),
            Statistic::Max => {
                return Some(self.max);
            }
        };
        Some(T::from_u64(raw))
    }

    pub fn count(&self) -> usize {
        self.count
    }

    /// Could implement PartialEq, but be a bit more clear how approximate this is
    pub fn seems_eq(&self, other: &Histogram<T>) -> bool {
        self.describe() == other.describe()
    }
}