comflow 0.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,850 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+ from scipy import sparse
4
+ from sys import getsizeof
5
+ import random
6
+ from collections import defaultdict
7
+ from scipy.sparse import issparse
8
+ from scipy.sparse import csr_matrix
9
+
10
+ from ._unot import unot
11
+
12
+ def cot_dense(S, D, A, M, cutoff, eps_p=1e-1, eps_mu=None, eps_nu=None, rho=1e1, nitermax=1e4, stopthr=1e-8):
13
+ """ Solve the collective optimal transport problem with distance limits.
14
+
15
+ Parameters
16
+ ----------
17
+ S : (n_pos_s,ns_s) numpy.ndarray
18
+ Source distributions over `n_pos_s` positions of `ns_s` source species.
19
+ D : (n_pos_d,ns_d) numpy.ndarray
20
+ Destination distributions over `n_pos_d` positions of `ns_d` destination species.
21
+ A : (ns_s,ns_d) numpy.ndarray
22
+ The cost coefficients for source-destination species pairs. An infinity value indicates that the two species cannot be coupled.
23
+ M : (n_pos_s,n_pos_d) numpy.ndarray
24
+ The distance (cost) matrix among the positions.
25
+ cutoff : (ns_s,ns_d) numpy.ndarray
26
+ The distance (cost) cutoff between each source-destination species pair. All transports are restricted by the cutoffs.
27
+ eps_p : float, defaults to 1e-1
28
+ The coefficient for entropy regularization of P.
29
+ eps_mu : float, defaults to eps_p
30
+ The coefficient for entropy regularization of unmatched source mass.
31
+ eps_nu : float, defaults to eps_p
32
+ The coefficient for entriopy regularization of unmatched target mass.
33
+ rho : float, defaults to 1e2
34
+ The coefficient for penalizing unmatched mass.
35
+ nitermax : int, optional
36
+ The maximum number of iterations in the unormalized OT problem. Defaults to 1e4.
37
+ stopthr : float, optional
38
+ The relatitive error threshold for terminating the iteration. Defaults to 1e-8.
39
+
40
+ Returns
41
+ -------
42
+ (ns_s,ns_d,n_pos_s,n_pos_d) numpy.ndarray
43
+ The transport plans among the multiple species.
44
+ """
45
+ np.set_printoptions(precision=2)
46
+ n_pos_s, ns_s = S.shape
47
+ n_pos_d, ns_d = D.shape
48
+ max_amount = max( S.sum(), D.sum() )
49
+ S = S / max_amount
50
+ D = D / max_amount
51
+
52
+ if eps_mu is None: eps_mu = eps_p
53
+ if eps_nu is None: eps_nu = eps_p
54
+ if max(abs(eps_p-eps_mu),abs(eps_p-eps_nu)) > 1e-8:
55
+ unot_solver = "momentum"
56
+ else:
57
+ unot_solver = "sinkhorn"
58
+
59
+ # Set up the large collective OT problem
60
+ a = S.flatten('F')
61
+ b = D.flatten('F')
62
+ C = np.inf * np.ones([len(a),len(b)])
63
+ for i in range(ns_s):
64
+ for j in range(ns_d):
65
+ if not np.isinf(A[i,j]):
66
+ tmp_M = np.array(M)
67
+ tmp_M[np.where(tmp_M > cutoff[i,j])] = np.inf
68
+ C[i*n_pos_s:(i+1)*n_pos_s, j*n_pos_d:(j+1)*n_pos_d] = A[i,j] * tmp_M
69
+ C = C/np.max(C[np.where(~np.isinf(C))])
70
+ nzind_a = np.where(a > 0)[0]
71
+ nzind_b = np.where(b > 0)[0]
72
+ tmp_P = unot(a[nzind_a], b[nzind_b], C[nzind_a,:][:,nzind_b], eps_p, rho, \
73
+ eps_mu=eps_mu, eps_nu=eps_nu, sparse_mtx=False, solver=unot_solver, nitermax=nitermax, stopthr=stopthr)
74
+ P = np.zeros_like(C)
75
+ for i in range(len(nzind_a)):
76
+ for j in range(len(nzind_b)):
77
+ P[nzind_a[i],nzind_b[j]] = tmp_P[i,j]
78
+ P_expand = np.zeros([ns_s, ns_d, n_pos_s, n_pos_d], float)
79
+ for i in range(ns_s):
80
+ for j in range(ns_d):
81
+ P_expand[i,j,:,:] = P[i*n_pos_s:(i+1)*n_pos_s,j*n_pos_d:(j+1)*n_pos_d]
82
+ return P_expand * max_amount
83
+
84
+ def cot_row_dense(S, D, A, M, cutoff, eps_p=1e-1, eps_mu=None, eps_nu=None, rho=1e1, nitermax=1e4, stopthr=1e-8):
85
+ """Solve for each sender species separately.
86
+ """
87
+ if eps_mu is None: eps_mu = eps_p
88
+ if eps_nu is None: eps_nu = eps_p
89
+ if max(abs(eps_p-eps_mu),abs(eps_p-eps_nu)) > 1e-8:
90
+ unot_solver = "momentum"
91
+ else:
92
+ unot_solver = "sinkhorn"
93
+
94
+ n_pos_s, ns_s = S.shape
95
+ n_pos_d, ns_d = D.shape
96
+ P_expand = np.zeros([ns_s, ns_d, n_pos_s, n_pos_d], float)
97
+ for i in range(ns_s):
98
+ a = S[:,i]
99
+ D_ind = np.where(~np.isinf(A[i,:]))[0]
100
+ b = D[:,D_ind].flatten('F')
101
+ max_amount = max(a.sum(), b.sum())
102
+ a = a / max_amount; b = b / max_amount
103
+ C = np.inf * np.ones([len(a), len(b)], float)
104
+ for j in range(len(D_ind)):
105
+ D_j = D_ind[j]
106
+ tmp_M = np.array(M)
107
+ tmp_M[np.where(tmp_M > cutoff[i,D_j])] = np.inf
108
+ C[:,j*n_pos_d:(j+1)*n_pos_d] = A[i,D_j] * tmp_M
109
+ C = C/np.max(C[np.where(~np.isinf(C))])
110
+ nzind_a = np.where(a > 0)[0]
111
+ nzind_b = np.where(b > 0)[0]
112
+ tmp_P = unot(a[nzind_a], b[nzind_b], C[nzind_a,:][:,nzind_b], eps_p, rho, \
113
+ eps_mu=eps_mu, eps_nu=eps_nu, sparse_mtx=False, solver=unot_solver, nitermax=nitermax, stopthr=stopthr)
114
+ P = np.zeros_like(C)
115
+ for ii in range(len(nzind_a)):
116
+ for jj in range(len(nzind_b)):
117
+ P[nzind_a[ii],nzind_b[jj]] = tmp_P[ii,jj]
118
+ for j in range(len(D_ind)):
119
+ P_expand[i,D_ind[j],:,:] = P[:,j*n_pos_d:(j+1)*n_pos_d] * max_amount
120
+ return P_expand
121
+
122
+ def cot_col_dense(S, D, A, M, cutoff, eps_p=1e-1, eps_mu=None, eps_nu=None, rho=1e1, nitermax=1e4, stopthr=1e-8):
123
+ """Solve for each destination species separately.
124
+ """
125
+ if eps_mu is None: eps_mu = eps_p
126
+ if eps_nu is None: eps_nu = eps_p
127
+ if max(abs(eps_p-eps_mu),abs(eps_p-eps_nu)) > 1e-8:
128
+ unot_solver = "momentum"
129
+ else:
130
+ unot_solver = "sinkhorn"
131
+
132
+ n_pos_s, ns_s = S.shape
133
+ n_pos_d, ns_d = D.shape
134
+ P_expand = np.zeros([ns_s, ns_d, n_pos_s, n_pos_d], float)
135
+ for j in range(ns_d):
136
+ b = D[:,j]
137
+ S_ind = np.where(~np.isinf(A[:,j]))[0]
138
+ a = S[:,S_ind].flatten('F')
139
+ max_amount = max(a.sum(), b.sum())
140
+ a = a / max_amount; b = b / max_amount
141
+ C = np.inf * np.ones([len(a), len(b)], float)
142
+ for i in range(len(S_ind)):
143
+ S_i = S_ind[i]
144
+ tmp_M = np.array(M)
145
+ tmp_M[np.where(tmp_M > cutoff[S_i,j])] = np.inf
146
+ C[i*n_pos_s:(i+1)*n_pos_s,:] = A[S_i,j] * tmp_M
147
+ C = C/np.max(C[np.where(~np.isinf(C))])
148
+ nzind_a = np.where(a > 0)[0]
149
+ nzind_b = np.where(b > 0)[0]
150
+ tmp_P = unot(a[nzind_a], b[nzind_b], C[nzind_a,:][:,nzind_b], eps_p, rho, \
151
+ eps_mu=eps_mu, eps_nu=eps_nu, sparse_mtx=False, solver=unot_solver, nitermax=nitermax, stopthr=stopthr)
152
+ P = np.zeros_like(C)
153
+ for ii in range(len(nzind_a)):
154
+ for jj in range(len(nzind_b)):
155
+ P[nzind_a[ii],nzind_b[jj]] = tmp_P[ii,jj]
156
+ for i in range(len(S_ind)):
157
+ P_expand[S_ind[i],j,:,:] = P[i*n_pos_s:(i+1)*n_pos_s,:] * max_amount
158
+ return P_expand
159
+
160
+ def cot_blk_dense(S, D, A, M, cutoff, eps_p=1e-1, eps_mu=None, eps_nu=None, rho=1e1, nitermax=1e4, stopthr=1e-8):
161
+ """Solve for each pair of species separately.
162
+ """
163
+ if eps_mu is None: eps_mu = eps_p
164
+ if eps_nu is None: eps_nu = eps_p
165
+ if max(abs(eps_p-eps_mu),abs(eps_p-eps_nu)) > 1e-8:
166
+ unot_solver = "momentum"
167
+ else:
168
+ unot_solver = "sinkhorn"
169
+
170
+ n_pos_s, ns_s = S.shape
171
+ n_pos_d, ns_d = D.shape
172
+ P_expand = np.zeros([ns_s, ns_d, n_pos_s, n_pos_d], float)
173
+ for i in range(ns_s):
174
+ for j in range(ns_d):
175
+ if np.isinf(A[i,j]): continue
176
+ a = S[:,i]; b = D[:,j]
177
+ max_amount = max(a.sum(), b.sum())
178
+ a = a / max_amount; b = b / max_amount
179
+ C = np.array(M)
180
+ C[np.where(C > cutoff[i,j])] = np.inf
181
+ C = C/np.max(C[np.where(~np.isinf(C))])
182
+ nzind_a = np.where(a > 0)[0]
183
+ nzind_b = np.where(b > 0)[0]
184
+ tmp_P = unot(a[nzind_a], b[nzind_b], C[nzind_a,:][:,nzind_b], eps_p, rho, \
185
+ eps_mu=eps_mu, eps_nu=eps_nu, sparse_mtx=False, solver=unot_solver, nitermax=nitermax, stopthr=stopthr)
186
+ P = np.zeros_like(C)
187
+ for ii in range(len(nzind_a)):
188
+ for jj in range(len(nzind_b)):
189
+ P[nzind_a[ii],nzind_b[jj]] = tmp_P[ii,jj]
190
+ P_expand[i,j,:,:] = P[:,:]
191
+ return P_expand
192
+
193
+ def cot_combine_sparse(S, D, Q, A, M, cutoff, eps_p=1e-1, eps_mu=None, eps_nu=None, rho=1e1, lam=1e1, weights=(0.25,0.25,0.25,0.25), nitermax=1e4, stopthr=1e-8, verbose=False):
194
+ if isinstance(eps_p, tuple):
195
+ eps_p_cot, eps_p_row, eps_p_col, eps_p_blk = eps_p
196
+ else:
197
+ eps_p_cot = eps_p_row = eps_p_col = eps_p_blk = eps_p
198
+ if isinstance(rho, tuple):
199
+ rho_cot, rho_row, rho_col, rho_blk = rho
200
+ else:
201
+ rho_cot = rho_row = rho_col = rho_blk = rho
202
+ if isinstance(lam, tuple):
203
+ lam_cot, lam_row, lam_col, lam_blk = lam
204
+ else:
205
+ lam_cot = lam_row = lam_col = lam_blk = lam
206
+ if eps_mu is None:
207
+ eps_mu_cot = eps_p_cot; eps_mu_row = eps_p_row
208
+ eps_mu_col = eps_p_col; eps_mu_blk = eps_p_blk
209
+ elif isinstance(eps_mu, tuple):
210
+ eps_mu_cot, eps_mu_row, eps_mu_col, eps_mu_blk = eps_mu
211
+ else:
212
+ eps_mu_cot = eps_mu_row = eps_mu_col = eps_mu_blk = eps_mu
213
+ if eps_nu is None:
214
+ eps_nu_cot = eps_p_cot; eps_nu_row = eps_p_row
215
+ eps_nu_col = eps_p_col; eps_nu_blk = eps_p_blk
216
+ elif isinstance(eps_nu, tuple):
217
+ eps_nu_cot, eps_nu_row, eps_nu_col, eps_nu_blk = eps_nu
218
+ else:
219
+ eps_nu_cot = eps_nu_row = eps_nu_col = eps_nu_blk = eps_nu
220
+
221
+ P_cot,CostC = cot_sparse(S, D, Q, A, M, cutoff, \
222
+ eps_p=eps_p_cot, eps_mu=eps_mu_cot, eps_nu=eps_nu_cot, rho=rho_cot, lam=lam_cot, \
223
+ nitermax=nitermax, stopthr=stopthr, verbose=False)
224
+ P_row = cot_row_sparse(S, D, Q, A, M, cutoff, \
225
+ eps_p=eps_p_row, eps_mu=eps_mu_row, eps_nu=eps_nu_row, rho=rho_row, lam=lam_row, \
226
+ nitermax=nitermax, stopthr=stopthr, verbose=False)
227
+ P_col = cot_col_sparse(S, D, Q, A, M, cutoff, \
228
+ eps_p=eps_p_col, eps_mu=eps_mu_col, eps_nu=eps_nu_col, rho=rho_col, lam=lam_col, \
229
+ nitermax=nitermax, stopthr=stopthr, verbose=False)
230
+ P_blk = cot_blk_sparse(S, D, Q, A, M, cutoff, \
231
+ eps_p=eps_p_blk, eps_mu=eps_mu_blk, eps_nu=eps_nu_blk, rho=rho_blk, lam=lam_blk, \
232
+ nitermax=nitermax, stopthr=stopthr, verbose=False)
233
+
234
+ P = {}
235
+ for i in range(A.shape[0]):
236
+ for j in range(A.shape[1]):
237
+ if not np.isinf(A[i,j]):
238
+ P[(i,j)] = float(weights[0]) * P_cot[(i,j)] + float(weights[1]) * P_row[(i,j)] \
239
+ + float(weights[2]) * P_col[(i,j)] + float(weights[3]) * P_blk[(i,j)]
240
+ return(P),CostC
241
+
242
+ def cot_sparse(S, D, Q, A, M, cutoff, eps_p=1e-1, eps_mu=None, eps_nu=None, rho=1e1, lam=1e1, nitermax=1e4, stopthr=1e-8, verbose=False):
243
+ """ Solve the collective optimal transport problem with distance limits in sparse format.
244
+
245
+ Parameters
246
+ ----------
247
+ S : (n_pos_s,ns_s) numpy.ndarray
248
+ Source distributions over `n_pos_s` positions of `ns_s` source species.
249
+ D : (n_pos_d,ns_d) numpy.ndarray
250
+ Destination distributions over `n_pos_d` positions of `ns_d` destination species.
251
+ Q : (n_pos_d,ns_d) numpy.ndarray
252
+ Intra-signal destination distributions over `n_pos_d` positions of `ns_d` destination species.
253
+ A : (ns_s,ns_d) numpy.ndarray
254
+ The cost coefficients for source-destination species pairs. An infinity value indicates that the two species cannot be coupled.
255
+ M : (n_pos_s,n_pos_d) numpy.ndarray
256
+ The distance (cost) matrix among the positions.
257
+ cutoff : (ns_s,ns_d) numpy.ndarray
258
+ The distance (cost) cutoff between each source-destination species pair. All transports are restricted by the cutoffs.
259
+ eps_p : float, defaults to 1e-1
260
+ The coefficient for entropy regularization of P.
261
+ eps_mu : float, defaults to eps_p
262
+ The coefficient for entropy regularization of unmatched source mass.
263
+ eps_nu : float, defaults to eps_p
264
+ The coefficient for entriopy regularization of unmatched target mass.
265
+ rho : float, defaults to 1e1
266
+ The coefficient for penalizing unmatched mass.
267
+ lam : float, defaults to le1
268
+ The coefficient for KL divergence between inter- and intra-signal distributions.
269
+ nitermax : int, optional
270
+ The maximum number of iterations in the unormalized OT problem. Defaults to 1e4.
271
+ stopthr : float, optional
272
+ The relatitive error threshold for terminating the iteration. Defaults to 1e-8.
273
+
274
+ Returns
275
+ -------
276
+ A dictionary of scipy.sparse.coo_matrix
277
+ The transport plan in coo sparse format for source species i and destinaton species j can be retrieved with the key (i,j).
278
+ """
279
+ np.set_printoptions(precision=2)
280
+ n_pos_s, ns_s = S.shape
281
+ n_pos_d, ns_d = D.shape
282
+ max_amount = max( S.sum(), D.sum() )
283
+ S = S / max_amount
284
+ D = D / max_amount
285
+
286
+ if eps_mu is None: eps_mu = eps_p
287
+ if eps_nu is None: eps_nu = eps_p
288
+ if max(abs(eps_p-eps_mu),abs(eps_p-eps_nu)) > 1e-8:
289
+ unot_solver = "momentum"
290
+ else:
291
+ unot_solver = "sinkhorn"
292
+
293
+ # Set up the large collective OT problem
294
+ a = S.flatten('F')
295
+ b = D.flatten('F')
296
+ q = Q.flatten('F')
297
+
298
+ C_data, C_row, C_col = [], [], []
299
+
300
+ # max_cutoff = cutoff.max()
301
+ # M_row, M_col = np.where(M <= max_cutoff)
302
+ # M_max_sp = sparse.coo_matrix((M[M_row,M_col], (M_row,M_col)), shape=M.shape)
303
+ M_max_sp = M.copy()
304
+
305
+ cost_scales = []
306
+ for i in range(ns_s):
307
+ for j in range(ns_d):
308
+ if not np.isinf(A[i,j]):
309
+ tmp_nzind_s = np.where(S[:,i] > 0)[0]
310
+ tmp_nzind_d = np.where(D[:,j] > 0)[0]
311
+ tmp_M_max_sp = coo_submatrix_pull(M_max_sp, tmp_nzind_s, tmp_nzind_d)
312
+ tmp_ind = np.where(tmp_M_max_sp.data <= cutoff[i,j])[0]
313
+ tmp_row = tmp_nzind_s[tmp_M_max_sp.row[tmp_ind]]
314
+ tmp_col = tmp_nzind_d[tmp_M_max_sp.col[tmp_ind]]
315
+ cost_scales.append(np.max(M_max_sp.data[np.where(M_max_sp.data <= cutoff[i,j])])*A[i,j])
316
+ C_data.append( tmp_M_max_sp.data[tmp_ind]*A[i,j] )
317
+ C_row.append( tmp_row+i*n_pos_s )
318
+ C_col.append( tmp_col+j*n_pos_d )
319
+
320
+ cost_scale = np.max(cost_scales)
321
+ C_data = np.concatenate(C_data, axis=0)
322
+ C_row = np.concatenate(C_row, axis=0)
323
+ C_col = np.concatenate(C_col, axis=0)
324
+ C = sparse.coo_matrix((C_data/cost_scale, (C_row, C_col)), shape=(len(a),len(b)))
325
+
326
+ # Solve the problem on nonzero mass
327
+ nzind_a = np.where(a > 0)[0]
328
+ nzind_b = np.where(b > 0)[0]
329
+ nzind_q = np.where(q > 0)[0]
330
+ overlap = np.intersect1d(nzind_b, nzind_q)
331
+ # C_csr = C.tocsr()
332
+
333
+ # valid_rows = np.where(np.diff(C_csr.indptr) > 0)[0]
334
+ # valid_cols = np.unique(C_csr.indices)
335
+
336
+ # nzind_a = np.intersect1d(nzind_a, valid_rows)
337
+ # overlap = np.intersect1d(overlap, valid_cols)
338
+
339
+ C_nz = coo_submatrix_pull(C, nzind_a, overlap)
340
+
341
+ if verbose:
342
+ print('Number of non-infinity entries in transport cost:', len(C.data))
343
+
344
+ # del C_data, C_row, C_col, C
345
+ del C_data, C_row, C_col
346
+
347
+ tmp_P = unot(a[nzind_a], b[overlap], q[overlap], C_nz, eps_p, rho, lam, \
348
+ eps_mu=eps_mu, eps_nu=eps_nu, sparse_mtx=True, solver=unot_solver, nitermax=nitermax, stopthr=stopthr)
349
+
350
+ del C_nz
351
+
352
+ P = sparse.coo_matrix((tmp_P.data, (nzind_a[tmp_P.row], overlap[tmp_P.col])), shape=(len(a),len(b)))
353
+ P = P.tocsr()
354
+
355
+ # Output a dictionary of transport plans
356
+ P_expand = {}
357
+ for i in range(ns_s):
358
+ for j in range(ns_d):
359
+ if not np.isinf(A[i,j]):
360
+ tmp_P = P[i*n_pos_s:(i+1)*n_pos_s, j*n_pos_d:(j+1)*n_pos_d]
361
+ P_expand[(i,j)] = tmp_P.tocoo() * max_amount
362
+
363
+ return P_expand,C
364
+
365
+ def cot_row_sparse(S, D, Q, A, M, cutoff, eps_p=1e-1, eps_mu=None, eps_nu=None, rho=1e1, lam=1e1, nitermax=1e4, stopthr=1e-8, verbose=False):
366
+ """Solve for each sender species separately.
367
+ """
368
+ if eps_mu is None: eps_mu = eps_p
369
+ if eps_nu is None: eps_nu = eps_p
370
+ if max(abs(eps_p-eps_mu),abs(eps_p-eps_nu)) > 1e-8:
371
+ unot_solver = "momentum"
372
+ else:
373
+ unot_solver = "sinkhorn"
374
+
375
+ n_pos_s, ns_s = S.shape
376
+ n_pos_d, ns_d = D.shape
377
+
378
+ # max_cutoff = cutoff.max()
379
+ # M_row, M_col = np.where(M <= max_cutoff)
380
+ # M_max_sp = sparse.coo_matrix((M[M_row,M_col], (M_row,M_col)), shape=M.shape)
381
+ M_max_sp = M.copy()
382
+
383
+ P_expand = {}
384
+ for i in range(ns_s):
385
+ a = S[:,i]
386
+ D_ind = np.where(~np.isinf(A[i,:]))[0]
387
+ b = D[:,D_ind].flatten('F')
388
+ q = Q[:,D_ind].flatten('F')
389
+ nzind_a = np.where(a > 0)[0]; nzind_b = np.where(b > 0)[0]; nzind_q = np.where(q > 0)[0]
390
+ if len(nzind_a)==0 or len(nzind_b)==0 or len(nzind_q)==0:
391
+ for j in range(len(D_ind)):
392
+ P_expand[(i,D_ind[j])] = sparse.coo_matrix(([],([],[])), shape=(n_pos_s, n_pos_d), dtype=float)
393
+ continue
394
+ max_amount = max(a.sum(), b.sum())
395
+ a = a / max_amount; b = b / max_amount
396
+ C_data, C_row, C_col = [], [], []
397
+ cost_scales = []
398
+ for j in range(len(D_ind)):
399
+ D_j = D_ind[j]
400
+ tmp_nzind_s = np.where(S[:,i] > 0)[0]
401
+ tmp_nzind_d = np.where(D[:,D_j] > 0)[0]
402
+ tmp_M_max_sp = coo_submatrix_pull(M_max_sp, tmp_nzind_s, tmp_nzind_d)
403
+ tmp_ind = np.where(tmp_M_max_sp.data <= cutoff[i,D_j])[0]
404
+ tmp_row = tmp_nzind_s[tmp_M_max_sp.row[tmp_ind]]
405
+ tmp_col = tmp_nzind_d[tmp_M_max_sp.col[tmp_ind]]
406
+ C_data.append( tmp_M_max_sp.data[tmp_ind]*A[i,D_j] )
407
+ C_row.append( tmp_row )
408
+ C_col.append( tmp_col+j*n_pos_d )
409
+ cost_scales.append( np.max(M_max_sp.data[np.where(M_max_sp.data <= cutoff[i,D_j])])*A[i,D_j] )
410
+ cost_scale = np.max(cost_scales)
411
+ C_data = np.concatenate(C_data, axis=0)
412
+ C_row = np.concatenate(C_row, axis=0)
413
+ C_col = np.concatenate(C_col, axis=0)
414
+ C = sparse.coo_matrix((C_data/cost_scale, (C_row, C_col)), shape=(len(a), len(b)))
415
+
416
+ nzind_a = np.where(a > 0)[0]
417
+ nzind_b = np.where(b > 0)[0]
418
+ nzind_q = np.where(q > 0)[0]
419
+ overlap = np.intersect1d(nzind_b, nzind_q)
420
+ # C_csr = C.tocsr()
421
+
422
+ # valid_rows = np.where(np.diff(C_csr.indptr) > 0)[0]
423
+ # valid_cols = np.unique(C_csr.indices)
424
+
425
+ # nzind_a = np.intersect1d(nzind_a, valid_rows)
426
+ # overlap = np.intersect1d(overlap, valid_cols)
427
+ C_nz = coo_submatrix_pull(C, nzind_a, overlap)
428
+
429
+ del C_data, C_row, C_col, C
430
+
431
+ tmp_P = unot(a[nzind_a], b[overlap], q[overlap], C_nz, eps_p, rho, lam,\
432
+ eps_mu=eps_mu, eps_nu=eps_nu, sparse_mtx=True, solver=unot_solver, nitermax=nitermax, stopthr=stopthr)
433
+
434
+ del C_nz
435
+
436
+ P = sparse.coo_matrix((tmp_P.data, (nzind_a[tmp_P.row], overlap[tmp_P.col])), shape=(len(a),len(b)))
437
+ P = P.tocsr()
438
+
439
+ for j in range(len(D_ind)):
440
+ tmp_P = P[:,j*n_pos_d:(j+1)*n_pos_d]
441
+ P_expand[(i,D_ind[j])] = tmp_P.tocoo() * max_amount
442
+
443
+ del P
444
+
445
+ return P_expand
446
+
447
+ def cot_col_sparse(S, D, Q, A, M, cutoff, eps_p=1e-1, eps_mu=None, eps_nu=None, rho=1e1, lam=1e1, nitermax=1e4, stopthr=1e-8, verbose=False):
448
+ """Solve for each destination species separately.
449
+ """
450
+ if eps_mu is None: eps_mu = eps_p
451
+ if eps_nu is None: eps_nu = eps_p
452
+ if max(abs(eps_p-eps_mu),abs(eps_p-eps_nu)) > 1e-8:
453
+ unot_solver = "momentum"
454
+ else:
455
+ unot_solver = "sinkhorn"
456
+
457
+ n_pos_s, ns_s = S.shape
458
+ n_pos_d, ns_d = D.shape
459
+
460
+ # max_cutoff = cutoff.max()
461
+ # M_row, M_col = np.where(M <= max_cutoff)
462
+ # M_max_sp = sparse.coo_matrix((M[M_row,M_col], (M_row,M_col)), shape=M.shape)
463
+ M_max_sp = M.copy()
464
+
465
+ P_expand = {}
466
+ for j in range(ns_d):
467
+ S_ind = np.where(~np.isinf(A[:,j]))[0]
468
+ a = S[:,S_ind].flatten('F')
469
+ b = D[:,j]
470
+ q = Q[:,j]
471
+ nzind_a = np.where(a > 0)[0]; nzind_b = np.where(b > 0)[0]; nzind_q = np.where(q > 0)[0]
472
+ if len(nzind_a)==0 or len(nzind_b)==0 or len(nzind_q)==0 :
473
+ for i in range(len(S_ind)):
474
+ P_expand[(S_ind[i],j)] = sparse.coo_matrix(([],([],[])), shape=(n_pos_s,n_pos_d), dtype=float)
475
+ continue
476
+ max_amount = max(a.sum(), b.sum())
477
+ a = a / max_amount; b = b / max_amount
478
+ C_data, C_row, C_col = [], [], []
479
+ cost_scales = []
480
+ for i in range(len(S_ind)):
481
+ S_i = S_ind[i]
482
+ tmp_nzind_s = np.where(S[:,S_i] > 0)[0]
483
+ tmp_nzind_d = np.where(D[:,j] > 0)[0]
484
+ tmp_M_max_sp = coo_submatrix_pull(M_max_sp, tmp_nzind_s, tmp_nzind_d)
485
+ tmp_ind = np.where(tmp_M_max_sp.data <= cutoff[S_i,j])[0]
486
+ tmp_row = tmp_nzind_s[tmp_M_max_sp.row[tmp_ind]]
487
+ tmp_col = tmp_nzind_d[tmp_M_max_sp.col[tmp_ind]]
488
+ C_data.append( tmp_M_max_sp.data[tmp_ind]*A[S_i,j] )
489
+ C_row.append( tmp_row+i*n_pos_s )
490
+ C_col.append( tmp_col )
491
+ cost_scales.append( np.max(M_max_sp.data[np.where(M_max_sp.data <= cutoff[S_i,j])])*A[S_i,j] )
492
+ cost_scale = np.max(cost_scales)
493
+ C_data = np.concatenate(C_data, axis=0)
494
+ C_row = np.concatenate(C_row, axis=0)
495
+ C_col = np.concatenate(C_col, axis=0)
496
+ C = sparse.coo_matrix((C_data/cost_scale, (C_row, C_col)), shape=(len(a), len(b)))
497
+
498
+ nzind_a = np.where(a > 0)[0]
499
+ nzind_b = np.where(b > 0)[0]
500
+ nzind_q = np.where(q > 0)[0]
501
+ overlap = np.intersect1d(nzind_b, nzind_q)
502
+ # C_csr = C.tocsr()
503
+
504
+ # valid_rows = np.where(np.diff(C_csr.indptr) > 0)[0]
505
+ # valid_cols = np.unique(C_csr.indices)
506
+
507
+ # nzind_a = np.intersect1d(nzind_a, valid_rows)
508
+ # overlap = np.intersect1d(overlap, valid_cols)
509
+ C_nz = coo_submatrix_pull(C, nzind_a, overlap)
510
+
511
+ del C_data, C_row, C_col, C
512
+
513
+ tmp_P = unot(a[nzind_a], b[overlap], q[overlap], C_nz, eps_p, rho, lam,\
514
+ eps_mu=eps_mu, eps_nu=eps_nu, sparse_mtx=True, solver=unot_solver, nitermax=nitermax, stopthr=stopthr)
515
+
516
+ del C_nz
517
+
518
+ P = sparse.coo_matrix((tmp_P.data, (nzind_a[tmp_P.row], overlap[tmp_P.col])), shape=(len(a),len(b)))
519
+ P = P.tocsr()
520
+
521
+ for i in range(len(S_ind)):
522
+ tmp_P = P[i*n_pos_s:(i+1)*n_pos_s,:]
523
+ P_expand[(S_ind[i],j)] = tmp_P.tocoo() * max_amount
524
+
525
+ del P
526
+
527
+ return P_expand
528
+
529
+ def cot_blk_sparse(S, D, Q, A, M, cutoff, eps_p=1e-1, eps_mu=None, eps_nu=None, rho=1e1, lam=1e1, nitermax=1e4, stopthr=1e-8, verbose=False):
530
+ if eps_mu is None: eps_mu = eps_p
531
+ if eps_nu is None: eps_nu = eps_p
532
+ if max(abs(eps_p-eps_mu), abs(eps_p-eps_nu)) > 1e-8:
533
+ unot_solver = "momentum"
534
+ else:
535
+ unot_solver = "sinkhorn"
536
+
537
+ n_pos_s, ns_s = S.shape
538
+ n_pos_d, ns_d = D.shape
539
+
540
+ # max_cutoff = cutoff.max()
541
+ # M_row, M_col = np.where(M <= max_cutoff)
542
+ # M_max_sp = sparse.coo_matrix((M[M_row,M_col], (M_row,M_col)), shape=M.shape)
543
+ M_max_sp = M.copy()
544
+
545
+ P_expand = {}
546
+ for i in range(ns_s):
547
+ for j in range(ns_d):
548
+ if not np.isinf(A[i,j]):
549
+ a = S[:,i]; b = D[:,j]; q = Q[:,j]
550
+ nzind_a = np.where(a > 0)[0]; nzind_b = np.where(b > 0)[0]; nzind_q = np.where(q > 0)[0]
551
+ if len(nzind_a)==0 or len(nzind_b)==0:
552
+ P_expand[(i,j)] = sparse.coo_matrix(([],([],[])), shape=(n_pos_s, n_pos_d), dtype=float)
553
+ continue
554
+ max_amount = max(a.sum(), b.sum())
555
+ a = a / max_amount; b = b / max_amount
556
+ tmp_nzind_s = np.where(S[:,i] > 0)[0]
557
+ tmp_nzind_d = np.where(D[:,j] > 0)[0]
558
+ tmp_M_max_sp = coo_submatrix_pull(M_max_sp, tmp_nzind_s, tmp_nzind_d)
559
+ tmp_ind = np.where(tmp_M_max_sp.data <= cutoff[i,j])[0]
560
+ tmp_row = tmp_nzind_s[tmp_M_max_sp.row[tmp_ind]]
561
+ tmp_col = tmp_nzind_d[tmp_M_max_sp.col[tmp_ind]]
562
+ C_data = tmp_M_max_sp.data[tmp_ind] * A[i,j]
563
+ cost_scale = np.max( M_max_sp.data[np.where(M_max_sp.data <= cutoff[i,j])] )*A[i,j]
564
+ C = sparse.coo_matrix((C_data/cost_scale, (tmp_row, tmp_col)), shape=(len(a), len(b)))
565
+
566
+ nzind_a = np.where(a > 0)[0]
567
+ nzind_b = np.where(b > 0)[0]
568
+ nzind_q = np.where(q > 0)[0]
569
+ overlap = np.intersect1d(nzind_b, nzind_q)
570
+ # C_csr = C.tocsr()
571
+
572
+ # valid_rows = np.where(np.diff(C_csr.indptr) > 0)[0]
573
+ # valid_cols = np.unique(C_csr.indices)
574
+
575
+ # nzind_a = np.intersect1d(nzind_a, valid_rows)
576
+ # overlap = np.intersect1d(overlap, valid_cols)
577
+ C_nz = coo_submatrix_pull(C, nzind_a, overlap)
578
+
579
+ del C_data, C
580
+
581
+ tmp_P = unot(a[nzind_a], b[overlap], q[overlap], C_nz, eps_p, rho, lam,\
582
+ eps_mu=eps_mu, eps_nu=eps_nu, sparse_mtx=True, solver=unot_solver, nitermax=nitermax, stopthr=stopthr)
583
+
584
+ del C_nz
585
+
586
+ P = sparse.coo_matrix((tmp_P.data, (nzind_a[tmp_P.row], overlap[tmp_P.col])), shape=(len(a),len(b)))
587
+
588
+ P_expand[(i,j)] = P * max_amount
589
+
590
+ return P_expand
591
+
592
+
593
+ def co_exp_batch_adata(adata, ggi_res, co_exp_ratio=0.05, batch_size=5000):
594
+ X = adata.X.toarray() if hasattr(adata.X, "toarray") else adata.X
595
+ gene_names = pd.Index(adata.var_names)
596
+ gene_to_idx = {g: i for i, g in enumerate(gene_names)}
597
+
598
+ ggi_res_temp = ggi_res[['src', 'dest']].drop_duplicates().copy()
599
+ ggi_res_temp['src_idx'] = ggi_res_temp['src'].map(gene_to_idx)
600
+ ggi_res_temp['dest_idx'] = ggi_res_temp['dest'].map(gene_to_idx)
601
+
602
+ co_ratios = np.empty(len(ggi_res_temp), dtype=np.float32)
603
+
604
+ # Process in batches
605
+ for start in range(0, len(ggi_res_temp), batch_size):
606
+ end = min(start + batch_size, len(ggi_res_temp))
607
+ batch = ggi_res_temp.iloc[start:end]
608
+
609
+ src_matrix = X[:, batch['src_idx'].values]
610
+ dest_matrix = X[:, batch['dest_idx'].values]
611
+
612
+ x12 = src_matrix * dest_matrix # (n_cells × batch_size)
613
+ co_ratios[start:end] = np.sum(x12 > 0, axis=0) / x12.shape[0]
614
+
615
+ ggi_res_temp['co_ratio'] = co_ratios
616
+
617
+ # Merge back
618
+ ggi_res = ggi_res.merge(
619
+ ggi_res_temp[['src', 'dest', 'co_ratio']],
620
+ on=['src', 'dest'],
621
+ how='left'
622
+ )
623
+
624
+ if co_exp_ratio > 0:
625
+ ggi_res = ggi_res[ggi_res['co_ratio'] > co_exp_ratio]
626
+
627
+ return ggi_res[['src', 'dest', 'src_tf', 'dest_tf', 'hop', 'co_ratio']]
628
+
629
+
630
+ def generate_tf_res(tf_gene_all, receptor_name, ggi_res):
631
+ import pandas as pd
632
+
633
+ tf_names = list(tf_gene_all.keys())
634
+ tf_n_hop = list(tf_gene_all.values())
635
+
636
+ # Initialize DataFrame
637
+ receptor_tf_temp = pd.DataFrame({
638
+ "receptor": [receptor_name] * len(tf_names),
639
+ "tf": tf_names,
640
+ "n_hop": tf_n_hop,
641
+ "target_genes": [[] for _ in tf_names] # initialize with empty lists
642
+ })
643
+
644
+ # Fill in `target_genes`
645
+ for i in range(len(tf_names)):
646
+ tf = tf_names[i]
647
+ hop = tf_n_hop[i]
648
+ # Filter rows where src == tf and hop == hop + 1
649
+ ggi_res_tf = ggi_res[(ggi_res["src"] == tf) & (ggi_res["hop"] == hop + 1)]
650
+ receptor_tf_temp.at[i, "target_genes"] = ggi_res_tf["dest"].unique().tolist()
651
+
652
+ return receptor_tf_temp
653
+
654
+ def generate_tf_gene_all(ggi_res: pd.DataFrame, max_hop: int) -> dict:
655
+ """
656
+ Track TF-to-gene paths across hops and collect destination genes with TF activity.
657
+
658
+ Args:
659
+ ggi_res: DataFrame with columns ['src', 'dest', 'hop', 'dest_tf']
660
+ max_hop: Maximum number of hops to search
661
+
662
+ Returns:
663
+ Dictionary of {gene_name: hop}
664
+ """
665
+ tf_gene_all = {}
666
+ ggi_hop = ggi_res[ggi_res["hop"] == 1].copy()
667
+
668
+ for k in range(1, max_hop + 1):
669
+ # Get the rows where dest_tf == "YES"
670
+ ggi_hop_yes = ggi_hop[ggi_hop["dest_tf"] == "YES"]
671
+
672
+ if not ggi_hop_yes.empty:
673
+ ggi_hop_tf = ggi_res[ggi_res["hop"] == k + 1]
674
+ if not ggi_hop_tf.empty:
675
+ # Keep only rows where ggi_hop_yes$dest in ggi_hop_tf$src
676
+ ggi_hop_yes = ggi_hop_yes[ggi_hop_yes["dest"].isin(ggi_hop_tf["src"])]
677
+ if not ggi_hop_yes.empty:
678
+ for _, row in ggi_hop_yes.iterrows():
679
+ tf_gene_all[row["dest"]] = row["hop"]
680
+
681
+ # Prepare next ggi_hop from "NO" group
682
+ ggi_hop_no = ggi_hop[ggi_hop["dest_tf"] == "NO"]
683
+ ggi_hop = ggi_res[ggi_res["hop"] == k + 1]
684
+ ggi_hop = ggi_hop[ggi_hop["src"].isin(ggi_hop_no["dest"])]
685
+
686
+ return tf_gene_all
687
+
688
+ def random_walk_vectorized(receptor_tf, ggi_res, max_n_hop=10):
689
+ """
690
+ Vectorized random walk to compute TF scores.
691
+
692
+ Args:
693
+ receptor_tf: DataFrame with columns 'receptor' and 'tf'
694
+ ggi_res: DataFrame with 'src' and 'dest' columns representing edges
695
+ max_n_hop: maximum number of hops
696
+
697
+ Returns:
698
+ dict: normalized probability of reaching each TF from the receptor
699
+ """
700
+ # All nodes
701
+ nodes = pd.Index(np.unique(ggi_res[['src', 'dest']].values.ravel()))
702
+ node_to_idx = {node: i for i, node in enumerate(nodes)}
703
+ n_nodes = len(nodes)
704
+
705
+ # Adjacency matrix
706
+ row = ggi_res['src'].map(node_to_idx).values
707
+ col = ggi_res['dest'].map(node_to_idx).values
708
+ data = np.ones(len(row))
709
+ adj = csr_matrix((data, (row, col)), shape=(n_nodes, n_nodes), dtype=float)
710
+
711
+ # Normalize rows to get transition probabilities
712
+ row_sums = np.array(adj.sum(axis=1)).flatten()
713
+ row_sums[row_sums == 0] = 1 # avoid division by zero
714
+ adj = adj.multiply(1 / row_sums[:, None])
715
+
716
+ # Initialize probability vector (start at receptor)
717
+ prob = np.zeros(n_nodes)
718
+ receptor_idx = node_to_idx[receptor_tf['receptor'].iloc[0]]
719
+ prob[receptor_idx] = 1.0
720
+
721
+ # Nodes that are TFs
722
+ tf_indices = [node_to_idx[tf] for tf in receptor_tf['tf']]
723
+
724
+ # Accumulate probabilities at TFs
725
+ tf_prob = np.zeros(len(tf_indices))
726
+
727
+ # Perform walks via matrix multiplication
728
+ current_prob = prob.copy()
729
+ for hop in range(max_n_hop):
730
+ current_prob = current_prob @ adj # next hop probabilities
731
+ tf_prob += current_prob[tf_indices]
732
+
733
+ hop_tf = receptor_tf['n_hop'].values.astype(float) # one hop per TF
734
+ # adjust probability -inverse-hop weighting
735
+ tf_prob = tf_prob / hop_tf
736
+
737
+ # Normalize by max_n_hop
738
+ tf_prob = tf_prob / tf_prob.sum()
739
+
740
+ return dict(zip(receptor_tf['tf'], tf_prob))
741
+
742
+
743
+ def calculate_TF_scores(adata, receptor_tf_temp):
744
+ """
745
+ Calculate TF scores for each cell in adata based on receptor_tf_temp info. (receptor to TF probability, TF gene expression, sum of target genes' gene expression)
746
+
747
+ Args:
748
+ adata: AnnData object with gene expression in adata.X and var_names as gene names
749
+ receptor_tf_temp: pd.DataFrame with columns ['tf', 'target_genes', 'score', 'n_hop']
750
+
751
+ Returns:
752
+ np.ndarray: TF scores, shape (n_cells, 1)
753
+ """
754
+
755
+ gene_names = adata.var_names.to_list()
756
+ n_cells = adata.n_obs
757
+
758
+ # Initialize score vector for each cell
759
+ tf_scores = np.zeros(n_cells)
760
+
761
+ # Pre-build gene index mapping for quick lookup
762
+ gene_to_idx = {g: i for i, g in enumerate(gene_names)}
763
+
764
+ for idx, row in receptor_tf_temp.iterrows():
765
+ target_genes = row["target_genes"]
766
+ tf_expr = adata[:, row["tf"]].X
767
+ if hasattr(tf_expr, "toarray"):
768
+ tf_expr = tf_expr.toarray()
769
+ tf_expr = tf_expr.flatten() # shape = (n_cells,)
770
+ score_weight = row["score"] * tf_expr # (n_cells,)
771
+
772
+ # Find indices of target genes in adata.var_names
773
+ valid_genes = [g for g in target_genes if g in gene_to_idx]
774
+
775
+ if not valid_genes:
776
+ continue # skip if no targets in dataset
777
+
778
+ gene_indices = [gene_to_idx[g] for g in valid_genes]
779
+
780
+ # Extract expression for these genes (cells x genes)
781
+ # Assuming adata.X is sparse or dense matrix: slicing columns for these genes
782
+ expr_subset = adata.X[:, gene_indices]
783
+
784
+ # Sum expression across target genes for each cell
785
+ # If sparse, use .sum(axis=1).A1 to get flat numpy array
786
+ if hasattr(expr_subset, "toarray"): # sparse matrix
787
+ gene_sum = expr_subset.sum(axis=1).A1
788
+ else:
789
+ gene_sum = expr_subset.sum(axis=1)
790
+
791
+ # Weighted contribution of this TF to each cell
792
+ tf_scores += gene_sum * score_weight # (n_cells,)
793
+
794
+ # Reshape to n_cells x 1 vector
795
+ return tf_scores.reshape(-1, 1)
796
+
797
+ def generate_ggi_res(ggi_tf, receptor_name, adata, max_hop, co_exp_ratio):
798
+ X = adata.X.toarray() if hasattr(adata.X, "toarray") else adata.X
799
+ gene_names = adata.var_names
800
+
801
+ ggi_tf1 = ggi_tf[(ggi_tf['src'] == receptor_name) & ggi_tf['dest'].isin(gene_names)].drop_duplicates()
802
+ if ggi_tf1.empty:
803
+ return pd.DataFrame()
804
+
805
+ ggi_res = []
806
+ current = ggi_tf1.copy()
807
+ current['hop'] = 1
808
+
809
+ for hop in range(1, max_hop + 1):
810
+ ggi_res.append(current)
811
+ next_srcs = current['dest'].unique()
812
+ current = ggi_tf[ggi_tf['src'].isin(next_srcs) & ggi_tf['dest'].isin(gene_names)].drop_duplicates()
813
+ if current.empty:
814
+ break
815
+ current = current.copy()
816
+ current['hop'] = hop + 1
817
+
818
+ ggi_res = pd.concat(ggi_res, ignore_index=True).drop_duplicates()
819
+
820
+ # Use vectorized batch version
821
+ ggi_res = co_exp_batch_adata(adata, ggi_res, co_exp_ratio)
822
+
823
+ return ggi_res
824
+
825
+
826
+ def coo_submatrix_pull(matr, rows, cols):
827
+ """
828
+ Pulls out an arbitrary i.e. non-contiguous submatrix out of
829
+ a sparse.coo_matrix.
830
+ """
831
+ if type(matr) != sparse.coo_matrix:
832
+ raise TypeError('Matrix must be sparse COOrdinate format')
833
+
834
+ gr = -1 * np.ones(matr.shape[0])
835
+ gc = -1 * np.ones(matr.shape[1])
836
+
837
+ lr = len(rows)
838
+ lc = len(cols)
839
+
840
+ ar = np.arange(0, lr)
841
+ ac = np.arange(0, lc)
842
+ gr[rows[ar]] = ar
843
+ gc[cols[ac]] = ac
844
+ mrow = matr.row
845
+ mcol = matr.col
846
+ newelem = (gr[mrow] > -1) & (gc[mcol] > -1)
847
+ newrows = mrow[newelem]
848
+ newcols = mcol[newelem]
849
+ return sparse.coo_matrix((matr.data[newelem], np.array([gr[newrows],
850
+ gc[newcols]])),(lr, lc))