-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdionysus_gudhi_persistence.py
287 lines (227 loc) · 8.31 KB
/
dionysus_gudhi_persistence.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import argparse
import os
import re
import subprocess
import sys
import time
import dionysus
import numpy as np
def read_simplicial_complex(dataset):
start = time.time()
with open(dataset, "rb") as src:
magic = src.read(20)
if magic != b"TTKSimplicialComplex":
print("Not a TTK Simplicial Complex file")
raise TypeError
ncells = int.from_bytes(src.read(4), "little", signed=True)
print(f"Number of cells: {ncells}")
dim = int.from_bytes(src.read(4), "little", signed=True)
print(f"Global dataset dimension: {dim}")
dims = [0, 0, 0, 0]
for i, _ in enumerate(dims):
dims[i] = int.from_bytes(src.read(4), "little", signed=True)
for i in range(dim + 1):
print(f" {dims[i]} cells of dimension {i}")
values = np.fromfile(src, dtype=np.double, count=ncells)
num_entries = int.from_bytes(src.read(4), "little", signed=True)
print(f"Number of entries in boundary matrix: {num_entries}")
edges = np.fromfile(src, dtype=np.int32, count=2 * dims[1])
triangles = np.fromfile(src, dtype=np.int32, count=3 * dims[2])
tetras = np.fromfile(src, dtype=np.int32, count=4 * dims[3])
print(f"Read TTK Simplicial Complex file: {time.time() - start:.3f}s")
return dims, values, (edges, triangles, tetras)
class Ripser_SparseDM:
def __init__(self):
self.dist_mat = None
self.diag = None
self.maxdim = 0
print("Using the Ripser backend")
def fill_dist_mat(self, dims, vals, edges):
edges = edges.reshape(-1, 2)
I = np.zeros(dims[0] + dims[1], dtype=np.int32)
J = np.zeros(dims[0] + dims[1], dtype=np.int32)
V = np.zeros(dims[0] + dims[1], dtype=np.double)
if dims[2] != 0:
self.maxdim = 1
if dims[3] != 0:
self.maxdim = 2
for i in range(dims[0]):
I[i] = i
J[i] = i
V[i] = vals[i]
for i, e in enumerate(edges):
o = dims[0] + i
I[o] = e[0]
J[o] = e[1]
V[o] = vals[dims[0] + i]
with open("dist_mat", "w") as dst:
for i, j, v in zip(I, J, V):
dst.write(f"{i} {j} {v}\n")
def compute_pers(self):
cmd = (
["backends_src/ripser/ripser"]
+ ["--format", "sparse"]
+ ["--dim", "2"]
+ ["dist_mat"]
)
with subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
) as proc:
self.diag = [[], [], []]
if proc.returncode != 0:
print(proc.stderr.read())
raise subprocess.CalledProcessError(proc.returncode, cmd)
for line in proc.stdout.readlines():
if "intervals" in line:
dim = int(line.strip()[-2])
line = line.strip()
m = re.search(r"\[(\d+|\d+.\d+),(\d+|\d+.\d+)?\)", line)
if m is not None:
self.diag[dim].append((m.groups()[0], m.groups()[1]))
os.remove("dist_mat")
def write_diag(self, output):
n_pairs = 0
for pairs in self.diag:
n_pairs += len(pairs)
if n_pairs == 0:
return
with open(output, "w") as dst:
for dim, pairs in enumerate(self.diag):
for birth, death in pairs:
dst.write(f"{dim} {birth} {death}\n")
class Dionysus_Filtration:
def __init__(self):
self.f = dionysus.Filtration()
self.diag = None
print("Using the Dionysus2 backend")
def add(self, verts, val):
self.f.append(dionysus.Simplex(verts, val))
def compute_pers(self):
self.f.sort()
m = dionysus.homology_persistence(self.f)
self.diag = dionysus.init_diagrams(m, self.f)
def write_diag(self, output):
with open(output, "w") as dst:
for i, pair in enumerate(self.diag):
for pt in pair:
dst.write(f"{i} {pt.birth} {pt.death}\n")
class Gudhi_SimplexTree:
def __init__(self):
import gudhi
self.st = gudhi.SimplexTree()
self.pairs = []
print("Using the Gudhi Simplex Tree backend")
def add(self, verts, val):
self.st.insert(verts, filtration=val)
def compute_pers(self):
self.pairs = self.st.persistence()
def write_diag(self, output):
with open(output, "w") as dst:
for dim, (birth, death) in self.pairs:
dst.write(f"{dim} {birth:.3f} {death:.3f}\n")
def compute_persistence(wrapper, dims, values, cpx, output):
start = time.time()
edges, triangles, tetras = cpx
if isinstance(wrapper, Ripser_SparseDM):
wrapper.fill_dist_mat(dims, values, edges)
else:
for i in range(dims[0]):
wrapper.add([i], values[i])
for i in range(dims[1]):
o = 2 * i
a = dims[0] + i
wrapper.add(edges[o : o + 2], values[a])
for i in range(dims[2]):
o = 3 * i
a = dims[0] + dims[1] + i
wrapper.add(triangles[o : o + 3], values[a])
for i in range(dims[3]):
o = 4 * i
a = dims[0] + dims[1] + dims[2] + i
wrapper.add(tetras[o : o + 4], values[a])
prec = round(time.time() - start, 3)
print(f"Filled filtration/simplex tree/distance matrix: {prec}s")
start = time.time()
wrapper.compute_pers()
pers = round(time.time() - start, 3)
print(f"Computed persistence: {pers}s")
wrapper.write_diag(output)
return (prec, pers)
def run(dataset, output, backend="Gudhi", simplicial=True):
if simplicial:
dims, vals, cpx = read_simplicial_complex(dataset)
dispatch = {
"Dionysus": Dionysus_Filtration,
"Gudhi": Gudhi_SimplexTree,
"Ripser": Ripser_SparseDM,
}
return compute_persistence(dispatch[backend](), dims, vals, cpx, output)
if backend == "Gudhi":
print("Use the Gudhi Cubical Complex backend")
import gudhi
start = time.time()
cpx = gudhi.CubicalComplex(perseus_file=dataset)
print(f"Loaded Perseus file: {time.time() - start:.3f}s")
print(f"Number of simplices: {cpx.num_simplices()}")
print(f"Global dimension: {cpx.dimension()}")
start = time.time()
diag = cpx.persistence()
pers = round(time.time() - start, 3)
print(f"Computed persistence: {pers}s")
with open(output, "w") as dst:
for dim, (birth, death) in diag:
dst.write(f"{dim} {birth:.3f} {death:.3f}\n")
return (0.0, pers)
print("Cannot use Dionysus with cubical complexes")
return (0.0, 0.0)
def main():
parser = argparse.ArgumentParser(
description="Apply Gudhi, Dionysus2 or Ripser on the given dataset"
)
parser.add_argument(
"-i",
type=str,
help="Path to input dataset",
default="datasets/fuel_64x64x64_uint8_order_expl.tsc",
dest="input_dataset",
)
parser.add_argument(
"-o",
type=str,
help="Output diagram file name",
default="out.gudhi",
dest="output_diagram",
)
parser.add_argument(
"-p",
"--gudhi_path",
type=str,
help="Path to Gudhi Python module",
default="build_dirs/gudhi/src/python",
)
parser.add_argument(
"-b", choices=["gudhi", "dionysus", "ripser"], default="gudhi", dest="backend"
)
args = parser.parse_args()
ext = args.input_dataset.split(".")[-1]
if ext not in ["tsc", "pers"]:
print("Input dataset not supported")
if ext == "pers" and args.backend != "gudhi":
print("Perseus Cubical Complex files can only be processed by Gudhi")
return
if ext == "pers" and "expl" in args.input_dataset:
print("Perseus Simplicial Complex files not supported")
return
# prepend path to Gudhi Python package to PYTHONPATH
sys.path = [args.gudhi_path] + sys.path
run(
args.input_dataset,
args.output_diagram,
backend=args.backend.capitalize(),
simplicial="expl" in args.input_dataset or "tsc" in args.input_dataset,
)
if __name__ == "__main__":
main()