Various changes.
[python_utils.git] / histogram.py
1 #!/usr/bin/env python3
2
3 import math
4 from numbers import Number
5 from typing import Generic, Iterable, List, Optional, Tuple, TypeVar
6
7 T = TypeVar("T", bound=Number)
8
9
10 class SimpleHistogram(Generic[T]):
11
12     # Useful in defining wide open bottom/top bucket bounds:
13     POSITIVE_INFINITY = math.inf
14     NEGATIVE_INFINITY = -math.inf
15
16     def __init__(self, buckets: List[Tuple[T, T]]):
17         from math_utils import RunningMedian
18         self.buckets = {}
19         for start_end in buckets:
20             if self._get_bucket(start_end[0]) is not None:
21                 raise Exception("Buckets overlap?!")
22             self.buckets[start_end] = 0
23         self.sigma = 0
24         self.median = RunningMedian()
25         self.maximum = None
26         self.minimum = None
27         self.count = 0
28
29     @staticmethod
30     def n_evenly_spaced_buckets(
31             min_bound: T,
32             max_bound: T,
33             n: int,
34     ) -> List[Tuple[T, T]]:
35         ret = []
36         stride = int((max_bound - min_bound) / n)
37         if stride <= 0:
38             raise Exception("Min must be < Max")
39         for bucket_start in range(min_bound, max_bound, stride):
40             ret.append((bucket_start, bucket_start + stride))
41         return ret
42
43     def _get_bucket(self, item: T) -> Optional[Tuple[T, T]]:
44         for start_end in self.buckets:
45             if start_end[0] <= item < start_end[1]:
46                 return start_end
47         return None
48
49     def add_item(self, item: T) -> bool:
50         bucket = self._get_bucket(item)
51         if bucket is None:
52             return False
53         self.count += 1
54         self.buckets[bucket] += 1
55         self.sigma += item
56         self.median.add_number(item)
57         if self.maximum is None or item > self.maximum:
58             self.maximum = item
59         if self.minimum is None or item < self.minimum:
60             self.minimum = item
61         return True
62
63     def add_items(self, lst: Iterable[T]) -> bool:
64         all_true = True
65         for item in lst:
66             all_true = all_true and self.add_item(item)
67         return all_true
68
69     def __repr__(self,
70                  label_formatter='%10s') -> str:
71         from text_utils import bar_graph
72
73         max_population: Optional[int] = None
74         for bucket in self.buckets:
75             pop = self.buckets[bucket]
76             if pop > 0:
77                 last_bucket_start = bucket[0]  # beginning of range
78             if max_population is None or pop > max_population:
79                 max_population = pop  # bucket with max items
80
81         txt = ""
82         if max_population is None:
83             return txt
84
85         for bucket in sorted(self.buckets, key=lambda x : x[0]):
86             pop = self.buckets[bucket]
87             start = bucket[0]
88             end = bucket[1]
89             bar = bar_graph(
90                 (pop / max_population),
91                 include_text = False,
92                 width = 58,
93                 left_end = "",
94                 right_end = "")
95             label = f'{label_formatter}..{label_formatter}' % (start, end)
96             txt += f'{label:20}: ' + bar + f"({pop/self.count*100.0:5.2f}% n={pop})\n"
97             if start == last_bucket_start:
98                 break
99         return txt