tda-sparse-vr 0.1.0__tar.gz
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.
- tda_sparse_vr-0.1.0/LICENSE +21 -0
- tda_sparse_vr-0.1.0/PKG-INFO +149 -0
- tda_sparse_vr-0.1.0/README.md +122 -0
- tda_sparse_vr-0.1.0/pyproject.toml +56 -0
- tda_sparse_vr-0.1.0/src/tda_sparse_vr/__init__.py +43 -0
- tda_sparse_vr-0.1.0/src/tda_sparse_vr/api.py +242 -0
- tda_sparse_vr-0.1.0/src/tda_sparse_vr/core.py +255 -0
- tda_sparse_vr-0.1.0/src/tda_sparse_vr/datasets.py +82 -0
- tda_sparse_vr-0.1.0/src/tda_sparse_vr/py.typed +0 -0
- tda_sparse_vr-0.1.0/src/tda_sparse_vr/suggest.py +238 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jan Aerts
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tda-sparse-vr
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Thin out Vietoris-Rips graphs
|
|
5
|
+
Keywords: topological data analysis,tda,vietoris-rips,graph sparsification,spanner,persistent homology
|
|
6
|
+
Author: Jan Aerts
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Science/Research
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Dist: numpy>=1.23
|
|
19
|
+
Requires-Dist: scipy>=1.9
|
|
20
|
+
Requires-Dist: pandas>=1.5 ; extra == 'pandas'
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Project-URL: Homepage, https://gitlab.kuleuven.be/aida-lab/public/tda-sparse-vr
|
|
23
|
+
Project-URL: Issues, https://gitlab.kuleuven.be/aida-lab/public/tda-sparse-vr/-/issues
|
|
24
|
+
Project-URL: Repository, https://gitlab.kuleuven.be/aida-lab/public/tda-sparse-vr.git
|
|
25
|
+
Provides-Extra: pandas
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# tda-sparse-vr
|
|
29
|
+
|
|
30
|
+
Sparsify Vietoris-Rips graphs while keeping their connected components, loops and branches.
|
|
31
|
+
|
|
32
|
+
The Vietoris-Rips (VR) graph of a point cloud connects every pair of points that lie closer than a
|
|
33
|
+
distance `eps`. It reflects the shape of the data, but it is dense. Clusters turn into cliques and
|
|
34
|
+
nearby strands are joined by many redundant edges, so the graph is often too large to draw or analyse.
|
|
35
|
+
`tda-sparse-vr` removes the redundant edges and keeps the ones that carry the shape.
|
|
36
|
+
|
|
37
|
+
## Features
|
|
38
|
+
|
|
39
|
+
- **Greedy spanner.** Drops every edge that the remaining edges already cover with a detour of at most
|
|
40
|
+
`t` times its length. Connected components never change, and distances grow by at most a factor `t`.
|
|
41
|
+
`t=1` keeps (nearly) the full VR graph, and `t=inf` leaves the minimum spanning tree.
|
|
42
|
+
- **Persistent loops (optional).** Always keeps the closing edge of every loop that lasts over a range
|
|
43
|
+
of scales (`death / birth >= rho`).
|
|
44
|
+
- **Connected result (optional).** Adds the shortest bridges between components so the output is a
|
|
45
|
+
single graph.
|
|
46
|
+
- **Parameter suggestions.** Proposes `eps`, `t` and `rho` from the data.
|
|
47
|
+
- **Light dependencies.** Works on point clouds or precomputed distance matrices and needs only NumPy
|
|
48
|
+
and SciPy.
|
|
49
|
+
|
|
50
|
+
## Quick start
|
|
51
|
+
|
|
52
|
+
### Minimal example
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
import numpy as np
|
|
56
|
+
import tda_sparse_vr as sv
|
|
57
|
+
|
|
58
|
+
X = pd.read_csv("horse.csv").to_numpy()
|
|
59
|
+
result = sv.sparsify(X, eps_rel=0.05, t=2.5)
|
|
60
|
+
graph = result.to_graph()
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Concept
|
|
64
|
+
|
|
65
|
+

