import { use, init, type ECharts } from "echarts/core"; import { ScatterChart } from "echarts/charts"; import { DataZoomComponent, TitleComponent, TooltipComponent, VisualMapComponent } from "echarts/components"; import { CanvasRenderer } from "echarts/renderers"; import { columnValues, type Column, type Table } from "@tedius-npm/newman"; import { cssColor, getColor } from "./color"; import { colorScale, IMAGE_MARGIN, IMAGE_SCALE_WIDTH, imageWithScale } from "./color-scale"; import { PLOT_IMAGE_HEIGHT, PLOT_IMAGE_WIDTH, isMagnitude, paintColor, plotColumns, plotRows, type ColorStops, type PlotSpec, } from "@tedius-npm/vandelay"; import { extent } from "./utils"; import type { PlotZoom } from "./view"; use([ScatterChart, TitleComponent, TooltipComponent, VisualMapComponent, DataZoomComponent, CanvasRenderer]); const GRADIENT_SAMPLES = 128; /** The top and bottom of the tab's grid, the ECharts defaults, so the color scale beside it can span the same height. */ export const TAB_GRID = { top: 65, bottom: 80 }; export type ScatterInput = { table: Table; rows: Uint32Array; x: number; y: number; paint: { column: number; colorRGB: ColorStops[] } | null; /** Each axis spans the drawn rows, as on the 2D tab, or the given range, as a slice spans its 3D view. */ bounds: "rows" | AxisBounds; zoom?: PlotZoom; /** A line written in the top right corner. */ note?: string; }; /** * The paint of an image as a visual map. ECharts spreads the colors of a visual map evenly between its min * and max, so passing the stops' own colors would ignore where each stop is. This samples getColor, * the function the 3D view paints with, over the whole column, so both views color a value the same * way, a value past the last stop included. */ function visualMap(table: Table, paint: NonNullable) { const col = table.columns[paint.column]; const first = paint.colorRGB[0].stop; const last = paint.colorRGB[paint.colorRGB.length - 1].stop; const min = Math.min(first, col.min === null ? first : Number(col.min)); let max = Math.max(last, col.max === null ? last : Number(col.max)); if (!(max > min)) max = min + 1; const color = Array.from({ length: GRADIENT_SAMPLES }, (_, i) => getColor(min + ((max - min) * i) / (GRADIENT_SAMPLES - 1), paint.colorRGB), ); return { show: false, dimension: 2, min, max, inRange: { color } }; } export type AxisBounds = { x: [number, number]; y: [number, number] }; function axisTitle(column: Column): string { return column.unit ? `${column.name} (${column.unit})` : column.name; } // A painted point's border, thin and dark, so it stays apart from its neighbours const BORDER_RGB: [number, number, number] = [26, 26, 26]; const BORDER_ALPHA = 0.6; const BORDER_WIDTH = 0.6; const PAINTED_BORDER = { borderColor: `rgba(${BORDER_RGB.join(", ")}, ${BORDER_ALPHA})`, borderWidth: BORDER_WIDTH }; const FONT = '"JetBrains Mono", monospace'; const SYMBOL_SIZE = 5; // A hovered point grows this many times, and a clicked one takes a border this wide const HOVER_SCALE = 4; const CLICK_BORDER = 15; /** How a painted point looks, in CSS pixels, for the drawing outside ECharts: the series' symbol and its border. */ export const PAINTED_POINT = { radius: SYMBOL_SIZE / 2, border: BORDER_WIDTH, borderRGB: BORDER_RGB, borderAlpha: BORDER_ALPHA, }; function axisStyle(column: Column, target: ScatterTarget, vertical: boolean) { const black = cssColor("black"); const image = target === "image"; const inverse = isMagnitude(column); return { name: image ? axisTitle(column) : (column.unit ?? ""), // "end" follows an inverted axis, so it flips too, to stay at the top or the right nameLocation: image ? "middle" : inverse ? "start" : "end", nameGap: image ? (vertical ? 110 : 60) : 12, nameTextStyle: { color: black, fontFamily: FONT, fontWeight: 700, fontSize: image ? 24 : 12 }, inverse, axisLine: { lineStyle: { color: black } }, axisTick: { lineStyle: { color: black } }, axisLabel: { color: black, fontFamily: FONT, fontSize: image ? 18 : 12 }, splitLine: { lineStyle: { color: cssColor("lightgray") } }, }; } function sliceBounds(table: Table, spec: PlotSpec): AxisBounds { const rows = plotRows(table, spec.filters, plotColumns(spec)); const span = (c: number) => extent(columnValues(table.columns[c], rows)) ?? [0, 0]; return { x: span(spec.axes.x), y: span(spec.axes.y) }; } function formatDensity(value: number): string { if (value === 0) return "0"; const magnitude = Math.abs(value); return magnitude >= 1e-3 && magnitude < 1e6 ? String(Number(value.toPrecision(3))) : value.toExponential(2); } export function densityText(table: Table, count: number, bounds: AxisBounds, x: number, y: number): string { const area = (bounds.x[1] - bounds.x[0]) * (bounds.y[1] - bounds.y[0]); if (!(area > 0)) return `${count} points`; const unit = (c: number) => table.columns[c].unit || table.columns[c].name; return `${formatDensity(count / area)} points per ${unit(x)} x ${unit(y)}`; } export function sliceInput(table: Table, spec: PlotSpec, rows: Uint32Array): ScatterInput { const { x, y } = spec.axes; const bounds = sliceBounds(table, spec); return { table, rows, x, y, paint: spec.paint, bounds, note: densityText(table, rows.length, bounds, x, y) }; } /** Where an option is drawn: the 2D tab, or an image of the export size. */ export type ScatterTarget = "tab" | "image"; /** * Everything but the tooltip and the click handler, which only the tab has. On the tab, the points * of a paint are drawn over the chart by drawPainted, from paintedPoints of the same input. */ export function scatterOption(input: ScatterInput, target: ScatterTarget = "tab") { const { table, rows, x, y, paint } = input; const xs = columnValues(table.columns[x], rows); const ys = columnValues(table.columns[y], rows); const colors = paint ? columnValues(table.columns[paint.column], rows) : null; const image = target === "image"; // On the tab, ECharts draws no painted point, only keeps its tooltip, its click and its zoom, and // drawPainted draws it in its color over the chart const hidden = !image && colors !== null; // A painted image draws each point as an item, so a point with no paint value can skip the // visual map and keep the series' black, as in the 3D view. Everything else goes in ECharts' // large mode, as flat [x, y, paint] triples, which ECharts keeps as they are, where it deep // copies an array of arrays on every setOption and getOption. const items = image && colors !== null; let data: Float64Array | (number[] | { value: number[]; visualMap: false })[]; if (items) { data = Array.from(rows, (_, i) => { const value = [xs[i], ys[i], colors[i]]; return Number.isFinite(value[2]) ? value : { value, visualMap: false as const }; }); } else { data = new Float64Array(rows.length * 3); for (let i = 0; i < rows.length; i++) { data[i * 3] = xs[i]; data[i * 3 + 1] = ys[i]; data[i * 3 + 2] = colors ? colors[i] : 0; } } // Fixed axis bounds, so zooming does not recompute them const [xMin, xMax] = input.bounds === "rows" ? (extent(xs) ?? [0, 0]) : input.bounds.x; const [yMin, yMax] = input.bounds === "rows" ? (extent(ys) ?? [0, 0]) : input.bounds.y; // An image with a painted point has a color scale, which scatterPng draws in the strip on its right const scaled = target === "image" && colors !== null && extent(colors) !== null; return { // Room for the full axis titles of an image, and for its color scale grid: target === "image" ? { left: 170, right: scaled ? IMAGE_SCALE_WIDTH : 70, ...IMAGE_MARGIN } : { ...TAB_GRID }, xAxis: { type: "value", min: xMin, max: xMax, scale: true, ...axisStyle(table.columns[x], target, false) }, yAxis: { type: "value", min: yMin, max: yMax, scale: true, ...axisStyle(table.columns[y], target, true) }, dataZoom: [ { type: "inside", xAxisIndex: 0, filterMode: "filter", ...(input.zoom && { start: input.zoom.x[0], end: input.zoom.x[1] }), }, { type: "inside", yAxisIndex: 0, filterMode: "filter", ...(input.zoom && { start: input.zoom.y[0], end: input.zoom.y[1] }), }, ], ...(input.note !== undefined && { title: { text: input.note, right: 16, top: 12, textStyle: { color: cssColor("black"), fontFamily: FONT, fontSize: 24, fontWeight: 600 }, }, }), visualMap: items ? visualMap(table, paint!) : { show: false, dimension: 2, min: 0, max: 1, inRange: { color: ["#000000"] } }, series: [ { type: "scatter", cursor: "none", symbolSize: SYMBOL_SIZE, // A typed array needs them named, and the visual map reads the third dimensions: ["x", "y", "paint"], data, selectedMode: "single", large: !items, // Invisible points have nothing to draw a part at a time, so their places come in one // pass. Undefined rather than left out, so the merge of the next option clears the 0. progressive: hidden ? 0 : undefined, // A style with no opacity is never painted, though its points still catch the pointer itemStyle: hidden ? { opacity: 0 } : { opacity: 1, color: "#000000", ...(items && PAINTED_BORDER) }, // What drawHighlights draws for a painted point, ECharts draws for the others emphasis: { scale: HOVER_SCALE, itemStyle: { color: cssColor("magenta") } }, select: { itemStyle: { color: cssColor("violet"), borderColor: cssColor("violet"), borderWidth: CLICK_BORDER, // makes the selected point look bigger }, }, }, ], }; } /** * `input` drawn as a PNG of the export size, on white, by a second ECharts instance on a detached * div that is disposed right after, with the color scale of its paint on the right. Animation and * progressive rendering are off, so the image holds every point when it is taken. */ export async function scatterPng(input: ScatterInput): Promise { const option = scatterOption(input, "image"); const chart = init(document.createElement("div"), null, { renderer: "canvas", width: PLOT_IMAGE_WIDTH, height: PLOT_IMAGE_HEIGHT, devicePixelRatio: 1, }); try { chart.setOption({ ...option, animation: false, series: option.series.map((s) => ({ ...s, progressive: 0 })) }); // What getDataURL encodes, kept as a canvas so the scale can join it const drawn = chart.renderToCanvas({ pixelRatio: 1, backgroundColor: "#ffffff" }); const scale = input.paint && colorScale(input.table, input.paint, input.rows); const url = (scale ? imageWithScale(drawn, scale) : drawn).toDataURL("image/png"); const bytes = Uint8Array.from(atob(url.slice(url.indexOf(",") + 1)), (c) => c.charCodeAt(0)); return new Blob([bytes], { type: "image/png" }); } finally { chart.dispose(); } } /// PAINTED POINTS OF THE TAB ///////////////////////////////////////////////////////////////////// /** * The painted points of the tab, in the order of its rows, so a later row is drawn over an earlier * one, as ECharts draws its items. `rgb` holds three bytes a point, paintColor's, the gradient the 3D * view and the color scale draw with, or black with no paint value. */ export type PaintedPoints = { rows: Uint32Array; xs: Float64Array; ys: Float64Array; rgb: Uint8Array }; /** The points of `input` as the tab draws them over its chart, or null with no paint. */ export function paintedPoints(input: ScatterInput): PaintedPoints | null { const { table, rows, x, y, paint } = input; if (!paint) return null; const values = columnValues(table.columns[paint.column], rows); const rgb = new Uint8Array(values.length * 3); for (let i = 0; i < values.length; i++) { if (Number.isFinite(values[i])) rgb.set(paintColor(values[i], paint.colorRGB), i * 3); } return { rows, xs: columnValues(table.columns[x], rows), ys: columnValues(table.columns[y], rows), rgb }; } /** * Where a chart draws its points, in CSS pixels: the box of its grid, and on each axis the value * at the box's first edge and the pixels per unit, negative on an inverted axis. */ export type ChartFrame = { left: number; top: number; right: number; bottom: number; x0: number; xScale: number; y0: number; yScale: number; }; /** * The frame of `chart` as its last render left it, so it follows the zoom, an inverted axis and the * room ECharts makes for the axis labels. Only public calls: the edges are bisected with * containPixel, and the values at them come from convertFromPixel, so an axis of huge values, such * as a source id, keeps its precision. Null without a grid, or with an axis of a single value, on * which ECharts draws no point either. */ export function chartFrame(chart: ECharts): ChartFrame | null { const width = chart.getWidth(); const height = chart.getHeight(); const inside = (px: number, py: number) => chart.containPixel({ gridIndex: 0 }, [px, py]); const cx = width / 2; const cy = height / 2; if (!inside(cx, cy)) return null; // From a pixel inside the grid towards one outside it, the last one inside const edge = (from: number, to: number, isInside: (t: number) => boolean) => { for (let k = 0; k < 32; k++) { const mid = (from + to) / 2; if (isInside(mid)) from = mid; else to = mid; } return from; }; const left = edge(cx, -1, (t) => inside(t, cy)); const right = edge(cx, width + 1, (t) => inside(t, cy)); const top = edge(cy, -1, (t) => inside(cx, t)); const bottom = edge(cy, height + 1, (t) => inside(cx, t)); const xAt = (px: number) => chart.convertFromPixel({ xAxisIndex: 0 }, px) as number; const yAt = (py: number) => chart.convertFromPixel({ yAxisIndex: 0 }, py) as number; const x0 = xAt(left); const y0 = yAt(top); const xScale = (right - left) / (xAt(right) - x0); const yScale = (bottom - top) / (yAt(bottom) - y0); if (!Number.isFinite(xScale) || !Number.isFinite(yScale)) return null; return { left, top, right, bottom, x0, xScale, y0, yScale }; } export function sameFrame(a: ChartFrame | null, b: ChartFrame | null): boolean { if (!a || !b) return a === b; return ( a.left === b.left && a.top === b.top && a.right === b.right && a.bottom === b.bottom && a.x0 === b.x0 && a.xScale === b.xScale && a.y0 === b.y0 && a.yScale === b.yScale ); } // How far past the grid a point's center may lie and still be drawn, the clip area of an ECharts scatter const CLIP_TOLERANCE = 0.1; // Whether a point centered on (px, py) is drawn. Like ECharts, a point whose center is inside the // grid is drawn whole, even where it pokes past the edge. The axes span the plotted values, so some // points sit right on an edge. function inside(frame: ChartFrame, px: number, py: number): boolean { const t = CLIP_TOLERANCE; return px >= frame.left - t && px <= frame.right + t && py >= frame.top - t && py <= frame.bottom + t; } /** The pixel of point `i`, or null when it is not drawn. */ export function pointAt(points: PaintedPoints, frame: ChartFrame, i: number): [number, number] | null { const px = frame.left + (points.xs[i] - frame.x0) * frame.xScale; const py = frame.top + (points.ys[i] - frame.y0) * frame.yScale; return inside(frame, px, py) ? [px, py] : null; } /** Where projectPoints puts a point that is not drawn, far past any canvas. */ export const OUTSIDE = -1e6; /** The pixel of every point into `out`, two numbers a point, OUTSIDE for one that is not drawn. */ export function projectPoints(points: PaintedPoints, frame: ChartFrame, out: Float32Array) { const { xs, ys } = points; for (let i = 0; i < xs.length; i++) { const px = frame.left + (xs[i] - frame.x0) * frame.xScale; const py = frame.top + (ys[i] - frame.y0) * frame.yScale; const drawn = inside(frame, px, py); out[i * 2] = drawn ? px : OUTSIDE; out[i * 2 + 1] = drawn ? py : OUTSIDE; } } /** * A circle of `radius` at (`px`, `py`) filled with `fill`, its border `border` pixels wide, drawn * as zrender draws a symbol: a unit circle under a transform of the symbol's size, and a border * that does not scale with it. A plain arc of that radius comes out with other edge pixels. */ function drawSymbol( ctx: CanvasRenderingContext2D, base: DOMMatrix, px: number, py: number, radius: number, fill: string, border: number, ) { ctx.setTransform(base.a * radius, 0, 0, base.d * radius, base.a * px + base.e, base.d * py + base.f); ctx.beginPath(); ctx.moveTo(1, 0); ctx.arc(0, 0, 1, 0, 2 * Math.PI); ctx.fillStyle = fill; ctx.fill(); ctx.lineWidth = border / radius; ctx.stroke(); } /** * Every point of `points` inside `frame` on a 2D canvas, as the series draws an item: its circle, * its fill, and the thin dark border of a painted point. The tab draws them with WebGL where it * can, in src/painted-layer.ts, since a canvas rasters each one apart. */ export function drawPainted(ctx: CanvasRenderingContext2D, points: PaintedPoints, frame: ChartFrame) { ctx.save(); const base = ctx.getTransform(); ctx.strokeStyle = PAINTED_BORDER.borderColor; const { rgb } = points; const at = new Float32Array(points.rows.length * 2); projectPoints(points, frame, at); for (let i = 0; i < points.rows.length; i++) { if (at[i * 2] === OUTSIDE) continue; const fill = `rgb(${rgb[i * 3]}, ${rgb[i * 3 + 1]}, ${rgb[i * 3 + 2]})`; drawSymbol(ctx, base, at[i * 2], at[i * 2 + 1], SYMBOL_SIZE / 2, fill, PAINTED_BORDER.borderWidth); } ctx.restore(); } /** * The clicked point, then the hovered one over it, each an index into `points`, drawn the way the * series' select and emphasis styles drew them: violet with a wide border, and magenta and larger. */ export function drawHighlights( ctx: CanvasRenderingContext2D, points: PaintedPoints, frame: ChartFrame, hovered: number | null, clicked: number | null, ) { ctx.save(); const base = ctx.getTransform(); const clickedAt = clicked === null ? null : pointAt(points, frame, clicked); if (clickedAt) { const violet = cssColor("violet"); ctx.strokeStyle = violet; drawSymbol(ctx, base, clickedAt[0], clickedAt[1], SYMBOL_SIZE / 2, violet, CLICK_BORDER); } const hoveredAt = hovered === null ? null : pointAt(points, frame, hovered); if (hoveredAt) { ctx.strokeStyle = PAINTED_BORDER.borderColor; const radius = (SYMBOL_SIZE / 2) * HOVER_SCALE; drawSymbol(ctx, base, hoveredAt[0], hoveredAt[1], radius, cssColor("magenta"), PAINTED_BORDER.borderWidth); } ctx.restore(); } ////////////////////////////////////////////////////////////////////////////////////////////////////