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.
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 +30 -25
  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,59 @@
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
+ import { z } from "zod";
7
+ /** One cell: a number, a string, or null for a missing value; a blank string is read as null. */
8
+ export declare const CELL_SCHEMA: z.ZodUnion<readonly [z.ZodNumber, z.ZodPipe<z.ZodString, z.ZodTransform<string | null, string>>, z.ZodNull]>;
9
+ /** The table as an agent sends it. */
10
+ export declare const DATA_TABLE_SCHEMA: z.ZodRecord<z.ZodString, z.ZodArray<z.ZodUnion<readonly [z.ZodNumber, z.ZodPipe<z.ZodString, z.ZodTransform<string | null, string>>, z.ZodNull]>>>;
11
+ /** A table: named columns of equal length. */
12
+ export type DataTable = z.infer<typeof DATA_TABLE_SCHEMA>;
13
+ /**
14
+ * Count a table's rows, checking it has columns, they are all the same
15
+ * length, and there are not too many rows to draw.
16
+ *
17
+ * @param table - The table.
18
+ * @param options - Where the table is in the figure, for errors, and the most rows allowed.
19
+ * @returns The row count.
20
+ */
21
+ export declare function countTableRows(table: DataTable, options: {
22
+ where: string;
23
+ maximumRows: number;
24
+ }): number;
25
+ /**
26
+ * Find a column by name, among the table's own columns only: a table is a
27
+ * plain object, so a name like "constructor" or "toString" would otherwise
28
+ * find Object's member, not a column.
29
+ *
30
+ * @param table - The table.
31
+ * @param options - The column's name.
32
+ * @returns Its values, or null when the table has no such column.
33
+ */
34
+ export declare function findColumn(table: DataTable, options: {
35
+ column: string;
36
+ }): DataTable[string] | null;
37
+ /**
38
+ * Find a column a field may leave out.
39
+ *
40
+ * @param table - The table.
41
+ * @param options - The column's name, or undefined when the field is not set.
42
+ * @returns Its values, or null when the field is not set or the table has no such column.
43
+ */
44
+ export declare function findOptionalColumn(table: DataTable, options: {
45
+ column: string | undefined;
46
+ }): DataTable[string] | null;
47
+ /**
48
+ * Whether a row becomes a mark: every listed column present, and every
49
+ * numeric one a finite number.
50
+ *
51
+ * @param table - The table.
52
+ * @param options - The row, and the columns it needs (from listMarkColumns).
53
+ * @returns True when the row is drawn.
54
+ */
55
+ export declare function checkRowBecomesMark(table: DataTable, options: {
56
+ row: number;
57
+ present: readonly string[];
58
+ numeric: readonly string[];
59
+ }): boolean;
@@ -0,0 +1,87 @@
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
+ import { z } from "zod";
7
+ /**
8
+ * Read a text cell, as missing (null) when it is empty or only whitespace.
9
+ * A blank names nothing a reader can see, so it must never decide an axis's
10
+ * kind, fail a numeric check or become a category; reading it once here,
11
+ * where every table enters, means every reader sees the same null. Text
12
+ * with anything in it is kept exactly as written, spaces included.
13
+ *
14
+ * @param value - The cell as the caller sent it.
15
+ * @returns The text, or null when it is blank.
16
+ */
17
+ function readTextCell(value) {
18
+ return value.trim() === "" ? null : value;
19
+ }
20
+ /** One cell: a number, a string, or null for a missing value; a blank string is read as null. */
21
+ export const CELL_SCHEMA = z.union([z.number(), z.string().transform(readTextCell), z.null()]);
22
+ /** The table as an agent sends it. */
23
+ export const DATA_TABLE_SCHEMA = z
24
+ .record(z.string().min(1), z.array(CELL_SCHEMA))
25
+ .describe("A table: { column_name: [values] }, every column the same length. "
26
+ + "A missing value is null, \"\" or a string of only whitespace: all three mean the same.");
27
+ /**
28
+ * Count a table's rows, checking it has columns, they are all the same
29
+ * length, and there are not too many rows to draw.
30
+ *
31
+ * @param table - The table.
32
+ * @param options - Where the table is in the figure, for errors, and the most rows allowed.
33
+ * @returns The row count.
34
+ */
35
+ export function countTableRows(table, options) {
36
+ const columns = Object.entries(table);
37
+ const first = columns[0];
38
+ if (first === undefined)
39
+ throw new Error(`${options.where}: the table has no columns.`);
40
+ const [firstName, firstValues] = first;
41
+ for (const [name, values] of columns) {
42
+ if (values.length !== firstValues.length) {
43
+ throw new Error(`${options.where}: every column must have the same length; "${firstName}" has ${firstValues.length}, "${name}" has ${values.length}.`);
44
+ }
45
+ }
46
+ if (firstValues.length > options.maximumRows) {
47
+ throw new Error(`${options.where}: at most ${options.maximumRows} rows; got ${firstValues.length}. Summarise the data first.`);
48
+ }
49
+ return firstValues.length;
50
+ }
51
+ /**
52
+ * Find a column by name, among the table's own columns only: a table is a
53
+ * plain object, so a name like "constructor" or "toString" would otherwise
54
+ * find Object's member, not a column.
55
+ *
56
+ * @param table - The table.
57
+ * @param options - The column's name.
58
+ * @returns Its values, or null when the table has no such column.
59
+ */
60
+ export function findColumn(table, options) {
61
+ return Object.hasOwn(table, options.column) ? (table[options.column] ?? null) : null;
62
+ }
63
+ /**
64
+ * Find a column a field may leave out.
65
+ *
66
+ * @param table - The table.
67
+ * @param options - The column's name, or undefined when the field is not set.
68
+ * @returns Its values, or null when the field is not set or the table has no such column.
69
+ */
70
+ export function findOptionalColumn(table, options) {
71
+ return options.column === undefined ? null : findColumn(table, { column: options.column });
72
+ }
73
+ /**
74
+ * Whether a row becomes a mark: every listed column present, and every
75
+ * numeric one a finite number.
76
+ *
77
+ * @param table - The table.
78
+ * @param options - The row, and the columns it needs (from listMarkColumns).
79
+ * @returns True when the row is drawn.
80
+ */
81
+ export function checkRowBecomesMark(table, options) {
82
+ return options.present.every((column) => (findColumn(table, { column })?.[options.row] ?? null) !== null)
83
+ && options.numeric.every((column) => {
84
+ const value = findColumn(table, { column })?.[options.row];
85
+ return typeof value === "number" && Number.isFinite(value);
86
+ });
87
+ }
@@ -0,0 +1,64 @@
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
+ /** How far past the data a density curve extends, in bandwidths. */
9
+ export declare const DENSITY_TAIL_BANDWIDTHS = 3;
10
+ /**
11
+ * Silverman's rule-of-thumb bandwidth for a Gaussian kernel. It can still be
12
+ * 0 or too small to draw with (a middle half a subnormal distance apart);
13
+ * findBandwidthFault decides that.
14
+ *
15
+ * @param values - The values; at least two, with a spread checkValuesHaveSpread accepts.
16
+ * @returns The bandwidth.
17
+ * @throws Error when the values have no spread checkValuesHaveSpread accepts.
18
+ */
19
+ export declare function computeSilvermanBandwidth(values: number[]): number;
20
+ /**
21
+ * The factor that scales a curve's summed kernels to a density, 1 / (n · h · √(2π)).
22
+ * The curve is n times this high where every value sits at one point.
23
+ *
24
+ * @param options - How many values, and the bandwidth.
25
+ * @returns The factor; Infinity or NaN when n · h · √(2π) underflows.
26
+ */
27
+ export declare function computeDensityNormaliser(options: {
28
+ count: number;
29
+ bandwidth: number;
30
+ }): number;
31
+ /**
32
+ * The x range a density curve is evaluated over: the data's range,
33
+ * extended by DENSITY_TAIL_BANDWIDTHS bandwidths each side.
34
+ *
35
+ * @param options - The data's smallest and largest value, and the bandwidth.
36
+ * @returns The curve's first and last x.
37
+ */
38
+ export declare function computeDensityRange(options: {
39
+ minimum: number;
40
+ maximum: number;
41
+ bandwidth: number;
42
+ }): {
43
+ minimum: number;
44
+ maximum: number;
45
+ };
46
+ /**
47
+ * What stops a bandwidth from drawing a finite curve, if anything. The curve
48
+ * is finite when the bandwidth and its normaliser are finite and above zero,
49
+ * its highest possible y is finite, and its range is finite with a width
50
+ * above zero: the model evaluates the curve with exactly these numbers. A
51
+ * fault is named by its cause: a bandwidth too narrow (the height overflows)
52
+ * or too wide (the height falls to zero, or the range overflows).
53
+ *
54
+ * @param options - How many values the curve sums, the data's smallest and
55
+ * largest value (shared by every curve in the plot), and the bandwidth.
56
+ * @returns What fails, phrased to follow the bandwidth ("is not a finite number above zero"),
57
+ * or null when the curve is finite.
58
+ */
59
+ export declare function findBandwidthFault(options: {
60
+ count: number;
61
+ minimum: number;
62
+ maximum: number;
63
+ bandwidth: number;
64
+ }): string | null;
@@ -0,0 +1,88 @@
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
+ import { checkValuesHaveSpread, computeStandardDeviation } from "./check_values_have_spread.js";
9
+ import { computeQuantile } from "./compute_quantile.js";
10
+ /** How far past the data a density curve extends, in bandwidths. */
11
+ export const DENSITY_TAIL_BANDWIDTHS = 3;
12
+ /** √(2π): a Gaussian kernel of width h peaks at 1 / (h · √(2π)). */
13
+ const SQUARE_ROOT_OF_TWO_PI = Math.sqrt(2 * Math.PI);
14
+ /** Silverman's rule of thumb: h = 0.9 · min(σ, IQR/1.34) · n^(-1/5). */
15
+ const SILVERMAN_FACTOR = 0.9;
16
+ const IQR_TO_SIGMA = 1.34;
17
+ const SILVERMAN_EXPONENT = -1 / 5;
18
+ /**
19
+ * Silverman's rule-of-thumb bandwidth for a Gaussian kernel. It can still be
20
+ * 0 or too small to draw with (a middle half a subnormal distance apart);
21
+ * findBandwidthFault decides that.
22
+ *
23
+ * @param values - The values; at least two, with a spread checkValuesHaveSpread accepts.
24
+ * @returns The bandwidth.
25
+ * @throws Error when the values have no spread checkValuesHaveSpread accepts.
26
+ */
27
+ export function computeSilvermanBandwidth(values) {
28
+ if (!checkValuesHaveSpread(values)) {
29
+ 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.");
30
+ }
31
+ const standardDeviation = computeStandardDeviation(values);
32
+ const sorted = [...values].sort((first, second) => first - second);
33
+ const interquartileRange = computeQuantile(sorted, { quantile: 0.75 }) - computeQuantile(sorted, { quantile: 0.25 });
34
+ const spread = interquartileRange > 0 ? Math.min(standardDeviation, interquartileRange / IQR_TO_SIGMA) : standardDeviation;
35
+ return SILVERMAN_FACTOR * spread * values.length ** SILVERMAN_EXPONENT;
36
+ }
37
+ /**
38
+ * The factor that scales a curve's summed kernels to a density, 1 / (n · h · √(2π)).
39
+ * The curve is n times this high where every value sits at one point.
40
+ *
41
+ * @param options - How many values, and the bandwidth.
42
+ * @returns The factor; Infinity or NaN when n · h · √(2π) underflows.
43
+ */
44
+ export function computeDensityNormaliser(options) {
45
+ return 1 / (options.count * options.bandwidth * SQUARE_ROOT_OF_TWO_PI);
46
+ }
47
+ /**
48
+ * The x range a density curve is evaluated over: the data's range,
49
+ * extended by DENSITY_TAIL_BANDWIDTHS bandwidths each side.
50
+ *
51
+ * @param options - The data's smallest and largest value, and the bandwidth.
52
+ * @returns The curve's first and last x.
53
+ */
54
+ export function computeDensityRange(options) {
55
+ const tail = DENSITY_TAIL_BANDWIDTHS * options.bandwidth;
56
+ return { minimum: options.minimum - tail, maximum: options.maximum + tail };
57
+ }
58
+ /**
59
+ * What stops a bandwidth from drawing a finite curve, if anything. The curve
60
+ * is finite when the bandwidth and its normaliser are finite and above zero,
61
+ * its highest possible y is finite, and its range is finite with a width
62
+ * above zero: the model evaluates the curve with exactly these numbers. A
63
+ * fault is named by its cause: a bandwidth too narrow (the height overflows)
64
+ * or too wide (the height falls to zero, or the range overflows).
65
+ *
66
+ * @param options - How many values the curve sums, the data's smallest and
67
+ * largest value (shared by every curve in the plot), and the bandwidth.
68
+ * @returns What fails, phrased to follow the bandwidth ("is not a finite number above zero"),
69
+ * or null when the curve is finite.
70
+ */
71
+ export function findBandwidthFault(options) {
72
+ const isFinitePositive = (value) => Number.isFinite(value) && value > 0;
73
+ if (!isFinitePositive(options.bandwidth))
74
+ return "is not a finite number above zero";
75
+ // 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π)).
76
+ // The normaliser overflows only when the bandwidth is tiny, and underflows to 0 only when n · bandwidth · √(2π) overflows, a bandwidth that is huge.
77
+ const normaliser = computeDensityNormaliser({ count: options.count, bandwidth: options.bandwidth });
78
+ if (!Number.isFinite(normaliser) || !Number.isFinite(options.count * normaliser)) {
79
+ return "is so narrow that the curve's height, up to 1 / (bandwidth · √(2π)), overflows";
80
+ }
81
+ if (normaliser === 0)
82
+ return "is so wide that the curve's height, 1 / (n · bandwidth · √(2π)), falls to zero";
83
+ const range = computeDensityRange(options);
84
+ if (!Number.isFinite(range.minimum) || !Number.isFinite(range.maximum) || !isFinitePositive(range.maximum - range.minimum)) {
85
+ 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`;
86
+ }
87
+ return null;
88
+ }
@@ -0,0 +1,30 @@
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
+ /** A point of the fit: an x and a y. */
11
+ export type FitPoint = {
12
+ x: number;
13
+ y: number;
14
+ };
15
+ /** A fitted line, and where it starts and ends over the points' x range. */
16
+ export type LineFit = {
17
+ slope: number;
18
+ intercept: number;
19
+ start: FitPoint;
20
+ end: FitPoint;
21
+ };
22
+ /**
23
+ * Fit a least-squares line.
24
+ *
25
+ * @param points - The points, each x and y a finite number.
26
+ * @returns The slope and intercept, and the line's ends at the smallest and
27
+ * largest x; null when any of these is not a finite number (fewer than two
28
+ * points, x values that do not vary measurably, or a sum that overflows).
29
+ */
30
+ export declare function findLineFit(points: readonly FitPoint[]): LineFit | null;
@@ -0,0 +1,36 @@
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
+ import { getNumberRange } from "./get_number_range.js";
11
+ /**
12
+ * Fit a least-squares line.
13
+ *
14
+ * @param points - The points, each x and y a finite number.
15
+ * @returns The slope and intercept, and the line's ends at the smallest and
16
+ * largest x; null when any of these is not a finite number (fewer than two
17
+ * points, x values that do not vary measurably, or a sum that overflows).
18
+ */
19
+ export function findLineFit(points) {
20
+ const count = points.length;
21
+ const meanX = points.reduce((sum, point) => sum + point.x, 0) / count;
22
+ const meanY = points.reduce((sum, point) => sum + point.y, 0) / count;
23
+ let covariance = 0;
24
+ let varianceX = 0;
25
+ for (const point of points) {
26
+ covariance += (point.x - meanX) * (point.y - meanY);
27
+ varianceX += (point.x - meanX) ** 2;
28
+ }
29
+ const slope = covariance / varianceX;
30
+ const intercept = meanY - slope * meanX;
31
+ const xs = points.map((point) => point.x);
32
+ const { minimum: low, maximum: high } = getNumberRange(xs);
33
+ const start = { x: low, y: slope * low + intercept };
34
+ const end = { x: high, y: slope * high + intercept };
35
+ return [slope, intercept, start.x, start.y, end.x, end.y].every(Number.isFinite) ? { slope, intercept, start, end } : null;
36
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Find the smallest and largest of a column of numbers.
3
+ *
4
+ * This loops instead of calling `Math.min(...values)`: spreading a column as
5
+ * call arguments throws `RangeError: Maximum call stack size exceeded` past
6
+ * about 200,000 values, and a host may allow tables bigger than that. It
7
+ * keeps `Math.min` and `Math.max` semantics otherwise: an empty column gives
8
+ * `Infinity` and `-Infinity`, and a `NaN` makes both `NaN`.
9
+ *
10
+ * @param values - The numbers to scan.
11
+ * @returns The smallest and largest value.
12
+ */
13
+ export declare function getNumberRange(values: readonly number[]): {
14
+ minimum: number;
15
+ maximum: number;
16
+ };
@@ -10,12 +10,12 @@
10
10
  * @param values - The numbers to scan.
11
11
  * @returns The smallest and largest value.
12
12
  */
13
- export function getNumberRange(values: readonly number[]): { minimum: number; maximum: number } {
14
- let minimum = Infinity;
15
- let maximum = -Infinity;
16
- for (const value of values) {
17
- minimum = Math.min(minimum, value);
18
- maximum = Math.max(maximum, value);
19
- }
20
- return { minimum, maximum };
13
+ export function getNumberRange(values) {
14
+ let minimum = Infinity;
15
+ let maximum = -Infinity;
16
+ for (const value of values) {
17
+ minimum = Math.min(minimum, value);
18
+ maximum = Math.max(maximum, value);
19
+ }
20
+ return { minimum, maximum };
21
21
  }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Which drawn rows make which series. One rule, read by the model to build
3
+ * each series and by validation to judge each series' trend line, so a
4
+ * figure is never accepted on groups the model would not draw.
5
+ */
6
+ import { type DataTable } from "./data_table.ts";
7
+ /** A row's group: the categories it has for each grouping field. */
8
+ export type Grouping = {
9
+ colourCategories: string[];
10
+ styleCategories: string[];
11
+ };
12
+ /** One series' rows, with the indices of its colour and style categories and its name. */
13
+ export type RowGroup = {
14
+ colourIndex: number;
15
+ styleIndex: number;
16
+ name: string;
17
+ rows: number[];
18
+ };
19
+ /**
20
+ * Split the drawn rows into series, one per colour and style category.
21
+ * Category indices count every category in the column, drawn or not, so a
22
+ * category with nothing drawn takes no series yet the others keep the
23
+ * colours and styles they would have had. A row whose colour or style
24
+ * column holds null has no category, so it joins no series and is not drawn.
25
+ *
26
+ * @param table - The data table.
27
+ * @param options - The row count, the colour and style columns, and which rows become marks.
28
+ * @returns The categories of each grouping column, the groups, each with at least one drawn row, and every
29
+ * drawn row in table order: the only rows an axis may read, so a row never drawn sets no range or category.
30
+ */
31
+ export declare function groupRows(table: DataTable, options: {
32
+ rowCount: number;
33
+ colour: string | undefined;
34
+ style: string | undefined;
35
+ isDrawn: (row: number) => boolean;
36
+ }): {
37
+ grouping: Grouping;
38
+ groups: RowGroup[];
39
+ drawnRows: number[];
40
+ };
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Which drawn rows make which series. One rule, read by the model to build
3
+ * each series and by validation to judge each series' trend line, so a
4
+ * figure is never accepted on groups the model would not draw.
5
+ */
6
+ import { findOptionalColumn } from "./data_table.js";
7
+ import { listCategories } from "./list_categories.js";
8
+ /**
9
+ * Split the drawn rows into series, one per colour and style category.
10
+ * Category indices count every category in the column, drawn or not, so a
11
+ * category with nothing drawn takes no series yet the others keep the
12
+ * colours and styles they would have had. A row whose colour or style
13
+ * column holds null has no category, so it joins no series and is not drawn.
14
+ *
15
+ * @param table - The data table.
16
+ * @param options - The row count, the colour and style columns, and which rows become marks.
17
+ * @returns The categories of each grouping column, the groups, each with at least one drawn row, and every
18
+ * drawn row in table order: the only rows an axis may read, so a row never drawn sets no range or category.
19
+ */
20
+ export function groupRows(table, options) {
21
+ const colourValues = findOptionalColumn(table, { column: options.colour });
22
+ const styleValues = findOptionalColumn(table, { column: options.style });
23
+ const grouping = {
24
+ colourCategories: colourValues === null ? [] : listCategories(colourValues),
25
+ styleCategories: styleValues === null ? [] : listCategories(styleValues),
26
+ };
27
+ // A Map per category list, so each drawn row finds its index in constant time, not by scanning the list.
28
+ const colourIndexes = buildFirstIndexMap(grouping.colourCategories);
29
+ const styleIndexes = buildFirstIndexMap(grouping.styleCategories);
30
+ const groups = new Map();
31
+ const drawnRows = [];
32
+ for (let row = 0; row < options.rowCount; row += 1) {
33
+ if (!options.isDrawn(row))
34
+ continue;
35
+ // A row with no category in a grouping column belongs to no series; index 0 would quietly put it in the first one.
36
+ if (colourValues !== null && colourValues[row] === null)
37
+ continue;
38
+ if (styleValues !== null && styleValues[row] === null)
39
+ continue;
40
+ const colourText = colourValues === null ? null : String(colourValues[row]);
41
+ const styleText = styleValues === null ? null : String(styleValues[row]);
42
+ const colourIndex = colourText === null ? 0 : colourIndexes.get(colourText) ?? -1;
43
+ const styleIndex = styleText === null ? 0 : styleIndexes.get(styleText) ?? -1;
44
+ const parts = [colourText, styleText !== colourText ? styleText : null].filter((part) => part !== null);
45
+ const name = parts.join(" · ");
46
+ const key = `${colourIndex}/${styleIndex}`;
47
+ const group = groups.get(key) ?? { colourIndex, styleIndex, name, rows: [] };
48
+ group.rows.push(row);
49
+ drawnRows.push(row);
50
+ groups.set(key, group);
51
+ }
52
+ return { grouping, groups: [...groups.values()], drawnRows };
53
+ }
54
+ /**
55
+ * Map each category to the index of its first occurrence, as indexOf finds it.
56
+ *
57
+ * @param categories - The category texts in order.
58
+ * @returns The first index of each text.
59
+ */
60
+ function buildFirstIndexMap(categories) {
61
+ const indexes = new Map();
62
+ categories.forEach((category, index) => {
63
+ if (!indexes.has(category))
64
+ indexes.set(category, index);
65
+ });
66
+ return indexes;
67
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The categories a column holds. It sits in `table`, below `model`, so the
3
+ * plot and map models read one definition rather than keeping copies that
4
+ * could drift.
5
+ */
6
+ /**
7
+ * List a column's distinct values as text, in the order they first appear.
8
+ * Numbers count as categories by their text, so 2024 and "2024" are one
9
+ * category; missing values are no category.
10
+ *
11
+ * @param values - The column, or the rows of it to read.
12
+ * @returns Each distinct value's text, first appearance first.
13
+ */
14
+ export declare function listCategories(values: readonly (number | string | null)[]): string[];
@@ -3,7 +3,6 @@
3
3
  * plot and map models read one definition rather than keeping copies that
4
4
  * could drift.
5
5
  */
6
-
7
6
  /**
8
7
  * List a column's distinct values as text, in the order they first appear.
9
8
  * Numbers count as categories by their text, so 2024 and "2024" are one
@@ -12,6 +11,6 @@
12
11
  * @param values - The column, or the rows of it to read.
13
12
  * @returns Each distinct value's text, first appearance first.
14
13
  */
15
- export function listCategories(values: readonly (number | string | null)[]): string[] {
16
- return [...new Set(values.filter((value) => value !== null).map(String))];
14
+ export function listCategories(values) {
15
+ return [...new Set(values.filter((value) => value !== null).map(String))];
17
16
  }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Read a table cell as a number a mark can be drawn from.
3
+ *
4
+ * Only a finite number counts: a numeric-looking string is not parsed, since
5
+ * the table's column checks already decide which columns are numeric, and
6
+ * `NaN` or an infinity would place a mark nowhere or scale every other value
7
+ * to nothing.
8
+ *
9
+ * @param value - The cell, as a table column holds it.
10
+ * @returns The number, or null when the cell is not a finite number.
11
+ */
12
+ export declare function readNumber(value: number | string | null | undefined): number | null;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Read a table cell as a number a mark can be drawn from.
3
+ *
4
+ * Only a finite number counts: a numeric-looking string is not parsed, since
5
+ * the table's column checks already decide which columns are numeric, and
6
+ * `NaN` or an infinity would place a mark nowhere or scale every other value
7
+ * to nothing.
8
+ *
9
+ * @param value - The cell, as a table column holds it.
10
+ * @returns The number, or null when the cell is not a finite number.
11
+ */
12
+ export function readNumber(value) {
13
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
14
+ }