-
Notifications
You must be signed in to change notification settings - Fork 12
/
toroidalcoords.py
438 lines (374 loc) · 14.6 KB
/
toroidalcoords.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
import numpy as np
import scipy
from numba import jit
import scipy.sparse as sparse
from scipy.sparse.linalg import lsqr
from scipy.optimize import LinearConstraint, milp, linprog
from .utils import PartUnity, CircleMapUtils, CohomologyUtils
from .emcoords import EMCoords
from .combinatorial import (
combinatorial_number_system_table,
combinatorial_number_system_d1_forward,
)
class ToroidalCoords(EMCoords):
"""
Object that performs sparse toroidal coordinates via persistent cohomology as in
(L. Scoccola, H. Gakhar, J. Bush, N. Schonsheck, T. Rask, L. Zhou, J. Perea 2022)
Parameters
----------
X: ndarray(N, d)
A point cloud with N points in d dimensions
n_landmarks: int
Number of landmarks to use
distance_matrix: boolean
If true, treat X as a distance matrix instead of a point cloud
prime : int
Field coefficient with which to compute rips on landmarks
maxdim : int
Maximum dimension of homology. Only dimension 1 is needed for circular coordinates,
but it may be of interest to see other dimensions (e.g. for a torus)
"""
def __init__(
self, X, n_landmarks, distance_matrix=False, prime=41, maxdim=1, verbose=False
):
EMCoords.__init__(self, X, n_landmarks, distance_matrix, prime, maxdim, verbose)
self.type_ = "toroidal"
simplicial_complex_dimension = 2
self.cns_lookup_table_ = combinatorial_number_system_table(
n_landmarks, simplicial_complex_dimension
)
def get_coordinates(
self,
perc=0.5,
cocycle_idxs=[0],
partunity_fn=PartUnity.linear,
standard_range=True,
check_cocycle_condition=True,
):
"""
Get toroidal coordinates.
Parameters
----------
perc : float
Percent coverage. Must be between 0 and 1.
cocycle_idx : integer
Integer representing the index of the persistent cohomology class
used to construct the Eilenberg-MacLane coordinate. Persistent cohomology
classes are ordered by persistence, from largest to smallest.
partunity_fn : (dist_land_data, r_cover) -> phi
A function from the distances of each landmark to a bump function
standard_range : bool
Whether to use the parameter perc to choose a filtration parameter that guarantees
that the selected cohomology class represents a non-trivial class in the Cech complex.
check_cocycle_condition : bool
Whether to check, and fix if necessary, that the integer cocycle constructed
using finite field coefficients satisfies the cocycle condition.
Returns
-------
thetas : ndarray(n, N)
List of circular coordinates, with n the length of cocycle_idxs
"""
# get representative cocycles and the intersection of their supports
homological_dimension = 1
cohomdeaths, cohombirths, cocycles = zip(
*[
self.get_representative_cocycle(cohomology_class, homological_dimension)
for cohomology_class in cocycle_idxs
]
)
cohomdeath_rips = max(cohomdeaths)
cohombirth_rips = min(cohombirths)
if cohomdeath_rips >= cohombirth_rips:
raise Exception(
"\
The supports of the chosen persistent cohomology classes do not intersect"
)
# lift to integer cocycles
integer_cocycles = [
CohomologyUtils.lift_to_integer_cocycle(cocycle, prime=self.prime_)
for cocycle in cocycles
]
# determine radius for balls
r_cover, rips_threshold = EMCoords.get_cover_radius(
self, perc, cohomdeath_rips, cohombirth_rips, standard_range
)
# compute partition of unity and choose a cover element for each data point
varphi, ball_indx = EMCoords.get_covering_partition(self, r_cover, partunity_fn)
# compute boundary matrix
dist_land_land = self.dist_land_land_
delta0 = CohomologyUtils.make_delta0(
dist_land_land, rips_threshold, self.cns_lookup_table_
)
# go from sparse to dense representation of cocycles
integer_cocycles_as_vectors = [
CohomologyUtils.sparse_cocycle_to_vector(
sparse_cocycle, self.cns_lookup_table_, self.n_landmarks_, int
)
for sparse_cocycle in integer_cocycles
]
if check_cocycle_condition:
delta1 = None
fixed_cocycles = []
for class_idx, cocycle_as_vector in enumerate(integer_cocycles_as_vectors):
is_cocycle, _ = _is_cocycle(
cocycle_as_vector,
dist_land_land,
rips_threshold,
self.cns_lookup_table_,
)
if is_cocycle:
fixed_cocycles.append(cocycle_as_vector)
else:
delta1 = (
delta1
if delta1
else CohomologyUtils.make_delta1_compact(
dist_land_land, rips_threshold, self.cns_lookup_table_
)
)
d1cocycle = delta1 @ cocycle_as_vector.T
y = d1cocycle // self.prime_
constraints = LinearConstraint(delta1, y, y, keep_feasible=True)
n_edges = delta1.shape[1]
objective = np.zeros((n_edges), dtype=int)
integrality = np.ones((n_edges), dtype=int)
optimizer_solution = milp(
objective,
integrality=integrality,
constraints=constraints,
)
if not optimizer_solution["success"]:
raise Exception(
"The cohomology class at index "
+ str(class_idx)
+ " does not have an integral lift."
)
else:
solution = optimizer_solution["x"]
new_cocycle_as_vector = (
cocycle_as_vector
- self.prime_ * np.array(np.rint(solution), dtype=int)
)
fixed_cocycles.append(new_cocycle_as_vector)
integer_cocycles_as_vectors = fixed_cocycles
# compute harmonic representatives of cocycles and their circle-valued integrals
inner_product_matrix, sqrt_inner_product_matrix = _make_inner_product(
dist_land_land, rips_threshold, self.cns_lookup_table_
)
harm_reps_and_integrals = [
_integrate_harmonic_representative(
cocycle, delta0, sqrt_inner_product_matrix
)
for cocycle in integer_cocycles_as_vectors
]
harm_reps, _ = zip(*harm_reps_and_integrals)
# compute circular coordinates on data points
circ_coords = [
_sparse_integrate(
harm_rep,
integral,
varphi,
ball_indx,
dist_land_land,
rips_threshold,
self.cns_lookup_table_,
)
for harm_rep, integral in harm_reps_and_integrals
]
# if more than one cohomology class was selected
if len(integer_cocycles) > 1:
# compute gram matrix with inner products between harmonic representative cocycles
gram_mat = _gram_matrix(harm_reps, inner_product_matrix)
# perform lattice reduction on the compute circular coordinates
# using the gram matrix of the harmonic representative cocycles
(
circ_coords,
change_basis,
decorrelated_vectors,
) = _reduce_circular_coordinates(circ_coords, gram_mat)
self.original_gram_matrix_ = gram_mat
self.gram_matrix_ = decorrelated_vectors @ decorrelated_vectors.T
self.change_basis_ = change_basis
return circ_coords
def _integrate_harmonic_representative(cocycle, boundary_matrix, sqrt_inner_product):
integral = lsqr(
sqrt_inner_product @ boundary_matrix, sqrt_inner_product @ cocycle.T
)[0]
harm_rep = cocycle - boundary_matrix.dot(integral)
return harm_rep, integral
def _make_inner_product(dist_mat, threshold, lookup_table):
n_points = dist_mat.shape[0]
n_edges = (n_points * (n_points - 1)) // 2
max_n_entries = n_edges
rows = np.empty((max_n_entries,), dtype=int)
columns = np.empty((max_n_entries,), dtype=int)
values = np.empty((max_n_entries,), dtype=float)
@jit(fastmath=True)
def _make_inner_product_get_row_columns_values(
dist_mat: np.ndarray,
threshold: float,
lookup_table: np.ndarray,
n_points: int,
rows: np.ndarray,
columns: np.ndarray,
values: np.ndarray,
):
n_entries = 0
for i in range(n_points):
for j in range(i + 1, n_points):
if dist_mat[i, j] < threshold:
row_index = combinatorial_number_system_d1_forward(
i, j, lookup_table
)
rows[n_entries] = row_index
columns[n_entries] = row_index
values[n_entries] = 1
n_entries += 1
return n_entries
n_entries = _make_inner_product_get_row_columns_values(
dist_mat, threshold, lookup_table, n_points, rows, columns, values
)
W = sparse.csr_array(
(values[:n_entries], (rows[:n_entries], columns[:n_entries])),
shape=(n_edges, n_edges),
)
WSqrt = W.copy()
return W, WSqrt
def _sparse_integrate(
harm_rep,
integral,
part_unity,
membership_function,
dist_mat,
threshold,
lookup_table,
):
n_points = integral.shape[0]
theta_matrix = np.zeros((n_points, n_points))
@jit(fastmath=True)
def _cocycle_to_matrix(
dist_mat: np.ndarray,
threshold: float,
lookup_table: np.ndarray,
n_points: int,
theta_matrix: np.ndarray,
):
for i in range(n_points):
for j in range(i + 1, n_points):
if dist_mat[i, j] < threshold:
index = combinatorial_number_system_d1_forward(i, j, lookup_table)
theta_matrix[i, j] = harm_rep[index]
_cocycle_to_matrix(dist_mat, threshold, lookup_table, n_points, theta_matrix)
class_map = integral[membership_function].copy()
for i in range(class_map.shape[0]):
class_map[i] += theta_matrix[membership_function[i], :].dot(part_unity[:, i])
return np.mod(2 * np.pi * class_map, 2 * np.pi)
@jit(fastmath=True)
def _is_cocycle(
cochain: np.ndarray,
dist_mat: np.ndarray,
threshold: float,
lookup_table: np.ndarray,
):
is_cocycle = True
first_failure = np.inf
n_points = dist_mat.shape[0]
for i in range(n_points):
for j in range(i + 1, n_points):
if dist_mat[i, j] < threshold:
for k in range(j + 1, n_points):
if (
dist_mat[i, k] < threshold
and dist_mat[j, k] < threshold
):
index_ij = combinatorial_number_system_d1_forward(
i, j, lookup_table
)
index_jk = combinatorial_number_system_d1_forward(
j, k, lookup_table
)
index_ik = combinatorial_number_system_d1_forward(
i, k, lookup_table
)
if (
cochain[index_ij]
+ cochain[index_jk]
- cochain[index_ik]
!= 0
):
is_cocycle = False
first_failure = min(
first_failure,
dist_mat[i, j],
dist_mat[j, k],
dist_mat[i, k],
)
return is_cocycle, first_failure
# improve circular coordinates with lattice reduction
def _reduce_circular_coordinates(circ_coords, gram_matrix):
lattice_red_input = np.linalg.cholesky(gram_matrix)
decorrelated_vectors, change_basis = _lll(lattice_red_input.T)
change_basis = change_basis.T
new_circ_coords = CircleMapUtils.linear_combination(
np.array(circ_coords), change_basis
)
return new_circ_coords, change_basis, decorrelated_vectors
def _gram_matrix(vectors, inner_product):
n = len(vectors)
res = np.zeros((n, n))
for i, v in enumerate(vectors):
for j, w in enumerate(vectors):
res[i, j] = v.T @ inner_product @ w
return res
## Lattice Reduction
# Gram-Schmidt (without normalization)
def _gram_schmidt(B):
def gs_cofficient(v1, v2):
return np.dot(v2, v1) / np.dot(v1, v1)
# projects v2 onto v1
def proj(v1, v2):
return gs_cofficient(v1, v2) * v1
n = len(B)
A = np.zeros((n, n))
A[:, 0] = B[:, 0]
for i in range(1, n):
Ai = B[:, i]
for j in range(0, i):
Aj = B[:, j]
# t = np.dot(B[i],B[j])
Ai = Ai - proj(Aj, Ai)
A[:, i] = Ai
return A
# LLL algorithm
def _lll(B, delta=3 / 4):
B = B.copy()
Q = _gram_schmidt(B)
change = np.eye(B.shape[0])
def mu(i, j):
v = B[:, i]
u = Q[:, j]
return np.dot(v, u) / np.dot(u, u)
n, k = len(B), 1
while k < n:
# length reduction step
for j in reversed(range(k)):
if abs(mu(k, j)) > 0.5:
mu_kj = mu(k, j)
B[:, k] = B[:, k] - round(mu_kj) * B[:, j]
change[:, k] = change[:, k] - round(mu_kj) * change[:, j]
Q = _gram_schmidt(B)
# swap step
if np.dot(Q[:, k], Q[:, k]) > (delta - mu(k, k - 1) ** 2) * (
np.dot(Q[:, k - 1], Q[:, k - 1])
):
k = k + 1
else:
B_k = B[:, k].copy()
B_k1 = B[:, k - 1].copy()
B[:, k], B[:, k - 1] = B_k1, B_k
change_k = change[:, k].copy()
change_k1 = change[:, k - 1].copy()
change[:, k], change[:, k - 1] = change_k1, change_k
Q = _gram_schmidt(B)
k = max(k - 1, 1)
return B, change