@topolab/tda 0.0.0-stage → 0.3.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 (90) hide show
  1. package/CHANGELOG.md +82 -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 +696 -0
  7. package/dist/build_info.json +12 -0
  8. package/dist/check.d.ts +118 -0
  9. package/dist/check.d.ts.map +1 -0
  10. package/dist/check.js +298 -0
  11. package/dist/check.js.map +1 -0
  12. package/dist/complex.d.ts +543 -0
  13. package/dist/complex.d.ts.map +1 -0
  14. package/dist/complex.js +712 -0
  15. package/dist/complex.js.map +1 -0
  16. package/dist/diagram.d.ts +116 -0
  17. package/dist/diagram.d.ts.map +1 -0
  18. package/dist/diagram.js +238 -0
  19. package/dist/diagram.js.map +1 -0
  20. package/dist/diagram_of.d.ts +17 -0
  21. package/dist/diagram_of.d.ts.map +1 -0
  22. package/dist/diagram_of.js +40 -0
  23. package/dist/diagram_of.js.map +1 -0
  24. package/dist/experimental.d.ts +14 -0
  25. package/dist/experimental.d.ts.map +1 -0
  26. package/dist/experimental.js +13 -0
  27. package/dist/experimental.js.map +1 -0
  28. package/dist/flat.d.ts +64 -0
  29. package/dist/flat.d.ts.map +1 -0
  30. package/dist/flat.js +158 -0
  31. package/dist/flat.js.map +1 -0
  32. package/dist/index.d.ts +38 -0
  33. package/dist/index.d.ts.map +1 -0
  34. package/dist/index.js +29 -0
  35. package/dist/index.js.map +1 -0
  36. package/dist/ladder/tda_ladder.d.ts +223 -0
  37. package/dist/ladder/tda_ladder.js +1360 -0
  38. package/dist/ladder/tda_ladder_bg.wasm +0 -0
  39. package/dist/ladder/tda_ladder_bg.wasm.d.ts +43 -0
  40. package/dist/ladder.d.ts +306 -0
  41. package/dist/ladder.d.ts.map +1 -0
  42. package/dist/ladder.js +607 -0
  43. package/dist/ladder.js.map +1 -0
  44. package/dist/load.d.ts +53 -0
  45. package/dist/load.d.ts.map +1 -0
  46. package/dist/load.js +173 -0
  47. package/dist/load.js.map +1 -0
  48. package/dist/memory.d.ts +58 -0
  49. package/dist/memory.d.ts.map +1 -0
  50. package/dist/memory.js +2 -0
  51. package/dist/memory.js.map +1 -0
  52. package/dist/persistence.d.ts +349 -0
  53. package/dist/persistence.d.ts.map +1 -0
  54. package/dist/persistence.js +478 -0
  55. package/dist/persistence.js.map +1 -0
  56. package/dist/pkg/tda_wasm.d.ts +13 -0
  57. package/dist/pkg/tda_wasm.js +1900 -0
  58. package/dist/prepared.d.ts +62 -0
  59. package/dist/prepared.d.ts.map +1 -0
  60. package/dist/prepared.js +81 -0
  61. package/dist/prepared.js.map +1 -0
  62. package/dist/source.d.ts +43 -0
  63. package/dist/source.d.ts.map +1 -0
  64. package/dist/source.js +99 -0
  65. package/dist/source.js.map +1 -0
  66. package/dist/tda.wasm +0 -0
  67. package/dist/types.d.ts +146 -0
  68. package/dist/types.d.ts.map +1 -0
  69. package/dist/types.js +2 -0
  70. package/dist/types.js.map +1 -0
  71. package/dist/vineyard.d.ts +278 -0
  72. package/dist/vineyard.d.ts.map +1 -0
  73. package/dist/vineyard.js +236 -0
  74. package/dist/vineyard.js.map +1 -0
  75. package/package.json +77 -4
  76. package/src/check.ts +338 -0
  77. package/src/complex.ts +1179 -0
  78. package/src/diagram.ts +299 -0
  79. package/src/diagram_of.ts +40 -0
  80. package/src/experimental.ts +13 -0
  81. package/src/flat.ts +204 -0
  82. package/src/index.ts +155 -0
  83. package/src/ladder.ts +903 -0
  84. package/src/load.ts +201 -0
  85. package/src/memory.ts +58 -0
  86. package/src/persistence.ts +752 -0
  87. package/src/prepared.ts +111 -0
  88. package/src/source.ts +132 -0
  89. package/src/types.ts +163 -0
  90. package/src/vineyard.ts +463 -0
