From b0797ddfe82af96e938ee1ec8c9feeea19a6ab7b Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Tue, 24 Nov 2026 15:07:19 +0100 Subject: [PATCH 1/3] fix(compare): start an all-zero chart axis at zero, in every chart kind nice_ticks padded a single value both ways, so an axis of zeros ran from -1 to 1, and a cost axis mixed $-1.0000 with $1.00. A zero now gets 0 to 1; the bars' own special case for it goes. --- app/nullius/charts.py | 8 +++----- app/tests/test_categorical_charts.py | 10 ++++++++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/app/nullius/charts.py b/app/nullius/charts.py index b6caf277..df8b8af8 100644 --- a/app/nullius/charts.py +++ b/app/nullius/charts.py @@ -116,9 +116,9 @@ def nice_ticks(lo: float, hi: float, count: int = 4, step_min: float = 0.0) -> t """Round ticks enclosing ``[lo, hi]``, about ``count`` steps, none finer than ``step_min``; ints where whole.""" if hi < lo: lo, hi = hi, lo - if hi == lo: - pad = abs(lo) * 0.1 or 1.0 - lo, hi = lo - pad, hi + pad + if hi == lo: # one value: a range around it, and none below zero when it is zero + pad = abs(lo) * 0.1 + lo, hi = (lo - pad, hi + pad) if pad else (0, 1) raw = (hi - lo) / count mag = 10 ** math.floor(math.log10(raw)) step = max(next(m * mag for m in (1, 2, 2.5, 5, 10) if m * mag >= raw), step_min) @@ -150,8 +150,6 @@ def _ticks_for(values: list, with_zero: bool) -> tuple: if with_zero: values = values + [0] lo, hi = (min(values), max(values)) if values else (0, 1) - if with_zero and lo == hi == 0: - hi = 1 whole = values and all(isinstance(v, int) for v in values) return nice_ticks(lo, hi, step_min=1 if whole else 0) diff --git a/app/tests/test_categorical_charts.py b/app/tests/test_categorical_charts.py index cb492bfd..a9f86478 100644 --- a/app/tests/test_categorical_charts.py +++ b/app/tests/test_categorical_charts.py @@ -31,6 +31,16 @@ def test_one_value_still_has_a_range(self): ticks = c.nice_ticks(5, 5) self.assertLess(ticks[0], 5); self.assertGreater(ticks[-1], 5) + def test_an_all_zero_axis_starts_at_zero_in_every_chart_kind(self): + usd = lambda v: f"${v:.4f}" if v < 0.01 else f"${v:.2f}" # the cost column's own format + for name, panel in (("bars", c.bars(metric(0, 0, fmt=usd))), ("dots", c.dots(metric(0, 0, fmt=usd))), + ("scatter", c.scatter(metric(0, 0, fmt=usd), metric(0, 0, fmt=usd)))): + with self.subTest(name): + ticks = [t.lines[0] for t in panel.texts if t.cls == "tick"] + self.assertEqual(ticks[0], "0") + self.assertFalse([t for t in ticks if "-" in t], ticks) + self.assertEqual({len(t.split(".")[-1]) for t in ticks if t != "0"}, {2}, ticks) # one format past the origin + class Bars(unittest.TestCase): def test_a_bar_per_present_value_from_zero_on_the_metric_s_own_axis(self): From b558e6feb7ebcc29414fbbbc7206f022f32fec44 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Tue, 24 Nov 2026 15:45:38 +0100 Subject: [PATCH 2/3] fix(compare): write each chart axis in one format, every tick its own, inside the metric's range A tick label used the value formatter, so labels repeated after rounding ($0.02 five times), changed precision or unit within an axis (0 $0.0025 $0.01, 500 beside 1.0k, 30s 1m 2m) and the origin read a bare 0. An axis now picks one unit from its largest tick and the decimals its step needs in that unit. A rate's axis keeps to 0 to 100%: one value at a bound pads inwards only. --- app/nullius/charts.py | 53 ++++++++++++++++++-------- app/tests/test_categorical_charts.py | 16 ++------ app/ui_tests/test_comparison_routes.py | 35 +++++++++++++++++ app/web/compare.py | 18 +++++++-- 4 files changed, 90 insertions(+), 32 deletions(-) diff --git a/app/nullius/charts.py b/app/nullius/charts.py index df8b8af8..29989248 100644 --- a/app/nullius/charts.py +++ b/app/nullius/charts.py @@ -3,7 +3,7 @@ The split: this module computes the geometry, in SVG user units, and ``templates/_charts.html`` draws it without arithmetic. -A caller passes :class:`Metric` objects, each a label, a tick formatter and one :class:`Value` per item, already +A caller passes :class:`Metric` objects, each a label, an axis formatter and one :class:`Value` per item, already computed and formatted as the caller shows them elsewhere: nothing here recomputes a value. A value of ``None`` is a gap, never a zero. A ``check`` item is drawn hollow and named so; nothing here ranks items. An item's ``series`` gives its marks one colour in every chart, the class ``s1`` to ``s8`` (cycling), which the stylesheet maps to @@ -63,11 +63,29 @@ def reading(self) -> str: return " ".join(filter(None, (self.text or "—", self.note))) +def places(step: float, least: int = 0) -> int: + """The fewest decimals, ``least`` at fewest, that write every multiple of ``step`` exactly.""" + p = least + while p < 12 and round(step, p) != round(step, 12): + p += 1 + return p + + +def number(v: float, step: float, top: float) -> str: + """A plain axis's tick: the decimals its step needs, the same for every tick.""" + return f"{v:.{places(step)}f}" + + @dataclass(frozen=True) class Metric: + """``fmt(v, step, top)`` writes the tick ``v`` of an axis whose ticks are ``step`` apart and reach ``top`` at most + in size: one unit and one precision for the whole axis, so that every label is its own. ``bounds`` (low, high), + either None, is the range the metric cannot leave (a rate's 0 and 1); the axis keeps to it.""" + label: str values: tuple - fmt: Callable = str # a tick's label + fmt: Callable = number + bounds: tuple = (None, None) @dataclass(frozen=True) @@ -112,13 +130,15 @@ def viewbox(self) -> str: return f"0 0 {self.width:g} {self.height:g}" -def nice_ticks(lo: float, hi: float, count: int = 4, step_min: float = 0.0) -> tuple: - """Round ticks enclosing ``[lo, hi]``, about ``count`` steps, none finer than ``step_min``; ints where whole.""" +def nice_ticks(lo: float, hi: float, count: int = 4, step_min: float = 0.0, bounds: tuple = (None, None)) -> tuple: + """Round ticks enclosing ``[lo, hi]``, about ``count`` steps, none finer than ``step_min``; ints where whole. One + value gets a range around it, inwards only from a bound, and none below zero when it is zero.""" if hi < lo: lo, hi = hi, lo - if hi == lo: # one value: a range around it, and none below zero when it is zero + if hi == lo: pad = abs(lo) * 0.1 - lo, hi = (lo - pad, hi + pad) if pad else (0, 1) + low, high = bounds + lo, hi = (max(lo - pad, low if low is not None else -math.inf), min(hi + pad, high if high is not None else math.inf)) if pad else (0, 1) raw = (hi - lo) / count mag = 10 ** math.floor(math.log10(raw)) step = max(next(m * mag for m in (1, 2, 2.5, 5, 10) if m * mag >= raw), step_min) @@ -131,8 +151,10 @@ def _clean(v: float): return int(v) if v == int(v) else v -def _tick(fmt: Callable, v) -> str: - return "0" if v == 0 else str(fmt(v)) +def _tick_labels(fmt: Callable, ticks: tuple) -> list: + """An axis's tick labels, in the one format ``fmt`` gives its step and its largest tick.""" + step, top = (ticks[1] - ticks[0]) if len(ticks) > 1 else 1, max(abs(t) for t in ticks) + return [str(fmt(t, step, top)) for t in ticks] class _Scale: @@ -145,13 +167,13 @@ def __call__(self, v: float) -> float: return round(self.a + (v - self.lo) / (self.hi - self.lo) * (self.b - self.a), 2) -def _ticks_for(values: list, with_zero: bool) -> tuple: +def _ticks_for(values: list, with_zero: bool, bounds: tuple = (None, None)) -> tuple: """A metric's ticks: around its present values, from zero when its marks grow from zero.""" if with_zero: values = values + [0] lo, hi = (min(values), max(values)) if values else (0, 1) whole = values and all(isinstance(v, int) for v in values) - return nice_ticks(lo, hi, step_min=1 if whole else 0) + return nice_ticks(lo, hi, step_min=1 if whole else 0, bounds=bounds) def _x_labels(scale: _Scale, fmt: Callable, y: float) -> list: @@ -159,8 +181,7 @@ def _x_labels(scale: _Scale, fmt: Callable, y: float) -> list: before it is left out, the last one never: the gridlines still mark every tick.""" last = len(scale.ticks) - 1 kept = [] - for i, t in enumerate(scale.ticks): - text = _tick(fmt, t) + for i, (t, text) in enumerate(zip(scale.ticks, _tick_labels(fmt, scale.ticks))): anchor = "start" if i == 0 else "end" if i == last else "middle" x, w = scale(t), len(text) * _CHAR_W x0 = {"start": x, "end": x - w, "middle": x - w / 2}[anchor] @@ -176,7 +197,7 @@ def _rows(metric: Metric, with_zero: bool, mark: Callable) -> Panel: gives the marks of ``v`` at the row's centre ``y``, none for a gap, and the x its reading starts at. The gridlines and the baseline's reference cross each row's band only, never a name.""" present = [v.value for v in metric.values if v.value is not None] - scale = _Scale(_ticks_for(present, with_zero), _LEFT, WIDTH - _RIGHT) + scale = _Scale(_ticks_for(present, with_zero, metric.bounds), _LEFT, WIDTH - _RIGHT) base = next((v for v in metric.values if v.baseline and v.value is not None), None) base = base if len(present) > 1 else None marks, texts, y = [], [], 4.0 @@ -250,12 +271,12 @@ def scatter(x: Metric, y: Metric) -> Panel: shown = [(t, a, b) for t, (a, b) in zip(tags, pairs) if a.value is not None and b.value is not None] left, right, top, bottom = _S_LEFT, WIDTH - 8, _S_TOP, _S_HEIGHT - _S_BOTTOM # the scales inset from the frame, so a dot on the last tick is whole - sx = _Scale(_ticks_for([a.value for _, a, _ in shown], False), left + 12, right - 12) - sy = _Scale(_ticks_for([b.value for _, _, b in shown], False), bottom - 12, top + 12) + sx = _Scale(_ticks_for([a.value for _, a, _ in shown], False, x.bounds), left + 12, right - 12) + sy = _Scale(_ticks_for([b.value for _, _, b in shown], False, y.bounds), bottom - 12, top + 12) marks = [Mark("line", sx(t), top, x2=sx(t), y2=bottom, cls="grid") for t in sx.ticks] marks += [Mark("line", left, sy(t), x2=right, y2=sy(t), cls="grid") for t in sy.ticks] texts = _x_labels(sx, x.fmt, bottom + 14) - texts += [Text(left - 4, sy(t) + 4, (_tick(y.fmt, t),), "end", "tick") for t in sy.ticks] + texts += [Text(left - 4, sy(t) + 4, (text,), "end", "tick") for t, text in zip(sy.ticks, _tick_labels(y.fmt, sy.ticks))] texts += [Text(left, 12, (y.label,), cls="axis-title"), Text(right, bottom + 30, (x.label,), "end", "axis-title")] places: dict = {} for item in shown: diff --git a/app/tests/test_categorical_charts.py b/app/tests/test_categorical_charts.py index a9f86478..b15bf494 100644 --- a/app/tests/test_categorical_charts.py +++ b/app/tests/test_categorical_charts.py @@ -5,7 +5,7 @@ from nullius import charts as c -def metric(*values, label="Metric", fmt=str): +def metric(*values, label="Metric", fmt=c.number): return c.Metric(label, tuple(c.Value(label=f"run {i}", value=v, text="—" if v is None else str(v)) for i, v in enumerate(values)), fmt) @@ -22,25 +22,15 @@ def test_round_steps_enclose_the_range(self): self.assertEqual(c.nice_ticks(0, 3, step_min=1), (0, 1, 2, 3)) # whole counts never step below one def test_long_tick_labels_that_would_touch_leave_one_out_never_the_last(self): - p = c.bars(metric(0, 32, 85, 4, fmt=lambda v: f"${v:.2f}")) + p = c.bars(metric(0, 32, 85, 4, fmt=lambda v, step, top: f"${v:.2f}")) labels = [t for t in p.texts if t.cls == "tick"] - self.assertEqual([t.lines[0] for t in labels], ["0", "$25.00", "$50.00", "$100.00"]) + self.assertEqual([t.lines[0] for t in labels], ["$0.00", "$25.00", "$50.00", "$100.00"]) self.assertEqual(len([m for m in p.marks if m.cls == "grid"]) // 4, 5) # every tick keeps its gridline def test_one_value_still_has_a_range(self): ticks = c.nice_ticks(5, 5) self.assertLess(ticks[0], 5); self.assertGreater(ticks[-1], 5) - def test_an_all_zero_axis_starts_at_zero_in_every_chart_kind(self): - usd = lambda v: f"${v:.4f}" if v < 0.01 else f"${v:.2f}" # the cost column's own format - for name, panel in (("bars", c.bars(metric(0, 0, fmt=usd))), ("dots", c.dots(metric(0, 0, fmt=usd))), - ("scatter", c.scatter(metric(0, 0, fmt=usd), metric(0, 0, fmt=usd)))): - with self.subTest(name): - ticks = [t.lines[0] for t in panel.texts if t.cls == "tick"] - self.assertEqual(ticks[0], "0") - self.assertFalse([t for t in ticks if "-" in t], ticks) - self.assertEqual({len(t.split(".")[-1]) for t in ticks if t != "0"}, {2}, ticks) # one format past the origin - class Bars(unittest.TestCase): def test_a_bar_per_present_value_from_zero_on_the_metric_s_own_axis(self): diff --git a/app/ui_tests/test_comparison_routes.py b/app/ui_tests/test_comparison_routes.py index 2221d7b5..81ae416a 100644 --- a/app/ui_tests/test_comparison_routes.py +++ b/app/ui_tests/test_comparison_routes.py @@ -617,5 +617,40 @@ def scored(task, groups): self.assertEqual([g["group"] for g in a.score_by_group], ["1", "2"]) +class ChartAxes(unittest.TestCase): + """Every axis of every chart kind writes its ticks in one format, each label its own, within the metric's range.""" + + def test_an_axis_s_tick_labels_are_distinct_in_one_format_inside_the_metric_s_range(self): + from types import SimpleNamespace + from web import compare as web_compare, filters + units = {"cost": filters._usd, "tokens": filters._tokens, "minutes": web_compare.MINUTES, + "rate": web_compare.POINTS, "score": web_compare.SCORE} + cases = [ # (unit, style, values) + ("cost", "dots", (0.01, 0.03)), ("cost", "dots", (0.02,)), ("tokens", "dots", (1000, 1100)), + ("minutes", "dots", (1.0, 3.0)), ("score", "dots", (0.001, 0.004)), + ("cost", "bars", (0.01,)), ("tokens", "bars", (1000,)), ("tokens", "bars", (1_000_000,)), ("minutes", "bars", (2.0,)), ("minutes", "bars", (0.5,)), + ("rate", "dots", (1.0, 1.0)), ("rate", "dots", (0.0,)), ("rate", "scatter", (1.0, 1.0)), + ("cost", "bars", (0.5,)), ("rate", "bars", (0.5,)), + ("cost", "bars", (0, 0)), ("cost", "dots", (0, 0)), ("cost", "scatter", (0, 0)), + ] + for unit, style, values in cases: + with self.subTest(unit=unit, style=style, values=values): + n = len(values) + jobs = [SimpleNamespace(agent_label=f"agent {i}", job_id=str(i), model_name="", is_control=False) for i in range(n)] + rows = {"m": {"label": "M", "values": list(values), "cells": [str(v) for v in values], + "deltas": [("", "")] * n, "unit": units[unit]}} + panel = web_compare.chart(rows, [{"i": i} for i in range(n)], jobs, style, ("m",) * len(web_compare.figures.STYLES[style].axes)) + ticks = [t for t in panel.texts if t.cls == "tick"] + low = max(t.y for t in ticks) # the x axis's labels, under the plot; a scatter's y labels above it + axes = [[t.lines[0] for t in ticks if t.y == low], [t.lines[0] for t in ticks if t.y != low]] + for labels in filter(None, axes): + self.assertEqual(len(set(labels)), len(labels), labels) # each its own + self.assertEqual(len({re.sub(r"[\d.]", "", t) for t in labels}), 1, labels) # one unit + self.assertEqual(len({len(t.partition(".")[2].rstrip("kMms%")) for t in labels}), 1, labels) # one precision + self.assertFalse([t for t in labels if "-" in t], labels) # never below zero + if unit == "rate": + self.assertLessEqual(max(float(t.rstrip("%")) for t in labels), 100, labels) + + if __name__ == "__main__": unittest.main() diff --git a/app/web/compare.py b/app/web/compare.py index bb47bc71..3a273439 100644 --- a/app/web/compare.py +++ b/app/web/compare.py @@ -347,8 +347,20 @@ def order_rank(t): } -# A row's tick labels: its difference's unit, but a rate's ticks are rates and a short run's in seconds. -AXIS = {POINTS: filters._pct, MINUTES: filters._runtime} +def _axis(*units): + """A row's tick labels, each unit ``(size, form, least)``: the first unit whose size the axis's largest tick reaches + writes every tick, at the decimals its step needs in that unit, ``least`` at fewest.""" + def fmt(v, step, top): + size, form, least = next((u for u in units if top >= u[0]), units[-1]) + return form.format(f"{v / size:.{figures.places(step / size, least)}f}") + return fmt + + +# A row's axis, by its difference's unit, as its cells read: a rate's ticks are rates, a short run's in seconds. +AXIS = {COUNT: _axis((1, "{}", 0)), SCORE: _axis((1, "{}", 2)), POINTS: _axis((0.01, "{}%", 0)), + MINUTES: _axis((1, "{}m", 0), (1 / 60, "{}s", 0)), filters._usd: _axis((1, "${}", 2)), + filters._tokens: _axis((1e6, "{}M", 2), (1e3, "{}k", 1), (1, "{}", 0))} +BOUNDS = {POINTS: (0, 1)} def chart(rows, columns, jobs, style, keys): @@ -369,7 +381,7 @@ def value(row, n, i): return figures.STYLES[style].draw(*( figures.Metric(rows[k]["label"], tuple(value(rows[k], n, c["i"]) for n, c in enumerate(columns, 1) if c["i"] is not None), - AXIS.get(rows[k]["unit"], rows[k]["unit"])) + AXIS.get(rows[k]["unit"], figures.number), BOUNDS.get(rows[k]["unit"], (None, None))) for k in keys)) From 74aaf3bf1112b34fa6cc318bf4c0319615963d58 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Tue, 24 Nov 2026 15:52:25 +0100 Subject: [PATCH 3/3] fix(compare): write a chart axis's origin without decimals, and rates and tokens in the fewest The origin keeps its unit and drops its decimals ($0, 0k, 0%, 0m). A rate or token axis whose step needs a decimal more than twice the step doubles it, so all rates of 100% read 90% 95% 100% and tokens 1000 and 1100 read 1.00k 1.05k 1.10k. --- app/nullius/charts.py | 26 +++++++++++++++-------- app/ui_tests/test_comparison_routes.py | 12 +++++++++-- app/web/compare.py | 29 +++++++++++++++----------- 3 files changed, 44 insertions(+), 23 deletions(-) diff --git a/app/nullius/charts.py b/app/nullius/charts.py index 29989248..849d270b 100644 --- a/app/nullius/charts.py +++ b/app/nullius/charts.py @@ -72,20 +72,23 @@ def places(step: float, least: int = 0) -> int: def number(v: float, step: float, top: float) -> str: - """A plain axis's tick: the decimals its step needs, the same for every tick.""" - return f"{v:.{places(step)}f}" + """A plain axis's tick: the decimals its step needs, the same for every tick; none at the origin.""" + return f"{v:.{0 if v == 0 else places(step)}f}" @dataclass(frozen=True) class Metric: """``fmt(v, step, top)`` writes the tick ``v`` of an axis whose ticks are ``step`` apart and reach ``top`` at most - in size: one unit and one precision for the whole axis, so that every label is its own. ``bounds`` (low, high), - either None, is the range the metric cannot leave (a rate's 0 and 1); the axis keeps to it.""" + in size: one unit and one precision for the whole axis, so that every label is its own; the origin may drop its + decimals. ``bounds`` (low, high), either None, is the range the metric cannot leave (a rate's 0 and 1); the axis + keeps to it. ``size(top)``, when given, is the unit ``fmt`` writes such an axis in: a step that needs a decimal + more in it than twice the step does is doubled, so the axis shows the fewest decimals (95%, not 92.5%).""" label: str values: tuple fmt: Callable = number bounds: tuple = (None, None) + size: Callable | None = None @dataclass(frozen=True) @@ -167,13 +170,18 @@ def __call__(self, v: float) -> float: return round(self.a + (v - self.lo) / (self.hi - self.lo) * (self.b - self.a), 2) -def _ticks_for(values: list, with_zero: bool, bounds: tuple = (None, None)) -> tuple: +def _ticks_for(values: list, with_zero: bool, metric: Metric) -> tuple: """A metric's ticks: around its present values, from zero when its marks grow from zero.""" if with_zero: values = values + [0] lo, hi = (min(values), max(values)) if values else (0, 1) whole = values and all(isinstance(v, int) for v in values) - return nice_ticks(lo, hi, step_min=1 if whole else 0, bounds=bounds) + ticks = nice_ticks(lo, hi, step_min=1 if whole else 0, bounds=metric.bounds) + if metric.size and len(ticks) > 1: + step, unit = ticks[1] - ticks[0], metric.size(max(abs(t) for t in ticks)) + if places(2 * step / unit) < places(step / unit): + ticks = nice_ticks(lo, hi, step_min=2 * step, bounds=metric.bounds) + return ticks def _x_labels(scale: _Scale, fmt: Callable, y: float) -> list: @@ -197,7 +205,7 @@ def _rows(metric: Metric, with_zero: bool, mark: Callable) -> Panel: gives the marks of ``v`` at the row's centre ``y``, none for a gap, and the x its reading starts at. The gridlines and the baseline's reference cross each row's band only, never a name.""" present = [v.value for v in metric.values if v.value is not None] - scale = _Scale(_ticks_for(present, with_zero, metric.bounds), _LEFT, WIDTH - _RIGHT) + scale = _Scale(_ticks_for(present, with_zero, metric), _LEFT, WIDTH - _RIGHT) base = next((v for v in metric.values if v.baseline and v.value is not None), None) base = base if len(present) > 1 else None marks, texts, y = [], [], 4.0 @@ -271,8 +279,8 @@ def scatter(x: Metric, y: Metric) -> Panel: shown = [(t, a, b) for t, (a, b) in zip(tags, pairs) if a.value is not None and b.value is not None] left, right, top, bottom = _S_LEFT, WIDTH - 8, _S_TOP, _S_HEIGHT - _S_BOTTOM # the scales inset from the frame, so a dot on the last tick is whole - sx = _Scale(_ticks_for([a.value for _, a, _ in shown], False, x.bounds), left + 12, right - 12) - sy = _Scale(_ticks_for([b.value for _, _, b in shown], False, y.bounds), bottom - 12, top + 12) + sx = _Scale(_ticks_for([a.value for _, a, _ in shown], False, x), left + 12, right - 12) + sy = _Scale(_ticks_for([b.value for _, _, b in shown], False, y), bottom - 12, top + 12) marks = [Mark("line", sx(t), top, x2=sx(t), y2=bottom, cls="grid") for t in sx.ticks] marks += [Mark("line", left, sy(t), x2=right, y2=sy(t), cls="grid") for t in sy.ticks] texts = _x_labels(sx, x.fmt, bottom + 14) diff --git a/app/ui_tests/test_comparison_routes.py b/app/ui_tests/test_comparison_routes.py index 81ae416a..0fe6aba5 100644 --- a/app/ui_tests/test_comparison_routes.py +++ b/app/ui_tests/test_comparison_routes.py @@ -618,13 +618,17 @@ def scored(task, groups): class ChartAxes(unittest.TestCase): - """Every axis of every chart kind writes its ticks in one format, each label its own, within the metric's range.""" + """Every axis of every chart kind writes its ticks in one format, each label its own, within the metric's range; + the origin keeps its unit and drops its decimals, and a rate or a token count takes the fewest decimals.""" def test_an_axis_s_tick_labels_are_distinct_in_one_format_inside_the_metric_s_range(self): from types import SimpleNamespace from web import compare as web_compare, filters units = {"cost": filters._usd, "tokens": filters._tokens, "minutes": web_compare.MINUTES, "rate": web_compare.POINTS, "score": web_compare.SCORE} + exact = {("rate", "dots", (1.0, 1.0)): ["90%", "95%", "100%"], ("tokens", "dots", (1000, 1100)): ["1.00k", "1.05k", "1.10k"], + ("tokens", "bars", (1000,)): ["0k", "0.5k", "1.0k"], ("cost", "bars", (0.5,)): ["$0", "$0.20", "$0.40", "$0.60"], + ("minutes", "bars", (2.0,)): ["0m", "0.5m", "1.0m", "1.5m", "2.0m"]} cases = [ # (unit, style, values) ("cost", "dots", (0.01, 0.03)), ("cost", "dots", (0.02,)), ("tokens", "dots", (1000, 1100)), ("minutes", "dots", (1.0, 3.0)), ("score", "dots", (0.001, 0.004)), @@ -646,10 +650,14 @@ def test_an_axis_s_tick_labels_are_distinct_in_one_format_inside_the_metric_s_ra for labels in filter(None, axes): self.assertEqual(len(set(labels)), len(labels), labels) # each its own self.assertEqual(len({re.sub(r"[\d.]", "", t) for t in labels}), 1, labels) # one unit - self.assertEqual(len({len(t.partition(".")[2].rstrip("kMms%")) for t in labels}), 1, labels) # one precision + origin = [t for t in labels if not re.sub(r"[^1-9]", "", t)] + self.assertFalse([t for t in origin if "." in t], labels) # a bare origin + self.assertLessEqual(len({len(t.partition(".")[2].rstrip("kMms%")) for t in labels if t not in origin}), 1, labels) # one precision self.assertFalse([t for t in labels if "-" in t], labels) # never below zero if unit == "rate": self.assertLessEqual(max(float(t.rstrip("%")) for t in labels), 100, labels) + if (unit, style, values) in exact: + self.assertEqual(axes[0], exact[unit, style, values]) if __name__ == "__main__": diff --git a/app/web/compare.py b/app/web/compare.py index 3a273439..77c5fb73 100644 --- a/app/web/compare.py +++ b/app/web/compare.py @@ -347,19 +347,22 @@ def order_rank(t): } -def _axis(*units): - """A row's tick labels, each unit ``(size, form, least)``: the first unit whose size the axis's largest tick reaches - writes every tick, at the decimals its step needs in that unit, ``least`` at fewest.""" +def _axis(*units, fewest=False): + """A row's tick labels and, with ``fewest``, its unit (``Metric.size``), each unit ``(size, form, least)``: the first + unit whose size the axis's largest tick reaches writes every tick, at the decimals its step needs in that unit, + ``least`` at fewest, and the origin with none.""" + unit = lambda top: next((u for u in units if top >= u[0]), units[-1]) + def fmt(v, step, top): - size, form, least = next((u for u in units if top >= u[0]), units[-1]) - return form.format(f"{v / size:.{figures.places(step / size, least)}f}") - return fmt + size, form, least = unit(top) + return form.format(f"{v / size:.{0 if v == 0 else figures.places(step / size, least)}f}") + return fmt, (lambda top: unit(top)[0]) if fewest else None # A row's axis, by its difference's unit, as its cells read: a rate's ticks are rates, a short run's in seconds. -AXIS = {COUNT: _axis((1, "{}", 0)), SCORE: _axis((1, "{}", 2)), POINTS: _axis((0.01, "{}%", 0)), +AXIS = {COUNT: _axis((1, "{}", 0)), SCORE: _axis((1, "{}", 2)), POINTS: _axis((0.01, "{}%", 0), fewest=True), MINUTES: _axis((1, "{}m", 0), (1 / 60, "{}s", 0)), filters._usd: _axis((1, "${}", 2)), - filters._tokens: _axis((1e6, "{}M", 2), (1e3, "{}k", 1), (1, "{}", 0))} + filters._tokens: _axis((1e6, "{}M", 0), (1e3, "{}k", 0), (1, "{}", 0), fewest=True)} BOUNDS = {POINTS: (0, 1)} @@ -379,10 +382,12 @@ def value(row, n, i): text=str(row["cells"][i]), note=row["deltas"][i][0], check=check, baseline=n == 1 and i == 0, tag=str(n), series=n) - return figures.STYLES[style].draw(*( - figures.Metric(rows[k]["label"], tuple(value(rows[k], n, c["i"]) for n, c in enumerate(columns, 1) if c["i"] is not None), - AXIS.get(rows[k]["unit"], figures.number), BOUNDS.get(rows[k]["unit"], (None, None))) - for k in keys)) + def metric(row): + fmt, size = AXIS.get(row["unit"], (figures.number, None)) + return figures.Metric(row["label"], tuple(value(row, n, c["i"]) for n, c in enumerate(columns, 1) if c["i"] is not None), + fmt, BOUNDS.get(row["unit"], (None, None)), size) + + return figures.STYLES[style].draw(*(metric(rows[k]) for k in keys)) def _charts_requested():