Debian Codegraph @

ot/gromov/_quantized.py

raw symbols SCIP
1 """
2 Quantized (Fused) Gromov-Wasserstein solvers.
3 """
4
5 # Author: Cédric Vincent-Cuaz <[email protected]>
6 #
7 # License: MIT License
8
9 import numpy as np
10 import warnings
11
12 try:
13 from networkx.algorithms.community import asyn_fluidc, louvain_communities
14 from networkx import from_numpy_array, pagerank
15
16 networkx_import = True
17 except ImportError:
18 networkx_import = False
19
20 try:
21 from sklearn.cluster import SpectralClustering, KMeans
22
23 sklearn_import = True
24 except ImportError:
25 sklearn_import = False
26
27 import random
28
29 from ..utils import list_to_array, unif, dist
30 from ..backend import get_backend
31 from ..lp import emd_1d
32 from ._gw import gromov_wasserstein, fused_gromov_wasserstein
33 from ._utils import init_matrix, gwloss
34
35
36 def quantized_fused_gromov_wasserstein_partitioned(
37 CR1,
38 CR2,
39 list_R1,
40 list_R2,
41 list_p1,
42 list_p2,
43 MR=None,
44 alpha=1.0,
45 build_OT=False,
46 log=False,
47 armijo=False,
48 max_iter=1e4,
49 tol_rel=1e-9,
50 tol_abs=1e-9,
51 nx=None,
52 **kwargs,
53 ):
54 r"""
55 Returns the quantized Fused Gromov-Wasserstein transport between
56 :math:`(\mathbf{C_1}, \mathbf{F_1}, \mathbf{p})` and :math:`(\mathbf{C_2},
57 \mathbf{F_2}, \mathbf{q})`, whose samples are assigned to partitions and representants
58 :math:`\mathcal{P_1} = \{(\mathbf{P_{1, i}}, \mathbf{r_{1, i}})\}_{i \leq npart1}`
59 and :math:`\mathcal{P_2} = \{(\mathbf{P_{2, j}}, \mathbf{r_{2, j}})\}_{j \leq npart2}`.
60 The latter must be precomputed and encoded e.g for the source as: :math:`\mathbf{CR_1}`
61 structure matrix between representants; `list_R1` a list of relations between
62 representants and their associated samples; `list_p1` a list of nodes
63 distribution within each partition; :math:`\mathbf{FR_1}` feature matrix
64 of representants.
65
66 The function estimates the following optimization problem:
67
68 .. math::
69 \mathbf{T}^* \in \mathop{\arg \min}_\mathbf{T} \quad \alpha \sum_{i,j,k,l}
70 L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) \mathbf{T}_{i,j} \mathbf{T}_{k,l}
71 + (1-\alpha) \langle \mathbf{T}, M\rangle_F
72 s.t. \ \mathbf{T} \mathbf{1} &= \mathbf{p}
73
74 \mathbf{T}^T \mathbf{1} &= \mathbf{q}
75
76 \mathbf{T} &\geq 0
77
78 \mathbf{T}_{|\mathbf{P_{1, i}}, \mathbf{P_{2, j}}} &= T^{g}_{ij} \mathbf{T}^{(i,j)}
79
80 using a two-step strategy computing: i) a global alignment :math:`\mathbf{T}^{g}`
81 between representants joint structure and feature spaces; ii) local alignments
82 :math:`\mathbf{T}^{(i, j)}` between partitions :math:`\mathbf{P_{1, i}}`
83 and :math:`\mathbf{P_{2, j}}` seen as 1D measures.
84
85 Where :
86
87 - :math:`\mathbf{C_1}`: Metric cost matrix in the source space
88 - :math:`\mathbf{C_2}`: Metric cost matrix in the target space
89 - :math:`\mathbf{F_1}`: Feature matrix in the source space
90 - :math:`\mathbf{F_2}`: Feature matrix in the target space
91 - :math:`\mathbf{M}`: Pairwise similarity matrix between features
92 - :math:`\mathbf{p}`: distribution in the source space
93 - :math:`\mathbf{q}`: distribution in the target space
94 - :math:`L`: quadratic loss function to account for the misfit between the similarity matrices
95
96 .. note:: This function is backend-compatible and will work on arrays
97 from all compatible backends. But the algorithm uses the C++ CPU backend
98 which can lead to copy overhead on GPU arrays.
99 .. note:: All computations in the Gromov-Wasserstein conjugate gradient solver
100 are done with numpy to limit memory overhead.
101
102 Parameters
103 ----------
104 CR1 : array-like, shape (npart1, npart1)
105 Structure matrix between partition representants in the source space.
106 CR2 : array-like, shape (npart2, npart2)
107 Structure matrix between partition representants in the target space.
108 list_R1 : list of npart1 arrays,
109 List of relations between representants and their associated samples in the source space.
110 list_R2 : list of npart2 arrays,
111 List of relations between representants and their associated samples in the target space.
112 list_p1 : list of npart1 arrays,
113 List of node distributions within each partition of the source space.
114 list_p : list of npart2 arrays,
115 List of node distributions within each partition of the target space.
116 MR : array-like, shape (npart1, npart2), optional. (Default is None)
117 Metric cost matrix between features of representants across spaces.
118 alpha: float, optional. Default is None.
119 FGW trade-off parameter in :math:`]0, 1]` between structure and features.
120 If `alpha = 1` features are ignored hence computing qGW.
121 build_OT: bool, optional. Default is False
122 Either to build or not the OT between non-partitioned structures.
123 log : bool, optional. Default is False
124 record log if True
125 armijo : bool, optional
126 If True the step of the line-search is found via an armijo research. Else closed form is used.
127 If there are convergence issues use False.
128 max_iter : int, optional
129 Max number of iterations
130 tol_rel : float, optional
131 Stop threshold on relative error (>0)
132 tol_abs : float, optional
133 Stop threshold on absolute error (>0)
134 nx : backend, optional
135 POT backend
136
137 **kwargs : dict
138 parameters can be directly passed to the ot.optim.cg solver
139
140 Returns
141 -------
142 T_global: array-like, shape (`npart1`, `npart2`)
143 Gromov-Wasserstein alignment :math:`\mathbf{T}^{g}` between representants.
144 Ts_local: dict of local OT matrices.
145 Dictionary with keys :math:`(i, j)` corresponding to 1D OT between
146 :math:`\mathbf{P_{1, i}}` and :math:`\mathbf{P_{2, j}}` if :math:`T^{g}_{ij} \neq 0`.
147 T: array-like, shape `(ns, nt)`
148 Coupling between the two spaces if `build_OT=True` else None.
149 log : dict, if `log=True`.
150 Convergence information and losses of inner OT problems.
151
152 References
153 ----------
154 .. [68] Chowdhury, S., Miller, D., & Needham, T. (2021).
155 Quantized gromov-wasserstein. ECML PKDD 2021. Springer International Publishing.
156
157 """
158 if nx is None:
159 arr = [CR1, CR2, *list_R1, *list_R2, *list_p1, *list_p2]
160
161 if MR is not None:
162 arr.append(MR)
163
164 nx = get_backend(*arr)
165
166 npart1 = len(list_R1)
167 npart2 = len(list_R2)
168
169 # compute marginals for global alignment
170 pR1 = nx.from_numpy(list_to_array([nx.sum(p) for p in list_p1]))
171 pR2 = nx.from_numpy(list_to_array([nx.sum(q) for q in list_p2]))
172
173 # compute global alignment
174 if alpha == 1.0:
175 res_global = gromov_wasserstein(
176 CR1,
177 CR2,
178 pR1,
179 pR2,
180 loss_fun="square_loss",
181 log=log,
182 armijo=armijo,
183 max_iter=max_iter,
184 tol_rel=tol_rel,
185 tol_abs=tol_abs,
186 )
187
188 if log:
189 T_global, dist_global = res_global[0], res_global[1]["gw_dist"]
190 else:
191 T_global = res_global
192
193 elif (alpha < 1.0) and (alpha > 0.0):
194 res_global = fused_gromov_wasserstein(
195 MR,
196 CR1,
197 CR2,
198 pR1,
199 pR2,
200 "square_loss",
201 alpha=alpha,
202 log=log,
203 armijo=armijo,
204 max_iter=max_iter,
205 tol_rel=tol_rel,
206 tol_abs=tol_abs,
207 )
208
209 if log:
210 T_global, dist_global = res_global[0], res_global[1]["fgw_dist"]
211 else:
212 T_global = res_global
213
214 else:
215 raise ValueError(
216 f"""
217 `alpha='{alpha}'` should be in ]0, 1].
218 """
219 )
220
221 if log:
222 log_ = {}
223 log_["global dist"] = dist_global
224
225 # compute local alignments
226 Ts_local = {}
227 list_p1_norm = [p / nx.sum(p) for p in list_p1]
228 list_p2_norm = [q / nx.sum(q) for q in list_p2]
229
230 for i in range(npart1):
231 for j in range(npart2):
232 if T_global[i, j] != 0.0:
233 res_1d = emd_1d(
234 list_R1[i],
235 list_R2[j],
236 list_p1_norm[i],
237 list_p2_norm[j],
238 metric="sqeuclidean",
239 p=1.0,
240 log=log,
241 )
242 if log:
243 T_local, log_local = res_1d
244 Ts_local[(i, j)] = T_local
245 log_[f"local dist ({i},{j})"] = log_local["cost"]
246 else:
247 Ts_local[(i, j)] = res_1d
248
249 if build_OT:
250 T_rows = []
251 for i in range(npart1):
252 list_Ti = []
253 for j in range(npart2):
254 if T_global[i, j] == 0.0:
255 T_local = nx.zeros(
256 (list_R1[i].shape[0], list_R2[j].shape[0]), type_as=T_global
257 )
258 else:
259 T_local = T_global[i, j] * Ts_local[(i, j)]
260 list_Ti.append(T_local)
261
262 Ti = nx.concatenate(list_Ti, axis=1)
263 T_rows.append(Ti)
264 T = nx.concatenate(T_rows, axis=0)
265
266 else:
267 T = None
268
269 if log:
270 return T_global, Ts_local, T, log_
271
272 else:
273 return T_global, Ts_local, T
274
275
276 def get_graph_partition(
277 C, npart, part_method="random", F=None, alpha=1.0, random_state=0, nx=None
278 ):
279 r"""
280 Partitioning a given graph with structure matrix :math:`\mathbf{C} \in R^{n \times n}`
281 into `npart` partitions either 'random', or using one of {'louvain', 'fluid'}
282 algorithms from networkx, or 'spectral' clustering from scikit-learn,
283 or (Fused) Gromov-Wasserstein projections from POT.
284
285 Parameters
286 ----------
287 C : array-like, shape (n, n)
288 Structure matrix.
289 npart : int,
290 number of partitions/clusters smaller than the number of nodes in
291 :math:`\mathbf{C}`.
292 part_method : str, optional. Default is 'random'.
293 Partitioning algorithm to use among {'random', 'louvain', 'fluid', 'spectral', 'GW', 'FGW'}.
294 'random' for random sampling of points; 'louvain' and 'fluid' for graph
295 partitioning algorithm that works well on adjacency matrix, If the
296 louvain algorithm is used, `npart` is ignored; 'spectral' for spectral
297 clustering; '(F)GW' for (F)GW projection using sr(F)GW solvers.
298 F : array-like, shape (n, d), optional. (Default is None)
299 Optional feature matrix aligned with the graph structure. Only used if
300 `part_method="FGW"`.
301 alpha : float, optional. (Default is 1.)
302 Trade-off parameter between feature and structure matrices, taking
303 values in [0, 1] and only used if `F != None` and `part_method="FGW"`.
304 random_state: int, optional
305 Random seed for the partitioning algorithm.
306 nx : backend, optional
307 POT backend.
308
309 Returns
310 -------
311 part : array-like, shape (npart,)
312 Array of partition assignment for each node.
313
314 References
315 ----------
316 .. [68] Chowdhury, S., Miller, D., & Needham, T. (2021).
317 Quantized gromov-wasserstein. ECML PKDD 2021. Springer International Publishing.
318
319 """
320 if nx is None:
321 nx = get_backend(C)
322
323 n = C.shape[0]
324 C0 = C
325
326 if (alpha != 1.0) and (F is None):
327 raise ValueError("`alpha != 1` but node features are not provided.")
328
329 if npart >= n:
330 warnings.warn(
331 "Requested number of partitions higher than the number of nodes"
332 "hence we enforce each node to be a partition.",
333 stacklevel=2,
334 )
335
336 part = np.arange(n)
337
338 elif npart == 1:
339 part = np.zeros(n)
340
341 elif part_method == "random":
342 # randomly partition the space
343 random.seed(random_state)
344 part = list_to_array(random.choices(np.arange(npart), k=C.shape[0]))
345
346 elif part_method == "louvain":
347 C = nx.to_numpy(C0)
348 graph = from_numpy_array(C)
349 part_sets = louvain_communities(graph, seed=random_state)
350 part = np.zeros(n)
351 for iset_, set_ in enumerate(part_sets):
352 set_ = list(set_)
353 part[set_] = iset_
354
355 elif part_method == "fluid":
356 C = nx.to_numpy(C0)
357 graph = from_numpy_array(C)
358 part_sets = asyn_fluidc(graph, npart, seed=random_state)
359 part = np.zeros(n)
360 for iset_, set_ in enumerate(part_sets):
361 set_ = list(set_)
362 part[set_] = iset_
363
364 elif part_method == "spectral":
365 C = nx.to_numpy(C0)
366 sc = SpectralClustering(
367 n_clusters=npart, random_state=random_state, affinity="precomputed"
368 ).fit(C)
369 part = sc.labels_
370
371 elif part_method in ["GW", "FGW"]:
372 raise ValueError(f"`part_method == {part_method}` not implemented yet.")
373
374 else:
375 raise ValueError(
376 f"""
377 Unknown `part_method='{part_method}'`. Use one of:
378 {'random', 'louvain', 'fluid', 'spectral', 'GW', 'FGW'}.
379 """
380 )
381 return nx.from_numpy(part, type_as=C0)
382
383
384 def get_graph_representants(C, part, rep_method="pagerank", random_state=0, nx=None):
385 r"""
386 Get representative node for each partition given by :math:`\mathbf{part} \in R^{n}`
387 of a graph with structure matrix :math:`\mathbf{C} \in R^{n \times n}`.
388 Selection is either done randomly or using 'pagerank' algorithm from networkx.
389
390 Parameters
391 ----------
392 C : array-like, shape (n, n)
393 structure matrix.
394 part : array-like, shape (n,)
395 Array of partition assignment for each node.
396 rep_method : str, optional. Default is 'pagerank'.
397 Selection method for representant in each partition. Can be either 'random'
398 i.e random sampling within each partition, or 'pagerank' to select a
399 node with maximal pagerank.
400 random_state: int, optional
401 Random seed for the partitioning algorithm
402 nx : backend, optional
403 POT backend
404
405 Returns
406 -------
407 rep_indices : list, shape (npart,)
408 indices for representative node of each partition sorted
409 according to partition identifiers.
410
411 References
412 ----------
413 .. [68] Chowdhury, S., Miller, D., & Needham, T. (2021).
414 Quantized gromov-wasserstein. ECML PKDD 2021. Springer International Publishing.
415
416 """
417 if nx is None:
418 nx = get_backend(C, part)
419
420 rep_indices = []
421 part_ids = nx.unique(part)
422 n_part_ids = part_ids.shape[0]
423 if n_part_ids == C.shape[0]:
424 rep_indices = nx.arange(n_part_ids)
425
426 elif rep_method == "random":
427 random.seed(random_state)
428 for id_, part_id in enumerate(part_ids):
429 indices = nx.where(part == part_id)[0]
430 rep_indices.append(random.choice(indices))
431
432 elif rep_method == "pagerank":
433 C0, part0 = C, part
434 C = nx.to_numpy(C0)
435 part = nx.to_numpy(part0)
436 part_ids = np.unique(part)
437
438 for id_ in part_ids:
439 indices = np.where(part == id_)[0]
440 C_id = C[indices, :][:, indices]
441 graph = from_numpy_array(C_id)
442 pagerank_values = list(pagerank(graph).values())
443 rep_idx = np.argmax(pagerank_values)
444 rep_indices.append(indices[rep_idx])
445
446 else:
447 raise ValueError(
448 f"""
449 Unknown `rep_method='{rep_method}'`. Use one of:
450 {'random', 'pagerank'}.
451 """
452 )
453
454 return rep_indices
455
456
457 def format_partitioned_graph(
458 C, p, part, rep_indices, F=None, M=None, alpha=1.0, nx=None
459 ):
460 r"""
461 Format an attributed graph :math:`(\mathbf{C}, \mathbf{F}, \mathbf{p})`
462 with structure matrix :math:`(\mathbf{C} \in R^{n \times n}`, feature matrix
463 :math:`(\mathbf{F} \in R^{n \times d}` and node relative importance
464 :math:`(\mathbf{p} \in \Sigma_n`, into a partitioned attributed graph
465 taking into account partitions and representants :math:`\mathcal{P} = \left{(\mathbf{P_{i}}, \mathbf{r_{i}})\right}_i`.
466
467 Parameters
468 ----------
469 C : array-like, shape (n, n)
470 Structure matrix.
471 p : array-like, shape (n,),
472 Node distribution.
473 part : array-like, shape (n,)
474 Array of partition assignment for each node.
475 rep_indices : list of array-like of ints, shape (npart,)
476 indices for representative node of each partition sorted according to
477 partition identifiers.
478 F : array-like, shape (n, d), optional. (Default is None)
479 Optional feature matrix aligned with the graph structure.
480 M : array-like, shape (n, n), optional. (Default is None)
481 Optional pairwise similarity matrix between features.
482 alpha: float, optional. Default is 1.
483 Trade-off parameter in :math:`]0, 1]` between structure and features.
484 If `alpha = 1` features are ignored. This trade-off is taken into account
485 into the outputted relations between nodes and representants.
486 nx : backend, optional
487 POT backend
488
489 Returns
490 -------
491 CR : array-like, shape (npart, npart)
492 Structure matrix between partition representants.
493 list_R : list of npart arrays,
494 List of relations between a representant and nodes in its partition,
495 for each partition.
496 list_p : list of npart arrays,
497 List of node distributions within each partition.
498 FR : array-like, shape (npart, d), if `F != None`.
499 Feature matrix of representants.
500
501 References
502 ----------
503 .. [68] Chowdhury, S., Miller, D., & Needham, T. (2021).
504 Quantized gromov-wasserstein. ECML PKDD 2021. Springer International Publishing.
505
506 """
507 if nx is None:
508 arr = [C, p, part]
509 if F is not None:
510 arr.append(F)
511 if M is not None:
512 arr.append(M)
513
514 nx = get_backend(*arr)
515
516 if alpha != 1.0:
517 if (M is None) or (F is None):
518 raise ValueError(
519 f"""
520 `alpha == {alpha} != 1` but features information is not properly provided.
521 """
522 )
523
524 CR = C[rep_indices, :][:, rep_indices]
525
526 if alpha != 1.0:
527 C_new = alpha * C + (1 - alpha) * M
528 else:
529 C_new = C
530
531 list_R, list_p = [], []
532
533 part_ids = nx.unique(part)
534
535 for id_, part_id in enumerate(part_ids):
536 indices = nx.where(part == part_id)[0]
537 list_R.append(C_new[rep_indices[id_], indices])
538 list_p.append(p[indices])
539
540 if F is None:
541 return CR, list_R, list_p
542 else:
543 FR = F[rep_indices, :]
544
545 return CR, list_R, list_p, FR
546
547
548 def quantized_fused_gromov_wasserstein(
549 C1,
550 C2,
551 npart1,
552 npart2,
553 p=None,
554 q=None,
555 C1_aux=None,
556 C2_aux=None,
557 F1=None,
558 F2=None,
559 alpha=1.0,
560 part_method="fluid",
561 rep_method="random",
562 log=False,
563 armijo=False,
564 max_iter=1e4,
565 tol_rel=1e-9,
566 tol_abs=1e-9,
567 random_state=0,
568 **kwargs,
569 ):
570 r"""
571 Returns the quantized Fused Gromov-Wasserstein transport between
572 :math:`(\mathbf{C_1}, \mathbf{F_1}, \mathbf{p})` and :math:`(\mathbf{C_2},
573 \mathbf{F_2}, \mathbf{q})`, whose samples are assigned to partitions and
574 representants :math:`\mathcal{P_1} = \{(\mathbf{P_{1, i}}, \mathbf{r_{1, i}})\}_{i \leq npart1}`
575 and :math:`\mathcal{P_2} = \{(\mathbf{P_{2, j}}, \mathbf{r_{2, j}})\}_{j \leq npart2}`.
576
577 The function estimates the following optimization problem:
578
579 .. math::
580 \mathbf{T}^* \in \mathop{\arg \min}_\mathbf{T} \quad \alpha \sum_{i,j,k,l}
581 L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) \mathbf{T}_{i,j} \mathbf{T}_{k,l}
582 + (1-\alpha) \langle \mathbf{T}, \mathbf{D}(\mathbf{F_1}, \mathbf{F}_2) \rangle_F
583 s.t. \ \mathbf{T} \mathbf{1} &= \mathbf{p}
584
585 \mathbf{T}^T \mathbf{1} &= \mathbf{q}
586
587 \mathbf{T} &\geq 0
588
589 \mathbf{T}_{|\mathbf{P_{1, i}}, \mathbf{P_{2, j}}} &= T^{g}_{ij} \mathbf{T}^{(i,j)}
590
591 using a two-step strategy computing: i) a global alignment :math:`\mathbf{T}^{g}`
592 between representants across joint structure and feature spaces;
593 ii) local alignments :math:`\mathbf{T}^{(i, j)}` between partitions
594 :math:`\mathbf{P_{1, i}}` and :math:`\mathbf{P_{2, j}}` seen as 1D measures.
595
596 Where :
597
598 - :math:`\mathbf{C_1}`: Metric cost matrix in the source space
599 - :math:`\mathbf{C_2}`: Metric cost matrix in the target space
600 - :math:`\mathbf{F_1}`: Feature matrix in the source space
601 - :math:`\mathbf{F_2}`: Feature matrix in the target space
602 - :math:`\mathbf{D}(\mathbf{F_1}, \mathbf{F_2})`: Pairwise euclidean distance matrix between features
603 - :math:`\mathbf{p}`: distribution in the source space
604 - :math:`\mathbf{q}`: distribution in the target space
605 - :math:`L`: quadratic loss function to account for the misfit between the similarity matrices
606
607 .. note:: This function is backend-compatible and will work on arrays
608 from all compatible backends. But the algorithm uses the C++ CPU backend
609 which can lead to copy overhead on GPU arrays.
610 .. note:: All computations in the conjugate gradient solver are done with
611 numpy to limit memory overhead.
612
613 Parameters
614 ----------
615 C1 : array-like, shape (ns, ns)
616 Structure matrix in the source space.
617 C2 : array-like, shape (nt, nt)
618 Structure matrix in the target space.
619 npart1 : int,
620 number of partition in the source space.
621 npart2 : int,
622 number of partition in the target space.
623 p : array-like, shape (ns,), optional
624 Distribution in the source space.
625 If let to its default value None, uniform distribution is taken.
626 q : array-like, shape (nt,), optional
627 Distribution in the target space.
628 If let to its default value None, uniform distribution is taken.
629 C1_aux : array-like, shape (ns, ns), optional. Default is None.
630 Auxiliary structure matrix in the source space to perform the partitioning
631 and representant selection.
632 C2_aux : array-like, shape (nt, nt), optional. Default is None.
633 Auxiliary structure matrix in the target space to perform the partitioning
634 and representant selection.
635 F1 : array-like, shape (ns, d), optional. Default is None.
636 Feature matrix in the source space.
637 F2 : array-like, shape (nt, d), optional. Default is None.
638 Feature matrix in the target space
639 alpha: float, optional. Default is 1.
640 FGW trade-off parameter in :math:`]0, 1]` between structure and features.
641 If `alpha = 1` features are ignored hence computing qGW, if `alpha=0`
642 structures are ignored and we compute the quantized Wasserstein transport.
643 part_method : str, optional. Default is 'spectral'.
644 Partitioning algorithm to use among {'random', 'louvain', 'fluid',
645 'spectral', 'louvain_fused', 'fluid_fused', 'spectral_fused', 'GW', 'FGW'}.
646 If part_method in {'louvain_fused', 'fluid_fused', 'spectral_fused'},
647 corresponding graph partitioning algorithm {'louvain', 'fluid', 'spectral'}
648 will be used on the modified structure matrix
649 :math:`\alpha \mathbf{C} + (1 - \alpha) \mathbf{D}(\mathbf{F})` where
650 :math:`\mathbf{D}(\mathbf{F})` is the pairwise euclidean matrix between features.
651 If part_method in {'GW', 'FGW'}, a (F)GW projection is used.
652 If the louvain algorithm is used, the requested number of partitions is
653 ignored.
654 rep_method : str, optional. Default is 'pagerank'.
655 Selection method for node representant in each partition.
656 Can be either 'random' i.e random sampling within each partition,
657 {'pagerank', 'pagerank_fused'} to select a node with maximal pagerank w.r.t
658 :math:`\mathbf{C}` or :math:`\alpha \mathbf{C} + (1 - \alpha) \mathbf{D}(\mathbf{F})`.
659 verbose : bool, optional
660 Print information along iterations
661 log : bool, optional
662 record log if True
663 armijo : bool, optional
664 If True the step of the line-search is found via an armijo research. Else closed form is used.
665 If there are convergence issues use False.
666 max_iter : int, optional
667 Max number of iterations
668 tol_rel : float, optional
669 Stop threshold on relative error (>0)
670 tol_abs : float, optional
671 Stop threshold on absolute error (>0)
672 random_state: int, optional
673 Random seed for the partitioning algorithm
674 **kwargs : dict
675 parameters can be directly passed to the ot.optim.cg solver
676
677 Returns
678 -------
679 T_global: array-like, shape (`npart1`, `npart2`)
680 Fused Gromov-Wasserstein alignment :math:`\mathbf{T}^{g}` between representants.
681 Ts_local: dict of local OT matrices.
682 Dictionary with keys :math:`(i, j)` corresponding to 1D OT between
683 :math:`\mathbf{P_{1, i}}` and :math:`\mathbf{P_{2, j}}` if :math:`T^{g}_{ij} \neq 0`.
684 T: array-like, shape `(ns, nt)`
685 Coupling between the two spaces.
686 log : dict
687 Convergence information for inner problems and qGW loss.
688
689 References
690 ----------
691 .. [68] Chowdhury, S., Miller, D., & Needham, T. (2021).
692 Quantized gromov-wasserstein. ECML PKDD 2021. Springer International Publishing.
693
694 """
695 if part_method in ["fluid", "louvain", "fluid_fused", "louvain_fused"] or (
696 rep_method in ["pagerank", "pagerank_fused"]
697 ):
698 if not networkx_import:
699 warnings.warn(
700 f"""
701 Networkx is not installed, so part_method={part_method} and/or
702 rep_method={rep_method} cannot be used and are set to `random`
703 default methods. Consider installing Networkx to fix this.
704 """
705 )
706 part_method = "random"
707 rep_method = "random"
708
709 if (part_method in ["spectral", "spectral_fused"]) and (not sklearn_import):
710 warnings.warn(
711 f"""
712 Scikit-learn is not installed, so part_method={part_method} and/or
713 rep_method={rep_method} cannot be used and are set to `random`
714 default methods. Consider installing Scikit-learn to fix this.
715 """
716 )
717 part_method = "random"
718 rep_method = "random"
719
720 if ("fused" in part_method) or ("fused" in rep_method) or (part_method == "FGW"):
721 if (F1 is None) or (F2 is None):
722 raise ValueError(
723 f"""
724 `part_method='{part_method}'` and/or `rep_method='{rep_method}'`
725 require feature matrices which are not provided as inputs.
726 """
727 )
728
729 arr = [C1, C2]
730 if C1_aux is not None:
731 arr.append(C1_aux)
732 else:
733 C1_aux = C1
734 if C2_aux is not None:
735 arr.append(C2_aux)
736 else:
737 C2_aux = C2
738 if p is not None:
739 arr.append(list_to_array(p))
740 else:
741 p = unif(C1.shape[0], type_as=C1)
742 if q is not None:
743 arr.append(list_to_array(q))
744 else:
745 q = unif(C2.shape[0], type_as=C1)
746 if F1 is not None:
747 arr.append(F1)
748 if F2 is not None:
749 arr.append(F1)
750
751 nx = get_backend(*arr)
752
753 DF1 = None
754 DF2 = None
755 # compute attributed graph partitions potentially using the auxiliary structure
756 if "fused" in part_method:
757 DF1 = dist(F1, F1)
758 DF2 = dist(F2, F2)
759 C1_new = alpha * C1_aux + (1 - alpha) * DF1
760 C2_new = alpha * C2_aux + (1 - alpha) * DF2
761
762 part_method_ = part_method[:-6]
763 part1 = get_graph_partition(
764 C1_new, npart1, part_method_, random_state=random_state, nx=nx
765 )
766 part2 = get_graph_partition(
767 C2_new, npart2, part_method_, random_state=random_state, nx=nx
768 )
769
770 else:
771 part1 = get_graph_partition(
772 C1_aux, npart1, part_method, F1, alpha, random_state, nx
773 )
774 part2 = get_graph_partition(
775 C2_aux, npart2, part_method, F2, alpha, random_state, nx
776 )
777
778 if "fused" in rep_method:
779 if DF1 is None:
780 DF1 = dist(F1, F1)
781 DF2 = dist(F2, F2)
782 C1_new = alpha * C1_aux + (1 - alpha) * DF1
783 C2_new = alpha * C2_aux + (1 - alpha) * DF2
784
785 rep_method_ = rep_method[:-6]
786
787 rep_indices1 = get_graph_representants(
788 C1_new, part1, rep_method_, random_state, nx
789 )
790 rep_indices2 = get_graph_representants(
791 C2_new, part2, rep_method_, random_state, nx
792 )
793
794 else:
795 rep_indices1 = get_graph_representants(
796 C1_aux, part1, rep_method, random_state, nx
797 )
798 rep_indices2 = get_graph_representants(
799 C2_aux, part2, rep_method, random_state, nx
800 )
801
802 # format partitions over (C1, F1) and (C2, F2)
803 if (F1 is None) and (F2 is None):
804 CR1, list_R1, list_p1 = format_partitioned_graph(
805 C1, p, part1, rep_indices1, nx=nx
806 )
807 CR2, list_R2, list_p2 = format_partitioned_graph(
808 C2, q, part2, rep_indices2, nx=nx
809 )
810
811 MR = None
812 else:
813 if DF1 is None:
814 DF1 = dist(F1, F1)
815 DF2 = dist(F2, F2)
816
817 CR1, list_R1, list_p1, FR1 = format_partitioned_graph(
818 C1, p, part1, rep_indices1, F1, DF1, alpha, nx
819 )
820 CR2, list_R2, list_p2, FR2 = format_partitioned_graph(
821 C2, q, part2, rep_indices2, F2, DF2, alpha, nx
822 )
823
824 MR = dist(FR1, FR2)
825 # call to partitioned quantized fused gromov-wasserstein solver
826
827 res = quantized_fused_gromov_wasserstein_partitioned(
828 CR1,
829 CR2,
830 list_R1,
831 list_R2,
832 list_p1,
833 list_p2,
834 MR,
835 alpha,
836 build_OT=True,
837 log=log,
838 armijo=armijo,
839 max_iter=max_iter,
840 tol_rel=tol_rel,
841 tol_abs=tol_abs,
842 nx=nx,
843 **kwargs,
844 )
845
846 if log:
847 T_global, Ts_local, T, log_ = res
848
849 # compute the transport cost on structures
850 constC, hC1, hC2 = init_matrix(C1, C2, p, q, "square_loss", nx)
851 structure_cost = gwloss(constC, hC1, hC2, T, nx)
852
853 if alpha != 1.0:
854 M = dist(F1, F2)
855 feature_cost = nx.sum(M * T)
856 else:
857 feature_cost = 0.0
858
859 log_["qFGW_dist"] = alpha * structure_cost + (1 - alpha) * feature_cost
860 return T_global, Ts_local, T, log_
861
862 else:
863 T_global, Ts_local, T = res
864
865 return T_global, Ts_local, T
866
867
868 def get_partition_and_representants_samples(
869 X, npart, method="kmeans", random_state=0, nx=None
870 ):
871 r"""
872 Compute `npart` partitions and representants over samples :math:`\mathbf{X} \in R^{n \times d}`
873 using either a random or a kmeans algorithm.
874
875 Parameters
876 ----------
877 X : array-like, shape (n, d)
878 Samples endowed with an euclidean geometry.
879 npart : int,
880 number of partitions smaller than the number of samples in
881 :math:`\mathbf{X}`.
882 method : str, optional. Default is 'kmeans'.
883 Partitioning and representant selection algorithms to use among
884 {'random', 'kmeans'}. 'random' for random sampling of points; 'kmeans'
885 for k-means clustering using scikit-learn implementation where closest
886 points to centroids are considered as representants.
887 random_state: int, optional
888 Random seed for the partitioning algorithm.
889 nx : backend, optional
890 POT backend.
891
892 Returns
893 -------
894 part : array-like, shape (npart,)
895 Array of partition assignment for each node.
896
897 rep_indices : list, shape (npart,)
898 indices for representative node of each partition sorted
899 according to partition identifiers.
900
901 References
902 ----------
903 .. [68] Chowdhury, S., Miller, D., & Needham, T. (2021).
904 Quantized gromov-wasserstein. ECML PKDD 2021. Springer International Publishing.
905
906 """
907 if nx is None:
908 nx = get_backend(X)
909
910 n = X.shape[0]
911 X0 = X
912
913 if npart >= n:
914 warnings.warn(
915 "Requested number of partitions higher than the number of nodes"
916 "hence we enforce each node to be a partition.",
917 stacklevel=2,
918 )
919
920 part = nx.arange(n)
921 rep_indices = nx.arange(n)
922
923 elif npart == 1:
924 random.seed(random_state)
925 part = nx.zeros(n)
926 rep_indices = [random.choice(nx.arange(n))]
927
928 elif method == "random":
929 # randomly partition the space
930 random.seed(random_state)
931 part = list_to_array(random.choices(np.arange(npart), k=X.shape[0]))
932 part = nx.from_numpy(part, type_as=X0)
933
934 # randomly select representant in each partition
935 rep_indices = []
936 part_ids = nx.unique(part)
937 for id_, part_id in enumerate(part_ids):
938 indices = nx.where(part == part_id)[0]
939 rep_indices.append(random.choice(indices))
940
941 elif method == "kmeans":
942 X = nx.to_numpy(X0)
943 km = KMeans(n_clusters=npart, random_state=random_state).fit(X)
944 part = nx.from_numpy(km.labels_, type_as=X0)
945
946 rep_indices = []
947 for part_id in range(npart):
948 indices = nx.where(part == part_id)[0]
949 dists = dist(X[indices], km.cluster_centers_[part_id][None, :])
950 best_idx = indices[dists.argmin()]
951 rep_indices.append(best_idx)
952
953 else:
954 raise ValueError(
955 f"""
956 Unknown `method='{method}'`. Use one of: {'random', 'kmeans'}
957 """
958 )
959
960 return part, rep_indices
961
962
963 def format_partitioned_samples(X, p, part, rep_indices, F=None, alpha=1.0, nx=None):
964 r"""
965 Format an attributed graph :math:`(\mathbf{D}(\mathbf{X}), \mathbf{F}, \mathbf{p})`
966 with euclidean structure matrix :math:`(\mathbf{D}(\mathbf{X}) \in R^{n \times n}`,
967 feature matrix :math:`(\mathbf{F} \in R^{n \times d}` and node relative importance
968 :math:`(\mathbf{p} \in \Sigma_n`, into a partitioned attributed graph
969 taking into account partitions and representants :math:`\mathcal{P} = \left{(\mathbf{P_{i}}, \mathbf{r_{i}})\right}_i`.
970
971 Parameters
972 ----------
973 X : array-like, shape (n, d)
974 Structure matrix.
975 p : array-like, shape (n,),
976 Node distribution.
977 part : array-like, shape (n,)
978 Array of partition assignment for each node.
979 rep_indices : list of array-like of ints, shape (npart,)
980 indices for representative node of each partition sorted according to
981 partition identifiers.
982 F : array-like, shape (n, p), optional. (Default is None)
983 Optional feature matrix aligned with the samples.
984 alpha: float, optional. Default is 1.
985 Trade-off parameter in :math:`]0, 1]` between structure and features.
986 If `alpha = 1` features are ignored. This trade-off is taken into account
987 into the outputted relations between nodes and representants.
988 nx : backend, optional
989 POT backend
990
991 Returns
992 -------
993 CR : array-like, shape (npart, npart)
994 Structure matrix between partition representants.
995 list_R : list of npart arrays,
996 List of relations between a representant and nodes in its partition,
997 for each partition.
998 list_p : list of npart arrays,
999 List of node distributions within each partition.
1000 FR : array-like, shape (npart, d), if `F != None`.
1001 Feature matrix of representants.
1002
1003 References
1004 ----------
1005 .. [68] Chowdhury, S., Miller, D., & Needham, T. (2021).
1006 Quantized gromov-wasserstein. ECML PKDD 2021. Springer International Publishing.
1007
1008 """
1009 if nx is None:
1010 arr = [X, p, part]
1011 if F is not None:
1012 arr.append(F)
1013
1014 nx = get_backend(*arr)
1015
1016 if alpha != 1.0:
1017 if F is None:
1018 raise ValueError(
1019 f"""
1020 `alpha == {alpha} != 1` but features information is not properly provided.
1021 """
1022 )
1023
1024 XR = X[rep_indices, :]
1025 CR = dist(XR, XR)
1026
1027 list_R, list_p = [], []
1028
1029 part_ids = nx.unique(part)
1030
1031 for id_, part_id in enumerate(part_ids):
1032 indices = nx.where(part == part_id)[0]
1033 structure_R = dist(X[indices], X[rep_indices[id_]][None, :])
1034
1035 if alpha != 1:
1036 features_R = dist(F[indices], F[rep_indices[id_]][None, :])
1037 else:
1038 features_R = 0.0
1039
1040 list_R.append(alpha * structure_R + (1 - alpha) * features_R)
1041 list_p.append(p[indices])
1042
1043 if F is None:
1044 return CR, list_R, list_p
1045 else:
1046 FR = F[rep_indices, :]
1047
1048 return CR, list_R, list_p, FR
1049
1050
1051 def quantized_fused_gromov_wasserstein_samples(
1052 X1,
1053 X2,
1054 npart1,
1055 npart2,
1056 p=None,
1057 q=None,
1058 F1=None,
1059 F2=None,
1060 alpha=1.0,
1061 method="kmeans",
1062 log=False,
1063 armijo=False,
1064 max_iter=1e4,
1065 tol_rel=1e-9,
1066 tol_abs=1e-9,
1067 random_state=0,
1068 **kwargs,
1069 ):
1070 r"""
1071 Returns the quantized Fused Gromov-Wasserstein transport between samples
1072 endowed with their respective euclidean geometry :math:`(\mathbf{D}(\mathbf{X_1}), \mathbf{F_1}, \mathbf{p})`
1073 and :math:`(\mathbf{D}(\mathbf{X_1}), \mathbf{F_2}, \mathbf{q})`, whose samples are assigned to partitions and
1074 representants :math:`\mathcal{P_1} = \{(\mathbf{P_{1, i}}, \mathbf{r_{1, i}})\}_{i \leq npart1}`
1075 and :math:`\mathcal{P_2} = \{(\mathbf{P_{2, j}}, \mathbf{r_{2, j}})\}_{j \leq npart2}`.
1076
1077 The function estimates the following optimization problem:
1078
1079 .. math::
1080 \mathbf{T}^* \in \mathop{\arg \min}_\mathbf{T} \quad \alpha \sum_{i,j,k,l}
1081 L(\mathbf{D}(\mathbf{X_1})_{i,k}, \mathbf{D}(\mathbf{X_2})_{j,l}) \mathbf{T}_{i,j} \mathbf{T}_{k,l}
1082 + (1-\alpha) \langle \mathbf{T}, \mathbf{D}(\mathbf{F_1}, \mathbf{F}_2) \rangle_F
1083 s.t. \ \mathbf{T} \mathbf{1} &= \mathbf{p}
1084
1085 \mathbf{T}^T \mathbf{1} &= \mathbf{q}
1086
1087 \mathbf{T} &\geq 0
1088
1089 \mathbf{T}_{|\mathbf{P_{1, i}}, \mathbf{P_{2, j}}} &= T^{g}_{ij} \mathbf{T}^{(i,j)}
1090
1091 using a two-step strategy computing: i) a global alignment :math:`\mathbf{T}^{g}`
1092 between representants across joint structure and feature spaces;
1093 ii) local alignments :math:`\mathbf{T}^{(i, j)}` between partitions
1094 :math:`\mathbf{P_{1, i}}` and :math:`\mathbf{P_{2, j}}` seen as 1D measures.
1095
1096 Where :
1097
1098 - :math:`\mathbf{X_1}`: Samples in the source space
1099 - :math:`\mathbf{X_2}`: Samples in the target space
1100 - :math:`\mathbf{F_1}`: Feature matrix in the source space
1101 - :math:`\mathbf{F_2}`: Feature matrix in the target space
1102 - :math:`\mathbf{D}(\mathbf{F_1}, \mathbf{F_2})`: Pairwise euclidean distance matrix between features
1103 - :math:`\mathbf{p}`: distribution in the source space
1104 - :math:`\mathbf{q}`: distribution in the target space
1105 - :math:`L`: quadratic loss function to account for the misfit between the similarity matrices
1106
1107 .. note:: This function is backend-compatible and will work on arrays
1108 from all compatible backends. But the algorithm uses the C++ CPU backend
1109 which can lead to copy overhead on GPU arrays.
1110 .. note:: All computations in the conjugate gradient solver are done with
1111 numpy to limit memory overhead.
1112
1113 Parameters
1114 ----------
1115 X1 : array-like, shape (ns, ds)
1116 Samples in the source space.
1117 X2 : array-like, shape (nt, dt)
1118 Samples in the target space.
1119 npart1 : int,
1120 number of partition in the source space.
1121 npart2 : int,
1122 number of partition in the target space.
1123 p : array-like, shape (ns,), optional
1124 Distribution in the source space.
1125 If let to its default value None, uniform distribution is taken.
1126 q : array-like, shape (nt,), optional
1127 Distribution in the target space.
1128 If let to its default value None, uniform distribution is taken.
1129 F1 : array-like, shape (ns, d), optional. Default is None.
1130 Feature matrix in the source space.
1131 F2 : array-like, shape (nt, d), optional. Default is None.
1132 Feature matrix in the target space
1133 alpha: float, optional. Default is 1.
1134 FGW trade-off parameter in :math:`]0, 1]` between structure and features.
1135 If `alpha = 1` features are ignored hence computing qGW, if `alpha=0`
1136 structures are ignored and we compute the quantized Wasserstein transport.
1137 method : str, optional. Default is 'kmeans'.
1138 Partitioning and representant selection algorithms to use among
1139 {'random', 'kmeans', 'kmeans_fused'}.
1140 If `part_method == 'kmeans_fused'`, kmeans is performed on augmented
1141 samples :math:`[\alpha \mathbf{X}; (1 - \alpha) \mathbf{F}]`.
1142 verbose : bool, optional
1143 Print information along iterations
1144 log : bool, optional
1145 record log if True
1146 armijo : bool, optional
1147 If True the step of the line-search is found via an armijo research. Else closed form is used.
1148 If there are convergence issues use False.
1149 max_iter : int, optional
1150 Max number of iterations
1151 tol_rel : float, optional
1152 Stop threshold on relative error (>0)
1153 tol_abs : float, optional
1154 Stop threshold on absolute error (>0)
1155 random_state: int, optional
1156 Random seed for the partitioning algorithm
1157 **kwargs : dict
1158 parameters can be directly passed to the ot.optim.cg solver
1159
1160 Returns
1161 -------
1162 T_global: array-like, shape (`npart1`, `npart2`)
1163 Fused Gromov-Wasserstein alignment :math:`\mathbf{T}^{g}` between representants.
1164 Ts_local: dict of local OT matrices.
1165 Dictionary with keys :math:`(i, j)` corresponding to 1D OT between
1166 :math:`\mathbf{P_{1, i}}` and :math:`\mathbf{P_{2, j}}` if :math:`T^{g}_{ij} \neq 0`.
1167 T: array-like, shape `(ns, nt)`
1168 Coupling between the two spaces.
1169 log : dict
1170 Convergence information for inner problems and qGW loss.
1171
1172 References
1173 ----------
1174 .. [68] Chowdhury, S., Miller, D., & Needham, T. (2021).
1175 Quantized gromov-wasserstein. ECML PKDD 2021. Springer International Publishing.
1176
1177 """
1178
1179 if (method in ["kmeans", "kmeans_fused"]) and (not sklearn_import):
1180 warnings.warn(
1181 f"""
1182 Scikit-learn is not installed, so method={method} cannot be used
1183 and is set to `random` default methods. Consider installing
1184 Scikit-learn to fix this.
1185 """
1186 )
1187 method = "random"
1188
1189 if ("fused" in method) and ((F1 is None) or (F2 is None)):
1190 raise ValueError(
1191 f"""
1192 `method='{method}'` requires feature matrices which are not provided as inputs.
1193 """
1194 )
1195
1196 arr = [X1, X2]
1197 if p is not None:
1198 arr.append(list_to_array(p))
1199 else:
1200 p = unif(X1.shape[0], type_as=X1)
1201 if q is not None:
1202 arr.append(list_to_array(q))
1203 else:
1204 q = unif(X2.shape[0], type_as=X1)
1205 if F1 is not None:
1206 arr.append(F1)
1207 if F2 is not None:
1208 arr.append(F1)
1209
1210 nx = get_backend(*arr)
1211
1212 # compute attributed partitions and representants
1213 if ("fused" in method) and (alpha != 1.0):
1214 X1_new = nx.concatenate([alpha * X1, (1 - alpha) * F1], axis=1)
1215 X2_new = nx.concatenate([alpha * X2, (1 - alpha) * F2], axis=1)
1216 method_ = method[:-6]
1217 else:
1218 X1_new, X2_new = X1, X2
1219 method_ = method
1220 part1, rep_indices1 = get_partition_and_representants_samples(
1221 X1_new, npart1, method_, random_state, nx
1222 )
1223 part2, rep_indices2 = get_partition_and_representants_samples(
1224 X2_new, npart2, method_, random_state, nx
1225 )
1226 # format partitions over (C1, F1) and (C2, F2)
1227
1228 if (F1 is None) and (F2 is None):
1229 CR1, list_R1, list_p1 = format_partitioned_samples(
1230 X1, p, part1, rep_indices1, nx=nx
1231 )
1232 CR2, list_R2, list_p2 = format_partitioned_samples(
1233 X2, q, part2, rep_indices2, nx=nx
1234 )
1235
1236 MR = None
1237 else:
1238 CR1, list_R1, list_p1, FR1 = format_partitioned_samples(
1239 X1, p, part1, rep_indices1, F1, alpha, nx
1240 )
1241 CR2, list_R2, list_p2, FR2 = format_partitioned_samples(
1242 X2, q, part2, rep_indices2, F2, alpha, nx
1243 )
1244
1245 MR = dist(FR1, FR2)
1246
1247 # call to partitioned quantized fused gromov-wasserstein solver
1248
1249 res = quantized_fused_gromov_wasserstein_partitioned(
1250 CR1,
1251 CR2,
1252 list_R1,
1253 list_R2,
1254 list_p1,
1255 list_p2,
1256 MR,
1257 alpha,
1258 build_OT=True,
1259 log=log,
1260 armijo=armijo,
1261 max_iter=max_iter,
1262 tol_rel=tol_rel,
1263 tol_abs=tol_abs,
1264 nx=nx,
1265 **kwargs,
1266 )
1267
1268 if log:
1269 T_global, Ts_local, T, log_ = res
1270
1271 C1 = dist(X1, X1)
1272 C2 = dist(X2, X2)
1273
1274 # compute the transport cost on structures
1275 constC, hC1, hC2 = init_matrix(C1, C2, p, q, "square_loss", nx)
1276 structure_cost = gwloss(constC, hC1, hC2, T, nx)
1277
1278 if alpha != 1.0:
1279 M = dist(F1, F2)
1280 feature_cost = nx.sum(M * T)
1281 else:
1282 feature_cost = 0.0
1283
1284 log_["qFGW_dist"] = alpha * structure_cost + (1 - alpha) * feature_cost
1285 return T_global, Ts_local, T, log_
1286
1287 else:
1288 T_global, Ts_local, T = res
1289
1290 return T_global, Ts_local, T