@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
@@ -0,0 +1,752 @@
1
+ /**
2
+ * Persistence of a complex the caller holds, of Rips filtrations, of images,
3
+ * of zigzags, and the volume-optimal cycles of a complex (internal module;
4
+ * the package root re-exports the API).
5
+ */
6
+ import { call, module } from './load.js';
7
+ import {
8
+ coeff as checkCoeff,
9
+ finite,
10
+ int,
11
+ isTyped,
12
+ kind,
13
+ minPersistence as checkMinPersistence,
14
+ nonNegative,
15
+ num,
16
+ oneOf,
17
+ options,
18
+ points as checkPoints,
19
+ viewKind
20
+ } from './check.js';
21
+ import type { Keys, PointCloud } from './check.js';
22
+ import { distanceMatrix, gridArgs, isMatrix } from './complex.js';
23
+ import { diagramOf } from './diagram_of.js';
24
+ import type { ComplexLike, Diagram, DistanceMatrix, Grid, Scale } from './types.js';
25
+ import type { CapacityError, CapacityDetails } from './memory.js';
26
+
27
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
28
+ type Raw = any;
29
+
30
+ const SCALES: readonly Scale[] = ['edgeLength', 'radius', 'squaredRadius', 'squaredRelaxation', 'epsilon', 'growthRadius', 'value'];
31
+
32
+ const INT32_MIN = -2147483648;
33
+ const INT32_MAX = 2147483647;
34
+ // The object form already holds an operation object and often a boundary
35
+ // array per record. Limit its additional packed copy to a conservative 1 GiB.
36
+ // PackedZigzag accepts the same records without this second JS structure.
37
+ const ZIGZAG_OBJECT_CONVERSION_BUDGET = 1_073_741_824;
38
+
39
+ function refuseZigzagObjectConversion(operations: number): never {
40
+ const status = module().__oom_status();
41
+ const memoryBytes = status.memory.buffer.byteLength;
42
+ const declaredMaxBytes = status.limitBytes as number;
43
+ const requestedBytes = operations * 5 * Float64Array.BYTES_PER_ELEMENT;
44
+ const details: CapacityDetails = {
45
+ function: 'zigzagPersistence', phase: 'input-conversion', requestedBytes,
46
+ inUseBytes: null, memoryBytes, committedBytes: memoryBytes,
47
+ limitBytes: ZIGZAG_OBJECT_CONVERSION_BUDGET, declaredMaxBytes,
48
+ allocationLimitBytes: Math.min(declaredMaxBytes, 2_147_483_647),
49
+ hostConversionBudgetBytes: ZIGZAG_OBJECT_CONVERSION_BUDGET,
50
+ input: { operations }, parameters: {},
51
+ estimateMethod: 'The request is a lower bound of five Float64 fields per operation. Boundaries add fields. The 1 GiB conversion budget is a conservative policy, not a measured JavaScript heap ceiling or a whole-input fit estimate.'
52
+ };
53
+ const error = new RangeError(`zigzagPersistence: input too large while building JavaScript records; at least ${requestedBytes} bytes requested by ${operations} operations, above the ${ZIGZAG_OBJECT_CONVERSION_BUDGET} byte object-conversion budget. Pass packed Float64Array records to avoid the extra copy.`) as CapacityError;
54
+ Object.assign(error, { code: 'TOO_LARGE', details });
55
+ throw error;
56
+ }
57
+
58
+ /**
59
+ * A complex argument as the typed arrays the engine reads: typed arrays of
60
+ * the right kind pass through, plain arrays (or other typed arrays) are
61
+ * checked (32-bit integer vertex ids, non-negative integer offsets, numbers)
62
+ * and converted. The rest (CSR shape, closure, monotonicity, NaN) the Rust
63
+ * core checks, naming the simplex.
64
+ */
65
+ export function complexArgs(
66
+ v: unknown,
67
+ name: string
68
+ ): { vertices: Int32Array; offsets: Uint32Array; filtrations: Float64Array; scale: Scale; top: number } {
69
+ const c = v as Partial<ComplexLike> | null;
70
+ const arrayLike = (x: unknown): x is ArrayLike<number> => Array.isArray(x) || (viewKind(x) !== undefined && viewKind(x) !== 'DataView');
71
+ if (c === null || typeof c !== 'object' || !arrayLike(c.vertices) || !arrayLike(c.offsets) || !arrayLike(c.filtrations)) {
72
+ throw new TypeError(
73
+ `${name} must be a complex { vertices, offsets, filtrations } (Int32Array, Uint32Array, Float64Array or arrays of numbers), got ${kind(v)}`
74
+ );
75
+ }
76
+ let vertices: Int32Array;
77
+ if (isTyped(c.vertices, 'Int32Array')) {
78
+ vertices = c.vertices;
79
+ } else {
80
+ const raw = c.vertices;
81
+ for (let j = 0; j < raw.length; j++) {
82
+ const x = raw[j];
83
+ if (typeof x !== 'number') throw new TypeError(`${name}.vertices[${j}] must be a number, got ${kind(x)}`);
84
+ if (!Number.isInteger(x) || x! < INT32_MIN || x! > INT32_MAX) {
85
+ throw new RangeError(`${name}.vertices[${j}] must be an integer from ${INT32_MIN} to ${INT32_MAX}, got ${String(x)}`);
86
+ }
87
+ }
88
+ vertices = Int32Array.from(raw);
89
+ }
90
+ let offsets: Uint32Array;
91
+ if (isTyped(c.offsets, 'Uint32Array')) {
92
+ offsets = c.offsets;
93
+ } else {
94
+ const raw = c.offsets;
95
+ for (let j = 0; j < raw.length; j++) {
96
+ const x = raw[j];
97
+ if (typeof x !== 'number') throw new TypeError(`${name}.offsets[${j}] must be a number, got ${kind(x)}`);
98
+ if (!Number.isInteger(x) || x! < 0 || x! > 4294967295) {
99
+ throw new RangeError(`${name}.offsets[${j}] must be an integer from 0 to 4294967295, got ${String(x)}`);
100
+ }
101
+ }
102
+ offsets = Uint32Array.from(raw);
103
+ }
104
+ let filtrations: Float64Array;
105
+ if (isTyped(c.filtrations, 'Float64Array')) {
106
+ filtrations = c.filtrations;
107
+ } else {
108
+ const raw = c.filtrations;
109
+ for (let j = 0; j < raw.length; j++) {
110
+ if (typeof raw[j] !== 'number') throw new TypeError(`${name}.filtrations[${j}] must be a number, got ${kind(raw[j])}`);
111
+ }
112
+ filtrations = Float64Array.from(raw);
113
+ }
114
+ const scale = c.scale === undefined ? 'value' : oneOf(c.scale, `${name}.scale`, SCALES);
115
+ let top = -1;
116
+ for (let i = 0; i + 1 < offsets.length; i++) top = Math.max(top, offsets[i + 1]! - offsets[i]! - 1);
117
+ return { vertices, offsets, filtrations, scale, top };
118
+ }
119
+
120
+ /** @internal Whether checked complex arrays are the empty complex: no simplex, `offsets` `[0]`. */
121
+ export function isEmptyComplex(c: { vertices: Int32Array; offsets: Uint32Array; filtrations: Float64Array }): boolean {
122
+ return c.filtrations.length === 0 && c.offsets.length === 1 && c.offsets[0] === 0 && c.vertices.length === 0;
123
+ }
124
+
125
+ /** Options of {@link persistence}. */
126
+ export interface PersistenceOptions {
127
+ /** The prime `p` of the coefficient field `Z/p`, from 2 to `2^31 − 1`. Default 2. */
128
+ coeff?: number;
129
+ /**
130
+ * Leave out the finite pairs with `death − birth <= minPersistence`
131
+ * (GUDHI's `min_persistence`); essential pairs are always kept. A finite
132
+ * number `>= 0`. Default 0: only the pairs of length zero are left out.
133
+ * `1e-12` removes the bars one ulp long that rounding leaves on symmetric
134
+ * input such as a lattice.
135
+ */
136
+ minPersistence?: number;
137
+ }
138
+
139
+ /** @internal The option keys of {@link PersistenceOptions}. */
140
+ export const PERSISTENCE_KEYS: Keys<PersistenceOptions> = { coeff: true, minPersistence: true };
141
+
142
+ /**
143
+ * The persistence diagram of a filtered simplicial complex: one a builder
144
+ * returned, or one the caller builds as `{ vertices, offsets, filtrations }`
145
+ * (`scale` is read when present, `'value'` otherwise).
146
+ *
147
+ * The complex must be closed (every face of every simplex listed, its
148
+ * vertices included) and monotone (no face valued above a coface); no
149
+ * simplex may be listed twice or list a vertex twice, and no value may be
150
+ * NaN (`Infinity`, `-Infinity` and `-0` are fine). Anything else is a
151
+ * `RangeError` naming the simplex. Vertex ids are any 32-bit integers;
152
+ * vertex order within a simplex and simplex order do not matter.
153
+ *
154
+ * The Rust core puts the simplices in the documented order and its reducer
155
+ * computes the pairs over `Z/coeff`, in
156
+ * every dimension up to the complex's top one (an empty complex has an
157
+ * empty diagram). Within a dimension the finite pairs come in the order of
158
+ * their death simplex, then the essential classes in the order of their
159
+ * birth simplex: an order that depends on the complex only.
160
+ */
161
+ export function persistence(complex: ComplexLike, opts?: PersistenceOptions): Diagram {
162
+ module();
163
+ const o = options<PersistenceOptions>(opts, 'persistence', PERSISTENCE_KEYS);
164
+ const c = complexArgs(complex, 'complex');
165
+ const coeff = checkCoeff(o.coeff);
166
+ const minPersistence = checkMinPersistence(o.minPersistence);
167
+ // The empty complex (one offset, 0) has an empty diagram; any other shape
168
+ // with no values goes to the engine, which refuses it.
169
+ if (isEmptyComplex(c)) return diagramOf(new Float64Array(0), c.top, c.scale, coeff);
170
+ return call('persistence', (m) =>
171
+ diagramOf(m.persistenceFlat(c.vertices, c.offsets, c.filtrations, coeff), c.top, c.scale, coeff, minPersistence)
172
+ );
173
+ }
174
+
175
+ // ---------------------------------------------------------------------------
176
+ // Rips
177
+ // ---------------------------------------------------------------------------
178
+
179
+ /** Which representatives {@link ripsPersistence} returns, and of which dimensions. */
180
+ export interface RepresentativesOptions {
181
+ /**
182
+ * `'cycles'` (default): for every finite pair a cycle (simplices with zero
183
+ * boundary, all present at the birth: for H₁ the edges of a loop), from a
184
+ * homology reduction over the death simplices. `'cocycles'`: for every
185
+ * pair, essential ones included, the reduction column of the cohomology
186
+ * pass (what ripser.py's `do_cocycles` returns).
187
+ */
188
+ kind?: 'cycles' | 'cocycles';
189
+ /** The homology dimensions to return representatives for. Default: every dimension up to `maxDim`; `[]` returns none. */
190
+ dims?: number[];
191
+ }
192
+
193
+ const REPRESENTATIVES_KEYS: Keys<RepresentativesOptions> = { kind: true, dims: true };
194
+
195
+ /** Options of {@link ripsPersistence}. */
196
+ export interface RipsPersistenceOptions {
197
+ /** The highest homology dimension, an integer from 0 to 9. Default 1. */
198
+ maxDim?: number;
199
+ /**
200
+ * Keep the simplices of diameter `<= maxEdgeLength`, non-negative.
201
+ * Default `Infinity`: the filtration is cut at the enclosing radius, past
202
+ * which every Rips complex is a cone, so no pair is lost.
203
+ */
204
+ maxEdgeLength?: number;
205
+ /** The prime `p` of the coefficient field `Z/p`, from 2 to `2^31 − 1`. Default 2. */
206
+ coeff?: number;
207
+ /**
208
+ * Also return a representative of every pair (`true` for the default
209
+ * {@link RepresentativesOptions}). Default `false`. The representatives of
210
+ * the pairs `minPersistence` leaves out are left out too.
211
+ */
212
+ representatives?: boolean | RepresentativesOptions;
213
+ /**
214
+ * Leave out the finite pairs with `death − birth <= minPersistence`
215
+ * (GUDHI's `min_persistence`); essential pairs are always kept. A finite
216
+ * number `>= 0`. Default 0: only the pairs of length zero are left out.
217
+ * `1e-12` removes the bars one ulp long that rounding leaves on symmetric
218
+ * input such as a lattice.
219
+ */
220
+ minPersistence?: number;
221
+ }
222
+
223
+ const RIPS_PERSISTENCE_KEYS: Keys<RipsPersistenceOptions> = {
224
+ maxDim: true,
225
+ maxEdgeLength: true,
226
+ coeff: true,
227
+ representatives: true,
228
+ minPersistence: true
229
+ };
230
+
231
+ /**
232
+ * The representatives of the pairs of a Rips diagram, as typed arrays
233
+ * (`materialize()` builds the objects). Representative `i` stands for pair
234
+ * `pairIndex[i]` of dimension `dims[i]` (the pair `pairs[dims[i]][2p]`,
235
+ * `pairs[dims[i]][2p + 1]`); its simplices are `simplexOffsets[i] ..
236
+ * simplexOffsets[i + 1]`, with their coefficients at the same positions of
237
+ * `coefficients` and their vertex ids, `dims[i] + 1` per simplex, ascending
238
+ * within a simplex (a simplex is oriented by that order), in
239
+ * `vertices[vertexOffsets[i] .. vertexOffsets[i + 1]]`.
240
+ *
241
+ * What a representative is (the package's tests check every one against the
242
+ * input itself): a cycle has zero boundary, every simplex has
243
+ * diameter `<= birth` and one exactly `birth`, it is not a cycle created before
244
+ * `birth` plus a boundary before `death`, and it is a boundary at `death` up
245
+ * to cycles created before `birth`; a cocycle has zero coboundary on every
246
+ * simplex of diameter `< death`, non-zero coboundary on some simplex of
247
+ * diameter `death`, and every simplex has diameter in [`birth`, `death`].
248
+ * Representatives are not unique, nor the shortest.
249
+ */
250
+ export interface RipsRepresentatives {
251
+ /** The kind of representative. */
252
+ kind: 'cycles' | 'cocycles';
253
+ /** The homology dimension of each representative. */
254
+ dims: Uint8Array;
255
+ /** The index of each representative's pair within the pairs of its dimension. */
256
+ pairIndex: Uint32Array;
257
+ /** The birth of each representative's pair. */
258
+ births: Float64Array;
259
+ /** The death of each representative's pair. */
260
+ deaths: Float64Array;
261
+ /** Length `count + 1`: the simplices of representative `i`. */
262
+ simplexOffsets: Uint32Array;
263
+ /** Length `count + 1`: the vertex ids of representative `i`. */
264
+ vertexOffsets: Uint32Array;
265
+ /** Vertex ids (indices into the input), `dims[i] + 1` per simplex. */
266
+ vertices: Int32Array;
267
+ /** The coefficient of each simplex, in `(−coeff/2, coeff/2]`; always 1 over `Z/2`. */
268
+ coefficients: Int32Array;
269
+ }
270
+
271
+ /** A Rips diagram, with the representatives when asked for. */
272
+ export interface RipsPersistence extends Diagram {
273
+ /** Present only with `representatives`. */
274
+ representatives?: RipsRepresentatives;
275
+ }
276
+
277
+ /** The kind and the dimension bit mask of a representatives request. */
278
+ function representativeRequest(v: unknown, maxDim: number): { kind: 'cycles' | 'cocycles'; mask: number } | null {
279
+ if (v === undefined || v === false) return null;
280
+ const o = v === true ? {} : options<RepresentativesOptions>(v, 'ripsPersistence', REPRESENTATIVES_KEYS, 'representatives', 'representatives.');
281
+ const k = o.kind === undefined ? 'cycles' : oneOf(o.kind, 'representatives.kind', ['cycles', 'cocycles'] as const);
282
+ let mask = 0;
283
+ if (o.dims === undefined) {
284
+ mask = (1 << (maxDim + 1)) - 1;
285
+ } else {
286
+ if (!Array.isArray(o.dims)) throw new TypeError(`representatives.dims must be an array of integers, got ${kind(o.dims)}`);
287
+ // An index loop, not forEach: a hole is an entry like any other, and refused.
288
+ for (let i = 0; i < o.dims.length; i++) {
289
+ const d = int(o.dims[i], `representatives.dims[${i}]`, 0, maxDim);
290
+ mask |= 1 << d;
291
+ }
292
+ }
293
+ return { kind: k, mask };
294
+ }
295
+
296
+ /**
297
+ * The engine's representatives as {@link RipsRepresentatives} against the
298
+ * per-dimension diagram. The engine has already left out the pairs
299
+ * `minPersistence` leaves out, with their representatives; here each representative's pair
300
+ * index into the flat list becomes (dimension, index within the dimension),
301
+ * the layout {@link diagramOf} gives the pairs.
302
+ */
303
+ function representativesOf(raw: Raw, kindOf: 'cycles' | 'cocycles'): { diagram: Float64Array; reps: RipsRepresentatives } {
304
+ const flat: Float64Array = raw.pairs;
305
+ const m = flat.length / 3;
306
+ const within = new Uint32Array(m);
307
+ const seen: number[] = [];
308
+ for (let p = 0; p < m; p++) {
309
+ const k = flat[3 * p]!;
310
+ while (seen.length <= k) seen.push(0);
311
+ within[p] = seen[k]!++;
312
+ }
313
+ const index: Uint32Array = raw.pairIndex;
314
+ const count = index.length;
315
+ const dims = new Uint8Array(count);
316
+ const pairIndex = new Uint32Array(count);
317
+ const births = new Float64Array(count);
318
+ const deaths = new Float64Array(count);
319
+ for (let i = 0; i < count; i++) {
320
+ const p = index[i]!;
321
+ dims[i] = flat[3 * p]!;
322
+ pairIndex[i] = within[p]!;
323
+ births[i] = flat[3 * p + 1]!;
324
+ deaths[i] = flat[3 * p + 2]!;
325
+ }
326
+ return {
327
+ diagram: flat,
328
+ reps: {
329
+ kind: kindOf,
330
+ dims,
331
+ pairIndex,
332
+ births,
333
+ deaths,
334
+ simplexOffsets: raw.simplexOffsets,
335
+ vertexOffsets: raw.vertexOffsets,
336
+ vertices: raw.vertices,
337
+ coefficients: raw.coefficients
338
+ }
339
+ };
340
+ }
341
+
342
+ /**
343
+ * The Vietoris–Rips persistence diagram of a point cloud or of a distance
344
+ * matrix, H₀ up to dimension `maxDim`, by the Rust core without building the complex
345
+ * (persistent cohomology with clearing, implicit coboundaries and
346
+ * apparent pairs, after Ripser ([reference](https://topolab.ai/tda/docs/references/#bauer-2021)); an edge collapse before H₂ and up).
347
+ * Distances are computed in double precision in GUDHI's order, so the
348
+ * diagram is GUDHI's, value for value, on dimensions 0 to `maxDim`; the
349
+ * classes a truncated complex reports in dimension `maxDim + 1` are not
350
+ * reported. A distance matrix is read in its strict lower triangle;
351
+ * `Infinity` entries are absent edges and no entry may be NaN or negative.
352
+ * A point cloud with two points whose squared distance overflows double
353
+ * precision is refused (a `RangeError`: rescale it). Within a dimension the pairs come in
354
+ * the engine's order. The Rips key holds the colex index of a simplex's
355
+ * vertices off its longest edge in 32 bits, so C(n, `maxDim`) must be below
356
+ * 2^32 for n points (at most 2,954 points at `maxDim` 3, 52 at 9); a larger
357
+ * input is refused with a `RangeError` whose message starts with
358
+ * `input too large:`.
359
+ *
360
+ * With `representatives`, the pairs (the same multiset, every value bit;
361
+ * the order within a dimension may differ) come with a representative cycle
362
+ * or cocycle each ({@link RipsRepresentatives}). Representatives are
363
+ * computed on the uncollapsed filtration, which is slower on dense
364
+ * filtrations in dimension 2 and up; past a working column of 256 MiB,
365
+ * cocycles are refused (a `RangeError`, `input too large:`) and cycles are computed on the collapsed
366
+ * filtration instead (still cycles of the Rips complex, of the same bars).
367
+ */
368
+ export function ripsPersistence(points: PointCloud | DistanceMatrix, opts?: RipsPersistenceOptions): RipsPersistence {
369
+ module();
370
+ const o = options<RipsPersistenceOptions>(opts, 'ripsPersistence', RIPS_PERSISTENCE_KEYS);
371
+ const matrix = isMatrix(points, 'points');
372
+ const n = matrix ? distanceMatrix(points, 'points') : checkPoints(points, 'points', { squaredDistances: true });
373
+ const maxDim = o.maxDim === undefined ? 1 : int(o.maxDim, 'maxDim', 0, 9);
374
+ const maxEdgeLength = o.maxEdgeLength === undefined ? Infinity : nonNegative(o.maxEdgeLength, 'maxEdgeLength');
375
+ const coeff = checkCoeff(o.coeff);
376
+ const request = representativeRequest(o.representatives, maxDim);
377
+ const minPersistence = checkMinPersistence(o.minPersistence);
378
+ return call('ripsPersistence', (m) => {
379
+ const head = matrix ? [(points as DistanceMatrix).distances, n] : [(points as PointCloud).coords, (points as PointCloud).d];
380
+ if (request === null) {
381
+ const flat: Float64Array = matrix
382
+ ? m.ripsPersistenceFromDistanceMatrixFlat(...head, maxDim, maxEdgeLength, coeff)
383
+ : m.ripsPersistenceFlat(...head, maxDim, maxEdgeLength, coeff);
384
+ return diagramOf(flat, maxDim, 'edgeLength', coeff, minPersistence);
385
+ }
386
+ const kindCode = request.kind === 'cocycles' ? 1 : 0;
387
+ const raw = matrix
388
+ ? m.ripsRepresentativesFromDistanceMatrixFlat(...head, maxDim, maxEdgeLength, coeff, kindCode, request.mask, minPersistence)
389
+ : m.ripsRepresentativesFlat(...head, maxDim, maxEdgeLength, coeff, kindCode, request.mask, minPersistence);
390
+ const { diagram, reps } = representativesOf(raw, request.kind);
391
+ return { ...diagramOf(diagram, maxDim, 'edgeLength', coeff), representatives: reps };
392
+ });
393
+ }
394
+
395
+ // ---------------------------------------------------------------------------
396
+ // Cubical
397
+ // ---------------------------------------------------------------------------
398
+
399
+ /** Options of {@link cubicalPersistence}. */
400
+ export interface CubicalPersistenceOptions {
401
+ /**
402
+ * `'T'` (default): each value sits on a top-dimensional cell (pixel,
403
+ * voxel) and every lower cell enters at the smallest value among the top
404
+ * cells containing it. `'V'` (2-D only): each value sits on a vertex and
405
+ * every cell enters at the largest value among its vertices. The names of
406
+ * Garin et al. 2020 and CubicalRipser.
407
+ */
408
+ construction?: 'T' | 'V';
409
+ /** The prime `p` of the coefficient field `Z/p`, from 2 to `2^31 − 1`. Default 2. */
410
+ coeff?: number;
411
+ /**
412
+ * Leave out the finite pairs with `death − birth <= minPersistence`
413
+ * (GUDHI's `min_persistence`); essential pairs are always kept. A finite
414
+ * number `>= 0`. Default 0: only the pairs of length zero are left out.
415
+ * `1e-12` removes the bars one ulp long that rounding leaves on symmetric
416
+ * input such as a lattice.
417
+ */
418
+ minPersistence?: number;
419
+ }
420
+
421
+ const CUBICAL_KEYS: Keys<CubicalPersistenceOptions> = { construction: true, coeff: true, minPersistence: true };
422
+
423
+ /**
424
+ * The sublevel-set persistence diagram of an image or a volume, homology up
425
+ * to the number of axes. 2-D and 3-D grids run the Rust core (union-find
426
+ * with Alexander duality; H₁ of volumes by a cohomology reduction over
427
+ * `Z/coeff`); other grids (up to 16 axes) run the Rust core's reducer over
428
+ * its cells. The T diagram
429
+ * is GUDHI's bitmap complex's in every case, up to the
430
+ * sign of a zero on input holding both -0 and +0; within a dimension the
431
+ * pairs come in the engine's order. In 2-D the field does not change the
432
+ * diagram.
433
+ */
434
+ export function cubicalPersistence(image: Grid, opts?: CubicalPersistenceOptions): Diagram {
435
+ module();
436
+ const o = options<CubicalPersistenceOptions>(opts, 'cubicalPersistence', CUBICAL_KEYS);
437
+ const extents = gridArgs(image, 'image');
438
+ const construction = o.construction === undefined ? 'T' : oneOf(o.construction, 'construction', ['T', 'V'] as const);
439
+ const coeff = checkCoeff(o.coeff);
440
+ const minPersistence = checkMinPersistence(o.minPersistence);
441
+ const top = image.shape.length;
442
+ if (construction === 'V') {
443
+ if (image.shape.length !== 2) {
444
+ throw new RangeError(`construction 'V' takes a 2-D image (image.shape of length 2), got ${image.shape.length} axes`);
445
+ }
446
+ return call('cubicalPersistence', (m) =>
447
+ diagramOf(m.cubicalVertexPersistenceFlat(image.values, image.shape[1], image.shape[0]), top, 'value', coeff, minPersistence)
448
+ );
449
+ }
450
+ return call('cubicalPersistence', (m) => diagramOf(m.cubicalPersistenceFlat(extents, image.values, coeff), top, 'value', coeff, minPersistence));
451
+ }
452
+
453
+ // ---------------------------------------------------------------------------
454
+ // Zigzag
455
+ // ---------------------------------------------------------------------------
456
+
457
+ /** An insertion of a cell into a zigzag (made by {@link insertOp}). */
458
+ export interface InsertOp {
459
+ type: 'insert';
460
+ /** The cell's id, a 32-bit integer. */
461
+ cell: number;
462
+ /** The ids of the cell's faces one dimension down, in the complex at that moment (empty for a vertex). */
463
+ boundary: number[];
464
+ /** The cell's dimension. */
465
+ dim: number;
466
+ /** The operation's value; when every operation has one, the diagram is on these values too. */
467
+ value?: number;
468
+ }
469
+
470
+ /** A removal of a cell from a zigzag (made by {@link removeOp}). */
471
+ export interface RemoveOp {
472
+ type: 'remove';
473
+ /** The cell's id. */
474
+ cell: number;
475
+ /** The operation's value; when every operation has one, the diagram is on these values too. */
476
+ value?: number;
477
+ }
478
+
479
+ /** One operation of a zigzag. */
480
+ export type ZigzagOp = InsertOp | RemoveOp;
481
+
482
+ /** Insert cell `cell` of dimension `dim` with faces `boundary`, at `value` if given. */
483
+ export function insertOp(cell: number, boundary: number[], dim: number, value?: number): InsertOp {
484
+ return value === undefined ? { type: 'insert', cell, boundary, dim } : { type: 'insert', cell, boundary, dim, value };
485
+ }
486
+
487
+ /** Remove cell `cell`, at `value` if given. */
488
+ export function removeOp(cell: number, value?: number): RemoveOp {
489
+ return value === undefined ? { type: 'remove', cell } : { type: 'remove', cell, value };
490
+ }
491
+
492
+ /** Packed zigzag operations, without one JavaScript object per operation.
493
+ * Each record is `[kind, cell, dim, value, boundaryLength, ...boundary]`.
494
+ * `kind` is 0 for insertion, 1 for removal; removals use dim=0 and no boundary.
495
+ * Set withValues when the value column supplies the monotone operation values.
496
+ * The engine validates the same cell-complex and value rules as object input.
497
+ */
498
+ export interface PackedZigzag {
499
+ records: Float64Array;
500
+ withValues?: boolean;
501
+ }
502
+
503
+ /** Options of {@link zigzagPersistence}. */
504
+ export interface ZigzagPersistenceOptions {
505
+ /**
506
+ * Leave out the finite bars with `death − birth <= minPersistence`,
507
+ * measured in the units the bars are reported in (GUDHI's
508
+ * `min_persistence`); bars that persist after the last operation are always
509
+ * kept. When every operation has a value, the bars of `pairs` are measured
510
+ * on those values and `indexPairs` keeps every bar; otherwise the bars of
511
+ * `indexPairs` are measured in operations (a bar is at least one operation
512
+ * long, so `1` leaves out the bars that last one operation). A finite
513
+ * number `>= 0`. Default 0: nothing more is left out.
514
+ */
515
+ minPersistence?: number;
516
+ }
517
+
518
+ const ZIGZAG_KEYS: Keys<ZigzagPersistenceOptions> = { minPersistence: true };
519
+
520
+ /** The diagram of a zigzag. */
521
+ export interface ZigzagPersistence {
522
+ /**
523
+ * `indexPairs[k]`: the bars of Hₖ on operation indices,
524
+ * `[birth, death, …]`: the class exists after operation `birth` and no
525
+ * longer after operation `death`, `Infinity` when it persists after the
526
+ * last operation. In no particular order. Without values, the bars no
527
+ * longer than `minPersistence` operations are left out.
528
+ */
529
+ indexPairs: Float64Array[];
530
+ /**
531
+ * `pairs[k]`, present when every operation has a value: the bars of Hₖ
532
+ * on those values, each endpoint the value of its operation (copied
533
+ * through), `Infinity` for a class that persists after the last operation; on
534
+ * non-increasing values the two endpoints are swapped so that
535
+ * birth <= death, and a bar between two operations of one value (length
536
+ * zero) is left out, as is a bar no longer than `minPersistence`.
537
+ */
538
+ pairs?: Float64Array[];
539
+ /** Always `'value'`. */
540
+ scale: 'value';
541
+ /** Always 2: zigzag persistence is computed over Z/2. */
542
+ coeff: 2;
543
+ }
544
+
545
+ /**
546
+ * Zigzag persistence of a sequence of insertions and removals of cells,
547
+ * by the FastZigzag conversion ([reference](https://topolab.ai/tda/docs/references/#dey-and-hou-2022)): the zigzag becomes one ordinary
548
+ * filtration of the cone over a non-repetitive copy of it, reduced over Z/2
549
+ * and read back as zigzag intervals. Homology up to
550
+ * the highest cell dimension. Z/2 only; no representatives.
551
+ *
552
+ * The operations must describe a zigzag of cell complexes, or the call is
553
+ * refused with a `RangeError` naming the operation: every face of an
554
+ * inserted cell is in the complex at that moment and has one dimension
555
+ * less; a vertex has no face, an edge two; the faces of a cell of
556
+ * dimension 2 or more form a cycle (every cell two dimensions down is a face
557
+ * of an even number of them); a cell is not inserted while it
558
+ * is in the complex, nor removed while it is not or while a coface of it is.
559
+ * When the operations have values, the values must be monotone (all
560
+ * non-decreasing or all non-increasing) and not NaN; either every operation
561
+ * has a value or none has.
562
+ */
563
+ export function zigzagPersistence(ops: ZigzagOp[] | PackedZigzag, opts?: ZigzagPersistenceOptions): ZigzagPersistence {
564
+ module();
565
+ const o = options<ZigzagPersistenceOptions>(opts, 'zigzagPersistence', ZIGZAG_KEYS);
566
+ let top = -1;
567
+ let records: Float64Array;
568
+ let withValues: boolean;
569
+ if (Array.isArray(ops)) {
570
+ if (ops.length * 5 * Float64Array.BYTES_PER_ELEMENT > ZIGZAG_OBJECT_CONVERSION_BUDGET) refuseZigzagObjectConversion(ops.length);
571
+ if (ops.length === 0) throw new RangeError('ops must hold at least one operation');
572
+ let length = 0;
573
+ let valued = 0;
574
+ // Index loops, not forEach: a hole is an entry like any other, and refused.
575
+ for (let i = 0; i < ops.length; i++) {
576
+ const op = ops[i]!;
577
+ if (op === null || typeof op !== 'object') throw new TypeError(`ops[${i}] must be an operation, got ${kind(op)}`);
578
+ // Build parameter paths only on refusal, preserving the existing checks
579
+ // and messages without allocating a string for every valid cell/face.
580
+ const type: unknown = op.type;
581
+ if (type !== 'insert' && type !== 'remove') oneOf(type, `ops[${i}].type`, ['insert', 'remove'] as const);
582
+ if (!Number.isInteger(op.cell) || op.cell < INT32_MIN || op.cell > INT32_MAX) int(op.cell, `ops[${i}].cell`, INT32_MIN, INT32_MAX);
583
+ if (op.value !== undefined) {
584
+ if (typeof op.value !== 'number') num(op.value, `ops[${i}].value`);
585
+ valued++;
586
+ }
587
+ if (op.type === 'insert') {
588
+ if (!Array.isArray(op.boundary)) throw new TypeError(`ops[${i}].boundary must be an array of cell ids, got ${kind(op.boundary)}`);
589
+ const boundary = op.boundary;
590
+ for (let j = 0; j < boundary.length; j++) {
591
+ const id = boundary[j]!;
592
+ if (!Number.isInteger(id) || id < INT32_MIN || id > INT32_MAX) int(id, `ops[${i}].boundary[${j}]`, INT32_MIN, INT32_MAX);
593
+ }
594
+ if (!Number.isSafeInteger(op.dim) || op.dim < 0 || op.dim > INT32_MAX) int(op.dim, `ops[${i}].dim`, 0);
595
+ top = Math.max(top, op.dim);
596
+ length += 5 + boundary.length;
597
+ } else {
598
+ length += 5;
599
+ }
600
+ }
601
+ if (valued !== 0 && valued !== ops.length) {
602
+ const missing = ops.findIndex((op) => op.value === undefined);
603
+ throw new RangeError(`ops[${missing}].value is missing: give every operation a value, or none`);
604
+ }
605
+ records = new Float64Array(length);
606
+ let at = 0;
607
+ for (const op of ops) {
608
+ records[at++] = op.type === 'insert' ? 0 : 1;
609
+ records[at++] = op.cell;
610
+ records[at++] = op.type === 'insert' ? op.dim : 0;
611
+ records[at++] = op.value ?? 0;
612
+ const boundary = op.type === 'insert' ? op.boundary : [];
613
+ records[at++] = boundary.length;
614
+ for (const id of boundary) records[at++] = id;
615
+ }
616
+ withValues = valued === ops.length;
617
+ } else {
618
+ if (ops === null || typeof ops !== 'object' || !isTyped(ops.records, 'Float64Array')) {
619
+ throw new TypeError(`ops must be an array of operations, got ${kind(ops)}`);
620
+ }
621
+ if (ops.withValues !== undefined && typeof ops.withValues !== 'boolean') throw new TypeError('withValues must be a boolean');
622
+ records = ops.records;
623
+ withValues = ops.withValues ?? false;
624
+ if (records.length === 0) throw new RangeError('ops.records must hold at least one operation');
625
+ // Discover the output's dimensions in constant heap space. The engine
626
+ // checks the record contents and operation semantics; reject incomplete
627
+ // headers/counts here so this scan never skips outside the typed array.
628
+ for (let at = 0; at < records.length;) {
629
+ if (records.length - at < 5) throw new RangeError('truncated zigzag record header');
630
+ const count = records[at + 4]!;
631
+ if (!Number.isSafeInteger(count) || count < 0 || count > records.length - at - 5) throw new RangeError('invalid zigzag boundary length');
632
+ if (records[at] === 0) top = Math.max(top, records[at + 2]!);
633
+ at += 5 + count;
634
+ }
635
+ }
636
+ const minPersistence = checkMinPersistence(o.minPersistence);
637
+ return call('zigzagPersistence', (m) => {
638
+ const raw = m.zigzagPersistenceFlat(records, withValues);
639
+ const indices: Float64Array = raw.indices;
640
+ for (let i = 2; i < indices.length; i += 3) if (indices[i] === -1) indices[i] = Infinity;
641
+ const indexPairs = diagramOf(indices, top, 'value', 2, withValues ? 0 : minPersistence).pairs;
642
+ const result: ZigzagPersistence = { indexPairs, scale: 'value', coeff: 2 };
643
+ if (withValues) result.pairs = diagramOf(raw.values, top, 'value', 2, minPersistence).pairs;
644
+ return result;
645
+ });
646
+ }
647
+
648
+ // ---------------------------------------------------------------------------
649
+ // Volume-optimal cycles
650
+ // ---------------------------------------------------------------------------
651
+
652
+ /**
653
+ * Volume-optimal cycles as typed arrays (`materialize()` builds the
654
+ * objects). Result `r` is the pair `(births[r], deaths[r])` in dimension `dim`; its
655
+ * volume is the `(dim + 1)`-simplices in rows `volumeOffsets[r] ..
656
+ * volumeOffsets[r + 1]` of `volumeVertices` (`dim + 2` vertex ids a row,
657
+ * increasing), its boundary, the cycle, the `dim`-simplices in rows
658
+ * `boundaryOffsets[r] .. boundaryOffsets[r + 1]` of `boundaryVertices`
659
+ * (`dim + 1` ids a row, increasing),
660
+ * and the cycle's distinct vertices `cycleVertices[cycleVertexOffsets[r] ..
661
+ * cycleVertexOffsets[r + 1]]`, sorted. `found[r]` is 0 when the merge tree
662
+ * has no answer for the pair; its lists are then empty.
663
+ */
664
+ export interface VolumeOptimalCycles {
665
+ /** The homology dimension of every result (the ambient dimension minus one). */
666
+ dim: number;
667
+ births: Float64Array;
668
+ deaths: Float64Array;
669
+ found: Uint8Array;
670
+ /** Length `count + 1`, in rows (simplices). */
671
+ volumeOffsets: Uint32Array;
672
+ volumeVertices: Int32Array;
673
+ /** Length `count + 1`, in rows (simplices). */
674
+ boundaryOffsets: Uint32Array;
675
+ boundaryVertices: Int32Array;
676
+ /** Length `count + 1`. */
677
+ cycleVertexOffsets: Uint32Array;
678
+ cycleVertices: Int32Array;
679
+ }
680
+
681
+ /** Options of {@link volumeOptimalCycles}. */
682
+ export interface VolumeOptimalCyclesOptions {
683
+ /** The homology dimension `n − 1` of a triangulation of a convex domain in R^n, a non-negative integer. Required. */
684
+ dim: number;
685
+ /** One finite pair `[birth, death]`: find its cycle only. Default: every finite pair. */
686
+ pair?: [number, number];
687
+ /**
688
+ * Without `pair`, leave out the pairs with `death − birth <=
689
+ * minPersistence` and their cycles (GUDHI's `min_persistence`); `pair`
690
+ * itself is always answered. A finite number `>= 0`. Default 0.
691
+ */
692
+ minPersistence?: number;
693
+ }
694
+
695
+ const VOLUME_OPTIMAL_KEYS: Keys<VolumeOptimalCyclesOptions> = { dim: true, pair: true, minPersistence: true };
696
+
697
+ /**
698
+ * The engine's one array (`volumeOptimalCyclesFlat`) cut into the typed
699
+ * arrays of {@link VolumeOptimalCycles}: `[count, volume rows, boundary
700
+ * rows, cycle vertices]`, then births, deaths, found, and the three CSR
701
+ * lists, each offsets then ids.
702
+ */
703
+ function cyclesOf(out: Float64Array, dim: number): VolumeOptimalCycles {
704
+ const [count, volumeRows, boundaryRows, cycleLength] = [out[0]!, out[1]!, out[2]!, out[3]!];
705
+ let at = 4;
706
+ const take = (length: number): Float64Array => out.subarray(at, (at += length));
707
+ const births = take(count).slice();
708
+ const deaths = take(count).slice();
709
+ const found = Uint8Array.from(take(count));
710
+ const volumeOffsets = Uint32Array.from(take(count + 1));
711
+ const volumeVertices = Int32Array.from(take(volumeRows * (dim + 2)));
712
+ const boundaryOffsets = Uint32Array.from(take(count + 1));
713
+ const boundaryVertices = Int32Array.from(take(boundaryRows * (dim + 1)));
714
+ const cycleVertexOffsets = Uint32Array.from(take(count + 1));
715
+ const cycleVertices = Int32Array.from(take(cycleLength));
716
+ return { dim, births, deaths, found, volumeOffsets, volumeVertices, boundaryOffsets, boundaryVertices, cycleVertexOffsets, cycleVertices };
717
+ }
718
+
719
+ /**
720
+ * Experimental: volume-optimal cycles in dimension `dim`, by the merge-tree /
721
+ * Alexander-duality method ([reference](https://topolab.ai/tda/docs/references/#obayashi-2018), §5).
722
+ * Meaningful for triangulations of convex
723
+ * domains in R^(dim + 1), such as alpha complexes. With `pair`, the cycle of
724
+ * that one finite pair (or the pair echoed with `found[0] === 0`); without,
725
+ * every finite pair's (longer than `minPersistence`), sorted by birth then
726
+ * death. The engine orders and checks the complex itself (closed, values
727
+ * non-decreasing from face to coface; a simplex's vertices in any order,
728
+ * none listed twice). The general L1 problem and stable volumes are not
729
+ * implemented.
730
+ */
731
+ export function volumeOptimalCycles(complex: ComplexLike, opts: VolumeOptimalCyclesOptions): VolumeOptimalCycles {
732
+ module();
733
+ const o = options<VolumeOptimalCyclesOptions>(opts, 'volumeOptimalCycles', VOLUME_OPTIMAL_KEYS);
734
+ const c = complexArgs(complex, 'complex');
735
+ const dim = int(o.dim, 'dim', 0, 0x7ffffffe);
736
+ let pair: [number, number] | null = null;
737
+ if (o.pair !== undefined) {
738
+ if (!Array.isArray(o.pair) || o.pair.length !== 2) throw new TypeError(`pair must be [birth, death], got ${kind(o.pair)}`);
739
+ pair = [finite(o.pair[0], 'pair[0]'), finite(o.pair[1], 'pair[1]')];
740
+ }
741
+ const minPersistence = checkMinPersistence(o.minPersistence);
742
+ // The empty complex has no pairs; any other shape with no values goes to
743
+ // the engine, which refuses it as it refuses every malformed complex.
744
+ const empty = isEmptyComplex(c);
745
+ if (empty && pair === null) return cyclesOf(Float64Array.of(0, 0, 0, 0, 0, 0, 0), dim);
746
+ if (empty) throw new RangeError('complex must hold at least one simplex to find the cycle of a pair');
747
+ const [birth, death] = pair ?? [0, 0];
748
+ const out: Float64Array = call('volumeOptimalCycles', (m) =>
749
+ m.volumeOptimalCyclesFlat(c.vertices, c.offsets, c.filtrations, dim + 1, pair !== null, birth, death, minPersistence)
750
+ );
751
+ return cyclesOf(out, dim);
752
+ }