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
94 changes: 60 additions & 34 deletions app/nullius/charts.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,12 @@
_CHARS = 46 # a label's line length, at the template's font size; longer labels wrap, never clip
_BAR = 10.0
_ROW_GAP = 9.0
_LEFT, _RIGHT = 8.0, 70.0 # room before the plot, and after it for the values
_LEFT, _RIGHT = 8.0, 70.0 # room before the plot, and after it for the readings, more for a longer one
_AXIS = 20.0 # the tick labels under the rows
_DOT = 4.5
SERIES = 8 # the series colours, --series-1 to --series-8 in style.css
_CHAR_W = 7.0 # a character's width, at the template's font size
_CHAR_W = 7.8 # a character's width, at the template's font size: a digit's, wider than most others
_WIDTHS = {".": 3.6, "/": 5.0, "%": 12.1, "m": 11.4, "M": 10.6, "—": 10.2} # the rest of a label's, as drawn


@dataclass(frozen=True)
Expand Down Expand Up @@ -173,42 +174,61 @@ 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, metric: Metric) -> tuple:
"""A metric's ticks: around its present values, from zero when its marks grow from zero."""
def _ticks_for(values: list, with_zero: bool, metric: Metric, count: int = 4) -> tuple:
"""A metric's ticks, about ``count`` steps: 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)
ticks = nice_ticks(lo, hi, step_min=1 if whole else 0, bounds=metric.bounds)
ticks = nice_ticks(lo, hi, count, 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)
ticks = nice_ticks(lo, hi, count, step_min=2 * step, bounds=metric.bounds)
return ticks


def _width(text: str) -> float:
"""A tick label's or a reading's width at the template's font size, no less than it draws."""
return sum(_WIDTHS.get(ch, _CHAR_W) for ch in text)


def _span(t: Text) -> tuple:
"""Where a one-line text runs, from its anchor and its width."""
w = _width(t.lines[0])
x0 = {"start": t.x, "end": t.x - w, "middle": t.x - w / 2}[t.anchor]
return x0, x0 + w


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, 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]
while kept and kept[-1][1] + 6 > x0 and i == last and len(kept) > 1:
kept.pop()
if not kept or kept[-1][1] + 6 <= x0 or i == last:
kept.append((Text(x, y, (text,), anchor, "tick"), x0 + w))
return [t for t, _ in kept]
"""The labels of an x axis's ticks at ``y``, each centred on its gridline, or against the edge of the panel it
would cross."""
texts = []
for t, text in zip(scale.ticks, _tick_labels(fmt, scale.ticks)):
x, half = scale(t), _width(text) / 2
texts.append(Text(0.0, y, (text,), "start", "tick") if x < half else
Text(WIDTH, y, (text,), "end", "tick") if x + half > WIDTH else Text(x, y, (text,), "middle", "tick"))
return texts


def _x_scale(values: list, with_zero: bool, metric: Metric, a: float, b: float) -> _Scale:
"""An x axis onto [a, b], with the most ticks, four steps at most, whose labels keep apart: wide labels take
fewer ticks, so that every gridline keeps its label."""
for count in (4, 3, 2, 1):
scale = _Scale(_ticks_for(values, with_zero, metric, count), a, b)
spans = [_span(t) for t in _x_labels(scale, metric.fmt, 0)]
if all(s[1] + 6 <= n[0] for s, n in zip(spans, spans[1:])):
break
return scale


