@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
package/src/ladder.ts ADDED
@@ -0,0 +1,903 @@
1
+ /**
2
+ * Persistence modules over commutative ladders CL(n), computed from data.
3
+ *
4
+ * Input is a *ladder filtration*: one simplicial complex in which every
5
+ * simplex carries the column (1..n) at which it enters the LOWER row and the
6
+ * column at which it enters the UPPER row (0 = never). The complex at vertex
7
+ * `(c, r)` of CL(n) holds the simplices that entered row `r` at a column
8
+ * `≤ c`; the upper row must contain the lower one and faces must enter no
9
+ * later than their cofaces. This is the general model ([reference](https://topolab.ai/tda/docs/references/#hiraoka-nakashima-obayashi-and-xu-2023), (5.1)).
10
+ *
11
+ * Two computations, both over GF(p) and both by zigzag persistence of
12
+ * subcomplexes (the representation itself is never formed):
13
+ *
14
+ * - {@link decomposeCL4}: for CL(n), n ≤ 4, the exact indecomposable
15
+ * decomposition — on CL(4) the multiplicity of each of the 76
16
+ * indecomposables (55 intervals, 21 non-intervals N1…N21), from the ranks of
17
+ * the 76 alternating zigzag courses of the CL(4) course list
18
+ * ({@link cl4Catalogue}) and the inverse of their 76 × 76 matrix (§4.1); CL(1),
19
+ * CL(2) and CL(3) by extension by zero into CL(4), reported on CL(n).
20
+ * - {@link intervalApproximation} and {@link connectedPersistenceDiagram}:
21
+ * for CL(n), the source-sink interval approximation δ (Definition 3.25,
22
+ * Remark 3.26) and the connected persistence diagram (Definitions 4.5,
23
+ * 4.7) as a `topolab.cpd.v1` record
24
+ * (https://topolab.ai/tda/docs/guides/commutative-ladders/).
25
+ *
26
+ * The engine is a WebAssembly module separate from the package root's
27
+ * (`@topolab/tda/ladder.wasm`). Call {@link load} once; the
28
+ * functions are then plain calls. A bad argument throws a `TypeError` (wrong
29
+ * type) or a `RangeError` (out of range) whose message names the parameter;
30
+ * a failure inside the engine throws an `Error`. An allocation trap replaces the instance and throws `TOO_LARGE`; the
31
+ * next call needs no `load()`. An empty-record trap remains an internal error.
32
+ *
33
+ * @packageDocumentation
34
+ */
35
+
36
+ // @ts-ignore - the ladder module's glue (wasm-bindgen --target web), built with the module
37
+ import * as rawModule from '../dist/ladder/tda_ladder.js';
38
+ import { coeff as checkCoeff, int, isTyped, kind, options, points } from './check.js';
39
+ import type { Keys } from './check.js';
40
+ import { compileSource } from './source.js';
41
+ import type { LoadSource } from './source.js';
42
+ import type { PointCloud } from './check.js';
43
+
44
+ export type { PointCloud } from './check.js';
45
+
46
+ /** What the wasm-bindgen module exports, as this wrapper uses it. */
47
+ interface RawObject {
48
+ free(): void;
49
+ /** wasm-bindgen's: zeroes the pointer and unregisters the finalizer, JavaScript only. */
50
+ __destroy_into_raw(): number;
51
+ }
52
+ interface RawApproximation extends RawObject {
53
+ readonly intervals: Uint32Array;
54
+ readonly compressed: Uint32Array;
55
+ readonly delta: Int32Array;
56
+ readonly deltaTilde: Int32Array;
57
+ }
58
+ interface RawDecomposition extends RawObject {
59
+ readonly courseRanks: Uint32Array;
60
+ readonly multiplicities: Uint32Array;
61
+ }
62
+ interface RawCatalogue extends RawObject {
63
+ readonly names: string;
64
+ readonly dimensionVectors: Uint32Array;
65
+ readonly courseOffsets: Uint32Array;
66
+ readonly courseLabels: Uint32Array;
67
+ readonly courseIds: string;
68
+ readonly courseRemarks: string;
69
+ }
70
+ interface RawClnCatalogue extends RawObject {
71
+ readonly cl4Indices: Uint32Array;
72
+ readonly names: string;
73
+ readonly dimensionVectors: Uint32Array;
74
+ }
75
+ interface RawFiltration extends RawObject {
76
+ readonly n: number;
77
+ readonly offsets: Uint32Array;
78
+ readonly vertices: Uint32Array;
79
+ readonly lower: Uint32Array;
80
+ readonly upper: Uint32Array;
81
+ }
82
+ interface RawLadder {
83
+ initSync(input: { module: WebAssembly.Module }): unknown;
84
+ version(): string;
85
+ __ladder_unload(): void;
86
+ __oom_status(): {epoch:number};
87
+ intervalApproximation(
88
+ n: number,
89
+ offsets: Uint32Array,
90
+ vertices: Uint32Array,
91
+ lower: Uint32Array,
92
+ upper: Uint32Array,
93
+ q: number,
94
+ p: number,
95
+ ): RawApproximation;
96
+ decomposeCL4(
97
+ n: number,
98
+ offsets: Uint32Array,
99
+ vertices: Uint32Array,
100
+ lower: Uint32Array,
101
+ upper: Uint32Array,
102
+ q: number,
103
+ p: number,
104
+ ): RawDecomposition;
105
+ courseRank(
106
+ n: number,
107
+ offsets: Uint32Array,
108
+ vertices: Uint32Array,
109
+ lower: Uint32Array,
110
+ upper: Uint32Array,
111
+ labels: Uint32Array,
112
+ q: number,
113
+ p: number,
114
+ ): number;
115
+ cl4Catalogue(): RawCatalogue;
116
+ clnCatalogue(n: number): RawClnCatalogue;
117
+ ripsThinningLadder(
118
+ points: Float64Array,
119
+ dim: number,
120
+ inLower: Uint8Array,
121
+ thresholds: Float64Array,
122
+ maxDim: number,
123
+ ): RawFiltration;
124
+ }
125
+
126
+ export type { LoadSource };
127
+
128
+ const raw = rawModule as unknown as RawLadder;
129
+
130
+ /** The load in progress or done, `null` when none is. */
131
+ let ready: Promise<void> | null = null;
132
+ /** The `source` the load in {@link ready} was given (`undefined` for the default). */
133
+ let readySource: LoadSource | undefined;
134
+ /** Settles when the last load started has settled: a new load waits for it. */
135
+ let settled: Promise<unknown> = Promise.resolve();
136
+ let loaded = false;
137
+ /** Incremented by every `unload()`, so a load it overtook drops its instance. */
138
+ let generation = 0;
139
+
140
+ /**
141
+ * Load the engine. Without `source` it is read from `ladder.wasm` next to
142
+ * the package's code (`@topolab/tda/ladder.wasm`): from the file in
143
+ * Node, by `fetch` in a browser, where bundlers that understand
144
+ * `new URL(…, import.meta.url)` resolve it. Nothing is written to
145
+ * `globalThis`.
146
+ *
147
+ * Concurrent calls behave as the root module's `load` does. Once the engine
148
+ * is loaded, `load` returns the same resolved promise and ignores `source`.
149
+ * While a load is in progress, a call with the same `source` (the same
150
+ * value, or none both times) shares that load and its outcome. A call with
151
+ * another `source` waits for the load in progress: if it succeeds, the call
152
+ * resolves too, without using its own `source`; if it fails, the call does
153
+ * not share that failure but loads from its own `source`. A failed load is
154
+ * not kept, so a later call can retry with a corrected source;
155
+ * {@link unload} rejects every load in progress.
156
+ */
157
+ export function load(source?: LoadSource): Promise<void> {
158
+ if (ready && !loaded && !Object.is(source, readySource)) {
159
+ const mine = generation;
160
+ const overtaken = () => new Error('@topolab/tda/ladder: unload() was called while load() was in progress');
161
+ return ready.then(
162
+ () => {
163
+ if (mine !== generation) throw overtaken();
164
+ },
165
+ () => {
166
+ if (mine !== generation) throw overtaken();
167
+ return load(source);
168
+ }
169
+ );
170
+ }
171
+ if (!ready) {
172
+ readySource = source;
173
+ const mine = generation;
174
+ const p = settled
175
+ .then(() =>
176
+ compileSource(source, () => new URL('./ladder/tda_ladder_bg.wasm', import.meta.url), {
177
+ exports: ['version', 'intervalApproximation', '__oom_record'],
178
+ file: 'ladder.wasm',
179
+ pkg: '@topolab/tda/ladder'
180
+ })
181
+ )
182
+ // The glue's initSync instantiates a compiled module without reading
183
+ // the global Request, Response or fetch.
184
+ .then((module) => {
185
+ raw.initSync({ module });
186
+ })
187
+ .then(
188
+ () => {
189
+ if (mine !== generation) {
190
+ // unload() ran while this load was in flight: it wins
191
+ raw.__ladder_unload();
192
+ throw new Error('@topolab/tda/ladder: unload() was called while load() was in progress');
193
+ }
194
+ loaded = true;
195
+ },
196
+ (e: unknown) => {
197
+ if (mine === generation) ready = null;
198
+ throw e;
199
+ }
200
+ );
201
+ ready = p;
202
+ settled = p.catch(() => undefined);
203
+ }
204
+ return ready;
205
+ }
206
+
207
+ /**
208
+ * Drop the engine, so that its memory can be reclaimed. Results already
209
+ * returned are copies and stay valid; functions that need the engine throw
210
+ * until {@link load} is called again; a load in progress rejects.
211
+ */
212
+ export function unload(): void {
213
+ generation++;
214
+ ready = null;
215
+ if (!loaded) return;
216
+ loaded = false;
217
+ catalogue = null;
218
+ clnCatalogues.clear();
219
+ // JavaScript only: the glue forgets its instance (no call into it).
220
+ raw.__ladder_unload();
221
+ }
222
+
223
+ /** Whether the engine is loaded (a {@link load} has resolved and no {@link unload} followed). */
224
+ export function isLoaded(): boolean {
225
+ return loaded;
226
+ }
227
+
228
+ function engine(): RawLadder {
229
+ if (!loaded) throw new Error('@topolab/tda/ladder is not loaded: await load() first');
230
+ return raw;
231
+ }
232
+
233
+ /**
234
+ * Run `f` on the engine. The engine refuses input it does not accept with a
235
+ * message starting "invalid input:" (a `RangeError` here); any other failure
236
+ * stays an `Error`.
237
+ */
238
+ function run<T>(f: (r: RawLadder) => T): T {
239
+ const r = engine();
240
+ try {
241
+ return f(r);
242
+ } catch (e) {
243
+ if (e instanceof Error && e.message.startsWith('invalid input:')) throw new RangeError(e.message);
244
+ throw e;
245
+ }
246
+ }
247
+
248
+ /** The version of the loaded engine (equal to the package's). */
249
+ export function version(): string {
250
+ return run((r) => r.version());
251
+ }
252
+
253
+ // ---------------------------------------------------------------------------
254
+ // Input
255
+ // ---------------------------------------------------------------------------
256
+
257
+ /**
258
+ * A ladder filtration on CL(n). Give the simplices either as vertex lists
259
+ * (`simplices`) or flat (`offsets` of length count + 1 starting at 0, and the
260
+ * concatenated `vertices`), each simplex's vertices in any order (the engine
261
+ * sorts them; a vertex listed twice is a `RangeError`). `lower[i]` /
262
+ * `upper[i]` is the column (1..n) at which simplex `i` enters the lower /
263
+ * upper row, 0 for never.
264
+ */
265
+ export interface LadderFiltration {
266
+ readonly n: number;
267
+ readonly simplices?: ReadonlyArray<ReadonlyArray<number>>;
268
+ readonly offsets?: ArrayLike<number>;
269
+ readonly vertices?: ArrayLike<number>;
270
+ readonly lower: ArrayLike<number>;
271
+ readonly upper: ArrayLike<number>;
272
+ }
273
+
274
+ /** A ladder filtration in the flat form the engine takes and returns. */
275
+ export interface FlatLadderFiltration extends LadderFiltration {
276
+ readonly offsets: Uint32Array;
277
+ readonly vertices: Uint32Array;
278
+ readonly lower: Uint32Array;
279
+ readonly upper: Uint32Array;
280
+ }
281
+
282
+ /** Homology dimension and coefficient field. */
283
+ export interface LadderOptions {
284
+ /** The homology dimension q, an integer from 0 to 61 (a simplex has at most 64 vertices). Required. */
285
+ readonly dim: number;
286
+ /** The prime p of the coefficient field GF(p), from 2 to `2^31 − 1`. Default 2. */
287
+ readonly coeff?: number;
288
+ }
289
+
290
+ const LADDER_KEYS: Keys<LadderOptions> = { dim: true, coeff: true };
291
+
292
+ /** An entry of an integer array, named `name` in messages: an integer from 0 to 2^32 - 1. */
293
+ function entry(v: unknown, name: string): number {
294
+ if (typeof v !== 'number') throw new TypeError(`${name} must be a number, got ${kind(v)}`);
295
+ if (!Number.isInteger(v) || v < 0 || v > 0xffffffff) {
296
+ throw new RangeError(`${name} must be an integer from 0 to 4294967295, got ${v}`);
297
+ }
298
+ return v;
299
+ }
300
+
301
+ /** An array-like (an array or a typed array) or a `TypeError` saying what `name` must be. */
302
+ function arrayLike(v: unknown, name: string, what: string): ArrayLike<unknown> {
303
+ if (v === null || typeof v !== 'object' || typeof (v as ArrayLike<unknown>).length !== 'number') {
304
+ throw new TypeError(`${name} must be ${what}, got ${kind(v)}`);
305
+ }
306
+ return v as ArrayLike<unknown>;
307
+ }
308
+
309
+ function u32(name: string, values: ArrayLike<number>): Uint32Array {
310
+ if (isTyped(values, 'Uint32Array')) return values;
311
+ arrayLike(values, name, 'an array of integers');
312
+ const out = new Uint32Array(values.length);
313
+ for (let i = 0; i < values.length; i++) out[i] = entry(values[i], `${name}[${i}]`);
314
+ return out;
315
+ }
316
+
317
+ /** The flat form of a filtration (no copy when it already is flat). */
318
+ export function flattenLadderFiltration(f: LadderFiltration): FlatLadderFiltration {
319
+ if (f === null || typeof f !== 'object') throw new TypeError(`filtration must be a ladder filtration, got ${kind(f)}`);
320
+ int(f.n, 'n', 1);
321
+ let offsets: Uint32Array;
322
+ let vertices: Uint32Array;
323
+ if (f.simplices !== undefined) {
324
+ // Entries are named by the caller's own indices (`simplices[2][1]`).
325
+ const simplices = arrayLike(f.simplices, 'simplices', 'an array of vertex lists');
326
+ offsets = new Uint32Array(simplices.length + 1);
327
+ for (let i = 0; i < simplices.length; i++) {
328
+ const s = arrayLike(simplices[i], `simplices[${i}]`, 'an array of vertex ids');
329
+ offsets[i + 1] = offsets[i]! + s.length;
330
+ }
331
+ vertices = new Uint32Array(offsets[simplices.length]!);
332
+ for (let i = 0; i < simplices.length; i++) {
333
+ const s = simplices[i] as ArrayLike<unknown>;
334
+ for (let j = 0; j < s.length; j++) vertices[offsets[i]! + j] = entry(s[j], `simplices[${i}][${j}]`);
335
+ }
336
+ } else if (f.offsets && f.vertices) {
337
+ offsets = u32('offsets', f.offsets);
338
+ vertices = u32('vertices', f.vertices);
339
+ } else {
340
+ throw new TypeError('filtration must give its simplices as `simplices` or as `offsets` and `vertices`');
341
+ }
342
+ return { n: f.n, offsets, vertices, lower: u32('lower', f.lower), upper: u32('upper', f.upper) };
343
+ }
344
+
345
+ function ladderOptions(opts: LadderOptions, fn: string): { q: number; p: number } {
346
+ const o = options<LadderOptions>(opts, fn, LADDER_KEYS);
347
+ return { q: int(o.dim, 'dim', 0, 61), p: checkCoeff(o.coeff) };
348
+ }
349
+
350
+ /**
351
+ * Reads a result object and frees it. If the instance traps while the
352
+ * object is read (its getters copy out of the instance), the object is
353
+ * abandoned with `__destroy_into_raw()` (no free() in the trapped instance,
354
+ * whose borrow of the object the abort may have left set, and no finalizer
355
+ * left to run later) and the engine is dropped.
356
+ */
357
+ function take<T extends RawObject, R>(obj: T, read: (o: T) => R): R {
358
+ let out: R;
359
+ const epoch = raw.__oom_status().epoch;
360
+ try {
361
+ out = read(obj);
362
+ } catch (e) {
363
+ if (raw.__oom_status().epoch !== epoch) {
364
+ obj.__destroy_into_raw();
365
+ throw e;
366
+ }
367
+ if (e instanceof WebAssembly.RuntimeError) {
368
+ obj.__destroy_into_raw();
369
+ throw e;
370
+ }
371
+ obj.free();
372
+ throw e;
373
+ }
374
+ obj.free();
375
+ return out;
376
+ }
377
+
378
+ // ---------------------------------------------------------------------------
379
+ // Intervals of CL(n)
380
+ // ---------------------------------------------------------------------------
381
+
382
+ /**
383
+ * An interval of CL(n), (4.2): a run `[birth, last]` in the upper row, the
384
+ * lower row, or both with `upper.birth ≤ lower.birth ≤ upper.last ≤
385
+ * lower.last`. Ends are INCLUSIVE.
386
+ */
387
+ export interface LadderInterval {
388
+ readonly upper: readonly [birth: number, last: number] | null;
389
+ readonly lower: readonly [birth: number, last: number] | null;
390
+ }
391
+
392
+ /** A row of an interval: `null`, or `[birth, last]` with `1 ≤ birth ≤ last` integers. */
393
+ function span(v: unknown, name: string): readonly [number, number] | null {
394
+ if (v === null) return null;
395
+ if (!Array.isArray(v) || v.length !== 2) throw new TypeError(`${name} must be null or a [birth, last] pair, got ${kind(v)}`);
396
+ const [b, d] = [int(v[0], `${name}[0]`, 1, 0xffffffff), int(v[1], `${name}[1]`, 1, 0xffffffff)];
397
+ if (b > d) throw new RangeError(`${name} must have birth <= last, got [${b}, ${d}]`);
398
+ return [b, d];
399
+ }
400
+
401
+ /** The checks of a {@link LadderInterval}: one row or two, and for two rows the order (4.2). */
402
+ function checkInterval(iv: unknown, name: string): LadderInterval {
403
+ if (iv === null || typeof iv !== 'object') throw new TypeError(`${name} must be a ladder interval { upper, lower }, got ${kind(iv)}`);
404
+ const { upper, lower } = iv as LadderInterval;
405
+ const up = span(upper, `${name}.upper`);
406
+ const low = span(lower, `${name}.lower`);
407
+ if (up === null && low === null) throw new RangeError(`${name} must have an upper row, a lower row or both`);
408
+ if (up && low && !(up[0] <= low[0] && low[0] <= up[1] && up[1] <= low[1])) {
409
+ throw new RangeError(
410
+ `${name} = [${up[0]},${up[1]}]_2 ⊔ [${low[0]},${low[1]}]_1 is not an interval of CL(n): (4.2) needs upper birth <= lower birth <= upper last <= lower last`
411
+ );
412
+ }
413
+ return { upper: up, lower: low };
414
+ }
415
+
416
+ /** `[b,d]_1`, `[b,d]_2` or `[b2,d2]_2 ⊔ [b1,d1]_1`; a value that is not a {@link LadderInterval} is a `TypeError` or `RangeError`. */
417
+ export function intervalName(iv: LadderInterval): string {
418
+ const { upper, lower } = checkInterval(iv, 'iv');
419
+ const parts: string[] = [];
420
+ if (upper) parts.push(`[${upper[0]},${upper[1]}]_2`);
421
+ if (lower) parts.push(`[${lower[0]},${lower[1]}]_1`);
422
+ return parts.join(' ⊔ ');
423
+ }
424
+
425
+ function intervalsFrom(flat: Uint32Array): LadderInterval[] {
426
+ const out: LadderInterval[] = [];
427
+ for (let i = 0; i < flat.length; i += 4) {
428
+ const [b2, d2, b1, d1] = [flat[i]!, flat[i + 1]!, flat[i + 2]!, flat[i + 3]!];
429
+ out.push({ upper: b2 === 0 ? null : [b2, d2], lower: b1 === 0 ? null : [b1, d1] });
430
+ }
431
+ return out;
432
+ }
433
+
434
+ // ---------------------------------------------------------------------------
435
+ // Interval approximation and the connected persistence diagram
436
+ // ---------------------------------------------------------------------------
437
+
438
+ /** The source-sink interval approximation of the homology in degree `q` (arrays in interval order). */
439
+ export interface IntervalApproximation {
440
+ readonly n: number;
441
+ /** The homology dimension. */
442
+ readonly dim: number;
443
+ /** The prime of the coefficient field. */
444
+ readonly coeff: number;
445
+ /** Every interval of CL(n): `[b,d]_1`, `[b,d]_2`, then two-row, each lexicographic. */
446
+ readonly intervals: readonly LadderInterval[];
447
+ /** `c^ξss(I)`: the ξss-compressed multiplicity (Definition 3.16). */
448
+ readonly compressed: Uint32Array;
449
+ /** `δ(I)`: the interval approximation (Definition 3.25); may be negative. */
450
+ readonly delta: Int32Array;
451
+ /** `δ̃(I)` (Definition 4.5): on a row, that row's persistence diagram (Proposition 4.6). */
452
+ readonly deltaTilde: Int32Array;
453
+ /** A negative δ: by Proposition 6.2 the module has a non-interval summand. */
454
+ readonly hasNegative: boolean;
455
+ }
456
+
457
+ /**
458
+ * The source-sink interval approximation of the homology in degree `q` of a ladder filtration,
459
+ * from `n(n+1)/2` zigzag persistence computations.
460
+ */
461
+ export function intervalApproximation(f: LadderFiltration, opts: LadderOptions): IntervalApproximation {
462
+ const flat = flattenLadderFiltration(f);
463
+ const { q, p } = ladderOptions(opts, 'intervalApproximation');
464
+ return take(run((r) => r.intervalApproximation(flat.n, flat.offsets, flat.vertices, flat.lower, flat.upper, q, p)), (a) => {
465
+ const delta = a.delta;
466
+ return {
467
+ n: flat.n,
468
+ dim: q,
469
+ coeff: p,
470
+ intervals: intervalsFrom(a.intervals),
471
+ compressed: a.compressed,
472
+ delta,
473
+ deltaTilde: a.deltaTilde,
474
+ hasNegative: delta.some((x) => x < 0),
475
+ };
476
+ });
477
+ }
478
+
479
+ /** A point of `topolab.cpd.v1`: `(birth, death)` with death EXCLUSIVE. */
480
+ export interface CpdPointV1 {
481
+ readonly id: string;
482
+ readonly birth: number;
483
+ readonly death: number;
484
+ readonly multiplicity: number;
485
+ readonly note: string | null;
486
+ }
487
+
488
+ /** A coupling of `topolab.cpd.v1`, endpoints by coordinate. */
489
+ export interface CpdCouplingV1 {
490
+ readonly id: string;
491
+ readonly upper: { readonly birth: number; readonly death: number };
492
+ readonly lower: { readonly birth: number; readonly death: number };
493
+ readonly multiplicity: number;
494
+ readonly note: string | null;
495
+ }
496
+
497
+ /** The `topolab.cpd.v1` record: the connected persistence diagram as a viewer of the record reads it (https://topolab.ai/tda/docs/guides/commutative-ladders/). */
498
+ export interface CpdRecordV1 {
499
+ readonly schema: 'topolab.cpd.v1';
500
+ readonly title: string;
501
+ /** `true` when the multiplicities were invented rather than computed from data. */
502
+ readonly synthetic: boolean;
503
+ readonly provenance: string;
504
+ readonly generator: string;
505
+ readonly citation: string;
506
+ readonly ladder: { readonly length: number; readonly orientation: string; readonly rows: Readonly<Record<string, string>> };
507
+ readonly homologyDimension: number;
508
+ readonly essentialAssignment: string;
509
+ readonly death: { readonly convention: 'exclusive'; readonly note: string };
510
+ readonly lifetime: string;
511
+ readonly multiplicity: string;
512
+ readonly upper: readonly CpdPointV1[];
513
+ readonly lower: readonly CpdPointV1[];
514
+ readonly couplings: readonly CpdCouplingV1[];
515
+ }
516
+
517
+ /** What a record says about its data; everything else is filled in. */
518
+ export interface CpdRecordMeta {
519
+ /** A non-empty title. */
520
+ readonly title: string;
521
+ /** One non-empty sentence: where the numbers came from (data set, model, thresholds). */
522
+ readonly provenance: string;
523
+ /** What each row is, e.g. `{ 1: 'the thinned cloud', 2: 'the full cloud' }`: the keys `'1'` and `'2'`, each a non-empty string; a row left out keeps its default, the lower row (1) or the upper row (2). */
524
+ readonly rows?: Readonly<Record<string, string>>;
525
+ /** What wrote the record. Default: this function and the package version. */
526
+ readonly generator?: string;
527
+ /** `true` when the multiplicities were invented rather than computed from data (an example). Default `false`. */
528
+ readonly synthetic?: boolean;
529
+ }
530
+
531
+ const META_KEYS: Keys<CpdRecordMeta> = { title: true, provenance: true, rows: true, generator: true, synthetic: true };
532
+
533
+ /** A non-empty string. */
534
+ function text(v: unknown, name: string): string {
535
+ if (typeof v !== 'string') throw new TypeError(`${name} must be a string, got ${kind(v)}`);
536
+ if (v.trim() === '') throw new RangeError(`${name} must not be empty`);
537
+ return v;
538
+ }
539
+
540
+ /** The checks of an {@link IntervalApproximation} as {@link connectedPersistenceDiagram} reads it. */
541
+ function checkApproximation(a: unknown): IntervalApproximation {
542
+ if (a === null || typeof a !== 'object') throw new TypeError(`a must be an interval approximation, got ${kind(a)}`);
543
+ const x = a as IntervalApproximation;
544
+ const n = int(x.n, 'a.n', 2);
545
+ int(x.dim, 'a.dim', 0);
546
+ int(x.coeff, 'a.coeff', 2);
547
+ if (!Array.isArray(x.intervals)) throw new TypeError(`a.intervals must be an array of ladder intervals, got ${kind(x.intervals)}`);
548
+ if (!isTyped(x.deltaTilde, 'Int32Array')) throw new TypeError(`a.deltaTilde must be an Int32Array, got ${kind(x.deltaTilde)}`);
549
+ if (x.deltaTilde.length !== x.intervals.length) {
550
+ throw new RangeError(`a.deltaTilde must have one entry per interval (${x.intervals.length}), got length ${x.deltaTilde.length}`);
551
+ }
552
+ x.intervals.forEach((iv, i) => {
553
+ const { upper, lower } = checkInterval(iv, `a.intervals[${i}]`);
554
+ if ((upper && upper[1] > n) || (lower && lower[1] > n)) throw new RangeError(`a.intervals[${i}] leaves CL(${n})`);
555
+ });
556
+ return x;
557
+ }
558
+
559
+ const CITATION =
560
+ 'Hiraoka, Nakashima, Obayashi, Xu, "Refinement of Interval Approximations for Fully Commutative Quivers", arXiv:2310.03649: ' +
561
+ 'Definition 3.16 (ξ-compressed multiplicity), Example 3.14 and Remark 4.9 (source-sink assignment ξss), Definition 3.25 and ' +
562
+ 'Remark 3.26 (interval approximation by Möbius inversion), Definition 4.5 (δ̃), Definition 4.7 (connected persistence diagram), ' +
563
+ 'Proposition 4.6 (rows are the row diagrams), Proposition 6.2 (a negative multiplicity witnesses a non-interval summand), (4.2).';
564
+
565
+ /**
566
+ * The connected persistence diagram (Definition 4.7) as a `topolab.cpd.v1`
567
+ * record. Points carry EXCLUSIVE deaths: the interval `[b, d]` of a row is
568
+ * the point `(b, d + 1)`, and a two-row interval `[b2,d2]_2 ⊔ [b1,d1]_1` is
569
+ * the coupling from `(b2, d2 + 1)` to `(b1, d1 + 1)`. Zero multiplicities are
570
+ * omitted; couplings may be negative. `a` is what {@link intervalApproximation}
571
+ * returns (a ladder of length at least 2: CL(1) has no diagram); `meta` is
572
+ * checked as {@link CpdRecordMeta} describes, an unknown key included.
573
+ */
574
+ export function connectedPersistenceDiagram(a: IntervalApproximation, meta: CpdRecordMeta): CpdRecordV1 {
575
+ checkApproximation(a);
576
+ if (meta === undefined) throw new TypeError('meta must be an object, got undefined');
577
+ const m = options<CpdRecordMeta>(meta, 'connectedPersistenceDiagram', META_KEYS, 'meta', '', 'meta field');
578
+ const title = text(m.title, 'meta.title');
579
+ const provenance = text(m.provenance, 'meta.provenance');
580
+ const generator = m.generator === undefined ? undefined : text(m.generator, 'meta.generator');
581
+ if (m.synthetic !== undefined && typeof m.synthetic !== 'boolean') {
582
+ throw new TypeError(`meta.synthetic must be a boolean, got ${kind(m.synthetic)}`);
583
+ }
584
+ let rows: Readonly<Record<string, string>> = { 1: 'the lower row', 2: 'the upper row' };
585
+ if (m.rows !== undefined) {
586
+ if (m.rows === null || typeof m.rows !== 'object' || Array.isArray(m.rows)) {
587
+ throw new TypeError(`meta.rows must be an object { 1: string, 2: string }, got ${kind(m.rows)}`);
588
+ }
589
+ for (const [k, v] of Object.entries(m.rows)) {
590
+ if (k !== '1' && k !== '2') throw new RangeError(`meta.rows may only describe rows "1" and "2", got "${k}"`);
591
+ text(v, `meta.rows[${k}]`);
592
+ }
593
+ // A row the caller does not describe keeps its default description.
594
+ rows = { ...rows, ...m.rows };
595
+ }
596
+ const upper: CpdPointV1[] = [];
597
+ const lower: CpdPointV1[] = [];
598
+ const couplings: CpdCouplingV1[] = [];
599
+ a.intervals.forEach((iv, i) => {
600
+ const k = a.deltaTilde[i]!;
601
+ if (k === 0) return;
602
+ if (iv.upper && iv.lower) {
603
+ couplings.push({
604
+ id: '',
605
+ upper: { birth: iv.upper[0], death: iv.upper[1] + 1 },
606
+ lower: { birth: iv.lower[0], death: iv.lower[1] + 1 },
607
+ multiplicity: k,
608
+ note: k < 0 ? 'negative: by Proposition 6.2 the module has a summand that is not an interval' : null,
609
+ });
610
+ } else {
611
+ const row = (iv.upper ?? iv.lower)!;
612
+ (iv.upper ? upper : lower).push({ id: '', birth: row[0], death: row[1] + 1, multiplicity: k, note: null });
613
+ }
614
+ });
615
+ const byPoint = (x: { birth: number; death: number }, y: { birth: number; death: number }) => x.birth - y.birth || x.death - y.death;
616
+ upper.sort(byPoint);
617
+ lower.sort(byPoint);
618
+ couplings.sort((x, y) => byPoint(x.upper, y.upper) || byPoint(x.lower, y.lower));
619
+ const ids = <T extends { id: string }>(list: T[], prefix: string): T[] => list.map((x, k) => ({ ...x, id: `${prefix}${k + 1}` }));
620
+ const n = a.n;
621
+ return {
622
+ schema: 'topolab.cpd.v1',
623
+ title,
624
+ synthetic: m.synthetic ?? false,
625
+ provenance,
626
+ generator: generator ?? `@topolab/tda/ladder ${version()} (connectedPersistenceDiagram)`,
627
+ citation: CITATION,
628
+ ladder: {
629
+ length: n,
630
+ orientation: `equi-oriented CL(${n}): arrows point right along each row and up from row 1 to row 2`,
631
+ rows,
632
+ },
633
+ homologyDimension: a.dim,
634
+ essentialAssignment: 'source-sink ξss (Example 3.14, Remark 4.9)',
635
+ death: {
636
+ convention: 'exclusive',
637
+ note: `A point (b, d) records the interval [b, d−1]: the class is present at every ladder index from b through d−1 and absent at d. Deaths therefore run to n+1 = ${n + 1} for a class present at the last index.`,
638
+ },
639
+ lifetime: 'death − birth, in ladder indices: the number of indices at which the class is present.',
640
+ multiplicity: `Computed over GF(${a.coeff}). A point's multiplicity is δ̃ of its one-row interval, which by Proposition 4.6 is the multiplicity in that row's persistence diagram; a coupling's is δ of its two-row interval and may be negative, which by Proposition 6.2 witnesses a summand that is not an interval.`,
641
+ upper: ids(upper, 'u'),
642
+ lower: ids(lower, 'l'),
643
+ couplings: ids(couplings, 'k'),
644
+ };
645
+ }
646
+
647
+ // ---------------------------------------------------------------------------
648
+ // CL(n), n ≤ 4: the exact decomposition
649
+ // ---------------------------------------------------------------------------
650
+
651
+ /** One of the 76 indecomposables of CL(4). */
652
+ export interface CL4Indecomposable {
653
+ /** `[b,d]_1`, `[b,d]_2`, `[b2,d2]_2 ⊔ [b1,d1]_1`, or `N1` … `N21` ([reference](https://topolab.ai/tda/docs/references/#hiraoka-nakashima-obayashi-and-xu-2023), Fig. 15). */
654
+ readonly name: string;
655
+ /** The interval, or null for a non-interval N_k. */
656
+ readonly interval: LadderInterval | null;
657
+ /** Dimensions at the 8 vertices, index `(row − 1)·4 + column − 1`. */
658
+ readonly dimensionVector: readonly number[];
659
+ }
660
+
661
+ /** One of the 76 alternating zigzag courses of the CL(4) course list. */
662
+ export interface CL4Course {
663
+ readonly id: string;
664
+ readonly remark: string;
665
+ /** Labels as `[column, row]`, alternating forward/backward from the first arrow. */
666
+ readonly labels: ReadonlyArray<readonly [column: number, row: number]>;
667
+ }
668
+
669
+ let catalogue: { indecomposables: CL4Indecomposable[]; courses: CL4Course[] } | null = null;
670
+
671
+ /** The 76 indecomposables (decomposition order) and the 76 courses. */
672
+ export function cl4Catalogue(): { readonly indecomposables: readonly CL4Indecomposable[]; readonly courses: readonly CL4Course[] } {
673
+ if (!catalogue) {
674
+ catalogue = take(run((r) => r.cl4Catalogue()), (c) => {
675
+ const names = c.names.split('\n');
676
+ const dv = c.dimensionVectors;
677
+ const indecomposables = names.map((name, k) => ({
678
+ name,
679
+ interval: parseIntervalName(name),
680
+ dimensionVector: Array.from(dv.subarray(8 * k, 8 * k + 8)),
681
+ }));
682
+ const ids = c.courseIds.split('\n');
683
+ const remarks = c.courseRemarks.split('\n');
684
+ const off = c.courseOffsets;
685
+ const lab = c.courseLabels;
686
+ const courses = ids.map((id, i) => {
687
+ const labels: Array<readonly [number, number]> = [];
688
+ for (let k = off[i]!; k < off[i + 1]!; k++) labels.push([lab[2 * k]!, lab[2 * k + 1]!] as const);
689
+ return { id, remark: remarks[i]!, labels };
690
+ });
691
+ return { indecomposables, courses };
692
+ });
693
+ }
694
+ return catalogue;
695
+ }
696
+
697
+ /**
698
+ * An indecomposable of CL(n), `n ≤ 4`, through its extension by zero into
699
+ * CL(4) (the first `4 − n` columns padded with zero spaces).
700
+ */
701
+ export interface CLnIndecomposable {
702
+ /**
703
+ * The name on CL(n): an interval in CL(n) columns (`[b,d]_1`, `[b,d]_2`,
704
+ * `[b2,d2]_2 ⊔ [b1,d1]_1`); a non-interval is `N1` … `N21` on CL(4) and, for
705
+ * n < 4, `N[upper row/lower row]` by its CL(n) dimension vector — CL(3) has
706
+ * two, `N[121/011]` and `N[110/121]` ([reference](https://topolab.ai/tda/docs/references/#hiraoka-nakashima-obayashi-and-xu-2023), Remark 6.1); CL(1) and
707
+ * CL(2) have none.
708
+ */
709
+ readonly name: string;
710
+ /** The interval in CL(n) coordinates, or null for a non-interval. */
711
+ readonly interval: LadderInterval | null;
712
+ /** Dimensions on CL(n), index `(row − 1)·n + column − 1`. */
713
+ readonly dimensionVector: readonly number[];
714
+ /** Index of the extension by zero in {@link cl4Catalogue}`().indecomposables`. */
715
+ readonly cl4Index: number;
716
+ /** Name of the extension by zero on CL(4). */
717
+ readonly cl4Name: string;
718
+ }
719
+
720
+ const clnCatalogues = new Map<number, CLnIndecomposable[]>();
721
+
722
+ function parseIntervalName(name: string): LadderInterval | null {
723
+ if (name.startsWith('N')) return null;
724
+ let upper: [number, number] | null = null;
725
+ let lower: [number, number] | null = null;
726
+ for (const r of name.matchAll(/\[(\d+),(\d+)\]_(\d)/g)) {
727
+ const span: [number, number] = [Number(r[1]), Number(r[2])];
728
+ if (r[3] === '2') upper = span;
729
+ else lower = span;
730
+ }
731
+ return { upper, lower };
732
+ }
733
+
734
+ /**
735
+ * The indecomposables of CL(n), `n ≤ 4`, in the order of their extensions by
736
+ * zero in {@link cl4Catalogue} — 3, 11, 29 and 76 of them for n = 1…4.
737
+ */
738
+ export function clnCatalogue(n: number): readonly CLnIndecomposable[] {
739
+ int(n, 'n', 1, 4);
740
+ let cat = clnCatalogues.get(n);
741
+ if (!cat) {
742
+ const cl4Names = cl4Catalogue().indecomposables.map((x) => x.name);
743
+ cat = take(run((r) => r.clnCatalogue(n)), (c) => {
744
+ const names = c.names.split('\n');
745
+ return names.map((name, i) => ({
746
+ name,
747
+ interval: parseIntervalName(name),
748
+ dimensionVector: Array.from(c.dimensionVectors.subarray(2 * n * i, 2 * n * (i + 1))),
749
+ cl4Index: c.cl4Indices[i]!,
750
+ cl4Name: cl4Names[c.cl4Indices[i]!]!,
751
+ }));
752
+ });
753
+ clnCatalogues.set(n, cat);
754
+ }
755
+ return cat;
756
+ }
757
+
758
+ /** The decomposition of the homology in degree `q` of a ladder filtration on CL(n), `n ≤ 4`. */
759
+ export interface CL4Decomposition {
760
+ /** The ladder length of the input, 1 … 4. */
761
+ readonly n: number;
762
+ /** The homology dimension. */
763
+ readonly dim: number;
764
+ /** The prime of the coefficient field. */
765
+ readonly coeff: number;
766
+ /** The 76 course ranks (of the extension by zero when n < 4), in the order of {@link cl4Catalogue}`().courses`. */
767
+ readonly courseRanks: Uint32Array;
768
+ /** The 76 multiplicities on CL(4), in the order of {@link cl4Catalogue}`().indecomposables`. */
769
+ readonly multiplicities: Uint32Array;
770
+ /** The summands with non-zero multiplicity, named and placed on CL(n) (with their CL(4) names). */
771
+ readonly summands: ReadonlyArray<CLnIndecomposable & { readonly multiplicity: number }>;
772
+ readonly isIntervalDecomposable: boolean;
773
+ }
774
+
775
+ /**
776
+ * The exact indecomposable decomposition of the degree-`q` homology over GF(p) of a ladder
777
+ * filtration on CL(n), `n ≤ 4`: 76 zigzag persistence computations (one per
778
+ * course), then `d = A⁻¹ r` solved exactly. For `n < 4` the filtration is
779
+ * extended by zero into CL(4) — every entry column shifted by `4 − n`, so the
780
+ * first `4 − n` columns are empty — and the summands are mapped back to CL(n)
781
+ * by dropping those columns. The embedding is exact: extension by zero is
782
+ * fully faithful, so it preserves indecomposability and multiplicities, and
783
+ * the engine checks that no summand meets the padded columns. The engine
784
+ * refuses (throws) rather than return a non-integral or negative
785
+ * multiplicity.
786
+ */
787
+ export function decomposeCL4(f: LadderFiltration, opts: LadderOptions): CL4Decomposition {
788
+ const flat = flattenLadderFiltration(f);
789
+ if (flat.n > 4)
790
+ throw new RangeError(`n must be at most 4 (CL(1)…CL(3) embed in CL(4)), got ${flat.n}`);
791
+ const { q, p } = ladderOptions(opts, 'decomposeCL4');
792
+ const { courseRanks, multiplicities } = take(
793
+ run((r) => r.decomposeCL4(flat.n, flat.offsets, flat.vertices, flat.lower, flat.upper, q, p)),
794
+ (d) => ({ courseRanks: d.courseRanks, multiplicities: d.multiplicities }),
795
+ );
796
+ const summands = clnCatalogue(flat.n).flatMap((x) => {
797
+ const m = multiplicities[x.cl4Index]!;
798
+ return m > 0 ? [{ ...x, multiplicity: m }] : [];
799
+ });
800
+ const listed = summands.reduce((acc, s) => acc + s.multiplicity, 0);
801
+ const total = multiplicities.reduce((acc, m) => acc + m, 0);
802
+ if (listed !== total) throw new Error('@topolab/tda/ladder: a summand meets the padded columns (engine bug)');
803
+ return {
804
+ n: flat.n,
805
+ dim: q,
806
+ coeff: p,
807
+ courseRanks,
808
+ multiplicities,
809
+ summands,
810
+ isIntervalDecomposable: summands.every((s) => s.interval !== null),
811
+ };
812
+ }
813
+
814
+ /**
815
+ * The course function (4.1) of the degree-`q` homology: the multiplicity of the longest
816
+ * interval in the tour along an alternating zigzag course, labels as
817
+ * `[column, row]` (`F(1) → F(2) ← F(3) → …`). One zigzag computation.
818
+ */
819
+ export function courseRank(
820
+ f: LadderFiltration,
821
+ labels: ReadonlyArray<readonly [number, number]>,
822
+ opts: LadderOptions,
823
+ ): number {
824
+ const flat = flattenLadderFiltration(f);
825
+ const { q, p } = ladderOptions(opts, 'courseRank');
826
+ if (!Array.isArray(labels)) throw new TypeError(`labels must be an array of [column, row] pairs, got ${kind(labels)}`);
827
+ // Entries are named by the caller's own indices (`labels[1][0]`).
828
+ const lab = new Uint32Array(2 * labels.length);
829
+ for (let i = 0; i < labels.length; i++) {
830
+ const label = arrayLike(labels[i], `labels[${i}]`, 'a [column, row] pair');
831
+ if (label.length !== 2) throw new RangeError(`labels[${i}] must be a [column, row] pair, got length ${label.length}`);
832
+ for (let j = 0; j < 2; j++) lab[2 * i + j] = entry(label[j], `labels[${i}][${j}]`);
833
+ }
834
+ return run((r) => r.courseRank(flat.n, flat.offsets, flat.vertices, flat.lower, flat.upper, lab, q, p));
835
+ }
836
+
837
+ // ---------------------------------------------------------------------------
838
+ // A model: nested point clouds
839
+ // ---------------------------------------------------------------------------
840
+
841
+ /** Options of {@link ripsThinningLadder}. */
842
+ export interface RipsThinningOptions {
843
+ /** Whether each point survives the thinning (is in the lower row's cloud), one entry per point: `true` or `1` to keep it, `false` or `0`. Required. */
844
+ readonly keep: ArrayLike<boolean | number>;
845
+ /** The edge lengths `ℓ_1 < … < ℓ_n`, finite, non-negative and strictly increasing: a simplex enters at the first `ℓ_i` at least its diameter (its longest edge). Required. */
846
+ readonly edgeLengths: ArrayLike<number>;
847
+ /** The largest simplex dimension built (degree `q` needs `q + 1`), an integer from 0 to 8. Default 2. */
848
+ readonly maxSimplexDim?: number;
849
+ }
850
+
851
+ const RIPS_THINNING_KEYS: Keys<RipsThinningOptions> = { keep: true, edgeLengths: true, maxSimplexDim: true };
852
+
853
+ /**
854
+ * The thinning model ([reference](https://topolab.ai/tda/docs/references/#hiraoka-nakashima-obayashi-and-xu-2023), §5.2) with Vietoris–Rips complexes:
855
+ * the upper row is the Rips filtration of the cloud, the lower row the Rips
856
+ * filtration of the points kept, both at the given edge lengths. Rips of a
857
+ * subset is the full subcomplex of Rips of the whole cloud, so the rows
858
+ * nest.
859
+ */
860
+ export function ripsThinningLadder(cloud: PointCloud, opts: RipsThinningOptions): FlatLadderFiltration {
861
+ engine();
862
+ const o = options<RipsThinningOptions>(opts, 'ripsThinningLadder', RIPS_THINNING_KEYS);
863
+ const n = points(cloud, 'points', { squaredDistances: true });
864
+ const keep = o.keep;
865
+ if (keep === null || typeof keep !== 'object' || typeof keep.length !== 'number') {
866
+ throw new TypeError(`keep must be an array of booleans, got ${kind(keep)}`);
867
+ }
868
+ if (keep.length !== n) throw new RangeError(`keep must have one entry per point (${n}), got length ${keep.length}`);
869
+ const inLower = new Uint8Array(n);
870
+ for (let i = 0; i < n; i++) {
871
+ const k = keep[i];
872
+ if (k !== true && k !== false && k !== 0 && k !== 1) {
873
+ throw new TypeError(`keep[${i}] must be a boolean (or 0 or 1), got ${kind(k)}`);
874
+ }
875
+ inLower[i] = k ? 1 : 0;
876
+ }
877
+ const lengths = o.edgeLengths;
878
+ if (lengths === null || typeof lengths !== 'object' || typeof lengths.length !== 'number') {
879
+ throw new TypeError(`edgeLengths must be an array of numbers, got ${kind(lengths)}`);
880
+ }
881
+ const edgeLengths = new Float64Array(lengths.length);
882
+ for (let i = 0; i < lengths.length; i++) {
883
+ const x = lengths[i];
884
+ if (typeof x !== 'number') throw new TypeError(`edgeLengths[${i}] must be a number, got ${kind(x)}`);
885
+ edgeLengths[i] = x;
886
+ }
887
+ if (edgeLengths.length === 0) throw new RangeError('edgeLengths must hold at least one edge length');
888
+ for (let i = 0; i < edgeLengths.length; i++) {
889
+ if (!Number.isFinite(edgeLengths[i])) throw new RangeError(`edgeLengths[${i}] must be finite, got ${edgeLengths[i]}`);
890
+ if (!(edgeLengths[i]! >= 0)) throw new RangeError(`edgeLengths[${i}] must be non-negative, got ${edgeLengths[i]}`);
891
+ if (i > 0 && !(edgeLengths[i]! > edgeLengths[i - 1]!)) {
892
+ throw new RangeError(`edgeLengths must be strictly increasing, but edgeLengths[${i}] = ${edgeLengths[i]} follows ${edgeLengths[i - 1]}`);
893
+ }
894
+ }
895
+ const maxSimplexDim = o.maxSimplexDim === undefined ? 2 : int(o.maxSimplexDim, 'maxSimplexDim', 0, 8);
896
+ return take(run((e) => e.ripsThinningLadder(cloud.coords, cloud.d, inLower, edgeLengths, maxSimplexDim)), (r) => ({
897
+ n: r.n,
898
+ offsets: r.offsets,
899
+ vertices: r.vertices,
900
+ lower: r.lower,
901
+ upper: r.upper,
902
+ }));
903
+ }