"""Synthetic chart generator with exact ground truth. Every chart is rendered with matplotlib from a random but seeded ``SynthSpec``. Alongside the image we store a JSON file holding the data, the axis limits and scale, and the *pixel* geometry of the plot area and ticks (taken from matplotlib's own transforms), so each pipeline stage can be scored on its own. Usage:: python -m tests.synth --n 200 --tier mixed --out data/synth """ from __future__ import annotations import io import json import random from dataclasses import asdict, dataclass from pathlib import Path from typing import Any import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt # noqa: E402 import numpy as np # noqa: E402 from PIL import Image # noqa: E402 KINDS = ("line", "bar", "grouped_bar", "stacked_bar", "scatter") TIERS = ("clean", "perturbed") _WORDS = [ "Apple", "Banana", "Cherry", "Date", "Fig", "Grape", "Kiwi", "Lemon", "Mango", "Nectar", "Olive", "Peach", "Pear", "Plum", "Quince", ] _MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] _SERIES_NAMES = [ "Revenue", "Cost", "Profit", "North", "South", "East", "West", "Alpha", "Beta", "Gamma", "Model A", "Model B", "Baseline", "Control", "Treatment", ] _STYLES_PERTURBED = [ "default", "default", "default", "seaborn-v0_8-whitegrid", "ggplot", "bmh", "seaborn-v0_8-ticks", "fivethirtyeight", "Solarize_Light2", "classic", ] @dataclass class SynthSpec: """All random choices for one synthetic chart.""" seed: int tier: str kind: str n_series: int n_points: int categorical_x: bool log_y: bool negative: bool grid: bool style: str markers: str # "" for none, else a matplotlib marker code linestyle: str legend_loc: str | None font_size: float font_family: str figsize: tuple[float, float] dpi: int jpeg_quality: int | None palette: str # "default" or "random" def random_spec(seed: int, tier: str = "clean", kind: str | None = None) -> SynthSpec: """Draw a random chart specification. The *clean* tier mimics a default matplotlib export (PNG, default style, 100 dpi, solid lines, default fonts). The *perturbed* tier varies style, fonts, resolution, line style, markers, legend position, log scales and JPEG quality. """ rng = random.Random(seed) kind = kind or rng.choice(KINDS) if kind == "bar": n_series = 1 elif kind in ("grouped_bar", "stacked_bar"): n_series = rng.randint(2, 4) else: n_series = rng.randint(1, 5) if kind == "scatter": n_points = rng.randint(10, 40) elif kind == "line": n_points = rng.randint(5, 30) else: n_points = rng.randint(3, 9) categorical_x = kind in ("bar", "grouped_bar", "stacked_bar") or ( kind == "line" and rng.random() < 0.25 ) if categorical_x: n_points = min(n_points, 12) clean = tier == "clean" log_y = (not clean) and kind in ("line", "scatter") and rng.random() < 0.25 negative = (not log_y) and kind in ("line", "bar", "grouped_bar") and rng.random() < 0.25 legend_loc: str | None if n_series == 1 and rng.random() < 0.6: legend_loc = None elif clean: legend_loc = "best" else: legend_loc = rng.choice(["best", "upper left", "upper right", "lower right", "outside"]) if clean: return SynthSpec( seed=seed, tier=tier, kind=kind, n_series=n_series, n_points=n_points, categorical_x=categorical_x, log_y=False, negative=negative, grid=rng.random() < 0.5, style="default", markers=rng.choice(["", "", "o"]) if kind == "line" else "", linestyle="-", legend_loc=legend_loc, font_size=10.0, font_family="DejaVu Sans", figsize=(6.4, 4.8), dpi=100, jpeg_quality=None, palette="default", ) return SynthSpec( seed=seed, tier=tier, kind=kind, n_series=n_series, n_points=n_points, categorical_x=categorical_x, log_y=log_y, negative=negative, grid=rng.random() < 0.5, style=rng.choice(_STYLES_PERTURBED), markers=rng.choice(["", "", "o", "s", "^", "D"]) if kind == "line" else rng.choice(["o", "s", "^"]), linestyle=rng.choice(["-", "-", "-", "--", ":"]) if kind == "line" else "-", legend_loc=legend_loc, font_size=rng.choice([7, 8, 9, 10, 11, 12, 14]), font_family=rng.choice(["DejaVu Sans", "DejaVu Serif", "DejaVu Sans Mono"]), figsize=(round(rng.uniform(4.0, 10.0), 2), round(rng.uniform(3.0, 7.0), 2)), dpi=rng.choice([50, 60, 72, 80, 100, 120, 150]), jpeg_quality=rng.choice([None, None, 95, 80, 60, 40]), palette=rng.choice(["default", "random"]), ) def _magnitude(rng: np.random.Generator) -> float: return float(10 ** rng.uniform(-1, 4)) def _random_walk(rng: np.random.Generator, n: int) -> np.ndarray: steps = rng.normal(0, 1, n) walk = np.cumsum(steps) + rng.uniform(-1, 1) * np.arange(n) * 0.3 return walk def make_data(spec: SynthSpec) -> dict[str, Any]: """Generate x values, category labels and per-series y values for ``spec``.""" rng = np.random.default_rng(spec.seed) prng = random.Random(spec.seed + 1) names = prng.sample(_SERIES_NAMES, spec.n_series) out: dict[str, Any] = {"names": names} if spec.categorical_x: if prng.random() < 0.3 and spec.n_points <= 12: start = prng.randint(0, 12 - spec.n_points) cats = _MONTHS[start:start + spec.n_points] else: cats = prng.sample(_WORDS, spec.n_points) out["categories"] = cats x = np.arange(spec.n_points, dtype=float) elif spec.kind == "scatter": x = None else: x0 = prng.choice([0.0, 1.0, float(prng.randint(-50, 2000))]) step = prng.choice([0.1, 0.5, 1.0, 2.0, 5.0, 10.0, 0.25]) x = x0 + step * np.arange(spec.n_points) mag = _magnitude(rng) series: list[dict[str, list[float]]] = [] for _ in range(spec.n_series): if spec.kind == "scatter": sx = rng.uniform(0, 1, spec.n_points) * mag * rng.uniform(0.5, 2) + rng.uniform(-1, 1) * mag if spec.log_y: sy = 10 ** (rng.uniform(0, 3.5, spec.n_points) + rng.uniform(-1, 1)) else: sy = (0.3 * sx / mag + rng.normal(0, 0.5, spec.n_points)) * mag series.append({"x": sx.tolist(), "y": sy.tolist()}) continue assert x is not None if spec.kind == "line": walk = _random_walk(rng, spec.n_points) if spec.log_y: walk = (walk - walk.min()) / max(np.ptp(walk), 1e-9) * rng.uniform(1.5, 4) y = 10 ** (walk + rng.uniform(-1, 2)) else: y = walk / max(np.ptp(walk), 1e-9) * mag if not spec.negative: y = y - y.min() + mag * rng.uniform(0.05, 1.5) else: if spec.negative: y = rng.uniform(-1, 1, spec.n_points) * mag y[np.abs(y) < 0.05 * mag] = 0.1 * mag else: y = rng.uniform(0.1, 1, spec.n_points) * mag series.append({"x": x.tolist(), "y": y.tolist()}) out["series"] = series return out def _palette(spec: SynthSpec) -> list[Any]: if spec.palette == "default": return [f"C{i}" for i in range(spec.n_series)] rng = random.Random(spec.seed + 2) hue0 = rng.random() cols = [] for i in range(spec.n_series): h = (hue0 + i / spec.n_series) % 1.0 s = rng.uniform(0.55, 0.95) v = rng.uniform(0.45, 0.85) cols.append(matplotlib.colors.hsv_to_rgb((h, s, v))) return cols def render(spec: SynthSpec, data: dict[str, Any]) -> tuple[np.ndarray, dict[str, Any]]: """Render the chart; return the RGB image and its pixel-level ground truth.""" rc = {"font.size": spec.font_size, "font.family": spec.font_family} style = spec.style if spec.style != "default" else "default" with plt.style.context(style), plt.rc_context(rc): fig, ax = plt.subplots(figsize=spec.figsize, dpi=spec.dpi) colors = _palette(spec) names = data["names"] ser = data["series"] n = spec.n_series if spec.kind == "line": for i, s in enumerate(ser): ax.plot(s["x"], s["y"], color=colors[i], linestyle=spec.linestyle, marker=spec.markers or None, label=names[i]) elif spec.kind == "scatter": for i, s in enumerate(ser): ax.scatter(s["x"], s["y"], color=colors[i], marker=spec.markers or "o", label=names[i], s=random.Random(spec.seed + 3).choice([20, 30, 40])) elif spec.kind == "bar": ax.bar(ser[0]["x"], ser[0]["y"], color=colors[0], label=names[0]) elif spec.kind == "grouped_bar": width = 0.8 / n for i, s in enumerate(ser): ax.bar(np.asarray(s["x"]) - 0.4 + width * (i + 0.5), s["y"], width=width, color=colors[i], label=names[i]) elif spec.kind == "stacked_bar": bottom = np.zeros(spec.n_points) for i, s in enumerate(ser): ax.bar(s["x"], s["y"], bottom=bottom, color=colors[i], label=names[i]) bottom = bottom + np.asarray(s["y"]) if spec.kind in ("bar", "grouped_bar", "stacked_bar") and spec.negative: ax.axhline(0, color="black", linewidth=0.8) if spec.categorical_x: ax.set_xticks(range(spec.n_points), data["categories"]) if spec.log_y: ax.set_yscale("log") if spec.grid: ax.grid(True, alpha=0.6) rng = random.Random(spec.seed + 4) if rng.random() < 0.5: ax.set_xlabel(rng.choice(["Time", "Category", "x", "Month", "Input value"])) if rng.random() < 0.5: ax.set_ylabel(rng.choice(["Value", "Amount ($)", "y", "Count", "Score"])) if rng.random() < 0.3: ax.set_title(rng.choice(["Results", "Quarterly overview", "Measurements"])) if spec.legend_loc == "outside": ax.legend(loc="center left", bbox_to_anchor=(1.02, 0.5)) fig.subplots_adjust(right=0.72) elif spec.legend_loc: ax.legend(loc=spec.legend_loc) fig.canvas.draw() renderer = fig.canvas.get_renderer() width_px, height_px = fig.canvas.get_width_height() bbox = ax.get_window_extent(renderer) gt = { "spec": asdict(spec), "image_size": [width_px, height_px], "plot_bbox": [bbox.x0, height_px - bbox.y1, bbox.x1, height_px - bbox.y0], "xlim": list(ax.get_xlim()), "ylim": list(ax.get_ylim()), "yscale": ax.get_yscale(), "xticks": _ticks(ax, "x", height_px), "yticks": _ticks(ax, "y", height_px), "names": names, "categories": data.get("categories"), "series": ser, } buf = io.BytesIO() fig.savefig(buf, format="png", dpi=spec.dpi) plt.close(fig) buf.seek(0) img = np.array(Image.open(buf).convert("RGB")) assert img.shape[1] == width_px and img.shape[0] == height_px, (img.shape, width_px, height_px) return img, gt def _ticks(ax: Any, which: str, height_px: int) -> list[dict[str, Any]]: axis = ax.xaxis if which == "x" else ax.yaxis lo, hi = sorted(ax.get_xlim() if which == "x" else ax.get_ylim()) ticks = [] for val, lab in zip(axis.get_majorticklocs(), axis.get_majorticklabels()): if not (lo - 1e-9 * abs(hi - lo) <= val <= hi + 1e-9 * abs(hi - lo)): continue if which == "x": px = float(ax.transData.transform((val, ax.get_ylim()[0]))[0]) else: px = float(height_px - ax.transData.transform((ax.get_xlim()[0], val))[1]) ticks.append({"value": float(val), "label": lab.get_text(), "px": px}) return ticks def ground_truth_frame(gt: dict[str, Any]) -> "Any": """Ground truth in the plotscribe CSV layout (see README, 'CSV layout').""" import pandas as pd kind = gt["spec"]["kind"] names = gt["names"] if kind == "scatter": rows = [] for name, s in zip(names, gt["series"]): for x, y in zip(s["x"], s["y"]): rows.append({"x": x, **{n: (y if n == name else np.nan) for n in names}}) return pd.DataFrame(rows, columns=["x", *names]) first = "category" if gt["categories"] else "x" xcol = gt["categories"] if gt["categories"] else gt["series"][0]["x"] cols = {first: xcol} suffix = " (segment)" if kind == "stacked_bar" else "" for name, s in zip(names, gt["series"]): cols[name + suffix] = s["y"] return pd.DataFrame(cols) def generate(seed: int, out_dir: Path, tier: str = "clean", kind: str | None = None) -> Path: """Render one chart into ``out_dir``; return the image path.""" spec = random_spec(seed, tier, kind) data = make_data(spec) img, gt = render(spec, data) out_dir.mkdir(parents=True, exist_ok=True) stem = f"{tier}_{spec.kind}_{seed:05d}" if spec.jpeg_quality: path = out_dir / f"{stem}.jpg" Image.fromarray(img).save(path, quality=spec.jpeg_quality) else: path = out_dir / f"{stem}.png" Image.fromarray(img).save(path) (out_dir / f"{stem}.json").write_text(json.dumps(gt, indent=1)) ground_truth_frame(gt).to_csv(out_dir / f"{stem}.gt.csv", index=False) return path def generate_set(n: int, out_dir: Path, tier: str = "clean", start_seed: int = 0, kinds: tuple[str, ...] = KINDS) -> list[Path]: """Generate ``n`` charts cycling through ``kinds`` so every kind is represented.""" paths = [] for i in range(n): seed = start_seed + i tiers = TIERS if tier == "mixed" else (tier,) t = tiers[i % len(tiers)] kind = kinds[(i // len(tiers)) % len(kinds)] paths.append(generate(seed, out_dir, t, kind)) return paths if __name__ == "__main__": import argparse p = argparse.ArgumentParser() p.add_argument("--n", type=int, default=100) p.add_argument("--tier", default="clean", choices=[*TIERS, "mixed"]) p.add_argument("--out", type=Path, default=Path("data/synth")) p.add_argument("--start-seed", type=int, default=0) a = p.parse_args() ps = generate_set(a.n, a.out, a.tier, a.start_seed) print(f"wrote {len(ps)} charts to {a.out}")