2 # -*- coding: utf-8 -*-
4 """A text-based simple histogram helper class."""
7 from typing import Dict, Generic, Iterable, List, Optional, Tuple, TypeVar
9 T = TypeVar("T", int, float)
14 class SimpleHistogram(Generic[T]):
15 """A simple histogram."""
17 # Useful in defining wide open bottom/top bucket bounds:
18 POSITIVE_INFINITY = math.inf
19 NEGATIVE_INFINITY = -math.inf
21 def __init__(self, buckets: List[Tuple[Bound, Bound]]):
22 from math_utils import RunningMedian
24 self.buckets: Dict[Tuple[Bound, Bound], Count] = {}
25 for start_end in buckets:
26 if self._get_bucket(start_end[0]) is not None:
27 raise Exception("Buckets overlap?!")
28 self.buckets[start_end] = 0
29 self.sigma: float = 0.0
30 self.median: RunningMedian = RunningMedian()
31 self.maximum: Optional[T] = None
32 self.minimum: Optional[T] = None
36 def n_evenly_spaced_buckets(
40 ) -> List[Tuple[int, int]]:
41 ret: List[Tuple[int, int]] = []
42 stride = int((max_bound - min_bound) / n)
44 raise Exception("Min must be < Max")
45 imax = math.ceil(max_bound)
46 imin = math.floor(min_bound)
47 for bucket_start in range(imin, imax, stride):
48 ret.append((bucket_start, bucket_start + stride))
51 def _get_bucket(self, item: T) -> Optional[Tuple[int, int]]:
52 for start_end in self.buckets:
53 if start_end[0] <= item < start_end[1]:
57 def add_item(self, item: T) -> bool:
58 bucket = self._get_bucket(item)
62 self.buckets[bucket] += 1
64 self.median.add_number(item)
65 if self.maximum is None or item > self.maximum:
67 if self.minimum is None or item < self.minimum:
71 def add_items(self, lst: Iterable[T]) -> bool:
74 all_true = all_true and self.add_item(item)
77 def __repr__(self, *, width: int = 80, label_formatter: str = '%d') -> str:
78 from text_utils import bar_graph
81 max_population: Optional[int] = None
82 for bucket in self.buckets:
83 pop = self.buckets[bucket]
85 last_bucket_start = bucket[0] # beginning of range
86 if max_population is None or pop > max_population:
87 max_population = pop # bucket with max items
88 if max_population is None:
91 max_label_width: Optional[int] = None
92 lowest_start: Optional[int] = None
93 highest_end: Optional[int] = None
94 for bucket in sorted(self.buckets, key=lambda x: x[0]):
96 if lowest_start is None:
99 if highest_end is None or end > highest_end:
101 label = f'[{label_formatter}..{label_formatter}): ' % (start, end)
102 label_width = len(label)
103 if max_label_width is None or label_width > max_label_width:
104 max_label_width = label_width
105 if start == last_bucket_start:
107 assert max_label_width is not None
108 assert lowest_start is not None
109 assert highest_end is not None
111 sigma_label = f'[{label_formatter}..{label_formatter}): ' % (
115 if len(sigma_label) > max_label_width:
116 max_label_width = len(sigma_label)
117 bar_width = width - (max_label_width + 16)
119 for bucket in sorted(self.buckets, key=lambda x: x[0]):
122 label = f'[{label_formatter}..{label_formatter}): ' % (start, end)
123 pop = self.buckets[bucket]
125 (pop / max_population),
131 txt += label.rjust(max_label_width)
133 txt += f"({pop/self.count*100.0:5.2f}% n={pop})\n"
134 if start == last_bucket_start:
136 txt += '-' * width + '\n'
137 txt += sigma_label.rjust(max_label_width)
138 txt += ' ' * (bar_width - 2)
139 txt += f'Σ=(100.00% n={self.count})\n'