@topolab/tda 0.0.0-stage → 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.
Files changed (105) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/CITATION.cff +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +100 -2
  5. package/SECURITY.md +34 -0
  6. package/THIRD_PARTY_LICENSES.md +697 -0
  7. package/dist/arrangement.d.ts +50 -0
  8. package/dist/arrangement.d.ts.map +1 -0
  9. package/dist/arrangement.js +63 -0
  10. package/dist/arrangement.js.map +1 -0
  11. package/dist/build_info.json +12 -0
  12. package/dist/check.d.ts +118 -0
  13. package/dist/check.d.ts.map +1 -0
  14. package/dist/check.js +298 -0
  15. package/dist/check.js.map +1 -0
  16. package/dist/complex.d.ts +543 -0
  17. package/dist/complex.d.ts.map +1 -0
  18. package/dist/complex.js +712 -0
  19. package/dist/complex.js.map +1 -0
  20. package/dist/diagram.d.ts +116 -0
  21. package/dist/diagram.d.ts.map +1 -0
  22. package/dist/diagram.js +238 -0
  23. package/dist/diagram.js.map +1 -0
  24. package/dist/diagram_of.d.ts +17 -0
  25. package/dist/diagram_of.d.ts.map +1 -0
  26. package/dist/diagram_of.js +40 -0
  27. package/dist/diagram_of.js.map +1 -0
  28. package/dist/experimental.d.ts +18 -0
  29. package/dist/experimental.d.ts.map +1 -0
  30. package/dist/experimental.js +16 -0
  31. package/dist/experimental.js.map +1 -0
  32. package/dist/flat.d.ts +64 -0
  33. package/dist/flat.d.ts.map +1 -0
  34. package/dist/flat.js +158 -0
  35. package/dist/flat.js.map +1 -0
  36. package/dist/index.d.ts +42 -0
  37. package/dist/index.d.ts.map +1 -0
  38. package/dist/index.js +31 -0
  39. package/dist/index.js.map +1 -0
  40. package/dist/ladder/tda_ladder.d.ts +223 -0
  41. package/dist/ladder/tda_ladder.js +1360 -0
  42. package/dist/ladder/tda_ladder_bg.wasm +0 -0
  43. package/dist/ladder/tda_ladder_bg.wasm.d.ts +43 -0
  44. package/dist/ladder.d.ts +306 -0
  45. package/dist/ladder.d.ts.map +1 -0
  46. package/dist/ladder.js +607 -0
  47. package/dist/ladder.js.map +1 -0
  48. package/dist/load.d.ts +53 -0
  49. package/dist/load.d.ts.map +1 -0
  50. package/dist/load.js +173 -0
  51. package/dist/load.js.map +1 -0
  52. package/dist/memory.d.ts +58 -0
  53. package/dist/memory.d.ts.map +1 -0
  54. package/dist/memory.js +2 -0
  55. package/dist/memory.js.map +1 -0
  56. package/dist/persistence.d.ts +349 -0
  57. package/dist/persistence.d.ts.map +1 -0
  58. package/dist/persistence.js +478 -0
  59. package/dist/persistence.js.map +1 -0
  60. package/dist/pkg/tda_wasm.d.ts +13 -0
  61. package/dist/pkg/tda_wasm.js +2528 -0
  62. package/dist/prepared.d.ts +62 -0
  63. package/dist/prepared.d.ts.map +1 -0
  64. package/dist/prepared.js +81 -0
  65. package/dist/prepared.js.map +1 -0
  66. package/dist/rivet_input.d.ts +93 -0
  67. package/dist/rivet_input.d.ts.map +1 -0
  68. package/dist/rivet_input.js +132 -0
  69. package/dist/rivet_input.js.map +1 -0
  70. package/dist/source.d.ts +43 -0
  71. package/dist/source.d.ts.map +1 -0
  72. package/dist/source.js +99 -0
  73. package/dist/source.js.map +1 -0
  74. package/dist/tda.wasm +0 -0
  75. package/dist/two_parameter.d.ts +243 -0
  76. package/dist/two_parameter.d.ts.map +1 -0
  77. package/dist/two_parameter.js +275 -0
  78. package/dist/two_parameter.js.map +1 -0
  79. package/dist/types.d.ts +146 -0
  80. package/dist/types.d.ts.map +1 -0
  81. package/dist/types.js +2 -0
  82. package/dist/types.js.map +1 -0
  83. package/dist/vineyard.d.ts +278 -0
  84. package/dist/vineyard.d.ts.map +1 -0
  85. package/dist/vineyard.js +236 -0
  86. package/dist/vineyard.js.map +1 -0
  87. package/package.json +77 -4
  88. package/src/arrangement.ts +96 -0
  89. package/src/check.ts +338 -0
  90. package/src/complex.ts +1179 -0
  91. package/src/diagram.ts +299 -0
  92. package/src/diagram_of.ts +40 -0
  93. package/src/experimental.ts +17 -0
  94. package/src/flat.ts +204 -0
  95. package/src/index.ts +181 -0
  96. package/src/ladder.ts +903 -0
  97. package/src/load.ts +201 -0
  98. package/src/memory.ts +58 -0
  99. package/src/persistence.ts +752 -0
  100. package/src/prepared.ts +111 -0
  101. package/src/rivet_input.ts +195 -0
  102. package/src/source.ts +132 -0
  103. package/src/two_parameter.ts +480 -0
  104. package/src/types.ts +163 -0
  105. package/src/vineyard.ts +463 -0
