plotilla 0.2.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -11
- package/data/boundaries/world_countries.geojson +1 -1
- package/dist/colour/colour_scale.d.ts +55 -0
- package/dist/colour/colour_scale.js +80 -0
- package/dist/colour/palette.d.ts +176 -0
- package/dist/colour/palette.js +220 -0
- package/dist/fields/axis_fields.d.ts +56 -0
- package/dist/fields/axis_fields.js +46 -0
- package/dist/fields/colour_fields.d.ts +32 -0
- package/dist/fields/colour_fields.js +31 -0
- package/dist/fields/column_fields.d.ts +52 -0
- package/{src/fields/column_fields.ts → dist/fields/column_fields.js} +15 -29
- package/dist/fields/common_fields.d.ts +9 -0
- package/{src/fields/common_fields.ts → dist/fields/common_fields.js} +3 -6
- package/dist/fields/decide_plot_axes.d.ts +56 -0
- package/dist/fields/decide_plot_axes.js +71 -0
- package/dist/fields/marker_fields.d.ts +8 -0
- package/dist/fields/marker_fields.js +13 -0
- package/dist/fields/read_date_time.d.ts +85 -0
- package/dist/fields/read_date_time.js +199 -0
- package/dist/figure/check_axis_year_formats.d.ts +36 -0
- package/dist/figure/check_axis_year_formats.js +116 -0
- package/dist/figure/check_plot_category_limits.d.ts +128 -0
- package/dist/figure/check_plot_category_limits.js +284 -0
- package/dist/figure/plot_figure.d.ts +861 -0
- package/dist/figure/plot_figure.js +58 -0
- package/dist/figure/resolve_plot_figure.d.ts +28 -0
- package/dist/figure/resolve_plot_figure.js +41 -0
- package/dist/figure/validate_plot_figure.d.ts +50 -0
- package/dist/figure/validate_plot_figure.js +441 -0
- package/dist/map/assign_map_layer_hue_slots.d.ts +89 -0
- package/dist/map/assign_map_layer_hue_slots.js +146 -0
- package/dist/map/boundary_sets.d.ts +65 -0
- package/dist/map/boundary_sets.js +103 -0
- package/dist/map/build_world_outline_across_180.d.ts +21 -0
- package/dist/map/build_world_outline_across_180.js +23 -0
- package/dist/map/check_map_layers.d.ts +16 -0
- package/dist/map/check_map_layers.js +31 -0
- package/dist/map/fetch_region_outlines.d.ts +25 -0
- package/dist/map/fetch_region_outlines.js +39 -0
- package/dist/map/geojson.d.ts +150 -0
- package/dist/map/geojson.js +248 -0
- package/dist/map/join_region_rows.d.ts +40 -0
- package/dist/map/join_region_rows.js +45 -0
- package/dist/map/map_layers.d.ts +229 -0
- package/dist/map/map_layers.js +87 -0
- package/dist/model/find_panel_colour_scale.d.ts +25 -0
- package/dist/model/find_panel_colour_scale.js +27 -0
- package/dist/model/map_model.d.ts +30 -0
- package/dist/model/map_model.js +234 -0
- package/dist/model/panel_layout.d.ts +42 -0
- package/dist/model/panel_layout.js +154 -0
- package/dist/model/panel_model.d.ts +223 -0
- package/dist/model/panel_model.js +7 -0
- package/dist/model/plot_model.d.ts +28 -0
- package/dist/model/plot_model.js +431 -0
- package/dist/model/statistics.d.ts +83 -0
- package/dist/model/statistics.js +107 -0
- package/dist/plots/bar_plot.d.ts +46 -0
- package/dist/plots/bar_plot.js +30 -0
- package/dist/plots/box_plot.d.ts +30 -0
- package/dist/plots/box_plot.js +21 -0
- package/dist/plots/density_plot.d.ts +36 -0
- package/dist/plots/density_plot.js +23 -0
- package/dist/plots/heatmap_plot.d.ts +22 -0
- package/dist/plots/heatmap_plot.js +18 -0
- package/dist/plots/histogram_plot.d.ts +32 -0
- package/dist/plots/histogram_plot.js +24 -0
- package/dist/plots/line_plot.d.ts +44 -0
- package/dist/plots/line_plot.js +25 -0
- package/dist/plots/map_plot.d.ts +92 -0
- package/dist/plots/map_plot.js +35 -0
- package/dist/plots/pie_plot.d.ts +17 -0
- package/dist/plots/pie_plot.js +16 -0
- package/dist/plots/scatter_plot.d.ts +47 -0
- package/dist/plots/scatter_plot.js +27 -0
- package/dist/renderers/date_ticks.d.ts +37 -0
- package/dist/renderers/date_ticks.js +148 -0
- package/dist/renderers/echarts_map.d.ts +47 -0
- package/dist/renderers/echarts_map.js +492 -0
- package/dist/renderers/echarts_options.d.ts +30 -0
- package/dist/renderers/echarts_options.js +449 -0
- package/dist/renderers/echarts_pie_radius.d.ts +52 -0
- package/dist/renderers/echarts_pie_radius.js +158 -0
- package/dist/renderers/escape_html.d.ts +10 -0
- package/dist/renderers/escape_html.js +15 -0
- package/dist/renderers/line_colour_segments.d.ts +39 -0
- package/dist/renderers/line_colour_segments.js +41 -0
- package/dist/renderers/plotly_map.d.ts +48 -0
- package/dist/renderers/plotly_map.js +159 -0
- package/dist/renderers/plotly_options.d.ts +19 -0
- package/dist/renderers/plotly_options.js +345 -0
- package/dist/renderers/year_ticks.d.ts +27 -0
- package/dist/renderers/year_ticks.js +42 -0
- package/dist/table/check_column.d.ts +36 -0
- package/dist/table/check_column.js +46 -0
- package/dist/table/check_values_have_spread.d.ts +30 -0
- package/{src/table/check_values_have_spread.ts → dist/table/check_values_have_spread.js} +16 -17
- package/dist/table/compute_quantile.d.ts +16 -0
- package/dist/table/compute_quantile.js +23 -0
- package/dist/table/data_table.d.ts +59 -0
- package/dist/table/data_table.js +87 -0
- package/dist/table/density_bandwidth.d.ts +64 -0
- package/dist/table/density_bandwidth.js +88 -0
- package/dist/table/find_line_fit.d.ts +30 -0
- package/dist/table/find_line_fit.js +36 -0
- package/dist/table/get_number_range.d.ts +16 -0
- package/{src/table/get_number_range.ts → dist/table/get_number_range.js} +8 -8
- package/dist/table/group_rows.d.ts +40 -0
- package/dist/table/group_rows.js +67 -0
- package/dist/table/list_categories.d.ts +14 -0
- package/{src/table/list_categories.ts → dist/table/list_categories.js} +2 -3
- package/dist/table/read_number.d.ts +12 -0
- package/dist/table/read_number.js +14 -0
- package/package.json +30 -25
- package/src/colour/colour_scale.ts +0 -80
- package/src/colour/palette.ts +0 -220
- package/src/examples/example_figures.ts +0 -320
- package/src/fields/axis_fields.ts +0 -32
- package/src/fields/colour_fields.ts +0 -40
- package/src/fields/decide_plot_axes.ts +0 -77
- package/src/fields/marker_fields.ts +0 -16
- package/src/figure/plot_figure.ts +0 -67
- package/src/figure/resolve_plot_figure.ts +0 -47
- package/src/figure/validate_plot_figure.ts +0 -412
- package/src/map/boundary_sets.ts +0 -116
- package/src/map/check_map_layers.ts +0 -32
- package/src/map/fetch_region_outlines.ts +0 -48
- package/src/map/geojson.ts +0 -174
- package/src/map/map_layers.ts +0 -108
- package/src/model/check_axis_shows_years.ts +0 -58
- package/src/model/map_model.ts +0 -238
- package/src/model/panel_layout.ts +0 -171
- package/src/model/panel_model.ts +0 -85
- package/src/model/plot_model.ts +0 -347
- package/src/model/statistics.ts +0 -134
- package/src/plots/bar_plot.ts +0 -36
- package/src/plots/box_plot.ts +0 -26
- package/src/plots/density_plot.ts +0 -29
- package/src/plots/heatmap_plot.ts +0 -24
- package/src/plots/histogram_plot.ts +0 -29
- package/src/plots/line_plot.ts +0 -29
- package/src/plots/map_plot.ts +0 -46
- package/src/plots/pie_plot.ts +0 -23
- package/src/plots/scatter_plot.ts +0 -32
- package/src/renderers/echarts_map.ts +0 -194
- package/src/renderers/echarts_options.ts +0 -317
- package/src/renderers/plotly_map.ts +0 -170
- package/src/renderers/plotly_options.ts +0 -318
- package/src/table/check_column.ts +0 -34
- package/src/table/compute_quantile.ts +0 -23
- package/src/table/data_table.ts +0 -83
- package/src/table/density_bandwidth.ts +0 -94
- package/src/table/find_line_fit.ts +0 -44
- package/src/table/group_rows.ts +0 -71
|
@@ -1,318 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Chart model → Plotly figure ({ data, layout }). Plain JSON, passed to
|
|
3
|
-
* `Plotly.newPlot` on the page.
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import { LINE_WIDTH, MARKER_SIZE, SEQUENTIAL_COLOURS, PLOT_THEMES, type LineDash, type MarkerShape, type PlotTheme } from "../colour/palette";
|
|
7
|
-
import { formatValue } from "../colour/colour_scale";
|
|
8
|
-
import { buildColourBar, buildPlotlyMap } from "./plotly_map";
|
|
9
|
-
import type { AxisModel, FigureModel, SeriesModel, Value } from "../model/panel_model";
|
|
10
|
-
import { computePanelRectangles, MINIMUM_SERIES_FOR_LEGEND, type FigureSize } from "../model/panel_layout";
|
|
11
|
-
|
|
12
|
-
const PLOTLY_DASHES: Record<LineDash, string> = { solid: "solid", dashed: "dash", dotted: "dot", dash_dot: "dashdot" };
|
|
13
|
-
const PLOTLY_SYMBOLS: Record<MarkerShape, string> = {
|
|
14
|
-
circle: "circle", square: "square", triangle: "triangle-up", diamond: "diamond", cross: "cross", star: "star",
|
|
15
|
-
};
|
|
16
|
-
const FILLED_AREA_ALPHA_HEXADECIMAL = "40";
|
|
17
|
-
const PANEL_TITLE_FONT_PIXELS = 13;
|
|
18
|
-
/** How far above its panel a panel title sits, in pixels. */
|
|
19
|
-
const PANEL_TITLE_OFFSET_PIXELS = 4;
|
|
20
|
-
/** A 2px surface gap between neighbouring fills (dataviz skill). */
|
|
21
|
-
const FILL_GAP_PIXELS = 2;
|
|
22
|
-
/**
|
|
23
|
-
* One panel's stacked bars: they share an offset group, so they occupy one
|
|
24
|
-
* slot, and each bar starts where the panel's earlier bars ended for its
|
|
25
|
-
* category. `ends` is keyed by category and sign.
|
|
26
|
-
*/
|
|
27
|
-
type BarStack = { offsetGroup: string; ends: Map<string, number> };
|
|
28
|
-
|
|
29
|
-
/** A heatmap cell's hover: where it is, then its real value (the colour may follow a log or rank); no trace name box. */
|
|
30
|
-
const HEATMAP_HOVER_TEMPLATE = "%{x}, %{y}: %{text}<extra></extra>";
|
|
31
|
-
|
|
32
|
-
/** Offset groups of stacked panels are named this, then the panel's index. */
|
|
33
|
-
const STACK_OFFSET_GROUP_PREFIX = "stack-";
|
|
34
|
-
const POSITIVE_STACK_SUFFIX = "+";
|
|
35
|
-
const NEGATIVE_STACK_SUFFIX = "-";
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* A line coloured by a number, for Plotly, which gives a line one colour: one
|
|
39
|
-
* segment per pair of points, coloured by the pair's mean value and grouped
|
|
40
|
-
* by colour step into one trace per step (segments split by gaps), so a line
|
|
41
|
-
* of any length takes at most as many line traces as the palette has steps.
|
|
42
|
-
* One markers trace carries the colour bar and the hover; its markers show
|
|
43
|
-
* only when the series asks for them.
|
|
44
|
-
*
|
|
45
|
-
* @param series - The line, coloured by a number.
|
|
46
|
-
* @param options - Its axes, the panel's colour range and Plotly colour scale, whether this trace shows the scale, and its colour bar.
|
|
47
|
-
* @returns The segment traces, then the markers trace.
|
|
48
|
-
*/
|
|
49
|
-
function buildColouredLineTraces(
|
|
50
|
-
series: Extract<SeriesModel, { mark: "line" }>,
|
|
51
|
-
options: { axes: Record<string, string>; colourRange: { minimum: number; maximum: number }; colourScale: [number, string][] | null; showScale: boolean; colourBar: Record<string, unknown> },
|
|
52
|
-
): Record<string, unknown>[] {
|
|
53
|
-
const span = options.colourRange.maximum - options.colourRange.minimum;
|
|
54
|
-
const segmentsByStep = new Map<number, { x: (Value | null)[]; y: (number | null)[] }>();
|
|
55
|
-
series.points.slice(1).forEach((point, index) => {
|
|
56
|
-
const previous = series.points[index];
|
|
57
|
-
if (previous === undefined) return;
|
|
58
|
-
const values = [previous.colourValue, point.colourValue].filter((value): value is number => value !== null);
|
|
59
|
-
if (values.length === 0) return;
|
|
60
|
-
const mean = values.reduce((sum, value) => sum + value, 0) / values.length;
|
|
61
|
-
const fraction = span === 0 ? 0 : (mean - options.colourRange.minimum) / span;
|
|
62
|
-
const step = Math.round(Math.min(1, Math.max(0, fraction)) * (SEQUENTIAL_COLOURS.length - 1));
|
|
63
|
-
const segments = segmentsByStep.get(step) ?? { x: [], y: [] };
|
|
64
|
-
segments.x.push(previous.x, point.x, null);
|
|
65
|
-
segments.y.push(previous.y, point.y, null);
|
|
66
|
-
segmentsByStep.set(step, segments);
|
|
67
|
-
});
|
|
68
|
-
const lines = [...segmentsByStep.entries()].sort(([first], [second]) => first - second).map(([step, segments]) => ({
|
|
69
|
-
type: "scatter", ...options.axes, name: series.name, mode: "lines", x: segments.x, y: segments.y,
|
|
70
|
-
line: { color: SEQUENTIAL_COLOURS[step], width: LINE_WIDTH, dash: PLOTLY_DASHES[series.dash] },
|
|
71
|
-
hoverinfo: "skip", showlegend: false,
|
|
72
|
-
}));
|
|
73
|
-
const markers = {
|
|
74
|
-
type: "scatter", ...options.axes, name: series.name, mode: "markers",
|
|
75
|
-
x: series.points.map((point) => point.x), y: series.points.map((point) => point.y),
|
|
76
|
-
marker: {
|
|
77
|
-
// Plotly still draws a marker of size 0, so markers the series does not ask for are made transparent.
|
|
78
|
-
size: MARKER_SIZE, opacity: series.showMarkers ? 1 : 0, color: series.points.map((point) => point.colourValue),
|
|
79
|
-
colorscale: options.colourScale, showscale: options.showScale, colorbar: options.colourBar,
|
|
80
|
-
cmin: options.colourRange.minimum, cmax: options.colourRange.maximum,
|
|
81
|
-
},
|
|
82
|
-
};
|
|
83
|
-
return [...lines, markers];
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/** The figure title's top, and the legend's top under a title, from the figure's top edge, in pixels (inside the header panel_layout reserves). */
|
|
87
|
-
const TITLE_TOP_PIXELS = 12;
|
|
88
|
-
const LEGEND_TOP_BELOW_TITLE_PIXELS = 42;
|
|
89
|
-
|
|
90
|
-
function convertColourScale(colours: readonly string[]): [number, string][] {
|
|
91
|
-
return colours.map((colour, index) => [index / (colours.length - 1), colour]);
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
function buildAxisLayout(axis: AxisModel, options: { theme: PlotTheme; domain: [number, number]; anchor: string }): Record<string, unknown> {
|
|
95
|
-
const ink = PLOT_THEMES[options.theme];
|
|
96
|
-
return {
|
|
97
|
-
domain: options.domain,
|
|
98
|
-
anchor: options.anchor,
|
|
99
|
-
type: axis.kind === "value" ? (axis.scale === "log" ? "log" : "linear") : axis.kind === "time" ? "date" : "category",
|
|
100
|
-
...(axis.kind === "category" ? { categoryorder: "array", categoryarray: axis.categories } : {}),
|
|
101
|
-
// No automargin: it would shrink every panel to fit one axis's labels; panel_layout has left room for them.
|
|
102
|
-
title: { text: axis.label, font: { color: ink.textSecondary } },
|
|
103
|
-
automargin: false,
|
|
104
|
-
// Years print as 2005, not 2k. Other numbers print 1450 as 1,450: Plotly
|
|
105
|
-
// leaves a 4-digit whole number unseparated unless separatethousands is set.
|
|
106
|
-
...(axis.kind === "value" ? (axis.isYearLike ? { tickformat: "d" } : { separatethousands: true }) : {}),
|
|
107
|
-
tickfont: { color: ink.textSecondary },
|
|
108
|
-
gridcolor: ink.gridLine,
|
|
109
|
-
linecolor: ink.gridLine,
|
|
110
|
-
zeroline: false,
|
|
111
|
-
...(axis.kind === "value" ? { rangemode: axis.includesZero ? "tozero" : "normal" } : {}),
|
|
112
|
-
};
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
function buildTraces(series: SeriesModel, options: { theme: PlotTheme; xAxis: string; yAxis: string; colourScale: [number, string][] | null; colourRange: { minimum: number; maximum: number } | null; showScale: boolean; colourBar: Record<string, unknown>; barStack: BarStack | null }): Record<string, unknown>[] {
|
|
116
|
-
const ink = PLOT_THEMES[options.theme];
|
|
117
|
-
const axes = { xaxis: options.xAxis, yaxis: options.yAxis };
|
|
118
|
-
switch (series.mark) {
|
|
119
|
-
case "line":
|
|
120
|
-
if (series.colour === null && options.colourRange !== null) {
|
|
121
|
-
return buildColouredLineTraces(series, { axes, colourRange: options.colourRange, colourScale: options.colourScale, showScale: options.showScale, colourBar: options.colourBar });
|
|
122
|
-
}
|
|
123
|
-
return [{
|
|
124
|
-
type: "scatter", ...axes, name: series.name, mode: series.showMarkers ? "lines+markers" : "lines",
|
|
125
|
-
x: series.points.map((point) => point.x), y: series.points.map((point) => point.y),
|
|
126
|
-
line: { color: series.colour ?? ink.textSecondary, width: LINE_WIDTH, dash: PLOTLY_DASHES[series.dash] },
|
|
127
|
-
marker: series.colour === null
|
|
128
|
-
? { size: MARKER_SIZE, color: series.points.map((point) => point.colourValue), colorscale: options.colourScale, showscale: options.showScale, colorbar: options.colourBar }
|
|
129
|
-
: { size: MARKER_SIZE, color: series.colour },
|
|
130
|
-
...(series.isFilled ? { fill: "tozeroy", fillcolor: `${series.colour}${FILLED_AREA_ALPHA_HEXADECIMAL}` } : {}),
|
|
131
|
-
}];
|
|
132
|
-
case "scatter": {
|
|
133
|
-
const isContinuous = series.colour === null;
|
|
134
|
-
return [{
|
|
135
|
-
type: "scatter", ...axes, name: series.name, mode: "markers",
|
|
136
|
-
x: series.points.map((point) => point.x), y: series.points.map((point) => point.y),
|
|
137
|
-
marker: {
|
|
138
|
-
symbol: PLOTLY_SYMBOLS[series.shape],
|
|
139
|
-
size: series.points.map((point) => point.sizePixels),
|
|
140
|
-
line: { color: ink.surface, width: FILL_GAP_PIXELS / 2 },
|
|
141
|
-
...(isContinuous
|
|
142
|
-
? { color: series.points.map((point) => point.colourValue), colorscale: options.colourScale, showscale: options.showScale, colorbar: options.colourBar }
|
|
143
|
-
: { color: series.colour }),
|
|
144
|
-
},
|
|
145
|
-
}];
|
|
146
|
-
}
|
|
147
|
-
case "bar": {
|
|
148
|
-
const categories = series.points.map((point) => point.x);
|
|
149
|
-
const values = series.points.map((point) => point.y);
|
|
150
|
-
const isContinuous = series.colour === null;
|
|
151
|
-
const stack = options.barStack;
|
|
152
|
-
const stacking = stack === null ? {} : {
|
|
153
|
-
offsetgroup: stack.offsetGroup,
|
|
154
|
-
base: series.points.map((point) => {
|
|
155
|
-
// Positive and negative bars stack away from zero separately, as Plotly's own stacking does.
|
|
156
|
-
const key = `${point.x}${point.y < 0 ? NEGATIVE_STACK_SUFFIX : POSITIVE_STACK_SUFFIX}`;
|
|
157
|
-
const start = stack.ends.get(key) ?? 0;
|
|
158
|
-
stack.ends.set(key, start + point.y);
|
|
159
|
-
return start;
|
|
160
|
-
}),
|
|
161
|
-
};
|
|
162
|
-
return [{
|
|
163
|
-
type: "bar", ...axes, name: series.name, orientation: series.isHorizontal ? "h" : "v", ...stacking,
|
|
164
|
-
x: series.isHorizontal ? values : categories, y: series.isHorizontal ? categories : values,
|
|
165
|
-
marker: {
|
|
166
|
-
line: { color: ink.surface, width: FILL_GAP_PIXELS / 2 },
|
|
167
|
-
...(isContinuous
|
|
168
|
-
? { color: series.points.map((point) => point.colourValue), colorscale: options.colourScale, showscale: options.showScale, colorbar: options.colourBar }
|
|
169
|
-
: { color: series.colour }),
|
|
170
|
-
},
|
|
171
|
-
}];
|
|
172
|
-
}
|
|
173
|
-
case "box":
|
|
174
|
-
// Precomputed statistics, so Plotly draws the same box as ECharts.
|
|
175
|
-
return [{
|
|
176
|
-
type: "box", ...axes, name: series.name, x: series.boxes.map((box) => box.category),
|
|
177
|
-
q1: series.boxes.map((box) => box.summary.firstQuartile), median: series.boxes.map((box) => box.summary.median),
|
|
178
|
-
q3: series.boxes.map((box) => box.summary.thirdQuartile), lowerfence: series.boxes.map((box) => box.summary.lowerWhisker),
|
|
179
|
-
upperfence: series.boxes.map((box) => box.summary.upperWhisker),
|
|
180
|
-
line: { color: series.colour, width: LINE_WIDTH }, fillcolor: "rgba(0,0,0,0)",
|
|
181
|
-
}, {
|
|
182
|
-
type: "scatter", ...axes, name: series.name, mode: "markers", showlegend: false, marker: { color: series.colour, size: MARKER_SIZE },
|
|
183
|
-
x: series.boxes.flatMap((box) => (series.showMarkers ? box.values : box.summary.outliers).map(() => box.category)),
|
|
184
|
-
y: series.boxes.flatMap((box) => series.showMarkers ? box.values : box.summary.outliers),
|
|
185
|
-
}];
|
|
186
|
-
case "histogram":
|
|
187
|
-
return [{
|
|
188
|
-
type: "bar", ...axes, name: series.name,
|
|
189
|
-
x: series.bins.map((bin) => (bin.start + bin.end) / 2), y: series.bins.map((bin) => bin.height),
|
|
190
|
-
width: series.bins.map((bin) => bin.end - bin.start),
|
|
191
|
-
marker: { color: series.colour, line: { color: ink.surface, width: FILL_GAP_PIXELS / 2 } },
|
|
192
|
-
}];
|
|
193
|
-
case "heatmap": {
|
|
194
|
-
const xs = [...new Set(series.cells.map((cell) => cell.x))];
|
|
195
|
-
const ys = [...new Set(series.cells.map((cell) => cell.y))];
|
|
196
|
-
// Nested maps (not a joined string key) so no x or y value can collide with another; the first cell at a position wins, as a scan would.
|
|
197
|
-
const cellsByYThenX = new Map<string, Map<string, (typeof series.cells)[number]>>();
|
|
198
|
-
for (const cell of series.cells) {
|
|
199
|
-
const row = cellsByYThenX.get(cell.y) ?? new Map<string, (typeof series.cells)[number]>();
|
|
200
|
-
cellsByYThenX.set(cell.y, row);
|
|
201
|
-
if (!row.has(cell.x)) row.set(cell.x, cell);
|
|
202
|
-
}
|
|
203
|
-
const findCell = (x: string, y: string): (typeof series.cells)[number] | undefined => cellsByYThenX.get(y)?.get(x);
|
|
204
|
-
// Colour follows the colour value; the hover shows the real one.
|
|
205
|
-
const z = ys.map((y) => xs.map((x) => findCell(x, y)?.colourValue ?? null));
|
|
206
|
-
const text = ys.map((y) => xs.map((x) => {
|
|
207
|
-
const cell = findCell(x, y);
|
|
208
|
-
return cell === undefined ? null : formatValue(cell.value);
|
|
209
|
-
}));
|
|
210
|
-
return [{
|
|
211
|
-
type: "heatmap", ...axes, name: series.name, x: xs, y: ys, z, text, hovertemplate: HEATMAP_HOVER_TEMPLATE,
|
|
212
|
-
colorscale: options.colourScale, showscale: options.showScale, colorbar: options.colourBar,
|
|
213
|
-
}];
|
|
214
|
-
}
|
|
215
|
-
case "pie":
|
|
216
|
-
return [];
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
/**
|
|
221
|
-
* Build the Plotly figure for a chart model.
|
|
222
|
-
*
|
|
223
|
-
* @param model - The chart model.
|
|
224
|
-
* @param options - The size the host draws the figure at, in pixels; build again when it changes.
|
|
225
|
-
* @returns `{ data, layout }` for Plotly.newPlot.
|
|
226
|
-
*/
|
|
227
|
-
export function buildPlotlyFigure(model: FigureModel, options: { size: FigureSize }): { data: Record<string, unknown>[]; layout: Record<string, unknown> } {
|
|
228
|
-
const ink = PLOT_THEMES[model.theme];
|
|
229
|
-
const { size } = options;
|
|
230
|
-
const rectangles = computePanelRectangles(model, { size });
|
|
231
|
-
const data: Record<string, unknown>[] = [];
|
|
232
|
-
const layout: Record<string, unknown> = {
|
|
233
|
-
paper_bgcolor: ink.surface,
|
|
234
|
-
plot_bgcolor: ink.surface,
|
|
235
|
-
font: { color: ink.textPrimary },
|
|
236
|
-
...(model.title === null ? {} : {
|
|
237
|
-
title: { text: model.title, font: { color: ink.textPrimary }, yref: "container", y: 1 - TITLE_TOP_PIXELS / size.height, yanchor: "top" },
|
|
238
|
-
}),
|
|
239
|
-
// In the header the layout reserves above the panels, below the title.
|
|
240
|
-
legend: {
|
|
241
|
-
orientation: "h", x: 0.5, xanchor: "center", yanchor: "top", font: { color: ink.textSecondary },
|
|
242
|
-
y: 1 - (model.title === null ? TITLE_TOP_PIXELS : LEGEND_TOP_BELOW_TITLE_PIXELS) / size.height,
|
|
243
|
-
},
|
|
244
|
-
// No margins: the panel layout has already left room for every label, in pixels.
|
|
245
|
-
margin: { l: 0, r: 0, t: 0, b: 0 },
|
|
246
|
-
// Plotly's barmode covers every panel, so stacking is done per panel instead (see BarStack).
|
|
247
|
-
barmode: "group",
|
|
248
|
-
hovermode: "closest",
|
|
249
|
-
annotations: [] as Record<string, unknown>[],
|
|
250
|
-
};
|
|
251
|
-
// One legend entry per series name, however many panels it appears in.
|
|
252
|
-
const namesInLegend = new Set<string>();
|
|
253
|
-
// A shared axis links to the first panel that has one, as ECharts links every axis it has: never to a pie's or map's missing axis.
|
|
254
|
-
const firstAxisReferences: { x: string | null; y: string | null } = { x: null, y: null };
|
|
255
|
-
const linkAxis = (direction: "x" | "y", options: { isShared: boolean; reference: string }): Record<string, string> => {
|
|
256
|
-
const first = firstAxisReferences[direction];
|
|
257
|
-
if (first === null) {
|
|
258
|
-
firstAxisReferences[direction] = options.reference;
|
|
259
|
-
return {};
|
|
260
|
-
}
|
|
261
|
-
return options.isShared ? { matches: first } : {};
|
|
262
|
-
};
|
|
263
|
-
|
|
264
|
-
model.panels.forEach((panel, panelIndex) => {
|
|
265
|
-
const rectangle = rectangles[panelIndex];
|
|
266
|
-
if (rectangle === undefined) throw new Error(`Expected a rectangle for panel ${panelIndex}; got none.`);
|
|
267
|
-
const xDomain: [number, number] = [rectangle.left, rectangle.left + rectangle.width];
|
|
268
|
-
const yDomain: [number, number] = [1 - rectangle.top - rectangle.height, 1 - rectangle.top];
|
|
269
|
-
if (panel.title !== null) {
|
|
270
|
-
(layout.annotations as Record<string, unknown>[]).push({
|
|
271
|
-
text: panel.title, showarrow: false, xref: "paper", yref: "paper", x: rectangle.left, xanchor: "left",
|
|
272
|
-
y: yDomain[1] + PANEL_TITLE_OFFSET_PIXELS / size.height, yanchor: "bottom", font: { color: ink.textPrimary, size: PANEL_TITLE_FONT_PIXELS },
|
|
273
|
-
});
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
const pie = panel.series.find((series) => series.mark === "pie");
|
|
277
|
-
if (pie !== undefined && pie.mark === "pie") {
|
|
278
|
-
data.push({
|
|
279
|
-
type: "pie", name: pie.name, hole: pie.hole, domain: { x: xDomain, y: yDomain },
|
|
280
|
-
labels: pie.slices.map((slice) => slice.label), values: pie.slices.map((slice) => slice.value),
|
|
281
|
-
marker: { colors: pie.slices.map((slice) => slice.colour), line: { color: ink.surface, width: FILL_GAP_PIXELS } },
|
|
282
|
-
textfont: { color: ink.textPrimary },
|
|
283
|
-
});
|
|
284
|
-
return;
|
|
285
|
-
}
|
|
286
|
-
const suffix = panelIndex === 0 ? "" : String(panelIndex + 1);
|
|
287
|
-
if (panel.map !== undefined) {
|
|
288
|
-
const colourScale = panel.colourScale === null ? null : convertColourScale(panel.colourScale.colours);
|
|
289
|
-
const built = buildPlotlyMap({ ...panel, map: panel.map }, { suffix, domain: { x: xDomain, y: yDomain }, theme: model.theme, colourScale });
|
|
290
|
-
layout[built.layoutKey] = built.layoutValue;
|
|
291
|
-
for (const trace of built.traces) {
|
|
292
|
-
const name = String(trace.name ?? "");
|
|
293
|
-
const isFirst = trace.showlegend !== false && model.legendNames.includes(name) && !namesInLegend.has(name);
|
|
294
|
-
if (isFirst) namesInLegend.add(name);
|
|
295
|
-
data.push({ ...trace, legendgroup: name, showlegend: isFirst });
|
|
296
|
-
}
|
|
297
|
-
return;
|
|
298
|
-
}
|
|
299
|
-
const xRef = `x${suffix}`;
|
|
300
|
-
const yRef = `y${suffix}`;
|
|
301
|
-
if (panel.xAxis !== null) layout[`xaxis${suffix}`] = { ...buildAxisLayout(panel.xAxis, { theme: model.theme, domain: xDomain, anchor: yRef }), ...linkAxis("x", { isShared: model.isXAxisShared, reference: xRef }) };
|
|
302
|
-
if (panel.yAxis !== null) layout[`yaxis${suffix}`] = { ...buildAxisLayout(panel.yAxis, { theme: model.theme, domain: yDomain, anchor: xRef }), ...linkAxis("y", { isShared: model.isYAxisShared, reference: yRef }) };
|
|
303
|
-
const colourScale = panel.colourScale === null ? null : convertColourScale(panel.colourScale.colours);
|
|
304
|
-
const isStacked = panel.series.some((series) => series.mark === "bar" && series.isStacked);
|
|
305
|
-
const barStack: BarStack | null = isStacked ? { offsetGroup: `${STACK_OFFSET_GROUP_PREFIX}${panelIndex}`, ends: new Map() } : null;
|
|
306
|
-
panel.series.forEach((series, seriesIndex) => {
|
|
307
|
-
const colourRange = panel.colourScale === null ? null : { minimum: panel.colourScale.minimum, maximum: panel.colourScale.maximum };
|
|
308
|
-
const traceOptions = { theme: model.theme, xAxis: xRef, yAxis: yRef, colourScale, colourRange, showScale: seriesIndex === 0, colourBar: buildColourBar(panel.colourScale, { domain: { x: xDomain, y: yDomain } }), barStack };
|
|
309
|
-
for (const trace of buildTraces(series, traceOptions)) {
|
|
310
|
-
const isFirst = series.name !== "" && !namesInLegend.has(series.name) && trace.showlegend !== false;
|
|
311
|
-
if (isFirst) namesInLegend.add(series.name);
|
|
312
|
-
data.push({ ...trace, legendgroup: series.name, showlegend: isFirst });
|
|
313
|
-
}
|
|
314
|
-
});
|
|
315
|
-
});
|
|
316
|
-
layout.showlegend = model.legendNames.length >= MINIMUM_SERIES_FOR_LEGEND;
|
|
317
|
-
return { data, layout };
|
|
318
|
-
}
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import { findColumn, type DataTable } from "./data_table";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Check that a field names a column of the table, and that the column holds
|
|
5
|
-
* only numbers when the field needs them.
|
|
6
|
-
*
|
|
7
|
-
* @param table - The table the plot draws from.
|
|
8
|
-
* @param options - The column named, the field naming it and where, for errors, and whether it must be numeric.
|
|
9
|
-
*/
|
|
10
|
-
export function checkColumn(table: DataTable, options: { column: string; field: string; where: string; isNumeric: boolean }): void {
|
|
11
|
-
const values = findColumn(table, { column: options.column });
|
|
12
|
-
if (values === null) {
|
|
13
|
-
throw new Error(
|
|
14
|
-
`${options.where}.${options.field}: names column "${options.column}", which is not in the table. ` +
|
|
15
|
-
`Columns: ${Object.keys(table).join(", ")}.`,
|
|
16
|
-
);
|
|
17
|
-
}
|
|
18
|
-
if (options.isNumeric && values.some((value) => value !== null && typeof value !== "number")) {
|
|
19
|
-
throw new Error(`${options.where}.${options.field}: column "${options.column}" must be numeric.`);
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Whether a column holds numbers (nulls aside), so colour by it is continuous.
|
|
25
|
-
*
|
|
26
|
-
* @param table - The table.
|
|
27
|
-
* @param options - The column.
|
|
28
|
-
* @returns True when every non-null value is a number.
|
|
29
|
-
*/
|
|
30
|
-
export function checkColumnIsNumeric(table: DataTable, options: { column: string }): boolean {
|
|
31
|
-
const values = findColumn(table, { column: options.column });
|
|
32
|
-
if (values === null) throw new Error(`Column "${options.column}" is not in the table.`);
|
|
33
|
-
return values.every((value) => value === null || typeof value === "number");
|
|
34
|
-
}
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Quantiles of a column's numbers. Below both validation and the model,
|
|
3
|
-
* because Silverman's bandwidth (which both judge) needs the interquartile
|
|
4
|
-
* range, and a box plot needs the quartiles.
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* The q-quantile of sorted values, by linear interpolation (the "type 7"
|
|
9
|
-
* definition used by R, NumPy and Excel).
|
|
10
|
-
*
|
|
11
|
-
* @param sorted - Values in ascending order; at least one.
|
|
12
|
-
* @param options - Which quantile, from 0 to 1.
|
|
13
|
-
* @returns The quantile.
|
|
14
|
-
*/
|
|
15
|
-
export function computeQuantile(sorted: number[], options: { quantile: number }): number {
|
|
16
|
-
if (sorted.length === 0) throw new Error("A quantile needs at least one value; got none.");
|
|
17
|
-
const position = (sorted.length - 1) * options.quantile;
|
|
18
|
-
const lower = Math.floor(position);
|
|
19
|
-
const upper = Math.ceil(position);
|
|
20
|
-
const lowerValue = sorted[lower] as number;
|
|
21
|
-
const upperValue = sorted[upper] as number;
|
|
22
|
-
return lowerValue + (upperValue - lowerValue) * (position - lower);
|
|
23
|
-
}
|
package/src/table/data_table.ts
DELETED
|
@@ -1,83 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The table every plot draws from: named columns of equal length. Columnar
|
|
3
|
-
* rather than a list of rows because it is about half the tokens for an
|
|
4
|
-
* agent to send.
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
import { z } from "zod";
|
|
8
|
-
|
|
9
|
-
/** One cell: a number, a string, or null for a missing value. */
|
|
10
|
-
export const CELL_SCHEMA = z.union([z.number(), z.string(), z.null()]);
|
|
11
|
-
|
|
12
|
-
/** The table as an agent sends it. */
|
|
13
|
-
export const DATA_TABLE_SCHEMA = z
|
|
14
|
-
.record(z.string().min(1), z.array(CELL_SCHEMA))
|
|
15
|
-
.describe("A table: { column_name: [values] }, every column the same length.");
|
|
16
|
-
|
|
17
|
-
/** A table: named columns of equal length. */
|
|
18
|
-
export type DataTable = z.infer<typeof DATA_TABLE_SCHEMA>;
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* Count a table's rows, checking it has columns, they are all the same
|
|
22
|
-
* length, and there are not too many rows to draw.
|
|
23
|
-
*
|
|
24
|
-
* @param table - The table.
|
|
25
|
-
* @param options - Where the table is in the figure, for errors, and the most rows allowed.
|
|
26
|
-
* @returns The row count.
|
|
27
|
-
*/
|
|
28
|
-
export function countTableRows(table: DataTable, options: { where: string; maximumRows: number }): number {
|
|
29
|
-
const columns = Object.entries(table);
|
|
30
|
-
const first = columns[0];
|
|
31
|
-
if (first === undefined) throw new Error(`${options.where}: the table has no columns.`);
|
|
32
|
-
const [firstName, firstValues] = first;
|
|
33
|
-
for (const [name, values] of columns) {
|
|
34
|
-
if (values.length !== firstValues.length) {
|
|
35
|
-
throw new Error(`${options.where}: every column must have the same length; "${firstName}" has ${firstValues.length}, "${name}" has ${values.length}.`);
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
if (firstValues.length > options.maximumRows) {
|
|
39
|
-
throw new Error(`${options.where}: at most ${options.maximumRows} rows; got ${firstValues.length}. Summarise the data first.`);
|
|
40
|
-
}
|
|
41
|
-
return firstValues.length;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Find a column by name, among the table's own columns only: a table is a
|
|
46
|
-
* plain object, so a name like "constructor" or "toString" would otherwise
|
|
47
|
-
* find Object's member, not a column.
|
|
48
|
-
*
|
|
49
|
-
* @param table - The table.
|
|
50
|
-
* @param options - The column's name.
|
|
51
|
-
* @returns Its values, or null when the table has no such column.
|
|
52
|
-
*/
|
|
53
|
-
export function findColumn(table: DataTable, options: { column: string }): DataTable[string] | null {
|
|
54
|
-
return Object.hasOwn(table, options.column) ? (table[options.column] ?? null) : null;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/**
|
|
58
|
-
* Find a column a field may leave out.
|
|
59
|
-
*
|
|
60
|
-
* @param table - The table.
|
|
61
|
-
* @param options - The column's name, or undefined when the field is not set.
|
|
62
|
-
* @returns Its values, or null when the field is not set or the table has no such column.
|
|
63
|
-
*/
|
|
64
|
-
export function findOptionalColumn(table: DataTable, options: { column: string | undefined }): DataTable[string] | null {
|
|
65
|
-
return options.column === undefined ? null : findColumn(table, { column: options.column });
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* Whether a row becomes a mark: every listed column present, and every
|
|
70
|
-
* numeric one a finite number.
|
|
71
|
-
*
|
|
72
|
-
* @param table - The table.
|
|
73
|
-
* @param options - The row, and the columns it needs (from listMarkColumns).
|
|
74
|
-
* @returns True when the row is drawn.
|
|
75
|
-
*/
|
|
76
|
-
export function checkRowBecomesMark(table: DataTable, options: { row: number; present: readonly string[]; numeric: readonly string[] }): boolean {
|
|
77
|
-
return options.present.every((column) => (findColumn(table, { column })?.[options.row] ?? null) !== null)
|
|
78
|
-
&& options.numeric.every((column) => {
|
|
79
|
-
const value = findColumn(table, { column })?.[options.row];
|
|
80
|
-
return typeof value === "number" && Number.isFinite(value);
|
|
81
|
-
});
|
|
82
|
-
}
|
|
83
|
-
|
|
@@ -1,94 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* A density's bandwidth and the arithmetic that turns it into a curve: its
|
|
3
|
-
* height and how far past the data it reaches. Validation (which refuses a
|
|
4
|
-
* density that cannot be drawn) and the model (which draws it) both use
|
|
5
|
-
* these, so a bandwidth validation accepts is one whose curve is finite.
|
|
6
|
-
* It lives below both, since validation may not read the model.
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
import { checkValuesHaveSpread, computeStandardDeviation } from "./check_values_have_spread";
|
|
10
|
-
import { computeQuantile } from "./compute_quantile";
|
|
11
|
-
|
|
12
|
-
/** How far past the data a density curve extends, in bandwidths. */
|
|
13
|
-
export const DENSITY_TAIL_BANDWIDTHS = 3;
|
|
14
|
-
|
|
15
|
-
/** √(2π): a Gaussian kernel of width h peaks at 1 / (h · √(2π)). */
|
|
16
|
-
const SQUARE_ROOT_OF_TWO_PI = Math.sqrt(2 * Math.PI);
|
|
17
|
-
|
|
18
|
-
/** Silverman's rule of thumb: h = 0.9 · min(σ, IQR/1.34) · n^(-1/5). */
|
|
19
|
-
const SILVERMAN_FACTOR = 0.9;
|
|
20
|
-
const IQR_TO_SIGMA = 1.34;
|
|
21
|
-
const SILVERMAN_EXPONENT = -1 / 5;
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Silverman's rule-of-thumb bandwidth for a Gaussian kernel. It can still be
|
|
25
|
-
* 0 or too small to draw with (a middle half a subnormal distance apart);
|
|
26
|
-
* findBandwidthFault decides that.
|
|
27
|
-
*
|
|
28
|
-
* @param values - The values; at least two, with a spread checkValuesHaveSpread accepts.
|
|
29
|
-
* @returns The bandwidth.
|
|
30
|
-
* @throws Error when the values have no spread checkValuesHaveSpread accepts.
|
|
31
|
-
*/
|
|
32
|
-
export function computeSilvermanBandwidth(values: number[]): number {
|
|
33
|
-
if (!checkValuesHaveSpread(values)) {
|
|
34
|
-
throw new Error("A density needs values whose spread is measurable: not all equal, nor so close together or far apart that it underflows or overflows. Set `bandwidth` to draw one anyway.");
|
|
35
|
-
}
|
|
36
|
-
const standardDeviation = computeStandardDeviation(values);
|
|
37
|
-
const sorted = [...values].sort((first, second) => first - second);
|
|
38
|
-
const interquartileRange = computeQuantile(sorted, { quantile: 0.75 }) - computeQuantile(sorted, { quantile: 0.25 });
|
|
39
|
-
const spread = interquartileRange > 0 ? Math.min(standardDeviation, interquartileRange / IQR_TO_SIGMA) : standardDeviation;
|
|
40
|
-
return SILVERMAN_FACTOR * spread * values.length ** SILVERMAN_EXPONENT;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* The factor that scales a curve's summed kernels to a density, 1 / (n · h · √(2π)).
|
|
45
|
-
* The curve is n times this high where every value sits at one point.
|
|
46
|
-
*
|
|
47
|
-
* @param options - How many values, and the bandwidth.
|
|
48
|
-
* @returns The factor; Infinity or NaN when n · h · √(2π) underflows.
|
|
49
|
-
*/
|
|
50
|
-
export function computeDensityNormaliser(options: { count: number; bandwidth: number }): number {
|
|
51
|
-
return 1 / (options.count * options.bandwidth * SQUARE_ROOT_OF_TWO_PI);
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* The x range a density curve is evaluated over: the data's range,
|
|
56
|
-
* extended by DENSITY_TAIL_BANDWIDTHS bandwidths each side.
|
|
57
|
-
*
|
|
58
|
-
* @param options - The data's smallest and largest value, and the bandwidth.
|
|
59
|
-
* @returns The curve's first and last x.
|
|
60
|
-
*/
|
|
61
|
-
export function computeDensityRange(options: { minimum: number; maximum: number; bandwidth: number }): { minimum: number; maximum: number } {
|
|
62
|
-
const tail = DENSITY_TAIL_BANDWIDTHS * options.bandwidth;
|
|
63
|
-
return { minimum: options.minimum - tail, maximum: options.maximum + tail };
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
* What stops a bandwidth from drawing a finite curve, if anything. The curve
|
|
68
|
-
* is finite when the bandwidth and its normaliser are finite and above zero,
|
|
69
|
-
* its highest possible y is finite, and its range is finite with a width
|
|
70
|
-
* above zero: the model evaluates the curve with exactly these numbers. A
|
|
71
|
-
* fault is named by its cause: a bandwidth too narrow (the height overflows)
|
|
72
|
-
* or too wide (the height falls to zero, or the range overflows).
|
|
73
|
-
*
|
|
74
|
-
* @param options - How many values the curve sums, the data's smallest and
|
|
75
|
-
* largest value (shared by every curve in the plot), and the bandwidth.
|
|
76
|
-
* @returns What fails, phrased to follow the bandwidth ("is not a finite number above zero"),
|
|
77
|
-
* or null when the curve is finite.
|
|
78
|
-
*/
|
|
79
|
-
export function findBandwidthFault(options: { count: number; minimum: number; maximum: number; bandwidth: number }): string | null {
|
|
80
|
-
const isFinitePositive = (value: number): boolean => Number.isFinite(value) && value > 0;
|
|
81
|
-
if (!isFinitePositive(options.bandwidth)) return "is not a finite number above zero";
|
|
82
|
-
// A y is the normaliser times a sum of n kernels, each at most 1, so it is at most n times the normaliser: 1 / (bandwidth · √(2π)).
|
|
83
|
-
// The normaliser overflows only when the bandwidth is tiny, and underflows to 0 only when n · bandwidth · √(2π) overflows, a bandwidth that is huge.
|
|
84
|
-
const normaliser = computeDensityNormaliser({ count: options.count, bandwidth: options.bandwidth });
|
|
85
|
-
if (!Number.isFinite(normaliser) || !Number.isFinite(options.count * normaliser)) {
|
|
86
|
-
return "is so narrow that the curve's height, up to 1 / (bandwidth · √(2π)), overflows";
|
|
87
|
-
}
|
|
88
|
-
if (normaliser === 0) return "is so wide that the curve's height, 1 / (n · bandwidth · √(2π)), falls to zero";
|
|
89
|
-
const range = computeDensityRange(options);
|
|
90
|
-
if (!Number.isFinite(range.minimum) || !Number.isFinite(range.maximum) || !isFinitePositive(range.maximum - range.minimum)) {
|
|
91
|
-
return `is so wide, or the numbers so large, that the curve's range, ${DENSITY_TAIL_BANDWIDTHS} bandwidths past the numbers, is not a finite width above zero`;
|
|
92
|
-
}
|
|
93
|
-
return null;
|
|
94
|
-
}
|
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The least-squares line through points, or null when arithmetic cannot give
|
|
3
|
-
* one. A scatter's trend line is this fit, so validation (which refuses a
|
|
4
|
-
* trend line that cannot be drawn) and the model (which draws it) ask the
|
|
5
|
-
* same function. Exact equality of x is not the only failure: x values so
|
|
6
|
-
* close together that their squared deviations underflow, or so far apart
|
|
7
|
-
* (or with y so large) that a sum overflows, give a slope, intercept or end
|
|
8
|
-
* that is not a finite number, and a line through those cannot be drawn.
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
import { getNumberRange } from "./get_number_range";
|
|
12
|
-
|
|
13
|
-
/** A point of the fit: an x and a y. */
|
|
14
|
-
export type FitPoint = { x: number; y: number };
|
|
15
|
-
|
|
16
|
-
/** A fitted line, and where it starts and ends over the points' x range. */
|
|
17
|
-
export type LineFit = { slope: number; intercept: number; start: FitPoint; end: FitPoint };
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* Fit a least-squares line.
|
|
21
|
-
*
|
|
22
|
-
* @param points - The points, each x and y a finite number.
|
|
23
|
-
* @returns The slope and intercept, and the line's ends at the smallest and
|
|
24
|
-
* largest x; null when any of these is not a finite number (fewer than two
|
|
25
|
-
* points, x values that do not vary measurably, or a sum that overflows).
|
|
26
|
-
*/
|
|
27
|
-
export function findLineFit(points: readonly FitPoint[]): LineFit | null {
|
|
28
|
-
const count = points.length;
|
|
29
|
-
const meanX = points.reduce((sum, point) => sum + point.x, 0) / count;
|
|
30
|
-
const meanY = points.reduce((sum, point) => sum + point.y, 0) / count;
|
|
31
|
-
let covariance = 0;
|
|
32
|
-
let varianceX = 0;
|
|
33
|
-
for (const point of points) {
|
|
34
|
-
covariance += (point.x - meanX) * (point.y - meanY);
|
|
35
|
-
varianceX += (point.x - meanX) ** 2;
|
|
36
|
-
}
|
|
37
|
-
const slope = covariance / varianceX;
|
|
38
|
-
const intercept = meanY - slope * meanX;
|
|
39
|
-
const xs = points.map((point) => point.x);
|
|
40
|
-
const { minimum: low, maximum: high } = getNumberRange(xs);
|
|
41
|
-
const start = { x: low, y: slope * low + intercept };
|
|
42
|
-
const end = { x: high, y: slope * high + intercept };
|
|
43
|
-
return [slope, intercept, start.x, start.y, end.x, end.y].every(Number.isFinite) ? { slope, intercept, start, end } : null;
|
|
44
|
-
}
|