2 # -*- coding: utf-8 -*-
4 """A text-based simple histogram helper class."""
7 from dataclasses import dataclass
8 from typing import Dict, Generic, Iterable, List, Optional, Tuple, TypeVar
10 T = TypeVar("T", int, float)
17 """A collection of details about the internal histogram buckets."""
19 num_populated_buckets: int = 0
20 max_population: Optional[int] = None
21 last_bucket_start: Optional[int] = None
22 lowest_start: Optional[int] = None
23 highest_end: Optional[int] = None
24 max_label_width: Optional[int] = None
27 class SimpleHistogram(Generic[T]):
28 """A simple histogram."""
30 # Useful in defining wide open bottom/top bucket bounds:
31 POSITIVE_INFINITY = math.inf
32 NEGATIVE_INFINITY = -math.inf
34 def __init__(self, buckets: List[Tuple[Bound, Bound]]):
35 from math_utils import NumericPopulation
37 self.buckets: Dict[Tuple[Bound, Bound], Count] = {}
38 for start_end in buckets:
39 if self._get_bucket(start_end[0]) is not None:
40 raise Exception("Buckets overlap?!")
41 self.buckets[start_end] = 0
42 self.sigma: float = 0.0
43 self.stats: NumericPopulation = NumericPopulation()
44 self.maximum: Optional[T] = None
45 self.minimum: Optional[T] = None
49 def n_evenly_spaced_buckets(
53 ) -> List[Tuple[int, int]]:
54 ret: List[Tuple[int, int]] = []
55 stride = int((max_bound - min_bound) / n)
57 raise Exception("Min must be < Max")
58 imax = math.ceil(max_bound)
59 imin = math.floor(min_bound)
60 for bucket_start in range(imin, imax, stride):
61 ret.append((bucket_start, bucket_start + stride))
64 def _get_bucket(self, item: T) -> Optional[Tuple[int, int]]:
65 for start_end in self.buckets:
66 if start_end[0] <= item < start_end[1]:
70 def add_item(self, item: T) -> bool:
71 bucket = self._get_bucket(item)
75 self.buckets[bucket] += 1
77 self.stats.add_number(item)
78 if self.maximum is None or item > self.maximum:
80 if self.minimum is None or item < self.minimum:
84 def add_items(self, lst: Iterable[T]) -> bool:
87 all_true = all_true and self.add_item(item)
90 def get_bucket_details(self, label_formatter: str) -> BucketDetails:
91 details = BucketDetails()
92 for (start, end), pop in sorted(self.buckets.items(), key=lambda x: x[0]):
94 details.num_populated_buckets += 1
95 details.last_bucket_start = start
96 if details.max_population is None or pop > details.max_population:
97 details.max_population = pop
98 if details.lowest_start is None or start < details.lowest_start:
99 details.lowest_start = start
100 if details.highest_end is None or end > details.highest_end:
101 details.highest_end = end
102 label = f'[{label_formatter}..{label_formatter}): ' % (start, end)
103 label_width = len(label)
104 if details.max_label_width is None or label_width > details.max_label_width:
105 details.max_label_width = label_width
108 def __repr__(self, *, width: int = 80, label_formatter: str = '%d') -> str:
109 from text_utils import bar_graph
111 details = self.get_bucket_details(label_formatter)
113 if details.num_populated_buckets == 0:
115 assert details.max_label_width is not None
116 assert details.lowest_start is not None
117 assert details.highest_end is not None
118 assert details.max_population is not None
119 sigma_label = f'[{label_formatter}..{label_formatter}): ' % (
120 details.lowest_start,
123 if len(sigma_label) > details.max_label_width:
124 details.max_label_width = len(sigma_label)
125 bar_width = width - (details.max_label_width + 17)
127 for (start, end), pop in sorted(self.buckets.items(), key=lambda x: x[0]):
128 if start < details.lowest_start:
130 label = f'[{label_formatter}..{label_formatter}): ' % (start, end)
132 (pop / details.max_population),
138 txt += label.rjust(details.max_label_width)
140 txt += f"({pop/self.count*100.0:5.2f}% n={pop})\n"
141 if start == details.last_bucket_start:
143 txt += '-' * width + '\n'
144 txt += sigma_label.rjust(details.max_label_width)
145 txt += ' ' * (bar_width - 2)
146 txt += f' pop(Σn)={self.count}\n'
147 txt += ' ' * (bar_width + details.max_label_width - 2)
148 txt += f' mean(x̄)={self.stats.get_mean():.3f}\n'
149 txt += ' ' * (bar_width + details.max_label_width - 2)
150 txt += f' median(p50)={self.stats.get_median():.3f}\n'
151 txt += ' ' * (bar_width + details.max_label_width - 2)
152 txt += f' mode(Mo)={self.stats.get_mode()[0]:.3f}\n'
153 txt += ' ' * (bar_width + details.max_label_width - 2)
154 txt += f' stdev(σ)={self.stats.get_stdev():.3f}\n'