SPB Git

Repository Public MIT

viz.test.ts 12.5 KB 271 lines typescript

1// @vitest-environment node2/**3 * =============================================================================4 *                  SP BOUCHER | SOFTWARE & RESEARCH5 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6 * =============================================================================7 *8 * Project          : VQuant9 * File             : server/services/research/viz.test.ts10 * Module           : server11 * Repository       : https://git.spboucher.ai/vquant12 * Project Website  : https://vquant.spboucher.ai13 * Created          : 2026-11-2014 * Last Modified    : 2026-11-2015 *16 * Author           : Simon-Pierre Boucher17 * Position         : Professor of Finance18 * Institution      : Université du Québec en Outaouais (UQO)19 * Organization     : SP Boucher20 * Website          : https://spboucher.ai21 * Git              : https://git.spboucher.ai22 *23 * Preferred Contact: contact@spboucher.ai24 * Development      : dev@spboucher.ai25 * Support          : support@spboucher.ai26 * Security/Admin   : admin@spboucher.ai27 *28 * Copyright (c) 202629 * Simon-Pierre Boucher30 * All rights reserved where applicable. This file is governed by the31 * applicable project license, copyright notices and relevant law.32 * Existing third-party rights and notices remain unaffected.33 *34 * SPDX Identifier  : MIT35 * License          : MIT License36 * License File     : LICENSE37 *38 * Do not embed credentials, private keys, access tokens,39 * certificates or confidential personal information.40 *41 * =============================================================================42 * END OF SP BOUCHER SOURCE HEADER43 * =============================================================================44 */4546/**47 * VQuant Scientific Visualization Standard (docs/next/VISUALIZATION_STANDARD.md): the palette is the design48 * tokens', and the figure linter finds — and where it can, repairs — deliberately broken figures. Runs real49 * matplotlib in the project's Python.50 */51import { beforeAll, describe, expect, it } from "vitest";52import { execFileSync } from "node:child_process";53import fs from "node:fs";54import os from "node:os";55import path from "node:path";56import { pythonPath } from "../python/lab";5758const scripts = path.join(process.cwd(), "server", "services", "python");59const tokens = JSON.parse(fs.readFileSync(path.join(process.cwd(), "shared", "design", "tokens.json"), "utf8"));60let dir: string;61let report: Record<string, any>;6263const PROGRAM = String.raw`64import json, os, sys65sys.path.insert(0, sys.argv[1])66out_dir = sys.argv[2]67import matplotlib68matplotlib.use("Agg")69import matplotlib.pyplot as plt70import numpy as np71import vq_viz72vq_viz.apply()73rng = np.random.default_rng(1)74x = np.arange(60)75res = {"tokens": vq_viz.TOKENS, "cycle": plt.rcParams["axes.prop_cycle"].by_key()["color"], "template": vq_viz.plotly_template()}7677def codes(r, fixed=None):78    return sorted(i["code"] for i in r["issues"] if fixed is None or i["fixed"] == fixed)7980# A. a clean figure81fig, ax = plt.subplots()82ax.plot(x, np.cumsum(rng.normal(size=60)), label="Strategy")83ax.plot(x, np.cumsum(rng.normal(size=60)), label="Benchmark")84ax.set_title("Cumulative return, 60 sessions"); ax.set_xlabel("Session"); ax.set_ylabel("Return (%)"); ax.legend(loc="best")85res["clean"] = vq_viz.lint(fig)86res["export"] = vq_viz.export(fig, os.path.join(out_dir, "clean"))87plt.close(fig)8889# B. forty long category labels on the x axis90fig, ax = plt.subplots(figsize=(6, 4))91ax.bar([f"Portfolio number {i:02d}" for i in range(40)], rng.random(40))92ax.set_title("Weights"); ax.set_ylabel("Weight")93before = vq_viz.lint(fig, fix=False)94res["ticks"] = {"before": codes(before), "ok_before": before["ok"], "after": vq_viz.lint(fig, fix=True)}95res["ticks"]["recheck"] = codes(vq_viz.lint(fig, fix=False))96plt.close(fig)9798# C. a legend dropped on the data99fig, ax = plt.subplots()100for k in range(3):101    ax.plot(x, 0.5 + 0.02 * rng.normal(size=60), label=f"Series {k} with a long name")102ax.set_ylim(0, 1); ax.set_title("Legend on the data"); ax.set_xlabel("t"); ax.set_ylabel("level")103ax.legend(loc="center")104res["legend"] = {"before": codes(vq_viz.lint(fig, fix=False)), "after": vq_viz.lint(fig, fix=True), "recheck": codes(vq_viz.lint(fig, fix=False))}105plt.close(fig)106107# D. unreadable text: tiny and nearly white108fig, ax = plt.subplots()109ax.plot(x, x); ax.set_title("Tiny", fontsize=4); ax.set_xlabel("x axis", fontsize=5); ax.set_ylabel("y axis", color="#F4F4F4")110r = vq_viz.lint(fig)111res["text"] = {"report": r, "min_font": min(t.get_fontsize() for t in [ax.title, ax._left_title, ax.xaxis.label] if t.get_text()), "ylabel_color": matplotlib.colors.to_hex(ax.yaxis.label.get_color())}112plt.close(fig)113114# E. nothing tells the reader what is plotted115fig, ax = plt.subplots()116ax.plot(rng.normal(size=50), rng.normal(size=50), "o")117res["bare"] = vq_viz.lint(fig)118plt.close(fig)119120# F. twelve series for eight colours121fig, ax = plt.subplots()122for k in range(12):123    ax.plot(x, np.cumsum(rng.normal(size=60)), label=f"s{k}")124ax.set_title("Twelve"); ax.set_xlabel("t"); ax.set_ylabel("v")125res["many"] = vq_viz.lint(fig)126plt.close(fig)127128# G. an annotation cut by the edge of the plot, on a figure of absurd size129fig, ax = plt.subplots(figsize=(30, 2))130ax.plot(x, x); ax.set_title("Clipped"); ax.set_xlabel("t"); ax.set_ylabel("v")131note = ax.text(59, 59, "An annotation that runs far beyond the right edge", clip_on=True)132res["clipped"] = {"report": vq_viz.lint(fig), "clip_on_after": note.get_clip_on(), "size_after": list(fig.get_size_inches())}133plt.close(fig)134135# H. an empty canvas136fig = plt.figure()137res["empty"] = vq_viz.lint(fig)138plt.close(fig)139140# I. off-palette colours141fig, ax = plt.subplots()142for c in ("#123456", "#abcdef", "#fedcba"):143    ax.plot(x, rng.normal(size=60), color=c, label=c)144ax.set_title("Colours"); ax.set_xlabel("t"); ax.set_ylabel("v")145res["palette"] = vq_viz.lint(fig)146plt.close(fig)147148# J. a scatter with the legend sitting on a point, and a subtitle left over the plot by tight_layout()149fig, ax = plt.subplots()150ax.scatter([1, 2, 3, 9.6], [1, 2, 3, 9.6], label="h = 1")151ax.scatter([1.5, 2.5], [2, 1], label="h = 4")152ax.set_xlim(0, 10); ax.set_ylim(0, 10); ax.set_xlabel("x"); ax.set_ylabel("y")153ax.legend(loc="upper right")154fig.text(0.13, 0.93, "Title placed in figure coordinates", fontsize=14)155fig.text(0.13, 0.87, "Subtitle that the layout does not know about", fontsize=10)156fig.tight_layout()157before = vq_viz.lint(fig, fix=False)158res["header"] = {"before": codes(before), "after": vq_viz.lint(fig, fix=True), "recheck": codes(vq_viz.lint(fig, fix=False))}159plt.close(fig)160161class FakePlotly:162    def __init__(self, d): self.d = d163    def to_dict(self): return self.d164res["plotly_bad"] = vq_viz.lint_plotly(FakePlotly({"data": [{"type": "scatter"} for _ in range(11)], "layout": {"font": {"size": 6}}}))165res["plotly_ok"] = vq_viz.lint_plotly(FakePlotly({"data": [{"type": "scatter", "line": {"color": vq_viz.COLORS[0]}}], "layout": {"title": {"text": "T"}, "yaxis": {"title": {"text": "USD"}}}}))166res["plotly_empty"] = vq_viz.lint_plotly(FakePlotly({"data": [], "layout": {}}))167print(json.dumps(res))168`;169170const codes = (r: any, fixed?: boolean): string[] => r.issues.filter((i: any) => fixed === undefined || i.fixed === fixed).map((i: any) => i.code).sort();171172beforeAll(() => {173  dir = fs.mkdtempSync(path.join(os.tmpdir(), "vq-viz-"));174  fs.writeFileSync(path.join(dir, "figures.py"), PROGRAM);175  const out = execFileSync(pythonPath(), [path.join(dir, "figures.py"), scripts, dir], { encoding: "utf8", env: { ...process.env, MPLBACKEND: "Agg", MPLCONFIGDIR: dir }, timeout: 120_000 });176  report = JSON.parse(out.trim().split("\n").pop()!);177}, 150_000);178179describe("design tokens", () => {180  it("uses the categorical, sequential and diverging palettes and the text colours of shared/design/tokens.json", () => {181    expect(report.tokens.categorical).toEqual(tokens.data.categorical.light);182    expect(report.tokens.sequential).toEqual(tokens.data.sequential.light);183    expect(report.tokens.diverging).toEqual(tokens.data.diverging.light);184    expect(report.tokens.up).toBe(tokens.upDown.classic.light.up);185    expect(report.tokens.down).toBe(tokens.upDown.classic.light.down);186    expect(report.tokens.cvdUp).toBe(tokens.upDown.cvd.light.up);187    expect(report.tokens.cvdDown).toBe(tokens.upDown.cvd.light.down);188    for (const k of ["text1", "text2", "text3", "line", "accent"]) expect(report.tokens[k], k).toBe(tokens.color.light[k]);189  });190191  it("applies the palette to matplotlib and to the plotly template", () => {192    expect(report.cycle.map((c: string) => c.toUpperCase())).toEqual(tokens.data.categorical.light);193    expect(report.template.layout.colorway).toEqual(tokens.data.categorical.light);194    expect(report.template.layout.font.color).toBe(tokens.color.light.text2);195  });196});197198describe("figure linter", () => {199  it("passes a clean figure and exports it as PNG, SVG and PDF", () => {200    expect(report.clean.ok).toBe(true);201    expect(report.clean.issues.filter((i: any) => i.severity !== "info")).toEqual([]);202    for (const fmt of ["png", "svg", "pdf"]) expect(fs.statSync(report.export[fmt]).size, fmt).toBeGreaterThan(2000);203    expect(report.export.errors).toBeUndefined();204    expect(fs.readFileSync(report.export.png).subarray(1, 4).toString()).toBe("PNG");205    expect(fs.readFileSync(report.export.svg, "utf8")).toContain("<svg");206    expect(fs.readFileSync(report.export.pdf).subarray(0, 4).toString()).toBe("%PDF");207    // 200 dpi: an 11 in wide figure is about 2 200 px wide (tight bounding box plus padding).208    expect(fs.readFileSync(report.export.png).readUInt32BE(16)).toBeGreaterThan(1900);209  });210211  it("detects colliding tick labels and repairs them", () => {212    expect(report.ticks.before).toContain("tick_overlap");213    expect(report.ticks.ok_before).toBe(false);214    expect(codes(report.ticks.after, true)).toContain("tick_overlap");215    expect(report.ticks.after.ok).toBe(true);216    expect(report.ticks.recheck).not.toContain("tick_overlap");217  });218219  it("detects a legend covering the data and moves it", () => {220    expect(report.legend.before).toContain("legend_overlap");221    expect(codes(report.legend.after, true)).toContain("legend_overlap");222    expect(report.legend.recheck).not.toContain("legend_overlap");223  });224225  it("raises text below the size floor and recolours text without contrast", () => {226    expect(codes(report.text.report, true)).toEqual(expect.arrayContaining(["contrast", "font_size"]));227    expect(report.text.min_font).toBeGreaterThanOrEqual(7.5);228    expect(report.text.ylabel_color).toBe(tokens.color.light.text3.toLowerCase());229  });230231  it("reports what only the author can fix: no title, axes without label or unit", () => {232    expect(report.bare.ok).toBe(false);233    expect(codes(report.bare, false)).toEqual(expect.arrayContaining(["title", "x_label", "y_label"]));234  });235236  it("reports too many series for the palette, and colours that are not the palette's", () => {237    expect(codes(report.many, false)).toContain("too_many_series");238    expect(report.many.ok).toBe(false);239    const off = report.palette.issues.find((i: any) => i.code === "off_palette");240    expect(off).toMatchObject({ severity: "info", fixed: false });241    expect(report.palette.ok).toBe(true); // information, not a defect242    expect(codes(report.clean)).not.toContain("off_palette");243  });244245  it("frees an annotation cut by the plot area and brings an absurd size back in range", () => {246    expect(codes(report.clipped.report, true)).toEqual(expect.arrayContaining(["size", "text_clipped"]));247    expect(report.clipped.clip_on_after).toBe(false);248    expect(report.clipped.size_after[0]).toBeLessThanOrEqual(16);249    expect(report.clipped.size_after[1]).toBeGreaterThanOrEqual(2.8);250  });251252  it("sees a scatter point hidden by the legend and a subtitle lying on the plot, and repairs both", () => {253    expect(report.header.before).toEqual(expect.arrayContaining(["header_over_plot", "legend_overlap"]));254    expect(codes(report.header.after, true)).toEqual(expect.arrayContaining(["header_over_plot", "legend_overlap"]));255    expect(report.header.recheck).not.toContain("header_over_plot");256    expect(report.header.recheck).not.toContain("legend_overlap");257  });258259  it("rejects an empty figure", () => {260    expect(report.empty.ok).toBe(false);261    expect(report.empty.issues[0]).toMatchObject({ code: "empty", severity: "error" });262  });263264  it("inspects plotly figures statically", () => {265    expect(codes(report.plotly_bad)).toEqual(expect.arrayContaining(["font_size", "title", "too_many_series", "y_label"]));266    expect(report.plotly_bad.ok).toBe(false);267    expect(report.plotly_ok).toEqual({ issues: [], ok: true });268    expect(report.plotly_empty.issues[0].code).toBe("empty");269  });270});271
Files main
Menu

Theme