7be643f3a038365f58c2522910a7d769ce398991
[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
19         self.buckets = {}
20         for start_end in buckets:
21             if self._get_bucket(start_end[0]) is not None:
22                 raise Exception("Buckets overlap?!")
23             self.buckets[start_end] = 0
24         self.sigma = 0
25         self.median = RunningMedian()
26         self.maximum = None
27         self.minimum = None
28         self.count = 0
29
30     @staticmethod
31     def n_evenly_spaced_buckets(
32         min_bound: T,
33         max_bound: T,
34         n: int,
35     ) -> List[Tuple[T, T]]:
36         ret = []
37         stride = int((max_bound - min_bound) / n)
38         if stride <= 0:
39             raise Exception("Min must be < Max")
40         for bucket_start in range(min_bound, max_bound, stride):
41             ret.append((bucket_start, bucket_start + stride))
42         return ret
43
44     def _get_bucket(self, item: T) -> Optional[Tuple[T, T]]:
45         for start_end in self.buckets:
46             if start_end[0] <= item < start_end[1]:
47                 return start_end
48         return None
49
50     def add_item(self, item: T) -> bool:
51         bucket = self._get_bucket(item)
52         if bucket is None:
53             return False
54         self.count += 1
55         self.buckets[bucket] += 1
56         self.sigma += item
57         self.median.add_number(item)
58         if self.maximum is None or item > self.maximum:
59             self.maximum = item
60         if self.minimum is None or item < self.minimum:
61             self.minimum = item
62         return True
63
64     def add_items(self, lst: Iterable[T]) -> bool:
65         all_true = True
66         for item in lst:
67             all_true = all_true and self.add_item(item)
68         return all_true
69
70     def __repr__(self, width: int = 80, *, label_formatter: str = '%5s') -> 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         max_label_width = None
86         lowest_start = None
87         highest_end = None
88         for bucket in sorted(self.buckets, key=lambda x: x[0]):
89             start = bucket[0]
90             if lowest_start is None:
91                 lowest_start = start
92             end = bucket[1]
93             if highest_end is None or end > highest_end:
94                 highest_end = end
95             label = f'[{label_formatter}..{label_formatter}): ' % (start, end)
96             label_width = len(label)
97             if max_label_width is None or label_width > max_label_width:
98                 max_label_width = label_width
99             if start == last_bucket_start:
100                 break
101         sigma_label = f'[{label_formatter}..{label_formatter}): ' % (
102             lowest_start,
103             highest_end,
104         )
105         if len(sigma_label) > max_label_width:
106             max_label_width = len(sigma_label)
107         bar_width = width - (max_label_width + 16)
108
109         for bucket in sorted(self.buckets, key=lambda x: x[0]):
110             start = bucket[0]
111             end = bucket[1]
112             label = f'[{label_formatter}..{label_formatter}): ' % (start, end)
113             pop = self.buckets[bucket]
114             bar = bar_graph(
115                 (pop / max_population),
116                 include_text=False,
117                 width=bar_width,
118                 left_end="",
119                 right_end="",
120             )
121             txt += label.rjust(max_label_width)
122             txt += bar
123             txt += f"({pop/self.count*100.0:5.2f}% n={pop})\n"
124             if start == last_bucket_start:
125                 break
126         txt += '-' * width + '\n'
127         txt += sigma_label.rjust(max_label_width)
128         txt += ' ' * (bar_width - 2)
129         txt += f'Σ=(100.00% n={self.count})\n'
130         return txt