@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.
- package/CHANGELOG.md +106 -0
- package/CITATION.cff +72 -0
- package/LICENSE +21 -0
- package/README.md +100 -2
- package/SECURITY.md +34 -0
- package/THIRD_PARTY_LICENSES.md +697 -0
- package/dist/arrangement.d.ts +50 -0
- package/dist/arrangement.d.ts.map +1 -0
- package/dist/arrangement.js +63 -0
- package/dist/arrangement.js.map +1 -0
- package/dist/build_info.json +12 -0
- package/dist/check.d.ts +118 -0
- package/dist/check.d.ts.map +1 -0
- package/dist/check.js +298 -0
- package/dist/check.js.map +1 -0
- package/dist/complex.d.ts +543 -0
- package/dist/complex.d.ts.map +1 -0
- package/dist/complex.js +712 -0
- package/dist/complex.js.map +1 -0
- package/dist/diagram.d.ts +116 -0
- package/dist/diagram.d.ts.map +1 -0
- package/dist/diagram.js +238 -0
- package/dist/diagram.js.map +1 -0
- package/dist/diagram_of.d.ts +17 -0
- package/dist/diagram_of.d.ts.map +1 -0
- package/dist/diagram_of.js +40 -0
- package/dist/diagram_of.js.map +1 -0
- package/dist/experimental.d.ts +18 -0
- package/dist/experimental.d.ts.map +1 -0
- package/dist/experimental.js +16 -0
- package/dist/experimental.js.map +1 -0
- package/dist/flat.d.ts +64 -0
- package/dist/flat.d.ts.map +1 -0
- package/dist/flat.js +158 -0
- package/dist/flat.js.map +1 -0
- package/dist/index.d.ts +42 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +31 -0
- package/dist/index.js.map +1 -0
- package/dist/ladder/tda_ladder.d.ts +223 -0
- package/dist/ladder/tda_ladder.js +1360 -0
- package/dist/ladder/tda_ladder_bg.wasm +0 -0
- package/dist/ladder/tda_ladder_bg.wasm.d.ts +43 -0
- package/dist/ladder.d.ts +306 -0
- package/dist/ladder.d.ts.map +1 -0
- package/dist/ladder.js +607 -0
- package/dist/ladder.js.map +1 -0
- package/dist/load.d.ts +53 -0
- package/dist/load.d.ts.map +1 -0
- package/dist/load.js +173 -0
- package/dist/load.js.map +1 -0
- package/dist/memory.d.ts +58 -0
- package/dist/memory.d.ts.map +1 -0
- package/dist/memory.js +2 -0
- package/dist/memory.js.map +1 -0
- package/dist/persistence.d.ts +349 -0
- package/dist/persistence.d.ts.map +1 -0
- package/dist/persistence.js +478 -0
- package/dist/persistence.js.map +1 -0
- package/dist/pkg/tda_wasm.d.ts +13 -0
- package/dist/pkg/tda_wasm.js +2528 -0
- package/dist/prepared.d.ts +62 -0
- package/dist/prepared.d.ts.map +1 -0
- package/dist/prepared.js +81 -0
- package/dist/prepared.js.map +1 -0
- package/dist/rivet_input.d.ts +93 -0
- package/dist/rivet_input.d.ts.map +1 -0
- package/dist/rivet_input.js +132 -0
- package/dist/rivet_input.js.map +1 -0
- package/dist/source.d.ts +43 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +99 -0
- package/dist/source.js.map +1 -0
- package/dist/tda.wasm +0 -0
- package/dist/two_parameter.d.ts +243 -0
- package/dist/two_parameter.d.ts.map +1 -0
- package/dist/two_parameter.js +275 -0
- package/dist/two_parameter.js.map +1 -0
- package/dist/types.d.ts +146 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/vineyard.d.ts +278 -0
- package/dist/vineyard.d.ts.map +1 -0
- package/dist/vineyard.js +236 -0
- package/dist/vineyard.js.map +1 -0
- package/package.json +77 -4
- package/src/arrangement.ts +96 -0
- package/src/check.ts +338 -0
- package/src/complex.ts +1179 -0
- package/src/diagram.ts +299 -0
- package/src/diagram_of.ts +40 -0
- package/src/experimental.ts +17 -0
- package/src/flat.ts +204 -0
- package/src/index.ts +181 -0
- package/src/ladder.ts +903 -0
- package/src/load.ts +201 -0
- package/src/memory.ts +58 -0
- package/src/persistence.ts +752 -0
- package/src/prepared.ts +111 -0
- package/src/rivet_input.ts +195 -0
- package/src/source.ts +132 -0
- package/src/two_parameter.ts +480 -0
- package/src/types.ts +163 -0
- package/src/vineyard.ts +463 -0
package/src/diagram.ts
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What is read off a persistence diagram: Betti numbers and curves,
|
|
3
|
+
* landscapes, images, and the distances between two diagrams (internal
|
|
4
|
+
* module; the package root re-exports the API).
|
|
5
|
+
*/
|
|
6
|
+
import { call, module } from './load.js';
|
|
7
|
+
import { f64, finite, int, kind, noNaN, num, options } from './check.js';
|
|
8
|
+
import type { Keys, Vec } from './check.js';
|
|
9
|
+
import type { Diagram } from './types.js';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The `[birth, death, …]` arrays of a diagram, after their checks: an even
|
|
13
|
+
* length and `birth <= death` without NaN in each pair (a class created at
|
|
14
|
+
* `Infinity`, which `persistence` gives a vertex valued `Infinity`, is a
|
|
15
|
+
* pair).
|
|
16
|
+
*/
|
|
17
|
+
function perDimension(diagram: Diagram, name: string): Float64Array[] {
|
|
18
|
+
if (diagram === null || typeof diagram !== 'object' || !Array.isArray(diagram.pairs)) {
|
|
19
|
+
throw new TypeError(`${name} must be a diagram { pairs: Float64Array[], … }, got ${kind(diagram)}`);
|
|
20
|
+
}
|
|
21
|
+
return diagram.pairs.map((p, k) => {
|
|
22
|
+
const a = f64(p, `${name}.pairs[${k}]`);
|
|
23
|
+
evenLength(a, `${name}.pairs[${k}]`);
|
|
24
|
+
for (let i = 0; i < a.length; i += 2) {
|
|
25
|
+
if (!(a[i]! <= a[i + 1]!)) {
|
|
26
|
+
throw new RangeError(`${name}.pairs[${k}][${i}], [${i + 1}] = (${a[i]}, ${a[i + 1]}) is not a persistence pair (need birth <= death, no NaN)`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return a;
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function evenLength(a: Float64Array, name: string): void {
|
|
34
|
+
if (a.length % 2 !== 0) throw new RangeError(`${name} must hold [birth, death] pairs (an even length), got length ${a.length}`);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The pairs a landscape or an image reads: an even length, every birth
|
|
39
|
+
* finite, every death at least the birth or `Infinity` (no NaN).
|
|
40
|
+
*/
|
|
41
|
+
function pairCheck(a: Float64Array, name: string): void {
|
|
42
|
+
evenLength(a, name);
|
|
43
|
+
for (let i = 0; i < a.length; i += 2) {
|
|
44
|
+
const b = a[i]!;
|
|
45
|
+
const d = a[i + 1]!;
|
|
46
|
+
if (!Number.isFinite(b) || !(d >= b)) {
|
|
47
|
+
throw new RangeError(`${name}[${i}], ${name}[${i + 1}] = (${b}, ${d}) is not a pair this function reads (need a finite birth and death >= birth or Infinity)`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The most values a landscape or an image returns: 2^27 doubles, 1 GiB. */
|
|
53
|
+
const MAX_VALUES = 2 ** 27;
|
|
54
|
+
|
|
55
|
+
/** A diagram packed as the module takes it: `[m, n_0 … n_(m−1)]`, then the m dimensions' `[birth, death, …]` back to back. */
|
|
56
|
+
function packed(pairs: Float64Array[]): Float64Array {
|
|
57
|
+
const m = pairs.length;
|
|
58
|
+
let total = 1 + m;
|
|
59
|
+
for (const p of pairs) total += p.length;
|
|
60
|
+
const out = new Float64Array(total);
|
|
61
|
+
out[0] = m;
|
|
62
|
+
let at = 1 + m;
|
|
63
|
+
pairs.forEach((p, k) => {
|
|
64
|
+
out[1 + k] = p.length;
|
|
65
|
+
out.set(p, at);
|
|
66
|
+
at += p.length;
|
|
67
|
+
});
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** `rows` arrays of `length` values each, out of the module's one array (a copy each, so each owns its buffer). */
|
|
72
|
+
function cut<T>(out: Float64Array, rows: number, length: number, as: (part: Float64Array) => T): T[] {
|
|
73
|
+
return Array.from({ length: rows }, (_, k) => as(out.subarray(k * length, (k + 1) * length)));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The Betti numbers at `t`, read off the diagram: entry `k` is the number of
|
|
78
|
+
* pairs of Hₖ with `birth <= t < death`, an essential class (death
|
|
79
|
+
* `Infinity`) counted at every `t >= birth`, `t = Infinity` included: the
|
|
80
|
+
* rank of Hₖ of the complex of the simplices valued `<= t`. One entry per
|
|
81
|
+
* dimension of the diagram. Computed by the Rust core, by binary search in each
|
|
82
|
+
* dimension's sorted births and finite deaths.
|
|
83
|
+
*/
|
|
84
|
+
export function bettiNumbers(diagram: Diagram, t: number): Uint32Array {
|
|
85
|
+
module();
|
|
86
|
+
const pairs = perDimension(diagram, 'diagram');
|
|
87
|
+
num(t, 't');
|
|
88
|
+
if (Number.isNaN(t)) throw new RangeError('t must not be NaN');
|
|
89
|
+
const out: Float64Array = call('bettiNumbers', (m) => m.bettiNumbersFlat(packed(pairs), t));
|
|
90
|
+
return Uint32Array.from(out);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The Betti curves on `grid` (any order, no NaN): `curves[k][i]` is
|
|
95
|
+
* `bettiNumbers(diagram, grid[i])[k]`. One curve per dimension of the
|
|
96
|
+
* diagram, by binary search in the sorted births and deaths (the Rust core,
|
|
97
|
+
* as {@link bettiNumbers}).
|
|
98
|
+
*/
|
|
99
|
+
export function bettiCurve(diagram: Diagram, grid: Vec): Uint32Array[] {
|
|
100
|
+
module();
|
|
101
|
+
const pairs = perDimension(diagram, 'diagram');
|
|
102
|
+
const g = f64(grid, 'grid');
|
|
103
|
+
noNaN(g, 'grid');
|
|
104
|
+
const out: Float64Array = call('bettiCurve', (m) => m.bettiCurveFlat(packed(pairs), g));
|
|
105
|
+
return cut(out, pairs.length, g.length, (c) => Uint32Array.from(c));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Options of {@link persistenceLandscape}. */
|
|
109
|
+
export interface PersistenceLandscapeOptions {
|
|
110
|
+
/** The points at which to evaluate, finite, any order. Required. */
|
|
111
|
+
grid: Vec;
|
|
112
|
+
/** How many landscape functions, λ₁ … λ_layers, a positive integer (`layers · grid.length` at most 2^27). Default 1. */
|
|
113
|
+
layers?: number;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const LANDSCAPE_KEYS: Keys<PersistenceLandscapeOptions> = { grid: true, layers: true };
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* The persistence landscape of one dimension's pairs `[birth, death, …]`:
|
|
120
|
+
* `λ_k(t)` is the k-th largest of `max(0, min(t − birth, death − t))` over
|
|
121
|
+
* the finite pairs, counted with multiplicity (0 when fewer than k pairs hold
|
|
122
|
+
* `t` strictly inside). Essential pairs carry no tent. Returns `layers`
|
|
123
|
+
* arrays, `landscape[k − 1][i] = λ_k(grid[i])`. Each value is one tent
|
|
124
|
+
* evaluated as `min(t − birth, death − t)` (by the Rust core), so the result does not
|
|
125
|
+
* depend on how the work is ordered.
|
|
126
|
+
*/
|
|
127
|
+
export function persistenceLandscape(pairs: Vec, opts: PersistenceLandscapeOptions): Float64Array[] {
|
|
128
|
+
module();
|
|
129
|
+
const o = options<PersistenceLandscapeOptions>(opts, 'persistenceLandscape', LANDSCAPE_KEYS);
|
|
130
|
+
const a = f64(pairs, 'pairs');
|
|
131
|
+
pairCheck(a, 'pairs');
|
|
132
|
+
if (o.grid === undefined) throw new TypeError('grid must be a Float64Array or an array of numbers, got undefined');
|
|
133
|
+
const grid = f64(o.grid, 'grid');
|
|
134
|
+
for (let i = 0; i < grid.length; i++) finite(grid[i], `grid[${i}]`);
|
|
135
|
+
const layers = o.layers === undefined ? 1 : int(o.layers, 'layers', 1);
|
|
136
|
+
if (layers * grid.length > MAX_VALUES) {
|
|
137
|
+
throw new RangeError(`layers · grid.length must be at most ${MAX_VALUES} values, got ${layers} · ${grid.length}`);
|
|
138
|
+
}
|
|
139
|
+
const out: Float64Array = call('persistenceLandscape', (m) => m.persistenceLandscapeFlat(a, 1, layers, grid));
|
|
140
|
+
return layers === 1 ? [out] : cut(out, layers, grid.length, (l) => l.slice());
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The region of the (birth, persistence) plane a persistence image covers. */
|
|
144
|
+
export interface ImageBounds {
|
|
145
|
+
birthMin: number;
|
|
146
|
+
birthMax: number;
|
|
147
|
+
persMin: number;
|
|
148
|
+
persMax: number;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Options of {@link persistenceImage}. */
|
|
152
|
+
export interface PersistenceImageOptions {
|
|
153
|
+
/** Pixels: `n` for `n × n`, or `[rows, columns]`, NumPy's order (rows along persistence, columns along birth); at most 2^27 pixels. Required. */
|
|
154
|
+
resolution: number | [number, number];
|
|
155
|
+
/** The region covered, or `'auto'` (default): the finite pairs' births and persistences padded by 10 %, persistence from 0. */
|
|
156
|
+
bounds?: 'auto' | ImageBounds;
|
|
157
|
+
/** The standard deviation of the Gaussian at each pair, positive and finite. Default 0.1. */
|
|
158
|
+
sigma?: number;
|
|
159
|
+
/** A pair weighs `persistence^weightPower`, finite. Default 1. */
|
|
160
|
+
weightPower?: number;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const IMAGE_KEYS: Keys<PersistenceImageOptions> = { resolution: true, bounds: true, sigma: true, weightPower: true };
|
|
164
|
+
const BOUNDS_KEYS: Keys<ImageBounds> = { birthMin: true, birthMax: true, persMin: true, persMax: true };
|
|
165
|
+
|
|
166
|
+
/** A persistence image: the pixel values row-major, `shape: [rows, columns]`, and the region covered. */
|
|
167
|
+
export interface PersistenceImage {
|
|
168
|
+
/** Row-major: row `r` at persistence `persMin + (r + ½)·(persMax − persMin)/rows` (row 0 the lowest), column `c` at birth `birthMin + (c + ½)·(birthMax − birthMin)/columns`. */
|
|
169
|
+
values: Float64Array;
|
|
170
|
+
/** `[rows, columns]`. */
|
|
171
|
+
shape: [number, number];
|
|
172
|
+
bounds: ImageBounds;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* The persistence image of one dimension's pairs ([reference](https://topolab.ai/tda/docs/references/#adams-et-al-2017)): each finite pair with `death > birth` adds `persistence^weightPower`
|
|
177
|
+
* times the Gaussian `exp(−((x − birth)² + (y − persistence)²) / (2 sigma²))`,
|
|
178
|
+
* evaluated at the pixel centres (by the Rust core; each pixel's terms are
|
|
179
|
+
* added in the order of the pairs). The Gaussian is not normalised: ([reference](https://topolab.ai/tda/docs/references/#adams-et-al-2017)) and GUDHI's `PersistenceImage` divide it by `2π sigma²`, so their
|
|
180
|
+
* values are these times `1 / (2π sigma²)`. The result is a
|
|
181
|
+
* {@link Grid}-shaped image (it can be fed to {@link cubicalPersistence}).
|
|
182
|
+
*/
|
|
183
|
+
export function persistenceImage(pairs: Vec, opts: PersistenceImageOptions): PersistenceImage {
|
|
184
|
+
module();
|
|
185
|
+
const o = options<PersistenceImageOptions>(opts, 'persistenceImage', IMAGE_KEYS);
|
|
186
|
+
const a = f64(pairs, 'pairs');
|
|
187
|
+
pairCheck(a, 'pairs');
|
|
188
|
+
let rows: number;
|
|
189
|
+
let columns: number;
|
|
190
|
+
if (typeof o.resolution === 'number') {
|
|
191
|
+
rows = columns = int(o.resolution, 'resolution', 1);
|
|
192
|
+
} else if (Array.isArray(o.resolution) && o.resolution.length === 2) {
|
|
193
|
+
rows = int(o.resolution[0], 'resolution[0]', 1);
|
|
194
|
+
columns = int(o.resolution[1], 'resolution[1]', 1);
|
|
195
|
+
} else {
|
|
196
|
+
throw new TypeError(`resolution must be a positive integer or [rows, columns], got ${kind(o.resolution)}`);
|
|
197
|
+
}
|
|
198
|
+
if (rows * columns > MAX_VALUES) throw new RangeError(`resolution must give at most ${MAX_VALUES} pixels, got ${rows} × ${columns}`);
|
|
199
|
+
const auto = o.bounds === undefined || o.bounds === 'auto';
|
|
200
|
+
let given: ImageBounds = { birthMin: 0, birthMax: 0, persMin: 0, persMax: 0 };
|
|
201
|
+
if (auto) {
|
|
202
|
+
let finitePair = false;
|
|
203
|
+
for (let i = 1; i < a.length && !finitePair; i += 2) finitePair = a[i] !== Infinity;
|
|
204
|
+
if (!finitePair) throw new RangeError("bounds 'auto' needs a finite pair; give the bounds for a diagram without one");
|
|
205
|
+
} else if (typeof o.bounds === 'object' && o.bounds !== null) {
|
|
206
|
+
options<ImageBounds>(o.bounds, 'persistenceImage', BOUNDS_KEYS, 'bounds', 'bounds.');
|
|
207
|
+
given = {
|
|
208
|
+
birthMin: finite(o.bounds.birthMin, 'bounds.birthMin'),
|
|
209
|
+
birthMax: finite(o.bounds.birthMax, 'bounds.birthMax'),
|
|
210
|
+
persMin: finite(o.bounds.persMin, 'bounds.persMin'),
|
|
211
|
+
persMax: finite(o.bounds.persMax, 'bounds.persMax')
|
|
212
|
+
};
|
|
213
|
+
if (!(given.birthMax > given.birthMin) || !(given.persMax > given.persMin)) {
|
|
214
|
+
throw new RangeError('bounds must have birthMax > birthMin and persMax > persMin');
|
|
215
|
+
}
|
|
216
|
+
} else {
|
|
217
|
+
throw new TypeError(`bounds must be 'auto' or { birthMin, birthMax, persMin, persMax }, got ${kind(o.bounds)}`);
|
|
218
|
+
}
|
|
219
|
+
const sigma = o.sigma === undefined ? 0.1 : finite(o.sigma, 'sigma');
|
|
220
|
+
if (!(sigma > 0)) throw new RangeError(`sigma must be positive, got ${sigma}`);
|
|
221
|
+
const weightPower = o.weightPower === undefined ? 1 : finite(o.weightPower, 'weightPower');
|
|
222
|
+
// The module returns the bounds it used, then the pixels.
|
|
223
|
+
const out: Float64Array = call('persistenceImage', (m) => m.persistenceImageFlat(a, rows, columns, auto, given.birthMin, given.birthMax, given.persMin, given.persMax, sigma, weightPower));
|
|
224
|
+
return {
|
|
225
|
+
values: out.slice(4),
|
|
226
|
+
shape: [rows, columns],
|
|
227
|
+
bounds: { birthMin: out[0]!, birthMax: out[1]!, persMin: out[2]!, persMax: out[3]! }
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// ---------------------------------------------------------------------------
|
|
232
|
+
// Distances: the same code, signatures and messages as @topolab/ot's
|
|
233
|
+
// ---------------------------------------------------------------------------
|
|
234
|
+
|
|
235
|
+
/** Options of {@link diagramWasserstein}. */
|
|
236
|
+
export interface DiagramWassersteinOptions {
|
|
237
|
+
/** The Wasserstein order q, finite and ≥ 1. Required: GUDHI defaults to 1, Dionysus and giotto-tda to 2. */
|
|
238
|
+
order: number;
|
|
239
|
+
/** The ground metric `L_p` between points, ≥ 1 or `Infinity`. Default `Infinity` (GUDHI's). */
|
|
240
|
+
internalP?: number;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const WASSERSTEIN_KEYS: Keys<DiagramWassersteinOptions> = { order: true, internalP: true };
|
|
244
|
+
|
|
245
|
+
/** Result of the diagram distances. */
|
|
246
|
+
export interface DiagramMatching {
|
|
247
|
+
/** The distance; `Infinity` when the essential parts cannot be matched. */
|
|
248
|
+
distance: number;
|
|
249
|
+
/** Matched pairs as `[i0, j0, i1, j1, …]` (indices of points of `D` and `E`), `-1` for the diagonal. Empty when `distance` is `Infinity`. */
|
|
250
|
+
matching: Int32Array;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const unpackMatching = (out: Float64Array): DiagramMatching => ({ distance: out[0]!, matching: Int32Array.from(out.subarray(1)) });
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* The exact Wasserstein distance of order `order` between two persistence
|
|
257
|
+
* diagrams of one homology dimension, each a flat `[birth, death, …]`
|
|
258
|
+
* array. Essential points (`death = Infinity`, `birth = -Infinity`, or
|
|
259
|
+
* both) are matched among their own kind by their finite coordinate;
|
|
260
|
+
* differing counts of a kind give `Infinity` (as GUDHI and Hera).
|
|
261
|
+
*
|
|
262
|
+
* Distances between points and to the diagonal are computed without
|
|
263
|
+
* overflow or underflow wherever they are representable. The distance is
|
|
264
|
+
* returned only when the powers it is summed from are: a distance to the
|
|
265
|
+
* power `order` that overflows, or a sum of powers below 2⁻⁹⁴⁰ while the
|
|
266
|
+
* diagrams differ, throws a `RangeError` that says so. As
|
|
267
|
+
* `W_q(kD, kE) = k · W_q(D, E)`, scaling the diagrams (down for an
|
|
268
|
+
* overflow, up for an underflow) or a lower `order` brings the powers into
|
|
269
|
+
* range. Dense finite-point costs are limited to 16,777,216 entries
|
|
270
|
+
* (128 MiB, about 4,096 finite points per side); a larger request throws,
|
|
271
|
+
* before allocation, a `RangeError` whose message starts with
|
|
272
|
+
* `input too large:` and gives the count and the limit (use fewer points,
|
|
273
|
+
* or {@link diagramBottleneck}, which builds no matrix).
|
|
274
|
+
*/
|
|
275
|
+
export function diagramWasserstein(D: Vec, E: Vec, opts: DiagramWassersteinOptions): DiagramMatching {
|
|
276
|
+
module();
|
|
277
|
+
const o = options<DiagramWassersteinOptions>(opts, 'diagramWasserstein', WASSERSTEIN_KEYS);
|
|
278
|
+
const order = num(o.order, 'order');
|
|
279
|
+
const internalP = o.internalP === undefined ? Infinity : num(o.internalP, 'internalP');
|
|
280
|
+
const d = f64(D, 'D');
|
|
281
|
+
const e = f64(E, 'E');
|
|
282
|
+
return call('diagramWasserstein', (m) => unpackMatching(m.diagramWassersteinFlat(d, e, order, internalP)));
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* The exact bottleneck distance (L∞ ground metric) between two persistence
|
|
287
|
+
* diagrams of one homology dimension, with an optimal matching. Essential
|
|
288
|
+
* points are matched as by {@link diagramWasserstein}, and differing counts
|
|
289
|
+
* give `Infinity`. Distances between finite points and to the diagonal
|
|
290
|
+
* never overflow; a finite distance that a double cannot hold (matched
|
|
291
|
+
* essential points about `1e308` apart) throws a `RangeError`, as
|
|
292
|
+
* {@link diagramWasserstein} does.
|
|
293
|
+
*/
|
|
294
|
+
export function diagramBottleneck(D: Vec, E: Vec): DiagramMatching {
|
|
295
|
+
module();
|
|
296
|
+
const d = f64(D, 'D');
|
|
297
|
+
const e = f64(E, 'E');
|
|
298
|
+
return call('diagramBottleneck', (m) => unpackMatching(m.diagramBottleneckFlat(d, e)));
|
|
299
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** The engines' flat pairs as a per-dimension diagram, and the `minPersistence` filter (internal). */
|
|
2
|
+
import { call } from './load.js';
|
|
3
|
+
import type { Diagram, Scale } from './types.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The engine pairs `[dimension, birth, death] * m` without the finite pairs
|
|
7
|
+
* with `death - birth <= minPersistence` (GUDHI's `min_persistence`;
|
|
8
|
+
* essential pairs are always kept), in the same order: the Rust core's
|
|
9
|
+
* filter. At 0 the pairs are returned
|
|
10
|
+
* as they are: every engine already leaves out the pairs of length zero.
|
|
11
|
+
*/
|
|
12
|
+
export function longPairs(flat: Float64Array, minPersistence: number): Float64Array {
|
|
13
|
+
if (!(minPersistence > 0)) return flat;
|
|
14
|
+
return call((m) => m.longPairsFlat(flat, minPersistence));
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The pairs `[dimension, birth, death] * m` of an engine as a {@link Diagram}
|
|
19
|
+
* with one array per dimension from 0 to `top` (or to the highest dimension
|
|
20
|
+
* present, if higher), each `[birth, death, …]` in the engine's order,
|
|
21
|
+
* without the pairs {@link longPairs} leaves out at `minPersistence`.
|
|
22
|
+
*/
|
|
23
|
+
export function diagramOf(flat_: Float64Array, top: number, scale: Scale, coeff: number, minPersistence = 0): Diagram {
|
|
24
|
+
const flat = longPairs(flat_, minPersistence);
|
|
25
|
+
const counts: number[] = new Array(Math.max(top + 1, 0)).fill(0);
|
|
26
|
+
for (let i = 0; i < flat.length; i += 3) {
|
|
27
|
+
const k = flat[i]!;
|
|
28
|
+
while (counts.length <= k) counts.push(0);
|
|
29
|
+
counts[k]!++;
|
|
30
|
+
}
|
|
31
|
+
const pairs = counts.map((c) => new Float64Array(2 * c));
|
|
32
|
+
const at = new Array(counts.length).fill(0);
|
|
33
|
+
for (let i = 0; i < flat.length; i += 3) {
|
|
34
|
+
const k = flat[i]!;
|
|
35
|
+
const p = pairs[k]!;
|
|
36
|
+
p[at[k]++] = flat[i + 1]!;
|
|
37
|
+
p[at[k]++] = flat[i + 2]!;
|
|
38
|
+
}
|
|
39
|
+
return { pairs, scale, coeff };
|
|
40
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@topolab/tda/experimental`: APIs that may change or go away in any
|
|
3
|
+
* release, outside the plain-data contract of the root entry point.
|
|
4
|
+
*
|
|
5
|
+
* `prepareComplex` keeps a validated complex in the module's memory for
|
|
6
|
+
* repeated persistence queries, and `augmentedArrangement` the augmented
|
|
7
|
+
* arrangement of a two-parameter module for repeated barcodes along lines.
|
|
8
|
+
* Unlike every root function, they return handles that own native memory:
|
|
9
|
+
* dispose them (or `unload()`). They use the module the root's `load()`
|
|
10
|
+
* loaded.
|
|
11
|
+
*
|
|
12
|
+
* @packageDocumentation
|
|
13
|
+
*/
|
|
14
|
+
export { prepareComplex } from './prepared.js';
|
|
15
|
+
export type { PreparedComplex } from './prepared.js';
|
|
16
|
+
export { augmentedArrangement } from './arrangement.js';
|
|
17
|
+
export type { AugmentedArrangement } from './arrangement.js';
|
package/src/flat.ts
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Object forms of typed-array results, built on request, and point clouds
|
|
3
|
+
* from rows (internal module; the package root re-exports the API). Pure
|
|
4
|
+
* TypeScript: none of these needs the module loaded.
|
|
5
|
+
*/
|
|
6
|
+
import { kind, oneOf } from './check.js';
|
|
7
|
+
import type { PointCloud } from './check.js';
|
|
8
|
+
import { complexArgs } from './persistence.js';
|
|
9
|
+
import type { RipsRepresentatives, VolumeOptimalCycles } from './persistence.js';
|
|
10
|
+
import type { Complex, ComplexLike, Scale, Simplex } from './types.js';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* A point cloud from one array of coordinates per point. Every row must have
|
|
14
|
+
* the same positive length `d`, and every coordinate must be a number (a
|
|
15
|
+
* string, `null` or a hole is a `TypeError`).
|
|
16
|
+
*/
|
|
17
|
+
export function pointCloud(rows: ArrayLike<ArrayLike<number>>): PointCloud {
|
|
18
|
+
if (rows === null || typeof rows !== 'object' || typeof rows.length !== 'number')
|
|
19
|
+
throw new TypeError(`rows must be an array of rows, got ${kind(rows)}`);
|
|
20
|
+
if (rows.length === 0) throw new RangeError('rows must hold at least one point');
|
|
21
|
+
const first = rows[0];
|
|
22
|
+
if (first === null || typeof first !== 'object' || typeof first.length !== 'number')
|
|
23
|
+
throw new TypeError(`rows[0] must be an array of numbers, got ${kind(first)}`);
|
|
24
|
+
const d = first.length;
|
|
25
|
+
if (d === 0) throw new RangeError('rows[0] must have at least one coordinate');
|
|
26
|
+
const coords = new Float64Array(rows.length * d);
|
|
27
|
+
for (let i = 0; i < rows.length; i++) {
|
|
28
|
+
const row = rows[i];
|
|
29
|
+
if (row === null || typeof row !== 'object' || typeof row.length !== 'number')
|
|
30
|
+
throw new TypeError(`rows[${i}] must be an array of numbers, got ${kind(row)}`);
|
|
31
|
+
if (row.length !== d) throw new RangeError(`rows[${i}] has ${row.length} coordinates, rows[0] has ${d}`);
|
|
32
|
+
for (let c = 0; c < d; c++) {
|
|
33
|
+
const x = row[c];
|
|
34
|
+
if (typeof x !== 'number') throw new TypeError(`rows[${i}][${c}] must be a number, got ${kind(x)}`);
|
|
35
|
+
coords[i * d + c] = x;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return { coords, d };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** One volume-optimal cycle as an object (what {@link materialize} builds from {@link VolumeOptimalCycles}). */
|
|
42
|
+
export interface VolumeOptimalCycle {
|
|
43
|
+
/** The homology dimension. */
|
|
44
|
+
dim: number;
|
|
45
|
+
birth: number;
|
|
46
|
+
death: number;
|
|
47
|
+
/** The cycle's distinct vertices, sorted. */
|
|
48
|
+
cycleVertices: number[];
|
|
49
|
+
/** The `dim`-simplices of the cycle, the boundary of the volume, each one's vertices increasing. */
|
|
50
|
+
cycleSimplices: number[][];
|
|
51
|
+
/** The `(dim + 1)`-simplices of the optimal volume, each one's vertices increasing. */
|
|
52
|
+
volumeSimplices: number[][];
|
|
53
|
+
/** Whether the merge tree had an answer for the pair. */
|
|
54
|
+
found: boolean;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** One representative of a Rips pair as an object (what {@link materialize} builds from {@link RipsRepresentatives}). */
|
|
58
|
+
export interface RipsRepresentative {
|
|
59
|
+
/** The homology dimension. */
|
|
60
|
+
dim: number;
|
|
61
|
+
/** The index of the pair within the pairs of its dimension. */
|
|
62
|
+
pairIndex: number;
|
|
63
|
+
birth: number;
|
|
64
|
+
death: number;
|
|
65
|
+
/** The simplices, each `dim + 1` vertex indices into the input, ascending. */
|
|
66
|
+
simplices: number[][];
|
|
67
|
+
/** The coefficient of each simplex, aligned with `simplices`. */
|
|
68
|
+
coefficients: number[];
|
|
69
|
+
/** The distinct vertices the simplices touch, sorted. */
|
|
70
|
+
vertices: number[];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Rows of `width` ids from flat `values`, rows [from, to). */
|
|
74
|
+
function idRows(values: Int32Array, from: number, to: number, width: number): number[][] {
|
|
75
|
+
const out: number[][] = [];
|
|
76
|
+
for (let s = from; s < to; s++) out.push(Array.from(values.subarray(s * width, (s + 1) * width)));
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Objects from typed arrays, built only when asked for, for drawing small
|
|
82
|
+
* results: a complex as `{ vertices, filtration }[]` (same order, same
|
|
83
|
+
* vertex order); volume-optimal cycles as {@link VolumeOptimalCycle}[]; Rips
|
|
84
|
+
* representatives as {@link RipsRepresentative}[].
|
|
85
|
+
*
|
|
86
|
+
* A complex's arrays are checked as `persistence` checks them: an
|
|
87
|
+
* entry that is not a number is a `TypeError` naming it
|
|
88
|
+
* (`complex.vertices[1]`), and `offsets` that do not frame `vertices` (one
|
|
89
|
+
* offset per simplex plus one, from 0 to `vertices.length`, increasing) are
|
|
90
|
+
* a `RangeError`. Closure and monotonicity are not checked.
|
|
91
|
+
*/
|
|
92
|
+
export function materialize(complex: ComplexLike): Simplex[];
|
|
93
|
+
export function materialize(cycles: VolumeOptimalCycles): VolumeOptimalCycle[];
|
|
94
|
+
export function materialize(representatives: RipsRepresentatives): RipsRepresentative[];
|
|
95
|
+
export function materialize(
|
|
96
|
+
input: ComplexLike | VolumeOptimalCycles | RipsRepresentatives
|
|
97
|
+
): Simplex[] | VolumeOptimalCycle[] | RipsRepresentative[] {
|
|
98
|
+
if (input === null || typeof input !== 'object') {
|
|
99
|
+
throw new TypeError(`materialize takes a complex, volume-optimal cycles or Rips representatives, got ${kind(input)}`);
|
|
100
|
+
}
|
|
101
|
+
if ('coefficients' in input && 'pairIndex' in input) {
|
|
102
|
+
const r = input;
|
|
103
|
+
const out: RipsRepresentative[] = [];
|
|
104
|
+
for (let i = 0; i < r.pairIndex.length; i++) {
|
|
105
|
+
const dim = r.dims[i]!;
|
|
106
|
+
const simplices: number[][] = [];
|
|
107
|
+
const coefficients: number[] = [];
|
|
108
|
+
let at = r.vertexOffsets[i]!;
|
|
109
|
+
for (let s = r.simplexOffsets[i]!; s < r.simplexOffsets[i + 1]!; s++) {
|
|
110
|
+
simplices.push(Array.from(r.vertices.subarray(at, at + dim + 1)));
|
|
111
|
+
at += dim + 1;
|
|
112
|
+
coefficients.push(r.coefficients[s]!);
|
|
113
|
+
}
|
|
114
|
+
const touched = Array.from(new Set(r.vertices.subarray(r.vertexOffsets[i]!, r.vertexOffsets[i + 1]!))).sort((a, b) => a - b);
|
|
115
|
+
out.push({ dim, pairIndex: r.pairIndex[i]!, birth: r.births[i]!, death: r.deaths[i]!, simplices, coefficients, vertices: touched });
|
|
116
|
+
}
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
if ('births' in input && 'found' in input) {
|
|
120
|
+
const c = input;
|
|
121
|
+
const out: VolumeOptimalCycle[] = [];
|
|
122
|
+
for (let r = 0; r < c.births.length; r++) {
|
|
123
|
+
out.push({
|
|
124
|
+
dim: c.dim,
|
|
125
|
+
birth: c.births[r]!,
|
|
126
|
+
death: c.deaths[r]!,
|
|
127
|
+
cycleVertices: Array.from(c.cycleVertices.subarray(c.cycleVertexOffsets[r]!, c.cycleVertexOffsets[r + 1]!)),
|
|
128
|
+
cycleSimplices: idRows(c.boundaryVertices, c.boundaryOffsets[r]!, c.boundaryOffsets[r + 1]!, c.dim + 1),
|
|
129
|
+
volumeSimplices: idRows(c.volumeVertices, c.volumeOffsets[r]!, c.volumeOffsets[r + 1]!, c.dim + 2),
|
|
130
|
+
found: c.found[r] === 1
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
return out;
|
|
134
|
+
}
|
|
135
|
+
const given = input as Partial<ComplexLike>;
|
|
136
|
+
if (given.vertices === undefined || given.offsets === undefined || given.filtrations === undefined) {
|
|
137
|
+
throw new TypeError(`materialize takes a complex, volume-optimal cycles or Rips representatives, got ${kind(input)}`);
|
|
138
|
+
}
|
|
139
|
+
// The entries as for every function that takes a complex, then its CSR
|
|
140
|
+
// shape as the engine checks it, with the engine's messages.
|
|
141
|
+
const { vertices, offsets, filtrations } = complexArgs(input, 'complex');
|
|
142
|
+
const n = filtrations.length;
|
|
143
|
+
if (offsets.length !== n + 1 || offsets[0] !== 0 || offsets[n] !== vertices.length) {
|
|
144
|
+
throw new RangeError(
|
|
145
|
+
`invalid input: offsets must have length n + 1 = ${n + 1} (one per value, plus one), start at 0 and end at vertices.length = ${vertices.length}`
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
for (let i = 0; i < n; i++) {
|
|
149
|
+
if (offsets[i + 1]! < offsets[i]!) {
|
|
150
|
+
throw new RangeError(`invalid input: offsets must be non-decreasing; offsets[${i + 1}] = ${offsets[i + 1]} < offsets[${i}] = ${offsets[i]}`);
|
|
151
|
+
}
|
|
152
|
+
if (offsets[i + 1] === offsets[i]) throw new RangeError(`invalid input: simplex ${i} is empty`);
|
|
153
|
+
}
|
|
154
|
+
const out: Simplex[] = [];
|
|
155
|
+
for (let i = 0; i < filtrations.length; i++) {
|
|
156
|
+
const simplex: number[] = [];
|
|
157
|
+
for (let j = offsets[i]!; j < offsets[i + 1]!; j++) simplex.push(vertices[j]!);
|
|
158
|
+
out.push({ vertices: simplex, filtration: filtrations[i]! });
|
|
159
|
+
}
|
|
160
|
+
return out;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* A `{ vertices, filtration }[]` list as a {@link Complex} (same order of
|
|
165
|
+
* the simplices, each simplex's vertices sorted increasing), on `scale`
|
|
166
|
+
* (default `'value'`): the inverse of {@link materialize} on a complex, for
|
|
167
|
+
* handing object lists to the functions that take a complex. Vertex ids must
|
|
168
|
+
* be integers that fit 32 bits, distinct within a simplex, and values
|
|
169
|
+
* numbers; anything else is refused rather than truncated.
|
|
170
|
+
*/
|
|
171
|
+
export function flatten(simplices: Simplex[], scale: Scale = 'value'): Complex {
|
|
172
|
+
oneOf(scale, 'scale', ['edgeLength', 'radius', 'squaredRadius', 'squaredRelaxation', 'epsilon', 'growthRadius', 'value'] as const);
|
|
173
|
+
if (!Array.isArray(simplices)) throw new TypeError(`simplices must be an array of { vertices, filtration }, got ${kind(simplices)}`);
|
|
174
|
+
const offsets = new Uint32Array(simplices.length + 1);
|
|
175
|
+
let total = 0;
|
|
176
|
+
for (let i = 0; i < simplices.length; i++) {
|
|
177
|
+
const s = simplices[i] as Partial<Simplex> | undefined;
|
|
178
|
+
if (!s || !Array.isArray(s.vertices)) throw new TypeError(`simplices[${i}].vertices must be an array of vertex ids, got ${kind(s?.vertices)}`);
|
|
179
|
+
if (typeof s.filtration !== 'number') throw new TypeError(`simplices[${i}].filtration must be a number, got ${kind(s.filtration)}`);
|
|
180
|
+
for (let j = 0; j < s.vertices.length; j++) {
|
|
181
|
+
const v = s.vertices[j];
|
|
182
|
+
if (typeof v !== 'number') throw new TypeError(`simplices[${i}].vertices[${j}] must be a number, got ${kind(v)}`);
|
|
183
|
+
if (!Number.isInteger(v) || v! < -2147483648 || v! > 2147483647) {
|
|
184
|
+
throw new RangeError(`simplices[${i}].vertices[${j}] must be an integer from -2147483648 to 2147483647, got ${String(v)}`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
total += s.vertices.length;
|
|
188
|
+
offsets[i + 1] = total;
|
|
189
|
+
}
|
|
190
|
+
const vertices = new Int32Array(total);
|
|
191
|
+
const filtrations = new Float64Array(simplices.length);
|
|
192
|
+
for (let i = 0; i < simplices.length; i++) {
|
|
193
|
+
const row = vertices.subarray(offsets[i]!, offsets[i + 1]!);
|
|
194
|
+
row.set(simplices[i]!.vertices);
|
|
195
|
+
row.sort();
|
|
196
|
+
for (let j = 1; j < row.length; j++) {
|
|
197
|
+
if (row[j] === row[j - 1]) {
|
|
198
|
+
throw new RangeError(`simplices[${i}].vertices lists the vertex ${row[j]} twice; a simplex is a set of distinct vertices`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
filtrations[i] = simplices[i]!.filtration;
|
|
202
|
+
}
|
|
203
|
+
return { vertices, offsets, filtrations, scale };
|
|
204
|
+
}
|