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,485 @@
1
+ import numpy as np
2
+ from scipy import sparse
3
+ from scipy.spatial import distance_matrix
4
+ from scipy.special import wrightomega
5
+ import matplotlib.pyplot as plt
6
+
7
+ def unot(a,
8
+ b,
9
+ q,
10
+ C,
11
+ eps_p,
12
+ rho,
13
+ lam,
14
+ eps_mu=None,
15
+ eps_nu=None,
16
+ sparse_mtx=False,
17
+ solver="sinkhorn",
18
+ nitermax=10000,
19
+ stopthr=1e-8,
20
+ verbose=False,
21
+ momentum_dt=0.1,
22
+ momentum_beta=0.0):
23
+ """ The main function calling different algorithms.
24
+
25
+ Parameters
26
+ ----------
27
+ a : (ns,) numpy.ndarray
28
+ Source distribution. The summation should be less than or equal to 1.
29
+ b : (nt,) numpy.ndarray
30
+ Target distribution. The summation should be less than or equal to 1.
31
+ q : (nt,) numpy.ndarray
32
+ intra signal distribution.
33
+ C : (ns,nt) numpy.ndarray
34
+ The cost matrix possibly with infinity entries.
35
+ eps_p : float
36
+ The coefficient of entropy regularization for P.
37
+ rho : float
38
+ The coefficient of penalty for unmatched mass.
39
+ lam : float
40
+ The coefficient for KL divergence between inter- and intra-signal distributions.
41
+ eps_mu : float, defaults to eps_p
42
+ The coefficient of entropy regularization for mu.
43
+ eps_nu : float, defaults to eps_p
44
+ The coefficient of entropy regularization for nu.
45
+ sparse_mtx : boolean, defaults to False
46
+ Whether using sparse matrix format. If True, C should be in coo_sparse format.
47
+ solver : str, defaults to 'sinkhorn'
48
+ The solver to use. Choose from 'sinkhorn' and 'momentum'.
49
+ nitermax : int, defaults to 10000
50
+ The maximum number of iterations.
51
+ stopthr : float, defaults to 1e-8
52
+ The relative error threshold for stopping.
53
+ verbose : boolean, defaults to False
54
+ Whether to print algorithm logs.
55
+ momentum_dt : float, defaults to 1e-1
56
+ Step size if momentum method is used.
57
+ momentum_beta : float, defautls to 0
58
+ The coefficient for the momentum term if momemtum method is used.
59
+ """
60
+ if eps_mu is None: eps_mu = eps_p
61
+ if eps_nu is None: eps_nu = eps_p
62
+ # Return a zero matrix if either a or b is all zero
63
+ nzind_a = np.where(a > 0)[0]; nzind_b = np.where(b > 0)[0]
64
+ if len(nzind_a) == 0 or len(nzind_b) == 0:
65
+ if sparse_mtx:
66
+ P = sparse.coo_matrix(([],([],[])), shape=(len(a), len(b)))
67
+ else:
68
+ P = np.zeros([len(a), len(b)], float)
69
+ return P
70
+ if solver == "sinkhorn" and max(abs(eps_p-eps_mu),abs(eps_p-eps_nu))>1e-8:
71
+ print("To use Sinkhorn algorithm, set eps_p=eps_mu=eps_nu")
72
+ exit()
73
+ if solver == "sinkhorn" and not sparse_mtx:
74
+ P = unot_sinkhorn_l1_dense(a,b,C,eps_p,rho, \
75
+ nitermax=nitermax,stopthr=stopthr,verbose=verbose)
76
+ elif solver == "sinkhorn" and sparse_mtx:
77
+ P = unot_sinkhorn_l1_sparse(a,b,q,C,eps_p,rho, lam, \
78
+ nitermax=nitermax,stopthr=stopthr,verbose=verbose)
79
+ elif solver == "momentum" and not sparse_mtx:
80
+ P = unot_momentum_l1_dense(a,b,C,eps_p,eps_mu,eps_nu,rho, \
81
+ nitermax=nitermax,stopthr=stopthr,dt=momentum_dt, \
82
+ beta=momentum_beta,precondition=True,verbose=verbose)
83
+ elif solver == "momentum" and sparse_mtx:
84
+ print("under construction")
85
+ exit()
86
+ return P
87
+
88
+ def unot_sinkhorn_l2_dense(a,b,C,eps,m,nitermax=10000,stopthr=1e-8,verbose=False):
89
+ """ Solve the unnormalized optimal transport with l2 penalty in dense matrix format.
90
+
91
+ Parameters
92
+ ----------
93
+ a : (ns,) numpy.ndarray
94
+ Source distribution. The summation should be less than or equal to 1.
95
+ b : (nt,) numpy.ndarray
96
+ Target distribution. The summation should be less than or equal to 1.
97
+ C : (ns,nt) numpy.ndarray
98
+ The cost matrix possibly with infinity entries.
99
+ eps : float
100
+ The coefficient for entropy regularization.
101
+ m : float
102
+ The coefficient for penalizing unmatched mass.
103
+ nitermax : int, optional
104
+ The max number of iterations. Defaults to 10000.
105
+ stopthr : float, optional
106
+ The threshold for terminating the iteration. Defaults to 1e-8.
107
+
108
+ Returns
109
+ -------
110
+ (ns,nt) numpy.ndarray
111
+ The optimal transport matrix.
112
+ """
113
+ f = np.zeros_like(a)
114
+ g = np.zeros_like(b)
115
+ r = np.zeros_like(a)
116
+ s = np.zeros_like(b)
117
+ niter = 0
118
+ err = 100
119
+ while niter <= nitermax and err > stopthr:
120
+ fprev = f
121
+ gprev = g
122
+ # Iteration
123
+ f = eps * np.log(a) \
124
+ - eps * np.log( np.sum( np.exp( ( f.reshape(-1,1) + g.reshape(1,-1) - C ) / eps ), axis=1 ) \
125
+ + np.exp( ( r + f ) / eps ) ) + f
126
+ g = eps * np.log(b) \
127
+ - eps * np.log( np.sum( np.exp( ( f.reshape(-1,1) + g.reshape(1,-1) - C ) / eps ), axis=0 ) \
128
+ + np.exp( ( s + g ) / eps ) ) + g
129
+ r = - eps * wrightomega( f/eps - np.log( eps/m ) ).real
130
+ s = - eps * wrightomega( g/eps - np.log( eps/m ) ).real
131
+ # Check relative error
132
+ if niter % 10 == 0:
133
+ err_f = abs(f - fprev).max() / max(abs(f).max(), abs(fprev).max(), 1.)
134
+ err_g = abs(g - gprev).max() / max(abs(g).max(), abs(gprev).max(), 1.)
135
+ err = 0.5 * (err_f + err_g)
136
+ niter = niter + 1
137
+ if verbose:
138
+ print('Number of iterations in unot:', niter)
139
+ P = np.exp( ( f.reshape(-1,1) + g.reshape(1,-1) - C ) / eps )
140
+ return P
141
+
142
+ def unot_sinkhorn_l1_dense(a,b,C,eps,m,nitermax=10000,stopthr=1e-8,verbose=False,output_fg=False):
143
+ """ Solve the unnormalized optimal transport with l1 penalty in dense matrix format.
144
+
145
+ Parameters
146
+ ----------
147
+ a : (ns,) numpy.ndarray
148
+ Source distribution. The summation should be less than or equal to 1.
149
+ b : (nt,) numpy.ndarray
150
+ Target distribution. The summation should be less than or equal to 1.
151
+ C : (ns,nt) numpy.ndarray
152
+ The cost matrix possibly with infinity entries.
153
+ eps : float
154
+ The coefficient for entropy regularization.
155
+ m : float
156
+ The coefficient for penalizing unmatched mass.
157
+ nitermax : int, optional
158
+ The max number of iterations. Defaults to 10000.
159
+ stopthr : float, optional
160
+ The threshold for terminating the iteration. Defaults to 1e-8.
161
+
162
+ Returns
163
+ -------
164
+ (ns,nt) numpy.ndarray
165
+ The optimal transport matrix.
166
+ """
167
+ f = np.zeros_like(a)
168
+ g = np.zeros_like(b)
169
+ niter = 0
170
+ err = 100
171
+ while niter <= nitermax and err > stopthr:
172
+ fprev = f
173
+ gprev = g
174
+ # Iteration
175
+ f = eps * np.log(a) \
176
+ - eps * np.log( np.sum( np.exp( ( f.reshape(-1,1) + g.reshape(1,-1) - C ) / eps ), axis=1 ) \
177
+ + np.exp( ( -m + f ) / eps ) ) + f
178
+ g = eps * np.log(b) \
179
+ - eps * np.log( np.sum( np.exp( ( f.reshape(-1,1) + g.reshape(1,-1) - C ) / eps ), axis=0 ) \
180
+ + np.exp( ( -m + g ) / eps ) ) + g
181
+ # Check relative error
182
+ if niter % 10 == 0:
183
+ err_f = abs(f - fprev).max() / max(abs(f).max(), abs(fprev).max(), 1.)
184
+ err_g = abs(g - gprev).max() / max(abs(g).max(), abs(gprev).max(), 1.)
185
+ err = 0.5 * (err_f + err_g)
186
+ niter = niter + 1
187
+ if verbose:
188
+ print('Number of iterations in unot:', niter)
189
+ P = np.exp( ( f.reshape(-1,1) + g.reshape(1,-1) - C ) / eps )
190
+ if output_fg:
191
+ return f,g
192
+ else:
193
+ return P
194
+
195
+ def unot_barycenter_sinkhorn_l1_dense(a,C,eps,m,w,nitermax=5):
196
+ L = len(a)
197
+ n = len(a[0])
198
+ f,g = {},{}
199
+ for k in range(L):
200
+ f[k] = np.zeros([n],float)
201
+ g[k] = np.zeros([n],float)
202
+
203
+ for i in range(nitermax):
204
+ for k in range(L):
205
+ f[k] = eps * np.log(a[k]) \
206
+ - eps * np.log( np.sum( np.exp( ( f[k].reshape(-1,1) + g[k].reshape(1,-1) - C ) / eps ), axis=1 ) #) + f[k] #\
207
+ + np.exp( ( -m + f[k] ) / eps ) ) + f[k]
208
+ Lnu = np.zeros([n],float)
209
+ for k in range(L):
210
+ Lnu = Lnu + w[k] * np.log( np.sum( np.exp( ( f[k].reshape(-1,1) + g[k].reshape(1,-1) - C ) / eps ), axis=0 ))
211
+ for k in range(L):
212
+ g[k] = eps * Lnu \
213
+ - eps * np.log( np.sum( np.exp( ( f[k].reshape(-1,1) + g[k].reshape(1,-1) - C ) / eps ), axis=0 ) #) + g[k] #\
214
+ + np.exp( ( -m + g[k] ) / eps ) ) + g[k]
215
+ return(np.exp(Lnu))
216
+
217
+ def regular_barycenter(a,C,eps,w,nitermax=10000):
218
+ L = len(a)
219
+ n = len(a[0])
220
+ f,g = {},{}
221
+ for k in range(L):
222
+ f[k] = np.zeros([n],float)
223
+ g[k] = np.zeros([n],float)
224
+
225
+ for i in range(nitermax):
226
+ for k in range(L):
227
+ f[k] = eps * np.log(a[k]) \
228
+ - eps * np.log( np.sum( np.exp( ( f[k].reshape(-1,1) + g[k].reshape(1,-1) - C ) / eps ), axis=1 ) ) + f[k]
229
+ Lnu = np.zeros([n],float)
230
+ for k in range(L):
231
+ Lnu = Lnu + w[k] * np.log( np.sum( np.exp( ( f[k].reshape(-1,1) + g[k].reshape(1,-1) - C ) / eps ), axis=0 ))
232
+ for k in range(L):
233
+ g[k] = eps * Lnu \
234
+ - eps * np.log( np.sum( np.exp( ( f[k].reshape(-1,1) + g[k].reshape(1,-1) - C ) / eps ), axis=0 ) ) + g[k]
235
+ return(np.exp(Lnu))
236
+
237
+ def unot_sinkhorn_l2_sparse(a,b,C,eps,m,nitermax=10000,stopthr=1e-8,verbose=False):
238
+ """ Solve the unnormalized optimal transport with l2 penalty in sparse matrix format.
239
+
240
+ Parameters
241
+ ----------
242
+ a : (ns,) numpy.ndarray
243
+ Source distribution. The summation should be less than or equal to 1.
244
+ b : (nt,) numpy.ndarray
245
+ Target distribution. The summation should be less than or equal to 1.
246
+ C : (ns,nt) scipy.sparse.coo_matrix
247
+ The cost matrix in coo sparse format. The entries exceeds the cost cutoff are omitted. The naturally zero entries should be explicitely included.
248
+ eps : float
249
+ The coefficient for entropy regularization.
250
+ m : float
251
+ The coefficient for penalizing unmatched mass.
252
+ nitermax : int, optional
253
+ The max number of iterations. Defaults to 10000.
254
+ stopthr : float, optional
255
+ The threshold for terminating the iteration. Defaults to 1e-8.
256
+
257
+ Returns
258
+ -------
259
+ (ns,nt) scipy.sparse.coo_matrix
260
+ The optimal transport matrix. The locations of entries should agree with C and there might by explicit zero entries.
261
+ """
262
+ tmp_K = C.copy()
263
+ f = np.zeros_like(a)
264
+ g = np.zeros_like(b)
265
+ r = np.zeros_like(a)
266
+ s = np.zeros_like(b)
267
+ niter = 0
268
+ err = 100
269
+ while niter <= nitermax and err > stopthr:
270
+ fprev = f
271
+ gprev = g
272
+ # Iteration
273
+ tmp_K.data = np.exp( ( -C.data + f[C.row] + g[C.col] ) / eps )
274
+ f = eps * np.log(a) \
275
+ - eps * np.log( np.sum( tmp_K, axis=1 ).A.reshape(-1) \
276
+ + np.exp( ( r + f ) / eps ) ) + f
277
+ tmp_K.data = np.exp( ( -C.data + f[C.row] + g[C.col] ) / eps )
278
+ g = eps * np.log(b) \
279
+ - eps * np.log( np.sum( tmp_K, axis=0 ).A.reshape(-1) \
280
+ + np.exp( ( s + g ) / eps ) ) + g
281
+ r = - eps * wrightomega( f/eps - np.log( eps/m ) ).real
282
+ s = - eps * wrightomega( g/eps - np.log( eps/m ) ).real
283
+ # Check relative error
284
+ if niter % 10 == 0:
285
+ err_f = abs(f - fprev).max() / max(abs(f).max(), abs(fprev).max(), 1.)
286
+ err_g = abs(g - gprev).max() / max(abs(g).max(), abs(gprev).max(), 1.)
287
+ err = 0.5 * (err_f + err_g)
288
+ niter = niter + 1
289
+ if verbose:
290
+ print('Number of iterations in unot:', niter)
291
+ tmp_K.data = np.exp( ( -C.data + f[C.row] + g[C.col] ) / eps )
292
+ return tmp_K
293
+
294
+ def unot_sinkhorn_l1_sparse(a,b,q,C,eps,m,lam,nitermax=10000,stopthr=1e-8,verbose=False):
295
+ """ Solve the unnormalized optimal transport with l1 penalty in sparse matrix format.
296
+
297
+ Parameters
298
+ ----------
299
+ a : (ns,) numpy.ndarray
300
+ Source distribution. The summation should be less than or equal to 1.
301
+ b : (nt,) numpy.ndarray
302
+ Target distribution. The summation should be less than or equal to 1.
303
+ q : (nt,) numpy.ndarray
304
+ intra signal distribution.
305
+ C : (ns,nt) scipy.sparse.coo_matrix
306
+ The cost matrix in coo sparse format. The entries exceeds the cost cutoff are omitted. The naturally zero entries should be explicitely included.
307
+ eps : float
308
+ The coefficient for entropy regularization.
309
+ m : float
310
+ The coefficient for penalizing unmatched mass.
311
+ lam : float
312
+ The coefficient for KL divergence between inter- and intra-signal distributions.
313
+ nitermax : int, optional
314
+ The max number of iterations. Defaults to 10000.
315
+ stopthr : float, optional
316
+ The threshold for terminating the iteration. Defaults to 1e-8.
317
+
318
+ Returns
319
+ -------
320
+ (ns,nt) scipy.sparse.coo_matrix
321
+ The optimal transport matrix. The locations of entries should agree with C and there might by explicit zero entries.
322
+ """
323
+ tmp_K = C.copy()
324
+ f = np.zeros_like(a)
325
+ f1 = np.full_like(a, m)
326
+ g = np.zeros_like(b)
327
+ r = np.zeros_like(a)
328
+ s = np.zeros_like(b)
329
+ niter = 0
330
+ err = 100
331
+ while niter <= nitermax and err > stopthr:
332
+ fprev = f
333
+ gprev = g
334
+ # Iteration
335
+ tmp_K.data = np.exp( ( -C.data + f[C.row] + g[C.col] ) / eps )
336
+ f2 = eps * np.log(a) \
337
+ - eps * np.log( np.sum( tmp_K, axis=1 ).A.reshape(-1) )\
338
+ + f
339
+ f = np.minimum(f1, f2)
340
+ tmp_K.data = np.exp( ( -C.data + f[C.row] + g[C.col] ) / eps )
341
+ g1 = m * eps / (eps+lam) + eps * lam * np.log(q) / (eps+lam) \
342
+ - eps *lam * np.log( np.sum( tmp_K, axis=0 ).A.reshape(-1)) /(eps+lam) \
343
+ + lam * g / (eps+lam)
344
+ g2 = eps * np.log(b) \
345
+ - eps * np.log( np.sum( tmp_K, axis=0 ).A.reshape(-1) \
346
+ ) + g
347
+ g = np.minimum(g1, g2)
348
+ # Check relative error
349
+ if niter % 10 == 0:
350
+ err_f = abs(f - fprev).max() / max(abs(f).max(), abs(fprev).max(), 1.)
351
+ err_g = abs(g - gprev).max() / max(abs(g).max(), abs(gprev).max(), 1.)
352
+ err = 0.5 * (err_f + err_g)
353
+ niter = niter + 1
354
+
355
+ if verbose:
356
+ print('Number of iterations in unot:', niter)
357
+ tmp_K.data = np.exp( ( -C.data + f[C.row] + g[C.col] ) / eps )
358
+
359
+ return tmp_K
360
+
361
+ def unot_nesterov_l2_dense(a,b,C,eps1,eps2,m,nitermax=10000,stopthr=1e-8):
362
+ dt = 0.01
363
+ f = np.zeros_like(a)
364
+ g = np.zeros_like(b)
365
+ f_old = np.array(f)
366
+ g_old = np.array(g)
367
+ F_old = np.array(f)
368
+ G_old = np.array(g)
369
+ niter = 0
370
+ err = 100
371
+ def Qf(ff,gg,ee1,ee2,mm,aa,bb,CC):
372
+ out = np.exp(ff/ee1) * np.sum(np.exp((gg.reshape(1,-1)-CC)/ee1), axis=1) \
373
+ + ee2 * wrightomega( ff*mm/ee2 - np.log( ee2/mm ) ).real / mm - aa
374
+ return out
375
+ def Qg(ff,gg,ee1,ee2,mm,aa,bb,CC):
376
+ out = np.exp(gg/ee1) * np.sum(np.exp((ff.reshape(-1,1)-CC)/ee1), axis=0) \
377
+ + ee2 * wrightomega( gg*mm/ee2 - np.log( ee2/mm ) ).real / mm - bb
378
+ return out
379
+ while niter <= nitermax and err > stopthr:
380
+ f = F_old - dt * Qf(F_old, G_old, eps1, eps2, m, a, b, C)
381
+ F = f + float(niter)/(niter+3.0) * (f-f_old)
382
+ g = G_old - dt * Qg(F_old, G_old, eps1, eps2, m, a, b, C)
383
+ G = g + float(niter)/(niter+3.0) * (g-g_old)
384
+ if niter % 10 == 0:
385
+ err_f = abs(f - f_old).max() / max(abs(f).max(), abs(f_old).max(), 1.)
386
+ err_g = abs(g - g_old).max() / max(abs(g).max(), abs(g_old).max(), 1.)
387
+ err = 0.5 * (err_f + err_g)
388
+ f_old[:] = f[:]; F_old[:] = F[:]
389
+ g_old[:] = g[:]; G_old[:] = G[:]
390
+ niter += 1
391
+ P = np.exp((f.reshape(-1,1)+g.reshape(1,-1)-C)/eps1)
392
+ return P
393
+
394
+ def unot_momentum_l2_dense(a,b,C,eps_p,eps_mu,eps_nu,m,nitermax=1e4,stopthr=1e-8,dt=0.01,beta=0.8):
395
+ f = np.zeros_like(a)
396
+ g = np.zeros_like(b)
397
+ f_old = np.array(f)
398
+ g_old = np.array(g)
399
+ F_old = np.array(f)
400
+ G_old = np.array(g)
401
+ niter = 0
402
+ err = 100
403
+ def Qf(ff,gg,ee_p,ee_mu,ee_nu,mm,aa,bb,CC):
404
+ out = np.exp(ff/ee_p) * np.sum(np.exp((gg.reshape(1,-1)-CC)/ee_p), axis=1) \
405
+ + ee_mu * wrightomega( ff/ee_mu - np.log( ee_mu/mm ) ).real / mm - aa
406
+ return out
407
+ def Qg(ff,gg,ee_p,ee_mu,ee_nu,mm,aa,bb,CC):
408
+ out = np.exp(gg/ee_p) * np.sum(np.exp((ff.reshape(-1,1)-CC)/ee_p), axis=0) \
409
+ + ee_nu * wrightomega( gg/ee_nu - np.log( ee_nu/mm ) ).real / mm - bb
410
+ return out
411
+ while niter <= nitermax and err > stopthr:
412
+ F = beta * F_old + Qf(f_old, g_old, eps_p, eps_mu, eps_nu, m, a, b, C)
413
+ f = f_old - dt * F
414
+ G = beta * G_old + Qg(f_old, g_old, eps_p, eps_mu, eps_nu, m, a, b, C)
415
+ g = g_old - dt * G
416
+ f_old[:] = f[:]; F_old[:] = F[:]
417
+ g_old[:] = g[:]; G_old[:] = G[:]
418
+ niter += 1
419
+ P = np.exp((f.reshape(-1,1)+g.reshape(1,-1)-C)/eps_p)
420
+ return P
421
+
422
+ def unot_momentum_l1_dense(a,b,C,eps_p,eps_mu,eps_nu,m,nitermax=1e4,stopthr=1e-8,dt=0.01,beta=0.8,precondition=False,verbose=False):
423
+ f = np.zeros_like(a)
424
+ g = np.zeros_like(b)
425
+ if precondition:
426
+ f,g = unot_sinkhorn_l1_dense(a,b,C,eps_p,m,output_fg=True)
427
+ f_old = np.array(f)
428
+ g_old = np.array(g)
429
+ F_old = np.array(f)
430
+ G_old = np.array(g)
431
+ niter = 0
432
+ err = 100
433
+ def Qf(ff,gg,ee_p,ee_mu,ee_nu,mm,aa,bb,CC):
434
+ out = np.exp(ff/ee_p) * np.sum(np.exp((gg.reshape(1,-1)-CC)/ee_p), axis=1) \
435
+ + np.exp((ff-mm)/ee_mu) - aa
436
+ return out
437
+ def Qg(ff,gg,ee_p,ee_mu,ee_nu,mm,aa,bb,CC):
438
+ out = np.exp(gg/ee_p) * np.sum(np.exp((ff.reshape(-1,1)-CC)/ee_p), axis=0) \
439
+ + np.exp((gg-mm)/ee_nu) - bb
440
+ return out
441
+ while niter <= nitermax and err > stopthr:
442
+ F = beta * F_old + Qf(f_old, g_old, eps_p, eps_mu, eps_nu, m, a, b, C)
443
+ f = f_old - dt * F
444
+ G = beta * G_old + Qg(f_old, g_old, eps_p, eps_mu, eps_nu, m, a, b, C)
445
+ g = g_old - dt * G
446
+ if niter % 10 == 0:
447
+ err_f = abs(f - f_old).max() / max(abs(f).max(), abs(f_old).max(), 1.)
448
+ err_g = abs(g - g_old).max() / max(abs(g).max(), abs(g_old).max(), 1.)
449
+ err = 0.5 * (err_f + err_g)
450
+ f_old[:] = f[:]; F_old[:] = F[:]
451
+ g_old[:] = g[:]; G_old[:] = G[:]
452
+ niter += 1
453
+ P = np.exp((f.reshape(-1,1)+g.reshape(1,-1)-C)/eps_p)
454
+ if verbose:
455
+ print(niter)
456
+ return P
457
+
458
+ def unot_momentum_l1_2end_dense(a,b,C,eps_p,eps_mu,eps_nu,m,nitermax=1e4,stopthr=1e-8,dt=0.01,beta=0.8):
459
+ f = np.zeros_like(a)
460
+ g = np.zeros_like(b)
461
+ f_old = np.array(f)
462
+ g_old = np.array(g)
463
+ F_old = np.array(f)
464
+ G_old = np.array(g)
465
+ niter = 0
466
+ err = 100
467
+ def Qf(ff,gg,ee_p,ee_mu,ee_nu,mm,aa,bb,CC):
468
+ out = np.exp(ff/ee_p) * np.sum(np.exp((gg.reshape(1,-1)-CC)/ee_p), axis=1) \
469
+ + aa / (np.exp(-(ff-mm)/ee_mu)+1) - aa
470
+ return out
471
+ def Qg(ff,gg,ee_p,ee_mu,ee_nu,mm,aa,bb,CC):
472
+ out = np.exp(gg/ee_p) * np.sum(np.exp((ff.reshape(-1,1)-CC)/ee_p), axis=0) \
473
+ + bb / (np.exp(-(gg-mm)/ee_nu)+1) - bb
474
+ return out
475
+ while niter <= nitermax and err > stopthr:
476
+ F = beta * F_old + Qf(f_old, g_old, eps_p, eps_mu, eps_nu, m, a, b, C)
477
+ f = f_old - dt * F
478
+ G = beta * G_old + Qg(f_old, g_old, eps_p, eps_mu, eps_nu, m, a, b, C)
479
+ g = g_old - dt * G
480
+ f_old[:] = f[:]; F_old[:] = F[:]
481
+ g_old[:] = g[:]; G_old[:] = G[:]
482
+ niter += 1
483
+ P = np.exp((f.reshape(-1,1)+g.reshape(1,-1)-C)/eps_p)
484
+ print(niter)
485
+ return P
@@ -0,0 +1,117 @@
1
+ import numpy as np
2
+ import ot
3
+
4
+ def uot(mu, nu, c, epsilon,
5
+ niter=50, tau=-0.5, verb = 1, rho = np.Inf, stopThr= 1E-7):
6
+
7
+ lmbda = rho / ( rho + epsilon )
8
+ if np.isinf(rho): lmbda = 1
9
+
10
+ mu = np.asarray(mu, float).reshape(-1,1)
11
+ nu = np.asarray(nu, float).reshape(-1,1)
12
+ N = [mu.shape[0], nu.shape[0]]
13
+ H1 = np.ones([N[0],1]); H2 = np.ones([N[1],1])
14
+
15
+ errs = []; Wprimal = []; Wdual = []
16
+ u = np.zeros([N[0],1], float)
17
+ v = np.zeros([N[1],1], float)
18
+ for i in range(niter):
19
+ u1 = u
20
+ u = ave(tau, u, \
21
+ lmbda * epsilon * np.log(mu) \
22
+ - lmbda * epsilon * lse( M(u,v,H1,H2,c,epsilon) ) \
23
+ + lmbda * u )
24
+ v = ave(tau, v, \
25
+ lmbda * epsilon * np.log(nu) \
26
+ - lmbda * epsilon * lse( M(u,v,H1,H2,c,epsilon).T ) \
27
+ + lmbda * v )
28
+ gamma = np.exp( M(u,v,H1,H2,c,epsilon) )
29
+
30
+ if np.isinf(rho):
31
+ Wprimal.append(np.sum(c * gamma) - epsilon*H(gamma) )
32
+ Wdual.append(np.sum(u*mu) + np.sum(v*nu) - epsilon*np.sum(gamma) )
33
+ err = np.linalg.norm( np.sum(gamma,axis=1) - mu )
34
+ errs.append( err )
35
+ else:
36
+ Wprimal.append(np.sum(c*gamma) - epsilon*H(gamma) \
37
+ + rho*KL(np.sum(gamma,axis=1), mu) \
38
+ + rho*KL(np.sum(gamma,axis=0), nu) )
39
+ Wdual.append(- rho*KLd(u/rho,mu) - rho*KLd(v/rho,nu) \
40
+ - epsilon*np.sum(gamma) )
41
+ err = np.linalg.norm(u-u1,1)
42
+ errs.append( err )
43
+ if err < stopThr and i > niter:
44
+ break
45
+
46
+ return gamma
47
+
48
+ def usot(mu, nu, c, c1, c2, alpha, epsilon = 0.1,
49
+ niter = 10, gw_loss = 'square', rho = np.Inf):
50
+
51
+ mu = np.asarray(mu, float).reshape(-1,1)
52
+ nu = np.asarray(nu, float).reshape(-1,1)
53
+ gamma0 = np.outer(mu, nu)
54
+ gamma_old = np.array(gamma0, float)
55
+ G = np.empty(c.shape, float)
56
+ for i in range(niter):
57
+ # Construct loss
58
+ G_w = ( 1.0 - alpha ) * c
59
+ if gw_loss == 'square':
60
+ fc1 = 0.5*c1**2; fc2 = 0.5*c2**2
61
+ hc1 = c1; hc2 = c2
62
+ constC1 = np.dot(np.dot(fc1, mu), np.ones(len(nu), float).reshape(1,-1))
63
+ constC2 = np.dot(np.ones(len(mu)).reshape(-1,1), np.dot(nu.reshape(1,-1),fc2.T))
64
+ constC = constC1 + constC2
65
+ G_gw = alpha * 2.0 * (constC - np.dot(hc1, gamma_old).dot(hc2.T))
66
+ G[:,:] = G_w[:,:] + G_gw[:,:]
67
+ if np.isinf(rho):
68
+ gamma_tuta = ot.sinkhorn(mu.reshape(-1), nu.reshape(-1), G, epsilon)
69
+ else:
70
+ gamma_tuta = uot(mu, nu, G, epsilon, rho = rho)
71
+ # Line search for update
72
+ CxC_tuta_minus_old = c1.dot(np.dot(gamma_tuta-gamma_old, c2))
73
+ CxC_old = c1.dot(np.dot(gamma_old, c2))
74
+ a = -alpha*np.sum( CxC_tuta_minus_old * ( gamma_tuta-gamma_old ) )
75
+ b = np.sum( ( (1.0-alpha)*c+alpha*constC-2.0*alpha*CxC_old ) * ( gamma_tuta-gamma_old) )
76
+ if a > 0:
77
+ tau_update = min(1.0,max(0.0,-0.5*b/a))
78
+ elif a + b < 0:
79
+ tau_update = 1.0
80
+ else:
81
+ tau_update = 0.0
82
+ gamma_new = (1.0-tau_update) * gamma_old + tau_update * gamma_tuta
83
+ gamma_old = gamma_new
84
+ return gamma_new
85
+
86
+ def ave(tau, u, u1):
87
+ return tau * u + ( 1 - tau ) * u1
88
+
89
+ def lse(A):
90
+ return np.log(np.sum(np.exp(A),axis=1)).reshape(-1,1)
91
+
92
+ def H(p):
93
+ return -np.sum( p * np.log(p+1E-20)-1 )
94
+
95
+ def KL(h,p):
96
+ return np.sum( h * np.log( h/p ) - h + p )
97
+
98
+ def KLd(u,p):
99
+ return np.sum( p * ( np.exp(-u) - 1 ) )
100
+
101
+ def M(u,v,H1,H2,c,epsilon):
102
+ y = -c + np.matmul(u.reshape(-1,1), H2.reshape(1,-1)) + \
103
+ np.matmul(H1.reshape(-1,1), v.reshape(1,-1))
104
+ return y/epsilon
105
+
106
+
107
+ def main():
108
+ print(uot([0.5,0.5],[0.5,0.5],np.array([[0.0,1.0],[1.0,0.0]]),0.1,rho=np.Inf))
109
+ a = np.ones(3)/3.0; b = a
110
+ c = np.array([[1,4,4],[4,1,4],[4,4,1]], float)
111
+ c1 = np.array([[0,10,0],[10,0,1],[0,1,0]], float)
112
+ c2 = np.array([[0,10,0],[10,0,0],[0,0,0]], float)
113
+ gamma = usot(a,b,c,c1,c2,0.5)
114
+ print(gamma)
115
+
116
+ if __name__ == "__main__":
117
+ main()
@@ -0,0 +1,20 @@
1
+ # __init__ file
2
+ from ._similarity import pairwise_scc
3
+ from ._similarity import partial_corr
4
+ from ._similarity import semipartial_corr
5
+ from ._similarity import treebased_score
6
+ from ._similarity import treebased_score_multifeature
7
+ from ._similarity import vf_diff
8
+ from ._similarity import d_graph_local_jaccard
9
+ from ._similarity import d_graph_local_jaccard_weighted
10
+ from ._similarity import d_graph_global_structure
11
+ from ._similarity import moranI_vector_global
12
+ from ._similarity import preprocess_vector_field
13
+ from ._plotting import plot_cluster_signaling_chord
14
+ from ._plotting import plot_cluster_signaling_network
15
+ from ._plotting import plot_cluster_signaling_network_multipair
16
+ from ._plotting import plot_cell_signaling
17
+ from ._plotting import plot_cell_signaling_compare
18
+ from ._plotting import get_cmap_qualitative
19
+ from ._clustering import leiden_clustering
20
+ from ._binarization import binarize_sparse_matrix
@@ -0,0 +1,43 @@
1
+ import numpy as np
2
+ from sklearn.cluster import KMeans
3
+ from sklearn.mixture import GaussianMixture
4
+
5
+ # %%
6
+ def binarize_sparse_matrix(
7
+ A,
8
+ method = None,
9
+ cutoff = 0,
10
+ random_state = 1,
11
+ append_zeros = 'full'
12
+ ):
13
+ # A is a scipy sparse csr_matrix
14
+ # Anything smaller than or equal to the cutoff is set to 0.
15
+ A_binary = A.copy()
16
+ n = A.shape[0]
17
+ nnz = len(A.data)
18
+ tmp_data = A.data
19
+ if append_zeros == 'full':
20
+ tmp_zeros = np.zeros(n*n-nnz)
21
+ elif append_zeros == 'match':
22
+ tmp_zeros = np.zeros_like(tmp_data)
23
+ tmp_X = np.concatenate((tmp_data, tmp_zeros), axis=0)
24
+ if method == 'kmeans':
25
+ kmeans = KMeans(n_clusters=2, random_state=random_state).fit(tmp_X.reshape(-1,1))
26
+ cl_centers = kmeans.cluster_centers_.reshape(-1)
27
+ if cl_centers[1] < cl_centers[0]:
28
+ new_data = 1 - kmeans.labels_[:nnz]
29
+ else:
30
+ new_data = kmeans.labels_[:nnz]
31
+ elif method == 'gaussian_mixture':
32
+ gm = GaussianMixture(n_components=2, random_state=random_state).fit(tmp_X.reshape(-1,1))
33
+ cl_centers = gm.means_.reshape(-1)
34
+ labels = gm.predict(tmp_data.reshape(-1,1))
35
+ if cl_centers[1] < cl_centers[0]:
36
+ labels = 1 - labels
37
+ new_data = labels
38
+ new_data[np.where(tmp_data <= cutoff)] = 0
39
+ A_binary.data[:] = new_data[:]
40
+ A_binary.eliminate_zeros()
41
+
42
+ return A_binary
43
+ # %%