@topolab/tda 0.3.0 → 0.4.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.
@@ -0,0 +1,480 @@
1
+ /**
2
+ * Two-parameter persistent homology: minimal presentations, bigraded Betti
3
+ * numbers, the Hilbert function and the fibered barcode (the barcode along a
4
+ * line), over Z/2.
5
+ */
6
+ import { allFinite, f64, finite, int, isTyped, kind, nonNegative, options, points as checkPoints, sized } from './check.js';
7
+ import type { Keys, PointCloud } from './check.js';
8
+ import { distanceMatrix, isMatrix } from './complex.js';
9
+ import { call, module } from './load.js';
10
+ import type { DistanceMatrix } from './types.js';
11
+
12
+ /**
13
+ * A minimal presentation of a two-parameter persistence module: generators
14
+ * and relations with grades `(x, y)`, and each relation as a sum of
15
+ * generators. Grades are stored as indices into the axes `xs` and `ys`.
16
+ * Relations are ordered by `y`, then `x`.
17
+ */
18
+ export interface Presentation {
19
+ /** The distinct first coordinates of the grades, increasing. */
20
+ xs: Float64Array;
21
+ /** The distinct second coordinates of the grades, increasing. */
22
+ ys: Float64Array;
23
+ /** `[x index, y index]` for each generator. */
24
+ generators: Uint32Array;
25
+ /** `[x index, y index]` for each relation. */
26
+ relations: Uint32Array;
27
+ /** Relation `j` is the sum of the generators `rows[offsets[j] .. offsets[j + 1]]`. */
28
+ offsets: Uint32Array;
29
+ /** Generator indices of the relations, increasing within a relation. */
30
+ rows: Uint32Array;
31
+ /** The homology degree the module is of. */
32
+ degree: number;
33
+ }
34
+
35
+ /** Options of {@link functionRipsPresentation}. */
36
+ export interface FunctionRipsPresentationOptions {
37
+ /** Homology degree, a non-negative integer. Default 1. */
38
+ degree?: number;
39
+ /** Largest edge kept, non-negative. Default `Infinity` (every pair). */
40
+ maxEdgeLength?: number;
41
+ }
42
+ const FUNCTION_RIPS_KEYS: Keys<FunctionRipsPresentationOptions> = { degree: true, maxEdgeLength: true };
43
+
44
+ /** The module's six arrays with the degree (internal: also used by src/rivet_input.ts). */
45
+ export function presentationOf(raw: Omit<Presentation, 'degree'>, degree: number): Presentation {
46
+ return {
47
+ xs: raw.xs,
48
+ ys: raw.ys,
49
+ generators: raw.generators,
50
+ relations: raw.relations,
51
+ offsets: raw.offsets,
52
+ rows: raw.rows,
53
+ degree
54
+ };
55
+ }
56
+
57
+ /**
58
+ * The minimal presentation of the degree-`degree` homology of the
59
+ * function-Rips bifiltration of a point cloud or a distance matrix: the
60
+ * simplex on a set of points is present at `(a, r)` when every point has
61
+ * function value `<= a` and every pair is at distance `<= r`. `values[i]` is
62
+ * the function at point `i` (for instance a codensity, so that dense
63
+ * regions come first). Degrees 0, 1 and 2 never build the complex (degrees 0
64
+ * and 1 take thousands of points, degree 2 hundreds); higher degrees build it
65
+ * up to dimension `degree + 1`.
66
+ */
67
+ export function functionRipsPresentation(
68
+ points: PointCloud | DistanceMatrix,
69
+ values: ArrayLike<number>,
70
+ opts?: FunctionRipsPresentationOptions
71
+ ): Presentation {
72
+ module();
73
+ const o = options<FunctionRipsPresentationOptions>(opts, 'functionRipsPresentation', FUNCTION_RIPS_KEYS);
74
+ const matrix = isMatrix(points, 'points');
75
+ const n = matrix ? distanceMatrix(points, 'points') : checkPoints(points, 'points');
76
+ const fn = f64(values, 'values');
77
+ sized(fn.length, n, 'values', 'one function value per point');
78
+ allFinite(fn, 'values');
79
+ const degree = o.degree === undefined ? 1 : int(o.degree, 'degree', 0, 254);
80
+ const threshold = o.maxEdgeLength === undefined ? Infinity : nonNegative(o.maxEdgeLength, 'maxEdgeLength');
81
+ return call((m) => {
82
+ if (matrix) {
83
+ return presentationOf(
84
+ m.functionRipsPresentationFromMatrixFlat((points as DistanceMatrix).distances, n, fn, threshold, degree),
85
+ degree
86
+ );
87
+ }
88
+ const { coords, d } = points as PointCloud;
89
+ return presentationOf(m.functionRipsPresentationFlat(coords, d, fn, threshold, degree), degree);
90
+ });
91
+ }
92
+
93
+ /** Options of {@link degreeRipsPresentation}. */
94
+ export interface DegreeRipsPresentationOptions {
95
+ /** Homology degree, a non-negative integer. Default 1. */
96
+ degree?: number;
97
+ /** Largest edge kept, non-negative; degrees are counted among the edges kept. Default `Infinity`. */
98
+ maxEdgeLength?: number;
99
+ }
100
+ const DEGREE_RIPS_KEYS: Keys<DegreeRipsPresentationOptions> = { degree: true, maxEdgeLength: true };
101
+
102
+ /**
103
+ * The minimal presentation of the degree-`degree` homology of the
104
+ * degree-Rips bifiltration of a point cloud or a distance matrix: at
105
+ * `(−k, r)`, the Rips complex at scale `r` on the points with at least `k`
106
+ * other points within `r`. The first coordinate is minus the degree, so that
107
+ * the complex grows along both axes; it needs no function on the points.
108
+ * Every simplex has one grade per degree its points reach, so the cost
109
+ * grows with the number of simplices times the number of points: for small
110
+ * clouds (about 60 points in degree 1 take a second).
111
+ */
112
+ export function degreeRipsPresentation(points: PointCloud | DistanceMatrix, opts?: DegreeRipsPresentationOptions): Presentation {
113
+ module();
114
+ const o = options<DegreeRipsPresentationOptions>(opts, 'degreeRipsPresentation', DEGREE_RIPS_KEYS);
115
+ const matrix = isMatrix(points, 'points');
116
+ const n = matrix ? distanceMatrix(points, 'points') : checkPoints(points, 'points');
117
+ const degree = o.degree === undefined ? 1 : int(o.degree, 'degree', 0, 254);
118
+ const threshold = o.maxEdgeLength === undefined ? Infinity : nonNegative(o.maxEdgeLength, 'maxEdgeLength');
119
+ return call((m) => {
120
+ if (matrix) {
121
+ return presentationOf(m.degreeRipsPresentationFromMatrixFlat((points as DistanceMatrix).distances, n, threshold, degree), degree);
122
+ }
123
+ const { coords, d } = points as PointCloud;
124
+ return presentationOf(m.degreeRipsPresentationFlat(coords, d, threshold, degree), degree);
125
+ });
126
+ }
127
+
128
+ /**
129
+ * A bifiltered cell complex: cell `k` has dimension `dims[k]` and facets
130
+ * `facets[offsets[k] .. offsets[k + 1]]` (cell indices; none for a vertex).
131
+ * Without `gradeOffsets` each cell has one grade, `(grades[2k], grades[2k +
132
+ * 1])`, and every facet's grade must be at most its cell's in both
133
+ * coordinates. With `gradeOffsets` the bifiltration is multicritical: cell
134
+ * `k` is present from each of the grades number `gradeOffsets[k]` to
135
+ * `gradeOffsets[k + 1]` of `grades` on, and a facet must be present wherever
136
+ * its cell is.
137
+ */
138
+ export interface Bifiltration {
139
+ /** Dimension of each cell. */
140
+ dims: Uint8Array;
141
+ /** `[x, y]` for each grade: one per cell, or as `gradeOffsets` says. */
142
+ grades: Float64Array;
143
+ /** Multicritical only: offsets of the cells' grades (one more than the cells), counted in grades. */
144
+ gradeOffsets?: Uint32Array;
145
+ /** CSR offsets of the facets (one more than the cells). */
146
+ offsets: Uint32Array;
147
+ /** Facets as cell indices. */
148
+ facets: Uint32Array;
149
+ }
150
+
151
+ /** Options of {@link bifiltrationPresentation}. */
152
+ export interface BifiltrationPresentationOptions {
153
+ /** Homology degree, a non-negative integer. Default 1. */
154
+ degree?: number;
155
+ }
156
+ const BIFILTRATION_PRESENTATION_KEYS: Keys<BifiltrationPresentationOptions> = { degree: true };
157
+
158
+ type ArrayKind = 'Float64Array' | 'Uint32Array' | 'Uint8Array';
159
+
160
+ /** A typed array of kind `arrayKind`, from this realm or another. */
161
+ function typed<T>(v: unknown, arrayKind: ArrayKind, name: string): T {
162
+ if (!isTyped(v, arrayKind)) throw new TypeError(`${name} must be a ${arrayKind}, got ${kind(v)}`);
163
+ return v as T;
164
+ }
165
+
166
+ /** A data object (its fields are read, not listed): anything but an object is a `TypeError`. */
167
+ function record<T extends object>(v: unknown, name: string): Partial<T> {
168
+ if (v === null || typeof v !== 'object' || Array.isArray(v)) throw new TypeError(`${name} must be an object, got ${kind(v)}`);
169
+ return v as Partial<T>;
170
+ }
171
+
172
+ /**
173
+ * The minimal presentation of the degree-`degree` homology of any
174
+ * bifiltered cell complex, one grade a cell or several, over Z/2.
175
+ */
176
+ export function bifiltrationPresentation(bifiltration: Bifiltration, opts?: BifiltrationPresentationOptions): Presentation {
177
+ module();
178
+ const b = record<Bifiltration>(bifiltration, 'bifiltration');
179
+ const o = options<BifiltrationPresentationOptions>(opts, 'bifiltrationPresentation', BIFILTRATION_PRESENTATION_KEYS);
180
+ const dims = typed<Uint8Array>(b.dims, 'Uint8Array', 'bifiltration.dims');
181
+ const grades = typed<Float64Array>(b.grades, 'Float64Array', 'bifiltration.grades');
182
+ const offsets = typed<Uint32Array>(b.offsets, 'Uint32Array', 'bifiltration.offsets');
183
+ const facets = typed<Uint32Array>(b.facets, 'Uint32Array', 'bifiltration.facets');
184
+ const degree = o.degree === undefined ? 1 : int(o.degree, 'degree', 0, 254);
185
+ if (b.gradeOffsets !== undefined) {
186
+ const gradeOffsets = typed<Uint32Array>(b.gradeOffsets, 'Uint32Array', 'bifiltration.gradeOffsets');
187
+ return call((m) => presentationOf(m.multicriticalPresentationFlat(dims, gradeOffsets, grades, offsets, facets, degree), degree));
188
+ }
189
+ return call((m) => presentationOf(m.bifiltrationPresentationFlat(dims, grades, offsets, facets, degree), degree));
190
+ }
191
+
192
+ /** A presentation's arrays, checked for their kinds (internal: also used by src/arrangement.ts). */
193
+ export function checked(p: Presentation, name: string): Presentation {
194
+ const o = record<Presentation>(p, name);
195
+ typed<Float64Array>(o.xs, 'Float64Array', `${name}.xs`);
196
+ typed<Float64Array>(o.ys, 'Float64Array', `${name}.ys`);
197
+ typed<Uint32Array>(o.generators, 'Uint32Array', `${name}.generators`);
198
+ typed<Uint32Array>(o.relations, 'Uint32Array', `${name}.relations`);
199
+ typed<Uint32Array>(o.offsets, 'Uint32Array', `${name}.offsets`);
200
+ typed<Uint32Array>(o.rows, 'Uint32Array', `${name}.rows`);
201
+ return o as Presentation;
202
+ }
203
+
204
+ /** The bigraded Betti numbers of a module and its Hilbert function. */
205
+ export interface BigradedBetti {
206
+ /** Grades `[x, y, …]` of the generators (ξ₀). */
207
+ b0: Float64Array;
208
+ /** Grades `[x, y, …]` of the relations (ξ₁). */
209
+ b1: Float64Array;
210
+ /** Grades `[x, y, …]` of the relations among the relations (ξ₂). */
211
+ b2: Float64Array;
212
+ /** The axes the Hilbert function is given on (the presentation's). */
213
+ xs: Float64Array;
214
+ /** See `xs`. */
215
+ ys: Float64Array;
216
+ /**
217
+ * The Hilbert function: `hilbert[iy · xs.length + ix]` is the dimension of
218
+ * the module at `(xs[ix], ys[iy])`, and at every point up to the next
219
+ * grid line on either axis. The module is zero below `xs[0]` or `ys[0]`.
220
+ */
221
+ hilbert: Uint32Array;
222
+ }
223
+
224
+ function gradesOf(p: Presentation, grid: Uint32Array): Float64Array {
225
+ const out = new Float64Array(grid.length);
226
+ for (let i = 0; i < grid.length; i += 2) {
227
+ out[i] = p.xs[grid[i]!]!;
228
+ out[i + 1] = p.ys[grid[i + 1]!]!;
229
+ }
230
+ return out;
231
+ }
232
+
233
+ /**
234
+ * The bigraded Betti numbers ξ₀, ξ₁, ξ₂ of a presented module (the grades
235
+ * of the generators, the relations and the relations among relations, with
236
+ * multiplicity) and its Hilbert function, the dimension of the module at
237
+ * every point of the plane.
238
+ */
239
+ export function bigradedBetti(presentation: Presentation): BigradedBetti {
240
+ module();
241
+ const p = checked(presentation, 'presentation');
242
+ return call((m) => {
243
+ const r = m.presentationInvariantsFlat(p.xs, p.ys, p.generators, p.relations, p.offsets, p.rows);
244
+ return {
245
+ b0: gradesOf(p, p.generators),
246
+ b1: gradesOf(p, p.relations),
247
+ b2: gradesOf(p, r.syzygies),
248
+ xs: p.xs,
249
+ ys: p.ys,
250
+ hilbert: r.hilbert
251
+ };
252
+ });
253
+ }
254
+
255
+ /**
256
+ * A line of non-negative slope: through `point`, along `direction` (both
257
+ * coordinates non-negative, not both zero) or at `angle` degrees from the
258
+ * first axis (0 to 90).
259
+ */
260
+ export type SliceLine =
261
+ | { point: ArrayLike<number>; direction: ArrayLike<number> }
262
+ | { point: ArrayLike<number>; angle: number };
263
+
264
+ /** The barcode of a module along one line. */
265
+ export interface FiberedBarcode {
266
+ /**
267
+ * `[birth, death, …]` in the line's parameter `t`: the point of the line
268
+ * at `t` is `point + t · direction`. `death` is `Infinity` for a class
269
+ * that persists along the rest of the line. Sorted by birth, then death.
270
+ */
271
+ pairs: Float64Array;
272
+ /** The point of the line that `t = 0` is: the line's `point`. */
273
+ point: [number, number];
274
+ /** The unit direction of the line, as the module computed it from `direction` or `angle`. */
275
+ direction: [number, number];
276
+ }
277
+
278
+ /**
279
+ * One line, checked, as the module reads it: `[px, py, a, b]` with `angle`
280
+ * false for the direction `(a, b)`, or `[px, py, degrees, 0]` with `angle`
281
+ * true. The module builds the line (it normalises the direction, or takes
282
+ * the cosine and sine of the angle), so that it is the line a Rust caller of
283
+ * `Line::new` or `Line::from_angle` gets, to the bit.
284
+ */
285
+ function lineOf(line: SliceLine, name: string): { numbers: [number, number, number, number]; angle: boolean } {
286
+ const l = record<{ point: ArrayLike<number>; direction: ArrayLike<number>; angle: number }>(line, name);
287
+ const point = l.point;
288
+ if (point === null || typeof point !== 'object' || point.length !== 2) {
289
+ throw new TypeError(`${name}.point must be [x, y], got ${kind(point)}`);
290
+ }
291
+ const px = finite(point[0], `${name}.point[0]`);
292
+ const py = finite(point[1], `${name}.point[1]`);
293
+ if (l.direction !== undefined) {
294
+ const direction = l.direction;
295
+ if (direction === null || typeof direction !== 'object' || direction.length !== 2) {
296
+ throw new TypeError(`${name}.direction must be [dx, dy], got ${kind(direction)}`);
297
+ }
298
+ const dx = nonNegative(direction[0], `${name}.direction[0]`);
299
+ const dy = nonNegative(direction[1], `${name}.direction[1]`);
300
+ if (!Number.isFinite(dx) || !Number.isFinite(dy) || (dx === 0 && dy === 0)) {
301
+ throw new RangeError(`${name}.direction must be finite and not zero, got [${dx}, ${dy}]`);
302
+ }
303
+ return { numbers: [px, py, dx, dy], angle: false };
304
+ }
305
+ const angle = finite(l.angle, `${name}.angle`);
306
+ if (angle < 0 || angle > 90) throw new RangeError(`${name}.angle must be between 0 and 90 degrees, got ${angle}`);
307
+ return { numbers: [px, py, angle, 0], angle: true };
308
+ }
309
+
310
+ /**
311
+ * The fibered barcode of a presented module: its barcode along each given
312
+ * line of non-negative slope. Restricted to such a line, a two-parameter
313
+ * module is a one-parameter module, and this is its barcode, in the line's
314
+ * parameter. One line gives one barcode; an array of lines an array of
315
+ * barcodes, in one call. The Rust core builds each line, as the crate's
316
+ * `Line::new` (a direction, normalised) or `Line::from_angle` (an angle: 0,
317
+ * 45 and 90 degrees exactly, others from the cosine and sine of the `libm`
318
+ * crate, a port of musl's) builds it, and returns it as the barcode's
319
+ * `point` and `direction`: the same bits in every JavaScript engine, in the
320
+ * Python package and from the crate.
321
+ */
322
+ export function fiberedBarcode(presentation: Presentation, line: SliceLine): FiberedBarcode;
323
+ export function fiberedBarcode(presentation: Presentation, lines: readonly SliceLine[]): FiberedBarcode[];
324
+ export function fiberedBarcode(presentation: Presentation, lines: SliceLine | readonly SliceLine[]): FiberedBarcode | FiberedBarcode[] {
325
+ module();
326
+ const p = checked(presentation, 'presentation');
327
+ const { many, flat, angles } = linesOf(lines);
328
+ return call((m) => barcodesOf(m.presentationSliceFlat(p.xs, p.ys, p.generators, p.relations, p.offsets, p.rows, flat, angles), many));
329
+ }
330
+
331
+ /**
332
+ * One line or an array of lines as the module reads them: `[px, py, a, b, …]`
333
+ * and one flag per line, 1 when the line is given by its angle (internal:
334
+ * also used by src/arrangement.ts).
335
+ */
336
+ export function linesOf(lines: SliceLine | readonly SliceLine[]): { many: boolean; flat: Float64Array; angles: Uint8Array } {
337
+ const many = Array.isArray(lines);
338
+ const list = (many ? lines : [lines]) as readonly SliceLine[];
339
+ const flat = new Float64Array(4 * list.length);
340
+ const angles = new Uint8Array(list.length);
341
+ list.forEach((l, i) => {
342
+ const { numbers, angle } = lineOf(l, many ? `lines[${i}]` : 'line');
343
+ flat.set(numbers, 4 * i);
344
+ angles[i] = angle ? 1 : 0;
345
+ });
346
+ return { many, flat, angles };
347
+ }
348
+
349
+ /**
350
+ * The barcodes of `{ pairs, offsets, lines }`, each with the line the module
351
+ * built (internal: also used by src/arrangement.ts).
352
+ */
353
+ export function barcodesOf(
354
+ r: { pairs: Float64Array; offsets: Uint32Array; lines: Float64Array },
355
+ many: boolean
356
+ ): FiberedBarcode | FiberedBarcode[] {
357
+ const out: FiberedBarcode[] = [];
358
+ for (let i = 0; i < r.lines.length / 4; i++) {
359
+ out.push({
360
+ pairs: r.pairs.slice(2 * r.offsets[i]!, 2 * r.offsets[i + 1]!),
361
+ point: [r.lines[4 * i]!, r.lines[4 * i + 1]!],
362
+ direction: [r.lines[4 * i + 2]!, r.lines[4 * i + 3]!]
363
+ });
364
+ }
365
+ return many ? out : out[0]!;
366
+ }
367
+
368
+ /** One map of a {@link Firep}: a column per generator of its source, with that generator's grade and the indices of its non-zero rows. */
369
+ export interface FirepMatrix {
370
+ /** `[x, y]` for each column. */
371
+ grades: Float64Array;
372
+ /** Column `j` has the rows `rows[offsets[j] .. offsets[j + 1]]`. */
373
+ offsets: Uint32Array;
374
+ /** Row indices into the target's generators, from 0. */
375
+ rows: Uint32Array;
376
+ }
377
+
378
+ /**
379
+ * A chain complex of free bigraded modules `C2 → C1 → C0` over Z/2, RIVET's
380
+ * free implicit representation (FIRep): the module it presents is the
381
+ * homology at `C1`. Every row of a column of `high` must have a grade at most
382
+ * the column's, and the two maps must compose to zero.
383
+ */
384
+ export interface Firep {
385
+ /** `C2 → C1`: a column per generator of `C2`, rows indexing `C1`. */
386
+ high: FirepMatrix;
387
+ /** `C1 → C0`: a column per generator of `C1` (so its grades are those of `C1`), rows indexing `C0`. */
388
+ low: FirepMatrix;
389
+ /** The number of generators of `C0` (their grades are not needed). */
390
+ lowRank: number;
391
+ }
392
+
393
+ /** Options of {@link firepPresentation}. */
394
+ export interface FirepPresentationOptions {
395
+ /** The homology degree recorded in the result (the module is the homology at `C1` whatever it is). Default 1. */
396
+ degree?: number;
397
+ }
398
+ const FIREP_KEYS: Keys<FirepPresentationOptions> = { degree: true };
399
+
400
+ function firepMatrix(v: unknown, name: string): FirepMatrix {
401
+ const m = record<FirepMatrix>(v, name);
402
+ return {
403
+ grades: typed<Float64Array>(m.grades, 'Float64Array', `${name}.grades`),
404
+ offsets: typed<Uint32Array>(m.offsets, 'Uint32Array', `${name}.offsets`),
405
+ rows: typed<Uint32Array>(m.rows, 'Uint32Array', `${name}.rows`)
406
+ };
407
+ }
408
+
409
+ /**
410
+ * The minimal presentation of the homology of a chain complex of free
411
+ * bigraded modules at its middle (RIVET's FIRep input), over Z/2.
412
+ */
413
+ export function firepPresentation(firep: Firep, opts?: FirepPresentationOptions): Presentation {
414
+ module();
415
+ const f = record<Firep>(firep, 'firep');
416
+ const high = firepMatrix(f.high, 'firep.high');
417
+ const low = firepMatrix(f.low, 'firep.low');
418
+ const lowRank = int(f.lowRank, 'firep.lowRank', 0);
419
+ const o = options<FirepPresentationOptions>(opts, 'firepPresentation', FIREP_KEYS);
420
+ const degree = o.degree === undefined ? 1 : int(o.degree, 'degree', 0, 254);
421
+ return call((m) =>
422
+ presentationOf(m.firepPresentationFlat(high.grades, high.offsets, high.rows, low.grades, low.offsets, low.rows, lowRank), degree)
423
+ );
424
+ }
425
+
426
+ /** Options of {@link coarsenPresentation}. */
427
+ export interface CoarsenPresentationOptions {
428
+ /**
429
+ * Bins on the first axis (RIVET's `--xbins`), a non-negative integer.
430
+ * Default 0: the axis as it is. So is an axis with at most this many
431
+ * distinct grades.
432
+ */
433
+ xbins?: number;
434
+ /** Bins on the second axis (RIVET's `--ybins`), as `xbins`. */
435
+ ybins?: number;
436
+ /**
437
+ * `[lo, hi]` covered by the bins of the first axis. Default: from the
438
+ * smallest to the largest first coordinate of the grades. `hi` must be at
439
+ * least the largest one.
440
+ */
441
+ xRange?: ArrayLike<number>;
442
+ /** `[lo, hi]` covered by the bins of the second axis, as `xRange`. */
443
+ yRange?: ArrayLike<number>;
444
+ }
445
+ const COARSEN_KEYS: Keys<CoarsenPresentationOptions> = { xbins: true, ybins: true, xRange: true, yRange: true };
446
+
447
+ function rangeOf(v: unknown, name: string): Float64Array {
448
+ if (v === undefined) return new Float64Array(0);
449
+ if (v === null || typeof v !== 'object' || (v as ArrayLike<number>).length !== 2) {
450
+ throw new TypeError(`${name} must be [lo, hi], got ${kind(v)}`);
451
+ }
452
+ const r = v as ArrayLike<number>;
453
+ const lo = finite(r[0], `${name}[0]`);
454
+ const hi = finite(r[1], `${name}[1]`);
455
+ if (lo > hi) throw new RangeError(`${name} must have lo <= hi, got [${lo}, ${hi}]`);
456
+ return Float64Array.of(lo, hi);
457
+ }
458
+
459
+ /**
460
+ * The minimal presentation of the module coarsened onto a grid, as RIVET
461
+ * coarsens with `--xbins` and `--ybins`: `xbins` values evenly spaced over
462
+ * `xRange`, the last at its end (`lo + k (hi − lo) / xbins`, `k = 1 …
463
+ * xbins`), the same for `y`, and every grade rounded up to the grid. The
464
+ * coarsened module at a point is the module at the largest grid point below
465
+ * it, so fewer grades, fewer anchors and a smaller augmented arrangement,
466
+ * at the price of moving every interval's ends up to the grid.
467
+ */
468
+ export function coarsenPresentation(presentation: Presentation, opts?: CoarsenPresentationOptions): Presentation {
469
+ module();
470
+ const p = checked(presentation, 'presentation');
471
+ const o = options<CoarsenPresentationOptions>(opts, 'coarsenPresentation', COARSEN_KEYS);
472
+ const xbins = o.xbins === undefined ? 0 : int(o.xbins, 'xbins', 0);
473
+ const ybins = o.ybins === undefined ? 0 : int(o.ybins, 'ybins', 0);
474
+ const xRange = rangeOf(o.xRange, 'xRange');
475
+ const yRange = rangeOf(o.yRange, 'yRange');
476
+ const degree = typeof p.degree === 'number' ? p.degree : 0;
477
+ return call((m) =>
478
+ presentationOf(m.presentationCoarsenFlat(p.xs, p.ys, p.generators, p.relations, p.offsets, p.rows, xbins, ybins, xRange, yRange), degree)
479
+ );
480
+ }