tda4j 0.7.0__py3-none-any.whl

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.
tda4j/__init__.py ADDED
@@ -0,0 +1,723 @@
1
+ """TDA4j for Python: persistent homology and topological data analysis, on the JVM library, with NumPy in and out.
2
+
3
+ >>> import numpy as np, tda4j
4
+ >>> square = np.array([[0, 0], [1, 0], [1, 1], [0, 1]])
5
+ >>> result = tda4j.persistence(square, max_dimension=1)
6
+ >>> result.bars # rows (dimension, birth, death); death is inf for a class that never dies
7
+ >>> result.representative(4) # the loop: its edges and coefficients
8
+ >>> result.bar_cells(4) # the edge that opened the loop and the triangle that closed it
9
+
10
+ Every function takes the library's options as keyword arguments, in snake_case: ``max_dimension=1`` is the option
11
+ ``maxDimension`` of the MATLAB and Java interface, ``prime=3`` the field with three elements, ``complex="alpha"`` the alpha
12
+ complex. By default the field is ``Z/17`` and the degrees are 0 to 2. The options and their defaults are those of the
13
+ interface described at https://tda4j.appliedtopology.org (the page "Calling from MATLAB or Java"); a mistyped one
14
+ raises ``ValueError`` and lists the accepted ones.
15
+
16
+ The library runs in a JVM (Java 21 or newer) that starts when the first function needs it. To give it a bigger heap, call
17
+ ``tda4j.start_jvm(["-Xmx16g"])`` before that. A wheel carries the jar; from a source checkout, set ``TDA4J_JAR``.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import os
23
+ from importlib import metadata
24
+
25
+ import jpype
26
+ import numpy as np
27
+
28
+ from . import _jvm
29
+ from ._jvm import Tda4jError, jar_path, start_jvm, translating
30
+ from ._results import (
31
+ BarCells,
32
+ BootstrapBand,
33
+ Boundary,
34
+ Cell,
35
+ CircularCoordinates,
36
+ EulerCurve,
37
+ Landmarks,
38
+ MapDegree,
39
+ MapResult,
40
+ MorseReduction,
41
+ PersistentLaplacian,
42
+ Plot,
43
+ Representative,
44
+ Result,
45
+ ToroidalCoordinates,
46
+ Zigzag,
47
+ )
48
+
49
+ try:
50
+ __version__ = metadata.version("tda4j")
51
+ except metadata.PackageNotFoundError: # a source checkout on sys.path
52
+ __version__ = "0+unknown"
53
+
54
+ __all__ = [
55
+ "BarCells",
56
+ "BootstrapBand",
57
+ "Boundary",
58
+ "Cell",
59
+ "CircularCoordinates",
60
+ "EulerCurve",
61
+ "Landmarks",
62
+ "MapDegree",
63
+ "MapResult",
64
+ "MorseReduction",
65
+ "PersistentLaplacian",
66
+ "Plot",
67
+ "Representative",
68
+ "Result",
69
+ "Tda4jError",
70
+ "ToroidalCoordinates",
71
+ "Zigzag",
72
+ "bootstrap_band",
73
+ "circular_coordinates",
74
+ "clear_plot_defaults",
75
+ "covering_radius",
76
+ "covering_radius_from_distances",
77
+ "delay_by_autocorrelation",
78
+ "dual_bars",
79
+ "euler_curve",
80
+ "euler_curve_from_distances",
81
+ "h1_bars",
82
+ "hom_bars",
83
+ "hom_dimension",
84
+ "inclusion_map",
85
+ "inclusion_map_from_distances",
86
+ "harmonic_chain_barcode",
87
+ "harmonic_chain_barcode_from_distances",
88
+ "harmonic_representatives",
89
+ "harmonic_representatives_from_distances",
90
+ "jar_path",
91
+ "load_result",
92
+ "morse_reduction",
93
+ "morse_reduction_from_distances",
94
+ "persistence",
95
+ "persistence_from_distances",
96
+ "persistence_from_distances_and_landmarks",
97
+ "persistence_from_image",
98
+ "persistence_from_landmarks",
99
+ "persistence_from_relation",
100
+ "persistent_laplacian",
101
+ "persistent_laplacian_from_distances",
102
+ "persistent_laplacian_of_map",
103
+ "persistent_laplacian_of_map_from_distances",
104
+ "product_bars",
105
+ "relative_persistence",
106
+ "relative_persistence_from_distances",
107
+ "select_landmarks",
108
+ "select_landmarks_from_distances",
109
+ "set_plot_defaults",
110
+ "side",
111
+ "simplicial_map",
112
+ "simplicial_map_from_distances",
113
+ "start_jvm",
114
+ "takens_embedding",
115
+ "tomato_clusters",
116
+ "tomato_diagram",
117
+ "toroidal_coordinates",
118
+ "zigzag_from_complexes",
119
+ "zigzag_from_steps",
120
+ ]
121
+
122
+
123
+ def _java():
124
+ return _jvm.facade()
125
+
126
+
127
+ # ---------------------------------------------------------------------------------------------------------------------
128
+ # persistent homology
129
+ # ---------------------------------------------------------------------------------------------------------------------
130
+
131
+ @translating
132
+ def persistence(points, **options) -> Result:
133
+ """Persistent homology of a point cloud: an array with one row per point, with Euclidean distances.
134
+
135
+ Options (keyword arguments): ``complex`` (``"vr"`` by default, or ``"cech"``, ``"alpha"``, ``"witness"``,
136
+ ``"dtm-rips"``, ``"dtm-alpha"``, ``"sparse-rips"``), ``engine``, ``max_dimension`` (2), ``max_filtration_value``,
137
+ ``prime`` (17), ``field`` (``"Z"``, ``"R"`` for the reals or ``"Q"`` for exact rationals),
138
+ ``representative_type`` (``"cycles"`` or ``"cocycles"``), ``min_persistence``, ``min_persistence_fraction``,
139
+ ``include_zero_length`` and the rest of the interface's options.
140
+ """
141
+ return Result(_java().computeFromPoints(_jvm.points_in(points), _jvm.options_in(options)))
142
+
143
+
144
+ @translating
145
+ def persistence_from_distances(distances, **options) -> Result:
146
+ """Persistent homology of a finite metric space given as a square, symmetric matrix of distances.
147
+
148
+ The complexes that need only distances: ``vr``, ``witness``, ``dtm-rips``, ``sparse-rips``.
149
+ """
150
+ return Result(_java().computeFromDistanceMatrix(_jvm.points_in(distances, "distances"), _jvm.options_in(options)))
151
+
152
+
153
+ @translating
154
+ def persistence_from_image(image, **options) -> Result:
155
+ """Persistent homology of an image or a voxel grid of any dimension, as a cubical complex.
156
+
157
+ ``sublevel=False`` takes superlevel sets, a ``nan`` pixel is missing data (not in the complex). The cells of a
158
+ representative are cubes in doubled coordinates: the pixel ``(i, j)`` is ``(2i + 1, 2j + 1)``.
159
+ """
160
+ array = np.ascontiguousarray(image, dtype=np.float64)
161
+ if array.ndim == 0 or array.size == 0:
162
+ raise ValueError("tda4j: image must have at least one pixel")
163
+ return Result(
164
+ _java().computeFromCubicalImage(
165
+ _jvm.ints_in(array.shape), _jvm.doubles_in(array.reshape(-1)), _jvm.options_in(options)
166
+ )
167
+ )
168
+
169
+
170
+ @translating
171
+ def persistence_from_relation(relation, **options) -> Result:
172
+ """Persistent homology of the Dowker complex of a relation: ``relation[x, w]`` is the strength of the tie between row
173
+ ``x`` and column ``w``, smaller being stronger and ``inf`` meaning never. The matrix need not be square.
174
+
175
+ ``dual=True`` builds the complex on the columns (the same bars). ``representatives_on="rows"`` or ``"columns"`` puts
176
+ the representatives (cycles, or cocycles with ``representative_type="cocycles"``) on that side; with distances from
177
+ landmarks (rows) to points (columns), ``"columns"`` puts them on the points."""
178
+ return Result(_java().computeFromRelation(_jvm.points_in(relation, "relation"), _jvm.options_in(options)))
179
+
180
+
181
+ @translating
182
+ def persistence_from_landmarks(points, landmarks, **options) -> Result:
183
+ """The witness complex of a point cloud on the landmarks (row numbers of ``points``)."""
184
+ return Result(
185
+ _java().computeFromPointsAndLandmarks(
186
+ _jvm.points_in(points), _jvm.ints_in(landmarks, "landmarks"), _jvm.options_in(options)
187
+ )
188
+ )
189
+
190
+
191
+ @translating
192
+ def persistence_from_distances_and_landmarks(distances, landmarks, **options) -> Result:
193
+ """``persistence_from_landmarks`` for a matrix of distances."""
194
+ return Result(
195
+ _java().computeFromDistanceMatrixAndLandmarks(
196
+ _jvm.points_in(distances, "distances"), _jvm.ints_in(landmarks, "landmarks"), _jvm.options_in(options)
197
+ )
198
+ )
199
+
200
+
201
+ @translating
202
+ def relative_persistence(points, subcomplex, **options) -> Result:
203
+ """Relative persistent homology of the Vietoris-Rips complex of a point cloud modulo the subcomplex on the points
204
+ ``subcomplex`` (row numbers): the bars of the pair ``(X, A)``. Modulo one point of a connected cloud the result is
205
+ the reduced homology. Options: ``engine`` (``"cohomology"``, ``"naive"``, ``"chunks"``), ``max_dimension``,
206
+ ``max_filtration_value``, ``field``, ``prime``, ``representative_type`` and the bar options."""
207
+ return Result(
208
+ _java().computeRelativeFromPoints(
209
+ _jvm.points_in(points), _jvm.ints_in(subcomplex, "subcomplex"), _jvm.options_in(options)
210
+ )
211
+ )
212
+
213
+
214
+ @translating
215
+ def relative_persistence_from_distances(distances, subcomplex, **options) -> Result:
216
+ """``relative_persistence`` for a matrix of distances."""
217
+ return Result(
218
+ _java().computeRelativeFromDistanceMatrix(
219
+ _jvm.points_in(distances, "distances"), _jvm.ints_in(subcomplex, "subcomplex"), _jvm.options_in(options)
220
+ )
221
+ )
222
+
223
+
224
+ @translating
225
+ def harmonic_chain_barcode(points, **options) -> Result:
226
+ """The harmonic chain barcode of the Vietoris-Rips complex of a point cloud (Hou, Parsa and Wang): the
227
+ representative of each bar is a cycle orthogonal to all boundaries (a harmonic cycle) that stays so for the bar's
228
+ whole life. It is not the ordinary barcode: a cycle stops being harmonic when a cell makes it non-orthogonal to a
229
+ boundary, before it becomes one.
230
+
231
+ Harmonic needs an inner product, so ``field`` is ``"R"`` (the default here; ``epsilon`` is the tolerance) or ``"Q"``
232
+ (exact rational numbers), and ``"Z"`` is an error. Options: ``max_dimension``, ``max_filtration_value``, ``field``,
233
+ ``epsilon``, ``orthogonalization`` (``"gram-schmidt"``, the default, or ``"laplacian-solve"``, which keeps only the
234
+ boundaries and takes a fraction of the memory on a large complex; over ``"R"`` the two can pair a few bars
235
+ differently when many values nearly tie), ``include_zero_length`` and the bar options."""
236
+ return Result(_java().harmonicChainBarcodeFromPoints(_jvm.points_in(points), _jvm.options_in(options)))
237
+
238
+
239
+ @translating
240
+ def harmonic_chain_barcode_from_distances(distances, **options) -> Result:
241
+ """``harmonic_chain_barcode`` for a matrix of distances."""
242
+ return Result(
243
+ _java().harmonicChainBarcodeFromDistanceMatrix(_jvm.points_in(distances, "distances"), _jvm.options_in(options))
244
+ )
245
+
246
+
247
+ @translating
248
+ def harmonic_representatives(points, **options) -> Result:
249
+ """The ordinary barcode of the Vietoris-Rips complex of a point cloud, the representative of each bar the harmonic
250
+ cycle at its birth (Basu and Cox): picked out by the persistence module alone, so it does not depend on the order
251
+ of cells of equal value. The options of ``harmonic_chain_barcode`` except ``include_zero_length`` (a bar of length
252
+ zero has no such cycle), and ``representative_type="cocycles"`` for the harmonic cocycle of each bar (at the last
253
+ value of its life) instead of its cycle."""
254
+ return Result(_java().harmonicRepresentativesFromPoints(_jvm.points_in(points), _jvm.options_in(options)))
255
+
256
+
257
+ @translating
258
+ def harmonic_representatives_from_distances(distances, **options) -> Result:
259
+ """``harmonic_representatives`` for a matrix of distances."""
260
+ return Result(
261
+ _java().harmonicRepresentativesFromDistanceMatrix(
262
+ _jvm.points_in(distances, "distances"), _jvm.options_in(options)
263
+ )
264
+ )
265
+
266
+
267
+ @translating
268
+ def load_result(path: str | os.PathLike) -> Result:
269
+ """A result saved by ``Result.save``, the MATLAB or Java ``save``, or the command line's ``--save-result``."""
270
+ return Result(_java().loadResult(_jvm.path_in(path)))
271
+
272
+
273
+ # ---------------------------------------------------------------------------------------------------------------------
274
+ # maps between spaces
275
+ # ---------------------------------------------------------------------------------------------------------------------
276
+
277
+ @translating
278
+ def inclusion_map(points, subsample, **options) -> MapResult:
279
+ """The map on persistent homology induced by the inclusion of the Vietoris-Rips complex of a subsample (row numbers
280
+ ``subsample``) into that of all the points: what survives from the subsample, and what only the sample sees.
281
+ Options: ``engine`` (``"ripser"`` or ``"cohomology"``), ``max_dimension``, ``max_filtration_value`` (shared by both
282
+ complexes), ``prime``."""
283
+ return MapResult(
284
+ _java().computeInclusionFromPoints(
285
+ _jvm.points_in(points), _jvm.ints_in(subsample, "subsample"), _jvm.options_in(options)
286
+ )
287
+ )
288
+
289
+
290
+ @translating
291
+ def inclusion_map_from_distances(distances, subsample, **options) -> MapResult:
292
+ """``inclusion_map`` for a matrix of distances."""
293
+ return MapResult(
294
+ _java().computeInclusionFromDistanceMatrix(
295
+ _jvm.points_in(distances, "distances"), _jvm.ints_in(subsample, "subsample"), _jvm.options_in(options)
296
+ )
297
+ )
298
+
299
+
300
+ @translating
301
+ def simplicial_map(source_points, target_points, vertex_map, **options) -> MapResult:
302
+ """The map induced by the simplicial map that sends point ``i`` of ``source_points`` to point ``vertex_map[i]`` of
303
+ ``target_points``. It must not increase a distance. Options as in ``inclusion_map``."""
304
+ return MapResult(
305
+ _java().computeMapFromPoints(
306
+ _jvm.points_in(source_points, "source_points"),
307
+ _jvm.points_in(target_points, "target_points"),
308
+ _jvm.ints_in(vertex_map, "vertex_map"),
309
+ _jvm.options_in(options),
310
+ )
311
+ )
312
+
313
+
314
+ @translating
315
+ def simplicial_map_from_distances(source_distances, target_distances, vertex_map, **options) -> MapResult:
316
+ """``simplicial_map`` between two metric spaces given as matrices of distances."""
317
+ return MapResult(
318
+ _java().computeMapFromDistanceMatrices(
319
+ _jvm.points_in(source_distances, "source_distances"),
320
+ _jvm.points_in(target_distances, "target_distances"),
321
+ _jvm.ints_in(vertex_map, "vertex_map"),
322
+ _jvm.options_in(options),
323
+ )
324
+ )
325
+
326
+
327
+ # ---------------------------------------------------------------------------------------------------------------------
328
+ # landmarks, curves, bands, clusters
329
+ # ---------------------------------------------------------------------------------------------------------------------
330
+
331
+ @translating
332
+ def select_landmarks(points, num_landmarks: int, **options) -> Landmarks:
333
+ """Landmarks of a point cloud by farthest-point sampling (option ``landmark_selector``, ``landmark_seed``)."""
334
+ chosen = _java().selectLandmarksFromPoints(
335
+ _jvm.points_in(points), _jvm.options_in({"num_landmarks": num_landmarks, **options})
336
+ )
337
+ return Landmarks(_jvm.vector_out(chosen.landmarks(), np.int64), float(chosen.coveringRadius()))
338
+
339
+
340
+ @translating
341
+ def select_landmarks_from_distances(distances, num_landmarks: int, **options) -> Landmarks:
342
+ """``select_landmarks`` for a matrix of distances."""
343
+ chosen = _java().selectLandmarksFromDistanceMatrix(
344
+ _jvm.points_in(distances, "distances"), _jvm.options_in({"num_landmarks": num_landmarks, **options})
345
+ )
346
+ return Landmarks(_jvm.vector_out(chosen.landmarks(), np.int64), float(chosen.coveringRadius()))
347
+
348
+
349
+ @translating
350
+ def covering_radius(points, landmarks) -> float:
351
+ """The largest distance from a point to its nearest landmark."""
352
+ return float(_java().coveringRadiusFromPoints(_jvm.points_in(points), _jvm.ints_in(landmarks, "landmarks")))
353
+
354
+
355
+ @translating
356
+ def covering_radius_from_distances(distances, landmarks) -> float:
357
+ return float(
358
+ _java().coveringRadiusFromDistanceMatrix(
359
+ _jvm.points_in(distances, "distances"), _jvm.ints_in(landmarks, "landmarks")
360
+ )
361
+ )
362
+
363
+
364
+ def _euler(java) -> EulerCurve:
365
+ return EulerCurve(_jvm.vector_out(java.scales()), _jvm.vector_out(java.values(), np.int64), java)
366
+
367
+
368
+ @translating
369
+ def euler_curve(points, **options) -> EulerCurve:
370
+ """The Euler characteristic curve of the Vietoris-Rips complex (options ``max_simplex_dimension`` (2) and
371
+ ``max_filtration_value``)."""
372
+ return _euler(_java().eulerCurveFromPoints(_jvm.points_in(points), _jvm.options_in(options)))
373
+
374
+
375
+ @translating
376
+ def euler_curve_from_distances(distances, **options) -> EulerCurve:
377
+ return _euler(_java().eulerCurveFromDistanceMatrix(_jvm.points_in(distances, "distances"), _jvm.options_in(options)))
378
+
379
+
380
+ @translating
381
+ def bootstrap_band(points, **options) -> BootstrapBand:
382
+ """The resampling confidence band of the bars of one degree. Options: ``dimension`` (1), ``rounds`` (100), ``alpha``
383
+ (0.05), ``seed`` (0), ``subsample_size`` (resample without replacement; by default with replacement), ``prime``,
384
+ ``max_filtration_value``."""
385
+ band = _java().bootstrapBand(_jvm.points_in(points), _jvm.options_in(options))
386
+ return BootstrapBand(
387
+ float(band.width()), float(band.threshold()), float(band.alpha()), _jvm.vector_out(band.distances())
388
+ )
389
+
390
+
391
+ @translating
392
+ def tomato_clusters(points, k: int, tau: float) -> np.ndarray:
393
+ """ToMATo clusters: the cluster number of every point (0 for the highest peak). ``k`` nearest neighbours define the
394
+ graph and the density, ``tau`` is the depth below which two peaks merge."""
395
+ return _jvm.vector_out(_java().tomatoClusters(_jvm.points_in(points), int(k), float(tau)), np.int64)
396
+
397
+
398
+ @translating
399
+ def tomato_diagram(points, k: int) -> np.ndarray:
400
+ """The ``(birth, death)`` pairs of ToMATo's peaks, to choose ``tau`` from; shape ``(n, 2)``."""
401
+ return _jvm.matrix_out(_java().tomatoDiagram(_jvm.points_in(points), int(k)), 2)
402
+
403
+
404
+ # ---------------------------------------------------------------------------------------------------------------------
405
+ # inputs from time series
406
+ # ---------------------------------------------------------------------------------------------------------------------
407
+
408
+ @translating
409
+ def takens_embedding(series, dimension: int, delay: int = 1, stride: int = 1) -> np.ndarray:
410
+ """The sliding-window embedding of a time series (1-D) or of a series of vectors (2-D, one row per time step): row
411
+ ``t`` is the window ``series[t], series[t + delay], ..., series[t + (dimension - 1) * delay]``, and ``stride`` skips
412
+ windows. The result is a point cloud for ``persistence``."""
413
+ array = np.asarray(series, dtype=np.float64)
414
+ if array.ndim == 1:
415
+ rows = _java().takensEmbedding(_jvm.doubles_in(array), int(dimension), int(delay), int(stride))
416
+ return _jvm.matrix_out(rows, int(dimension))
417
+ if array.ndim == 2:
418
+ rows = _java().takensEmbeddingOfVectors(_jvm.points_in(array, "series"), int(dimension), int(delay), int(stride))
419
+ return _jvm.matrix_out(rows, int(dimension) * array.shape[1])
420
+ raise ValueError(f"tda4j: series must be 1-D or 2-D, got {array.ndim} dimensions")
421
+
422
+
423
+ @translating
424
+ def delay_by_autocorrelation(series, max_lag: int) -> int:
425
+ """The first lag in ``1..max_lag`` where the autocorrelation of the series is zero or negative: a first guess for the
426
+ ``delay`` of ``takens_embedding``."""
427
+ return int(_java().delayByAutocorrelation(_jvm.doubles_in(series), int(max_lag)))
428
+
429
+
430
+ # ---------------------------------------------------------------------------------------------------------------------
431
+ # discrete Morse reduction
432
+ # ---------------------------------------------------------------------------------------------------------------------
433
+
434
+ def _morse(java) -> MorseReduction:
435
+ return MorseReduction(
436
+ cell_counts=_jvm.vector_out(java.cellCounts(), np.int64),
437
+ critical_counts=_jvm.vector_out(java.criticalCounts(), np.int64),
438
+ pair_count=int(java.pairCount()),
439
+ critical_cells=[tuple(int(v) for v in cell) for cell in java.criticalCells()],
440
+ bars=_jvm.matrix_out(java.bars(), 3),
441
+ )
442
+
443
+
444
+ @translating
445
+ def morse_reduction(points, **options) -> MorseReduction:
446
+ """Discrete Morse reduction of the Vietoris-Rips complex of a point cloud: cells that enter together are paired off, and
447
+ the bars are computed on the cells left, which are the bars of the complex. Options: ``max_dimension`` (2),
448
+ ``max_filtration_value``, ``strategy`` (``"reduction"``, or ``"coreduction"``), ``prime``, ``threads``."""
449
+ return _morse(_java().morseReductionFromPoints(_jvm.points_in(points), _jvm.options_in(options)))
450
+
451
+
452
+ @translating
453
+ def morse_reduction_from_distances(distances, **options) -> MorseReduction:
454
+ """``morse_reduction`` for a matrix of distances."""
455
+ return _morse(
456
+ _java().morseReductionFromDistanceMatrix(_jvm.points_in(distances, "distances"), _jvm.options_in(options))
457
+ )
458
+
459
+
460
+ # ---------------------------------------------------------------------------------------------------------------------
461
+ # zigzag persistence
462
+ # ---------------------------------------------------------------------------------------------------------------------
463
+
464
+ def _simplices_in(simplices, name: str):
465
+ """A ``int[][]`` of simplices, each a sequence of vertex numbers."""
466
+ rows = [[int(v) for v in simplex] for simplex in simplices]
467
+ if any(not row for row in rows):
468
+ raise ValueError(f"tda4j: {name} must be simplices with at least one vertex each")
469
+ return jpype.JArray(jpype.JInt, 2)(rows)
470
+
471
+
472
+ def _zigzag(java) -> Zigzag:
473
+ return Zigzag(
474
+ bars=_jvm.matrix_out(java.toArray(), 3),
475
+ representatives=[
476
+ Representative(
477
+ [tuple(int(v) for v in cell) for cell in java.cycleVertices(i)],
478
+ _jvm.vector_out(java.cycleCoefficients(i)),
479
+ )
480
+ for i in range(int(java.size()))
481
+ ],
482
+ last_position=int(java.lastPosition()),
483
+ )
484
+
485
+
486
+ @translating
487
+ def zigzag_from_steps(initial, simplices, additions, **options) -> Zigzag:
488
+ """Zigzag persistent homology of the sequence of complexes that starts at ``initial`` (a list of simplices, each a
489
+ sequence of vertex numbers) and in step ``k`` adds the simplex ``simplices[k]`` if ``additions[k]`` is true and
490
+ removes it otherwise. A simplex is added after its facets and removed before the simplices it is a facet of. A bar
491
+ ``(dimension, birth, death)`` is a class present in the homology at the positions ``birth`` to ``death - 1``.
492
+ Options: ``max_dimension`` (2) and ``prime`` (17)."""
493
+ flags = [bool(a) for a in additions]
494
+ return _zigzag(
495
+ _java().zigzagFromSteps(
496
+ _simplices_in(initial, "initial"),
497
+ _simplices_in(simplices, "simplices"),
498
+ jpype.JArray(jpype.JBoolean)(flags),
499
+ _jvm.options_in(options),
500
+ )
501
+ )
502
+
503
+
504
+ @translating
505
+ def zigzag_from_complexes(complexes, **options) -> Zigzag:
506
+ """Zigzag persistent homology of a list of complexes (each a list of simplices), each included in the next or the next
507
+ in it. With ``link="union"`` or ``link="intersection"`` two consecutive complexes are joined through their union or
508
+ intersection, which takes a position of its own. Options: ``link``, ``max_dimension`` (2) and ``prime`` (17)."""
509
+ nested = [[[int(v) for v in simplex] for simplex in complex_] for complex_ in complexes]
510
+ if any(not simplex for complex_ in nested for simplex in complex_):
511
+ raise ValueError("tda4j: complexes must contain simplices with at least one vertex each")
512
+ return _zigzag(_java().zigzagFromComplexes(jpype.JArray(jpype.JInt, 3)(nested), _jvm.options_in(options)))
513
+
514
+
515
+ # ---------------------------------------------------------------------------------------------------------------------
516
+ # the persistent Laplacian
517
+ # ---------------------------------------------------------------------------------------------------------------------
518
+
519
+ def _laplacian(java) -> PersistentLaplacian:
520
+ return PersistentLaplacian(
521
+ dimension=int(java.dimension()),
522
+ start=float(java.start()),
523
+ stop=float(java.stop()),
524
+ cells=[tuple(int(v) for v in cell) for cell in java.cells()],
525
+ matrix=_jvm.matrix_out(java.matrix(), int(java.size())),
526
+ eigenvalues=_jvm.vector_out(java.eigenvalues()),
527
+ kernel=_jvm.matrix_out(java.kernel(), int(java.size())),
528
+ betti_number=int(java.bettiNumber()),
529
+ spectral_gap=float(java.spectralGap()) if java.hasSpectralGap() else None,
530
+ weights=_jvm.vector_out(java.weights()),
531
+ )
532
+
533
+
534
+ @translating
535
+ def persistent_laplacian(points, dimension: int, start: float, stop: float) -> PersistentLaplacian:
536
+ """The persistent Laplacian of the Vietoris-Rips complex of a point cloud: a symmetric matrix on the simplices of the
537
+ given dimension that have entered by the scale ``start``, for the complex at the scale ``stop`` (``start <= stop``).
538
+ Its kernel has the dimension of the persistent Betti number: the classes of that dimension at ``start`` that are still
539
+ there at ``stop``; the smallest eigenvalue that is not zero is its ``spectral_gap``."""
540
+ return _laplacian(_java().persistentLaplacianFromPoints(_jvm.points_in(points), int(dimension), float(start), float(stop)))
541
+
542
+
543
+ @translating
544
+ def persistent_laplacian_from_distances(distances, dimension: int, start: float, stop: float) -> PersistentLaplacian:
545
+ """``persistent_laplacian`` for a matrix of distances."""
546
+ return _laplacian(
547
+ _java().persistentLaplacianFromDistanceMatrix(
548
+ _jvm.points_in(distances, "distances"), int(dimension), float(start), float(stop)
549
+ )
550
+ )
551
+
552
+
553
+ @translating
554
+ def persistent_laplacian_of_map(
555
+ source_points, target_points, vertex_map, dimension: int, start: float, stop: float
556
+ ) -> PersistentLaplacian:
557
+ """The persistent Laplacian of a simplicial map between two Vietoris-Rips complexes: ``vertex_map[i]`` is the index of
558
+ the point of ``target_points`` that the point ``i`` of ``source_points`` goes to, the complex of the source is taken at
559
+ the scale ``start`` and that of the target at ``stop``. The matrix is on the simplices of the given dimension of the
560
+ target that the map hits, and its kernel has the dimension of the rank of the map on homology (``betti_number``). The
561
+ map has to be simplicial; if it is not, this says which simplex has no image. A simplex that several simplices of the
562
+ source go onto counts for as many (``weights``)."""
563
+ return _laplacian(
564
+ _java().persistentLaplacianOfMapFromPoints(
565
+ _jvm.points_in(source_points, "source_points"),
566
+ _jvm.points_in(target_points, "target_points"),
567
+ _jvm.ints_in(vertex_map, "vertex_map"),
568
+ int(dimension),
569
+ float(start),
570
+ float(stop),
571
+ )
572
+ )
573
+
574
+
575
+ @translating
576
+ def persistent_laplacian_of_map_from_distances(
577
+ source_distances, target_distances, vertex_map, dimension: int, start: float, stop: float
578
+ ) -> PersistentLaplacian:
579
+ """``persistent_laplacian_of_map`` for two matrices of distances."""
580
+ return _laplacian(
581
+ _java().persistentLaplacianOfMapFromDistanceMatrices(
582
+ _jvm.points_in(source_distances, "source_distances"),
583
+ _jvm.points_in(target_distances, "target_distances"),
584
+ _jvm.ints_in(vertex_map, "vertex_map"),
585
+ int(dimension),
586
+ float(start),
587
+ float(stop),
588
+ )
589
+ )
590
+
591
+
592
+ # ---------------------------------------------------------------------------------------------------------------------
593
+ # algebra of barcodes: products, Hom and duals
594
+ # ---------------------------------------------------------------------------------------------------------------------
595
+
596
+ def _bars_in(bars, name: str):
597
+ """Rows ``(dimension, birth, death)`` from a result (all of its bars, also the short ones) or any array of rows."""
598
+ if hasattr(bars, "all_bars"):
599
+ bars = bars.all_bars
600
+ array = np.asarray(bars, dtype=np.float64)
601
+ if array.size == 0:
602
+ array = np.empty((0, 3))
603
+ return _jvm.points_in(array, name)
604
+
605
+
606
+ @translating
607
+ def product_bars(first, second, filtration: str = "max") -> np.ndarray:
608
+ """The bars of the homology of the product of two filtered complexes, from the barcodes of the factors (each a
609
+ result or an array of rows ``(dimension, birth, death)``, every dimension of it). A cell of the product enters at
610
+ the larger (``filtration="max"``, the default) or the sum (``"sum"``) of the values of its two factors. Right in
611
+ the dimensions below the highest dimension both were computed to."""
612
+ return _jvm.matrix_out(_java().productBars(_bars_in(first, "first"), _bars_in(second, "second"), str(filtration)), 3)
613
+
614
+
615
+ @translating
616
+ def hom_bars(first, second) -> np.ndarray:
617
+ """The internal Hom of two barcodes (results or arrays of rows ``(dimension, birth, death)``): the module of maps from
618
+ the first to the second shifted by ``t``. A bar of dimension ``p`` and one of dimension ``q`` give a bar of dimension
619
+ ``q - p``."""
620
+ return _jvm.matrix_out(_java().homBars(_bars_in(first, "first"), _bars_in(second, "second")), 3)
621
+
622
+
623
+ @translating
624
+ def hom_dimension(first, second) -> int:
625
+ """The dimension of the space of maps of persistence modules from ``first`` to ``second``, degree by degree."""
626
+ return int(_java().homDimension(_bars_in(first, "first"), _bars_in(second, "second")))
627
+
628
+
629
+ @translating
630
+ def dual_bars(bars) -> np.ndarray:
631
+ """The dual of a barcode: the row ``(dimension, birth, death)`` of ``[b, d)`` becomes ``(dimension, -d, -b)``, the
632
+ interval ``(-d, -b]`` (``-inf`` as the first end for a bar that never dies)."""
633
+ return _jvm.matrix_out(_java().dualBars(_bars_in(bars, "bars")), 3)
634
+
635
+
636
+ # ---------------------------------------------------------------------------------------------------------------------
637
+ # circular and toroidal coordinates
638
+ # ---------------------------------------------------------------------------------------------------------------------
639
+
640
+ @translating
641
+ def h1_bars(points, num_landmarks: int = 0, complex: str = "vr", prime: int = 47) -> np.ndarray:
642
+ """The loops of the Vietoris-Rips complex as ``(birth, death)`` rows, most persistent first: the numbering that
643
+ ``circular_coordinates`` and ``toroidal_coordinates`` use. With ``num_landmarks``, the loops of the balls around
644
+ that many maxmin landmarks, which the coordinates with the same ``num_landmarks`` use. With ``complex="cech"`` or
645
+ ``"alpha"``, the loops of that complex over the field with ``prime`` elements, at a ball's radius (they have no
646
+ landmark form)."""
647
+ return _jvm.matrix_out(_java().h1Bars(_jvm.points_in(points), int(num_landmarks), str(complex), int(prime)), 2)
648
+
649
+
650
+ @translating
651
+ def circular_coordinates(
652
+ points, r: float, cocycle_index: int = 0, prime: int = 47, num_landmarks: int = 0, complex: str = "vr"
653
+ ) -> CircularCoordinates:
654
+ """One angle in [0, 1) per point for loop ``cocycle_index`` of ``h1_bars``, at a scale ``r`` between its birth and
655
+ death. ``num_landmarks`` (default 0, every point) computes Perea's sparse coordinates over that many maxmin
656
+ landmarks, for many points. ``complex`` (``"vr"``, ``"cech"`` or ``"alpha"``) is the complex whose loop it is, as in
657
+ ``h1_bars``. Raises ``Tda4jError`` if the class has no integer lift at ``prime``: retry with a larger prime."""
658
+ result = _java().circularCoordinates(
659
+ _jvm.points_in(points), float(r), int(cocycle_index), int(prime), int(num_landmarks), str(complex)
660
+ )
661
+ return CircularCoordinates(
662
+ _jvm.vector_out(result.theta()),
663
+ float(result.birth()),
664
+ float(result.death()),
665
+ float(result.r()),
666
+ int(result.prime()),
667
+ result,
668
+ )
669
+
670
+
671
+ @translating
672
+ def toroidal_coordinates(
673
+ points, r: float, cocycle_indices, prime: int = 47, reduce: bool = True, num_landmarks: int = 0, complex: str = "vr"
674
+ ) -> ToroidalCoordinates:
675
+ """One angle per point for each of several loops of ``h1_bars`` alive together at ``r`` (``reduce`` applies the
676
+ lattice reduction, ``num_landmarks`` Perea's sparse coordinates, ``complex`` the complex the loops are of, as in
677
+ ``circular_coordinates``): ``theta[c][i]`` is coordinate ``c`` of point ``i``."""
678
+ result = _java().toroidalCoordinates(
679
+ _jvm.points_in(points),
680
+ float(r),
681
+ _jvm.ints_in(cocycle_indices, "cocycle_indices"),
682
+ int(prime),
683
+ bool(reduce),
684
+ int(num_landmarks),
685
+ str(complex),
686
+ )
687
+ count = int(result.dimension())
688
+ n = len(points)
689
+ return ToroidalCoordinates(
690
+ np.array([_jvm.vector_out(result.theta(c)) for c in range(count)]).reshape(count, n),
691
+ _jvm.vector_out(result.cocycleIndices(), np.int64),
692
+ _jvm.int_matrix_out(result.basisChange(), count),
693
+ _jvm.matrix_out(result.originalGram(), count),
694
+ _jvm.matrix_out(result.reducedGram(), count),
695
+ float(result.r()),
696
+ int(result.prime()),
697
+ result,
698
+ )
699
+
700
+
701
+ # ---------------------------------------------------------------------------------------------------------------------
702
+ # plots
703
+ # ---------------------------------------------------------------------------------------------------------------------
704
+
705
+ @translating
706
+ def set_plot_defaults(*settings: str) -> None:
707
+ """Changes to the look of every plot drawn from now on, written ``element.property=value``
708
+ (``set_plot_defaults("palette=print")``); see the plotting page of the user guide."""
709
+ _java().setPlotDefaults(jpype.JArray(jpype.JString)(list(settings)))
710
+
711
+
712
+ @translating
713
+ def clear_plot_defaults() -> None:
714
+ _java().clearPlotDefaults()
715
+
716
+
717
+ @translating
718
+ def side(*plots: Plot) -> Plot:
719
+ """Plots in one row, as one plot: ``tda4j.side(result.plot_barcode(), result.plot_diagram()).save("both.svg")``."""
720
+ if len(plots) < 2:
721
+ raise ValueError("tda4j: side needs at least two plots")
722
+ figures = jpype.JArray(jpype.JClass("org.appliedtopology.tda4j.plot.Figure"))([p._j for p in plots])
723
+ return Plot(_java().side(figures))