Clean up histogram __repr__
[python_utils.git] / histogram.py
index ca67839da4cb7a7031df835690c30dc9dde15c73..7be643f3a038365f58c2522910a7d769ce398991 100644 (file)
@@ -4,10 +4,6 @@ import math
 from numbers import Number
 from typing import Generic, Iterable, List, Optional, Tuple, TypeVar
 
-from math_utils import RunningMedian
-from text_utils import bar_graph
-
-
 T = TypeVar("T", bound=Number)
 
 
@@ -18,6 +14,8 @@ class SimpleHistogram(Generic[T]):
     NEGATIVE_INFINITY = -math.inf
 
     def __init__(self, buckets: List[Tuple[T, T]]):
+        from math_utils import RunningMedian
+
         self.buckets = {}
         for start_end in buckets:
             if self._get_bucket(start_end[0]) is not None:
@@ -31,9 +29,9 @@ class SimpleHistogram(Generic[T]):
 
     @staticmethod
     def n_evenly_spaced_buckets(
-            min_bound: T,
-            max_bound: T,
-            n: int,
+        min_bound: T,
+        max_bound: T,
+        n: int,
     ) -> List[Tuple[T, T]]:
         ret = []
         stride = int((max_bound - min_bound) / n)
@@ -69,36 +67,64 @@ class SimpleHistogram(Generic[T]):
             all_true = all_true and self.add_item(item)
         return all_true
 
-    def __repr__(self) -> str:
+    def __repr__(self, width: int = 80, *, label_formatter: str = '%5s') -> str:
+        from text_utils import bar_graph
+
         max_population: Optional[int] = None
         for bucket in self.buckets:
             pop = self.buckets[bucket]
             if pop > 0:
-                last_bucket_start = bucket[0]
+                last_bucket_start = bucket[0]  # beginning of range
             if max_population is None or pop > max_population:
-                max_population = pop
+                max_population = pop  # bucket with max items
+
         txt = ""
         if max_population is None:
             return txt
 
-        for bucket in sorted(self.buckets, key=lambda x : x[0]):
-            pop = self.buckets[bucket]
+        max_label_width = None
+        lowest_start = None
+        highest_end = None
+        for bucket in sorted(self.buckets, key=lambda x: x[0]):
             start = bucket[0]
+            if lowest_start is None:
+                lowest_start = start
             end = bucket[1]
+            if highest_end is None or end > highest_end:
+                highest_end = end
+            label = f'[{label_formatter}..{label_formatter}): ' % (start, end)
+            label_width = len(label)
+            if max_label_width is None or label_width > max_label_width:
+                max_label_width = label_width
+            if start == last_bucket_start:
+                break
+        sigma_label = f'[{label_formatter}..{label_formatter}): ' % (
+            lowest_start,
+            highest_end,
+        )
+        if len(sigma_label) > max_label_width:
+            max_label_width = len(sigma_label)
+        bar_width = width - (max_label_width + 16)
+
+        for bucket in sorted(self.buckets, key=lambda x: x[0]):
+            start = bucket[0]
+            end = bucket[1]
+            label = f'[{label_formatter}..{label_formatter}): ' % (start, end)
+            pop = self.buckets[bucket]
             bar = bar_graph(
                 (pop / max_population),
-                include_text = False,
-                width = 70,
-                left_end = "",
-                right_end = "")
-            label = f'{start}..{end}'
-            txt += f'{label:12}: ' + bar + f"({pop}) ({len(bar)})\n"
+                include_text=False,
+                width=bar_width,
+                left_end="",
+                right_end="",
+            )
+            txt += label.rjust(max_label_width)
+            txt += bar
+            txt += f"({pop/self.count*100.0:5.2f}% n={pop})\n"
             if start == last_bucket_start:
                 break
-
-        txt = txt + f'''{self.count} item(s)
-{self.maximum} max
-{self.minimum} min
-{self.sigma/self.count:.3f} mean
-{self.median.get_median()} median'''
+        txt += '-' * width + '\n'
+        txt += sigma_label.rjust(max_label_width)
+        txt += ' ' * (bar_width - 2)
+        txt += f'Σ=(100.00% n={self.count})\n'
         return txt