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,1250 @@
1
+ from typing import Optional
2
+ import gc
3
+ import ot
4
+ import sys
5
+ import anndata
6
+ import numpy as np
7
+ import pandas as pd
8
+ import scanpy as sc
9
+ from matplotlib import cm
10
+ import matplotlib.pyplot as plt
11
+ import plotly
12
+ from scipy import sparse
13
+ from scipy.spatial import distance_matrix
14
+ from scipy.stats import spearmanr, pearsonr
15
+ from sklearn.preprocessing import normalize
16
+ from scipy.spatial import cKDTree
17
+
18
+ from .._optimal_transport import cot_sparse
19
+ from .._optimal_transport import cot_combine_sparse
20
+ from .._optimal_transport import uot
21
+ from .._optimal_transport import usot
22
+ from .._optimal_transport import generate_ggi_res, generate_tf_res, generate_tf_gene_all, random_walk_vectorized, calculate_TF_scores
23
+
24
+ def kernel_function(x, eta, nu, kernel, normalization=None):
25
+ if kernel == "exp":
26
+ phi = np.exp(-np.power(x/eta, nu))
27
+ elif kernel == "lorentz":
28
+ phi = 1 / ( 1 + np.power(x/eta, nu) )
29
+ if normalization == "unit_row_sum":
30
+ phi = (phi.T / np.sum(phi.T, axis=0)).T
31
+ elif normalization == "unit_col_sum":
32
+ phi = phi / np.sum(phi, axis=0)
33
+ return phi
34
+
35
+ def coo_from_dense_submat(row, col, x, shape):
36
+ col_ind, row_ind = np.meshgrid(col, row)
37
+ sparse_mat = sparse.coo_matrix((x.reshape(-1), (row_ind.reshape(-1), col_ind.reshape(-1))), shape=shape)
38
+ sparse_mat.eliminate_zeros()
39
+ return(sparse_mat)
40
+
41
+ class CellCommunication(object):
42
+ def __init__(self,
43
+ adata,
44
+ df_ligrec,
45
+ ggi_tf,
46
+ co_exp_ratio,
47
+ max_hop,
48
+ dmat,
49
+ dis_thr,
50
+ cost_scale,
51
+ cost_type,
52
+ heteromeric = None,
53
+ heteromeric_rule = 'min',
54
+ heteromeric_delimiter = '_'
55
+ ):
56
+ data_genes = set(adata.var_names)
57
+
58
+ if not heteromeric:
59
+ self.ligs = list(set(df_ligrec.iloc[:,0]).intersection(data_genes))
60
+ self.recs = list(set(df_ligrec.iloc[:,1]).intersection(data_genes))
61
+ A = np.inf * np.ones([len(self.ligs), len(self.recs)], float)
62
+ for i in range(len(df_ligrec)):
63
+ tmp_lig = df_ligrec.iloc[i][0]
64
+ tmp_rec = df_ligrec.iloc[i][1]
65
+ if tmp_lig in self.ligs and tmp_rec in self.recs:
66
+ if cost_scale is None:
67
+ A[self.ligs.index(tmp_lig), self.recs.index(tmp_rec)] = 1.0
68
+ else:
69
+ A[self.ligs.index(tmp_lig), self.recs.index(tmp_rec)] = cost_scale[(tmp_lig, tmp_rec)]
70
+ self.A = A
71
+ self.S = adata[:,self.ligs].X.toarray()
72
+ self.D = adata[:,self.recs].X.toarray()
73
+ Q = []
74
+ self.receptor_tf_tables = {} # receptor → TF-target genes DataFrame with probability from receptor to TF
75
+ self.rec_tf_score_tables = pd.DataFrame({ "cell_id":adata.obs_names}) # receptor → TF score is sum of (TF gene expression * probability from receptor to TF * sum of target gene expression) over all TF
76
+
77
+ for i in range(len(self.recs)): # for each receptor
78
+ receptor_name = self.recs[i]
79
+ print("receptor:", receptor_name)
80
+ ggi_res = generate_ggi_res(ggi_tf, receptor_name, adata, max_hop, co_exp_ratio)
81
+ if len(ggi_res) > 0:
82
+ tf_gene_all = generate_tf_gene_all(ggi_res, max_hop) # Dict: {gene_name: hop}
83
+
84
+ # Convert to DataFrame and drop duplicates
85
+ tf_gene_df = pd.DataFrame(list(tf_gene_all.items()), columns=["gene", "hop"]).drop_duplicates()
86
+ tf_gene_all = dict(zip(tf_gene_df["gene"], tf_gene_df["hop"]))
87
+
88
+ ggi_res["dest_tf_enrich"] = "NO"
89
+ if tf_gene_all:
90
+ dest_match = ggi_res["dest"].isin(tf_gene_all.keys())
91
+ ggi_res.loc[dest_match, "dest_tf_enrich"] = "YES"
92
+ receptor_tf_temp = generate_tf_res(tf_gene_all, receptor_name, ggi_res) #add the no. of steps from receptor to TFs & add the names of target genes of TFs
93
+ normalized_scores = random_walk_vectorized(receptor_tf_temp, ggi_res, max_hop)
94
+ receptor_tf_temp["score"] = receptor_tf_temp["tf"].map(normalized_scores)
95
+ print("rep to each TF prob.", receptor_tf_temp)
96
+ self.receptor_tf_tables[receptor_name] = receptor_tf_temp.copy()
97
+
98
+ tf_score_vector = calculate_TF_scores(adata, receptor_tf_temp)
99
+ print("rep score.", tf_score_vector)
100
+ self.rec_tf_score_tables[receptor_name] = tf_score_vector.copy()
101
+
102
+ if tf_score_vector:
103
+ tem_tf_score_vector= tf_score_vector
104
+ else:
105
+ tem_tf_score_vector = np.zeros((adata.n_obs, 1))
106
+ Q.append(tem_tf_score_vector)
107
+ self.Q = np.hstack(Q) # shape (n_cells, len(self.recs))
108
+
109
+
110
+ elif heteromeric:
111
+ tmp_ligs = list(set(df_ligrec.iloc[:,0]))
112
+ tmp_recs = list(set(df_ligrec.iloc[:,1]))
113
+ avail_ligs = []
114
+ avail_recs = []
115
+ for tmp_lig in tmp_ligs:
116
+ lig_genes = set(tmp_lig.split(heteromeric_delimiter))
117
+ if lig_genes.issubset(data_genes):
118
+ avail_ligs.append(tmp_lig)
119
+ for tmp_rec in tmp_recs:
120
+ rec_genes = set(tmp_rec.split(heteromeric_delimiter))
121
+ if rec_genes.issubset(data_genes):
122
+ avail_recs.append(tmp_rec)
123
+ self.ligs = avail_ligs
124
+ self.recs = avail_recs
125
+ A = np.inf * np.ones([len(self.ligs), len(self.recs)], float)
126
+ for i in range(len(df_ligrec)):
127
+ tmp_lig = df_ligrec.iloc[i,0]
128
+ tmp_rec = df_ligrec.iloc[i,1]
129
+ if tmp_lig in self.ligs and tmp_rec in self.recs:
130
+ if cost_scale is None:
131
+ A[self.ligs.index(tmp_lig), self.recs.index(tmp_rec)] = 1.0
132
+ else:
133
+ A[self.ligs.index(tmp_lig), self.recs.index(tmp_rec)] = cost_scale[(tmp_lig, tmp_rec)]
134
+ self.A = A
135
+ ncell = adata.shape[0]
136
+ S = np.zeros([ncell, A.shape[0]], float)
137
+ D = np.zeros([ncell, A.shape[1]], float)
138
+ Q = []
139
+ self.receptor_tf_tables = {} # receptor → TF-target genes DataFrame with probability from receptor to TF
140
+ self.rec_tf_score_tables = pd.DataFrame({ "cell_id":adata.obs_names}) # receptor → TF score is sum of (TF gene expression * probability from receptor to TF * sum of target gene expression) over all TF
141
+ for i in range(len(self.ligs)):
142
+ tmp_lig = self.ligs[i]
143
+ lig_genes = tmp_lig.split(heteromeric_delimiter)
144
+ if heteromeric_rule == 'min':
145
+ S[:,i] = adata[:, lig_genes].X.toarray().min(axis=1)[:]
146
+ elif heteromeric_rule == 'ave':
147
+ S[:,i] = adata[:, lig_genes].X.toarray().mean(axis=1)[:]
148
+
149
+
150
+ for i in range(len(self.recs)): # for each receptor complex
151
+ tmp_rec = self.recs[i]
152
+ print("receptor:", tmp_rec)
153
+ rec_genes = tmp_rec.split(heteromeric_delimiter)
154
+ if heteromeric_rule == 'min':
155
+ D[:,i] = adata[:, rec_genes].X.toarray().min(axis=1)[:]
156
+ elif heteromeric_rule == 'ave':
157
+ D[:,i] = adata[:, rec_genes].X.toarray().mean(axis=1)[:]
158
+ tf_score_list = []
159
+ for receptor_name in rec_genes: # for each sub-receptor
160
+ ggi_res = generate_ggi_res(ggi_tf, receptor_name, adata, max_hop, co_exp_ratio)
161
+ if len(ggi_res) > 0:
162
+ tf_gene_all = generate_tf_gene_all(ggi_res, max_hop) # Dict: {gene_name: hop}
163
+
164
+ # Convert to DataFrame and drop duplicates
165
+ tf_gene_df = pd.DataFrame(list(tf_gene_all.items()), columns=["gene", "hop"]).drop_duplicates()
166
+ tf_gene_all = dict(zip(tf_gene_df["gene"], tf_gene_df["hop"]))
167
+
168
+ ggi_res["dest_tf_enrich"] = "NO"
169
+ if tf_gene_all:
170
+ dest_match = ggi_res["dest"].isin(tf_gene_all.keys())
171
+ ggi_res.loc[dest_match, "dest_tf_enrich"] = "YES"
172
+ receptor_tf_temp = generate_tf_res(tf_gene_all, receptor_name, ggi_res) #add the no. of steps from receptor to TFs & add the names of target genes of TFs
173
+ normalized_scores = random_walk_vectorized(receptor_tf_temp, ggi_res, max_hop)
174
+ receptor_tf_temp["score"] = receptor_tf_temp["tf"].map(normalized_scores)
175
+ print("rep to TF prob.", receptor_tf_temp)
176
+ self.receptor_tf_tables[receptor_name] = receptor_tf_temp.copy()
177
+ tf_score_vector = calculate_TF_scores(adata, receptor_tf_temp)
178
+ tf_score_list.append(tf_score_vector)
179
+ print("rep to TF score.", tf_score_vector)
180
+ self.rec_tf_score_tables[receptor_name] = tf_score_vector.copy()
181
+
182
+ if tf_score_list:
183
+ if heteromeric_rule == 'min':
184
+ # Stack vertically and then take element-wise minimum across columns (axis=1)
185
+ stacked_scores = np.hstack(tf_score_list) # shape (n_cells, n_receptors)
186
+ # Take min across the columns (receptors) for each cell (row)
187
+ tem_tf_score_vector= np.min(stacked_scores, axis=1).reshape(-1, 1) # shape (n_cells, 1)
188
+ # Result: one vector, min TF score per cell across receptors
189
+ elif heteromeric_rule == 'ave':
190
+ # Default behavior: concatenate horizontally to get matrix
191
+ tem_tf_score_vector= np.mean(stacked_scores, axis=1).reshape(-1, 1) # shape (n_cells, 1)
192
+ else:
193
+ tem_tf_score_vector = np.zeros((adata.n_obs, 1))
194
+ Q.append(tem_tf_score_vector)
195
+
196
+ self.S = S
197
+ self.D = D
198
+ self.Q = np.hstack(Q) # shape (n_cells, len(self.recs))
199
+
200
+ if self.Q.shape == self.D.shape:
201
+ print("Q and D have the same shape:", self.Q.shape)
202
+ else:
203
+ print("Q and D have different shapes.")
204
+ print("Q shape:", self.Q.shape)
205
+ print("D shape:", D.shape)
206
+ # check min and max before scaling
207
+ print("min(Q) before scaling:", np.min(self.Q))
208
+ print("max(Q) before scaling:", np.max(self.Q))
209
+ # Q_scaled = (self.Q - np.min(self.Q)) / (np.max(self.Q) - np.min(self.Q)) # scale to [0,1]
210
+ # Q_scaled = Q_scaled * (np.max(self.D) - np.min(self.D)) + np.min(self.D) # scale to [min(D), max(D)]
211
+ # self.Q = Q_scaled # scale Q to have same range of D
212
+
213
+ # print("min(Q) after scaling:", np.min(self.Q))
214
+ # print("max(Q) after scaling:", np.max(self.Q))
215
+ print("min(D):", np.min(self.D))
216
+ print("max(D):", np.max(self.D))
217
+
218
+ print("Check min equal:", np.isclose(np.min(self.Q), np.min(self.D)))
219
+ print("Check max equal:", np.isclose(np.max(self.Q), np.max(self.D)))
220
+
221
+
222
+
223
+ if cost_type == 'euc':
224
+ self.M = dmat
225
+ elif cost_type == 'euc_square':
226
+ # self.M = dmat ** 2
227
+ self.M = dmat.power(2)
228
+ if np.isscalar(dis_thr):
229
+ if cost_type == 'euc_square':
230
+ dis_thr = dis_thr ** 2
231
+ self.cutoff = float(dis_thr) * np.ones_like(A)
232
+ elif type(dis_thr) is dict:
233
+ self.cutoff = np.zeros_like(A)
234
+ for i in range(A.shape[0]):
235
+ for j in range(A.shape[1]):
236
+ if A[i,j] > 0:
237
+ if cost_type == 'euc_square':
238
+ self.cutoff[i,j] = dis_thr[(self.ligs[i], self.recs[j])] ** 2
239
+ else:
240
+ self.cutoff[i,j] = dis_thr[(self.ligs[i], self.recs[j])]
241
+ self.nlig = self.S.shape[1]; self.nrec = self.D.shape[1]
242
+ self.npts = adata.shape[0]
243
+
244
+ def run_cot_signaling(self,
245
+ cot_eps_p=1e-1,
246
+ cot_eps_mu=None,
247
+ cot_eps_nu=None,
248
+ cot_rho=1e1,
249
+ cot_lam=1e1,
250
+ cot_nitermax=1e4,
251
+ cot_weights=(0.25,0.25,0.25,0.25),
252
+ smooth=False,
253
+ smth_eta=None,
254
+ smth_nu=None,
255
+ smth_kernel=None
256
+ ):
257
+ if not smooth:
258
+ self.comm_network,self.C = cot_combine_sparse(self.S, self.D, self.Q, self.A, self.M, self.cutoff, \
259
+ eps_p=cot_eps_p, eps_mu=cot_eps_mu, eps_nu=cot_eps_nu, rho=cot_rho, lam=cot_lam, weights=cot_weights, nitermax=cot_nitermax)
260
+ if smooth:
261
+ # Smooth the expression
262
+ S_smth = np.zeros_like(self.S)
263
+ D_smth = np.zeros_like(self.D)
264
+ Q_smth = np.zeros_like(self.Q)
265
+ for i in range(self.nlig):
266
+ nzind = np.where(self.S[:,i] > 0)[0]
267
+ phi = kernel_function(self.M[nzind,:][:,nzind], smth_eta, smth_nu, smth_kernel, normalization='unit_col_sum')
268
+ S_smth[nzind,i] = np.matmul( phi, self.S[nzind,i].reshape(-1,1) )[:,0]
269
+ for i in range(self.nrec):
270
+ nzind = np.where(self.D[:,i] > 0)[0]
271
+ phi = kernel_function(self.M[nzind,:][:,nzind], smth_eta, smth_nu, smth_kernel, normalization='unit_col_sum')
272
+ D_smth[nzind,i] = np.matmul( phi, self.D[nzind,i].reshape(-1,1) )[:,0]
273
+ Q_smth[nzind,i] = np.matmul( phi, self.Q[nzind,i].reshape(-1,1) )[:,0]
274
+ # Get the transport plans for the smoothed distributions
275
+ P_smth,self.C = cot_combine_sparse(S_smth, D_smth, Q_smth, self.A, self.M, self.cutoff, \
276
+ eps_p=cot_eps_p, eps_mu=cot_eps_mu, eps_nu=cot_eps_nu, rho=cot_rho, lam=cot_lam, weights=cot_weights, nitermax=cot_nitermax)
277
+ # Deconvolute back to original cells
278
+ self.comm_network = {}
279
+ for i in range(self.nlig):
280
+ S = self.S[:,i]
281
+ nzind_S = np.where(S > 0)[0]
282
+ phi_S = kernel_function(self.M[nzind_S,:][:,nzind_S], smth_eta, smth_nu, smth_kernel, normalization='unit_col_sum')
283
+ S_contrib = phi_S * S[nzind_S]; S_contrib = S_contrib / np.sum(S_contrib, axis=1, keepdims=True)
284
+ for j in range(self.nrec):
285
+ D = self.D[:,j]
286
+ nzind_D = np.where(D > 0)[0]
287
+ if np.isinf(self.A[i,j]): continue
288
+ P_dense = P_smth[(i,j)].toarray()
289
+ P_sub = P_dense[nzind_S,:][:,nzind_D]
290
+ phi_D = kernel_function(self.M[nzind_D,:][:,nzind_D], smth_eta, smth_nu, smth_kernel, normalization='unit_col_sum')
291
+ D_contrib = phi_D * D[nzind_D]; D_contrib = D_contrib / np.sum(D_contrib, axis=1, keepdims=True)
292
+ P_deconv = np.matmul(S_contrib.T, np.matmul(P_sub, D_contrib))
293
+ for k in range(len(nzind_D)):
294
+ P_dense[nzind_S, nzind_D[k]] = P_deconv[:,k]
295
+ P_deconv_sparse = coo_from_dense_submat(nzind_S, nzind_D, P_deconv, shape=(self.npts, self.npts))
296
+ self.comm_network[(i,j)] = P_deconv_sparse
297
+
298
+ def smooth(self, eta, nu, kernel):
299
+ S_smth = np.zeros_like(self.S)
300
+ D_smth = np.zeros_like(self.D)
301
+ for i in range(self.nlig):
302
+ nzind = np.where(self.S[:,i] > 0)[0]
303
+ phi = kernel_function(self.M[nzind,:][:,nzind], eta, nu, kernel, normalization='unit_col_sum')
304
+ S_smth[nzind,i] = np.matmul( phi, self.S[nzind,i].reshape(-1,1) )[:,0]
305
+ for i in range(self.nrec):
306
+ nzind = np.where(self.D[:,i] > 0)[0]
307
+ phi = kernel_function(self.M[nzind,:][:,nzind], eta, nu, kernel, normalization='unit_col_sum')
308
+ D_smth[nzind,i] = np.matmul( phi, self.D[nzind,i].reshape(-1,1) )[:,0]
309
+ self.S_smth = S_smth
310
+ self.D_smth = D_smth
311
+ self.kernel_eta = eta
312
+ self.kernel_nu = nu
313
+ self.kernel = kernel
314
+
315
+ def assign_distance(adata, dmat=None):
316
+ if dmat is None:
317
+ adata.obsp["spatial_distance"] = distance_matrix(adata.obsm["spatial"], adata.obsm["spatial"])
318
+ else:
319
+ adata.obsp["spatial_distance"] = dmat
320
+
321
+ def summarize_cluster(X, clusterid, clusternames, n_permutations=500):
322
+ # Input a sparse matrix of cell signaling and output a pandas dataframe
323
+ # for cluster-cluster signaling
324
+ n = len(clusternames)
325
+ X_cluster = np.empty([n,n], float)
326
+ p_cluster = np.zeros([n,n], float)
327
+ for i in range(n):
328
+ tmp_idx_i = np.where(clusterid==clusternames[i])[0]
329
+ for j in range(n):
330
+ tmp_idx_j = np.where(clusterid==clusternames[j])[0]
331
+ X_cluster[i,j] = X[tmp_idx_i,:][:,tmp_idx_j].mean()
332
+ for i in range(n_permutations):
333
+ clusterid_perm = np.random.permutation(clusterid)
334
+ X_cluster_perm = np.empty([n,n], float)
335
+ for j in range(n):
336
+ tmp_idx_j = np.where(clusterid_perm==clusternames[j])[0]
337
+ for k in range(n):
338
+ tmp_idx_k = np.where(clusterid_perm==clusternames[k])[0]
339
+ X_cluster_perm[j,k] = X[tmp_idx_j,:][:,tmp_idx_k].mean()
340
+ p_cluster[X_cluster_perm >= X_cluster] += 1.0
341
+ p_cluster = p_cluster / n_permutations
342
+ df_cluster = pd.DataFrame(data=X_cluster, index=clusternames, columns=clusternames)
343
+ df_p_value = pd.DataFrame(data=p_cluster, index=clusternames, columns=clusternames)
344
+ return df_cluster, df_p_value
345
+
346
+ def cluster_center(adata, clustering, method="geometric_mean"):
347
+ X = adata.obsm['spatial']
348
+ cluster_pos = {}
349
+ clusternames = list( adata.obs[clustering].unique() )
350
+ clusternames.sort()
351
+ clusterid = np.array( adata.obs[clustering], str )
352
+ for name in clusternames:
353
+ tmp_idx = np.where(clusterid==name)[0]
354
+ tmp_X = X[tmp_idx]
355
+ if method == "geometric_mean":
356
+ X_mean = np.mean(tmp_X, axis=0)
357
+ elif method == "representative_point":
358
+ tmp_D = distance_matrix(tmp_X, tmp_X)
359
+ tmp_D = tmp_D ** 2
360
+ X_mean = tmp_X[np.argmin(tmp_D.sum(axis=1)),:]
361
+ cluster_pos[name] = X_mean
362
+ return cluster_pos
363
+
364
+ def spatial_communication(
365
+ adata: anndata.AnnData,
366
+ species: str = None,
367
+ database_name: str = None,
368
+ df_ligrec: pd.DataFrame = None,
369
+ pathways: pd.DataFrame = None,
370
+ co_exp_ratio: float = 1e-1,
371
+ pathway_sum: bool = False,
372
+ heteromeric: bool = False,
373
+ heteromeric_rule: str = 'min',
374
+ heteromeric_delimiter: str = '_',
375
+ dis_thr: Optional[float] = None,
376
+ cost_scale: Optional[dict] = None,
377
+ cost_type: str = 'euc',
378
+ cot_eps_p: float = 1e-1,
379
+ cot_eps_mu: Optional[float] = None,
380
+ cot_eps_nu: Optional[float] = None,
381
+ cot_rho: float =1e1,
382
+ cot_lam: float =1e1,
383
+ cot_nitermax: int = 10000,
384
+ cot_weights: tuple = (0.25,0.25,0.25,0.25),
385
+ smooth: bool = False,
386
+ smth_eta: float = None,
387
+ smth_nu: float = None,
388
+ smth_kernel: str = 'exp',
389
+ copy: bool = False
390
+ ):
391
+ """
392
+ Infer spatial communication.
393
+
394
+ Parameters
395
+ ----------
396
+ adata
397
+ The data matrix of shape ``n_obs`` × ``n_var``.
398
+ Rows correspond to cells or spots and columns to genes.
399
+ If the spatial distance is absent in ``.obsp['spatial_distance']``, Euclidean distance determined from ``.obsm['spatial']`` will be used.
400
+ species
401
+ Name of the species, either "Mouse" or others
402
+ database_name
403
+ Name of the ligand-receptor interaction database. Will be included in the keywords for anndata slots.
404
+ df_ligrec
405
+ A data frame where each row corresponds to a ligand-receptor pair with ligands, receptors, and the associated signaling pathways in the three columns, respectively.
406
+ pathways
407
+ A data frame of the system data containing gene-gene interactions and pathways from KEGG and Reactome as well as the information of transcriptional factors. Got it from SpaTalk.
408
+ co_exp_ratio
409
+ Min cell ratio in receiving cells with co-expressed source and target genes for predicting the downstream pathway activity.
410
+ pathway_sum
411
+ Whether to sum over all ligand-receptor pairs of each pathway.
412
+ heteromeric
413
+ Whether the ligands or receptors are made of heteromeric complexes.
414
+ heteromeric_rule
415
+ Use either 'min' (minimum) or 'ave' (average) expression of the components as the level for the heteromeric complex.
416
+ heteromeric_delimiter
417
+ The character in ligand and receptor names separating individual components.
418
+ dis_thr
419
+ The threshold of spatial distance of signaling.
420
+ cost_scale
421
+ Weight coefficients of the cost matrix for each ligand-receptor pair, e.g. cost_scale[('ligA','recA')] specifies weight for the pair ligA and recA.
422
+ If None, all pairs have the same weight.
423
+ cost_type
424
+ If 'euc', the original Euclidean distance will be used as cost matrix. If 'euc_square', the square of the Euclidean distance will be used.
425
+ cot_eps_p
426
+ The coefficient of entropy regularization for transport plan.
427
+ cot_eps_mu
428
+ The coefficient of entropy regularization for untransported source (ligand). Set to equal to cot_eps_p for fast algorithm.
429
+ cot_eps_nu
430
+ The coefficient of entropy regularization for unfulfilled target (receptor). Set to equal to cot_eps_p for fast algorithm.
431
+ cot_rho
432
+ The coefficient of penalty for unmatched mass.
433
+ cot_lam
434
+ The coefficient for KL divergence between inter- and intra-signal distributions.
435
+ cot_nitermax
436
+ Maximum iteration for collective optimal transport algorithm.
437
+ cot_weights
438
+ A tuple of four weights that add up to one. The weights corresponds to four setups of collective optimal transport:
439
+ 1) all ligands-all receptors, 2) each ligand-all receptors, 3) all ligands-each receptor, 4) each ligand-each receptor.
440
+ smooth
441
+ Whether to (spatially) smooth the gene expression for identifying more global signaling trend.
442
+ smth_eta
443
+ Kernel bandwidth for smoothing
444
+ smth_nu
445
+ Kernel sharpness for smoothing
446
+ smth_kernel
447
+ 'exp' exponential kernel. 'lorentz' Lorentz kernel.
448
+ copy
449
+ Whether to return a copy of the :class:`anndata.AnnData`.
450
+
451
+ Returns
452
+ -------
453
+ adata : anndata.AnnData
454
+ Signaling matrices are added to ``.obsp``, e.g., for a LR interaction database named "databaseX",
455
+ ``.obsp['comflow-databaseX-ligA-recA']``
456
+ is a ``n_obs`` × ``n_obs`` matrix with the *ij* th entry being the "score" of
457
+ cell *i* sending signal to cell *j* through ligA and recA. If ``pathway_sum==True``, the cell-by-cell signaling matrix for a pathway "pathwayX"
458
+ will be stored in ``.obsp['comflow-databaseX-pathwayX']``.
459
+ The marginal sums (sender and receiver) of the signaling matrices are stored in ``.obsm['comflow-databaseX-sum-sender']`` and ``.obsm['comflow-databaseX-sum-receiver']``.
460
+ Metadata of the analysis is added to ``.uns['comflow-databaseX-info']``.
461
+ If copy=True, return the AnnData object and return None otherwise.
462
+
463
+ Examples
464
+ --------
465
+ >>> import anndata
466
+ >>> import comflow as ct
467
+ >>> import pandas as pd
468
+ >>> import numpy as np
469
+ >>> # create a toy data with four cells and four genes
470
+ >>> X = np.array([[1,0,0,0],[2,0,0,0],[0,1,1,4],[0,3,4,1]], float)
471
+ >>> adata = anndata.AnnData(X=X, var=pd.DataFrame(index=['LigA','RecA','RecB','RecC']))
472
+ >>> adata.obsm['spatial'] = np.array([[0,0],[1,0],[0,1],[1,2]], float)
473
+ >>> # create a toy ligand-receptor database with two pairs sharing the same ligand
474
+ >>> df_ligrec = pd.DataFrame([['LigA','RecA_RecB'],['LigA','RecC']])
475
+ >>> df_ligrec = pd.DataFrame([['LigA','RecA_RecB','PathwayA'],['LigA','RecC','PathwayA']])
476
+ >>> # infer CCC with a distance threshold of 1.1. Due the threshold, the last cell won't be communicating with other cells.
477
+ >>> ct.tl.spatial_communication(adata, database_name='toyDB',df_ligrec=df_ligrec, pathway_sum=True, heteromeric=True, dis_thr=1.1)
478
+ >>> adata
479
+ AnnData object with n_obs × n_vars = 4 × 4
480
+ uns: 'comflow-toyDB-info'
481
+ obsm: 'spatial', 'comflow-toyDB-sum-sender', 'comflow-toyDB-sum-receiver'
482
+ obsp: 'comflow-toyDB-LigA-RecA_RecB', 'comflow-toyDB-LigA-RecC', 'comflow-toyDB-PathwayA', 'comflow-toyDB-total-total'
483
+ >>> print(adata.obsp['comflow-toyDB-LigA-RecA_RecB'])
484
+ (0, 2) 0.600000000000005
485
+ >>> print(adata.obsp['comflow-toyDB-LigA-RecC'])
486
+ (0, 2) 0.9000000000039632
487
+ >>> print(adata.obsm['comflow-toyDB-sum-receiver'])
488
+ r-LigA-RecA_RecB r-LigA-RecC r-total-total r-PathwayA
489
+ 0 0.0 0.0 0.0 0.0
490
+ 1 0.0 0.0 0.0 0.0
491
+ 2 0.6 0.9 1.5 1.5
492
+ 3 0.0 0.0 0.0 0.0
493
+ >>> print(adata.obsm['comflow-toyDB-sum-sender'])
494
+ s-LigA-RecA_RecB s-LigA-RecC s-total-total s-PathwayA
495
+ 0 0.6 0.9 1.5 1.5
496
+ 1 0.0 0.0 0.0 0.0
497
+ 2 0.0 0.0 0.0 0.0
498
+ 3 0.0 0.0 0.0 0.0
499
+ >>> print(adata.obsp['comflow-toyDB-PathwayA'])
500
+ (0, 2) 1.5000000000039682
501
+ >>> print(adata.obsp['comflow-toyDB-total-total'])
502
+ (0, 2) 1.5000000000039682
503
+ >>> adata.uns['comflow-toyDB-info']
504
+ {'df_ligrec': ligand receptor pathway
505
+ 0 LigA RecA_RecB PathwayA
506
+ 1 LigA RecC PathwayA, 'distance_threshold': 1.1}
507
+
508
+
509
+ """
510
+
511
+ assert database_name is not None, "Please give a database_name"
512
+ assert df_ligrec is not None, "Please give a ligand-receptor database"
513
+ assert pathways is not None, "Please give a pathway database"
514
+
515
+ if not 'spatial_distance' in adata.obsp.keys():
516
+ # dis_mat = distance_matrix(adata.obsm["spatial"], adata.obsm["spatial"])
517
+ coords = np.asarray(
518
+ adata.obsm["spatial"],
519
+ dtype=np.float32
520
+ )
521
+
522
+ n_cells = coords.shape[0]
523
+
524
+ # --------------------------------------------------
525
+ # 1. Determine maximum spatial cutoff
526
+ # --------------------------------------------------
527
+
528
+ if np.isscalar(dis_thr):
529
+ max_cutoff = float(dis_thr)
530
+
531
+ elif isinstance(dis_thr, dict):
532
+ max_cutoff = max(dis_thr.values())
533
+
534
+ else:
535
+ raise TypeError(
536
+ "dis_thr must be either a scalar or dictionary"
537
+ )
538
+
539
+ # --------------------------------------------------
540
+ # 2. Build spatial index
541
+ # --------------------------------------------------
542
+
543
+ tree = cKDTree(coords)
544
+ # --------------------------------------------------
545
+ # 3. Find ONLY cell pairs within max_cutoff
546
+ # --------------------------------------------------
547
+
548
+ pairs = tree.query_pairs(
549
+ r=max_cutoff,
550
+ output_type="ndarray"
551
+ )
552
+ # --------------------------------------------------
553
+ # 4. Calculate distances ONLY for these pairs
554
+ # --------------------------------------------------
555
+ row = pairs[:, 0]
556
+ col = pairs[:, 1]
557
+ dist = np.linalg.norm(
558
+ coords[row] - coords[col],
559
+ axis=1
560
+ ).astype(np.float32)
561
+
562
+ # --------------------------------------------------
563
+ # 5. Make symmetric
564
+ # --------------------------------------------------
565
+ M_row = np.concatenate([
566
+ row,
567
+ col
568
+ ])
569
+
570
+ M_col = np.concatenate([
571
+ col,
572
+ row
573
+ ])
574
+
575
+ M_dist = np.concatenate([
576
+ dist,
577
+ dist
578
+ ])
579
+ # --------------------------------------------------
580
+ # 6. Add diagonal: distance(cell, cell) = 0
581
+ # --------------------------------------------------
582
+
583
+ diag = np.arange(n_cells)
584
+
585
+ M_row = np.concatenate([
586
+ M_row,
587
+ diag
588
+ ])
589
+
590
+ M_col = np.concatenate([
591
+ M_col,
592
+ diag
593
+ ])
594
+
595
+ M_dist = np.concatenate([
596
+ M_dist,
597
+ np.zeros(n_cells, dtype=np.float32)
598
+ ])
599
+
600
+ # --------------------------------------------------
601
+ # 7. Construct sparse distance matrix directly
602
+ # --------------------------------------------------
603
+
604
+ M_max_sp = sparse.coo_matrix(
605
+ (M_dist, (M_row, M_col)),
606
+ shape=(n_cells, n_cells),
607
+ dtype=np.float32
608
+ )
609
+
610
+ # assign_distance(adata, dmat=None)
611
+ dis_mat = M_max_sp
612
+ else:
613
+ dis_mat = adata.obsp['spatial_distance']
614
+
615
+ # remove unavailable genes from df_ligrec
616
+ if not heteromeric:
617
+ data_genes = list(adata.var_names)
618
+ tmp_ligrec = []
619
+ for i in range(df_ligrec.shape[0]):
620
+ if df_ligrec.iloc[i][0] in data_genes and df_ligrec.iloc[i][1] in data_genes:
621
+ tmp_ligrec.append([df_ligrec.iloc[i][0], df_ligrec.iloc[i][1], df_ligrec.iloc[i][2]])
622
+ tmp_ligrec = np.array(tmp_ligrec, str)
623
+ df_ligrec = pd.DataFrame(data=tmp_ligrec)
624
+
625
+ elif heteromeric:
626
+ data_genes = set(list(adata.var_names))
627
+ tmp_ligrec = []
628
+ for i in range(df_ligrec.shape[0]):
629
+ tmp_lig = df_ligrec.iloc[i][0].split(heteromeric_delimiter)
630
+ tmp_rec = df_ligrec.iloc[i][1].split(heteromeric_delimiter)
631
+ if set(tmp_lig).issubset(data_genes) and set(tmp_rec).issubset(data_genes):
632
+ tmp_ligrec.append([df_ligrec.iloc[i][0], df_ligrec.iloc[i][1], df_ligrec.iloc[i][2]])
633
+ tmp_ligrec = np.array(tmp_ligrec, str)
634
+ df_ligrec = pd.DataFrame(data=tmp_ligrec)
635
+
636
+ # remove unavailable genes from pathways
637
+ tmp_pathway = []
638
+ for i in range(pathways.shape[0]):
639
+ if pathways.iloc[i][0] in data_genes and pathways.iloc[i][1] in data_genes and pathways.iloc[i][7] == species:
640
+ tmp_pathway.append([pathways.iloc[i][0], pathways.iloc[i][1], pathways.iloc[i][5],pathways.iloc[i][6]]) #0: src, 1: dest, 5:if scr_tf, 6: if dest_tf
641
+ tmp_pathway = np.array(tmp_pathway, str)
642
+ ggi_tf = pd.DataFrame(
643
+ data=tmp_pathway,
644
+ columns=["src", "dest","src_tf", "dest_tf"]
645
+ )
646
+
647
+
648
+ # Drop duplicate pairs
649
+ df_ligrec = df_ligrec.drop_duplicates()
650
+
651
+ if species == "Mouse":
652
+ max_hop = 4
653
+ else:
654
+ max_hop = 3
655
+
656
+ model = CellCommunication(adata,
657
+ df_ligrec,
658
+ ggi_tf,
659
+ co_exp_ratio,
660
+ max_hop,
661
+ dis_mat,
662
+ dis_thr,
663
+ cost_scale,
664
+ cost_type,
665
+ heteromeric = heteromeric,
666
+ heteromeric_rule = heteromeric_rule,
667
+ heteromeric_delimiter = heteromeric_delimiter
668
+ )
669
+ model.run_cot_signaling(cot_eps_p=cot_eps_p,
670
+ cot_eps_mu = cot_eps_mu,
671
+ cot_eps_nu = cot_eps_nu,
672
+ cot_rho = cot_rho,
673
+ cot_lam = cot_lam,
674
+ cot_nitermax = cot_nitermax,
675
+ cot_weights = cot_weights,
676
+ smooth = smooth,
677
+ smth_eta = smth_eta,
678
+ smth_nu = smth_nu,
679
+ smth_kernel = smth_kernel
680
+ )
681
+
682
+
683
+ adata.uns['comflow-'+database_name+'-info'] = {}
684
+ df_ligrec_write = pd.DataFrame(data=df_ligrec.values, columns=['ligand','receptor','pathway'])
685
+ adata.uns['comflow-'+database_name+'-info']['df_ligrec'] = df_ligrec_write
686
+ adata.uns['comflow-'+database_name+'-info']['distance_threshold'] = dis_thr
687
+
688
+ ncell = adata.shape[0]
689
+ X_sender = np.empty([ncell,0], float)
690
+ X_receiver = np.empty([ncell,0], float)
691
+ col_names_sender = []
692
+ col_names_receiver = []
693
+ tmp_ligs = model.ligs
694
+ tmp_recs = model.recs
695
+ S_total = sparse.csr_matrix((ncell, ncell), dtype=float)
696
+ if pathway_sum:
697
+ pathways = list(np.sort(list(set(df_ligrec.iloc[:,2].values))))
698
+ S_pathway = [sparse.csr_matrix((ncell, ncell), dtype=float) for i in range(len(pathways))]
699
+ X_sender_pathway = [np.zeros([ncell,1], float) for i in range(len(pathways))]
700
+ X_receiver_pathway = [np.zeros([ncell,1], float) for i in range(len(pathways))]
701
+ for (i,j) in model.comm_network.keys():
702
+ S = model.comm_network[(i,j)]
703
+ adata.obsp['comflow-'+database_name+'-'+tmp_ligs[i]+'-'+tmp_recs[j]] = S
704
+ S_total = S_total + S
705
+ lig_sum = np.array(S.sum(axis=1))
706
+ rec_sum = np.array(S.sum(axis=0).T)
707
+ X_sender = np.concatenate((X_sender, lig_sum), axis=1)
708
+ X_receiver = np.concatenate((X_receiver, rec_sum), axis=1)
709
+ col_names_sender.append("s-%s-%s" % (tmp_ligs[i], tmp_recs[j]))
710
+ col_names_receiver.append("r-%s-%s" % (tmp_ligs[i], tmp_recs[j]))
711
+ if pathway_sum:
712
+ mask = (df_ligrec.iloc[:,0] == tmp_ligs[i]) & (df_ligrec.iloc[:,1] == tmp_recs[j])
713
+ pathway = df_ligrec[mask].iloc[:,2].values[0]
714
+ pathway_idx = pathways.index(pathway)
715
+ S_pathway[pathway_idx] = S_pathway[pathway_idx] + S
716
+ X_sender_pathway[pathway_idx] = X_sender_pathway[pathway_idx] + np.array(S.sum(axis=1))
717
+ X_receiver_pathway[pathway_idx] = X_receiver_pathway[pathway_idx] + np.array(S.sum(axis=0).T)
718
+ if pathway_sum:
719
+ for pathway_idx in range(len(pathways)):
720
+ pathway = pathways[pathway_idx]
721
+ adata.obsp['comflow-'+database_name+'-'+pathway] = S_pathway[pathway_idx]
722
+
723
+ X_sender = np.concatenate((X_sender, X_sender.sum(axis=1).reshape(-1,1)), axis=1)
724
+ X_receiver = np.concatenate((X_receiver, X_receiver.sum(axis=1).reshape(-1,1)), axis=1)
725
+ col_names_sender.append("s-total-total")
726
+ col_names_receiver.append("r-total-total")
727
+
728
+ if pathway_sum:
729
+ for pathway_idx in range(len(pathways)):
730
+ pathway = pathways[pathway_idx]
731
+ X_sender = np.concatenate((X_sender, X_sender_pathway[pathway_idx]), axis=1)
732
+ X_receiver = np.concatenate((X_receiver, X_receiver_pathway[pathway_idx]), axis=1)
733
+ col_names_sender.append("s-"+pathway)
734
+ col_names_receiver.append("r-"+pathway)
735
+
736
+ adata.obsp['comflow-'+database_name+'-total-total'] = S_total
737
+
738
+ df_sender = pd.DataFrame(data=X_sender, columns=col_names_sender, index=adata.obs_names)
739
+ df_receiver = pd.DataFrame(data=X_receiver, columns=col_names_receiver, index=adata.obs_names)
740
+ adata.obsm['comflow-'+database_name+'-sum-sender'] = df_sender
741
+ adata.obsm['comflow-'+database_name+'-sum-receiver'] = df_receiver
742
+
743
+ # del model
744
+ gc.collect()
745
+
746
+ return adata, model if copy else None
747
+
748
+
749
+ def communication_direction(
750
+ adata: anndata.AnnData,
751
+ database_name: str = None,
752
+ pathway_name: str = None,
753
+ lr_pair = None,
754
+ k: int = 5,
755
+ pos_idx: Optional[np.ndarray] = None,
756
+ copy: bool = False
757
+ ):
758
+ """
759
+ Construct spatial vector fields for inferred communication.
760
+
761
+ Parameters
762
+ ----------
763
+ adata
764
+ The data matrix of shape ``n_obs`` × ``n_var``.
765
+ Rows correspond to cells or spots and columns to genes.
766
+ database_name
767
+ Name of the ligand-receptor database.
768
+ If both pathway_name and lr_pair are None, the signaling direction of all ligand-receptor pairs is computed.
769
+ pathway_name
770
+ Name of the signaling pathway.
771
+ If given, only the signaling direction of this signaling pathway is computed.
772
+ lr_pair
773
+ A tuple of ligand-receptor pair.
774
+ If given, only the signaling direction of this pair is computed.
775
+ k
776
+ Top k senders or receivers to consider when determining the direction.
777
+ pos_idx
778
+ The columns in ``.obsm['spatial']`` to use. If None, all columns are used.
779
+ For example, to use just the first and third columns, set pos_idx to ``numpy.array([0,2],int)``.
780
+ copy
781
+ Whether to return a copy of the :class:`anndata.AnnData`.
782
+
783
+ Returns
784
+ -------
785
+ adata : anndata.AnnData
786
+ Vector fields describing signaling directions are added to ``.obsm``,
787
+ e.g., for a database named "databaseX",
788
+ ``.obsm['comflow_sender_vf-databaseX-ligA-recA']`` and ``.obsm['comflow_receiver_vf-databaseX-ligA-recA']``
789
+ describe the signaling directions of the cells as, respectively, senders and receivers through the
790
+ ligand-receptor pair ligA and recA.
791
+ If copy=True, return the AnnData object and return None otherwise.
792
+
793
+ """
794
+
795
+ obsp_names = []
796
+ if not lr_pair is None:
797
+ obsp_names.append(database_name+'-'+lr_pair[0]+'-'+lr_pair[1])
798
+ elif not pathway_name is None:
799
+ obsp_names.append(database_name+'-'+pathway_name)
800
+ else:
801
+ obsp_names.append(database_name+'-total-total')
802
+
803
+ ncell = adata.shape[0]
804
+ pts = np.array( adata.obsm['spatial'], float )
805
+ if not pos_idx is None:
806
+ pts = pts[:,pos_idx]
807
+ storage = 'sparse'
808
+
809
+ if storage == 'dense':
810
+ for i in range(len(obsp_names)):
811
+ # lig = name_mat[i,0]
812
+ # rec = name_mat[i,1]
813
+ S_np = adata.obsp['comflow-'+obsp_names[i]].toarray()
814
+ sender_vf = np.zeros_like(pts)
815
+ receiver_vf = np.zeros_like(pts)
816
+
817
+ tmp_idx = np.argsort(-S_np,axis=1)[:,:k]
818
+ avg_v = np.zeros_like(pts)
819
+ for ik in range(k):
820
+ tmp_v = pts[tmp_idx[:,ik]] - pts[np.arange(ncell,dtype=int)]
821
+ tmp_v = normalize(tmp_v, norm='l2')
822
+ avg_v = avg_v + tmp_v * S_np[np.arange(ncell,dtype=int),tmp_idx[:,ik]].reshape(-1,1)
823
+ avg_v = normalize(avg_v)
824
+ sender_vf = avg_v * np.sum(S_np,axis=1).reshape(-1,1)
825
+
826
+ S_np = S_np.T
827
+ tmp_idx = np.argsort(-S_np,axis=1)[:,:k]
828
+ avg_v = np.zeros_like(pts)
829
+ for ik in range(k):
830
+ tmp_v = -pts[tmp_idx[:,ik]] + pts[np.arange(ncell,dtype=int)]
831
+ tmp_v = normalize(tmp_v, norm='l2')
832
+ avg_v = avg_v + tmp_v * S_np[np.arange(ncell,dtype=int),tmp_idx[:,ik]].reshape(-1,1)
833
+ avg_v = normalize(avg_v)
834
+ receiver_vf = avg_v * np.sum(S_np,axis=1).reshape(-1,1)
835
+
836
+ del S_np
837
+
838
+ elif storage == 'sparse':
839
+ for i in range(len(obsp_names)):
840
+ # lig = name_mat[i,0]
841
+ # rec = name_mat[i,1]
842
+ S = adata.obsp['comflow-'+obsp_names[i]]
843
+ S_sum_sender = np.array( S.sum(axis=1) ).reshape(-1)
844
+ S_sum_receiver = np.array( S.sum(axis=0) ).reshape(-1)
845
+ sender_vf = np.zeros_like(pts)
846
+ receiver_vf = np.zeros_like(pts)
847
+
848
+ S_lil = S.tolil()
849
+ for j in range(S.shape[0]):
850
+ if len(S_lil.rows[j]) <= k:
851
+ tmp_idx = np.array( S_lil.rows[j], int )
852
+ tmp_data = np.array( S_lil.data[j], float )
853
+ else:
854
+ row_np = np.array( S_lil.rows[j], int )
855
+ data_np = np.array( S_lil.data[j], float )
856
+ sorted_idx = np.argsort( -data_np )[:k]
857
+ tmp_idx = row_np[ sorted_idx ]
858
+ tmp_data = data_np[ sorted_idx ]
859
+ if len(tmp_idx) == 0:
860
+ continue
861
+ elif len(tmp_idx) == 1:
862
+ avg_v = pts[tmp_idx[0],:] - pts[j,:]
863
+ else:
864
+ tmp_v = pts[tmp_idx,:] - pts[j,:]
865
+ tmp_v = normalize(tmp_v, norm='l2')
866
+ avg_v = tmp_v * tmp_data.reshape(-1,1)
867
+ avg_v = np.sum( avg_v, axis=0 )
868
+ avg_v = normalize( avg_v.reshape(1,-1) )
869
+ sender_vf[j,:] = avg_v[0,:] * S_sum_sender[j]
870
+
871
+ S_lil = S.T.tolil()
872
+ for j in range(S.shape[0]):
873
+ if len(S_lil.rows[j]) <= k:
874
+ tmp_idx = np.array( S_lil.rows[j], int )
875
+ tmp_data = np.array( S_lil.data[j], float )
876
+ else:
877
+ row_np = np.array( S_lil.rows[j], int )
878
+ data_np = np.array( S_lil.data[j], float )
879
+ sorted_idx = np.argsort( -data_np )[:k]
880
+ tmp_idx = row_np[ sorted_idx ]
881
+ tmp_data = data_np[ sorted_idx ]
882
+ if len(tmp_idx) == 0:
883
+ continue
884
+ elif len(tmp_idx) == 1:
885
+ avg_v = -pts[tmp_idx,:] + pts[j,:]
886
+ else:
887
+ tmp_v = -pts[tmp_idx,:] + pts[j,:]
888
+ tmp_v = normalize(tmp_v, norm='l2')
889
+ avg_v = tmp_v * tmp_data.reshape(-1,1)
890
+ avg_v = np.sum( avg_v, axis=0 )
891
+ avg_v = normalize( avg_v.reshape(1,-1) )
892
+ receiver_vf[j,:] = avg_v[0,:] * S_sum_receiver[j]
893
+
894
+
895
+
896
+ adata.obsm["comflow_sender_vf-"+obsp_names[i]] = sender_vf
897
+ adata.obsm["comflow_receiver_vf-"+obsp_names[i]] = receiver_vf
898
+
899
+ return adata if copy else None
900
+
901
+ def cluster_communication(
902
+ adata: anndata.AnnData,
903
+ database_name: str = None,
904
+ pathway_name: str = None,
905
+ lr_pair = None,
906
+ clustering: str = None,
907
+ n_permutations: int = 100,
908
+ random_seed: int = 1,
909
+ copy: bool = False
910
+ ):
911
+ """
912
+ Summarize cell-cell communication to cluster-cluster communication and compute p-values by permutating cell/spot labels.
913
+
914
+ Parameters
915
+ ----------
916
+ adata
917
+ The data matrix of shape ``n_obs`` × ``n_var``.
918
+ Rows correspond to cells or positions and columns to genes.
919
+ database_name
920
+ Name of the ligand-receptor database.
921
+ If both pathway_name and lr_pair are None, the cluster signaling through all ligand-receptor pairs is summarized.
922
+ pathway_name
923
+ Name of the signaling pathway.
924
+ If given, the signaling through all ligand-receptor pairs of the given pathway is summarized.
925
+ lr_pair
926
+ A tuple of ligand-receptor pair.
927
+ If given, only the cluster signaling through this pair is computed.
928
+ clustering
929
+ Name of clustering with the labels stored in ``.obs[clustering]``.
930
+ n_permutations
931
+ Number of label permutations for computing the p-value.
932
+ random_seed
933
+ The numpy random_seed for reproducible random permutations.
934
+ copy
935
+ Whether to return a copy of the :class:`anndata.AnnData`.
936
+
937
+ Returns
938
+ -------
939
+ adata : anndata.AnnData
940
+ Add cluster-cluster communication matrix to
941
+ ``.uns['comflow_cluster-databaseX-clustering-ligA-recA']``
942
+ for the ligand-receptor database named 'databaseX' and the cell clustering
943
+ named 'clustering' through the ligand-receptor pair 'ligA' and 'recA'.
944
+ The first object is the communication score matrix and the second object contains
945
+ the corresponding p-values.
946
+ If copy=True, return the AnnData object and return None otherwise.
947
+
948
+ """
949
+ np.random.seed(random_seed)
950
+
951
+ assert database_name is not None, "Please at least specify database_name."
952
+
953
+ celltypes = list( adata.obs[clustering].unique() )
954
+ celltypes.sort()
955
+ for i in range(len(celltypes)):
956
+ celltypes[i] = str(celltypes[i])
957
+ clusterid = np.array(adata.obs[clustering], str)
958
+ obsp_names = []
959
+ if not lr_pair is None:
960
+ obsp_names.append(database_name+'-'+lr_pair[0]+'-'+lr_pair[1])
961
+ elif not pathway_name is None:
962
+ obsp_names.append(database_name+'-'+pathway_name)
963
+ else:
964
+ obsp_names.append(database_name+'-total-total')
965
+ # name_mat = adata.uns['comflow-'+pathway_name+'-info']['df_ligrec'].values
966
+ # name_mat = np.concatenate((name_mat, np.array([['total','total']],str)), axis=0)
967
+ for i in range(len(obsp_names)):
968
+ S = adata.obsp['comflow-'+obsp_names[i]]
969
+ tmp_df, tmp_p_value = summarize_cluster(S,
970
+ clusterid, celltypes, n_permutations=n_permutations)
971
+ adata.uns['comflow_cluster-'+clustering+'-'+obsp_names[i]] = {'communication_matrix': tmp_df, 'communication_pvalue': tmp_p_value}
972
+
973
+ return adata if copy else None
974
+
975
+
976
+ def cluster_communication_spatial_permutation(
977
+ adata: anndata.AnnData,
978
+ df_ligrec: pd.DataFrame = None,
979
+ database_name: str = None,
980
+ heteromeric: bool = False,
981
+ heteromeric_rule: str = 'min',
982
+ heteromeric_delimiter: str = '_',
983
+ dis_thr: Optional[float] = None,
984
+ cost_scale: Optional[dict] = None,
985
+ cost_type: str = 'euc',
986
+ cot_eps_p: float = 1e-1,
987
+ cot_eps_mu: Optional[float] = None,
988
+ cot_eps_nu: Optional[float] = None,
989
+ cot_rho: float =1e1,
990
+ cot_nitermax: int = 100,
991
+ cot_weights: tuple = (0.25,0.25,0.25,0.25),
992
+ smooth: bool = False,
993
+ smth_eta: float = None,
994
+ smth_nu: float = None,
995
+ smth_kernel: str = 'exp',
996
+ clustering: str = None,
997
+ perm_type: str = 'within_cluster',
998
+ n_permutations: int = 100,
999
+ random_seed: int = 1,
1000
+ verbose: bool = True,
1001
+ copy: bool = False
1002
+ ):
1003
+ """
1004
+ Infer cluster-cluster communication and compute p-value by permutating cell/spot locations.
1005
+
1006
+ The cluster_communication function using label permutations is computationally efficient but may overestimate the communications of neighboring cell clusters.
1007
+ This function compute the p-value by permutating the locations of cell or spots and requires more computation time since the communication matrix is recomputed for each permutation.
1008
+ To avoid repeated calculation of the cell-level CCC matrices, the cluster-level CCC is summarized for all LR pairs and signaling pathways.
1009
+
1010
+ Parameters
1011
+ ----------
1012
+ adata
1013
+ The data matrix of shape ``n_obs`` × ``n_var``.
1014
+ Rows correspond to cells or spots and columns to genes.
1015
+ If the spatial distance is absent in ``.obsp['spatial_distance']``, Euclidean distance determined from ``.obsm['spatial']`` will be used.
1016
+ df_ligrec
1017
+ A data frame where each row corresponds to a ligand-receptor pair with ligands, receptors, and the associated signaling pathways in the three columns, respectively.
1018
+ database_name
1019
+ Name of the ligand-receptor interaction database. Will be included in the keywords for anndata slots.
1020
+ heteromeric
1021
+ Whether the ligands or receptors are made of heteromeric complexes.
1022
+ heteromeric_rule
1023
+ Use either 'min' (minimum) or 'ave' (average) expression of the components as the complex level.
1024
+ heteromeric_delimiter
1025
+ The character in ligand and receptor names separating individual components.
1026
+ dis_thr
1027
+ The threshold of spatial distance of signaling.
1028
+ cost_scale
1029
+ Weight coefficients of the cost matrix for each ligand-receptor pair, e.g. cost_scale[('ligA','recA')] specifies weight for the pair ligA and recA.
1030
+ If None, all pairs have the same weight.
1031
+ cost_type
1032
+ If 'euc', the original Euclidean distance will be used as cost matrix. If 'euc_square', the square of the Euclidean distance will be used.
1033
+ cot_eps_p
1034
+ The coefficient of entropy regularization for transport plan.
1035
+ cot_eps_mu
1036
+ The coefficient of entropy regularization for untransported source (ligand). Set to equal to cot_eps_p for fast algorithm.
1037
+ cot_eps_nu
1038
+ The coefficient of entropy regularization for unfulfilled target (receptor). Set to equal to cot_eps_p for fast algorithm.
1039
+ cot_rho
1040
+ The coefficient of penalty for unmatched mass.
1041
+ cot_nitermax
1042
+ Maximum iteration for collective optimal transport algorithm.
1043
+ The default of this parameter is set to a much smaller one (100) compared to the default in ``spatial_communication`` to speed up the repeated OT calculation.
1044
+ The resulting communication matrices will be slightly different from the using 10000 for cot_nitermax but very similar.
1045
+ cot_weights
1046
+ A tuple of four weights that add up to one. The weights corresponds to four setups of collective optimal transport:
1047
+ 1) all ligands-all receptors, 2) each ligand-all receptors, 3) all ligands-each receptor, 4) each ligand-each receptor.
1048
+ smooth
1049
+ Whether to (spatially) smooth the gene expression for identifying more global signaling trend.
1050
+ smth_eta
1051
+ Kernel bandwidth for smoothing
1052
+ smth_nu
1053
+ Kernel sharpness for smoothing
1054
+ smth_kernel
1055
+ 'exp' exponential kernel. 'lorentz' Lorentz kernel.
1056
+ clustering
1057
+ Name of clustering with the labels stored in ``.obs[clustering]``.
1058
+ perm_type
1059
+ The type of permutation to perform.
1060
+ If "within_cluster", the cells/spots are permutated within each cluster.
1061
+ If "all_cell", the cells/spots are permutated all together.
1062
+ n_permutations
1063
+ Number of location permutations for computing the p-value.
1064
+ random_seed
1065
+ The numpy random_seed for reproducible random permutations.
1066
+ verbose
1067
+ Whether to print the permutation iterations.
1068
+ copy
1069
+ Whether to return a copy of the :class:`anndata.AnnData`.
1070
+
1071
+ Returns
1072
+ -------
1073
+ adata : anndata.AnnData
1074
+ For example, the cluster-level communication summary by this location permutation method for the LR pair 'LigA' and 'RecA' from the database 'databaseX' is stored in
1075
+ ``adata.uns['comflow_cluster_spatial_permutation-databaseX-clustering-ligA-recA']``
1076
+ If copy=True, return the AnnData object and return None otherwise.
1077
+
1078
+ """
1079
+
1080
+ assert perm_type in ['all_cell','within_cluster'], "Please specify 'all_cell' or 'within_cluster' for perm_type."
1081
+
1082
+ # Assign a spatial distance matrix among spots
1083
+ dis_mats = []
1084
+ if not 'spatial_distance' in adata.obsp.keys():
1085
+ dis_mat = distance_matrix(adata.obsm["spatial"], adata.obsm["spatial"])
1086
+ else:
1087
+ dis_mat = adata.obsp['spatial_distance']
1088
+
1089
+ # Remove unavailable genes from df_ligrec
1090
+ print("ligrec dataframe shape", df_ligrec.shape)
1091
+ if not heteromeric:
1092
+ data_genes = list(adata.var_names)
1093
+ tmp_ligrec = []
1094
+ for i in range(df_ligrec.shape[0]):
1095
+ if df_ligrec.iloc[i][0] in data_genes and df_ligrec.iloc[i][1] in data_genes:
1096
+ tmp_ligrec.append([df_ligrec.iloc[i][0], df_ligrec.iloc[i][1], df_ligrec.iloc[i][2]])
1097
+ tmp_ligrec = np.array(tmp_ligrec, str)
1098
+ df_ligrec = pd.DataFrame(data=tmp_ligrec, columns=['ligand','receptor','pathway'])
1099
+ elif heteromeric:
1100
+ data_genes = set(list(adata.var_names))
1101
+ tmp_ligrec = []
1102
+ for i in range(df_ligrec.shape[0]):
1103
+ tmp_lig = df_ligrec.iloc[i][0].split(heteromeric_delimiter)
1104
+ tmp_rec = df_ligrec.iloc[i][1].split(heteromeric_delimiter)
1105
+ if set(tmp_lig).issubset(data_genes) and set(tmp_rec).issubset(data_genes):
1106
+ tmp_ligrec.append([df_ligrec.iloc[i][0], df_ligrec.iloc[i][1], df_ligrec.iloc[i][2]])
1107
+ tmp_ligrec = np.array(tmp_ligrec, str)
1108
+ df_ligrec = pd.DataFrame(data=tmp_ligrec, columns=['ligand','receptor','pathway'])
1109
+ # Drop duplicate pairs
1110
+ df_ligrec = df_ligrec.drop_duplicates()
1111
+ print("ligrec dataframe shape after filtering", df_ligrec.shape)
1112
+
1113
+ # Generate permutation indices
1114
+ perm_idx = []
1115
+ ncell = adata.shape[0]
1116
+ np.random.seed(random_seed)
1117
+ perm_idx.append(np.arange(ncell))
1118
+ for i in range(n_permutations):
1119
+ if perm_type == 'all_cell':
1120
+ perm_idx.append(np.random.permutation(ncell))
1121
+ elif perm_type == 'within_cluster':
1122
+ celltypes = np.sort( list( adata.obs[clustering].unique() ) )
1123
+ clusterid = np.array(adata.obs[clustering], str)
1124
+ tmp_perm_idx = np.arange(ncell)
1125
+ for celltype in celltypes:
1126
+ cell_idx = np.where(clusterid==celltype)[0]
1127
+ tmp_perm_idx[cell_idx] = np.random.permutation(cell_idx)
1128
+ perm_idx.append(tmp_perm_idx)
1129
+
1130
+
1131
+
1132
+ # Compute the cluster-level commutation score for all permutations
1133
+ # and all lr_pairs, and pathways
1134
+ celltypes = list( adata.obs[clustering].unique() )
1135
+ celltypes.sort()
1136
+ clusterid = np.array(adata.obs[clustering], str)
1137
+
1138
+ pathways = list(set(df_ligrec['pathway']))
1139
+ n_uns_names = len(df_ligrec) + len(pathways) + 1
1140
+
1141
+ S_cl = np.empty([len(perm_idx), len(celltypes), len(celltypes), n_uns_names], float)
1142
+
1143
+ uns_names = []
1144
+
1145
+
1146
+ for i_perm in range(len(perm_idx)):
1147
+ if verbose:
1148
+ print("Permutation: ", i_perm)
1149
+ adata_tmp = anndata.AnnData(adata[perm_idx[i_perm],:].X,
1150
+ obs=pd.DataFrame(index=adata[perm_idx[i_perm],:].obs_names),
1151
+ var=pd.DataFrame(index=adata.var_names))
1152
+ model = CellCommunication(adata_tmp,
1153
+ df_ligrec,
1154
+ dis_mat,
1155
+ dis_thr,
1156
+ cost_scale,
1157
+ cost_type,
1158
+ heteromeric = heteromeric,
1159
+ heteromeric_rule = heteromeric_rule,
1160
+ heteromeric_delimiter = heteromeric_delimiter
1161
+ )
1162
+ model.run_cot_signaling(cot_eps_p=cot_eps_p,
1163
+ cot_eps_mu = cot_eps_mu,
1164
+ cot_eps_nu = cot_eps_nu,
1165
+ cot_rho = cot_rho,
1166
+ cot_lam = cot_lam,
1167
+ cot_nitermax = cot_nitermax,
1168
+ cot_weights = cot_weights,
1169
+ smooth = smooth,
1170
+ smth_eta = smth_eta,
1171
+ smth_nu = smth_nu,
1172
+ smth_kernel = smth_kernel
1173
+ )
1174
+ for i_pair in range(len(df_ligrec)):
1175
+ lig = df_ligrec.iloc[i_pair]['ligand']
1176
+ rec = df_ligrec.iloc[i_pair]['receptor']
1177
+ i = model.ligs.index(lig)
1178
+ j = model.recs.index(rec)
1179
+ S_tmp = model.comm_network[(i,j)]
1180
+ uns_names.append(database_name+'-'+lig+'-'+rec)
1181
+ df_cluster_tmp,_ = summarize_cluster(S_tmp, clusterid, celltypes, n_permutations=1)
1182
+ S_cl[i_perm, :, :, i_pair] = df_cluster_tmp.values[:,:]
1183
+ for i_pathway in range(len(pathways)):
1184
+ pathway = pathways[i_pathway]
1185
+ S_tmp = sparse.csr_matrix((ncell, ncell), dtype=float)
1186
+ for i_pair in range(df_ligrec.shape[0]):
1187
+ if df_ligrec.iloc[i_pair,2] == pathway:
1188
+ i = model.ligs.index(df_ligrec.iloc[i_pair]['ligand'])
1189
+ j = model.recs.index(df_ligrec.iloc[i_pair]['receptor'])
1190
+ S_tmp = S_tmp + model.comm_network[(i,j)]
1191
+ uns_names.append(database_name+'-'+pathway)
1192
+ df_cluster_tmp,_ = summarize_cluster(S_tmp, clusterid, celltypes, n_permutations=1)
1193
+ S_cl[i_perm, :, :, len(df_ligrec)+i_pathway] = df_cluster_tmp.values[:,:]
1194
+ S_tmp = sparse.csr_matrix((ncell, ncell), dtype=float)
1195
+ for (i,j) in model.comm_network.keys():
1196
+ S_tmp = S_tmp + model.comm_network[(i,j)]
1197
+ uns_names.append(database_name+'-total-total')
1198
+ df_cluster_tmp,_ = summarize_cluster(S_tmp, clusterid, celltypes, n_permutations=1)
1199
+ S_cl[i_perm, :, :, -1] = df_cluster_tmp.values[:,:]
1200
+
1201
+ del model
1202
+ gc.collect()
1203
+
1204
+ # Compute p-value
1205
+ for i_uns in range(S_cl.shape[-1]):
1206
+ p_cluster = np.zeros([len(celltypes), len(celltypes)], float)
1207
+ for i_perm in range(n_permutations):
1208
+ p_cluster[S_cl[i_perm+1,:,:, i_uns] >= S_cl[0,:,:, i_uns]] += 1.0
1209
+ p_cluster = p_cluster / n_permutations
1210
+ df_cluster = pd.DataFrame(data=S_cl[0,:,:,i_uns], index=celltypes, columns=celltypes)
1211
+ df_p_value = pd.DataFrame(data=p_cluster, index=celltypes, columns=celltypes)
1212
+ adata.uns['comflow_cluster_spatial_permutation-'+clustering+'-'+uns_names[i_uns]] = {'communication_matrix': df_cluster, 'communication_pvalue': df_p_value}
1213
+
1214
+ return adata if copy else None
1215
+
1216
+ def cluster_position(
1217
+ adata: anndata.AnnData,
1218
+ clustering: str = None,
1219
+ method: str = 'geometric_mean',
1220
+ copy: bool = False
1221
+ ):
1222
+ """
1223
+ Assign spatial positions to clusters.
1224
+
1225
+ Parameters
1226
+ ----------
1227
+ adata
1228
+ The data matrix of shape ``n_obs`` × ``n_var``.
1229
+ Rows correspond to cells or positions and columns to genes.
1230
+ clustering
1231
+ Name of clustering with the labels stored in ``.obs[clustering]``.
1232
+ method
1233
+ 'geometric_mean' geometric mean of the positions.
1234
+ 'representative_point' the position in the cluster with
1235
+ minimum total distance to other points.
1236
+ copy
1237
+ Whether to return a copy of the :class:`anndata.AnnData`.
1238
+
1239
+ Returns
1240
+ -------
1241
+ adata : anndata.AnnData
1242
+ Add cluster positions to ``.uns['cluster_pos-clustering_name']`` for the clustering named
1243
+ 'clustering_name'.
1244
+ If copy=True, return the AnnData object and return None otherwise.
1245
+
1246
+ """
1247
+ cluster_pos = cluster_center(adata, clustering, method=method)
1248
+ adata.uns['cluster_pos-'+clustering] = cluster_pos
1249
+
1250
+ return adata if copy else None