Coverage for lab/report_html.py: 100%
83 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Self-contained HTML pages for the lab's reports: one file, no scripts, no external assets, light and dark.
3`evaluation/hello_world.py`'s page is built from these too. Pure; numbers go in, a string comes out.
4"""
6from __future__ import annotations
8import html
9import math
10from collections.abc import Mapping, Sequence
12import numpy as np
13import pandas as pd
15PALETTE = ("#d97706", "#2563eb", "#059669", "#7c3aed", "#dc2626", "#64748b", "#0891b2", "#ca8a04")
17STYLE = """:root{color-scheme:light dark;--fg:#111827;--bg:#ffffff;--muted:#6b7280;--line:#e5e7eb}
18@media (prefers-color-scheme: dark){:root{--fg:#f3f4f6;--bg:#111827;--muted:#9ca3af;--line:#374151}}
19body{font:15px/1.5 system-ui,sans-serif;color:var(--fg);background:var(--bg);max-width:900px;margin:2rem auto;padding:0 16px}
20table{border-collapse:collapse;width:100%;margin:1rem 0}td,th{border-bottom:1px solid var(--line);padding:.35rem .5rem;text-align:right}
21td:first-child,th:first-child{text-align:left}.muted{color:var(--muted)}svg{max-width:100%;height:auto}"""
24def fmt(value: object, digits: int = 3) -> str:
25 """A number to `digits` places, '-' for None or a non-finite float, anything else as text."""
26 if value is None:
27 return "-"
28 if isinstance(value, (int, np.integer)) and not isinstance(value, bool):
29 return str(int(value))
30 if isinstance(value, (float, np.floating)):
31 return f"{float(value):.{digits}f}" if math.isfinite(float(value)) else "-"
32 return str(value)
35def svg_lines(series: Sequence[pd.Series], colors: Sequence[str] = PALETTE, width: int = 720, height: int = 260, label: str = "Equity curves") -> str:
36 """One polyline per series on a shared vertical scale."""
37 values = np.concatenate([np.asarray(curve, dtype=float) for curve in series]) if series else np.array([])
38 values = values[np.isfinite(values)]
39 low, high = (float(values.min()), float(values.max())) if values.size else (0.0, 1.0)
40 span = high - low or 1.0
41 paths = []
42 for curve, color in zip(series, colors, strict=False):
43 data = np.asarray(curve, dtype=float)
44 steps = max(len(data) - 1, 1)
45 points = " ".join(f"{i / steps * width:.1f},{height - (value - low) / span * height:.1f}" for i, value in enumerate(data) if math.isfinite(value))
46 paths.append(f'<polyline fill="none" stroke="{color}" stroke-width="1.6" points="{points}"/>')
47 return f'<svg viewBox="0 0 {width} {height}" width="100%" role="img" aria-label="{html.escape(label)}">{"".join(paths)}</svg>'
50def svg_bars(values: Mapping[str, float], width: int = 720, bar: int = 18, label: str = "Bars") -> str:
51 """Horizontal bars, one per key, signed around a zero line."""
52 items = [(name, float(value)) for name, value in values.items() if value is not None and math.isfinite(float(value))]
53 if not items:
54 return ""
55 scale = max(abs(value) for _, value in items) or 1.0
56 zero, half, rows = width * 0.45, width * 0.25, []
57 for index, (name, value) in enumerate(items):
58 y = index * (bar + 6)
59 length = abs(value) / scale * half
60 x = zero if value >= 0 else zero - length
61 color = PALETTE[2] if value >= 0 else PALETTE[4]
62 rows.append(f'<text x="0" y="{y + bar - 4}" font-size="12" fill="currentColor">{html.escape(name)}</text>'
63 f'<rect x="{x:.1f}" y="{y}" width="{length:.1f}" height="{bar}" fill="{color}"/>'
64 f'<text x="{zero + half + 8:.1f}" y="{y + bar - 4}" font-size="12" fill="currentColor">{fmt(value)}</text>')
65 total = len(items) * (bar + 6)
66 return f'<svg viewBox="0 0 {width} {total}" width="100%" role="img" aria-label="{html.escape(label)}"><line x1="{zero}" y1="0" x2="{zero}" y2="{total}" stroke="currentColor" stroke-opacity=".3"/>{"".join(rows)}</svg>'
69def svg_heatmap(matrix: pd.DataFrame, cell: int = 26, label: str = "Correlation") -> str:
70 """A square matrix in [-1, 1] as coloured cells (blue negative, orange positive) with row and column names."""
71 names = [str(name) for name in matrix.columns]
72 pad = 8 + 7 * max((len(name) for name in names), default=1)
73 size = pad + cell * len(names)
74 cells = []
75 for row, row_name in enumerate(matrix.index):
76 cells.append(f'<text x="{pad - 4}" y="{pad + row * cell + cell * 0.65:.1f}" font-size="11" text-anchor="end" fill="currentColor">{html.escape(str(row_name))}</text>')
77 for column, _ in enumerate(matrix.columns):
78 value = float(matrix.iat[row, column])
79 alpha = min(abs(value), 1.0) if math.isfinite(value) else 0.0
80 color = "217,119,6" if value >= 0 else "37,99,235"
81 tip = f"{html.escape(str(row_name))} / {html.escape(names[column])}: {fmt(value, 2)}"
82 cells.append(f'<rect x="{pad + column * cell}" y="{pad + row * cell}" width="{cell - 1}" height="{cell - 1}" fill="rgba({color},{alpha:.2f})"><title>{tip}</title></rect>')
83 for column, name in enumerate(names):
84 cells.append(f'<text x="{pad + column * cell + cell / 2:.1f}" y="{pad - 4}" font-size="11" text-anchor="start" transform="rotate(-60 {pad + column * cell + cell / 2:.1f} {pad - 4})" fill="currentColor">{html.escape(name)}</text>')
85 return f'<svg viewBox="0 0 {size} {size}" width="100%" role="img" aria-label="{html.escape(label)}">{"".join(cells)}</svg>'
88def svg_histogram(values: Sequence[float], bins: int = 30, width: int = 720, height: int = 160, label: str = "Distribution") -> str:
89 """An inline SVG histogram of `values`."""
90 data = np.asarray(values, dtype=float)
91 data = data[np.isfinite(data)]
92 if data.size == 0:
93 return ""
94 counts, _ = np.histogram(data, bins=bins)
95 top = counts.max() or 1
96 step = width / bins
97 rects = "".join(
98 f'<rect x="{i * step:.1f}" y="{height - count / top * height:.1f}" width="{step - 1:.1f}" height="{count / top * height:.1f}" fill="{PALETTE[1]}"/>'
99 for i, count in enumerate(counts)
100 )
101 return f'<svg viewBox="0 0 {width} {height}" width="100%" role="img" aria-label="{html.escape(label)}">{rects}</svg>'
104def table(rows: Sequence[Sequence[object]], header: Sequence[str] | None = None) -> str:
105 """An HTML table from rows and a header."""
106 head = "<thead><tr>" + "".join(f"<th>{html.escape(str(cell))}</th>" for cell in header) + "</tr></thead>" if header else ""
107 body = "".join("<tr>" + "".join(f"<td>{html.escape(fmt(cell))}</td>" for cell in row) + "</tr>" for row in rows)
108 return f"<table>{head}<tbody>{body}</tbody></table>"
111def legend(names: Sequence[str], colors: Sequence[str] = PALETTE) -> str:
112 """An HTML legend for a chart's series, each name in its colour."""
113 return '<p class="muted">' + " ".join(f'<span style="color:{color}">■</span> {html.escape(name)}' for name, color in zip(names, colors, strict=False)) + "</p>"
116def page(title: str, sections: Sequence[tuple[str, str]], subtitle: str = "", footer: str = "") -> str:
117 """A whole page: a title, an optional muted subtitle, (heading, html) sections and an optional footer line."""
118 parts = [f"<h1>{html.escape(title)}</h1>"]
119 if subtitle:
120 parts.append(f'<p class="muted">{html.escape(subtitle)}</p>')
121 for heading, body in sections:
122 parts.append((f"<h2>{html.escape(heading)}</h2>" if heading else "") + body)
123 if footer:
124 parts.append(f"<p><strong>{html.escape(footer)}</strong></p>")
125 return (f'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">\n'
126 f"<title>{html.escape(title)}</title><style>\n{STYLE}</style></head><body>\n" + "\n".join(parts) + "</body></html>\n")