research-weights.ts

1.8 kB · typescript · 50 lines

1import { frame, plot, type Color, type Frame, type Pen, type Ink, type Point } from "mrlyjs/view";2import census from "../files/figures/census/research-weights.json" with { type: "json" };34const SAMPLES = 720;56export const units = {};78// PANEL910function center(ys: number[]) {11  let sum = 0;12  for (const y of ys) sum += y;13  const mean = sum / ys.length;14  return ys.map((y) => y - mean);15}1617function reach(first: number[], second: number[]) {18  let top = 0;19  for (const y of [...first, ...second]) top = Math.max(top, Math.abs(y));20  return top * 1.14;21}2223function trace(pen: Pen, area: Frame, ys: number[], span: number, thick: number, color: Color) {24  const last = ys.length - 1;25  const pts = ys.map((y, i): Point => [area.x + (area.w * i) / last, area.y + area.h * (0.5 - (0.5 * y) / span)]);26  pen.polyline(pts, thick, color);27}2829function panel(pen: Pen, ink: Ink, area: Frame, first: number[], second: number[]) {30  plot.axis(pen, area, ink.line);31  const inner = area.inset(18);32  const mid = inner.y + inner.h / 2;33  pen.segment([inner.x, mid], [inner.x + inner.w, mid], 1, ink.line);34  const span = reach(first, second);35  trace(pen, inner, second, span, 3.4, ink.orange);36  trace(pen, inner, first, span, 2.1, ink.blue);37}3839// DRAW4041export default function draw(pen: Pen, ink: Ink) {42  const { lattice, smooth, thin, fat } = census as Record<string, number[]>;43  for (const ys of [lattice, smooth, thin, fat]) {44    if (ys?.length !== SAMPLES) throw new Error(`research-weights: a curve of ${ys?.length} samples, want ${SAMPLES}`);45  }46  const box = pen.frame(0.08);47  const half = box.h / 2;48  panel(pen, ink, frame(box.x, box.y, box.w, half).inset(14), center(lattice), center(smooth));49  panel(pen, ink, frame(box.x, box.y + half, box.w, half).inset(14), center(thin), center(fat));50}