@@ -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
+ }
package/src/types.ts ADDED
@@ -0,0 +1,163 @@
1
+ /**
2
+ * The plain data the package takes and returns. Every result is a plain
3
+ * object of typed arrays, numbers, strings, booleans and arrays of them, so
4
+ * it survives `postMessage` and `structuredClone` whole; no result has
5
+ * methods.
6
+ */
7
+ import type { PointCloud } from './check.js';
8
+
9
+ export type { PointCloud };
10
+
11
+ /**
12
+ * The quantity a filtration's values measure, carried by every complex and
13
+ * diagram.
14
+ *
15
+ * - `'edgeLength'`: an edge length, twice a ball radius (Rips, ellipsoid
16
+ * Rips; cutoff `maxEdgeLength`);
17
+ * - `'radius'`: the radius of a ball (Čech, Delaunay–Čech, ellipsoid Čech;
18
+ * cutoff `maxRadius`);
19
+ * - `'squaredRadius'`: a squared radius, negative at weighted vertices
20
+ * (alpha, coupled alpha, k-fold cover; cutoff `maxSquaredRadius`);
21
+ * - `'squaredRelaxation'`: the relaxation of the witness complex, a squared
22
+ * length (cutoff `maxSquaredRelaxation`);
23
+ * - `'epsilon'`: the wing length ε (wing complex; cutoff `maxEpsilon`);
24
+ * - `'growthRadius'`: the ℓ∞ radius `j · stepSize` within which the boxes of
25
+ * the box filtration grow (cutoffs `stepSize`, `maxSteps`);
26
+ * - `'value'`: the caller's own values (cubical complexes, a complex the
27
+ * caller builds, zigzag operations).
28
+ */
29
+ export type Scale =
30
+ | 'edgeLength'
31
+ | 'radius'
32
+ | 'squaredRadius'
33
+ | 'squaredRelaxation'
34
+ | 'epsilon'
35
+ | 'growthRadius'
36
+ | 'value';
37
+
38
+ /** A dense `n × n` distance matrix, row-major; only the strict lower triangle (`distances[i·n + j]`, `i > j`) is read, and no entry may be NaN or negative. */
39
+ export interface DistanceMatrix {
40
+ /** The `n²` distances, row-major. */
41
+ distances: Float64Array;
42
+ }
43
+
44
+ /**
45
+ * An image or a volume: `values` row-major in NumPy's order, the last axis
46
+ * fastest. A `height × width` image is `shape: [height, width]`, its pixel
47
+ * `(row, column)` at `values[row · width + column]`, as in `ImageData`.
48
+ */
49
+ export interface Grid {
50
+ /** The values, row-major (length the product of `shape`). */
51
+ values: Float64Array;
52
+ /** The extent of each axis, slowest first. */
53
+ shape: number[];
54
+ }
55
+
56
+ /**
57
+ * A filtered simplicial complex as three typed arrays (CSR): simplex `i` is
58
+ * `vertices[offsets[i] .. offsets[i + 1])`, its vertex ids in increasing
59
+ * order, entered at `filtrations[i]`.
60
+ *
61
+ * Every builder lists its simplices in one documented order: by value
62
+ * (`-0` equal to `+0`), then by dimension, then lexicographically on the
63
+ * increasing vertex lists (as Python sorts lists). Values never decrease,
64
+ * and every face comes before its cofaces. (Where the input's ties are not
65
+ * exact in double precision, the full Čech builder raises a coface to its
66
+ * faces' values; see `cechComplex`.)
67
+ *
68
+ * A function that takes simplices (`persistence`, `volumeOptimalCycles`,
69
+ * `flatten`, the ladder filtrations) accepts each simplex's vertices in any
70
+ * order and sorts them; a vertex listed twice in one simplex is refused with
71
+ * a `RangeError`.
72
+ */
73
+ export interface Complex {
74
+ /** Concatenated vertex ids of every simplex (increasing within a simplex). */
75
+ vertices: Int32Array;
76
+ /** Length `count + 1`; simplex `i` is `vertices[offsets[i] .. offsets[i + 1])`. */
77
+ offsets: Uint32Array;
78
+ /** The value at which simplex `i` enters. */
79
+ filtrations: Float64Array;
80
+ /** The quantity the values measure. */
81
+ scale: Scale;
82
+ }
83
+
84
+ /**
85
+ * What the functions that take a complex accept: a {@link Complex}, or the
86
+ * same three arrays as number arrays (converted, with integer checks), with
87
+ * or without `scale`.
88
+ */
89
+ export interface ComplexLike {
90
+ vertices: ArrayLike<number>;
91
+ offsets: ArrayLike<number>;
92
+ filtrations: ArrayLike<number>;
93
+ scale?: Scale;
94
+ }
95
+
96
+ /** One simplex as an object (what {@link materialize} builds from a {@link Complex}). */
97
+ export interface Simplex {
98
+ /** Vertex ids, increasing in what the package returns; any order in what it takes. */
99
+ vertices: number[];
100
+ /** The value at which the simplex enters. */
101
+ filtration: number;
102
+ }
103
+
104
+ /**
105
+ * Every cell of a T-construction cubical complex, in the order (value, then
106
+ * cell dimension, then bitmap position).
107
+ */
108
+ export interface CubicalComplex {
109
+ /** The grid's shape (the input's, slowest axis first). */
110
+ shape: number[];
111
+ /**
112
+ * Position of each cell in the bitmap, the grid of `2 · shape[i] + 1`
113
+ * positions along axis `i`, numbered row-major (the last axis fastest): a
114
+ * cell's coordinate is odd along the axes it spans, and the pixel at
115
+ * `(p0, p1, …)` is the cell at `(2 p0 + 1, 2 p1 + 1, …)`.
116
+ */
117
+ cells: Uint32Array;
118
+ /** The dimension of each cell (the number of its odd coordinates). */
119
+ dims: Uint8Array;
120
+ /** The value of each cell: the smallest value of the pixels containing it. */
121
+ filtrations: Float64Array;
122
+ /** Always `'value'`: the image's own values. */
123
+ scale: 'value';
124
+ }
125
+
126
+ /**
127
+ * A persistence diagram. `pairs[k]` lists the classes of Hₖ as
128
+ * `[birth, death, birth, death, …]`, essential classes with
129
+ * `death = Infinity`, one array per homology dimension from 0 to the highest
130
+ * the call computes (empty arrays included). Pairs of length zero are left
131
+ * out, and with the `minPersistence` option every finite pair with
132
+ * `death − birth <= minPersistence`.
133
+ */
134
+ export interface Diagram {
135
+ /** `pairs[k]`: the pairs of Hₖ, `[birth, death, …]`. */
136
+ pairs: Float64Array[];
137
+ /** The quantity the values measure. */
138
+ scale: Scale;
139
+ /** The coefficient field `Z/coeff` the diagram was computed over. */
140
+ coeff: number;
141
+ }
142
+
143
+ /** The result of a builder's `…Persistence` function: the diagram, and with `complex: true` the complex it was computed from. */
144
+ export interface BuilderPersistence<C extends Complex = Complex> extends Diagram {
145
+ /** The complex, as the builder returns it; present only with `complex: true`. */
146
+ complex?: C;
147
+ }
148
+
149
+ /** Options every builder's `…Persistence` function takes beside the builder's own. */
150
+ export interface BuilderPersistenceOptions {
151
+ /** The prime `p` of the coefficient field `Z/p`, from 2 to `2^31 − 1`. Default 2. */
152
+ coeff?: number;
153
+ /** Also return the complex, as the builder returns it. Default `false`. */
154
+ complex?: boolean;
155
+ /**
156
+ * Leave out the finite pairs with `death − birth <= minPersistence`
157
+ * (GUDHI's `min_persistence`); essential pairs are always kept. A finite
158
+ * number `>= 0`. Default 0: only the pairs of length zero are left out.
159
+ * `1e-12` removes the bars one ulp long that rounding leaves on symmetric
160
+ * input such as a lattice.
161
+ */
162
+ minPersistence?: number;
163
+ }