|
|
66
|
+
|
|
67
|
+
## Install
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
pip install tda-sparse-vr # numpy and scipy
|
|
71
|
+
pip install "tda-sparse-vr[pandas]" # only needed for SparseVR.to_frame()
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Use
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
import numpy as np
|
|
78
|
+
import tda_sparse_vr as sv
|
|
79
|
+
|
|
80
|
+
X = sv.datasets.loop_flare_zipper() # (226, 2) toy cloud: a loop, a flare, two close legs
|
|
81
|
+
|
|
82
|
+
result = sv.sparsify(X) # eps suggested from the data, t = 2
|
|
83
|
+
print(result) # kept edges, components before/after, edge kinds
|
|
84
|
+
|
|
85
|
+
result = sv.sparsify(X, eps=0.4, t=1.5, closers=True, rho=2.5, connect_components=True)
|
|
86
|
+
result = sv.sparsify(X, eps_rel=0.1) # the same kind of call, scale as a fraction of the diameter
|
|
87
|
+
result.eps # the VR scale in data units; result.eps_rel is the same as a fraction of result.scale
|
|
88
|
+
result.edges # (m, 2) integer array, i < j
|
|
89
|
+
result.lengths # (m,)
|
|
90
|
+
result.kind # 0 = spanner, 1 = loop closer, 2 = bridge (sv.KIND_NAMES)
|
|
91
|
+
result.to_frame() # pandas DataFrame
|
|
92
|
+
result.to_graph() # {"nodes": [...], "links": [...]} for force-graph style viewers
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
`eps` is in the units of the data, like in other TDA software. `eps_rel` is the same scale as a fraction of
|
|
96
|
+
`scale`, by default the largest pairwise distance (about the longest side of the point cloud):
|
|
97
|
+
`eps_rel=0.1` connects points closer than 10 % of the longest extent, whatever the units. Give one or
|
|
98
|
+
the other, not both. Rescale your data so that its largest distance is 1 and the two coincide. Pass
|
|
99
|
+
`scale=` to use another reference length, for example `np.ptp(X, axis=0).max()` for the longest side
|
|
100
|
+
of the bounding box.
|
|
101
|
+
|
|
102
|
+
A precomputed distance matrix works too: `sv.sparsify(D, precomputed=True)`. Other scipy metrics:
|
|
103
|
+
`metric="cityblock"`. If the distances are not a true metric (for example cosine distance) the
|
|
104
|
+
triangle-inequality shortcut is switched off automatically (slower, still correct).
|
|
105
|
+
|
|
106
|
+
### Parameters
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
from scipy.spatial.distance import cdist
|
|
110
|
+
D = cdist(X, X)
|
|
111
|
+
|
|
112
|
+
s = sv.suggest_parameters(D) # Suggestion(eps=0.4074 = 9.6% of the longest distance, t=2, rho=2.88, ...)
|
|
113
|
+
s.eps_rel # the same as a fraction of the largest distance, for sparsify(eps_rel=...)
|
|
114
|
+
print(sv.stretch_curve(D, s.eps)) # edges kept for several t: pick the texture you want
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
* **`eps`** (default `None`, i.e. suggested): there is no fixed good value, because a good scale
|
|
118
|
+
follows the point spacing and shrinks as points are added. On the test shapes the suggestions are 4 to 8 % of the
|
|
119
|
+
longest distance for 500 points (the horse: 11 % at 500 points, 5 % at 2,000) and 8 to 25 % for 100 points. The suggestion is the smallest scale (on a x1.5 grid, starting at the median MST edge) at which the pruned
|
|
120
|
+
graph stops changing, raised to cover the birth of every persistent loop found on a farthest-point
|
|
121
|
+
subsample. The search is capped (`max_edges`); if the cap is hit, `converged` is `False` and
|
|
122
|
+
`sparsify` warns. Multi-scale or heavy-tailed data may not settle: give `eps` yourself.
|
|
123
|
+
* **`rho`**: the geometric midpoint between the weakest loop and the strongest noise cycle; 2.5 if
|
|
124
|
+
there is no loop. In the cases tried, noise cycles stayed below a ratio of about 1.9.
|
|
125
|
+
* **`t`**: persistence only brackets it. `t = 1` is the VR graph and `t >= 3` is about MST plus loops;
|
|
126
|
+
in between it sets how much local texture (ladder rungs, mesh triangles) survives. The default is 2;
|
|
127
|
+
use 1.5 for a more mesh-like picture.
|
|
128
|
+
|
|
129
|
+
These are heuristics, checked on a few synthetic shapes and real tables, not guarantees.
|
|
130
|
+
|
|
131
|
+
## Limits
|
|
132
|
+
|
|
133
|
+
* The distance matrix is dense, so memory grows like `n^2`. The spanner handled a few thousand
|
|
134
|
+
points in seconds to tens of seconds.
|
|
135
|
+
* Loop persistence is expensive and refuses graphs
|
|
136
|
+
with more than `max_persistence_edges` (default 50,000) edges: lower `eps` or subsample.
|
|
137
|
+
* Loop detection uses H1 only (ordinary loops, not enclosed cavities).
|
|
138
|
+
|
|
139
|
+
## Development
|
|
140
|
+
|
|
141
|
+
```bash
|
|
142
|
+
uv sync
|
|
143
|
+
uv run pytest
|
|
144
|
+
uv build
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
## License
|
|
148
|
+
|
|
149
|
+
MIT.
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# tda-sparse-vr
|
|
2
|
+
|
|
3
|
+
Sparsify Vietoris-Rips graphs while keeping their connected components, loops and branches.
|
|
4
|
+
|
|
5
|
+
The Vietoris-Rips (VR) graph of a point cloud connects every pair of points that lie closer than a
|
|
6
|
+
distance `eps`. It reflects the shape of the data, but it is dense. Clusters turn into cliques and
|
|
7
|
+
nearby strands are joined by many redundant edges, so the graph is often too large to draw or analyse.
|
|
8
|
+
`tda-sparse-vr` removes the redundant edges and keeps the ones that carry the shape.
|
|
9
|
+
|
|
10
|
+
## Features
|
|
11
|
+
|
|
12
|
+
- **Greedy spanner.** Drops every edge that the remaining edges already cover with a detour of at most
|
|
13
|
+
`t` times its length. Connected components never change, and distances grow by at most a factor `t`.
|
|
14
|
+
`t=1` keeps (nearly) the full VR graph, and `t=inf` leaves the minimum spanning tree.
|
|
15
|
+
- **Persistent loops (optional).** Always keeps the closing edge of every loop that lasts over a range
|
|
16
|
+
of scales (`death / birth >= rho`).
|
|
17
|
+
- **Connected result (optional).** Adds the shortest bridges between components so the output is a
|
|
18
|
+
single graph.
|
|
19
|
+
- **Parameter suggestions.** Proposes `eps`, `t` and `rho` from the data.
|
|
20
|
+
- **Light dependencies.** Works on point clouds or precomputed distance matrices and needs only NumPy
|
|
21
|
+
and SciPy.
|
|
22
|
+
|
|
23
|
+
## Quick start
|
|
24
|
+
|
|
25
|
+
### Minimal example
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
import numpy as np
|
|
29
|
+
import tda_sparse_vr as sv
|
|
30
|
+
|
|
31
|
+
X = pd.read_csv("horse.csv").to_numpy()
|
|
32
|
+
result = sv.sparsify(X, eps_rel=0.05, t=2.5)
|
|
33
|
+
graph = result.to_graph()
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Concept
|
|
37
|
+
|
|
38
|
+

|
|
39
|
+
|
|
40
|
+
## Install
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install tda-sparse-vr # numpy and scipy
|
|
44
|
+
pip install "tda-sparse-vr[pandas]" # only needed for SparseVR.to_frame()
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Use
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
import numpy as np
|
|
51
|
+
import tda_sparse_vr as sv
|
|
52
|
+
|
|
53
|
+
X = sv.datasets.loop_flare_zipper() # (226, 2) toy cloud: a loop, a flare, two close legs
|
|
54
|
+
|
|
55
|
+
result = sv.sparsify(X) # eps suggested from the data, t = 2
|
|
56
|
+
print(result) # kept edges, components before/after, edge kinds
|
|
57
|
+
|
|
58
|
+
result = sv.sparsify(X, eps=0.4, t=1.5, closers=True, rho=2.5, connect_components=True)
|
|
59
|
+
result = sv.sparsify(X, eps_rel=0.1) # the same kind of call, scale as a fraction of the diameter
|
|
60
|
+
result.eps # the VR scale in data units; result.eps_rel is the same as a fraction of result.scale
|
|
61
|
+
result.edges # (m, 2) integer array, i < j
|
|
62
|
+
result.lengths # (m,)
|
|
63
|
+
result.kind # 0 = spanner, 1 = loop closer, 2 = bridge (sv.KIND_NAMES)
|
|
64
|
+
result.to_frame() # pandas DataFrame
|
|
65
|
+
result.to_graph() # {"nodes": [...], "links": [...]} for force-graph style viewers
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
`eps` is in the units of the data, like in other TDA software. `eps_rel` is the same scale as a fraction of
|
|
69
|
+
`scale`, by default the largest pairwise distance (about the longest side of the point cloud):
|
|
70
|
+
`eps_rel=0.1` connects points closer than 10 % of the longest extent, whatever the units. Give one or
|
|
71
|
+
the other, not both. Rescale your data so that its largest distance is 1 and the two coincide. Pass
|
|
72
|
+
`scale=` to use another reference length, for example `np.ptp(X, axis=0).max()` for the longest side
|
|
73
|
+
of the bounding box.
|
|
74
|
+
|
|
75
|
+
A precomputed distance matrix works too: `sv.sparsify(D, precomputed=True)`. Other scipy metrics:
|
|
76
|
+
`metric="cityblock"`. If the distances are not a true metric (for example cosine distance) the
|
|
77
|
+
triangle-inequality shortcut is switched off automatically (slower, still correct).
|
|
78
|
+
|
|
79
|
+
### Parameters
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from scipy.spatial.distance import cdist
|
|
83
|
+
D = cdist(X, X)
|
|
84
|
+
|
|
85
|
+
s = sv.suggest_parameters(D) # Suggestion(eps=0.4074 = 9.6% of the longest distance, t=2, rho=2.88, ...)
|
|
86
|
+
s.eps_rel # the same as a fraction of the largest distance, for sparsify(eps_rel=...)
|
|
87
|
+
print(sv.stretch_curve(D, s.eps)) # edges kept for several t: pick the texture you want
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
* **`eps`** (default `None`, i.e. suggested): there is no fixed good value, because a good scale
|
|
91
|
+
follows the point spacing and shrinks as points are added. On the test shapes the suggestions are 4 to 8 % of the
|
|
92
|
+
longest distance for 500 points (the horse: 11 % at 500 points, 5 % at 2,000) and 8 to 25 % for 100 points. The suggestion is the smallest scale (on a x1.5 grid, starting at the median MST edge) at which the pruned
|
|
93
|
+
graph stops changing, raised to cover the birth of every persistent loop found on a farthest-point
|
|
94
|
+
subsample. The search is capped (`max_edges`); if the cap is hit, `converged` is `False` and
|
|
95
|
+
`sparsify` warns. Multi-scale or heavy-tailed data may not settle: give `eps` yourself.
|
|
96
|
+
* **`rho`**: the geometric midpoint between the weakest loop and the strongest noise cycle; 2.5 if
|
|
97
|
+
there is no loop. In the cases tried, noise cycles stayed below a ratio of about 1.9.
|
|
98
|
+
* **`t`**: persistence only brackets it. `t = 1` is the VR graph and `t >= 3` is about MST plus loops;
|
|
99
|
+
in between it sets how much local texture (ladder rungs, mesh triangles) survives. The default is 2;
|
|
100
|
+
use 1.5 for a more mesh-like picture.
|
|
101
|
+
|
|
102
|
+
These are heuristics, checked on a few synthetic shapes and real tables, not guarantees.
|
|
103
|
+
|
|
104
|
+
## Limits
|
|
105
|
+
|
|
106
|
+
* The distance matrix is dense, so memory grows like `n^2`. The spanner handled a few thousand
|
|
107
|
+
points in seconds to tens of seconds.
|
|
108
|
+
* Loop persistence is expensive and refuses graphs
|
|
109
|
+
with more than `max_persistence_edges` (default 50,000) edges: lower `eps` or subsample.
|
|
110
|
+
* Loop detection uses H1 only (ordinary loops, not enclosed cavities).
|
|
111
|
+
|
|
112
|
+
## Development
|
|
113
|
+
|
|
114
|
+
```bash
|
|
115
|
+
uv sync
|
|
116
|
+
uv run pytest
|
|
117
|
+
uv build
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## License
|
|
121
|
+
|
|
122
|
+
MIT.
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["uv_build>=0.8.9,<0.9.0"]
|
|
3
|
+
build-backend = "uv_build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "tda-sparse-vr"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Thin out Vietoris-Rips graphs"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
authors = [{ name = "Jan Aerts" }]
|
|
13
|
+
requires-python = ">=3.10"
|
|
14
|
+
keywords = ["topological data analysis", "tda", "vietoris-rips", "graph sparsification", "spanner", "persistent homology"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Intended Audience :: Science/Research",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Programming Language :: Python :: 3.10",
|
|
20
|
+
"Programming Language :: Python :: 3.11",
|
|
21
|
+
"Programming Language :: Python :: 3.12",
|
|
22
|
+
"Programming Language :: Python :: 3.13",
|
|
23
|
+
"Topic :: Scientific/Engineering :: Mathematics",
|
|
24
|
+
"Typing :: Typed",
|
|
25
|
+
]
|
|
26
|
+
dependencies = [
|
|
27
|
+
"numpy>=1.23",
|
|
28
|
+
"scipy>=1.9",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Homepage = "https://gitlab.kuleuven.be/aida-lab/public/tda-sparse-vr"
|
|
33
|
+
Repository = "https://gitlab.kuleuven.be/aida-lab/public/tda-sparse-vr.git"
|
|
34
|
+
Issues = "https://gitlab.kuleuven.be/aida-lab/public/tda-sparse-vr/-/issues"
|
|
35
|
+
|
|
36
|
+
[project.optional-dependencies]
|
|
37
|
+
pandas = ["pandas>=1.5"]
|
|
38
|
+
|
|
39
|
+
[dependency-groups]
|
|
40
|
+
dev = [
|
|
41
|
+
"pytest>=7",
|
|
42
|
+
"pandas>=1.5",
|
|
43
|
+
]
|
|
44
|
+
demo = [
|
|
45
|
+
"graph-widget==0.1.18; python_version >= '3.11'",
|
|
46
|
+
"marimo>=0.26.1; python_version >= '3.11'",
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
[tool.uv]
|
|
50
|
+
default-groups = ["dev", "demo"]
|
|
51
|
+
|
|
52
|
+
[tool.uv.build-backend]
|
|
53
|
+
module-name = "tda_sparse_vr"
|
|
54
|
+
|
|
55
|
+
[tool.pytest.ini_options]
|
|
56
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Thin out Vietoris-Rips graphs: a greedy spanner, optional persistent loop closers, and
|
|
2
|
+
data-driven suggestions for the scale ``eps``, the stretch ``t`` and the loop threshold ``rho``."""
|
|
3
|
+
|
|
4
|
+
from . import datasets
|
|
5
|
+
from .api import KIND_NAMES, SparseVR, dedupe, sparsify
|
|
6
|
+
from .core import (
|
|
7
|
+
LoopPersistence,
|
|
8
|
+
bridge_edges,
|
|
9
|
+
candidate_edges,
|
|
10
|
+
greedy_spanner,
|
|
11
|
+
loop_persistence,
|
|
12
|
+
)
|
|
13
|
+
from .suggest import (
|
|
14
|
+
EpsilonSuggestion,
|
|
15
|
+
StretchCurve,
|
|
16
|
+
Suggestion,
|
|
17
|
+
stretch_curve,
|
|
18
|
+
suggest_epsilon,
|
|
19
|
+
suggest_parameters,
|
|
20
|
+
suggest_rho,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
__version__ = "0.1.0"
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"EpsilonSuggestion",
|
|
27
|
+
"KIND_NAMES",
|
|
28
|
+
"LoopPersistence",
|
|
29
|
+
"SparseVR",
|
|
30
|
+
"StretchCurve",
|
|
31
|
+
"Suggestion",
|
|
32
|
+
"bridge_edges",
|
|
33
|
+
"candidate_edges",
|
|
34
|
+
"datasets",
|
|
35
|
+
"dedupe",
|
|
36
|
+
"greedy_spanner",
|
|
37
|
+
"loop_persistence",
|
|
38
|
+
"sparsify",
|
|
39
|
+
"stretch_curve",
|
|
40
|
+
"suggest_epsilon",
|
|
41
|
+
"suggest_parameters",
|
|
42
|
+
"suggest_rho",
|
|
43
|
+
]
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
"""High-level entry point: ``sparsify`` and its result type."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import warnings
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from scipy.spatial.distance import cdist
|
|
10
|
+
|
|
11
|
+
from .core import (
|
|
12
|
+
bridge_edges,
|
|
13
|
+
check_distance_matrix,
|
|
14
|
+
greedy_spanner,
|
|
15
|
+
loop_persistence,
|
|
16
|
+
n_components,
|
|
17
|
+
)
|
|
18
|
+
from .suggest import DEFAULT_RHO, DEFAULT_T, suggest_epsilon
|
|
19
|
+
|
|
20
|
+
__all__ = ["KIND_NAMES", "SparseVR", "dedupe", "sparsify"]
|
|
21
|
+
|
|
22
|
+
KIND_NAMES = ("spanner", "loop_closer", "bridge") # values of SparseVR.kind: 0, 1, 2
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _py(value):
|
|
26
|
+
"""JSON-friendly Python value (numpy scalars unwrapped, NaN -> None)."""
|
|
27
|
+
if hasattr(value, "item"):
|
|
28
|
+
value = value.item()
|
|
29
|
+
if isinstance(value, float) and value != value:
|
|
30
|
+
return None
|
|
31
|
+
return value
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class SparseVR:
|
|
36
|
+
"""The sparse graph plus what produced it. ``edges[k] = (i, j)`` has length ``lengths[k]``
|
|
37
|
+
and origin ``KIND_NAMES[kind[k]]``.
|
|
38
|
+
|
|
39
|
+
``eps`` is the VR scale in the units of the data; ``eps_rel = eps / scale`` is the same scale as
|
|
40
|
+
a fraction of ``scale`` (by default the largest distance in the data)."""
|
|
41
|
+
|
|
42
|
+
edges: np.ndarray # (m, 2) int, i < j
|
|
43
|
+
lengths: np.ndarray # (m,)
|
|
44
|
+
kind: np.ndarray # (m,) int8: 0 spanner, 1 persistent-loop closer, 2 component bridge
|
|
45
|
+
n_points: int
|
|
46
|
+
eps: float
|
|
47
|
+
scale: float
|
|
48
|
+
t: float
|
|
49
|
+
rho: float | None
|
|
50
|
+
n_vr_edges: int
|
|
51
|
+
n_components_vr: int
|
|
52
|
+
n_components: int
|
|
53
|
+
eps_converged: bool | None = None # None when eps was given
|
|
54
|
+
info: dict = field(default_factory=dict)
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def eps_rel(self) -> float:
|
|
58
|
+
"""``eps`` as a fraction of ``scale``."""
|
|
59
|
+
return self.eps / self.scale if self.scale > 0 else self.eps
|
|
60
|
+
|
|
61
|
+
def __len__(self) -> int:
|
|
62
|
+
return len(self.edges)
|
|
63
|
+
|
|
64
|
+
def summary(self) -> str:
|
|
65
|
+
counts = {name: int((self.kind == k).sum()) for k, name in enumerate(KIND_NAMES)}
|
|
66
|
+
return (
|
|
67
|
+
f"{self.n_points} points, eps={self.eps:.4g} ({self.eps_rel:.1%} of {self.scale:.4g}), "
|
|
68
|
+
f"t={self.t:g}: {len(self):,} of "
|
|
69
|
+
f"{self.n_vr_edges:,} VR edges kept ({len(self) / max(self.n_vr_edges, 1):.1%}); "
|
|
70
|
+
f"{counts}; components {self.n_components_vr} -> {self.n_components}"
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
__repr__ = summary
|
|
74
|
+
|
|
75
|
+
def to_frame(self):
|
|
76
|
+
"""Edges as a pandas DataFrame (needs pandas)."""
|
|
77
|
+
import pandas as pd
|
|
78
|
+
|
|
79
|
+
return pd.DataFrame(
|
|
80
|
+
{
|
|
81
|
+
"i": self.edges[:, 0],
|
|
82
|
+
"j": self.edges[:, 1],
|
|
83
|
+
"length": self.lengths,
|
|
84
|
+
"kind": [KIND_NAMES[k] for k in self.kind],
|
|
85
|
+
}
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def to_graph(self, nodes=None) -> dict:
|
|
89
|
+
"""``{"nodes": [...], "links": [...]}`` for force-graph style viewers such as graph_widget.
|
|
90
|
+
|
|
91
|
+
``nodes`` may be a DataFrame, a list of dicts or a mapping of column name to values; its
|
|
92
|
+
columns become node attributes.
|
|
93
|
+
"""
|
|
94
|
+
if nodes is None:
|
|
95
|
+
records = [{} for _ in range(self.n_points)]
|
|
96
|
+
elif hasattr(nodes, "to_dict"):
|
|
97
|
+
records = nodes.to_dict("records")
|
|
98
|
+
elif isinstance(nodes, dict):
|
|
99
|
+
records = [dict(zip(nodes, row)) for row in zip(*nodes.values())]
|
|
100
|
+
else:
|
|
101
|
+
records = [dict(r) for r in nodes]
|
|
102
|
+
if len(records) != self.n_points:
|
|
103
|
+
raise ValueError(f"expected {self.n_points} node records, got {len(records)}")
|
|
104
|
+
return {
|
|
105
|
+
"nodes": [{"id": i, **{k: _py(v) for k, v in r.items()}} for i, r in enumerate(records)],
|
|
106
|
+
"links": [
|
|
107
|
+
{"source": int(a), "target": int(b), "distance": float(d), "kind": KIND_NAMES[k]}
|
|
108
|
+
for (a, b), d, k in zip(self.edges, self.lengths, self.kind)
|
|
109
|
+
],
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def dedupe(data):
|
|
114
|
+
"""Merge exact duplicate rows. Returns ``(unique_rows, inverse)``; ``inverse[k]`` is the row of
|
|
115
|
+
``unique_rows`` that point ``k`` maps to, so edges of the result refer to ``unique_rows``."""
|
|
116
|
+
unique, inverse = np.unique(np.asarray(data, dtype=float), axis=0, return_inverse=True)
|
|
117
|
+
return unique, inverse.ravel()
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _distance_matrix(data, precomputed: bool, metric: str) -> np.ndarray:
|
|
121
|
+
if precomputed:
|
|
122
|
+
return check_distance_matrix(data)
|
|
123
|
+
X = np.asarray(data, dtype=float)
|
|
124
|
+
if X.ndim != 2:
|
|
125
|
+
raise ValueError(f"expected a 2-D array of points (n, d), got shape {X.shape}")
|
|
126
|
+
if X.shape[0] == 0:
|
|
127
|
+
raise ValueError("no points given")
|
|
128
|
+
if not np.all(np.isfinite(X)):
|
|
129
|
+
raise ValueError("the data contain NaN or infinite values")
|
|
130
|
+
return check_distance_matrix(cdist(X, X, metric=metric))
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _is_metric(D: np.ndarray, seed: int = 0, trials: int = 20_000) -> bool:
|
|
134
|
+
"""Cheap randomised triangle-inequality check (the A* bound needs a true metric)."""
|
|
135
|
+
n = len(D)
|
|
136
|
+
if n < 3:
|
|
137
|
+
return True
|
|
138
|
+
rng = np.random.default_rng(seed)
|
|
139
|
+
a, b, c = rng.integers(0, n, (3, trials))
|
|
140
|
+
return bool(np.all(D[a, c] <= D[a, b] + D[b, c] + 1e-9 * float(D.max())))
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def sparsify(
|
|
144
|
+
data,
|
|
145
|
+
*,
|
|
146
|
+
eps: float | None = None,
|
|
147
|
+
eps_rel: float | None = None,
|
|
148
|
+
scale: float | None = None,
|
|
149
|
+
t: float = DEFAULT_T,
|
|
150
|
+
closers: bool = False,
|
|
151
|
+
rho: float | None = None,
|
|
152
|
+
connect_components: bool = False,
|
|
153
|
+
precomputed: bool = False,
|
|
154
|
+
metric: str = "euclidean",
|
|
155
|
+
assume_metric: bool | None = None,
|
|
156
|
+
max_persistence_edges: int = 50_000,
|
|
157
|
+
) -> SparseVR:
|
|
158
|
+
"""Thin out the Vietoris-Rips graph of a point cloud or distance matrix.
|
|
159
|
+
|
|
160
|
+
1. Build the VR graph: connect every pair of points closer than ``eps``.
|
|
161
|
+
2. Keep a greedy ``t``-spanner of it: an edge survives only if no path of length
|
|
162
|
+
``<= t * length`` exists among the kept edges.
|
|
163
|
+
3. ``closers=True``: also keep the closing edge of every persistent H1 loop
|
|
164
|
+
(``death / birth >= rho``). Slow for large graphs.
|
|
165
|
+
4. ``connect_components=True``: add the MST edges longer than the VR scale so the result is
|
|
166
|
+
connected.
|
|
167
|
+
|
|
168
|
+
The scale is given either as ``eps``, in the units of the data, or as ``eps_rel``, a fraction of
|
|
169
|
+
``scale``. ``scale`` defaults to the largest pairwise distance (the diameter, about the longest
|
|
170
|
+
side of the point cloud), so ``eps_rel=0.1`` means "connect points closer than 10 % of the
|
|
171
|
+
longest extent", whatever the units. If you rescale the data so that its largest distance is 1,
|
|
172
|
+
``eps`` and ``eps_rel`` are the same number. Pass ``scale`` to use another reference, for
|
|
173
|
+
example ``np.ptp(X, axis=0).max()``, the longest side of the bounding box.
|
|
174
|
+
|
|
175
|
+
With neither given, ``eps`` is suggested from the data (see ``suggest_epsilon``) and reported in
|
|
176
|
+
the result. A good scale shrinks as the number of points grows, which is why there is no fixed
|
|
177
|
+
default fraction.
|
|
178
|
+
"""
|
|
179
|
+
if eps is not None and eps_rel is not None:
|
|
180
|
+
raise ValueError("give either eps (data units) or eps_rel (fraction of scale), not both")
|
|
181
|
+
for name, value in (("eps", eps), ("eps_rel", eps_rel)):
|
|
182
|
+
if value is not None and not value >= 0:
|
|
183
|
+
raise ValueError(f"{name} must be >= 0, got {value}")
|
|
184
|
+
if scale is not None and not (np.isfinite(scale) and scale > 0):
|
|
185
|
+
raise ValueError(f"scale must be a positive number, got {scale}")
|
|
186
|
+
D = _distance_matrix(data, precomputed, metric)
|
|
187
|
+
n = len(D)
|
|
188
|
+
scale = float(D.max()) if scale is None else float(scale)
|
|
189
|
+
if assume_metric is None:
|
|
190
|
+
assume_metric = _is_metric(D)
|
|
191
|
+
if not assume_metric:
|
|
192
|
+
warnings.warn("the distances violate the triangle inequality; using plain Dijkstra (slower)")
|
|
193
|
+
converged = None
|
|
194
|
+
if eps is None and eps_rel is None:
|
|
195
|
+
s = suggest_epsilon(D, t, assume_metric=assume_metric)
|
|
196
|
+
eps, converged = s.eps, s.converged
|
|
197
|
+
if not converged:
|
|
198
|
+
warnings.warn("eps could not be settled within the edge cap; pass eps explicitly")
|
|
199
|
+
elif eps is None:
|
|
200
|
+
eps = np.inf if np.isinf(eps_rel) else eps_rel * scale
|
|
201
|
+
eps = float(eps)
|
|
202
|
+
if closers and rho is None:
|
|
203
|
+
rho = DEFAULT_RHO
|
|
204
|
+
|
|
205
|
+
i, j, w, keep = greedy_spanner(D, eps, t, assume_metric=assume_metric)
|
|
206
|
+
ei, ej, ew = [i[keep]], [j[keep]], [w[keep]]
|
|
207
|
+
kind = [np.zeros(int(keep.sum()), dtype=np.int8)]
|
|
208
|
+
comps_vr = n_components(n, i, j)
|
|
209
|
+
info = {"n_spanner_edges": int(keep.sum())}
|
|
210
|
+
|
|
211
|
+
if closers:
|
|
212
|
+
lp = loop_persistence(D, eps, max_edges=max_persistence_edges)
|
|
213
|
+
ci, cj, cw = lp.closing_edges(rho)
|
|
214
|
+
have = np.concatenate([ei[0].astype(np.int64) * n + ej[0]])
|
|
215
|
+
new = ~np.isin(ci.astype(np.int64) * n + cj, have)
|
|
216
|
+
ei.append(ci[new]); ej.append(cj[new]); ew.append(cw[new])
|
|
217
|
+
kind.append(np.ones(int(new.sum()), dtype=np.int8))
|
|
218
|
+
info["n_persistent_loops"] = int(len(ci))
|
|
219
|
+
info["n_loop_closers_added"] = int(new.sum())
|
|
220
|
+
|
|
221
|
+
if connect_components:
|
|
222
|
+
bi, bj, bw = bridge_edges(D, eps)
|
|
223
|
+
ei.append(bi); ej.append(bj); ew.append(bw)
|
|
224
|
+
kind.append(np.full(len(bi), 2, dtype=np.int8))
|
|
225
|
+
info["n_bridges"] = int(len(bi))
|
|
226
|
+
|
|
227
|
+
I, J = np.concatenate(ei), np.concatenate(ej)
|
|
228
|
+
return SparseVR(
|
|
229
|
+
edges=np.column_stack([I, J]).astype(np.int64),
|
|
230
|
+
lengths=np.concatenate(ew).astype(float),
|
|
231
|
+
kind=np.concatenate(kind),
|
|
232
|
+
n_points=n,
|
|
233
|
+
eps=eps,
|
|
234
|
+
scale=scale,
|
|
235
|
+
t=float(t),
|
|
236
|
+
rho=rho,
|
|
237
|
+
n_vr_edges=len(w),
|
|
238
|
+
n_components_vr=comps_vr,
|
|
239
|
+
n_components=n_components(n, I, J),
|
|
240
|
+
eps_converged=converged,
|
|
241
|
+
info=info,
|
|
242
|
+
)
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
"""Building blocks: greedy spanner, H1 persistence of the flag filtration, MST bridges.
|
|
2
|
+
|
|
3
|
+
Everything here works on a dense, symmetric distance matrix ``D`` (shape ``(n, n)``).
|
|
4
|
+
Edges are always reported as ``i < j`` and, where a filtration order matters, sorted by
|
|
5
|
+
length with ties broken by position (stable sort), so results are deterministic.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import heapq
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
from scipy.sparse import csr_matrix
|
|
15
|
+
from scipy.sparse.csgraph import connected_components, minimum_spanning_tree
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"LoopPersistence",
|
|
19
|
+
"bridge_edges",
|
|
20
|
+
"candidate_edges",
|
|
21
|
+
"check_distance_matrix",
|
|
22
|
+
"greedy_spanner",
|
|
23
|
+
"loop_persistence",
|
|
24
|
+
"n_components",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
_REL_TOL = 1e-12 # relative slack when comparing path lengths
|
|
28
|
+
_ZERO_FLOOR = 1e-12 # scipy's csgraph reads 0 as "no edge"; duplicates get this weight there
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# --------------------------------------------------------------------------- input checks
|
|
32
|
+
def check_distance_matrix(D) -> np.ndarray:
|
|
33
|
+
"""Return ``D`` as a float array after checking it is a valid distance matrix."""
|
|
34
|
+
D = np.asarray(D, dtype=float)
|
|
35
|
+
if D.ndim != 2 or D.shape[0] != D.shape[1]:
|
|
36
|
+
raise ValueError(f"a distance matrix must be square, got shape {D.shape}")
|
|
37
|
+
if D.shape[0] == 0:
|
|
38
|
+
raise ValueError("the distance matrix is empty")
|
|
39
|
+
if not np.all(np.isfinite(D)):
|
|
40
|
+
raise ValueError("the distance matrix contains NaN or infinite values")
|
|
41
|
+
if (D < 0).any():
|
|
42
|
+
raise ValueError("the distance matrix contains negative values")
|
|
43
|
+
atol = 1e-9 * max(float(D.max()), 1e-300)
|
|
44
|
+
if not np.allclose(D, D.T, rtol=0.0, atol=atol):
|
|
45
|
+
raise ValueError("the distance matrix is not symmetric")
|
|
46
|
+
if not np.allclose(np.diag(D), 0.0, atol=atol):
|
|
47
|
+
raise ValueError("the distance matrix has a non-zero diagonal")
|
|
48
|
+
return D
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# ----------------------------------------------------------------------------- union-find
|
|
52
|
+
def _find(parent: list[int], x: int) -> int:
|
|
53
|
+
while parent[x] != x:
|
|
54
|
+
parent[x] = parent[parent[x]]
|
|
55
|
+
x = parent[x]
|
|
56
|
+
return x
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _forest_mask(n: int, i: np.ndarray, j: np.ndarray) -> np.ndarray:
|
|
60
|
+
"""Kruskal over edges already in filtration order: True where an edge joins two components."""
|
|
61
|
+
parent = list(range(n))
|
|
62
|
+
mask = np.zeros(len(i), dtype=bool)
|
|
63
|
+
for e, (a, b) in enumerate(zip(i.tolist(), j.tolist())):
|
|
64
|
+
ra, rb = _find(parent, a), _find(parent, b)
|
|
65
|
+
if ra != rb:
|
|
66
|
+
parent[ra] = rb
|
|
67
|
+
mask[e] = True
|
|
68
|
+
return mask
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def n_components(n: int, i, j) -> int:
|
|
72
|
+
"""Number of connected components of the graph on ``n`` nodes with edges ``(i, j)``."""
|
|
73
|
+
i, j = np.asarray(i, dtype=np.int64), np.asarray(j, dtype=np.int64)
|
|
74
|
+
if len(i) == 0:
|
|
75
|
+
return int(n)
|
|
76
|
+
graph = csr_matrix((np.ones(len(i)), (i, j)), shape=(n, n))
|
|
77
|
+
return int(connected_components(graph, directed=False)[0])
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
# ------------------------------------------------------------------------------- VR graph
|
|
81
|
+
def candidate_edges(D: np.ndarray, eps: float):
|
|
82
|
+
"""Edges of the Vietoris-Rips graph at scale ``eps``: arrays ``(i, j, w)`` with ``i < j``,
|
|
83
|
+
sorted by length (stable)."""
|
|
84
|
+
iu, ju = np.nonzero(np.triu(D <= eps, k=1))
|
|
85
|
+
w = D[iu, ju]
|
|
86
|
+
order = np.argsort(w, kind="stable")
|
|
87
|
+
return iu[order], ju[order], w[order]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
# ----------------------------------------------------------------------------- the spanner
|
|
91
|
+
def _has_path(adj, D, u: int, v: int, limit: float, metric: bool) -> bool:
|
|
92
|
+
"""Is there a path from ``u`` to ``v`` of length <= ``limit`` in the graph ``adj``?
|
|
93
|
+
|
|
94
|
+
With ``metric`` the distance matrix is used as an admissible A* lower bound, which is only
|
|
95
|
+
valid when ``D`` satisfies the triangle inequality.
|
|
96
|
+
"""
|
|
97
|
+
h = D[v] if metric else None
|
|
98
|
+
best = {u: 0.0}
|
|
99
|
+
heap = [(float(h[u]) if metric else 0.0, 0.0, u)]
|
|
100
|
+
while heap:
|
|
101
|
+
_, d, x = heapq.heappop(heap)
|
|
102
|
+
if x == v:
|
|
103
|
+
return True
|
|
104
|
+
if d > best[x]:
|
|
105
|
+
continue
|
|
106
|
+
for y, wy in adj[x]:
|
|
107
|
+
nd = d + wy
|
|
108
|
+
if nd > limit:
|
|
109
|
+
continue
|
|
110
|
+
f = nd + (h[y] if metric else 0.0)
|
|
111
|
+
if f <= limit and nd < best.get(y, np.inf):
|
|
112
|
+
best[y] = nd
|
|
113
|
+
heapq.heappush(heap, (f, nd, y))
|
|
114
|
+
return False
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def greedy_spanner(D: np.ndarray, eps: float, t: float, *, assume_metric: bool = True):
|
|
118
|
+
"""Greedy ``t``-spanner of the Vietoris-Rips graph at scale ``eps``.
|
|
119
|
+
|
|
120
|
+
Edges are scanned from shortest to longest. An edge is kept only if the edges kept so far
|
|
121
|
+
do not already connect its endpoints by a path of length ``<= t * length``. Consequences:
|
|
122
|
+
|
|
123
|
+
* ``t = 1`` keeps (almost) every edge, ``t = inf`` leaves the minimum spanning forest;
|
|
124
|
+
* connected components are the same as in the full VR graph;
|
|
125
|
+
* for every VR edge, the shortest path between its endpoints in the result is at most
|
|
126
|
+
``t`` times its length.
|
|
127
|
+
|
|
128
|
+
Returns ``(i, j, w, keep)``: all VR edges (sorted by length) and a boolean mask of the kept ones.
|
|
129
|
+
``assume_metric=False`` drops the A* lower bound, needed if ``D`` violates the triangle inequality.
|
|
130
|
+
"""
|
|
131
|
+
t = float(t)
|
|
132
|
+
if not t >= 1.0:
|
|
133
|
+
raise ValueError(f"the stretch t must be >= 1, got {t}")
|
|
134
|
+
n = len(D)
|
|
135
|
+
i, j, w = candidate_edges(D, eps)
|
|
136
|
+
if np.isinf(t):
|
|
137
|
+
return i, j, w, _forest_mask(n, i, j)
|
|
138
|
+
adj: list[list[tuple[int, float]]] = [[] for _ in range(n)]
|
|
139
|
+
keep = np.zeros(len(w), dtype=bool)
|
|
140
|
+
slack = 1.0 + _REL_TOL
|
|
141
|
+
for e in range(len(w)):
|
|
142
|
+
u, v, we = int(i[e]), int(j[e]), float(w[e])
|
|
143
|
+
if _has_path(adj, D, u, v, t * we * slack, assume_metric):
|
|
144
|
+
continue
|
|
145
|
+
keep[e] = True
|
|
146
|
+
adj[u].append((v, we))
|
|
147
|
+
adj[v].append((u, we))
|
|
148
|
+
return i, j, w, keep
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
# ------------------------------------------------------------------------------ persistence
|
|
152
|
+
@dataclass(frozen=True)
|
|
153
|
+
class LoopPersistence:
|
|
154
|
+
"""H1 classes of the flag filtration, one per non-tree edge.
|
|
155
|
+
|
|
156
|
+
Each class is born at the length of ``(i, j)`` (the edge that closes the cycle) and dies at
|
|
157
|
+
``death``, the scale at which triangles fill it in (``inf`` if that never happens below ``eps``).
|
|
158
|
+
"""
|
|
159
|
+
|
|
160
|
+
i: np.ndarray
|
|
161
|
+
j: np.ndarray
|
|
162
|
+
birth: np.ndarray
|
|
163
|
+
death: np.ndarray
|
|
164
|
+
|
|
165
|
+
@property
|
|
166
|
+
def ratio(self) -> np.ndarray:
|
|
167
|
+
"""``death / birth``: about 1 for noise, large for loops that last."""
|
|
168
|
+
b, d = self.birth, self.death
|
|
169
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
170
|
+
r = np.where(d <= b, 1.0, d / np.maximum(b, np.finfo(float).tiny))
|
|
171
|
+
return r
|
|
172
|
+
|
|
173
|
+
def closing_edges(self, rho: float):
|
|
174
|
+
"""Arrays ``(i, j, birth)`` of the classes with ``death / birth >= rho``."""
|
|
175
|
+
keep = self.ratio >= rho
|
|
176
|
+
return self.i[keep], self.j[keep], self.birth[keep]
|
|
177
|
+
|
|
178
|
+
def __len__(self) -> int:
|
|
179
|
+
return len(self.i)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def loop_persistence(D: np.ndarray, eps: float = np.inf, *, max_edges: int = 50_000) -> LoopPersistence:
|
|
183
|
+
"""H1 persistence (over Z/2) of the flag filtration of the VR graph up to scale ``eps``.
|
|
184
|
+
|
|
185
|
+
The cost grows quickly with the number of edges, so graphs with more than ``max_edges``
|
|
186
|
+
edges are refused; subsample the points or lower ``eps``.
|
|
187
|
+
"""
|
|
188
|
+
n = len(D)
|
|
189
|
+
i, j, w = candidate_edges(D, eps)
|
|
190
|
+
m = len(w)
|
|
191
|
+
if m > max_edges:
|
|
192
|
+
raise ValueError(
|
|
193
|
+
f"{m:,} edges at eps={eps:g} exceed max_edges={max_edges:,}; "
|
|
194
|
+
"lower eps, subsample the points, or raise max_edges"
|
|
195
|
+
)
|
|
196
|
+
tree = _forest_mask(n, i, j) # same order as the filtration, so it matches the reduction
|
|
197
|
+
eid = np.full((n, n), -1, dtype=np.int32)
|
|
198
|
+
eid[i, j] = eid[j, i] = np.arange(m, dtype=np.int32)
|
|
199
|
+
adj = eid >= 0
|
|
200
|
+
|
|
201
|
+
tris = []
|
|
202
|
+
for e in range(m):
|
|
203
|
+
a, b = int(i[e]), int(j[e])
|
|
204
|
+
ks = np.flatnonzero(adj[a] & adj[b])
|
|
205
|
+
ks = ks[ks > b]
|
|
206
|
+
if len(ks):
|
|
207
|
+
tris.append(np.column_stack([np.full(len(ks), e, dtype=np.int32), eid[a, ks], eid[b, ks]]))
|
|
208
|
+
tris = np.vstack(tris) if tris else np.empty((0, 3), dtype=np.int32)
|
|
209
|
+
tris = tris[np.argsort(tris.max(axis=1), kind="stable")]
|
|
210
|
+
|
|
211
|
+
# Standard column reduction over Z/2; a column is a Python int used as a bitmask over edges.
|
|
212
|
+
pivot: dict[int, int] = {}
|
|
213
|
+
death = np.full(m, np.inf)
|
|
214
|
+
for tri in tris.tolist():
|
|
215
|
+
col = (1 << tri[0]) | (1 << tri[1]) | (1 << tri[2])
|
|
216
|
+
while col:
|
|
217
|
+
p = col.bit_length() - 1
|
|
218
|
+
if p not in pivot:
|
|
219
|
+
if tree[p]: # cannot happen: a pivot is the youngest edge of a cycle
|
|
220
|
+
raise RuntimeError("internal error: a spanning-tree edge became a pivot")
|
|
221
|
+
pivot[p] = col
|
|
222
|
+
death[p] = w[max(tri)]
|
|
223
|
+
break
|
|
224
|
+
col ^= pivot[p]
|
|
225
|
+
loops = ~tree
|
|
226
|
+
return LoopPersistence(i=i[loops], j=j[loops], birth=w[loops], death=death[loops])
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
# ---------------------------------------------------------------------------------- bridges
|
|
230
|
+
def _mst_edges(D: np.ndarray):
|
|
231
|
+
"""Minimum spanning tree of the complete graph: arrays ``(i, j, w)`` with ``i < j``."""
|
|
232
|
+
n = len(D)
|
|
233
|
+
if n < 2:
|
|
234
|
+
empty = np.empty(0, dtype=np.int64)
|
|
235
|
+
return empty, empty.copy(), np.empty(0)
|
|
236
|
+
W = np.where(D > 0, D, _ZERO_FLOOR)
|
|
237
|
+
np.fill_diagonal(W, 0.0)
|
|
238
|
+
mst = minimum_spanning_tree(csr_matrix(W)).tocoo()
|
|
239
|
+
i = np.minimum(mst.row, mst.col).astype(np.int64)
|
|
240
|
+
j = np.maximum(mst.row, mst.col).astype(np.int64)
|
|
241
|
+
return i, j, D[i, j]
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def bridge_edges(D: np.ndarray, eps: float):
|
|
245
|
+
"""MST edges of the complete graph that are longer than ``eps``.
|
|
246
|
+
|
|
247
|
+
Inside a connected component of the VR graph the MST uses edges of length ``<= eps``, so
|
|
248
|
+
these are exactly the ``components - 1`` edges that join the components into one tree.
|
|
249
|
+
Returns ``(i, j, w)`` sorted by length.
|
|
250
|
+
"""
|
|
251
|
+
i, j, w = _mst_edges(D)
|
|
252
|
+
far = w > eps
|
|
253
|
+
i, j, w = i[far], j[far], w[far]
|
|
254
|
+
order = np.argsort(w, kind="stable")
|
|
255
|
+
return i[order], j[order], w[order]
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Small synthetic point clouds with known topology, for demos and tests.
|
|
2
|
+
|
|
3
|
+
Each generator returns an ``(n, 2)`` array. Loops are real H1 features; the "zipper" shapes have two
|
|
4
|
+
close parallel legs, whose Vietoris-Rips graph is a dense ladder but which contain no loop.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
__all__ = ["figure_eight", "hairpin", "loop_flare_zipper", "ring", "y_shape"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _noisy(X: np.ndarray, noise: float, rng: np.random.Generator) -> np.ndarray:
|
|
15
|
+
# The tiny floor keeps points distinct, so no two points sit at distance exactly 0.
|
|
16
|
+
return X + rng.normal(0.0, noise + 1e-6, X.shape)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def ring(n: int = 100, noise: float = 0.03, seed: int = 0) -> np.ndarray:
|
|
20
|
+
"""Unit circle: one loop."""
|
|
21
|
+
rng = np.random.default_rng(seed)
|
|
22
|
+
t = rng.uniform(0, 2 * np.pi, n)
|
|
23
|
+
return _noisy(np.c_[np.cos(t), np.sin(t)], noise, rng)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def figure_eight(n: int = 100, noise: float = 0.03, seed: int = 0) -> np.ndarray:
|
|
27
|
+
"""Two unit circles touching at the origin: two loops."""
|
|
28
|
+
rng = np.random.default_rng(seed)
|
|
29
|
+
t = rng.uniform(0, 2 * np.pi, n)
|
|
30
|
+
s = rng.integers(0, 2, n) * 2 - 1
|
|
31
|
+
return _noisy(np.c_[s + np.cos(t), np.sin(t)], noise, rng)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def y_shape(n: int = 100, noise: float = 0.03, seed: int = 0) -> np.ndarray:
|
|
35
|
+
"""Three flares meeting in the origin: no loop."""
|
|
36
|
+
rng = np.random.default_rng(seed)
|
|
37
|
+
arm = rng.integers(0, 3, n)
|
|
38
|
+
r = rng.uniform(0, 1.5, n)
|
|
39
|
+
a = np.pi / 2 + arm * 2 * np.pi / 3
|
|
40
|
+
return _noisy(np.c_[r * np.cos(a), r * np.sin(a)], noise, rng)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def hairpin(n: int = 100, noise: float = 0.03, seed: int = 0, gap: float = 0.3) -> np.ndarray:
|
|
44
|
+
"""Two close parallel legs joined by a small arch: a zipper, but no loop."""
|
|
45
|
+
rng = np.random.default_rng(seed)
|
|
46
|
+
length = 2.0
|
|
47
|
+
arch = np.pi * gap / 2
|
|
48
|
+
d = rng.uniform(0, 1, n) * (2 * length + arch)
|
|
49
|
+
th = (d - length) / arch * np.pi
|
|
50
|
+
X = np.where(
|
|
51
|
+
(d < length)[:, None],
|
|
52
|
+
np.c_[np.full(n, -gap / 2), d],
|
|
53
|
+
np.where(
|
|
54
|
+
(d < length + arch)[:, None],
|
|
55
|
+
np.c_[-gap / 2 * np.cos(th), length + gap / 2 * np.sin(th)],
|
|
56
|
+
np.c_[np.full(n, gap / 2), length - (d - length - arch)],
|
|
57
|
+
),
|
|
58
|
+
)
|
|
59
|
+
return _noisy(X, noise, rng)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def loop_flare_zipper(seed: int = 3) -> np.ndarray:
|
|
63
|
+
"""226 points: a loop, a forked flare on its right and two close legs hanging below it."""
|
|
64
|
+
rng = np.random.default_rng(seed)
|
|
65
|
+
parts = []
|
|
66
|
+
t = rng.uniform(0, 2 * np.pi, 80)
|
|
67
|
+
parts.append(np.c_[np.cos(t), np.sin(t)])
|
|
68
|
+
s = rng.uniform(0, 1, 18)
|
|
69
|
+
parts.append(np.c_[1.0 + 0.9 * s, 0.0 * s])
|
|
70
|
+
s = rng.uniform(0, 1, 22)
|
|
71
|
+
parts.append(np.c_[1.9 + 0.9 * s, 0.55 * s])
|
|
72
|
+
s = rng.uniform(0, 1, 22)
|
|
73
|
+
parts.append(np.c_[1.9 + 0.9 * s, -0.55 * s])
|
|
74
|
+
gap, length = 0.28, 1.5
|
|
75
|
+
s = rng.uniform(0, 1, 38)
|
|
76
|
+
parts.append(np.c_[np.full(38, -gap / 2), -1.0 - length * s])
|
|
77
|
+
s = rng.uniform(0, 1, 38)
|
|
78
|
+
parts.append(np.c_[np.full(38, gap / 2), -1.0 - length * s])
|
|
79
|
+
th = rng.uniform(0, np.pi, 8)
|
|
80
|
+
parts.append(np.c_[gap / 2 * np.cos(th), -1.0 - length - gap / 2 * np.sin(th)])
|
|
81
|
+
X = np.vstack(parts)
|
|
82
|
+
return X + rng.normal(0, 0.022, X.shape)
|
|
File without changes
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"""Data-driven starting values for the scale ``eps``, the stretch ``t`` and the loop threshold ``rho``.
|
|
2
|
+
|
|
3
|
+
These are heuristics, validated on a handful of synthetic clouds and a few real tables, not
|
|
4
|
+
theorems. Use them as a first guess and look at the diagnostics.
|
|
5
|
+
|
|
6
|
+
* **eps** is the smallest scale, on a geometric grid, at which the pruned graph stops changing,
|
|
7
|
+
raised so that every persistent H1 loop (found on a farthest-point subsample) is already born.
|
|
8
|
+
The grid starts at the median MST edge length (the H0 sampling scale).
|
|
9
|
+
* **rho** sits in the gap between noise cycles (death/birth close to 1) and real loops.
|
|
10
|
+
* **t** has no persistence-derived optimum: it sets how much local texture (ladder rungs,
|
|
11
|
+
triangles) survives. ``t = 1`` is the VR graph and ``t >= 3`` is about MST + persistent loops.
|
|
12
|
+
The default is 2; ``stretch_curve`` shows the trade-off for your data.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
|
|
21
|
+
from .core import (
|
|
22
|
+
_mst_edges,
|
|
23
|
+
greedy_spanner,
|
|
24
|
+
loop_persistence,
|
|
25
|
+
n_components,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"DEFAULT_RHO",
|
|
30
|
+
"DEFAULT_T",
|
|
31
|
+
"EpsilonSuggestion",
|
|
32
|
+
"Suggestion",
|
|
33
|
+
"StretchCurve",
|
|
34
|
+
"stretch_curve",
|
|
35
|
+
"suggest_epsilon",
|
|
36
|
+
"suggest_parameters",
|
|
37
|
+
"suggest_rho",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
DEFAULT_T = 2.0
|
|
41
|
+
DEFAULT_RHO = 2.5
|
|
42
|
+
NOISE_CEILING = 2.0 # classes with death/birth >= this are called persistent loops
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _farthest_point_sample(D: np.ndarray, m: int) -> np.ndarray:
|
|
46
|
+
n = len(D)
|
|
47
|
+
if m >= n:
|
|
48
|
+
return np.arange(n)
|
|
49
|
+
idx = [0]
|
|
50
|
+
dmin = D[0].copy()
|
|
51
|
+
for _ in range(m - 1):
|
|
52
|
+
k = int(dmin.argmax())
|
|
53
|
+
idx.append(k)
|
|
54
|
+
dmin = np.minimum(dmin, D[k])
|
|
55
|
+
return np.array(idx)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _keys(i: np.ndarray, j: np.ndarray, n: int) -> np.ndarray:
|
|
59
|
+
return i.astype(np.int64) * n + j.astype(np.int64)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True)
|
|
63
|
+
class EpsilonSuggestion:
|
|
64
|
+
eps: float
|
|
65
|
+
converged: bool # False if the edge cap stopped the search before the graph stabilised
|
|
66
|
+
eps_stable: float # the scale where the pruned graph stopped changing
|
|
67
|
+
n_loops: int # persistent loops found on the subsample
|
|
68
|
+
loop_birth: float # largest birth among them (0 if none)
|
|
69
|
+
loop_ratios: np.ndarray = field(default_factory=lambda: np.empty(0)) # death/birth of all H1 classes on the subsample
|
|
70
|
+
trace: list = field(default_factory=list) # (eps, vr_edges, kept_edges, overlap_with_previous)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def suggest_epsilon(
|
|
74
|
+
D: np.ndarray,
|
|
75
|
+
t: float = DEFAULT_T,
|
|
76
|
+
*,
|
|
77
|
+
overlap: float = 0.95,
|
|
78
|
+
growth: float = 1.5,
|
|
79
|
+
max_edges: int = 100_000,
|
|
80
|
+
loop_floor: float = NOISE_CEILING,
|
|
81
|
+
sample: int = 100,
|
|
82
|
+
assume_metric: bool = True,
|
|
83
|
+
) -> EpsilonSuggestion:
|
|
84
|
+
"""Suggest ``eps`` for a distance matrix ``D`` (see the module docstring for the rule).
|
|
85
|
+
|
|
86
|
+
``max_edges`` caps the number of VR edges examined, so heavy-tailed or multi-scale data cannot
|
|
87
|
+
run away. If the cap is hit, ``converged`` is False and the last scale tried is returned.
|
|
88
|
+
"""
|
|
89
|
+
n = len(D)
|
|
90
|
+
dmax = float(D.max())
|
|
91
|
+
if n <= 2 or dmax == 0.0:
|
|
92
|
+
return EpsilonSuggestion(dmax, True, dmax, 0, 0.0, np.empty(0), [])
|
|
93
|
+
_, _, lengths = _mst_edges(D)
|
|
94
|
+
nonzero = lengths[lengths > 0]
|
|
95
|
+
eps = float(np.median(nonzero)) if len(nonzero) else dmax
|
|
96
|
+
|
|
97
|
+
prev_keys = None
|
|
98
|
+
prev_eps = eps
|
|
99
|
+
converged = False
|
|
100
|
+
trace = []
|
|
101
|
+
while True:
|
|
102
|
+
n_vr = int((np.count_nonzero(D <= eps) - n) // 2)
|
|
103
|
+
if n_vr > max_edges and prev_keys is not None:
|
|
104
|
+
eps = prev_eps
|
|
105
|
+
break
|
|
106
|
+
i, j, w, keep = greedy_spanner(D, eps, t, assume_metric=assume_metric)
|
|
107
|
+
keys = _keys(i[keep], j[keep], n)
|
|
108
|
+
jac = 0.0
|
|
109
|
+
if prev_keys is not None:
|
|
110
|
+
union = len(np.union1d(keys, prev_keys))
|
|
111
|
+
jac = len(np.intersect1d(keys, prev_keys)) / union if union else 1.0
|
|
112
|
+
trace.append((eps, len(w), int(keep.sum()), jac))
|
|
113
|
+
if prev_keys is not None and jac >= overlap:
|
|
114
|
+
converged = True
|
|
115
|
+
break
|
|
116
|
+
if eps >= dmax:
|
|
117
|
+
converged = True
|
|
118
|
+
break
|
|
119
|
+
if n_vr > max_edges:
|
|
120
|
+
break
|
|
121
|
+
prev_keys, prev_eps = keys, eps
|
|
122
|
+
eps = min(eps * growth, dmax)
|
|
123
|
+
eps_stable = eps
|
|
124
|
+
|
|
125
|
+
idx = _farthest_point_sample(D, sample)
|
|
126
|
+
sub = D[np.ix_(idx, idx)]
|
|
127
|
+
lp = loop_persistence(sub, np.inf, max_edges=len(idx) * len(idx))
|
|
128
|
+
real = lp.ratio >= loop_floor
|
|
129
|
+
birth = float(lp.birth[real].max()) if real.any() else 0.0
|
|
130
|
+
return EpsilonSuggestion(
|
|
131
|
+
eps=max(eps_stable, 1.1 * birth),
|
|
132
|
+
converged=converged,
|
|
133
|
+
eps_stable=eps_stable,
|
|
134
|
+
n_loops=int(real.sum()),
|
|
135
|
+
loop_birth=birth,
|
|
136
|
+
loop_ratios=lp.ratio,
|
|
137
|
+
trace=trace,
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def suggest_rho(ratios, *, floor: float = NOISE_CEILING, default: float = DEFAULT_RHO) -> float:
|
|
142
|
+
"""Pick ``rho`` in the gap between noise cycles and persistent loops.
|
|
143
|
+
|
|
144
|
+
``ratios`` are the ``death / birth`` values of the H1 classes. Classes with a ratio of at
|
|
145
|
+
least ``floor`` count as loops. ``rho`` is the geometric midpoint between the weakest loop and
|
|
146
|
+
the strongest noise cycle; ``default`` is returned if there is no loop.
|
|
147
|
+
"""
|
|
148
|
+
r = np.asarray(ratios, dtype=float)
|
|
149
|
+
loops = r[r >= floor]
|
|
150
|
+
if len(loops) == 0:
|
|
151
|
+
return default
|
|
152
|
+
weakest = float(loops[np.isfinite(loops)].min()) if np.isfinite(loops).any() else 10.0 * floor
|
|
153
|
+
noise = r[r < floor]
|
|
154
|
+
ceiling = float(noise.max()) if len(noise) else 1.0
|
|
155
|
+
return float(np.sqrt(weakest * max(ceiling, 1.0)))
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
@dataclass(frozen=True)
|
|
159
|
+
class Suggestion:
|
|
160
|
+
eps: float # absolute, in the units of the distance matrix
|
|
161
|
+
t: float
|
|
162
|
+
rho: float
|
|
163
|
+
epsilon: EpsilonSuggestion
|
|
164
|
+
scale: float # reference length: the largest distance in the matrix
|
|
165
|
+
|
|
166
|
+
@property
|
|
167
|
+
def eps_rel(self) -> float:
|
|
168
|
+
"""``eps`` as a fraction of ``scale``: the value to pass to ``sparsify(eps_rel=...)``."""
|
|
169
|
+
return self.eps / self.scale if self.scale > 0 else self.eps
|
|
170
|
+
|
|
171
|
+
def __repr__(self) -> str:
|
|
172
|
+
flag = "" if self.epsilon.converged else " (not converged: edge cap reached)"
|
|
173
|
+
return (
|
|
174
|
+
f"Suggestion(eps={self.eps:.4g} = {self.eps_rel:.1%} of the longest distance{flag}, "
|
|
175
|
+
f"t={self.t:g}, rho={self.rho:.3g}, "
|
|
176
|
+
f"persistent loops on the subsample: {self.epsilon.n_loops})"
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def suggest_parameters(
|
|
181
|
+
D: np.ndarray, *, t: float = DEFAULT_T, sample: int = 100, assume_metric: bool = True, **kwargs
|
|
182
|
+
) -> Suggestion:
|
|
183
|
+
"""Suggest ``eps``, ``t`` and ``rho`` for a distance matrix (see the module docstring).
|
|
184
|
+
|
|
185
|
+
``eps`` is absolute (in the units of ``D``); ``eps_rel`` is the same value as a fraction of the
|
|
186
|
+
largest distance in ``D``."""
|
|
187
|
+
eps = suggest_epsilon(D, t, sample=sample, assume_metric=assume_metric, **kwargs)
|
|
188
|
+
return Suggestion(
|
|
189
|
+
eps=eps.eps,
|
|
190
|
+
t=float(t),
|
|
191
|
+
rho=suggest_rho(eps.loop_ratios),
|
|
192
|
+
epsilon=eps,
|
|
193
|
+
scale=float(D.max()),
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
@dataclass(frozen=True)
|
|
198
|
+
class StretchCurve:
|
|
199
|
+
"""Edges kept by the spanner for several values of ``t`` at one ``eps``."""
|
|
200
|
+
|
|
201
|
+
t: np.ndarray
|
|
202
|
+
n_edges: np.ndarray
|
|
203
|
+
fraction: np.ndarray # share of the VR graph's edges
|
|
204
|
+
excess: np.ndarray # edges beyond a spanning forest: the number of independent cycles kept
|
|
205
|
+
n_vr_edges: int
|
|
206
|
+
|
|
207
|
+
def __repr__(self) -> str:
|
|
208
|
+
rows = [f"VR graph: {self.n_vr_edges:,} edges", " t edges kept excess"]
|
|
209
|
+
for t, e, f, x in zip(self.t, self.n_edges, self.fraction, self.excess):
|
|
210
|
+
rows.append(f"{t:7.3g} {e:9,d} {f:5.1%} {x:7,d}")
|
|
211
|
+
return "\n".join(rows)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def stretch_curve(
|
|
215
|
+
D: np.ndarray,
|
|
216
|
+
eps: float,
|
|
217
|
+
ts=(1.1, 1.25, 1.5, 2.0, 3.0, 5.0, np.inf),
|
|
218
|
+
*,
|
|
219
|
+
assume_metric: bool = True,
|
|
220
|
+
) -> StretchCurve:
|
|
221
|
+
"""How many edges survive at each ``t``: pick the knee that gives the texture you want."""
|
|
222
|
+
n = len(D)
|
|
223
|
+
counts, n_vr = [], 0
|
|
224
|
+
comps = None
|
|
225
|
+
for t in ts:
|
|
226
|
+
i, j, w, keep = greedy_spanner(D, eps, t, assume_metric=assume_metric)
|
|
227
|
+
n_vr = len(w)
|
|
228
|
+
counts.append(int(keep.sum()))
|
|
229
|
+
if comps is None:
|
|
230
|
+
comps = n_components(n, i, j)
|
|
231
|
+
counts = np.array(counts)
|
|
232
|
+
return StretchCurve(
|
|
233
|
+
t=np.array(ts, dtype=float),
|
|
234
|
+
n_edges=counts,
|
|
235
|
+
fraction=counts / max(n_vr, 1),
|
|
236
|
+
excess=counts - (n - comps),
|
|
237
|
+
n_vr_edges=n_vr,
|
|
238
|
+
)
|