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