4 from numbers import Number
5 from typing import Dict, Generic, Iterable, List, Optional, Tuple, TypeVar
7 T = TypeVar("T", int, float)
12 class SimpleHistogram(Generic[T]):
13 # Useful in defining wide open bottom/top bucket bounds:
14 POSITIVE_INFINITY = math.inf
15 NEGATIVE_INFINITY = -math.inf
17 def __init__(self, buckets: List[Tuple[Bound, Bound]]):
18 from math_utils import RunningMedian
20 self.buckets: Dict[Tuple[Bound, Bound], Count] = {}
21 for start_end in buckets:
22 if self._get_bucket(start_end[0]) is not None:
23 raise Exception("Buckets overlap?!")
24 self.buckets[start_end] = 0
25 self.sigma: float = 0.0
26 self.median: RunningMedian = RunningMedian()
27 self.maximum: Optional[T] = None
28 self.minimum: Optional[T] = None
32 def n_evenly_spaced_buckets(
36 ) -> List[Tuple[int, int]]:
37 ret: List[Tuple[int, int]] = []
38 stride = int((max_bound - min_bound) / n)
40 raise Exception("Min must be < Max")
41 imax = math.ceil(max_bound)
42 imin = math.floor(min_bound)
43 for bucket_start in range(imin, imax, stride):
44 ret.append((bucket_start, bucket_start + stride))
47 def _get_bucket(self, item: T) -> Optional[Tuple[int, int]]:
48 for start_end in self.buckets:
49 if start_end[0] <= item < start_end[1]:
53 def add_item(self, item: T) -> bool:
54 bucket = self._get_bucket(item)
58 self.buckets[bucket] += 1
60 self.median.add_number(item)
61 if self.maximum is None or item > self.maximum:
63 if self.minimum is None or item < self.minimum:
67 def add_items(self, lst: Iterable[T]) -> bool:
70 all_true = all_true and self.add_item(item)
73 def __repr__(self, *, width: int = 80, label_formatter: str = '%d') -> str:
74 from text_utils import bar_graph
77 max_population: Optional[int] = None
78 for bucket in self.buckets:
79 pop = self.buckets[bucket]
81 last_bucket_start = bucket[0] # beginning of range
82 if max_population is None or pop > max_population:
83 max_population = pop # bucket with max items
84 if max_population is None:
87 max_label_width: Optional[int] = None
88 lowest_start: Optional[int] = None
89 highest_end: Optional[int] = None
90 for bucket in sorted(self.buckets, key=lambda x: x[0]):
92 if lowest_start is None:
95 if highest_end is None or end > highest_end:
97 label = f'[{label_formatter}..{label_formatter}): ' % (start, end)
98 label_width = len(label)
99 if max_label_width is None or label_width > max_label_width:
100 max_label_width = label_width
101 if start == last_bucket_start:
103 assert max_label_width is not None
104 assert lowest_start is not None
105 assert highest_end is not None
107 sigma_label = f'[{label_formatter}..{label_formatter}): ' % (
111 if len(sigma_label) > max_label_width:
112 max_label_width = len(sigma_label)
113 bar_width = width - (max_label_width + 16)
115 for bucket in sorted(self.buckets, key=lambda x: x[0]):
118 label = f'[{label_formatter}..{label_formatter}): ' % (start, end)
119 pop = self.buckets[bucket]
121 (pop / max_population),
127 txt += label.rjust(max_label_width)
129 txt += f"({pop/self.count*100.0:5.2f}% n={pop})\n"
130 if start == last_bucket_start:
132 txt += '-' * width + '\n'
133 txt += sigma_label.rjust(max_label_width)
134 txt += ' ' * (bar_width - 2)
135 txt += f'Σ=(100.00% n={self.count})\n'