| """Deterministic, information-complete plot rendering. |
| |
| ``PlotRenderer`` draws directly from ``plot_world_v1`` with Pillow. Unlike the |
| initial marker-only prototype, the image contains the information a solver needs: |
| numeric or categorical x ticks, numeric y ticks, title/axis labels, a |
| series-coloured legend, and line or grouped-bar geometry. |
| |
| Redacted points are never placed at their hidden y coordinate. A fixed vertical |
| strip at the point's observed x spans the complete data region, and the hidden |
| point breaks its line. Axis scaling uses ``world["render_domain"]`` when present; |
| otherwise it is derived from visible points only. Consequently completion worlds |
| that differ only in a hidden y value produce byte-identical pixel assets. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import io |
| from collections.abc import Iterable, Mapping, Sequence |
| from dataclasses import dataclass |
| from fractions import Fraction |
| from math import ceil, floor |
| from typing import Any |
|
|
| from ..dsl.ast import canonical_number_str, parse_number |
| from ..sources.base import World |
| from ..sources.world_ops import hidden_nodes |
| from .base import ( |
| GlyphRecord, |
| RenderedAssets, |
| RendererFamily, |
| RendererKind, |
| RenderError, |
| _encode_uint32_png, |
| build_render_manifest, |
| build_text_manifest, |
| font_sha256, |
| validate_rendered_assets, |
| ) |
|
|
| _NAME = "plot_renderer" |
| _VERSION = "3" |
| _KIND: RendererKind = "plot" |
| _MIN_WIDTH = 320 |
| _MIN_HEIGHT = 220 |
| _Y_TICKS = 5 |
| _MAX_X_TICKS = 16 |
|
|
|
|
| @dataclass(frozen=True) |
| class _Point: |
| node_id: str |
| x_label: str |
| x_value: Fraction | None |
| y: Fraction | None |
| y_label: str |
| hidden: bool |
|
|
|
|
| @dataclass(frozen=True) |
| class _Series: |
| node_id: str |
| label: str |
| points: tuple[_Point, ...] |
| hidden: bool |
|
|
|
|
| @dataclass(frozen=True) |
| class _Domain: |
| numeric_x: bool |
| x_min: Fraction |
| x_max: Fraction |
| y_min: Fraction |
| y_max: Fraction |
| x_labels: tuple[str, ...] |
|
|
| def manifest_record(self) -> dict[str, Any]: |
| return { |
| "numeric_x": self.numeric_x, |
| "x_min": canonical_number_str(self.x_min) if self.numeric_x else None, |
| "x_max": canonical_number_str(self.x_max) if self.numeric_x else None, |
| "y_min": canonical_number_str(self.y_min), |
| "y_max": canonical_number_str(self.y_max), |
| "x_labels": list(self.x_labels), |
| } |
|
|
|
|
| class _Canvas: |
| """Pillow RGBA canvas plus a same-pass integer owner canvas.""" |
|
|
| def __init__(self, width: int, height: int, family: RendererFamily) -> None: |
| import numpy as np |
| from matplotlib.font_manager import findfont |
| from PIL import Image, ImageDraw |
|
|
| self.width = width |
| self.height = height |
| self.family = family |
| self.image = Image.new("RGBA", (width, height), family.palette.get("background", "#FFFFFF")) |
| self.owner_image = Image.new("I", (width, height), 0) |
| self.draw = ImageDraw.Draw(self.image) |
| self.owner_draw = ImageDraw.Draw(self.owner_image) |
| self.owner_ids: list[str] = [] |
| self.owner_index: dict[str, int] = {} |
| self.glyphs: list[GlyphRecord] = [] |
| self._font_path = findfont(family.font_name, fallback_to_default=False) |
| self._font_sha256 = font_sha256(family.font_name) |
| self._font_cache: dict[int, Any] = {} |
| self._np = np |
|
|
| def _owner(self, node_id: str) -> int: |
| index = self.owner_index.get(node_id) |
| if index is None: |
| self.owner_ids.append(node_id) |
| index = len(self.owner_ids) |
| self.owner_index[node_id] = index |
| return index |
|
|
| def reserve(self, node_id: str) -> None: |
| self._owner(node_id) |
|
|
| def font(self, size: int) -> Any: |
| from PIL import ImageFont |
|
|
| size = max(7, int(size)) |
| font = self._font_cache.get(size) |
| if font is None: |
| font = ImageFont.truetype(self._font_path, size=size) |
| self._font_cache[size] = font |
| return font |
|
|
| def line( |
| self, |
| node_id: str, |
| xy: Sequence[tuple[float, float]], |
| *, |
| fill: str, |
| width: int, |
| ) -> None: |
| index = self._owner(node_id) |
| self.draw.line(xy, fill=fill, width=width, joint="curve") |
| self.owner_draw.line(xy, fill=index, width=max(1, width)) |
|
|
| def rectangle( |
| self, |
| node_id: str | None, |
| box: tuple[float, float, float, float], |
| *, |
| fill: str, |
| outline: str | None = None, |
| width: int = 1, |
| ) -> None: |
| self.draw.rectangle(box, fill=fill, outline=outline, width=width) |
| index = 0 if node_id is None else self._owner(node_id) |
| self.owner_draw.rectangle(box, fill=index) |
|
|
| def ellipse( |
| self, |
| node_id: str, |
| box: tuple[float, float, float, float], |
| *, |
| fill: str, |
| outline: str, |
| width: int = 1, |
| ) -> None: |
| index = self._owner(node_id) |
| self.draw.ellipse(box, fill=fill, outline=outline, width=width) |
| self.owner_draw.ellipse(box, fill=index) |
|
|
| def text( |
| self, |
| node_id: str, |
| text: str, |
| xy: tuple[float, float], |
| *, |
| size: int, |
| fill: str, |
| anchor: str, |
| max_width: float | None = None, |
| ) -> tuple[int, int, int, int] | None: |
| if not text: |
| return None |
| index = self._owner(node_id) |
| x, y, font, bbox = self._text_layout( |
| text, |
| xy, |
| size=size, |
| anchor=anchor, |
| max_width=max_width, |
| ) |
| self.draw.text((x, y), text, font=font, fill=fill, anchor=anchor) |
| self.owner_draw.text((x, y), text, font=font, fill=index, anchor=anchor) |
| self.glyphs.append( |
| GlyphRecord( |
| node_id=node_id, |
| text=text, |
| x0=bbox[0] / self.width, |
| y0=(self.height - bbox[3]) / self.height, |
| x1=bbox[2] / self.width, |
| y1=(self.height - bbox[1]) / self.height, |
| font_sha256=self._font_sha256, |
| ) |
| ) |
| return bbox |
|
|
| def text_bbox( |
| self, |
| text: str, |
| xy: tuple[float, float], |
| *, |
| size: int, |
| anchor: str, |
| max_width: float | None = None, |
| ) -> tuple[int, int, int, int]: |
| """Measure text exactly as :meth:`text` will draw it, without painting.""" |
| _, _, _, bbox = self._text_layout( |
| text, |
| xy, |
| size=size, |
| anchor=anchor, |
| max_width=max_width, |
| ) |
| return bbox |
|
|
| def _text_layout( |
| self, |
| text: str, |
| xy: tuple[float, float], |
| *, |
| size: int, |
| anchor: str, |
| max_width: float | None, |
| ) -> tuple[float, float, Any, tuple[int, int, int, int]]: |
| font_size = size |
| font = self.font(font_size) |
| if max_width is not None: |
| while font_size > 7: |
| probe = self.draw.textbbox(xy, text, font=font, anchor=anchor) |
| if probe[2] - probe[0] <= max_width: |
| break |
| font_size -= 1 |
| font = self.font(font_size) |
|
|
| x, y = xy |
| bbox = self.draw.textbbox((x, y), text, font=font, anchor=anchor) |
| if max_width is not None and bbox[2] - bbox[0] > max_width + 1: |
| raise RenderError(f"plot text does not fit its allotted width: {text!r}") |
|
|
| |
| |
| if bbox[0] < 2: |
| x += 2 - bbox[0] |
| if bbox[2] > self.width - 2: |
| x -= bbox[2] - (self.width - 2) |
| if bbox[1] < 2: |
| y += 2 - bbox[1] |
| if bbox[3] > self.height - 2: |
| y -= bbox[3] - (self.height - 2) |
| raw_bbox = self.draw.textbbox((x, y), text, font=font, anchor=anchor) |
| bbox = ( |
| floor(raw_bbox[0]), |
| floor(raw_bbox[1]), |
| ceil(raw_bbox[2]), |
| ceil(raw_bbox[3]), |
| ) |
| if bbox[0] < 0 or bbox[1] < 0 or bbox[2] > self.width or bbox[3] > self.height: |
| raise RenderError(f"plot glyph is outside the canvas: {text!r}, bbox={bbox!r}") |
| return x, y, font, bbox |
|
|
| def finish(self) -> tuple[bytes, bytes, dict[str, int]]: |
| owner_array = self._np.asarray(self.owner_image, dtype="<u4") |
| rgba_buf = io.BytesIO() |
| self.image.save(rgba_buf, format="PNG", compress_level=9, optimize=False) |
| counts = { |
| node_id: int(self._np.count_nonzero(owner_array == index)) |
| for node_id, index in self.owner_index.items() |
| } |
| return rgba_buf.getvalue(), _encode_uint32_png(owner_array), counts |
|
|
|
|
| class PlotRenderer: |
| """Deterministic renderer for ``plot_world_v1``.""" |
|
|
| name = _NAME |
| version = _VERSION |
| kind = _KIND |
|
|
| def render( |
| self, |
| world: World, |
| *, |
| renderer_id: str, |
| seed: int, |
| width: int, |
| height: int, |
| family: RendererFamily | None = None, |
| ) -> RenderedAssets: |
| if world.get("world_schema") != "plot_world_v1": |
| raise RenderError( |
| f"plot renderer expects plot_world_v1, got {world.get('world_schema')!r}" |
| ) |
| family = family or _PLOT_TRAIN_FAMILY |
| if family.kind != self.kind: |
| raise RenderError( |
| f"renderer family {family.name!r} has kind {family.kind!r}, expected {self.kind!r}" |
| ) |
| if renderer_id != family.name: |
| raise RenderError(f"renderer_id {renderer_id!r} does not match family {family.name!r}") |
| if width < _MIN_WIDTH or height < _MIN_HEIGHT: |
| raise RenderError( |
| f"plot canvas must be at least {_MIN_WIDTH}x{_MIN_HEIGHT}, got {width}x{height}" |
| ) |
|
|
| series = _parse_series(world) |
| domain = _build_domain(world, series) |
| canvas = _Canvas(width, height, family) |
| visible = _draw_plot(canvas, world, series, domain, family) |
| rgba_png, node_map_png, counts = canvas.finish() |
|
|
| manifest = build_render_manifest( |
| renderer_id=renderer_id, |
| renderer_name=self.name, |
| renderer_version=self.version, |
| family=family, |
| world=world, |
| seed=seed, |
| width=width, |
| height=height, |
| rgba_png=rgba_png, |
| node_map_png=node_map_png, |
| visible_node_ids=visible, |
| owner_ids=canvas.owner_ids, |
| node_pixel_counts=counts, |
| glyph_count=len(canvas.glyphs), |
| backend="pillow", |
| backend_version=_pillow_version(), |
| ) |
| manifest["render_domain"] = domain.manifest_record() |
| manifest["plot_type"] = _plot_type(world) |
| assets = RenderedAssets( |
| rgba_png=rgba_png, |
| node_map_png=node_map_png, |
| render_manifest=manifest, |
| text_manifest=build_text_manifest(canvas.glyphs, world=world), |
| ) |
| validate_rendered_assets(assets) |
| return assets |
|
|
|
|
| def _parse_series(world: World) -> tuple[_Series, ...]: |
| hidden = hidden_nodes(world) |
| raw_series = world.get("series", []) or [] |
| if not isinstance(raw_series, list) or not raw_series: |
| raise RenderError("plot world has no series") |
| output: list[_Series] = [] |
| seen: set[str] = set() |
| for raw in raw_series: |
| if not isinstance(raw, Mapping): |
| raise RenderError("plot series is not an object") |
| sid = str(raw.get("id", "")) |
| if not sid or sid in seen: |
| raise RenderError(f"plot series has a missing/duplicate id: {sid!r}") |
| seen.add(sid) |
| is_series_hidden = sid in hidden |
| points: list[_Point] = [] |
| raw_points = raw.get("points", []) or [] |
| if not isinstance(raw_points, list): |
| raise RenderError(f"plot series {sid!r} points are not a list") |
| for raw_point in raw_points: |
| if not isinstance(raw_point, Mapping): |
| raise RenderError(f"plot series {sid!r} contains a non-object point") |
| pid = str(raw_point.get("id", "")) |
| if not pid or pid in seen: |
| raise RenderError(f"plot point has a missing/duplicate id: {pid!r}") |
| seen.add(pid) |
| x_label = str(raw_point.get("x", "")) |
| if not x_label: |
| raise RenderError(f"plot point {pid!r} has no x value") |
| try: |
| x_value: Fraction | None = parse_number(x_label) |
| except (TypeError, ValueError, ZeroDivisionError): |
| x_value = None |
| is_hidden = is_series_hidden or pid in hidden |
| if is_hidden: |
| |
| |
| |
| y: Fraction | None = None |
| y_label = "" |
| else: |
| try: |
| y = parse_number(raw_point.get("y", "")) |
| except (TypeError, ValueError, ZeroDivisionError) as exc: |
| raise RenderError(f"plot point {pid!r} has an invalid y value") from exc |
| y_label = _exact_value_label(y) |
| points.append( |
| _Point( |
| node_id=pid, |
| x_label=x_label, |
| x_value=x_value, |
| y=y, |
| y_label=y_label, |
| hidden=is_hidden, |
| ) |
| ) |
| output.append( |
| _Series( |
| node_id=sid, |
| label=str(raw.get("label", sid)), |
| points=tuple(points), |
| hidden=is_series_hidden, |
| ) |
| ) |
| if not any(s.points for s in output): |
| raise RenderError("plot world has no points") |
| return tuple(output) |
|
|
|
|
| def _build_domain(world: World, series: Sequence[_Series]) -> _Domain: |
| all_points = [point for item in series for point in item.points] |
| numeric_x = all(point.x_value is not None for point in all_points) |
| axis_values = _axis_values(world.get("x_axis")) |
| x_labels = _dedup([*axis_values, *(point.x_label for point in all_points)]) |
| if not x_labels: |
| raise RenderError("plot world has no x labels") |
|
|
| render_domain = world.get("render_domain") |
| domain_map = render_domain if isinstance(render_domain, Mapping) else {} |
|
|
| if numeric_x: |
| numeric_values = [point.x_value for point in all_points if point.x_value is not None] |
| x_min_override = _domain_bound(domain_map, "x", "min") |
| x_max_override = _domain_bound(domain_map, "x", "max") |
| x_min = x_min_override if x_min_override is not None else min(numeric_values) |
| x_max = x_max_override if x_max_override is not None else max(numeric_values) |
| else: |
| x_min = Fraction(0) |
| x_max = Fraction(max(1, len(x_labels) - 1)) |
| x_min, x_max = _nondegenerate(x_min, x_max) |
|
|
| visible_y = [ |
| point.y |
| for item in series |
| if not item.hidden |
| for point in item.points |
| if not point.hidden and point.y is not None |
| ] |
| y_min_override = _domain_bound(domain_map, "y", "min") |
| y_max_override = _domain_bound(domain_map, "y", "max") |
| if visible_y: |
| y_min = y_min_override if y_min_override is not None else min(visible_y) |
| y_max = y_max_override if y_max_override is not None else max(visible_y) |
| else: |
| y_min = y_min_override if y_min_override is not None else Fraction(0) |
| y_max = y_max_override if y_max_override is not None else Fraction(1) |
|
|
| if "bar" in _plot_type(world) and y_min_override is None and y_max_override is None: |
| y_min = min(y_min, Fraction(0)) |
| y_max = max(y_max, Fraction(0)) |
| y_min, y_max = _nondegenerate(y_min, y_max) |
| if y_min_override is None and y_max_override is None: |
| padding = (y_max - y_min) / 10 |
| y_min -= padding |
| y_max += padding |
|
|
| return _Domain( |
| numeric_x=numeric_x, |
| x_min=x_min, |
| x_max=x_max, |
| y_min=y_min, |
| y_max=y_max, |
| x_labels=tuple(x_labels), |
| ) |
|
|
|
|
| def _draw_plot( |
| canvas: _Canvas, |
| world: World, |
| series: Sequence[_Series], |
| domain: _Domain, |
| family: RendererFamily, |
| ) -> tuple[str, ...]: |
| width, height = canvas.width, canvas.height |
| legend_width = max(118, min(210, int(width * 0.24))) |
| left = max(62, int(width * 0.11)) |
| right = width - legend_width |
| top = max(54, int(height * 0.12)) |
| bottom = height - max(58, int(height * 0.15)) |
| if right - left < 140 or bottom - top < 100: |
| raise RenderError("plot canvas leaves insufficient data area after labels/legend") |
|
|
| text_color = family.palette.get("text", "#202020") |
| axis_color = family.palette.get("axis", "#444444") |
| grid_color = family.palette.get("grid", "#D8D8D8") |
| plot_type = _plot_type(world) |
| visible_series_count = sum(not item.hidden for item in series) |
| x_padding = 0.0 |
| if "bar" in plot_type: |
| _, bar_width = _bar_dimensions(canvas.width, len(domain.x_labels), visible_series_count) |
| x_padding = ((max(1, visible_series_count) - 1) / 2 + 0.42) * bar_width + 2 |
| x_span = right - left - 2 * x_padding |
| if x_span <= 0: |
| raise RenderError("plot data area is too narrow for grouped bars") |
|
|
| |
| title = _display_text(world.get("title")) or "Chart" |
| x_axis_label = _axis_label(world.get("x_axis")) or "X" |
| y_axis_label = _axis_label(world.get("y_axis")) or "Value" |
| canvas.text( |
| "plot:title", |
| title, |
| (width / 2, 18), |
| size=max(14, min(20, width // 45)), |
| fill=text_color, |
| anchor="ma", |
| max_width=width - 20, |
| ) |
| canvas.text( |
| "axis:y:label", |
| y_axis_label, |
| (left, top - 9), |
| size=11, |
| fill=text_color, |
| anchor="ld", |
| max_width=max(80, (right - left) * 0.45), |
| ) |
| canvas.text( |
| "axis:x:label", |
| x_axis_label, |
| ((left + right) / 2, height - 8), |
| size=11, |
| fill=text_color, |
| anchor="md", |
| max_width=right - left, |
| ) |
|
|
| def x_position(point: _Point) -> float: |
| if domain.numeric_x: |
| assert point.x_value is not None |
| ratio = float((point.x_value - domain.x_min) / (domain.x_max - domain.x_min)) |
| else: |
| ratio = ( |
| domain.x_labels.index(point.x_label) / (len(domain.x_labels) - 1) |
| if len(domain.x_labels) > 1 |
| else 0.5 |
| ) |
| if ratio < -1e-9 or ratio > 1 + 1e-9: |
| raise RenderError(f"x value {point.x_label!r} is outside render_domain") |
| return left + x_padding + min(1.0, max(0.0, ratio)) * x_span |
|
|
| def x_label_position(label: str) -> float: |
| if domain.numeric_x: |
| value = parse_number(label) |
| ratio = float((value - domain.x_min) / (domain.x_max - domain.x_min)) |
| else: |
| ratio = ( |
| domain.x_labels.index(label) / (len(domain.x_labels) - 1) |
| if len(domain.x_labels) > 1 |
| else 0.5 |
| ) |
| return left + x_padding + min(1.0, max(0.0, ratio)) * x_span |
|
|
| def y_position(value: Fraction) -> float: |
| ratio = float((value - domain.y_min) / (domain.y_max - domain.y_min)) |
| if ratio < -1e-9 or ratio > 1 + 1e-9: |
| raise RenderError(f"y value {canonical_number_str(value)!r} is outside render_domain") |
| return bottom - min(1.0, max(0.0, ratio)) * (bottom - top) |
|
|
| |
| for i in range(_Y_TICKS): |
| ratio = Fraction(i, _Y_TICKS - 1) |
| value = domain.y_min + ratio * (domain.y_max - domain.y_min) |
| y = bottom - float(ratio) * (bottom - top) |
| node_id = f"axis:y:tick:{i}" |
| canvas.line(node_id, [(left, y), (right, y)], fill=grid_color, width=1) |
| canvas.text( |
| node_id, |
| _format_number(value), |
| (left - 7, y), |
| size=9, |
| fill=text_color, |
| anchor="rm", |
| max_width=left - 12, |
| ) |
| canvas.line("axis:x", [(left, bottom), (right, bottom)], fill=axis_color, width=2) |
| canvas.line("axis:y", [(left, top), (left, bottom)], fill=axis_color, width=2) |
|
|
| tick_labels = _decimate(domain.x_labels, _MAX_X_TICKS) |
| spacing = (right - left) / max(1, len(tick_labels) - 1) |
| tick_size = max(7, min(10, int(spacing * 0.28))) |
| for i, label in enumerate(tick_labels): |
| x = x_label_position(label) |
| node_id = f"axis:x:tick:{i}" |
| canvas.line(node_id, [(x, bottom), (x, bottom + 5)], fill=axis_color, width=1) |
| canvas.text( |
| node_id, |
| label, |
| (x, bottom + 8 + (i % 2) * 10), |
| size=tick_size, |
| fill=text_color, |
| anchor="ma", |
| max_width=max(24, spacing * 1.8), |
| ) |
|
|
| |
| |
| |
| hidden_x = _dedup(point.x_label for item in series for point in item.points if point.hidden) |
| strip_half_width = max(4, min(12, int((right - left) / max(24, len(domain.x_labels) * 8)))) |
| for label in hidden_x: |
| prototype = next( |
| point for item in series for point in item.points if point.x_label == label |
| ) |
| x = x_position(prototype) |
| canvas.rectangle( |
| None, |
| (x - strip_half_width, top, x + strip_half_width, bottom), |
| fill=family.palette.get("redact", "#111111"), |
| ) |
|
|
| colours = _series_colours(family) |
| visible: list[str] = [] |
|
|
| |
| |
| for item in series: |
| if item.hidden: |
| continue |
| visible.append(item.node_id) |
| canvas.reserve(item.node_id) |
| for point in item.points: |
| if not point.hidden: |
| visible.append(point.node_id) |
| canvas.reserve(point.node_id) |
|
|
| if "bar" in plot_type: |
| _draw_bars(canvas, series, domain, x_position, y_position, colours) |
| else: |
| _draw_lines(canvas, series, x_position, y_position, colours, scatter="scatter" in plot_type) |
| _draw_value_labels( |
| canvas, |
| series, |
| domain, |
| x_position, |
| y_position, |
| colours, |
| plot_type=plot_type, |
| data_bounds=(left, top, right, bottom), |
| ) |
|
|
| |
| |
| legend_x = right + 17 |
| legend_y = top + 8 |
| visible_series = [item for item in series if not item.hidden] |
| row_height = max(18, min(28, (bottom - top) // max(1, len(visible_series)))) |
| for index, item in enumerate(visible_series): |
| y = legend_y + index * row_height |
| if y + 13 > bottom: |
| raise RenderError("plot legend does not fit within the canvas") |
| colour = colours[index % len(colours)] |
| canvas.rectangle( |
| item.node_id, |
| (legend_x, y, legend_x + 18, y + 8), |
| fill=colour, |
| outline=axis_color, |
| ) |
| canvas.text( |
| item.node_id, |
| item.label, |
| (legend_x + 24, y + 4), |
| size=10, |
| fill=text_color, |
| anchor="lm", |
| max_width=width - (legend_x + 28) - 4, |
| ) |
|
|
| return tuple(_dedup(visible)) |
|
|
|
|
| def _draw_lines( |
| canvas: _Canvas, |
| series: Sequence[_Series], |
| x_position: Any, |
| y_position: Any, |
| colours: Sequence[str], |
| *, |
| scatter: bool, |
| ) -> None: |
| visible_series = [item for item in series if not item.hidden] |
| count = len(visible_series) |
| for series_index, item in enumerate(visible_series): |
| colour = colours[series_index % len(colours)] |
| x_offset = (series_index - (count - 1) / 2) * min(4.0, 8.0 / max(1, count)) |
| run: list[tuple[float, float]] = [] |
| runs: list[list[tuple[float, float]]] = [] |
| for point in item.points: |
| if point.hidden: |
| if len(run) >= 2: |
| runs.append(run) |
| run = [] |
| continue |
| assert point.y is not None |
| run.append((x_position(point) + x_offset, y_position(point.y))) |
| if len(run) >= 2: |
| runs.append(run) |
| if not scatter: |
| for coordinates in runs: |
| canvas.line(item.node_id, coordinates, fill=colour, width=3) |
| for point_index, point in enumerate(point for point in item.points if not point.hidden): |
| assert point.y is not None |
| x = x_position(point) + x_offset |
| y = y_position(point.y) |
| radius = max(3.0, 6.0 - series_index * 0.35 + (point_index % 2) * 0.2) |
| canvas.ellipse( |
| point.node_id, |
| (x - radius, y - radius, x + radius, y + radius), |
| fill=colour, |
| outline="#202020", |
| width=1, |
| ) |
|
|
|
|
| def _draw_bars( |
| canvas: _Canvas, |
| series: Sequence[_Series], |
| domain: _Domain, |
| x_position: Any, |
| y_position: Any, |
| colours: Sequence[str], |
| ) -> None: |
| visible_series = [item for item in series if not item.hidden] |
| count = max(1, len(visible_series)) |
| _, bar_width = _bar_dimensions(canvas.width, len(domain.x_labels), count) |
| baseline_value = min(max(Fraction(0), domain.y_min), domain.y_max) |
| baseline = y_position(baseline_value) |
| for series_index, item in enumerate(visible_series): |
| colour = colours[series_index % len(colours)] |
| offset = (series_index - (count - 1) / 2) * bar_width |
| for point in item.points: |
| if point.hidden: |
| continue |
| assert point.y is not None |
| x = x_position(point) + offset |
| y = y_position(point.y) |
| y0, y1 = sorted((baseline, y)) |
| if y1 - y0 < 1: |
| y1 = y0 + 1 |
| canvas.rectangle( |
| point.node_id, |
| (x - bar_width * 0.42, y0, x + bar_width * 0.42, y1), |
| fill=colour, |
| outline="#202020", |
| ) |
|
|
|
|
| def _draw_value_labels( |
| canvas: _Canvas, |
| series: Sequence[_Series], |
| domain: _Domain, |
| x_position: Any, |
| y_position: Any, |
| colours: Sequence[str], |
| *, |
| plot_type: str, |
| data_bounds: tuple[float, float, float, float], |
| ) -> None: |
| """Draw every visible point's exact value with deterministic collision avoidance.""" |
| left, top, right, bottom = data_bounds |
| visible_series = [item for item in series if not item.hidden] |
| count = max(1, len(visible_series)) |
| if "bar" in plot_type: |
| _, bar_width = _bar_dimensions(canvas.width, len(domain.x_labels), count) |
| x_offsets = [(series_index - (count - 1) / 2) * bar_width for series_index in range(count)] |
| else: |
| x_offsets = [ |
| (series_index - (count - 1) / 2) * min(4.0, 8.0 / count) |
| for series_index in range(count) |
| ] |
|
|
| |
| |
| occupied: list[tuple[int, int, int, int]] = [] |
| if "bar" not in plot_type: |
| for series_index, item in enumerate(visible_series): |
| for point in item.points: |
| if point.hidden: |
| continue |
| assert point.y is not None |
| x = x_position(point) + x_offsets[series_index] |
| y = y_position(point.y) |
| occupied.append((round(x - 7), round(y - 7), round(x + 7), round(y + 7))) |
|
|
| background = canvas.family.palette.get("background", "#FFFFFF") |
| base_size = max(8, min(10, canvas.width // 72)) |
| max_width = min(190.0, max(40.0, right - left - 8)) |
| for series_index, item in enumerate(visible_series): |
| colour = colours[series_index % len(colours)] |
| for point_index, point in enumerate(point for point in item.points if not point.hidden): |
| assert point.y is not None |
| if not point.y_label: |
| raise RenderError(f"visible point {point.node_id!r} has no exact value label") |
| x = x_position(point) + x_offsets[series_index] |
| y = y_position(point.y) |
| candidates = _value_label_candidates( |
| x, |
| y, |
| data_bounds=data_bounds, |
| parity=(series_index + point_index) % 2, |
| ) |
|
|
| selected: ( |
| tuple[ |
| tuple[float, float], |
| str, |
| int, |
| tuple[int, int, int, int], |
| ] |
| | None |
| ) = None |
| fallback: list[ |
| tuple[ |
| tuple[int, int, int], |
| tuple[float, float], |
| str, |
| int, |
| tuple[int, int, int, int], |
| ] |
| ] = [] |
| for font_size in range(base_size, 6, -1): |
| for candidate_index, (xy, anchor) in enumerate(candidates): |
| bbox = canvas.text_bbox( |
| point.y_label, |
| xy, |
| size=font_size, |
| anchor=anchor, |
| max_width=max_width, |
| ) |
| padded = _expand_bbox(bbox, 2) |
| score = _label_overlap_score( |
| padded, |
| occupied, |
| bounds=( |
| round(left + 1), |
| round(top + 1), |
| round(right - 1), |
| round(bottom - 1), |
| ), |
| ) |
| if score == 0: |
| selected = (xy, anchor, font_size, bbox) |
| break |
| fallback.append( |
| ( |
| (score, -font_size, candidate_index), |
| xy, |
| anchor, |
| font_size, |
| bbox, |
| ) |
| ) |
| if selected is not None: |
| break |
|
|
| if selected is None: |
| if not fallback: |
| raise RenderError(f"no value-label placement for point {point.node_id!r}") |
| _, xy, anchor, font_size, bbox = min(fallback, key=lambda item: item[0]) |
| else: |
| xy, anchor, font_size, bbox = selected |
|
|
| label_background = _clip_bbox( |
| _expand_bbox(bbox, 2), |
| width=canvas.width, |
| height=canvas.height, |
| ) |
| canvas.rectangle(point.node_id, label_background, fill=background) |
| drawn_bbox = canvas.text( |
| point.node_id, |
| point.y_label, |
| xy, |
| size=font_size, |
| fill=colour, |
| anchor=anchor, |
| max_width=max_width, |
| ) |
| assert drawn_bbox is not None |
| occupied.append(_expand_bbox(drawn_bbox, 2)) |
|
|
|
|
| def _value_label_candidates( |
| x: float, |
| y: float, |
| *, |
| data_bounds: tuple[float, float, float, float], |
| parity: int, |
| ) -> tuple[tuple[tuple[float, float], str], ...]: |
| left, top, right, bottom = data_bounds |
| above = ((x, y - 9), "mb") |
| below = ((x, y + 9), "mt") |
| right_of = ((x + 10, y), "lm") |
| left_of = ((x - 10, y), "rm") |
| above_right = ((x + 7, y - 7), "lb") |
| above_left = ((x - 7, y - 7), "rb") |
| below_right = ((x + 7, y + 7), "lt") |
| below_left = ((x - 7, y + 7), "rt") |
|
|
| inward = right_of if x <= (left + right) / 2 else left_of |
| outward = left_of if inward is right_of else right_of |
| if y <= top + (bottom - top) * 0.32: |
| primary, secondary = below, above |
| diagonal_in = below_right if inward is right_of else below_left |
| diagonal_out = below_left if inward is right_of else below_right |
| elif y >= top + (bottom - top) * 0.68: |
| primary, secondary = above, below |
| diagonal_in = above_right if inward is right_of else above_left |
| diagonal_out = above_left if inward is right_of else above_right |
| elif parity: |
| primary, secondary = below, above |
| diagonal_in = below_right if inward is right_of else below_left |
| diagonal_out = above_left if inward is right_of else above_right |
| else: |
| primary, secondary = above, below |
| diagonal_in = above_right if inward is right_of else above_left |
| diagonal_out = below_left if inward is right_of else below_right |
| return ( |
| primary, |
| diagonal_in, |
| inward, |
| secondary, |
| diagonal_out, |
| outward, |
| above_right, |
| above_left, |
| below_right, |
| below_left, |
| ) |
|
|
|
|
| def _expand_bbox(bbox: tuple[int, int, int, int], padding: int) -> tuple[int, int, int, int]: |
| return ( |
| bbox[0] - padding, |
| bbox[1] - padding, |
| bbox[2] + padding, |
| bbox[3] + padding, |
| ) |
|
|
|
|
| def _clip_bbox( |
| bbox: tuple[int, int, int, int], *, width: int, height: int |
| ) -> tuple[float, float, float, float]: |
| return ( |
| max(0, bbox[0]), |
| max(0, bbox[1]), |
| min(width - 1, bbox[2]), |
| min(height - 1, bbox[3]), |
| ) |
|
|
|
|
| def _label_overlap_score( |
| bbox: tuple[int, int, int, int], |
| occupied: Sequence[tuple[int, int, int, int]], |
| *, |
| bounds: tuple[int, int, int, int], |
| ) -> int: |
| left, top, right, bottom = bounds |
| overflow = ( |
| max(0, left - bbox[0]) |
| + max(0, top - bbox[1]) |
| + max(0, bbox[2] - right) |
| + max(0, bbox[3] - bottom) |
| ) |
| overlap = sum(_bbox_overlap_area(bbox, other) for other in occupied) |
| return overflow * 1_000_000 + overlap |
|
|
|
|
| def _bbox_overlap_area(first: tuple[int, int, int, int], second: tuple[int, int, int, int]) -> int: |
| width = max(0, min(first[2], second[2]) - max(first[0], second[0])) |
| height = max(0, min(first[3], second[3]) - max(first[1], second[1])) |
| return width * height |
|
|
|
|
| def _bar_dimensions( |
| canvas_width: int, unique_x_count: int, series_count: int |
| ) -> tuple[float, float]: |
| group_width = max(12.0, min(56.0, (canvas_width * 0.58) / max(1, unique_x_count))) |
| return group_width, max(3.0, group_width / (max(1, series_count) + 0.4)) |
|
|
|
|
| def _domain_bound(domain: Mapping[str, Any], axis: str, bound: str) -> Fraction | None: |
| direct = domain.get(f"{axis}_{bound}") |
| nested = domain.get(axis) |
| raw = direct |
| if raw is None and isinstance(nested, Mapping): |
| raw = nested.get(bound) |
| if raw is None: |
| return None |
| try: |
| return parse_number(raw) |
| except (TypeError, ValueError, ZeroDivisionError) as exc: |
| raise RenderError(f"invalid render_domain {axis}_{bound}: {raw!r}") from exc |
|
|
|
|
| def _axis_values(axis: Any) -> list[str]: |
| if not isinstance(axis, Mapping): |
| return [] |
| values = axis.get("values") or [] |
| if not isinstance(values, Sequence) or isinstance(values, (str, bytes)): |
| return [] |
| return [str(value) for value in values if str(value)] |
|
|
|
|
| def _axis_label(axis: Any) -> str: |
| if isinstance(axis, Mapping): |
| return _display_text(axis.get("label")) |
| return _display_text(axis) |
|
|
|
|
| def _display_text(value: Any) -> str: |
| if value is None: |
| return "" |
| if isinstance(value, Mapping): |
| for key in ("text", "label", "title", "name"): |
| if value.get(key) is not None: |
| return str(value[key]) |
| return "" |
| if isinstance(value, Sequence) and not isinstance(value, (str, bytes)): |
| return ", ".join(str(item) for item in value) |
| return str(value) |
|
|
|
|
| def _plot_type(world: World) -> str: |
| return str(world.get("plot_type", "line")).strip().lower() or "line" |
|
|
|
|
| def _nondegenerate(low: Fraction, high: Fraction) -> tuple[Fraction, Fraction]: |
| if high < low: |
| raise RenderError(f"render domain is reversed: {low} > {high}") |
| if high == low: |
| return low - 1, high + 1 |
| return low, high |
|
|
|
|
| def _format_number(value: Fraction) -> str: |
| if value.denominator == 1: |
| return str(value.numerator) |
| decimal = f"{float(value):.2f}".rstrip("0").rstrip(".") |
| return decimal if decimal not in {"-0", ""} else "0" |
|
|
|
|
| def _exact_value_label(value: Fraction) -> str: |
| """An exact human-readable value: terminating decimal when possible.""" |
| if value.numerator == 0: |
| return "0" |
| denominator = value.denominator |
| powers_of_two = 0 |
| powers_of_five = 0 |
| while denominator % 2 == 0: |
| denominator //= 2 |
| powers_of_two += 1 |
| while denominator % 5 == 0: |
| denominator //= 5 |
| powers_of_five += 1 |
| if denominator != 1: |
| return canonical_number_str(value) |
|
|
| decimal_places = max(powers_of_two, powers_of_five) |
| scaled = abs(value.numerator) |
| scaled *= 2 ** (decimal_places - powers_of_two) |
| scaled *= 5 ** (decimal_places - powers_of_five) |
| sign = "-" if value.numerator < 0 else "" |
| if decimal_places == 0: |
| return f"{sign}{scaled}" |
| digits = str(scaled).rjust(decimal_places + 1, "0") |
| integer = digits[:-decimal_places] |
| fractional = digits[-decimal_places:].rstrip("0") |
| return f"{sign}{integer}.{fractional}" if fractional else f"{sign}{integer}" |
|
|
|
|
| def _dedup(values: Iterable[str]) -> list[str]: |
| seen: set[str] = set() |
| output: list[str] = [] |
| for value in values: |
| if value not in seen: |
| seen.add(value) |
| output.append(value) |
| return output |
|
|
|
|
| def _decimate(values: Sequence[str], maximum: int) -> tuple[str, ...]: |
| if len(values) <= maximum: |
| return tuple(values) |
| indices = {round(index * (len(values) - 1) / (maximum - 1)) for index in range(maximum)} |
| return tuple(values[index] for index in sorted(indices)) |
|
|
|
|
| def _series_colours(family: RendererFamily) -> tuple[str, ...]: |
| colours = tuple( |
| family.palette[key] for key in sorted(family.palette) if key.startswith("series_") |
| ) |
| if colours: |
| return colours |
| return (family.palette.get("mark", "#1f77b4"),) |
|
|
|
|
| def _pillow_version() -> str: |
| import PIL |
|
|
| return str(PIL.__version__) |
|
|
|
|
| _PLOT_TRAIN_FAMILY = RendererFamily( |
| name="plot_train_v1", |
| kind="plot", |
| font_name="DejaVu Sans", |
| palette={ |
| "background": "#FFFFFF", |
| "text": "#202020", |
| "axis": "#444444", |
| "grid": "#D9DEE8", |
| "redact": "#151515", |
| "mark": "#2563EB", |
| "series_0": "#2563EB", |
| "series_1": "#EA580C", |
| "series_2": "#16A34A", |
| "series_3": "#DC2626", |
| "series_4": "#7C3AED", |
| "series_5": "#A16207", |
| }, |
| layout={"engine": "pillow_v3_exact_labels", "y_ticks": _Y_TICKS}, |
| ) |
| _PLOT_HELDOUT_FAMILY = RendererFamily( |
| name="plot_heldout_v1", |
| kind="plot", |
| font_name="DejaVu Serif", |
| palette={ |
| "background": "#F7F7F0", |
| "text": "#17212B", |
| "axis": "#38434F", |
| "grid": "#D5D2C8", |
| "redact": "#303030", |
| "mark": "#0F766E", |
| "series_0": "#0F766E", |
| "series_1": "#BE123C", |
| "series_2": "#B7791F", |
| "series_3": "#4338CA", |
| "series_4": "#A21CAF", |
| "series_5": "#475569", |
| }, |
| layout={"engine": "pillow_v3_exact_labels_heldout", "y_ticks": _Y_TICKS}, |
| ) |
|
|
| PLOT_FAMILIES: dict[str, RendererFamily] = { |
| "plot_train_v1": _PLOT_TRAIN_FAMILY, |
| "plot_heldout_v1": _PLOT_HELDOUT_FAMILY, |
| } |
|
|
|
|
| __all__ = ["PLOT_FAMILIES", "PlotRenderer"] |
|
|