package/src/complex.ts ADDED
@@ -0,0 +1,1179 @@
1
+ /**
2
+ * The filtered complexes, the shapes some of them are built from, and the
3
+ * persistence of each builder's own complex in one call (internal module;
4
+ * the package root re-exports the API).
5
+ */
6
+ import { call, module } from './load.js';
7
+ import {
8
+ allFinite,
9
+ boolOption,
10
+ f64,
11
+ noNaN,
12
+ finite,
13
+ int,
14
+ intOption,
15
+ isTyped,
16
+ kind,
17
+ nonNegative,
18
+ num,
19
+ options,
20
+ points as checkPoints,
21
+ positive,
22
+ sized,
23
+ u32
24
+ } from './check.js';
25
+ import type { Keys, PointCloud } from './check.js';
26
+ import { diagramOf } from './diagram_of.js';
27
+ import type {
28
+ Complex,
29
+ CubicalComplex,
30
+ DistanceMatrix,
31
+ Grid,
32
+ BuilderPersistence,
33
+ BuilderPersistenceOptions,
34
+ Scale
35
+ } from './types.js';
36
+ import { coeff as checkCoeff, flatTolerance as checkFlatTolerance, minPersistence as checkMinPersistence } from './check.js';
37
+
38
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
39
+ type Raw = any;
40
+
41
+ /** A builder's typed arrays as a {@link Complex} on `scale`. */
42
+ function complexOf(raw: Raw, scale: Scale): Complex {
43
+ return { vertices: raw.vertices, offsets: raw.offsets, filtrations: raw.filtrations, scale };
44
+ }
45
+
46
+ /** Options shared by the `…Persistence` functions: `coeff`, `complex` and `minPersistence`. */
47
+ interface Fused {
48
+ coeff: number;
49
+ complex: boolean;
50
+ minPersistence: number;
51
+ }
52
+
53
+ /** The option keys of {@link BuilderPersistenceOptions}. */
54
+ const FUSED_KEYS: Keys<BuilderPersistenceOptions> = { coeff: true, complex: true, minPersistence: true };
55
+
56
+ function fused(o: Partial<BuilderPersistenceOptions>): Fused {
57
+ return {
58
+ coeff: checkCoeff(o.coeff),
59
+ complex: boolOption(o.complex, 'complex', false),
60
+ minPersistence: checkMinPersistence(o.minPersistence)
61
+ };
62
+ }
63
+
64
+ /**
65
+ * The result of a pipeline call (`{ pairs, simplices?, empty?, … }`) as a
66
+ * diagram with homology up to `top` (without the pairs `minPersistence`
67
+ * leaves out), and the complex (built by `shape`) when asked for.
68
+ */
69
+ function persistenceOf<C extends Complex>(
70
+ raw: Raw,
71
+ scale: Scale,
72
+ f: Fused,
73
+ top: number,
74
+ withComplex: boolean,
75
+ shape: (simplices: Raw) => C
76
+ ): BuilderPersistence<C> {
77
+ const diagram = diagramOf(raw.empty ? new Float64Array(0) : raw.pairs, top, scale, f.coeff, f.minPersistence);
78
+ if (!withComplex) return diagram;
79
+ return { ...diagram, complex: shape(Object.assign({}, raw, raw.simplices ?? emptyComplex())) };
80
+ }
81
+
82
+ function emptyComplex(): Raw {
83
+ return { vertices: new Int32Array(0), offsets: Uint32Array.of(0), filtrations: new Float64Array(0) };
84
+ }
85
+
86
+ /** A non-negative integer that caps the simplex dimension, with a default. */
87
+ function maxSimplexDim(v: unknown, fallback: number, max = 0x7fffffff): number {
88
+ return intOption(v, 'maxSimplexDim', fallback, 0, max);
89
+ }
90
+
91
+ // ---------------------------------------------------------------------------
92
+ // Rips
93
+ // ---------------------------------------------------------------------------
94
+
95
+ /** The number of points of a distance matrix, after its checks. */
96
+ export function distanceMatrix(v: unknown, name: string): number {
97
+ const { distances } = v as DistanceMatrix;
98
+ if (!isTyped(distances, 'Float64Array')) {
99
+ throw new TypeError(`${name}.distances must be a Float64Array, got ${kind(distances)}`);
100
+ }
101
+ const n = Math.round(Math.sqrt(distances.length));
102
+ if (distances.length === 0 || n * n !== distances.length) {
103
+ throw new RangeError(`${name}.distances must hold n × n entries for a positive integer n, got length ${distances.length}`);
104
+ }
105
+ noNaN(distances, `${name}.distances`);
106
+ // The strict lower triangle is what the builders read; the other entries
107
+ // are checked after it, so that no entry of the matrix is negative.
108
+ const sign = (i: number, j: number) => {
109
+ const x = distances[i * n + j]!;
110
+ if (!(x >= 0)) {
111
+ throw new RangeError(`${name}.distances[${i * n + j}] (row ${i}, column ${j}) must be non-negative or Infinity, got ${x}`);
112
+ }
113
+ };
114
+ for (let i = 1; i < n; i++) for (let j = 0; j < i; j++) sign(i, j);
115
+ for (let i = 0; i < n; i++) for (let j = i; j < n; j++) sign(i, j);
116
+ return n;
117
+ }
118
+
119
+ /**
120
+ * Whether the input of a Rips function is a distance matrix, after the type
121
+ * check of either form. A key whose value is `undefined` counts as absent.
122
+ */
123
+ export function isMatrix(v: unknown, name: string): boolean {
124
+ const object = v !== null && typeof v === 'object';
125
+ const coords = object && (v as { coords?: unknown }).coords !== undefined;
126
+ const distances = object && (v as { distances?: unknown }).distances !== undefined;
127
+ if (coords && distances) {
128
+ throw new TypeError(`${name} must be a point cloud { coords, d } or a distance matrix { distances }, not both`);
129
+ }
130
+ if (distances) return true;
131
+ if (!coords) {
132
+ throw new TypeError(
133
+ `${name} must be a point cloud { coords: Float64Array, d: number } or a distance matrix { distances: Float64Array }, got ${kind(v)}`
134
+ );
135
+ }
136
+ return false;
137
+ }
138
+
139
+ /** Options of {@link ripsComplex}. */
140
+ export interface RipsComplexOptions {
141
+ /** Largest edge kept, positive (`Infinity` keeps every pair). Required. */
142
+ maxEdgeLength: number;
143
+ /** Largest simplex dimension, a non-negative integer. Default 3. */
144
+ maxSimplexDim?: number;
145
+ }
146
+
147
+ const RIPS_COMPLEX_KEYS: Keys<RipsComplexOptions> = { maxEdgeLength: true, maxSimplexDim: true };
148
+
149
+ /**
150
+ * The Vietoris–Rips complex of a point cloud or of a distance matrix: every
151
+ * point a vertex at 0, every pair at distance `<= maxEdgeLength` an edge at
152
+ * that distance, every clique of up to `maxSimplexDim + 1` points a simplex
153
+ * at its longest edge. Built by the Rust core (clique enumeration over a
154
+ * sorted neighbour graph); distances in double precision in GUDHI's order,
155
+ * so the values are GUDHI's `Rips_complex`'s, bit for bit. A distance matrix
156
+ * is read in its strict lower triangle, as GUDHI reads it; none of its
157
+ * entries may be NaN or negative (`Infinity` is an absent edge). A point
158
+ * cloud with two points whose squared distance overflows double precision
159
+ * is refused (a `RangeError`: rescale it), and so is an input with both `coords` and
160
+ * `distances`. Complexes above 2^25 simplices are refused (a `RangeError`
161
+ * whose message starts with `input too large:`). Values on the
162
+ * `'edgeLength'` scale.
163
+ */
164
+ export function ripsComplex(points: PointCloud | DistanceMatrix, opts: RipsComplexOptions): Complex {
165
+ module();
166
+ const o = options<RipsComplexOptions>(opts, 'ripsComplex', RIPS_COMPLEX_KEYS);
167
+ const matrix = isMatrix(points, 'points');
168
+ const n = matrix ? distanceMatrix(points, 'points') : checkPoints(points, 'points', { squaredDistances: true });
169
+ const maxEdgeLength = positive(o.maxEdgeLength, 'maxEdgeLength');
170
+ const cap = maxSimplexDim(o.maxSimplexDim, 3);
171
+ return call('ripsComplex', (m) => {
172
+ if (matrix) {
173
+ return complexOf(m.ripsComplexFromMatrixFlat((points as DistanceMatrix).distances, n, maxEdgeLength, cap), 'edgeLength');
174
+ }
175
+ const { coords, d } = points as PointCloud;
176
+ return complexOf(m.ripsComplexFlat(coords, d, maxEdgeLength, cap), 'edgeLength');
177
+ });
178
+ }
179
+
180
+ // ---------------------------------------------------------------------------
181
+ // Čech and Delaunay–Čech
182
+ // ---------------------------------------------------------------------------
183
+
184
+ /** Options of {@link cechComplex}. */
185
+ export interface CechComplexOptions {
186
+ /** Largest radius of a smallest enclosing ball, positive (`Infinity` allowed). Required. */
187
+ maxRadius: number;
188
+ /** Largest simplex dimension, a non-negative integer. Default 3. */
189
+ maxSimplexDim?: number;
190
+ }
191
+
192
+ const CECH_COMPLEX_KEYS: Keys<CechComplexOptions> = { maxRadius: true, maxSimplexDim: true };
193
+
194
+ /**
195
+ * The Čech complex of a point cloud (at least 2 points): every vertex set
196
+ * whose smallest enclosing ball has radius `<= maxRadius`, up to
197
+ * `maxSimplexDim`, valued by that radius (exact geometry; scale
198
+ * `'radius'`). It grows combinatorially; {@link cechPersistence} computes
199
+ * its diagram from the far smaller Delaunay–Čech complex for points in
200
+ * dimension 1 to 3. The output is a filtration {@link persistence} accepts:
201
+ * where the input's ties are not exact in double precision, rounding can put
202
+ * a face a few ulps above a coface, and the builder raises such a coface to
203
+ * its faces' values (a face is never lowered).
204
+ *
205
+ * Complexes above 2^25 simplices are refused while they are built (a
206
+ * `RangeError` whose message starts with `input too large:`). The builder
207
+ * keeps the smallest enclosing ball of every simplex below `maxSimplexDim`
208
+ * for its cofaces, so memory can run out first (`TOO_LARGE`).
209
+ */
210
+ export function cechComplex(points: PointCloud, opts: CechComplexOptions): Complex {
211
+ module();
212
+ const o = options<CechComplexOptions>(opts, 'cechComplex', CECH_COMPLEX_KEYS);
213
+ checkPoints(points, 'points', { min: 2 });
214
+ const maxRadius = positive(o.maxRadius, 'maxRadius');
215
+ const cap = maxSimplexDim(o.maxSimplexDim, 3);
216
+ const { coords, d } = points;
217
+ return call('cechComplex', (m) => complexOf(m.cechComplexFlat(coords, d, maxRadius, cap), 'radius'));
218
+ }
219
+
220
+ /** Options of {@link cechPersistence}. */
221
+ export interface CechPersistenceOptions extends CechComplexOptions, BuilderPersistenceOptions {}
222
+
223
+ const CECH_PERSISTENCE_KEYS: Keys<CechPersistenceOptions> = { ...CECH_COMPLEX_KEYS, ...FUSED_KEYS };
224
+
225
+ /**
226
+ * The persistence of the Čech complex of a point cloud ({@link cechComplex}),
227
+ * built and reduced in one call. For points in dimension 1 to 3 it is
228
+ * computed on the Delaunay–Čech complex, whose diagram is the Čech
229
+ * complex's ([reference](https://topolab.ai/tda/docs/references/#bauer-and-edelsbrunner-2017)), and `complex: true`
230
+ * returns that complex; above dimension 3 on the full Čech complex, whose
231
+ * values are monotone as built (see {@link cechComplex}).
232
+ * Homology up to `maxSimplexDim`; in that top dimension a truncated full
233
+ * Čech complex has classes only the truncation creates, the Delaunay–Čech
234
+ * complex none once `maxSimplexDim` reaches the point dimension.
235
+ */
236
+ export function cechPersistence(points: PointCloud, opts: CechPersistenceOptions): BuilderPersistence {
237
+ module();
238
+ const o = options<CechPersistenceOptions>(opts, 'cechPersistence', CECH_PERSISTENCE_KEYS);
239
+ checkPoints(points, 'points', { min: 2 });
240
+ const maxRadius = positive(o.maxRadius, 'maxRadius');
241
+ const cap = maxSimplexDim(o.maxSimplexDim, 3);
242
+ const f = fused(o);
243
+ const { coords, d } = points;
244
+ return call('cechPersistence', (m) =>
245
+ persistenceOf(m.cechPipeline(coords, d, maxRadius, cap, f.coeff, f.complex), 'radius', f, cap, f.complex,
246
+ (raw) => complexOf(raw, 'radius'))
247
+ );
248
+ }
249
+
250
+ /**
251
+ * What `flatTolerance` did to a cloud: it was projected onto its
252
+ * least-squares line (`rank` 1) or plane (`rank` 2), and no point moved
253
+ * farther than `maxDistance` (input units, computed in double).
254
+ */
255
+ export interface Flattened {
256
+ /** The dimension of the line (1) or plane (2) the points were projected onto. */
257
+ rank: 1 | 2;
258
+ /** The largest distance a point moved. */
259
+ maxDistance: number;
260
+ }
261
+
262
+ /** The complex of {@link alphaComplex} or {@link delaunayCechComplex}. */
263
+ export interface FlattenableComplex extends Complex {
264
+ /** Present only when `flatTolerance` flattened the input: the complex is then that of the projected points. */
265
+ flattened?: Flattened;
266
+ }
267
+
268
+ /** The result of {@link alphaPersistence}. */
269
+ export interface AlphaPersistence extends BuilderPersistence<FlattenableComplex> {
270
+ /** Present only when `flatTolerance` flattened the input. */
271
+ flattened?: Flattened;
272
+ }
273
+
274
+ /** The engine's `flattenedRank` / `flattenedMaxDistance`, or nothing. */
275
+ function flattenedOf(raw: Raw): { flattened?: Flattened } {
276
+ return raw.flattenedRank === undefined ? {} : { flattened: { rank: raw.flattenedRank, maxDistance: raw.flattenedMaxDistance } };
277
+ }
278
+
279
+ /** The engine's "off" for `flatTolerance` (NaN). */
280
+ function tolerance(v: number | undefined): number {
281
+ return v === undefined ? NaN : v;
282
+ }
283
+
284
+ /** Options of {@link delaunayCechComplex}. */
285
+ export interface DelaunayCechComplexOptions {
286
+ /** Largest enclosing-ball radius kept, positive (`Infinity` keeps the whole triangulation). Required. */
287
+ maxRadius: number;
288
+ /** Largest simplex dimension, a non-negative integer. Default 3 (the triangulation has none above the point dimension). */
289
+ maxSimplexDim?: number;
290
+ /**
291
+ * Opt-in flattening, a finite number `>= 0`; default off. A cloud in 2 or
292
+ * 3 dimensions of full exact affine rank whose least-squares line (tried
293
+ * first) or plane moves no point farther than `flatTolerance` times its
294
+ * extent (the largest distance from the centroid) is projected onto it,
295
+ * and the result is the exact Delaunay–Čech complex of the projected
296
+ * points, with `flattened`. Exactly flat input is never changed.
297
+ */
298
+ flatTolerance?: number;
299
+ }
300
+
301
+ const DELAUNAY_CECH_KEYS: Keys<DelaunayCechComplexOptions> = { maxRadius: true, maxSimplexDim: true, flatTolerance: true };
302
+
303
+ /**
304
+ * The Delaunay–Čech complex of points in dimension 1, 2 or 3: every face of
305
+ * the Delaunay triangulation, valued by the radius of the smallest ball
306
+ * enclosing its vertices (for a simplex of both complexes the value
307
+ * {@link cechComplex} gives it, bit for bit; scale `'radius'`). Its diagram
308
+ * is the Čech complex's, from a far smaller complex. Repeated points keep
309
+ * their first copy. Cospherical points are triangulated by exact predicates
310
+ * with a symbolic perturbation of fixed priority, so the complex is a pure
311
+ * function of the input.
312
+ */
313
+ export function delaunayCechComplex(points: PointCloud, opts: DelaunayCechComplexOptions): FlattenableComplex {
314
+ module();
315
+ const o = options<DelaunayCechComplexOptions>(opts, 'delaunayCechComplex', DELAUNAY_CECH_KEYS);
316
+ checkPoints(points, 'points', { dims: [1, 2, 3] });
317
+ const maxRadius = positive(o.maxRadius, 'maxRadius');
318
+ const cap = maxSimplexDim(o.maxSimplexDim, 3);
319
+ const flat = tolerance(checkFlatTolerance(o.flatTolerance));
320
+ const { coords, d } = points;
321
+ return call('delaunayCechComplex', (m) => {
322
+ const raw = m.delaunayCechComplexFlat(coords, d, maxRadius, cap, flat);
323
+ return { ...complexOf(raw, 'radius'), ...flattenedOf(raw) };
324
+ });
325
+ }
326
+
327
+ // ---------------------------------------------------------------------------
328
+ // Alpha
329
+ // ---------------------------------------------------------------------------
330
+
331
+ /** Options of {@link alphaComplex}. */
332
+ export interface AlphaComplexOptions {
333
+ /**
334
+ * The weight of each point, a squared radius (finite, non-negative): the
335
+ * regular triangulation's weight, not a coordinate. Default: all 0, the
336
+ * unweighted alpha complex.
337
+ */
338
+ weights?: Float64Array | number[];
339
+ /** Drop the simplices valued above this squared radius, positive (`Infinity` keeps all). Default `Infinity`. */
340
+ maxSquaredRadius?: number;
341
+ /**
342
+ * Opt-in flattening, a finite number `>= 0`; default off. A cloud of full
343
+ * exact affine rank whose least-squares line (tried first) or plane moves
344
+ * no point farther than `flatTolerance` times its extent (the largest
345
+ * distance from the centroid) is projected onto it, and the result is the
346
+ * exact (weighted) alpha complex of the projected points, weights
347
+ * unchanged, with `flattened`. Exactly flat input is never changed.
348
+ */
349
+ flatTolerance?: number;
350
+ }
351
+
352
+ const ALPHA_COMPLEX_KEYS: Keys<AlphaComplexOptions> = { weights: true, maxSquaredRadius: true, flatTolerance: true };
353
+
354
+ /** `[x, y, z, weight] * n` for the engine, after the checks of the alpha functions. */
355
+ function alphaArgs(points: PointCloud, o: Partial<AlphaComplexOptions>): { coords: Float64Array; cutoff: number; flat: number } {
356
+ const n = checkPoints(points, 'points', { dims: [3] });
357
+ const weights = o.weights === undefined ? null : f64(o.weights, 'weights');
358
+ if (weights !== null) {
359
+ sized(weights.length, n, 'weights', 'one weight per point');
360
+ for (let i = 0; i < n; i++) {
361
+ const w = weights[i]!;
362
+ if (!(w >= 0) || !Number.isFinite(w)) throw new RangeError(`weights[${i}] must be finite and non-negative, got ${w}`);
363
+ }
364
+ }
365
+ // Non-positive is the engine's "no cutoff": an omitted or infinite one.
366
+ const max = o.maxSquaredRadius === undefined ? Infinity : positive(o.maxSquaredRadius, 'maxSquaredRadius');
367
+ const flat = tolerance(checkFlatTolerance(o.flatTolerance));
368
+ const coords = new Float64Array(4 * n);
369
+ for (let i = 0; i < n; i++) {
370
+ coords[4 * i] = points.coords[3 * i]!;
371
+ coords[4 * i + 1] = points.coords[3 * i + 1]!;
372
+ coords[4 * i + 2] = points.coords[3 * i + 2]!;
373
+ coords[4 * i + 3] = weights === null ? 0 : weights[i]!;
374
+ }
375
+ return { coords, cutoff: Number.isFinite(max) ? max : 0, flat };
376
+ }
377
+
378
+ /**
379
+ * The (weighted) alpha complex of points in three dimensions, over their
380
+ * exact regular triangulation: values are squared radii (scale `'squaredRadius'`),
381
+ * a vertex at minus its weight. Of the points at one position the heaviest
382
+ * is the vertex (the smallest index on a tie); the others are hidden, as are
383
+ * points whose power cell is empty. Without a cutoff, near-degenerate input can
384
+ * end with astronomically large values for the last tetrahedra, genuine
385
+ * values but rarely wanted; the filtration is monotone, so a cutoff leaves a
386
+ * closed complex.
387
+ */
388
+ export function alphaComplex(points: PointCloud, opts?: AlphaComplexOptions): FlattenableComplex {
389
+ module();
390
+ const { coords, cutoff, flat } = alphaArgs(points, options<AlphaComplexOptions>(opts, 'alphaComplex', ALPHA_COMPLEX_KEYS));
391
+ return call('alphaComplex', (m) => {
392
+ const raw = m.weightedAlphaComplexFlat(coords, cutoff, flat);
393
+ return { ...complexOf(raw, 'squaredRadius'), ...flattenedOf(raw) };
394
+ });
395
+ }
396
+
397
+ /** Options of {@link alphaPersistence}. */
398
+ export interface AlphaPersistenceOptions extends AlphaComplexOptions, BuilderPersistenceOptions {}
399
+
400
+ const ALPHA_PERSISTENCE_KEYS: Keys<AlphaPersistenceOptions> = { ...ALPHA_COMPLEX_KEYS, ...FUSED_KEYS };
401
+
402
+ /** The persistence of {@link alphaComplex}, built and reduced in one call: homology up to dimension 3. */
403
+ export function alphaPersistence(points: PointCloud, opts?: AlphaPersistenceOptions): AlphaPersistence {
404
+ module();
405
+ const o = options<AlphaPersistenceOptions>(opts, 'alphaPersistence', ALPHA_PERSISTENCE_KEYS);
406
+ const { coords, cutoff, flat } = alphaArgs(points, o);
407
+ const f = fused(o);
408
+ return call('alphaPersistence', (m) => {
409
+ const raw = m.weightedAlphaPipeline(coords, cutoff, f.coeff, f.complex, flat);
410
+ const flattened = flattenedOf(raw);
411
+ const p: AlphaPersistence = persistenceOf(raw, 'squaredRadius', f, 3, f.complex,
412
+ (r) => ({ ...complexOf(r, 'squaredRadius'), ...flattened }));
413
+ return { ...p, ...flattened };
414
+ });
415
+ }
416
+
417
+ /** Options of {@link coupledAlphaComplex}. */
418
+ export interface CoupledAlphaComplexOptions {
419
+ /** One colour per point: 0 for a survivor, 1 for a deleted point. Required. */
420
+ colors: ArrayLike<number>;
421
+ /** Inclusive cutoff on the squared radius, non-negative (0 keeps the vertices and the simplices of coincident points). Default `Infinity`. */
422
+ maxSquaredRadius?: number;
423
+ /** Largest simplex dimension, an integer from 0 to 3. Default 3. */
424
+ maxSimplexDim?: number;
425
+ }
426
+
427
+ const COUPLED_ALPHA_KEYS: Keys<CoupledAlphaComplexOptions> = { colors: true, maxSquaredRadius: true, maxSimplexDim: true };
428
+
429
+ /**
430
+ * The coupled alpha complex of a planar two-colour point cloud: the nerve of
431
+ * the sets `B(p, r) ∩ Vor(p, points of p's colour)` (closed balls cut by
432
+ * each colour's own Voronoi cells) ([reference](https://topolab.ai/tda/docs/references/#reani-and-bobrowski-2021), Def. 3.1). A simplex enters at the smallest squared
433
+ * radius at which its vertices' sets meet (scale `'squaredRadius'`). The
434
+ * simplices whose vertices all have colour 0 form the alpha complex of the
435
+ * survivors, with that complex's values up to rounding, and the whole
436
+ * complex has, at every radius, the homotopy type of the union of all the
437
+ * balls, so the two rows of a commutative ladder come from one call (see
438
+ * https://topolab.ai/tda/docs/guides/coupled-alpha/). Vertex ids are input indices, coincident points
439
+ * included. No flag completion and no perturbation.
440
+ *
441
+ * Bounded by design: at most 24 points and simplices up to dimension 3,
442
+ * each birth found by enumerating every candidate minimizer of a planar
443
+ * convex problem in IEEE binary128 (quadruple precision, in software).
444
+ * Dimension 3 holds the whole nerve for generic input; dimension 2
445
+ * suffices for H₀, H₁ and their inclusion maps.
446
+ * Cell membership uses a relative tolerance of 1e-12 after the input is
447
+ * translated and scaled to unit size.
448
+ *
449
+ * There is no `coupledAlphaPersistence`: the whole complex has the
450
+ * homotopy type of the union of all the balls (the diagram of the planar
451
+ * alpha complex of all the points), and its use is the inclusion of the
452
+ * survivors' subcomplex, which {@link persistence} of either complex does
453
+ * not give.
454
+ */
455
+ export function coupledAlphaComplex(points: PointCloud, opts: CoupledAlphaComplexOptions): Complex {
456
+ module();
457
+ const o = options<CoupledAlphaComplexOptions>(opts, 'coupledAlphaComplex', COUPLED_ALPHA_KEYS);
458
+ const n = checkPoints(points, 'points', { dims: [2] });
459
+ if (n > 24) throw new RangeError(`points must hold at most 24 points, got ${n}`);
460
+ const colors = o.colors;
461
+ if (colors === null || typeof colors !== 'object' || typeof (colors as ArrayLike<number>).length !== 'number') {
462
+ throw new TypeError(`colors must be an array of 0s and 1s, got ${kind(colors)}`);
463
+ }
464
+ sized(colors.length, n, 'colors', 'one colour per point');
465
+ const c = new Float64Array(n);
466
+ for (let i = 0; i < n; i++) {
467
+ const x = colors[i];
468
+ if (typeof x !== 'number') throw new TypeError(`colors[${i}] must be a number, got ${kind(x)}`);
469
+ if (x !== 0 && x !== 1) throw new RangeError(`colors[${i}] must be 0 or 1, got ${x}`);
470
+ c[i] = x;
471
+ }
472
+ const cutoff = o.maxSquaredRadius === undefined ? Infinity : nonNegative(o.maxSquaredRadius, 'maxSquaredRadius');
473
+ const cap = maxSimplexDim(o.maxSimplexDim, 3, 3);
474
+ return call('coupledAlphaComplex', (m) => complexOf(m.coupledAlphaComplex2DFlat(points.coords, c, cutoff, cap), 'squaredRadius'));
475
+ }
476
+
477
+ // ---------------------------------------------------------------------------
478
+ // Witness
479
+ // ---------------------------------------------------------------------------
480
+
481
+ /** Options of {@link witnessComplex}. */
482
+ export interface WitnessComplexOptions {
483
+ /** The number of landmarks, chosen by farthest-point sampling, a positive integer. Required. */
484
+ landmarks: number;
485
+ /** The largest relaxation `a` (a squared length), non-negative. Required. */
486
+ maxSquaredRelaxation: number;
487
+ /** Largest simplex dimension, a non-negative integer. Default 3. */
488
+ maxSimplexDim?: number;
489
+ }
490
+
491
+ const WITNESS_KEYS: Keys<WitnessComplexOptions> = { landmarks: true, maxSquaredRelaxation: true, maxSimplexDim: true };
492
+
493
+ /**
494
+ * The Euclidean (relaxed weak) witness complex of a point cloud ([reference](https://topolab.ai/tda/docs/references/#de-silva-and-carlsson-2004)), relaxed as in ([reference](https://topolab.ai/tda/docs/references/#boissonnat-guibas-and-oudot-2009)), on
495
+ * squared distances: a set of landmarks is a simplex at the smallest
496
+ * `a <= maxSquaredRelaxation` at which it and its faces are a-witnessed, a
497
+ * witness w a-witnessing it when its squared distance to the farthest of
498
+ * them is at most `a` more than its squared distance to the nearest other
499
+ * landmark (scale `'squaredRelaxation'`). Landmarks are chosen by
500
+ * deterministic farthest-point sampling; vertex ids index the landmarks in
501
+ * selection order, not the input points. The strong witness complex is not
502
+ * implemented. A cloud with two points whose squared distance overflows
503
+ * double precision is refused (a `RangeError`: rescale it).
504
+ */
505
+ export function witnessComplex(points: PointCloud, opts: WitnessComplexOptions): Complex {
506
+ module();
507
+ const o = options<WitnessComplexOptions>(opts, 'witnessComplex', WITNESS_KEYS);
508
+ checkPoints(points, 'points', { squaredDistances: true });
509
+ const landmarks = int(o.landmarks, 'landmarks', 1);
510
+ const relaxation = nonNegative(o.maxSquaredRelaxation, 'maxSquaredRelaxation');
511
+ const cap = maxSimplexDim(o.maxSimplexDim, 3);
512
+ const { coords, d } = points;
513
+ return call('witnessComplex', (m) => complexOf(m.euclideanWitnessComplexFlat(coords, d, landmarks, relaxation, cap), 'squaredRelaxation'));
514
+ }
515
+
516
+ // ---------------------------------------------------------------------------
517
+ // k-fold cover
518
+ // ---------------------------------------------------------------------------
519
+
520
+ /**
521
+ * Numerical diagnostics of the k-fold cover builder. `intervalAnomalies`
522
+ * must be 0; anything else means the rhomboid face poset came out
523
+ * incomplete, which cannot happen for input in general position.
524
+ */
525
+ export interface KFoldCoverDiagnostics {
526
+ /** Cells of the order-k mosaic before octahedra are split into tetrahedra. */
527
+ mosaicCells: number;
528
+ /** Non-simplicial (generation-2) cells that had to be split. */
529
+ octahedra: number;
530
+ /** 4-rhomboids discovered by the level sweep (or by the exact enumeration, see `usedExactFallback`). */
531
+ topRhomboids: number;
532
+ /**
533
+ * Mosaic cells (vertices included) whose squared radius came out as
534
+ * `Infinity` from overflow or dependent support, counted over all radii,
535
+ * including cells removed by a cutoff. Finite radii are never clipped.
536
+ */
537
+ clampedCells: number;
538
+ /** Orientation tests that needed exact arithmetic to decide their sign. */
539
+ exactSignFallbacks: number;
540
+ /** Must be 0. See above. */
541
+ intervalAnomalies: number;
542
+ /**
543
+ * True when the level sweep could not be certified and the top rhomboids
544
+ * were found by the exact O(n^5) enumeration instead (a cloud on one
545
+ * sphere to within ~1e-10, say): the exact result, only slower. Exactly
546
+ * cospherical input is refused instead, and above 128 points the call
547
+ * throws rather than run the exact path.
548
+ */
549
+ usedExactFallback: boolean;
550
+ /** 4 · (bounding-box diagonal)², a scale of the input; informational only (no radius is clipped to it). */
551
+ squaredRadiusBound: number;
552
+ }
553
+
554
+ /**
555
+ * The k-fold cover complex: the complex, the k-subset of the input each
556
+ * vertex stands for, and the diagnostics. Vertex ids index `mosaicVertices`,
557
+ * not the input points.
558
+ */
559
+ export interface KFoldCoverComplex extends Complex {
560
+ /** `mosaicVertices[i]`: the sorted k-subset of input indices vertex `i` stands for. */
561
+ mosaicVertices: number[][];
562
+ diagnostics: KFoldCoverDiagnostics;
563
+ }
564
+
565
+ /** Options of {@link kFoldCoverComplex}. */
566
+ export interface KFoldCoverComplexOptions {
567
+ /** The cover multiplicity, a positive integer (at least `k + 3` points are needed). Required. */
568
+ k: number;
569
+ /** Drop the simplices valued above this squared radius, positive (`Infinity` keeps all). Default `Infinity`. */
570
+ maxSquaredRadius?: number;
571
+ /** Largest simplex dimension, a non-negative integer. Default 3 (the mosaic's own dimension). */
572
+ maxSimplexDim?: number;
573
+ }
574
+
575
+ const KFOLD_COMPLEX_KEYS: Keys<KFoldCoverComplexOptions> = { k: true, maxSquaredRadius: true, maxSimplexDim: true };
576
+
577
+ function kFoldArgs(points: PointCloud, o: Partial<KFoldCoverComplexOptions>): { k: number; cutoff: number; cap: number } {
578
+ const n = checkPoints(points, 'points', { dims: [3] });
579
+ const k = int(o.k, 'k', 1);
580
+ if (n < k + 3) throw new RangeError(`points must hold at least k + 3 points (k = ${k}), got ${n}`);
581
+ const max = o.maxSquaredRadius === undefined ? Infinity : positive(o.maxSquaredRadius, 'maxSquaredRadius');
582
+ return { k, cutoff: Number.isFinite(max) ? max : 0, cap: maxSimplexDim(o.maxSimplexDim, 3) };
583
+ }
584
+
585
+ function kFoldOf(raw: Raw): KFoldCoverComplex {
586
+ const flat: Int32Array = raw.mosaicVertices;
587
+ const width: number = raw.mosaicWidth;
588
+ const count: number = raw.mosaicCount;
589
+ const offsets: Uint32Array | undefined = raw.mosaicOffsets;
590
+ const mosaicVertices: number[][] = [];
591
+ for (let i = 0; i < count; i++) {
592
+ const a = offsets ? offsets[i]! : i * width;
593
+ const b = offsets ? offsets[i + 1]! : a + width;
594
+ mosaicVertices.push(Array.from(flat.subarray(a, b)));
595
+ }
596
+ return {
597
+ ...complexOf(raw, 'squaredRadius'),
598
+ mosaicVertices,
599
+ diagnostics: {
600
+ mosaicCells: raw.numMosaicCells,
601
+ octahedra: raw.numOctahedra,
602
+ topRhomboids: raw.numTopRhomboids,
603
+ clampedCells: raw.numClampedCells,
604
+ exactSignFallbacks: raw.numExactSignFallbacks,
605
+ intervalAnomalies: raw.numIntervalAnomalies,
606
+ usedExactFallback: raw.usedExactFallback,
607
+ squaredRadiusBound: raw.squaredRadiusBound
608
+ }
609
+ };
610
+ }
611
+
612
+ /**
613
+ * The k-fold cover complex of unweighted points in three dimensions: the
614
+ * order-k Delaunay mosaic filtered by the squared radius function (scale
615
+ * `'squaredRadius'`), the exact nerve of the k-fold cover, so its
616
+ * persistence is the k-fold cover's ([reference](https://topolab.ai/tda/docs/references/#edelsbrunner-and-osang-2018)). `k = 1` is the
617
+ * alpha complex. The input must be genuinely three-dimensional and must not
618
+ * repeat a point; exactly cospherical input that makes two order-k sites
619
+ * coincide (an integer grid from `k = 2`) is refused: perturb it. The mosaic
620
+ * is a pure function of the input.
621
+ */
622
+ export function kFoldCoverComplex(points: PointCloud, opts: KFoldCoverComplexOptions): KFoldCoverComplex {
623
+ module();
624
+ const { k, cutoff, cap } = kFoldArgs(points, options<KFoldCoverComplexOptions>(opts, 'kFoldCoverComplex', KFOLD_COMPLEX_KEYS));
625
+ return call('kFoldCoverComplex', (m) => kFoldOf(m.kFoldCoverComplexFlat(points.coords, k, cutoff, cap)));
626
+ }
627
+
628
+ /** Options of {@link kFoldCoverPersistence}. */
629
+ export interface KFoldCoverPersistenceOptions extends KFoldCoverComplexOptions, BuilderPersistenceOptions {}
630
+
631
+ const KFOLD_PERSISTENCE_KEYS: Keys<KFoldCoverPersistenceOptions> = { ...KFOLD_COMPLEX_KEYS, ...FUSED_KEYS };
632
+
633
+ /** The persistence of {@link kFoldCoverComplex}, built and reduced in one call: homology up to `maxSimplexDim`. */
634
+ export function kFoldCoverPersistence(points: PointCloud, opts: KFoldCoverPersistenceOptions): BuilderPersistence<KFoldCoverComplex> {
635
+ module();
636
+ const o = options<KFoldCoverPersistenceOptions>(opts, 'kFoldCoverPersistence', KFOLD_PERSISTENCE_KEYS);
637
+ const { k, cutoff, cap } = kFoldArgs(points, o);
638
+ const f = fused(o);
639
+ return call('kFoldCoverPersistence', (m) =>
640
+ persistenceOf(m.kFoldCoverPipeline(points.coords, k, cutoff, cap, f.coeff, f.complex), 'squaredRadius', f, cap,
641
+ f.complex, kFoldOf)
642
+ );
643
+ }
644
+
645
+ // ---------------------------------------------------------------------------
646
+ // Ellipsoids
647
+ // ---------------------------------------------------------------------------
648
+
649
+ /**
650
+ * The semi-axes of the ellipsoids: a tangent-to-normal ratio `q >= 1`
651
+ * ([reference](https://topolab.ai/tda/docs/references/#canova-et-al), §2.1; the `d − 1` tangent semi-axes have length 1, the
652
+ * normal one `1/q`), or `'pca'`, the semi-axes from the normalized local
653
+ * singular values with a 1e-4 floor (the paper's Appendix 8.1).
654
+ */
655
+ export type EllipsoidAxes = number | 'pca';
656
+
657
+ /** Options of {@link ellipsoids}, shared by the ellipsoid complexes. */
658
+ export interface EllipsoidOptions {
659
+ /** The local PCA neighbourhood size, an integer `>= 2` (it counts the point itself and is clamped to the number of points). Required. */
660
+ neighbors: number;
661
+ /** The semi-axes: a ratio `>= 1` or `'pca'`. Required. */
662
+ axes: EllipsoidAxes;
663
+ }
664
+
665
+ const ELLIPSOID_KEYS: Keys<EllipsoidOptions> = { neighbors: true, axes: true };
666
+
667
+ /** The engine's axes ratio (`0` selects `'pca'`), after the checks of the ellipsoid functions. */
668
+ function ellipsoidArgs(points: PointCloud, o: Partial<EllipsoidOptions>): { neighbors: number; ratio: number } {
669
+ checkPoints(points, 'points', { dims: [2, 3], min: 2, squaredDistances: true });
670
+ const neighbors = int(o.neighbors, 'neighbors', 2);
671
+ if (o.axes === 'pca') return { neighbors, ratio: 0 };
672
+ if (typeof o.axes !== 'number') throw new TypeError(`axes must be a number or 'pca', got ${kind(o.axes)}`);
673
+ if (!Number.isFinite(o.axes) || o.axes < 1) throw new RangeError(`axes must be a finite ratio >= 1 or 'pca', got ${o.axes}`);
674
+ return { neighbors, ratio: o.axes };
675
+ }
676
+
677
+ /**
678
+ * The ellipsoid fitted at one point, for drawing. At value `f` of
679
+ * {@link ellipsoidRipsComplex} the ellipsoid has semi-axes
680
+ * `(f / 2) · semiAxes` along the rows of `frame`; at value `r` of
681
+ * {@link ellipsoidCechComplex}, `r · semiAxes`.
682
+ */
683
+ export interface EllipsoidGeometry {
684
+ /** The centre: the input point itself, not the neighbourhood mean. */
685
+ center: number[];
686
+ /** Orthonormal local frame, one row per principal axis, in descending order of local variance; `frame[0]` is the dominant (tangent) direction. */
687
+ frame: number[][];
688
+ /** The semi-axes at unit scale: descending, `semiAxes[0] === 1`. */
689
+ semiAxes: number[];
690
+ }
691
+
692
+ /**
693
+ * The ellipsoids the two ellipsoid complexes fit at every point (the same
694
+ * fitting, so a drawing matches the complex), for renderers that draw them.
695
+ */
696
+ export function ellipsoids(points: PointCloud, opts: EllipsoidOptions): EllipsoidGeometry[] {
697
+ module();
698
+ const { neighbors, ratio } = ellipsoidArgs(points, options<EllipsoidOptions>(opts, 'ellipsoids', ELLIPSOID_KEYS));
699
+ const { coords, d } = points;
700
+ const flat: Float64Array = call('ellipsoids', (m) => m.computeEllipsoidGeometry(coords, d, neighbors, ratio));
701
+ const stride = 2 * d + d * d;
702
+ const out: EllipsoidGeometry[] = [];
703
+ for (let i = 0; i < flat.length / stride; i++) {
704
+ let at = i * stride;
705
+ const center: number[] = [];
706
+ for (let c = 0; c < d; c++) center.push(flat[at++]!);
707
+ const frame: number[][] = [];
708
+ for (let a = 0; a < d; a++) {
709
+ const row: number[] = [];
710
+ for (let c = 0; c < d; c++) row.push(flat[at++]!);
711
+ frame.push(row);
712
+ }
713
+ const semiAxes: number[] = [];
714
+ for (let c = 0; c < d; c++) semiAxes.push(flat[at++]!);
715
+ out.push({ center, frame, semiAxes });
716
+ }
717
+ return out;
718
+ }
719
+
720
+ /** Options of {@link ellipsoidRipsComplex}. */
721
+ export interface EllipsoidRipsComplexOptions extends EllipsoidOptions {
722
+ /** Drop the simplices valued above this edge length, positive (`Infinity` keeps all). Default `Infinity`. */
723
+ maxEdgeLength?: number;
724
+ /** Largest simplex dimension, a non-negative integer. Default 2. */
725
+ maxSimplexDim?: number;
726
+ }
727
+
728
+ const ELLIPSOID_RIPS_COMPLEX_KEYS: Keys<EllipsoidRipsComplexOptions> = { ...ELLIPSOID_KEYS, maxEdgeLength: true, maxSimplexDim: true };
729
+
730
+ /**
731
+ * The Rips-type ellipsoid complex of points in two or three dimensions
732
+ * ([reference](https://topolab.ai/tda/docs/references/#canova-et-al)): each point
733
+ * gets an ellipsoid from a local PCA frame, an edge appears when two
734
+ * ellipsoids first touch, and higher simplices come from flag expansion. A
735
+ * flag complex, as the paper builds it (Definition 2.2), not a nerve. Values
736
+ * are twice the birth radius, on the Rips scale (`'edgeLength'`), so
737
+ * `axes: 1` (balls) reproduces {@link ripsComplex}.
738
+ *
739
+ * Complexes above 2^25 simplices are refused with a `RangeError` whose
740
+ * message starts with `input too large:`. Without `maxEdgeLength`, or with
741
+ * one at which the centroid of the points lies in every ellipsoid (every
742
+ * pair is then an edge), the count of every set of at most
743
+ * `maxSimplexDim + 1` points is checked before any pair is solved.
744
+ * Otherwise, when the vertices and edges alone exceed the limit, the pairs
745
+ * stop at the first edge past it; when only the higher cliques do, they
746
+ * are refused while they are enumerated.
747
+ */
748
+ export function ellipsoidRipsComplex(points: PointCloud, opts: EllipsoidRipsComplexOptions): Complex {
749
+ module();
750
+ const o = options<EllipsoidRipsComplexOptions>(opts, 'ellipsoidRipsComplex', ELLIPSOID_RIPS_COMPLEX_KEYS);
751
+ const { neighbors, ratio } = ellipsoidArgs(points, o);
752
+ const cutoff = o.maxEdgeLength === undefined ? 0 : positive(o.maxEdgeLength, 'maxEdgeLength');
753
+ const cap = maxSimplexDim(o.maxSimplexDim, 2);
754
+ const { coords, d } = points;
755
+ return call('ellipsoidRipsComplex', (m) => complexOf(m.ellipsoidRipsComplexFlat(coords, d, neighbors, ratio, cap, cutoff), 'edgeLength'));
756
+ }
757
+
758
+ /** Options of {@link ellipsoidRipsPersistence}. */
759
+ export interface EllipsoidRipsPersistenceOptions extends EllipsoidRipsComplexOptions, BuilderPersistenceOptions {}
760
+
761
+ const ELLIPSOID_RIPS_PERSISTENCE_KEYS: Keys<EllipsoidRipsPersistenceOptions> = { ...ELLIPSOID_RIPS_COMPLEX_KEYS, ...FUSED_KEYS };
762
+
763
+ /** The persistence of {@link ellipsoidRipsComplex}, built and reduced in one call: homology up to `maxSimplexDim`. */
764
+ export function ellipsoidRipsPersistence(points: PointCloud, opts: EllipsoidRipsPersistenceOptions): BuilderPersistence {
765
+ module();
766
+ const o = options<EllipsoidRipsPersistenceOptions>(opts, 'ellipsoidRipsPersistence', ELLIPSOID_RIPS_PERSISTENCE_KEYS);
767
+ const { neighbors, ratio } = ellipsoidArgs(points, o);
768
+ const cutoff = o.maxEdgeLength === undefined ? 0 : positive(o.maxEdgeLength, 'maxEdgeLength');
769
+ const cap = maxSimplexDim(o.maxSimplexDim, 2);
770
+ const f = fused(o);
771
+ const { coords, d } = points;
772
+ return call('ellipsoidRipsPersistence', (m) =>
773
+ persistenceOf(m.ellipsoidRipsPipeline(coords, d, neighbors, ratio, cap, cutoff, f.coeff, f.complex), 'edgeLength',
774
+ f, cap, f.complex, (raw) => complexOf(raw, 'edgeLength'))
775
+ );
776
+ }
777
+
778
+ /** Options of {@link ellipsoidCechComplex}. */
779
+ export interface EllipsoidCechComplexOptions extends EllipsoidOptions {
780
+ /** Drop the simplices valued above this radius, positive (`Infinity` keeps all). Default `Infinity`; without one every triple reaches the solver, so pass one. */
781
+ maxRadius?: number;
782
+ /** Largest simplex dimension, a non-negative integer. Default 2. */
783
+ maxSimplexDim?: number;
784
+ }
785
+
786
+ const ELLIPSOID_CECH_COMPLEX_KEYS: Keys<EllipsoidCechComplexOptions> = { ...ELLIPSOID_KEYS, maxRadius: true, maxSimplexDim: true };
787
+
788
+ /**
789
+ * The ellipsoidal Čech complex, a nerve ([reference](https://topolab.ai/tda/docs/references/#giunti-hill-and-ye)): the ellipsoids of {@link ellipsoidRipsComplex}, but a simplex enters
790
+ * only when the ellipsoids of all its vertices share a point, at the
791
+ * smallest radius at which they do (scale `'radius'`). The ellipsoids are
792
+ * convex, so the cover is good and the nerve lemma applies: its persistence
793
+ * is the persistence of the growing union of ellipsoids. It is a subcomplex
794
+ * of {@link ellipsoidRipsComplex} on the same input, each shared simplex
795
+ * entering no earlier here (at half the value, on the radius scale), and
796
+ * `axes: 1` reproduces {@link cechComplex}, simplex for simplex, with
797
+ * values equal to within a few ulps (measured to 1.8e-16 in 2D and 3.0e-16
798
+ * in 3D).
799
+ *
800
+ * Complexes above 2^25 simplices are refused while they are built (a
801
+ * `RangeError` whose message starts with `input too large:`). Without
802
+ * `maxRadius`, or with one at which the centroid of the points lies in
803
+ * every ellipsoid, the complex is every set of at most `maxSimplexDim + 1`
804
+ * points, and that count is checked before anything is solved.
805
+ */
806
+ export function ellipsoidCechComplex(points: PointCloud, opts: EllipsoidCechComplexOptions): Complex {
807
+ module();
808
+ const o = options<EllipsoidCechComplexOptions>(opts, 'ellipsoidCechComplex', ELLIPSOID_CECH_COMPLEX_KEYS);
809
+ const { neighbors, ratio } = ellipsoidArgs(points, o);
810
+ const cutoff = o.maxRadius === undefined ? 0 : positive(o.maxRadius, 'maxRadius');
811
+ const cap = maxSimplexDim(o.maxSimplexDim, 2);
812
+ const { coords, d } = points;
813
+ return call('ellipsoidCechComplex', (m) => complexOf(m.ellipsoidCechComplexFlat(coords, d, neighbors, ratio, cap, cutoff), 'radius'));
814
+ }
815
+
816
+ /** Options of {@link ellipsoidCechPersistence}. */
817
+ export interface EllipsoidCechPersistenceOptions extends EllipsoidCechComplexOptions, BuilderPersistenceOptions {}
818
+
819
+ const ELLIPSOID_CECH_PERSISTENCE_KEYS: Keys<EllipsoidCechPersistenceOptions> = { ...ELLIPSOID_CECH_COMPLEX_KEYS, ...FUSED_KEYS };
820
+
821
+ /** The persistence of {@link ellipsoidCechComplex}, built and reduced in one call: homology up to `maxSimplexDim`. */
822
+ export function ellipsoidCechPersistence(points: PointCloud, opts: EllipsoidCechPersistenceOptions): BuilderPersistence {
823
+ module();
824
+ const o = options<EllipsoidCechPersistenceOptions>(opts, 'ellipsoidCechPersistence', ELLIPSOID_CECH_PERSISTENCE_KEYS);
825
+ const { neighbors, ratio } = ellipsoidArgs(points, o);
826
+ const cutoff = o.maxRadius === undefined ? 0 : positive(o.maxRadius, 'maxRadius');
827
+ const cap = maxSimplexDim(o.maxSimplexDim, 2);
828
+ const f = fused(o);
829
+ const { coords, d } = points;
830
+ return call('ellipsoidCechPersistence', (m) =>
831
+ persistenceOf(m.ellipsoidCechPipeline(coords, d, neighbors, ratio, cap, cutoff, f.coeff, f.complex), 'radius', f,
832
+ cap, f.complex, (raw) => complexOf(raw, 'radius'))
833
+ );
834
+ }
835
+
836
+ // ---------------------------------------------------------------------------
837
+ // Wings
838
+ // ---------------------------------------------------------------------------
839
+
840
+ /** Options of {@link wings}, shared by the wing complex. */
841
+ export interface WingOptions {
842
+ /** The spine ratio q (spine half-length over wing length), in [0, 1]. Required. */
843
+ q: number;
844
+ /** The wing angle θ, in (0, π/2]. Required. */
845
+ theta: number;
846
+ /**
847
+ * The unit normal at every point, `[x0, y0, x1, y1, …]`, or the number of
848
+ * nearest neighbours (an integer `>= 2`) from which to estimate them by an
849
+ * osculating-circle fit. Required.
850
+ */
851
+ normals: number | Float64Array | number[];
852
+ }
853
+
854
+ const WING_KEYS: Keys<WingOptions> = { q: true, theta: true, normals: true };
855
+
856
+ /** The engine's `normals` (`[k]` or the 2n normals), after the checks of the wing functions. */
857
+ function wingArgs(points: PointCloud, o: Partial<WingOptions>): { q: number; theta: number; normals: Float64Array } {
858
+ const n = checkPoints(points, 'points', { dims: [2], min: 2 });
859
+ const q = num(o.q, 'q');
860
+ if (!(q >= 0 && q <= 1)) throw new RangeError(`q must lie in [0, 1], got ${q}`);
861
+ const theta = num(o.theta, 'theta');
862
+ if (!(theta > 0 && theta <= Math.PI / 2)) throw new RangeError(`theta must lie in (0, π/2], got ${theta}`);
863
+ if (typeof o.normals === 'number') return { q, theta, normals: Float64Array.of(int(o.normals, 'normals', 2)) };
864
+ if (o.normals === undefined) throw new TypeError('normals must be a neighbour count or the unit normals, got undefined');
865
+ const normals = f64(o.normals, 'normals');
866
+ sized(normals.length, 2 * n, 'normals', 'two coordinates per point');
867
+ allFinite(normals, 'normals');
868
+ return { q, theta, normals };
869
+ }
870
+
871
+ /**
872
+ * How the unit normal α a wing was built from was obtained:
873
+ * `'supplied'` (the caller's, normalised), `'osculating'` (an
874
+ * osculating-circle fit on the k nearest neighbours ([reference](https://topolab.ai/tda/docs/references/#weng-and-zhao-2026), Eq. 3.1)), `'tangent'` (the fit was singular or its radius exceeded 1e6 times
875
+ * the local scale, so the 90° rotation of the PCA tangent pointing away from
876
+ * the neighbourhood centroid), or `'isolated'` (no neighbours: `+e_x`, a
877
+ * placeholder).
878
+ */
879
+ export type WingNormalSource = 'supplied' | 'osculating' | 'tangent' | 'isolated';
880
+
881
+ const WING_NORMAL_SOURCES: WingNormalSource[] = ['supplied', 'osculating', 'tangent', 'isolated'];
882
+
883
+ /**
884
+ * One wing of the wing complex, for drawing; the same normals the complex
885
+ * uses, so a drawing matches the diagram. Estimated normals carry the
886
+ * failure modes the source paper does not address (it works with exact
887
+ * normals): at an inflection the wing can point the wrong way, noise can
888
+ * reverse a wing, and k has to sit between the noise and the feature scale.
889
+ */
890
+ export interface WingGeometry {
891
+ /** The sample point, copied through. */
892
+ point: number[];
893
+ /** The unit normal α (Eq. 3.1) the wing was built from. */
894
+ normal: number[];
895
+ /** Where `normal` came from. */
896
+ normalSource: WingNormalSource;
897
+ /** Radius of the fitted osculating circle, `1/|κ|`; `Infinity` for supplied normals or a singular fit. */
898
+ curvatureRadius: number;
899
+ /** Mean distance to the k nearest neighbours, the scale the curvature clamp compares against; `Infinity` for supplied normals. */
900
+ neighborhoodScale: number;
901
+ /**
902
+ * The wing polygon at unit scale: six offsets from `point`, in the order
903
+ * A, B, C, D, C′, B′ (the concave hexagon of the paper's Eqs. 3.2–3.4). At
904
+ * scale ε vertex `v` is `point[c] + ε · outline[v][c]`.
905
+ */
906
+ outline: number[][];
907
+ }
908
+
909
+ /** The wings {@link wingComplex} builds, for renderers that draw them. */
910
+ export function wings(points: PointCloud, opts: WingOptions): WingGeometry[] {
911
+ module();
912
+ const { q, theta, normals } = wingArgs(points, options<WingOptions>(opts, 'wings', WING_KEYS));
913
+ const coords = points.coords;
914
+ const flat: Float64Array = call('wings', (m) => m.computeWingGeometry(coords, q, theta, normals));
915
+ const stride = 19;
916
+ const out: WingGeometry[] = [];
917
+ for (let i = 0; i < flat.length / stride; i++) {
918
+ let at = i * stride;
919
+ const point = [flat[at++]!, flat[at++]!];
920
+ const normal = [flat[at++]!, flat[at++]!];
921
+ const code = flat[at++]!;
922
+ const normalSource = WING_NORMAL_SOURCES[code];
923
+ if (normalSource === undefined) throw new Error(`unknown normal provenance code ${code}`);
924
+ const curvatureRadius = flat[at++]!;
925
+ const neighborhoodScale = flat[at++]!;
926
+ const outline: number[][] = [];
927
+ for (let v = 0; v < 6; v++) outline.push([flat[at++]!, flat[at++]!]);
928
+ out.push({ point, normal, normalSource, curvatureRadius, neighborhoodScale, outline });
929
+ }
930
+ return out;
931
+ }
932
+
933
+ /** Options of {@link wingComplex}. */
934
+ export interface WingComplexOptions extends WingOptions {
935
+ /** Drop the edges that enter above this ε, positive. Default `Infinity`. */
936
+ maxEpsilon?: number;
937
+ /** Largest simplex dimension, a non-negative integer. Default 3. */
938
+ maxSimplexDim?: number;
939
+ }
940
+
941
+ const WING_COMPLEX_KEYS: Keys<WingComplexOptions> = { ...WING_KEYS, maxEpsilon: true, maxSimplexDim: true };
942
+
943
+ /**
944
+ * The curvature-adaptive wing complex of a planar point cloud, a flag
945
+ * complex (not a nerve) ([reference](https://topolab.ai/tda/docs/references/#weng-and-zhao-2026)). Pair
946
+ * births are analytic; the 1-skeleton is expanded to a flag complex by the
947
+ * Rust core. Values on the wing scale ε (`'epsilon'`).
948
+ */
949
+ export function wingComplex(points: PointCloud, opts: WingComplexOptions): Complex {
950
+ module();
951
+ const o = options<WingComplexOptions>(opts, 'wingComplex', WING_COMPLEX_KEYS);
952
+ const { q, theta, normals } = wingArgs(points, o);
953
+ const maxEpsilon = o.maxEpsilon === undefined ? Infinity : positive(o.maxEpsilon, 'maxEpsilon');
954
+ const cap = maxSimplexDim(o.maxSimplexDim, 3);
955
+ return call('wingComplex', (m) => complexOf(m.wingComplexFlat(points.coords, q, theta, normals, cap, maxEpsilon), 'epsilon'));
956
+ }
957
+
958
+ /** Options of {@link wingPersistence}. */
959
+ export interface WingPersistenceOptions extends WingComplexOptions, BuilderPersistenceOptions {}
960
+
961
+ const WING_PERSISTENCE_KEYS: Keys<WingPersistenceOptions> = { ...WING_COMPLEX_KEYS, ...FUSED_KEYS };
962
+
963
+ /** The persistence of {@link wingComplex}, built and reduced in one call: homology up to `maxSimplexDim`. */
964
+ export function wingPersistence(points: PointCloud, opts: WingPersistenceOptions): BuilderPersistence {
965
+ module();
966
+ const o = options<WingPersistenceOptions>(opts, 'wingPersistence', WING_PERSISTENCE_KEYS);
967
+ const { q, theta, normals } = wingArgs(points, o);
968
+ const maxEpsilon = o.maxEpsilon === undefined ? Infinity : positive(o.maxEpsilon, 'maxEpsilon');
969
+ const cap = maxSimplexDim(o.maxSimplexDim, 3);
970
+ const f = fused(o);
971
+ return call('wingPersistence', (m) =>
972
+ persistenceOf(m.wingPipeline(points.coords, q, theta, normals, cap, maxEpsilon, f.coeff, f.complex), 'epsilon',
973
+ f, cap, f.complex, (raw) => complexOf(raw, 'epsilon'))
974
+ );
975
+ }
976
+
977
+ // ---------------------------------------------------------------------------
978
+ // Box filtration
979
+ // ---------------------------------------------------------------------------
980
+
981
+ /** Numerical diagnostics of the box filtration's growth engine. `iterationCapHits` must be 0. */
982
+ export interface BoxFiltrationDiagnostics {
983
+ /** Growth subproblems solved: `numBoxes · numSteps`. */
984
+ expansions: number;
985
+ /** Steepest-descent moves summed over all of them; a cost measure. */
986
+ descentSteps: number;
987
+ /** Must be 0: a subproblem that stalled numerically, whose box may be smaller than the paper's rule prescribes. */
988
+ iterationCapHits: number;
989
+ }
990
+
991
+ /** A box: its lower and its upper corner. */
992
+ export interface BoxExtent {
993
+ /** Lower corner, one coordinate per axis. */
994
+ lower: number[];
995
+ /** Upper corner, one coordinate per axis. */
996
+ upper: number[];
997
+ }
998
+
999
+ /**
1000
+ * The box filtration: the complex (vertex `i` is the box grown from point
1001
+ * `i`; values exactly the grid `{0, stepSize, …, numSteps · stepSize}`),
1002
+ * the grid, the diagnostics and, on request, the grown boxes.
1003
+ */
1004
+ export interface BoxFiltration extends Complex {
1005
+ /** m: the number of growth steps taken. */
1006
+ numSteps: number;
1007
+ /** π: the growth increment and the grid spacing. */
1008
+ stepSize: number;
1009
+ /** The growth aggressiveness the boxes were grown with. */
1010
+ growth: number;
1011
+ /** The last step at which an edge entered: the last interesting scale. */
1012
+ maxBirthStep: number;
1013
+ /** Edges of the 1-skeleton, before the dimension cap. */
1014
+ numEdges: number;
1015
+ /** With `boxes: true`, `boxes[step][i]`: box `i` at value `step · stepSize`. */
1016
+ boxes?: BoxExtent[][];
1017
+ diagnostics: BoxFiltrationDiagnostics;
1018
+ }
1019
+
1020
+ /** Options of {@link boxFiltration}. */
1021
+ export interface BoxFiltrationOptions {
1022
+ /** π > 0, finite: the growth increment and the grid of values. Required. */
1023
+ stepSize: number;
1024
+ /**
1025
+ * The growth aggressiveness, in [0, 1]: 0 never grows (the discrete
1026
+ * complex); 1 grows every box to its whole neighbourhood (the ℓ∞ Rips
1027
+ * filtration on the grid). The paper's experiments use about 0.5. Required.
1028
+ */
1029
+ growth: number;
1030
+ /** Stop after this many steps, a positive integer. Default: the paper's m, the first step whose neighbourhood covers the whole cloud. */
1031
+ maxSteps?: number;
1032
+ /** Largest simplex dimension, a non-negative integer. Default 3. */
1033
+ maxSimplexDim?: number;
1034
+ /**
1035
+ * Also return every box at every step, `(numSteps + 1) · n` records.
1036
+ * Default `false`. The build holds those boxes either way, so the step
1037
+ * limit of {@link boxFiltration} applies with `false` too.
1038
+ */
1039
+ boxes?: boolean;
1040
+ }
1041
+
1042
+ const BOX_KEYS: Keys<BoxFiltrationOptions> = { stepSize: true, growth: true, maxSteps: true, maxSimplexDim: true, boxes: true };
1043
+
1044
+ function boxArgs(points: PointCloud, o: Partial<BoxFiltrationOptions>) {
1045
+ checkPoints(points, 'points', { dims: [2, 3] });
1046
+ const stepSize = finite(o.stepSize, 'stepSize');
1047
+ if (!(stepSize > 0)) throw new RangeError(`stepSize must be positive, got ${stepSize}`);
1048
+ const growth = num(o.growth, 'growth');
1049
+ if (!(growth >= 0 && growth <= 1)) throw new RangeError(`growth must lie in [0, 1], got ${growth}`);
1050
+ // 0 is the engine's "the paper's m"
1051
+ const maxSteps = o.maxSteps === undefined ? 0 : int(o.maxSteps, 'maxSteps', 1);
1052
+ return { stepSize, growth, maxSteps, cap: maxSimplexDim(o.maxSimplexDim, 3), boxes: boolOption(o.boxes, 'boxes', false) };
1053
+ }
1054
+
1055
+ function boxOf(d: number, withBoxes: boolean): (raw: Raw) => BoxFiltration {
1056
+ return (raw) => {
1057
+ let boxes: BoxExtent[][] | undefined;
1058
+ if (withBoxes) {
1059
+ const extents: Float64Array = raw.boxExtents;
1060
+ boxes = [];
1061
+ let at = 0;
1062
+ for (let step = 0; step <= raw.numSteps; step++) {
1063
+ const perStep: BoxExtent[] = [];
1064
+ for (let box = 0; box < raw.numBoxes; box++) {
1065
+ const lower = Array.from(extents.subarray(at, at + d));
1066
+ const upper = Array.from(extents.subarray(at + d, at + 2 * d));
1067
+ at += 2 * d;
1068
+ perStep.push({ lower, upper });
1069
+ }
1070
+ boxes.push(perStep);
1071
+ }
1072
+ }
1073
+ return {
1074
+ ...complexOf(raw, 'growthRadius'),
1075
+ numSteps: raw.numSteps,
1076
+ stepSize: raw.stepSize,
1077
+ growth: raw.alpha,
1078
+ maxBirthStep: raw.maxBirthStep,
1079
+ numEdges: raw.numEdges,
1080
+ ...(boxes !== undefined ? { boxes } : {}),
1081
+ diagnostics: {
1082
+ expansions: raw.numExpansions,
1083
+ descentSteps: raw.numDescentSteps,
1084
+ iterationCapHits: raw.numIterationCapHits
1085
+ }
1086
+ };
1087
+ };
1088
+ }
1089
+
1090
+ /**
1091
+ * The box filtration of points in two or three dimensions, a nerve
1092
+ * ([reference](https://topolab.ai/tda/docs/references/#alvarado-gupta-and-krishnamoorthy)): every point starts
1093
+ * as a degenerate box and grows, a step at a time, inside the ℓ∞ ball of
1094
+ * radius `j · stepSize` around itself (scale `'growthRadius'`), following
1095
+ * the paper's rule: growth is worth taking when it covers other points (each
1096
+ * worth `growth`) for less than it costs in added width (each unit worth
1097
+ * `1 − growth`). Simplices enter when their boxes first intersect; boxes
1098
+ * have the Helly property, so the flag complex of the intersection graph is
1099
+ * the nerve and the nerve theorem applies.
1100
+ *
1101
+ * Every value is a multiple of `stepSize`: compare diagrams only at equal
1102
+ * `stepSize`. Deterministic, bit for bit: the steps are integer and the
1103
+ * intersection tests exact. Duplicate, collinear and coincident points are
1104
+ * accepted.
1105
+ *
1106
+ * The build holds every box at every step, whether or not `boxes` returns
1107
+ * them: `(numSteps + 1) · n · 2d` box coordinates of 2^28 or more are
1108
+ * refused, with `boxes` `true` or `false`, by a `RangeError` whose message
1109
+ * starts with `input too large:` (a larger `stepSize` or a smaller
1110
+ * `maxSteps` takes fewer steps).
1111
+ */
1112
+ export function boxFiltration(points: PointCloud, opts: BoxFiltrationOptions): BoxFiltration {
1113
+ module();
1114
+ const a = boxArgs(points, options<BoxFiltrationOptions>(opts, 'boxFiltration', BOX_KEYS));
1115
+ const { coords, d } = points;
1116
+ return call('boxFiltration', (m) => boxOf(d, a.boxes)(m.boxFiltrationFlat(coords, d, a.stepSize, a.growth, a.maxSteps, a.cap, a.boxes)));
1117
+ }
1118
+
1119
+ /** Options of {@link boxFiltrationPersistence}. */
1120
+ export interface BoxFiltrationPersistenceOptions extends BoxFiltrationOptions, BuilderPersistenceOptions {}
1121
+
1122
+ const BOX_PERSISTENCE_KEYS: Keys<BoxFiltrationPersistenceOptions> = { ...BOX_KEYS, ...FUSED_KEYS };
1123
+
1124
+ /**
1125
+ * The persistence of {@link boxFiltration}, built and reduced in one call:
1126
+ * homology up to `maxSimplexDim`. The step limit of {@link boxFiltration}
1127
+ * applies, with `boxes` `true` or `false`.
1128
+ */
1129
+ export function boxFiltrationPersistence(points: PointCloud, opts: BoxFiltrationPersistenceOptions): BuilderPersistence<BoxFiltration> {
1130
+ module();
1131
+ const o = options<BoxFiltrationPersistenceOptions>(opts, 'boxFiltrationPersistence', BOX_PERSISTENCE_KEYS);
1132
+ const a = boxArgs(points, o);
1133
+ const f = fused(o);
1134
+ const { coords, d } = points;
1135
+ return call('boxFiltrationPersistence', (m) =>
1136
+ persistenceOf(m.boxFiltrationPipeline(coords, d, a.stepSize, a.growth, a.maxSteps, a.cap, a.boxes, f.coeff, f.complex),
1137
+ 'growthRadius', f, a.cap, f.complex, boxOf(d, a.boxes))
1138
+ );
1139
+ }
1140
+
1141
+ // ---------------------------------------------------------------------------
1142
+ // Cubical
1143
+ // ---------------------------------------------------------------------------
1144
+
1145
+ /** The grid's extents, fastest axis first (the engine's order), after its checks. */
1146
+ export function gridArgs(v: unknown, name: string): number[] {
1147
+ if (v === null || typeof v !== 'object') {
1148
+ throw new TypeError(`${name} must be { values: Float64Array, shape: number[] }, got ${kind(v)}`);
1149
+ }
1150
+ const { values, shape } = v as Grid;
1151
+ if (!isTyped(values, 'Float64Array')) throw new TypeError(`${name}.values must be a Float64Array, got ${kind(values)}`);
1152
+ if (!Array.isArray(shape)) throw new TypeError(`${name}.shape must be an array of positive integers, got ${kind(shape)}`);
1153
+ if (shape.length === 0 || shape.length > 16) {
1154
+ throw new RangeError(`${name}.shape must have from 1 to 16 axes, got ${shape.length}`);
1155
+ }
1156
+ let size = 1;
1157
+ for (let i = 0; i < shape.length; i++) {
1158
+ u32(shape[i], `${name}.shape[${i}]`, 1);
1159
+ size *= shape[i]!;
1160
+ }
1161
+ sized(values.length, size, `${name}.values`, 'one value per cell of the shape');
1162
+ allFinite(values, `${name}.values`);
1163
+ return [...shape].reverse();
1164
+ }
1165
+
1166
+ /**
1167
+ * Every cell of the cubical complex of an image or a volume, T-construction
1168
+ * (each value on a top-dimensional cell, every lower cell at the smallest
1169
+ * value of the top cells containing it), by the Rust core: the cells, values
1170
+ * and order of GUDHI's `Bitmap_cubical_complex`.
1171
+ */
1172
+ export function cubicalComplex(image: Grid): CubicalComplex {
1173
+ module();
1174
+ const extents = gridArgs(image, 'image');
1175
+ return call('cubicalComplex', (m) => {
1176
+ const raw = m.cubicalComplexFlat(extents, image.values);
1177
+ return { shape: [...image.shape], cells: raw.cells, dims: raw.dimensions, filtrations: raw.filtrations, scale: 'value' as const };
1178
+ });
1179
+ }