def _rows(metric: Metric, with_zero: bool, mark: Callable) -> Panel:
"""A row per item, its name over its mark, on one x axis: what bars and dots share. ``mark(v, scale, y)``
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."""
gives the marks of ``v`` at the row's centre ``y``, none for a gap, and the x its reading starts at, 10 past
the plot at most. 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), _LEFT, WIDTH - _RIGHT)
room = round(max((_width(v.text or "—") for v in metric.values), default=0) + 10, 2) # the longest reading's
scale = _x_scale(present, with_zero, metric, _LEFT, WIDTH - max(_RIGHT, room))
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 @@ -268,27 +288,30 @@ def _tag_box(px: float, py: float, width: float, side: str, radius=_DOT, extra=0
return x, base, anchor, (x0, base - _TAG_H + 3, x0 + width, base + 3 + extra)


def _overlaps(a: tuple, b: tuple) -> bool:
return a[0] < b[2] and b[0] < a[2] and a[1] < b[3] and b[1] < a[3]
def _overlap(a: tuple, b: tuple) -> float:
"""The area two boxes share: 0 when they are apart."""
return max(0.0, min(a[2], b[2]) - max(a[0], b[0])) * max(0.0, min(a[3], b[3]) - max(a[1], b[1]))


def scatter(x: Metric, y: Metric, *, tiles=False) -> Panel:
"""A dot per item at (x, y), and its tag (``Value.tag``, else its place in the order) beside it, spelled out in a
key under the plot. Every item keeps its own dot: items at one place are set in a ring around it, each tag outward
from its dot. Any other tag takes the first side of its dot inside the plot and clear of the dots and tags before
it."""
from its dot. Any other tag takes the first place beside its dot inside the plot and clear of the dots and tags
before it, else the one least over those tags, then over the dots."""
radius = 11 if tiles else _DOT
pairs = list(zip(x.values, y.values))
tags = [a.tag or str(i + 1) for i, (a, _) in enumerate(pairs)]
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), left + 12, right - 12)
# the scales inset from the frame, so a dot on the last tick is whole; the frame leaves the y labels their room
sy = _Scale(_ticks_for([b.value for _, _, b in shown], False, y), bottom - 12, top + 12)
ylabels = _tick_labels(y.fmt, sy.ticks)
left = max(left, round(4 + max(map(_width, ylabels)), 2))
sx = _x_scale([a.value for _, a, _ in shown], False, x, left + 12, right - 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, (text,), "end", "tick") for t, text in zip(sy.ticks, _tick_labels(y.fmt, sy.ticks))]
texts += [Text(left - 4, sy(t) + 4, (text,), "end", "tick") for t, text in zip(sy.ticks, ylabels)]
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 All @@ -311,7 +334,7 @@ def scatter(x: Metric, y: Metric, *, tiles=False) -> Panel:
placed.append((px, py, *rest))
dots = placed
taken = [(px - radius, py - radius, px + radius, py + radius) for px, py, *_ in dots]
taken += [(tx - _TAG_W, ty - _TAG_H + 3, tx + _TAG_W, ty + 3) for _, _, (tx, ty), *_ in (d for d in dots if d[2] and not tiles)]
tagged = [(tx - _TAG_W, ty - _TAG_H + 3, tx + _TAG_W, ty + 3) for _, _, (tx, ty), *_ in (d for d in dots if d[2] and not tiles)]
for px, py, at, tag, a, b in dots:
marks.append(Mark("tile" if tiles else "circle", px, py, r=radius, cls=a.cls("dot"), key=a.key,
title=f"{tag} {a.name}: {x.label} {a.reading}, {y.label} {b.reading}"))
Expand All @@ -320,12 +343,15 @@ def scatter(x: Metric, y: Metric, *, tiles=False) -> Panel:
continue
width = _TAG_W * max(len(tag), len(a.note) if tiles else 0)
extra = 15 if tiles and a.note else 0
offsets = [0] if not tiles else [0] + [sign*d for d in range(15, 211, 15) for sign in (1, -1)]
# a tile's label may slide far along its tile, a dot's tag beside it a line up or down (above or below it, a
# line would bring it onto its own dot)
offsets = [0] + [sign*d for d in range(15, 211 if tiles else 16, 15) for sign in (1, -1)]
spots = [_tag_box(px, py + offset, width, side, radius, extra)
for offset in offsets for side in ("right", "left", "above", "below")]
for offset in offsets for side in ("right", "left", "above", "below") if tiles or not offset or side in ("right", "left")]
inside = [s for s in spots if s[3][0] >= left and s[3][2] <= right and s[3][1] >= top and s[3][3] <= bottom]
tx, base, anchor, box = next((s for s in inside if not any(_overlaps(s[3], t) for t in taken)), (inside or spots)[0])
taken.append(box)
tx, base, anchor, box = min(inside or spots, key=lambda s: (sum(_overlap(s[3], t) for t in tagged),
sum(_overlap(s[3], t) for t in taken)))
tagged.append(box)
texts.append(Text(tx, base, (tag, a.note) if tiles and a.note else (tag,), anchor, "tag", key=a.key))
key_y = _S_HEIGHT + 8
key = _LEFT + (12 if any(a.series for a, _ in pairs) else 0)
Expand Down
76 changes: 59 additions & 17 deletions app/tests/test_categorical_charts.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,42 @@ def shapes(panel, cls):
return [m for m in panel.marks if cls in m.cls.split()]


def span(t):
"""Where a one-line text runs, measured here from its anchor and the module's text width."""
w = c._width(t.lines[0])
x0 = {"start": t.x, "end": t.x - w, "middle": t.x - w / 2}[t.anchor]
return x0, x0 + w


def x_labels(panel):
"""The tick labels under the plot, left to right, and the x of each vertical gridline."""
labels = sorted((t for t in panel.texts if t.cls == "tick" and t.y > max(m.y2 for m in panel.marks if m.cls == "grid")),
key=lambda t: t.x)
return labels, sorted({m.x for m in panel.marks if m.cls == "grid" and m.x == m.x2})


class Ticks(unittest.TestCase):
def test_round_steps_enclose_the_range(self):
self.assertEqual(c.nice_ticks(0, 1), (0, 0.25, 0.5, 0.75, 1))
self.assertEqual(c.nice_ticks(-3, 5), (-4, -2, 0, 2, 4, 6))
self.assertEqual(c.nice_ticks(0.0012, 0.0031)[0], 0.001)
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, 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.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_wide_tick_labels_take_fewer_ticks_and_every_gridline_keeps_its_label(self):
for fmt, expected in ((lambda v, step, top: f"${v:.2f}", ["$0.00", "$25.00", "$50.00", "$75.00", "$100.00"]),
(lambda v, step, top: f"${v:.4f}", ["$0.0000", "$50.0000", "$100.0000"])):
labels, grid = x_labels(c.bars(metric(0, 32, 85, 4, fmt=fmt)))
self.assertEqual([t.lines[0] for t in labels], expected)
self.assertEqual(len(grid), len(expected)) # a label on every gridline
spans = [span(t) for t in labels]
self.assertTrue(all(a[1] + 6 <= b[0] for a, b in zip(spans, spans[1:])), spans) # and none touching

def test_each_x_label_is_centred_on_its_gridline_where_the_panel_has_room(self):
labels, grid = x_labels(c.scatter(metric(0, 0.5, fmt=lambda v, step, top: f"${v:.2f}"), metric(0.4, 0.7)))
self.assertEqual([(t.x, t.anchor) for t in labels], [(x, "middle") for x in grid])
labels, grid = x_labels(c.bars(metric(0, 32, 85, 4, fmt=lambda v, step, top: f"${v:.2f}")))
self.assertEqual((labels[0].x, labels[0].anchor), (0, "start")) # no room before the first: the panel's edge
self.assertEqual([(t.x, t.anchor) for t in labels[1:]], [(x, "middle") for x in grid[1:]])

def test_one_value_still_has_a_range(self):
ticks = c.nice_ticks(5, 5)
Expand Down Expand Up @@ -92,6 +116,13 @@ def test_a_gap_has_no_dot_and_no_track(self):
p = c.dots(metric(1, None))
self.assertEqual((len(shapes(p, "dot")), len(shapes(p, "track"))), (1, 1))

def test_a_reading_never_passes_the_panel_s_right_edge(self):
m = c.Metric("Solved", (c.Value("a", 1234, "1234/2000"), c.Value("b", 1500, "1500/2000")))
for draw in (c.dots, c.bars):
readings = [t for t in draw(m).texts if t.cls == "value"]
self.assertEqual(len(readings), 2)
self.assertLessEqual(max(span(t)[1] for t in readings), c.WIDTH, draw.__name__)


class Scatter(unittest.TestCase):
def test_logo_tiles_keep_exact_tooltips_and_distinct_centres(self):
Expand Down Expand Up @@ -131,18 +162,29 @@ def test_logo_tiles_and_two_line_labels_do_not_overlap(self):
self.assertFalse(wide > 0 and high > 0, (box, other))

def test_tags_stay_inside_the_plot_and_clear_of_each_other(self):
values = [(0.40 + k * 0.002, 1 + k * 0.01) for k in range(7)] # a tight cluster
p = c.scatter(metric(*[a for a, _ in values]), metric(*[b for _, b in values]))
boxes = []
for t in (t for t in p.texts if t.cls == "tag"):
w = c._TAG_W * len(t.lines[0])
x0 = {"start": t.x, "end": t.x - w, "middle": t.x - w / 2}[t.anchor]
boxes.append((x0, t.y - c._TAG_H + 3, x0 + w, t.y + 3))
self.assertEqual(len(boxes), 7)
for box in boxes:
self.assertGreaterEqual(box[0], c._S_LEFT); self.assertLessEqual(box[2], c.WIDTH - 8)
clear = sum(not any(c._overlaps(a, b) for b in boxes if b is not a) for a in boxes)
self.assertGreaterEqual(clear, 5)
cluster = [(0.40 + k * 0.002, 1 + k * 0.01) for k in range(7)] # a tight cluster
close = [(0.87, 0.02), (0.64, 0.9), (0.51, 0.515), (0.51, 0.495), (0.5, 0.46)] # 3 and 4 nearly at one place
for values in (cluster, close):
p = c.scatter(metric(*[a for a, _ in values]), metric(*[b for _, b in values]))
boxes = []
for t in (t for t in p.texts if t.cls == "tag"):
w = c._TAG_W * len(t.lines[0])
x0 = {"start": t.x, "end": t.x - w, "middle": t.x - w / 2}[t.anchor]
boxes.append((x0, t.y - c._TAG_H + 3, x0 + w, t.y + 3))
self.assertEqual(len(boxes), len(values))
for i, box in enumerate(boxes):
self.assertGreaterEqual(box[0], c._S_LEFT); self.assertLessEqual(box[2], c.WIDTH - 8)
for other in boxes[i + 1:]: # measured here, not by the placement's own predicate
wide, high = (min(box[k + 2], other[k + 2]) - max(box[k], other[k]) for k in (0, 1))
self.assertFalse(wide > 0 and high > 0, (values, box, other))

def test_the_left_margin_fits_the_longest_y_label(self):
p = c.scatter(metric(0.4, 0.5, 0.6), metric(0.0012, 0.0016, 0.0019, fmt=lambda v, step, top: f"${v:.4f}"))
frame = min(m.x for m in p.marks if m.cls == "grid" and m.y == m.y2)
ys = [t for t in p.texts if t.cls == "tick" and t.anchor == "end" and t.x < frame]
self.assertEqual(len(ys), 5)
self.assertGreaterEqual(min(span(t)[0] for t in ys), 0) # inside the panel
self.assertLessEqual(max(span(t)[1] for t in ys), frame) # and clear of the plot

def test_a_tag_is_the_caller_s_and_a_run_missing_either_value_has_no_dot(self):
x = c.Metric("X", (c.Value("a", 1, "1", tag="3"), c.Value("b", None, "—", tag="5"), c.Value("d", 2, "2", tag="6")))
Expand Down