Skip to main content

tetsy_stats/
lib.rs

1// Copyright 2015-2020 Parity Technologies (UK) Ltd.
2// This file is part of Tetsy Vapory.
3
4// Tetsy Vapory is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Tetsy Vapory is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Tetsy Vapory.  If not, see <http://www.gnu.org/licenses/>.
16
17//! Statistical functions and helpers.
18
19use std::iter::FromIterator;
20use std::ops::{Add, Sub, Deref, Div};
21
22#[macro_use]
23extern crate log;
24
25/// Sorted corpus of data.
26#[derive(Debug, Clone, PartialEq)]
27pub struct Corpus<T>(Vec<T>);
28
29impl<T: Ord> From<Vec<T>> for Corpus<T> {
30	fn from(mut data: Vec<T>) -> Self {
31		data.sort();
32		Corpus(data)
33	}
34}
35
36impl<T: Ord> FromIterator<T> for Corpus<T> {
37	fn from_iter<I: IntoIterator<Item=T>>(iterable: I) -> Self {
38		iterable.into_iter().collect::<Vec<_>>().into()
39	}
40}
41
42impl<T> Deref for Corpus<T> {
43	type Target = [T];
44
45	fn deref(&self) -> &[T] { &self.0[..] }
46}
47
48impl<T: Ord> Corpus<T> {
49	/// Get given percentile (approximated).
50	pub fn percentile(&self, val: usize) -> Option<&T> {
51		let len = self.0.len();
52		let x = val * len / 100;
53		let x = ::std::cmp::min(x, len);
54		if x == 0 {
55			return None;
56		}
57
58		self.0.get(x - 1)
59	}
60
61	/// Get the median element, if it exists.
62	pub fn median(&self) -> Option<&T> {
63		self.0.get(self.0.len() / 2)
64	}
65
66	/// Whether the corpus is empty.
67	pub fn is_empty(&self) -> bool {
68		self.0.is_empty()
69	}
70
71	/// Number of elements in the corpus.
72	pub fn len(&self) -> usize {
73		self.0.len()
74	}
75}
76
77impl<T: Ord + Copy + ::std::fmt::Display> Corpus<T>
78	where T: Add<Output=T> + Sub<Output=T> + Div<Output=T> + From<usize>
79{
80	/// Create a histogram of this corpus if it at least spans the buckets. Bounds are left closed.
81	/// Excludes outliers.
82	pub fn histogram(&self, bucket_number: usize) -> Option<Histogram<T>> {
83		// TODO: get outliers properly.
84		let upto = self.len() - self.len() / 40;
85		Histogram::create(&self.0[..upto], bucket_number)
86	}
87}
88
89/// Discretised histogram.
90#[derive(Debug, PartialEq)]
91pub struct Histogram<T> {
92	/// Bounds of each bucket.
93	pub bucket_bounds: Vec<T>,
94	/// Count within each bucket.
95	pub counts: Vec<usize>,
96}
97
98impl<T: Ord + Copy + ::std::fmt::Display> Histogram<T>
99	where T: Add<Output=T> + Sub<Output=T> + Div<Output=T> + From<usize>
100{
101	// Histogram of a sorted corpus if it at least spans the buckets. Bounds are left closed.
102	fn create(corpus: &[T], bucket_number: usize) -> Option<Histogram<T>> {
103		if corpus.len() < 1 { return None; }
104		let corpus_end = corpus.last().expect("there is at least 1 element; qed").clone();
105		let corpus_start = corpus.first().expect("there is at least 1 element; qed").clone();
106		trace!(target: "stats", "Computing histogram from {} to {} with {} buckets.", corpus_start, corpus_end, bucket_number);
107		// Bucket needs to be at least 1 wide.
108		let bucket_size = {
109			// Round up to get the entire corpus included.
110			let raw_bucket_size = (corpus_end - corpus_start + bucket_number.into()) / bucket_number.into();
111			if raw_bucket_size == 0.into() { 1.into() } else { raw_bucket_size }
112		};
113		let mut bucket_end = corpus_start + bucket_size;
114
115		let mut bucket_bounds = vec![corpus_start; bucket_number + 1];
116		let mut counts = vec![0; bucket_number];
117		let mut corpus_i = 0;
118		// Go through the corpus adding to buckets.
119		for bucket in 0..bucket_number {
120			while corpus.get(corpus_i).map_or(false, |v| v < &bucket_end) {
121				// Initialized to size bucket_number above; iterates up to bucket_number; qed
122				counts[bucket] += 1;
123				corpus_i += 1;
124			}
125			// Initialized to size bucket_number + 1 above; iterates up to bucket_number; subscript is in range; qed
126			bucket_bounds[bucket + 1] = bucket_end;
127			bucket_end = bucket_end + bucket_size;
128		}
129		Some(Histogram { bucket_bounds: bucket_bounds, counts: counts })
130	}
131}
132
133#[cfg(test)]
134mod tests {
135	use super::*;
136
137	#[test]
138	fn check_corpus() {
139		let corpus = Corpus::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
140		assert_eq!(corpus.percentile(0), None);
141		assert_eq!(corpus.percentile(1), None);
142		assert_eq!(corpus.percentile(101), Some(&10));
143		assert_eq!(corpus.percentile(100), Some(&10));
144		assert_eq!(corpus.percentile(50), Some(&5));
145		assert_eq!(corpus.percentile(60), Some(&6));
146		assert_eq!(corpus.median(), Some(&6));
147	}
148
149	#[test]
150	fn check_histogram() {
151		let hist = Histogram::create(&[643,689,1408,2000,2296,2512,4250,4320,4842,4958,5804,6065,6098,6354,7002,7145,7845,8589,8593,8895], 5).unwrap();
152		let correct_bounds: Vec<usize> = vec![643, 2294, 3945, 5596, 7247, 8898];
153		assert_eq!(Histogram { bucket_bounds: correct_bounds, counts: vec![4,2,4,6,4] }, hist);
154	}
155
156	#[test]
157	fn smaller_data_range_than_bucket_range() {
158		assert_eq!(
159			Histogram::create(&[1, 2, 2], 3),
160			Some(Histogram { bucket_bounds: vec![1, 2, 3, 4], counts: vec![1, 2, 0] })
161		);
162	}
163
164	#[test]
165	fn data_range_is_not_multiple_of_bucket_range() {
166		assert_eq!(
167			Histogram::create(&[1, 2, 5], 2),
168			Some(Histogram { bucket_bounds: vec![1, 4, 7], counts: vec![2, 1] })
169		);
170	}
171
172	#[test]
173	fn data_range_is_multiple_of_bucket_range() {
174		assert_eq!(
175			Histogram::create(&[1, 2, 6], 2),
176			Some(Histogram { bucket_bounds: vec![1, 4, 7], counts: vec![2, 1] })
177		);
178	}
179
180	#[test]
181	fn none_when_too_few_data() {
182		assert!(Histogram::<usize>::create(&[], 1).is_none());
183	}
184}