from __future__ import annotations import argparse import copy import json import sys from dataclasses import dataclass from pathlib import Path from typing import Any, Mapping, Sequence from reportlab.graphics import renderSVG from reportlab.graphics.shapes import Circle, Drawing, Line, Rect, String from reportlab.lib import colors CONDITIONS = ("no_gate", "prompt_only", "stateless_hook", "beforedone") CONDITION_LABELS = { "no_gate": "C0 No gate", "prompt_only": "C1 Prompt only", "stateless_hook": "C2 Stateless Hook", "beforedone": "C3 BeforeDone", } CONDITION_COLORS = { "no_gate": "#778396", "prompt_only": "#53769A", "stateless_hook": "#D18449", "beforedone": "#0A756A", } EXPECTED_CONFIRMATORY_RUNS = 144 FIGURE_WIDTH = 960 FIGURE_HEIGHT = 540 class FigureError(ValueError): """A figure cannot be derived without inventing or obscuring study data.""" @dataclass(frozen=True) class FigureArtifact: key: str filename: str title: str caption: str drawing: Drawing def _mapping(value: object, label: str) -> Mapping[str, Any]: if not isinstance(value, Mapping): raise FigureError(f"{label} must be an object") return value def _number_or_none(value: object, label: str) -> float | None: if value is None: return None if isinstance(value, bool) or not isinstance(value, (int, float)): raise FigureError(f"{label} must be numeric or null") return float(value) def _integer(value: object, label: str) -> int: if isinstance(value, bool) or not isinstance(value, int): raise FigureError(f"{label} must be an integer") return value def load_results(root: Path) -> dict[str, Any]: path = root.resolve() / "data" / "analysis" / "results.json" try: payload = json.loads(path.read_text(encoding="utf-8")) except FileNotFoundError as exc: raise FigureError(f"missing analysis results: {path}") from exc except (OSError, json.JSONDecodeError) as exc: raise FigureError(f"cannot read analysis results: {exc}") from exc if not isinstance(payload, dict): raise FigureError("analysis results must be a JSON object") return payload def confirmatory_completed_count(results: Mapping[str, Any]) -> int: input_data = _mapping(results.get("input"), "results.input") count = _integer( input_data.get("confirmatory_completed_count"), "results.input.confirmatory_completed_count", ) if count < 0 or count > EXPECTED_CONFIRMATORY_RUNS: raise FigureError( "results.input.confirmatory_completed_count is outside the frozen schedule" ) return count def _validate_mode(results: Mapping[str, Any], mode: str) -> int: if mode not in {"draft", "final"}: raise FigureError("mode must be 'draft' or 'final'") completed = confirmatory_completed_count(results) if mode == "final" and completed != EXPECTED_CONFIRMATORY_RUNS: raise FigureError( "final figures require all 144 confirmatory runs; " f"found {completed}" ) return completed def _base_drawing(title: str, subtitle: str) -> Drawing: drawing = Drawing(FIGURE_WIDTH, FIGURE_HEIGHT) drawing.add( Rect( 0, 0, FIGURE_WIDTH, FIGURE_HEIGHT, fillColor=colors.white, strokeColor=colors.HexColor("#D8E0E7"), strokeWidth=2, ) ) drawing.add( Rect( 0, FIGURE_HEIGHT - 10, FIGURE_WIDTH, 10, fillColor=colors.HexColor("#0A756A"), strokeColor=None, ) ) drawing.add( String( 54, FIGURE_HEIGHT - 58, title, fontName="Helvetica-Bold", fontSize=24, fillColor=colors.HexColor("#172534"), ) ) drawing.add( String( 54, FIGURE_HEIGHT - 86, subtitle, fontName="Helvetica", fontSize=12, fillColor=colors.HexColor("#556575"), ) ) return drawing def _add_pending_panel(drawing: Drawing, completed: int) -> None: drawing.add( Rect( 210, 210, 540, 92, rx=10, ry=10, fillColor=colors.HexColor("#F5F8FA"), strokeColor=colors.HexColor("#8CA0B3"), strokeWidth=1.5, strokeDashArray=[8, 5], ) ) drawing.add( String( 480, 268, "NO CONFIRMATORY DATA", textAnchor="middle", fontName="Helvetica-Bold", fontSize=20, fillColor=colors.HexColor("#516273"), ) ) drawing.add( String( 480, 236, f"DRAFT - {completed}/{EXPECTED_CONFIRMATORY_RUNS} completed runs", textAnchor="middle", fontName="Helvetica", fontSize=14, fillColor=colors.HexColor("#66788A"), ) ) def _outcome_rows(results: Mapping[str, Any]) -> dict[str, Mapping[str, Any]]: outcomes = _mapping(results.get("outcomes"), "results.outcomes") metric = _mapping( outcomes.get("evidence_unsupported_completion"), "results.outcomes.evidence_unsupported_completion", ) rows: dict[str, Mapping[str, Any]] = {} for condition in CONDITIONS: rows[condition] = _mapping( metric.get(condition), f"results.outcomes.evidence_unsupported_completion.{condition}", ) return rows def unsupported_completion_drawing( results: Mapping[str, Any], *, mode: str, ) -> Drawing: completed = _validate_mode(results, mode) rows = _outcome_rows(results) subtitle = ( "Primary outcome: unsupported completed claims / eligible phase outputs" ) drawing = _base_drawing("Unsupported completion by condition", subtitle) left, bottom, width, height = 104, 102, 790, 330 for step in range(5): rate = step / 4 y = bottom + height * rate drawing.add( Line( left, y, left + width, y, strokeColor=colors.HexColor("#E2E8ED"), strokeWidth=1, ) ) drawing.add( String( left - 18, y - 4, f"{int(rate * 100)}%", textAnchor="end", fontName="Helvetica", fontSize=10, fillColor=colors.HexColor("#607182"), ) ) bar_width = 112 gap = (width - bar_width * len(CONDITIONS)) / (len(CONDITIONS) + 1) has_data = False for index, condition in enumerate(CONDITIONS): row = rows[condition] rate = _number_or_none( row.get("raw_rate"), f"unsupported completion rate for {condition}", ) numerator = _integer(row.get("numerator"), f"{condition}.numerator") denominator = _integer(row.get("denominator"), f"{condition}.denominator") x = left + gap + index * (bar_width + gap) drawing.add( String( x + bar_width / 2, 70, CONDITION_LABELS[condition], textAnchor="middle", fontName="Helvetica-Bold" if condition == "beforedone" else "Helvetica", fontSize=10, fillColor=colors.HexColor("#263747"), ) ) if rate is None: if denominator != 0: raise FigureError( f"{condition} has a denominator but no unsupported-completion rate" ) drawing.add( Rect( x, bottom, bar_width, height, fillColor=colors.HexColor("#F4F6F8"), strokeColor=colors.HexColor("#B5C0CA"), strokeWidth=1, strokeDashArray=[6, 5], ) ) drawing.add( String( x + bar_width / 2, bottom + 12, "N/A", textAnchor="middle", fontName="Helvetica-Bold", fontSize=11, fillColor=colors.HexColor("#778797"), ) ) continue if not 0 <= rate <= 1 or denominator <= 0 or not 0 <= numerator <= denominator: raise FigureError(f"invalid unsupported-completion summary for {condition}") has_data = True bar_height = height * rate drawing.add( Rect( x, bottom, bar_width, bar_height, fillColor=colors.HexColor(CONDITION_COLORS[condition]), strokeColor=None, ) ) drawing.add( String( x + bar_width / 2, min(bottom + height - 14, bottom + bar_height + 10), f"{rate * 100:.1f}% ({numerator}/{denominator})", textAnchor="middle", fontName="Helvetica-Bold", fontSize=10, fillColor=colors.HexColor("#263747"), ) ) if mode == "draft" and not has_data: _add_pending_panel(drawing, completed) return drawing def _cost_rows( results: Mapping[str, Any], metric: str, ) -> dict[str, Mapping[str, Any]]: costs = _mapping(results.get("costs"), "results.costs") descriptive = _mapping(costs.get("descriptive"), "results.costs.descriptive") summary = _mapping(descriptive.get(metric), f"results.costs.descriptive.{metric}") rows: dict[str, Mapping[str, Any]] = {} for condition in CONDITIONS: rows[condition] = _mapping( summary.get(condition), f"results.costs.descriptive.{metric}.{condition}", ) return rows def cost_tradeoff_drawing( results: Mapping[str, Any], *, mode: str, ) -> Drawing: completed = _validate_mode(results, mode) verifier_rows = _cost_rows(results, "verifier_executions") wall_rows = _cost_rows(results, "wall_seconds") drawing = _base_drawing( "Verification cost and elapsed-time trade-off", "Condition medians; whiskers show the interquartile range", ) points: list[tuple[str, float, float, float, float, float, float]] = [] for condition in CONDITIONS: verifier = verifier_rows[condition] wall = wall_rows[condition] x = _number_or_none(verifier.get("median"), f"{condition}.verifier median") y = _number_or_none(wall.get("median"), f"{condition}.wall median") x1 = _number_or_none(verifier.get("q1"), f"{condition}.verifier q1") x3 = _number_or_none(verifier.get("q3"), f"{condition}.verifier q3") y1 = _number_or_none(wall.get("q1"), f"{condition}.wall q1") y3 = _number_or_none(wall.get("q3"), f"{condition}.wall q3") n_x = _integer(verifier.get("n"), f"{condition}.verifier n") n_y = _integer(wall.get("n"), f"{condition}.wall n") values = (x, y, x1, x3, y1, y3) if all(value is None for value in values): if n_x != 0 or n_y != 0: raise FigureError(f"{condition} has cost counts without summaries") continue if any(value is None for value in values) or n_x <= 0 or n_x != n_y: raise FigureError(f"incomplete cost summary for {condition}") assert x is not None and y is not None assert x1 is not None and x3 is not None and y1 is not None and y3 is not None if min(x, y, x1, x3, y1, y3) < 0 or not (x1 <= x <= x3 and y1 <= y <= y3): raise FigureError(f"invalid cost quartiles for {condition}") points.append((condition, x, y, x1, x3, y1, y3)) left, bottom, width, height = 116, 104, 730, 320 max_x = max((point[4] for point in points), default=4.0) max_y = max((point[6] for point in points), default=120.0) max_x = max(1.0, max_x * 1.2) max_y = max(1.0, max_y * 1.2) for step in range(5): fraction = step / 4 x = left + width * fraction y = bottom + height * fraction drawing.add( Line( x, bottom, x, bottom + height, strokeColor=colors.HexColor("#E2E8ED"), strokeWidth=1, ) ) drawing.add( Line( left, y, left + width, y, strokeColor=colors.HexColor("#E2E8ED"), strokeWidth=1, ) ) drawing.add( String( x, bottom - 18, f"{max_x * fraction:.1f}", textAnchor="middle", fontName="Helvetica", fontSize=9, fillColor=colors.HexColor("#607182"), ) ) drawing.add( String( left - 14, y - 3, f"{max_y * fraction:.0f}", textAnchor="end", fontName="Helvetica", fontSize=9, fillColor=colors.HexColor("#607182"), ) ) drawing.add( String( left + width / 2, 56, "Visible-verifier executions per run", textAnchor="middle", fontName="Helvetica-Bold", fontSize=11, fillColor=colors.HexColor("#405263"), ) ) drawing.add( String( 26, bottom + height / 2, "Wall seconds", textAnchor="middle", fontName="Helvetica-Bold", fontSize=11, fillColor=colors.HexColor("#405263"), angle=90, ) ) for condition, x, y, x1, x3, y1, y3 in points: px = left + width * x / max_x py = bottom + height * y / max_y px1 = left + width * x1 / max_x px3 = left + width * x3 / max_x py1 = bottom + height * y1 / max_y py3 = bottom + height * y3 / max_y color = colors.HexColor(CONDITION_COLORS[condition]) drawing.add(Line(px1, py, px3, py, strokeColor=color, strokeWidth=2)) drawing.add(Line(px, py1, px, py3, strokeColor=color, strokeWidth=2)) drawing.add(Circle(px, py, 8, fillColor=color, strokeColor=colors.white)) drawing.add( String( px + 12, py + 8, CONDITION_LABELS[condition], fontName="Helvetica-Bold", fontSize=10, fillColor=color, ) ) if mode == "draft" and not points: _add_pending_panel(drawing, completed) return drawing def build_figure_artifacts( results: Mapping[str, Any], *, mode: str, ) -> list[FigureArtifact]: _validate_mode(results, mode) return [ FigureArtifact( key="unsupported_completion", filename="unsupported-completion-by-condition.svg", title="Unsupported completion by condition", caption=( "Figure 1. Unsupported completed claims as a fraction of eligible " "phase outputs. In draft mode, N/A bars explicitly indicate that no " "confirmatory estimate exists." ), drawing=unsupported_completion_drawing(results, mode=mode), ), FigureArtifact( key="cost_tradeoff", filename="cost-verification-tradeoff.svg", title="Verification cost and elapsed-time trade-off", caption=( "Figure 2. Median visible-verifier executions and wall-clock time by " "condition, with interquartile-range whiskers. An empty draft panel " "contains no simulated points." ), drawing=cost_tradeoff_drawing(results, mode=mode), ), ] def scaled_drawing(drawing: Drawing, width: float) -> Drawing: scaled = copy.deepcopy(drawing) factor = width / float(drawing.width) scaled.scale(factor, factor) scaled.width = float(drawing.width) * factor scaled.height = float(drawing.height) * factor return scaled def generate_figures(root: Path, *, mode: str) -> list[Path]: root = root.resolve() results = load_results(root) artifacts = build_figure_artifacts(results, mode=mode) output = root / "paper" / "generated" / "figures" output.mkdir(parents=True, exist_ok=True) written: list[Path] = [] for artifact in artifacts: svg = renderSVG.drawToString(artifact.drawing) if not svg.endswith("\n"): svg += "\n" path = output / artifact.filename path.write_bytes(svg.encode("utf-8")) written.append(path) return written def _parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description="Generate deterministic figures from canonical BeforeDone analysis." ) parser.add_argument("--root", type=Path, default=Path.cwd()) parser.add_argument("--mode", choices=("draft", "final"), default="draft") return parser def main(argv: Sequence[str] | None = None) -> int: args = _parser().parse_args(argv) try: paths = generate_figures(args.root, mode=args.mode) except (FigureError, OSError) as exc: print(f"figure generation failed: {exc}", file=sys.stderr) return 2 for path in paths: print(path) return 0 if __name__ == "__main__": raise SystemExit(main())