Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 45 additions & 18 deletions app/nullius/charts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -63,11 +63,32 @@ 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; 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; 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 = str # a tick's label
fmt: Callable = number
bounds: tuple = (None, None)
size: Callable | None = None


@dataclass(frozen=True)
Expand Down Expand Up @@ -112,13 +133,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:
pad = abs(lo) * 0.1 or 1.0
lo, hi = lo - pad, hi + pad
pad = abs(lo) * 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)
Expand All @@ -131,8 +154,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:
Expand All @@ -145,24 +170,26 @@ 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, 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)
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)
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:
"""The labels of an x axis's ticks at ``y``, the end ones inside the panel. A label that would touch the one
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]
Expand All @@ -178,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), _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
Expand Down Expand Up @@ -252,12 +279,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), 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)
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:
Expand Down
6 changes: 3 additions & 3 deletions app/tests/test_categorical_charts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -22,9 +22,9 @@ 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):
Expand Down
43 changes: 43 additions & 0 deletions app/ui_tests/test_comparison_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -617,5 +617,48 @@ 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;
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)),
("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
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__":
unittest.main()
29 changes: 23 additions & 6 deletions app/web/compare.py
Original file line number Diff line number Diff line change
Expand Up @@ -347,8 +347,23 @@ 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, 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 = 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), fewest=True),
MINUTES: _axis((1, "{}m", 0), (1 / 60, "{}s", 0)), filters._usd: _axis((1, "${}", 2)),
filters._tokens: _axis((1e6, "{}M", 0), (1e3, "{}k", 0), (1, "{}", 0), fewest=True)}
BOUNDS = {POINTS: (0, 1)}


def chart(rows, columns, jobs, style, keys):
Expand All @@ -367,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"], rows[k]["unit"]))
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():
Expand Down
Loading