plotilla 1.0.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.
Files changed (155) hide show
  1. package/README.md +37 -11
  2. package/data/boundaries/world_countries.geojson +1 -1
  3. package/dist/colour/colour_scale.d.ts +55 -0
  4. package/dist/colour/colour_scale.js +80 -0
  5. package/dist/colour/palette.d.ts +176 -0
  6. package/dist/colour/palette.js +220 -0
  7. package/dist/fields/axis_fields.d.ts +56 -0
  8. package/dist/fields/axis_fields.js +46 -0
  9. package/dist/fields/colour_fields.d.ts +32 -0
  10. package/dist/fields/colour_fields.js +31 -0
  11. package/dist/fields/column_fields.d.ts +52 -0
  12. package/{src/fields/column_fields.ts → dist/fields/column_fields.js} +15 -29
  13. package/dist/fields/common_fields.d.ts +9 -0
  14. package/{src/fields/common_fields.ts → dist/fields/common_fields.js} +3 -6
  15. package/dist/fields/decide_plot_axes.d.ts +56 -0
  16. package/dist/fields/decide_plot_axes.js +71 -0
  17. package/dist/fields/marker_fields.d.ts +8 -0
  18. package/dist/fields/marker_fields.js +13 -0
  19. package/dist/fields/read_date_time.d.ts +85 -0
  20. package/dist/fields/read_date_time.js +199 -0
  21. package/dist/figure/check_axis_year_formats.d.ts +36 -0
  22. package/dist/figure/check_axis_year_formats.js +116 -0
  23. package/dist/figure/check_plot_category_limits.d.ts +128 -0
  24. package/dist/figure/check_plot_category_limits.js +284 -0
  25. package/dist/figure/plot_figure.d.ts +861 -0
  26. package/dist/figure/plot_figure.js +58 -0
  27. package/dist/figure/resolve_plot_figure.d.ts +28 -0
  28. package/dist/figure/resolve_plot_figure.js +41 -0
  29. package/dist/figure/validate_plot_figure.d.ts +50 -0
  30. package/dist/figure/validate_plot_figure.js +441 -0
  31. package/dist/map/assign_map_layer_hue_slots.d.ts +89 -0
  32. package/dist/map/assign_map_layer_hue_slots.js +146 -0
  33. package/dist/map/boundary_sets.d.ts +65 -0
  34. package/dist/map/boundary_sets.js +103 -0
  35. package/dist/map/build_world_outline_across_180.d.ts +21 -0
  36. package/dist/map/build_world_outline_across_180.js +23 -0
  37. package/dist/map/check_map_layers.d.ts +16 -0
  38. package/dist/map/check_map_layers.js +31 -0
  39. package/dist/map/fetch_region_outlines.d.ts +25 -0
  40. package/dist/map/fetch_region_outlines.js +39 -0
  41. package/dist/map/geojson.d.ts +150 -0
  42. package/dist/map/geojson.js +248 -0
  43. package/dist/map/join_region_rows.d.ts +40 -0
  44. package/dist/map/join_region_rows.js +45 -0
  45. package/dist/map/map_layers.d.ts +229 -0
  46. package/dist/map/map_layers.js +87 -0
  47. package/dist/model/find_panel_colour_scale.d.ts +25 -0
  48. package/dist/model/find_panel_colour_scale.js +27 -0
  49. package/dist/model/map_model.d.ts +30 -0
  50. package/dist/model/map_model.js +234 -0
  51. package/dist/model/panel_layout.d.ts +42 -0
  52. package/dist/model/panel_layout.js +154 -0
  53. package/dist/model/panel_model.d.ts +223 -0
  54. package/dist/model/panel_model.js +7 -0
  55. package/dist/model/plot_model.d.ts +28 -0
  56. package/dist/model/plot_model.js +431 -0
  57. package/dist/model/statistics.d.ts +83 -0
  58. package/dist/model/statistics.js +107 -0
  59. package/dist/plots/bar_plot.d.ts +46 -0
  60. package/dist/plots/bar_plot.js +30 -0
  61. package/dist/plots/box_plot.d.ts +30 -0
  62. package/dist/plots/box_plot.js +21 -0
  63. package/dist/plots/density_plot.d.ts +36 -0
  64. package/dist/plots/density_plot.js +23 -0
  65. package/dist/plots/heatmap_plot.d.ts +22 -0
  66. package/dist/plots/heatmap_plot.js +18 -0
  67. package/dist/plots/histogram_plot.d.ts +32 -0
  68. package/dist/plots/histogram_plot.js +24 -0
  69. package/dist/plots/line_plot.d.ts +44 -0
  70. package/dist/plots/line_plot.js +25 -0
  71. package/dist/plots/map_plot.d.ts +92 -0
  72. package/dist/plots/map_plot.js +35 -0
  73. package/dist/plots/pie_plot.d.ts +17 -0
  74. package/dist/plots/pie_plot.js +16 -0
  75. package/dist/plots/scatter_plot.d.ts +47 -0
  76. package/dist/plots/scatter_plot.js +27 -0
  77. package/dist/renderers/date_ticks.d.ts +37 -0
  78. package/dist/renderers/date_ticks.js +148 -0
  79. package/dist/renderers/echarts_map.d.ts +47 -0
  80. package/dist/renderers/echarts_map.js +492 -0
  81. package/dist/renderers/echarts_options.d.ts +30 -0
  82. package/dist/renderers/echarts_options.js +449 -0
  83. package/dist/renderers/echarts_pie_radius.d.ts +52 -0
  84. package/dist/renderers/echarts_pie_radius.js +158 -0
  85. package/dist/renderers/escape_html.d.ts +10 -0
  86. package/dist/renderers/escape_html.js +15 -0
  87. package/dist/renderers/line_colour_segments.d.ts +39 -0
  88. package/dist/renderers/line_colour_segments.js +41 -0
  89. package/dist/renderers/plotly_map.d.ts +48 -0
  90. package/dist/renderers/plotly_map.js +159 -0
  91. package/dist/renderers/plotly_options.d.ts +19 -0
  92. package/dist/renderers/plotly_options.js +345 -0
  93. package/dist/renderers/year_ticks.d.ts +27 -0
  94. package/dist/renderers/year_ticks.js +42 -0
  95. package/dist/table/check_column.d.ts +36 -0
  96. package/dist/table/check_column.js +46 -0
  97. package/dist/table/check_values_have_spread.d.ts +30 -0
  98. package/{src/table/check_values_have_spread.ts → dist/table/check_values_have_spread.js} +16 -17
  99. package/dist/table/compute_quantile.d.ts +16 -0
  100. package/dist/table/compute_quantile.js +23 -0
  101. package/dist/table/data_table.d.ts +59 -0
  102. package/dist/table/data_table.js +87 -0
  103. package/dist/table/density_bandwidth.d.ts +64 -0
  104. package/dist/table/density_bandwidth.js +88 -0
  105. package/dist/table/find_line_fit.d.ts +30 -0
  106. package/dist/table/find_line_fit.js +36 -0
  107. package/dist/table/get_number_range.d.ts +16 -0
  108. package/{src/table/get_number_range.ts → dist/table/get_number_range.js} +8 -8
  109. package/dist/table/group_rows.d.ts +40 -0
  110. package/dist/table/group_rows.js +67 -0
  111. package/dist/table/list_categories.d.ts +14 -0
  112. package/{src/table/list_categories.ts → dist/table/list_categories.js} +2 -3
  113. package/dist/table/read_number.d.ts +12 -0
  114. package/dist/table/read_number.js +14 -0
  115. package/package.json +28 -23
  116. package/src/colour/colour_scale.ts +0 -80
  117. package/src/colour/palette.ts +0 -220
  118. package/src/examples/example_figures.ts +0 -320
  119. package/src/fields/axis_fields.ts +0 -32
  120. package/src/fields/colour_fields.ts +0 -40
  121. package/src/fields/decide_plot_axes.ts +0 -77
  122. package/src/fields/marker_fields.ts +0 -16
  123. package/src/figure/plot_figure.ts +0 -67
  124. package/src/figure/resolve_plot_figure.ts +0 -47
  125. package/src/figure/validate_plot_figure.ts +0 -412
  126. package/src/map/boundary_sets.ts +0 -116
  127. package/src/map/check_map_layers.ts +0 -32
  128. package/src/map/fetch_region_outlines.ts +0 -48
  129. package/src/map/geojson.ts +0 -174
  130. package/src/map/map_layers.ts +0 -108
  131. package/src/model/check_axis_shows_years.ts +0 -58
  132. package/src/model/map_model.ts +0 -238
  133. package/src/model/panel_layout.ts +0 -171
  134. package/src/model/panel_model.ts +0 -85
  135. package/src/model/plot_model.ts +0 -347
  136. package/src/model/statistics.ts +0 -134
  137. package/src/plots/bar_plot.ts +0 -36
  138. package/src/plots/box_plot.ts +0 -26
  139. package/src/plots/density_plot.ts +0 -29
  140. package/src/plots/heatmap_plot.ts +0 -24
  141. package/src/plots/histogram_plot.ts +0 -29
  142. package/src/plots/line_plot.ts +0 -29
  143. package/src/plots/map_plot.ts +0 -46
  144. package/src/plots/pie_plot.ts +0 -23
  145. package/src/plots/scatter_plot.ts +0 -32
  146. package/src/renderers/echarts_map.ts +0 -194
  147. package/src/renderers/echarts_options.ts +0 -317
  148. package/src/renderers/plotly_map.ts +0 -170
  149. package/src/renderers/plotly_options.ts +0 -318
  150. package/src/table/check_column.ts +0 -34
  151. package/src/table/compute_quantile.ts +0 -23
  152. package/src/table/data_table.ts +0 -83
  153. package/src/table/density_bandwidth.ts +0 -94
  154. package/src/table/find_line_fit.ts +0 -44
  155. package/src/table/group_rows.ts +0 -71
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The figure: one shared table and one or more plots in a grid. This is
3
+ * the whole shape a caller sends, and the one list of plot types.
4
+ */
5
+ import { z } from "zod";
6
+ import { BAR_NUMERIC_COLUMNS, BAR_PLOT_SCHEMA } from "../plots/bar_plot.js";
7
+ import { BOX_NUMERIC_COLUMNS, BOX_PLOT_SCHEMA } from "../plots/box_plot.js";
8
+ import { DENSITY_NUMERIC_COLUMNS, DENSITY_PLOT_SCHEMA } from "../plots/density_plot.js";
9
+ import { HEATMAP_NUMERIC_COLUMNS, HEATMAP_PLOT_SCHEMA } from "../plots/heatmap_plot.js";
10
+ import { HISTOGRAM_NUMERIC_COLUMNS, HISTOGRAM_PLOT_SCHEMA } from "../plots/histogram_plot.js";
11
+ import { LINE_NUMERIC_COLUMNS, LINE_PLOT_SCHEMA } from "../plots/line_plot.js";
12
+ import { MAP_NUMERIC_COLUMNS, MAP_PLOT_SCHEMA } from "../plots/map_plot.js";
13
+ import { PIE_NUMERIC_COLUMNS, PIE_PLOT_SCHEMA } from "../plots/pie_plot.js";
14
+ import { SCATTER_NUMERIC_COLUMNS, SCATTER_PLOT_SCHEMA } from "../plots/scatter_plot.js";
15
+ import { DATA_TABLE_SCHEMA } from "../table/data_table.js";
16
+ /** Every plot type's schema, in the order the catalogue lists them. */
17
+ export const PLOT_SCHEMAS = [
18
+ LINE_PLOT_SCHEMA, SCATTER_PLOT_SCHEMA, BAR_PLOT_SCHEMA, BOX_PLOT_SCHEMA,
19
+ HISTOGRAM_PLOT_SCHEMA, DENSITY_PLOT_SCHEMA, HEATMAP_PLOT_SCHEMA, PIE_PLOT_SCHEMA, MAP_PLOT_SCHEMA,
20
+ ];
21
+ /** Any one plot, told apart by its type. */
22
+ export const PLOT_SCHEMA = z.discriminatedUnion("type", PLOT_SCHEMAS);
23
+ /**
24
+ * Find a plot type's schema.
25
+ *
26
+ * @param type - The plot type.
27
+ * @returns Its schema.
28
+ */
29
+ export function findPlotSchema(type) {
30
+ const schema = PLOT_SCHEMAS.find((candidate) => candidate.shape.type.value === type);
31
+ if (schema === undefined)
32
+ throw new Error(`No schema for plot type "${type}".`);
33
+ return schema;
34
+ }
35
+ /** Each plot type's column fields that must hold numbers. */
36
+ export const NUMERIC_COLUMNS = {
37
+ line: LINE_NUMERIC_COLUMNS, scatter: SCATTER_NUMERIC_COLUMNS, bar: BAR_NUMERIC_COLUMNS, box: BOX_NUMERIC_COLUMNS,
38
+ histogram: HISTOGRAM_NUMERIC_COLUMNS, density: DENSITY_NUMERIC_COLUMNS, heatmap: HEATMAP_NUMERIC_COLUMNS, pie: PIE_NUMERIC_COLUMNS, map: MAP_NUMERIC_COLUMNS,
39
+ };
40
+ /** The chart libraries a figure can be drawn with. */
41
+ export const RENDERERS = ["plotly", "echarts"];
42
+ /** Whether panels share an axis when the agent does not say: no. */
43
+ export const DEFAULT_IS_AXIS_SHARED = false;
44
+ /** The whole figure an agent sends: one table and its plots. Its JSON Schema is what an agent reads. */
45
+ export const PLOT_FIGURE_SCHEMA = z.strictObject({
46
+ data: DATA_TABLE_SCHEMA.describe("The table the plots draw from, unless a plot brings its own."),
47
+ plots: z.array(PLOT_SCHEMA).min(1).describe("The plots, filling the grid row by row."),
48
+ grid: z
49
+ .strictObject({ rows: z.number().int().min(1), columns: z.number().int().min(1) })
50
+ .optional()
51
+ .describe("Rows and columns of plots. Default: one column, a row per plot."),
52
+ title: z.string().min(1).optional().describe("A title over the whole figure."),
53
+ // The host shows the caption under the chart; neither library draws it, so plotilla passes it through.
54
+ caption: z.string().min(1).optional().describe("A line the host shows under the figure: its source, or what to notice."),
55
+ renderer: z.enum(RENDERERS).optional().describe("The library that draws the figure. Default: the caller's."),
56
+ is_x_axis_shared: z.boolean().default(DEFAULT_IS_AXIS_SHARED).describe("Link the x axes of the plots that have one (pies and maps have none), so zooming one zooms all. Needs two or more, of one kind (numbers, categories or dates) and one scale."),
57
+ is_y_axis_shared: z.boolean().default(DEFAULT_IS_AXIS_SHARED).describe("Link the y axes of the plots that have one (pies and maps have none), so zooming one zooms all. Needs two or more, of one kind (numbers, categories or dates) and one scale."),
58
+ });
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Resolve a figure the way a host shows one: check it, load the outlines its
3
+ * map layers name, and build its model once so any problem surfaces now
4
+ * rather than as a broken chart (renderers build their own).
5
+ */
6
+ import { type BoundarySetLoader } from "../map/boundary_sets.ts";
7
+ import { type GeoJsonFetcher } from "../map/fetch_region_outlines.ts";
8
+ import { type FigureSize } from "../model/panel_layout.ts";
9
+ import type { PlotFigure } from "./plot_figure.ts";
10
+ import { type PlotFigureLimits } from "./validate_plot_figure.ts";
11
+ /** A figure checked and with its outlines loaded, and what the agent should be told about it. */
12
+ export type ResolvedPlotFigure = {
13
+ figure: PlotFigure;
14
+ notes: string[];
15
+ };
16
+ /**
17
+ * Resolve a figure.
18
+ *
19
+ * @param input - The figure as the caller sent it. Never changed: outlines go into a copy.
20
+ * @param options - The caller's limits, the size it draws at in pixels, how to load a built-in outline set, and how to fetch outlines from an address.
21
+ * @returns The figure, valid, defaults and outlines filled in, and notes for the agent (table rows whose region name matched no outline, regions no row matched, rows that repeat a region a later row names, map layers with nothing to show, values a log scale cannot show).
22
+ */
23
+ export declare function resolvePlotFigure(input: unknown, options: {
24
+ limits: PlotFigureLimits;
25
+ size: FigureSize;
26
+ loadBoundarySet: BoundarySetLoader;
27
+ fetchGeoJson: GeoJsonFetcher;
28
+ }): Promise<ResolvedPlotFigure>;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Resolve a figure the way a host shows one: check it, load the outlines its
3
+ * map layers name, and build its model once so any problem surfaces now
4
+ * rather than as a broken chart (renderers build their own).
5
+ */
6
+ import { resolveBoundarySet } from "../map/boundary_sets.js";
7
+ import { fetchRegionOutlines } from "../map/fetch_region_outlines.js";
8
+ import { computePanelRectangles } from "../model/panel_layout.js";
9
+ import { buildFigureModel } from "../model/plot_model.js";
10
+ import { validatePlotFigure, validatePlotFigureBeforeOutlines } from "./validate_plot_figure.js";
11
+ /**
12
+ * Resolve a figure.
13
+ *
14
+ * @param input - The figure as the caller sent it. Never changed: outlines go into a copy.
15
+ * @param options - The caller's limits, the size it draws at in pixels, how to load a built-in outline set, and how to fetch outlines from an address.
16
+ * @returns The figure, valid, defaults and outlines filled in, and notes for the agent (table rows whose region name matched no outline, regions no row matched, rows that repeat a region a later row names, map layers with nothing to show, values a log scale cannot show).
17
+ */
18
+ export async function resolvePlotFigure(input, options) {
19
+ // Everything that needs no outlines first, so a figure that will be refused fetches nothing.
20
+ const figure = validatePlotFigureBeforeOutlines(input, { limits: options.limits });
21
+ const boundaryNotes = [];
22
+ for (const [index, plot] of figure.plots.entries()) {
23
+ if (plot.type !== "map")
24
+ continue;
25
+ for (const [layerIndex, layer] of plot.layers.entries()) {
26
+ if (layer.type !== "regions" || layer.boundaries === undefined)
27
+ continue;
28
+ const note = await resolveBoundarySet(layer, {
29
+ table: layer.data ?? plot.data ?? figure.data, where: `plots[${index}].layers[${layerIndex}]`, loadBoundarySet: options.loadBoundarySet,
30
+ });
31
+ if (note !== null)
32
+ boundaryNotes.push(note);
33
+ }
34
+ await fetchRegionOutlines(plot.layers, { where: `plots[${index}]`, fetchGeoJson: options.fetchGeoJson });
35
+ }
36
+ const resolved = validatePlotFigure(figure, { limits: options.limits });
37
+ const model = buildFigureModel(resolved);
38
+ // Laid out once at the host's size, so a figure that cannot fit is refused now, not when drawn.
39
+ computePanelRectangles(model, { size: options.size });
40
+ return { figure: resolved, notes: [...boundaryNotes, ...model.notes] };
41
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Check a figure before anything is drawn. The schema checks each field on
3
+ * its own; this adds what needs the table or the caller's limits. Every
4
+ * error names the field at fault, so a caller can fix the spec in one go.
5
+ */
6
+ import { z } from "zod";
7
+ import { type PlotFigure } from "./plot_figure.ts";
8
+ /** What the caller allows, from its own configuration. */
9
+ export type PlotFigureLimits = {
10
+ maximumPlots: number;
11
+ maximumRows: number;
12
+ maximumHistogramBins: number;
13
+ };
14
+ /**
15
+ * Validate a figure, filling in every default.
16
+ *
17
+ * @param input - The figure as the caller sent it.
18
+ * @param options - The caller's limits.
19
+ * @returns The figure, valid, with defaults filled in.
20
+ */
21
+ export declare function validatePlotFigure(input: unknown, options: {
22
+ limits: PlotFigureLimits;
23
+ }): PlotFigure;
24
+ /**
25
+ * Validate a figure as far as it can be before its outlines are loaded:
26
+ * everything but the outlines themselves, so a figure that will be refused
27
+ * makes the host fetch nothing.
28
+ *
29
+ * @param input - The figure as the caller sent it.
30
+ * @param options - The caller's limits.
31
+ * @returns The figure with defaults filled in, its outlines still to load.
32
+ */
33
+ export declare function validatePlotFigureBeforeOutlines(input: unknown, options: {
34
+ limits: PlotFigureLimits;
35
+ }): PlotFigure;
36
+ /**
37
+ * Check a figure's shape alone, filling in every default: what can be known
38
+ * before outlines are loaded and without the table's contents.
39
+ *
40
+ * @param input - The figure as the caller sent it.
41
+ * @returns A copy of the figure, with defaults filled in.
42
+ */
43
+ export declare function parsePlotFigure(input: unknown): PlotFigure;
44
+ /**
45
+ * Strip a field's optional and default wrappers, down to the schema it was defined with.
46
+ *
47
+ * @param schema - The field's schema as a plot holds it.
48
+ * @returns The schema inside.
49
+ */
50
+ export declare function unwrapField(schema: z.ZodType): z.ZodType;
@@ -0,0 +1,441 @@
1
+ /**
2
+ * Check a figure before anything is drawn. The schema checks each field on
3
+ * its own; this adds what needs the table or the caller's limits. Every
4
+ * error names the field at fault, so a caller can fix the spec in one go.
5
+ */
6
+ import { z } from "zod";
7
+ import { COLUMN_FIELD_SCHEMAS, listMarkColumns } from "../fields/column_fields.js";
8
+ import { checkMapLayers } from "../map/check_map_layers.js";
9
+ import { LAYER_NUMERIC_COLUMNS, MAP_LAYER_SCHEMAS } from "../map/map_layers.js";
10
+ import { checkColumn, checkColumnHasNoValues, checkColumnIsNumeric } from "../table/check_column.js";
11
+ import { checkRowBecomesMark, countTableRows, findColumn } from "../table/data_table.js";
12
+ import { checkValuesHaveSpread } from "../table/check_values_have_spread.js";
13
+ import { computeSilvermanBandwidth, findBandwidthFault } from "../table/density_bandwidth.js";
14
+ import { getNumberRange } from "../table/get_number_range.js";
15
+ import { findLineFit } from "../table/find_line_fit.js";
16
+ import { groupRows } from "../table/group_rows.js";
17
+ import { decideColourIsContinuous } from "../colour/colour_scale.js";
18
+ import { decidePlotAxes } from "../fields/decide_plot_axes.js";
19
+ import { findOffsetConflict, readDateColumn } from "../fields/read_date_time.js";
20
+ import { checkAxisYearFormats, checkSharedAxisYearFormats } from "./check_axis_year_formats.js";
21
+ import { checkMapLayerColourLimit, checkMapLayerHueSlots, checkPieSliceLimit, checkPlotCategoryLimits, checkRegionsColourLimit } from "./check_plot_category_limits.js";
22
+ import { findPlotSchema, NUMERIC_COLUMNS, PLOT_FIGURE_SCHEMA } from "./plot_figure.js";
23
+ /**
24
+ * Validate a figure, filling in every default.
25
+ *
26
+ * @param input - The figure as the caller sent it.
27
+ * @param options - The caller's limits.
28
+ * @returns The figure, valid, with defaults filled in.
29
+ */
30
+ export function validatePlotFigure(input, options) {
31
+ const figure = parsePlotFigure(input);
32
+ checkPlotFigure(figure, { limits: options.limits, areOutlinesLoaded: true });
33
+ return figure;
34
+ }
35
+ /**
36
+ * Validate a figure as far as it can be before its outlines are loaded:
37
+ * everything but the outlines themselves, so a figure that will be refused
38
+ * makes the host fetch nothing.
39
+ *
40
+ * @param input - The figure as the caller sent it.
41
+ * @param options - The caller's limits.
42
+ * @returns The figure with defaults filled in, its outlines still to load.
43
+ */
44
+ export function validatePlotFigureBeforeOutlines(input, options) {
45
+ const figure = parsePlotFigure(input);
46
+ checkPlotFigure(figure, { limits: options.limits, areOutlinesLoaded: false });
47
+ return figure;
48
+ }
49
+ /**
50
+ * Run every check that needs the table or the caller's limits.
51
+ *
52
+ * @param figure - The figure, through the schema.
53
+ * @param options - The caller's limits, and whether map outlines are loaded yet.
54
+ */
55
+ function checkPlotFigure(figure, options) {
56
+ const { limits } = options;
57
+ countTableRows(figure.data, { where: "data", maximumRows: limits.maximumRows });
58
+ if (figure.plots.length > limits.maximumPlots)
59
+ throw new Error(`plots: at most ${limits.maximumPlots}; got ${figure.plots.length}.`);
60
+ if (figure.grid !== undefined) {
61
+ const room = figure.grid.rows * figure.grid.columns;
62
+ if (room < figure.plots.length) {
63
+ throw new Error(`grid: ${figure.grid.rows} x ${figure.grid.columns} has room for ${room} plot${room === 1 ? "" : "s"}; got ${figure.plots.length}.`);
64
+ }
65
+ }
66
+ figure.plots.forEach((plot, index) => {
67
+ const where = `plots[${index}]`;
68
+ if (plot.data !== undefined)
69
+ countTableRows(plot.data, { where: `${where}.data`, maximumRows: limits.maximumRows });
70
+ checkPlot(plot, { table: plot.data ?? figure.data, where, limits, areOutlinesLoaded: options.areOutlinesLoaded });
71
+ });
72
+ if (figure.is_x_axis_shared)
73
+ checkSharedAxes(figure, { direction: "x" });
74
+ if (figure.is_y_axis_shared)
75
+ checkSharedAxes(figure, { direction: "y" });
76
+ }
77
+ /** How each axis kind is named to a caller. */
78
+ const AXIS_KIND_NAMES = { value: "numbers", category: "categories", time: "dates" };
79
+ /**
80
+ * Check that a shared axis can be linked: at least two plots have it, and
81
+ * all of one kind and scale, since Plotly links only axes of one type and a
82
+ * link to an axis no plot has means nothing. Judged by the rule the model
83
+ * builds its axes with, after every plot's columns are checked.
84
+ *
85
+ * @param figure - The figure, its plots checked.
86
+ * @param options - Which axis is shared.
87
+ */
88
+ function checkSharedAxes(figure, options) {
89
+ const field = `is_${options.direction}_axis_shared`;
90
+ const plotsWithAxis = figure.plots.flatMap((plot, index) => {
91
+ const axis = decidePlotAxes(plot, { table: plot.data ?? figure.data })[options.direction];
92
+ return axis === null ? [] : [{ axis, plot, where: `plots[${index}]` }];
93
+ });
94
+ const [first, ...others] = plotsWithAxis;
95
+ if (first === undefined || others.length === 0) {
96
+ throw new Error(`${field}: links the ${options.direction} axes of two or more plots, and ${first === undefined ? "no plot" : `only ${first.where}`} here has one ` +
97
+ "(pies and maps have none); leave it out.");
98
+ }
99
+ for (const other of others) {
100
+ if (other.axis.kind !== first.axis.kind) {
101
+ throw new Error(`${field}: shared ${options.direction} axes must hold one kind of value; ${first.where} has ${AXIS_KIND_NAMES[first.axis.kind]} ` +
102
+ `and ${other.where} ${AXIS_KIND_NAMES[other.axis.kind]}. Share only plots whose ${options.direction} axes match, or leave it out.`);
103
+ }
104
+ if (other.axis.scale !== first.axis.scale) {
105
+ throw new Error(`${field}: shared ${options.direction} axes must have one scale; ${first.where} is "${first.axis.scale}" ` +
106
+ `and ${other.where} "${other.axis.scale}". Give them the same scale, or leave it out.`);
107
+ }
108
+ }
109
+ if (first.axis.kind === "time")
110
+ checkSharedTimeAxisOffsets(plotsWithAxis, { field, table: figure.data });
111
+ checkSharedAxisYearFormats(figure, options);
112
+ }
113
+ /**
114
+ * Check that plots on one shared time axis carry one UTC offset: the axis
115
+ * prints each wall clock as written, and one axis shows one clock. Each
116
+ * column is read as the model reads it, so one offset per column holds
117
+ * already, and the columns are compared the way a column's values are.
118
+ *
119
+ * @param plotsWithAxis - The plots sharing the axis, each with its time axis and where it is.
120
+ * @param options - The sharing field, for the refusal, and the figure's table.
121
+ * @throws Error naming the field and two of the offsets when they differ.
122
+ */
123
+ function checkSharedTimeAxisOffsets(plotsWithAxis, options) {
124
+ const offsets = plotsWithAxis.map(({ axis, plot }) => {
125
+ const column = axis.plotField === "x" ? ("x" in plot ? plot.x : undefined) : ("y" in plot ? plot.y : undefined);
126
+ if (column === undefined)
127
+ throw new Error(`Expected a column for the time axis of a ${plot.type} plot; got none.`);
128
+ const values = (findColumn(plot.data ?? options.table, { column }) ?? []).filter((value) => typeof value === "string");
129
+ return readDateColumn(values, { column })[0]?.offset ?? null;
130
+ });
131
+ const conflict = findOffsetConflict(offsets);
132
+ if (conflict === null)
133
+ return;
134
+ const firstWhere = plotsWithAxis[conflict.first.index]?.where;
135
+ const secondWhere = plotsWithAxis[conflict.second.index]?.where;
136
+ throw new Error(`${options.field}: a shared time axis shows one clock, so its dates must carry one UTC offset; ${firstWhere} has ${conflict.first.name} ` +
137
+ `and ${secondWhere} ${conflict.second.name}. Share only plots whose dates carry the same offset, or leave it out.`);
138
+ }
139
+ /**
140
+ * Check a figure's shape alone, filling in every default: what can be known
141
+ * before outlines are loaded and without the table's contents.
142
+ *
143
+ * @param input - The figure as the caller sent it.
144
+ * @returns A copy of the figure, with defaults filled in.
145
+ */
146
+ export function parsePlotFigure(input) {
147
+ const parsed = PLOT_FIGURE_SCHEMA.safeParse(input);
148
+ if (!parsed.success)
149
+ throw new Error(formatIssues(parsed.error.issues));
150
+ return parsed.data;
151
+ }
152
+ /**
153
+ * Check one plot's columns, colour and limits against its table, and a map's layers against theirs.
154
+ *
155
+ * @param plot - The plot, already through the schema.
156
+ * @param options - Its table, where it is in the figure, the caller's limits, and whether map outlines are loaded yet.
157
+ */
158
+ function checkPlot(plot, options) {
159
+ const shape = findPlotSchema(plot.type).shape;
160
+ checkColumnFields(plot, { shape, numericColumns: NUMERIC_COLUMNS[plot.type], table: options.table, where: options.where });
161
+ if (plot.type === "map") {
162
+ let scaledLayerWhere = null;
163
+ plot.layers.forEach((layer, index) => {
164
+ const where = `${options.where}.layers[${index}]`;
165
+ if (layer.data !== undefined)
166
+ countTableRows(layer.data, { where: `${where}.data`, maximumRows: options.limits.maximumRows });
167
+ const layerShape = findLayerSchema(layer.type).shape;
168
+ const layerTable = layer.data ?? options.table;
169
+ checkColumnFields(layer, { shape: layerShape, numericColumns: LAYER_NUMERIC_COLUMNS[layer.type], table: layerTable, where });
170
+ // Points and lines are drawn where every coordinate is a number; which regions match an outline is known only once outlines load.
171
+ const coordinates = layer.type === "points" ? [layer.longitude, layer.latitude]
172
+ : layer.type === "lines" ? [layer.from_longitude, layer.from_latitude, layer.to_longitude, layer.to_latitude] : [];
173
+ const isDrawn = (row) => checkRowBecomesMark(layerTable, { row, present: [], numeric: coordinates });
174
+ const colourField = layer.type === "regions" ? "value" : "colour";
175
+ const isScaled = layer.type === "regions" || layer.type === "points" || layer.type === "lines"
176
+ ? checkColourValues(layer, { colourField, isAlwaysScaled: false, isDrawn, isYColumnEmpty: false, table: layerTable, where })
177
+ : false;
178
+ // A map shows one colour scale: a second layer colouring by a number has nowhere to show its own.
179
+ if (isScaled) {
180
+ if (scaledLayerWhere !== null) {
181
+ throw new Error(`${where}.${colourField}: a map can colour by one number at a time, and ${scaledLayerWhere} already does; colour this layer by category, or leave its colour out.`);
182
+ }
183
+ scaledLayerWhere = where;
184
+ }
185
+ if (layer.type === "points" || layer.type === "lines") {
186
+ checkMapLayerColourLimit(layer, { table: layerTable, isDrawn, where });
187
+ }
188
+ if (layer.type === "density" && layer.weight !== undefined)
189
+ checkWeightsAreNotNegative(layerTable, { column: layer.weight, where });
190
+ });
191
+ checkMapLayers(plot.layers, { isGlobe: plot.projection === "globe", areOutlinesLoaded: options.areOutlinesLoaded, where: options.where });
192
+ // Which rows a regions layer draws is known only once its outlines are loaded and checked.
193
+ if (options.areOutlinesLoaded) {
194
+ plot.layers.forEach((layer, index) => {
195
+ if (layer.type !== "regions")
196
+ return;
197
+ checkRegionsColourLimit(layer, { table: layer.data ?? options.table, where: `${options.where}.layers[${index}]` });
198
+ });
199
+ }
200
+ // After every layer's own colour check, so a layer with too many categories is refused for that first, with its advice.
201
+ checkMapLayerHueSlots(plot.layers, { table: options.table, where: options.where, areOutlinesLoaded: options.areOutlinesLoaded });
202
+ return;
203
+ }
204
+ if ("colour" in plot && plot.colour !== undefined && !("colour_scale" in shape)) {
205
+ const isContinuous = plot.colour_type === "continuous"
206
+ || (plot.colour_type === undefined && checkColumnIsNumeric(options.table, { column: plot.colour }));
207
+ if (isContinuous) {
208
+ throw new Error(`${options.where}.colour: a ${plot.type} plot cannot colour by a number, having no single value per mark. ` +
209
+ 'Use a column of categories, or colour_type "categorical".');
210
+ }
211
+ }
212
+ // One rule for which rows become marks, shared with the model, so a range is never judged on rows it will not draw.
213
+ const colour = "colour" in plot ? plot.colour : undefined;
214
+ const isColourCategorical = colour !== undefined && !decideColourIsContinuous(findColumn(options.table, { column: colour }) ?? [], { colourType: "colour_type" in plot ? plot.colour_type : undefined });
215
+ const markColumns = listMarkColumns(plot, { isColourCategorical });
216
+ const isDrawn = (row) => checkRowBecomesMark(options.table, { row, ...markColumns });
217
+ // With no y value no row becomes a mark, so no column can be judged on its drawn rows; the model notes the empty y column instead (#113).
218
+ const isYColumnEmpty = "y" in plot && plot.y !== undefined && checkColumnHasNoValues(options.table, { column: plot.y });
219
+ if (plot.type === "heatmap") {
220
+ checkColourValues(plot, { colourField: "value", isAlwaysScaled: true, isDrawn, isYColumnEmpty, table: options.table, where: options.where });
221
+ }
222
+ else if ("colour_scale" in shape) {
223
+ checkColourValues(plot, { colourField: "colour", isAlwaysScaled: false, isDrawn, isYColumnEmpty, table: options.table, where: options.where });
224
+ }
225
+ const rowCount = countTableRows(options.table, { where: options.where, maximumRows: options.limits.maximumRows });
226
+ // Refused here, naming the field, so drawing never meets more categories than it has colours, shapes or dashes for.
227
+ checkPlotCategoryLimits(plot, { table: options.table, rowCount, isColourCategorical, isDrawn, where: options.where });
228
+ checkAxisYearFormats(plot, { table: options.table, isDrawn, where: options.where });
229
+ // A histogram or density draws the rows with a number in x and, coloured by category, a category: with none there is nothing to draw.
230
+ if ((plot.type === "histogram" || plot.type === "density") && !Array.from({ length: rowCount }, (_, row) => row).some(isDrawn)) {
231
+ throw new Error(plot.colour === undefined
232
+ ? `${options.where}.x: "${plot.x}" has no numbers to draw.`
233
+ : `${options.where}.x: no row has both a number in "${plot.x}" and a "${plot.colour}" category, so there is nothing to draw.`);
234
+ }
235
+ // Each curve's bandwidth is the caller's or, with none, worked out from its spread; it is judged by the same rule the model draws with.
236
+ if (plot.type === "density") {
237
+ const xValues = findColumn(options.table, { column: plot.x }) ?? [];
238
+ const colourValues = plot.colour === undefined ? null : findColumn(options.table, { column: plot.colour });
239
+ const numbersByCategory = new Map();
240
+ for (let row = 0; row < rowCount; row += 1) {
241
+ if (!isDrawn(row))
242
+ continue;
243
+ const category = colourValues === null ? "" : String(colourValues[row]);
244
+ // A drawn row's x is a finite number, by the drawn-rows rule.
245
+ const numbers = numbersByCategory.get(category) ?? [];
246
+ numbers.push(xValues[row]);
247
+ numbersByCategory.set(category, numbers);
248
+ }
249
+ // Every curve spans the range of all drawn numbers, so they line up.
250
+ const drawnNumbers = Array.from(numbersByCategory.values()).flat();
251
+ const { minimum, maximum } = getNumberRange(drawnNumbers);
252
+ // A data range that overflows defeats every bandwidth, so it is the numbers in x that must change.
253
+ if (!Number.isFinite(maximum - minimum)) {
254
+ throw new Error(`${options.where}.x: the numbers in "${plot.x}" run from ${minimum} to ${maximum}, a range too wide for a number to hold, so no curve width can draw them.`);
255
+ }
256
+ const describeCategory = (category) => (colourValues === null ? "" : ` in "${plot.colour}" category "${category}"`);
257
+ for (const [category, numbers] of numbersByCategory) {
258
+ if (plot.bandwidth === undefined && !checkValuesHaveSpread(numbers)) {
259
+ throw new Error(colourValues === null
260
+ ? `${options.where}.x: a density needs numbers in "${plot.x}" whose spread is measurable (not all equal, nor so close together or far apart that it underflows or overflows) to work out its curve's width; set \`bandwidth\` to draw one anyway.`
261
+ : `${options.where}.x: a density needs numbers in "${plot.x}" whose spread is measurable (not all equal, nor so close together or far apart that it underflows or overflows) in each "${plot.colour}" category, and "${category}" has none; set \`bandwidth\` to draw one anyway.`);
262
+ }
263
+ const bandwidth = plot.bandwidth ?? computeSilvermanBandwidth(numbers);
264
+ const fault = findBandwidthFault({ count: numbers.length, minimum, maximum, bandwidth });
265
+ if (fault === null)
266
+ continue;
267
+ throw new Error(plot.bandwidth === undefined
268
+ ? `${options.where}.x: a density's curve width, worked out from the numbers in "${plot.x}"${describeCategory(category)} (Silverman's rule), is ${bandwidth}, which ${fault}; set \`bandwidth\` to draw one anyway.`
269
+ : `${options.where}.bandwidth: ${bandwidth}${describeCategory(category)} ${fault}; choose one nearer the spread of "${plot.x}".`);
270
+ }
271
+ }
272
+ // The model fits one trend line per series over its drawn rows, on a value x axis, by the same fit as here.
273
+ if (plot.type === "scatter" && plot.show_trend_line) {
274
+ // A fit runs over numbers; names or dates on x leave nothing to fit, so the field cannot apply.
275
+ const xKind = decidePlotAxes(plot, { table: options.table }).x?.kind;
276
+ if (xKind !== "value") {
277
+ throw new Error(`${options.where}.show_trend_line: a trend line needs numbers on x, and "${plot.x}" holds ${xKind === "time" ? "dates" : "text"}, drawn as ${xKind === "time" ? "a time axis" : "categories"}; ` +
278
+ "leave the trend line out, or plot it against a column of numbers.");
279
+ }
280
+ const xValues = findColumn(options.table, { column: plot.x }) ?? [];
281
+ const yValues = findColumn(options.table, { column: plot.y }) ?? [];
282
+ const { groups } = groupRows(options.table, { rowCount, colour: isColourCategorical ? colour : undefined, style: plot.marker_shape, isDrawn });
283
+ for (const group of groups) {
284
+ // A drawn row's x and y are finite numbers, by the drawn-rows rule.
285
+ if (findLineFit(group.rows.map((row) => ({ x: xValues[row], y: yValues[row] }))) !== null)
286
+ continue;
287
+ const seriesClause = group.name === "" ? "" : ` in each series, and "${group.name}" does not`;
288
+ throw new Error(`${options.where}.show_trend_line: a trend line is a least-squares fit, which needs drawn rows with at least two different numbers in "${plot.x}", ` +
289
+ `at a scale where the fit neither underflows nor overflows${seriesClause}; ` +
290
+ "leave the trend line out, or give it rows whose x values differ by an amount a line can be fitted to, with x and y small enough not to overflow.");
291
+ }
292
+ }
293
+ if (plot.type === "pie") {
294
+ checkPieSliceLimit(plot, { table: options.table, rowCount, where: options.where });
295
+ const negative = (findColumn(options.table, { column: plot.value }) ?? []).find((value) => typeof value === "number" && value < 0);
296
+ if (negative !== undefined)
297
+ throw new Error(`${options.where}.value: a slice is a share of the whole and cannot be negative; "${plot.value}" has ${negative}.`);
298
+ }
299
+ // A log scale spaces numbers; a column of text is drawn as categories, which it cannot space.
300
+ if ((plot.type === "line" || plot.type === "scatter") && plot.x_scale === "log" && !checkColumnIsNumeric(options.table, { column: plot.x })) {
301
+ throw new Error(`${options.where}.x_scale: "log" needs a column of numbers; "${plot.x}" holds text, drawn as categories.`);
302
+ }
303
+ // A log axis has nowhere to put zero or less: it needs a positive number to show.
304
+ // A histogram's or density's y is counts the model works out, never a column.
305
+ const scaledColumns = [
306
+ { field: "x_scale", scale: "x_scale" in plot ? plot.x_scale : undefined, column: "x" in plot ? plot.x : undefined },
307
+ { field: "y_scale", scale: "y_scale" in plot ? plot.y_scale : undefined, column: plot.type === "histogram" || plot.type === "density" ? undefined : ("y" in plot ? plot.y : undefined) },
308
+ ];
309
+ for (const { field, scale, column } of scaledColumns) {
310
+ if (scale !== "log" || column === undefined || isYColumnEmpty)
311
+ continue;
312
+ const hasPositive = (findColumn(options.table, { column }) ?? []).some((value, row) => isDrawn(row) && typeof value === "number" && value > 0);
313
+ if (!hasPositive)
314
+ throw new Error(`${options.where}.${field}: a log scale needs at least one positive number; "${column}" has none.`);
315
+ }
316
+ if (plot.type === "histogram" && plot.bins !== undefined && plot.bins > options.limits.maximumHistogramBins) {
317
+ throw new Error(`${options.where}.bins: at most ${options.limits.maximumHistogramBins}; got ${plot.bins}.`);
318
+ }
319
+ }
320
+ /**
321
+ * Check every field of a plot or map layer that names a column, and that
322
+ * colour_type comes with the column it describes.
323
+ *
324
+ * @param record - The plot or layer, through the schema.
325
+ * @param options - Its schema's fields, which columns must be numeric, its table, and where it is.
326
+ */
327
+ function checkColumnFields(record, options) {
328
+ const values = record;
329
+ for (const [field, schema] of Object.entries(options.shape)) {
330
+ const column = values[field];
331
+ if (!COLUMN_FIELD_SCHEMAS.has(unwrapField(schema)) || typeof column !== "string")
332
+ continue;
333
+ checkColumn(options.table, { column, field, where: options.where, isNumeric: options.numericColumns.includes(field) });
334
+ }
335
+ // A regions layer is coloured by its value; everything else by colour.
336
+ const colourField = values.type === "regions" ? "value" : "colour";
337
+ if (values.colour_type !== undefined && values[colourField] === undefined) {
338
+ throw new Error(`${options.where}.colour_type: only meaningful with \`${colourField}\`.`);
339
+ }
340
+ }
341
+ /**
342
+ * Check a colour that follows a scale has values the scale can show:
343
+ * colour_type "continuous" needs numbers, and the scale needs at least one
344
+ * number (a positive one, on a log scale). Without one the range is empty.
345
+ *
346
+ * @param record - The plot or layer, through the schema.
347
+ * @param options - Which field names the colouring column, whether it is always a scale (a heatmap's value), which rows become marks, whether the y column has no values (so none does, and the colour column is not at fault), its table, and where it is.
348
+ * @returns Whether the colour is a scale.
349
+ */
350
+ function checkColourValues(record, options) {
351
+ const values = record;
352
+ const column = values[options.colourField];
353
+ if (typeof column !== "string") {
354
+ if (values.colour_scale !== undefined)
355
+ throw new Error(`${options.where}.colour_scale: only meaningful with \`${options.colourField}\`, a column of numbers to colour by.`);
356
+ return false;
357
+ }
358
+ const field = `${options.where}.${options.colourField}`;
359
+ const isNumeric = checkColumnIsNumeric(options.table, { column });
360
+ if (values.colour_type === "continuous" && !isNumeric) {
361
+ throw new Error(`${field}: colour_type "continuous" needs a column of numbers; "${column}" holds text.`);
362
+ }
363
+ const isScaled = options.isAlwaysScaled || values.colour_type === "continuous" || (values.colour_type === undefined && isNumeric);
364
+ if (!isScaled) {
365
+ if (values.colour_scale !== undefined) {
366
+ throw new Error(`${options.where}.colour_scale: "${column}" is coloured by category, which a colour scale does not apply to; colour by a column of numbers, or leave colour_scale out.`);
367
+ }
368
+ return false;
369
+ }
370
+ const isLog = values.colour_scale === "log";
371
+ const isUsable = (value) => typeof value === "number" && Number.isFinite(value) && (!isLog || value > 0);
372
+ // Judged on the rows that become marks: the model builds the range from those alone.
373
+ if (!options.isYColumnEmpty && !(findColumn(options.table, { column }) ?? []).some((value, row) => options.isDrawn(row) && isUsable(value))) {
374
+ throw new Error(isLog
375
+ ? `${field}: a log colour scale needs at least one positive number; "${column}" has none.`
376
+ : `${field}: a colour scale needs at least one number; "${column}" has none.`);
377
+ }
378
+ return true;
379
+ }
380
+ /**
381
+ * Check a density layer's weights: each says how much a place counts, so none may be negative.
382
+ *
383
+ * @param table - The layer's table.
384
+ * @param options - The weight column, and where the layer is.
385
+ */
386
+ function checkWeightsAreNotNegative(table, options) {
387
+ const negative = (findColumn(table, { column: options.column }) ?? []).find((value) => typeof value === "number" && value < 0);
388
+ if (negative !== undefined) {
389
+ throw new Error(`${options.where}.weight: weights say how much each place counts and cannot be negative; "${options.column}" has ${negative}.`);
390
+ }
391
+ }
392
+ /**
393
+ * Find a map layer type's schema.
394
+ *
395
+ * @param type - The layer type.
396
+ * @returns Its schema.
397
+ */
398
+ function findLayerSchema(type) {
399
+ const schema = MAP_LAYER_SCHEMAS.find((candidate) => candidate.shape.type.value === type);
400
+ if (schema === undefined)
401
+ throw new Error(`No schema for map layer type "${type}".`);
402
+ return schema;
403
+ }
404
+ /**
405
+ * Strip a field's optional and default wrappers, down to the schema it was defined with.
406
+ *
407
+ * @param schema - The field's schema as a plot holds it.
408
+ * @returns The schema inside.
409
+ */
410
+ export function unwrapField(schema) {
411
+ let inner = schema;
412
+ while (inner instanceof z.ZodOptional || inner instanceof z.ZodDefault)
413
+ inner = inner.unwrap();
414
+ return inner;
415
+ }
416
+ /**
417
+ * Turn the schema's complaints into one message, each line naming its field.
418
+ *
419
+ * @param issues - The schema's issues.
420
+ * @returns The message.
421
+ */
422
+ function formatIssues(issues) {
423
+ return issues
424
+ .flatMap((issue) => {
425
+ const where = formatPath(issue.path);
426
+ if (issue.code === "unrecognized_keys") {
427
+ return issue.keys.map((key) => `${where === "" ? key : `${where}.${key}`}: not a field of this plot or figure.`);
428
+ }
429
+ return [`${where === "" ? "figure" : where}: ${issue.message}`];
430
+ })
431
+ .join("\n");
432
+ }
433
+ /**
434
+ * Write a path the way a caller would point at the field: plots[0].bins.
435
+ *
436
+ * @param path - The path, as the schema reports it.
437
+ * @returns The written path.
438
+ */
439
+ function formatPath(path) {
440
+ return path.map((part, index) => (typeof part === "number" ? `[${part}]` : `${index === 0 ? "" : "."}${String(part)}`)).join("");
441
+ }