4 from numbers import Number
5 from typing import Generic, Iterable, List, Optional, Tuple, TypeVar
7 T = TypeVar("T", bound=Number)
10 class SimpleHistogram(Generic[T]):
12 # Useful in defining wide open bottom/top bucket bounds:
13 POSITIVE_INFINITY = math.inf
14 NEGATIVE_INFINITY = -math.inf
16 def __init__(self, buckets: List[Tuple[T, T]]):
17 from math_utils import RunningMedian
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
25 self.median = RunningMedian()
31 def n_evenly_spaced_buckets(
35 ) -> List[Tuple[T, T]]:
37 stride = int((max_bound - min_bound) / n)
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))
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]:
50 def add_item(self, item: T) -> bool:
51 bucket = self._get_bucket(item)
55 self.buckets[bucket] += 1
57 self.median.add_number(item)
58 if self.maximum is None or item > self.maximum:
60 if self.minimum is None or item < self.minimum:
64 def add_items(self, lst: Iterable[T]) -> bool:
67 all_true = all_true and self.add_item(item)
70 def __repr__(self, *, width: int = 80, label_formatter: str = None) -> str:
71 from text_utils import bar_graph
73 max_population: Optional[int] = None
74 for bucket in self.buckets:
75 pop = self.buckets[bucket]
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
82 if max_population is None:
85 max_label_width = None
88 for bucket in sorted(self.buckets, key=lambda x: x[0]):
90 if lowest_start is None:
93 if highest_end is None or end > highest_end:
95 if label_formatter is None:
96 if type(start) == int and type(end) == int:
97 label_formatter = '%d'
98 elif type(start) == float and type(end) == float:
99 label_formatter = '%.2f'
101 label_formatter = '%s'
102 label = f'[{label_formatter}..{label_formatter}): ' % (start, end)
103 label_width = len(label)
104 if max_label_width is None or label_width > max_label_width:
105 max_label_width = label_width
106 if start == last_bucket_start:
108 sigma_label = f'[{label_formatter}..{label_formatter}): ' % (
112 if len(sigma_label) > max_label_width:
113 max_label_width = len(sigma_label)
114 bar_width = width - (max_label_width + 16)
116 for bucket in sorted(self.buckets, key=lambda x: x[0]):
119 label = f'[{label_formatter}..{label_formatter}): ' % (start, end)
120 pop = self.buckets[bucket]
122 (pop / max_population),
128 txt += label.rjust(max_label_width)
130 txt += f"({pop/self.count*100.0:5.2f}% n={pop})\n"
131 if start == last_bucket_start:
133 txt += '-' * width + '\n'
134 txt += sigma_label.rjust(max_label_width)
135 txt += ' ' * (bar_width - 2)
136 txt += f'Σ=(100.00% n={self.count})\n'