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.
- comflow/__init__.py +10 -0
- comflow/_optimal_transport/__init__.py +13 -0
- comflow/_optimal_transport/_cot.py +850 -0
- comflow/_optimal_transport/_cot_preRevise.py +850 -0
- comflow/_optimal_transport/_unot.py +485 -0
- comflow/_optimal_transport/_usot.py +117 -0
- comflow/_utils/__init__.py +20 -0
- comflow/_utils/_binarization.py +43 -0
- comflow/_utils/_clustering.py +57 -0
- comflow/_utils/_plotting.py +398 -0
- comflow/_utils/_similarity.py +479 -0
- comflow/plotting/__init__.py +5 -0
- comflow/plotting/_plotting.py +794 -0
- comflow/preprocessing/__init__.py +3 -0
- comflow/preprocessing/_infer_spatial.py +161 -0
- comflow/preprocessing/_ligand_receptor_database.py +153 -0
- comflow/tools/__init__.py +12 -0
- comflow/tools/_downstream_analysis.py +870 -0
- comflow/tools/_spatial_communication.py +1250 -0
- comflow-0.0.3.dist-info/LICENSE.md +21 -0
- comflow-0.0.3.dist-info/METADATA +113 -0
- comflow-0.0.3.dist-info/RECORD +24 -0
- comflow-0.0.3.dist-info/WHEEL +5 -0
- comflow-0.0.3.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,870 @@
|
|
|
1
|
+
from typing import Optional, Union
|
|
2
|
+
import ot
|
|
3
|
+
import sys
|
|
4
|
+
import anndata
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
import scanpy as sc
|
|
8
|
+
import networkx as nx
|
|
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 sklearn.neighbors import kneighbors_graph
|
|
17
|
+
from sklearn.decomposition import PCA
|
|
18
|
+
import karateclub
|
|
19
|
+
|
|
20
|
+
from .._utils import partial_corr
|
|
21
|
+
from .._utils import semipartial_corr
|
|
22
|
+
from .._utils import treebased_score
|
|
23
|
+
from .._utils import treebased_score_multifeature
|
|
24
|
+
from .._utils import d_graph_local_jaccard
|
|
25
|
+
from .._utils import d_graph_local_jaccard_weighted
|
|
26
|
+
from .._utils import d_graph_global_structure
|
|
27
|
+
from .._utils import leiden_clustering
|
|
28
|
+
from .._utils import moranI_vector_global
|
|
29
|
+
from .._utils import preprocess_vector_field
|
|
30
|
+
from .._utils import binarize_sparse_matrix
|
|
31
|
+
|
|
32
|
+
def communication_deg_detection(
|
|
33
|
+
adata: anndata.AnnData,
|
|
34
|
+
n_var_genes: int = None,
|
|
35
|
+
var_genes = None,
|
|
36
|
+
database_name: str = None,
|
|
37
|
+
pathway_name: str = None,
|
|
38
|
+
summary: str = 'receiver',
|
|
39
|
+
lr_pair: tuple = ('total','total'),
|
|
40
|
+
nknots: int = 6,
|
|
41
|
+
n_deg_genes: int = None,
|
|
42
|
+
n_points: int = 50,
|
|
43
|
+
deg_pvalue_cutoff: float = 0.05,
|
|
44
|
+
):
|
|
45
|
+
"""
|
|
46
|
+
Identify signaling dependent genes
|
|
47
|
+
|
|
48
|
+
This function depends on tradeSeq [Van_den_Berge2020]_. Currently, tradeSeq version 1.0.1 with R version 3.6.3 has been tested to work.
|
|
49
|
+
For the R-python interface, rpy2==3.4.2 and anndata2ri==1.0.6 have been tested to work.
|
|
50
|
+
|
|
51
|
+
Here, the total received or sent signal for the spots are considered as a "gene expression" where tradeSeq is used to find the correlated genes.
|
|
52
|
+
|
|
53
|
+
Parameters
|
|
54
|
+
----------
|
|
55
|
+
adata
|
|
56
|
+
The data matrix of shape ``n_obs`` × ``n_var``.
|
|
57
|
+
Rows correspond to cells or positions and columns to genes.
|
|
58
|
+
The count data should be available through adata.layers['count'].
|
|
59
|
+
For example, when examining the received signal through the ligand-receptor pair "ligA" and "RecA" infered with the LR database "databaseX",
|
|
60
|
+
the signaling inference result should be available in
|
|
61
|
+
``adata.obsm['commot-databaseX-sum-receiver']['r-ligA-recA']``
|
|
62
|
+
n_var_genes
|
|
63
|
+
The number of most variable genes to test.
|
|
64
|
+
var_genes
|
|
65
|
+
The genes to test. n_var_genes will be ignored if given.
|
|
66
|
+
n_deg_genes
|
|
67
|
+
The number of top deg genes to evaluate yhat.
|
|
68
|
+
pathway_name
|
|
69
|
+
Name of the signaling pathway (choose from the third column of ``.uns['commot-databaseX-info']['df_ligrec']``).
|
|
70
|
+
If ``pathway_name`` is specified, ``lr_pair`` will be ignored.
|
|
71
|
+
summary
|
|
72
|
+
'sender' or 'receiver'
|
|
73
|
+
lr_pair
|
|
74
|
+
A tuple of the ligand-receptor pair.
|
|
75
|
+
If ``pathway_name`` is specified, ``lr_pair`` will be ignored.
|
|
76
|
+
nknots
|
|
77
|
+
Number of knots in spline when constructing GAM.
|
|
78
|
+
n_points
|
|
79
|
+
Number of points on which to evaluate the fitted GAM
|
|
80
|
+
for downstream clustering and visualization.
|
|
81
|
+
deg_pvalue_cutoff
|
|
82
|
+
The p-value cutoff of genes for obtaining the fitted gene expression patterns.
|
|
83
|
+
|
|
84
|
+
Returns
|
|
85
|
+
-------
|
|
86
|
+
df_deg: pd.DataFrame
|
|
87
|
+
A data frame of deg analysis results, including Wald statistics, degree of freedom, and p-value.
|
|
88
|
+
df_yhat: pd.DataFrame
|
|
89
|
+
A data frame of smoothed gene expression values.
|
|
90
|
+
|
|
91
|
+
References
|
|
92
|
+
----------
|
|
93
|
+
|
|
94
|
+
.. [Van_den_Berge2020] Van den Berge, K., Roux de Bézieux, H., Street, K., Saelens, W., Cannoodt, R., Saeys, Y., ... & Clement, L. (2020).
|
|
95
|
+
Trajectory-based differential expression analysis for single-cell sequencing data. Nature communications, 11(1), 1-13.
|
|
96
|
+
|
|
97
|
+
"""
|
|
98
|
+
# setup R environment
|
|
99
|
+
# !!! anndata2ri works only with 3.6.3 on the tested machine
|
|
100
|
+
import rpy2
|
|
101
|
+
import anndata2ri
|
|
102
|
+
import rpy2.robjects as ro
|
|
103
|
+
from rpy2.robjects.conversion import localconverter
|
|
104
|
+
import rpy2.rinterface_lib.callbacks
|
|
105
|
+
import logging
|
|
106
|
+
rpy2.rinterface_lib.callbacks.logger.setLevel(logging.ERROR)
|
|
107
|
+
|
|
108
|
+
ro.r('library(tradeSeq)')
|
|
109
|
+
ro.r('library(clusterExperiment)')
|
|
110
|
+
anndata2ri.activate()
|
|
111
|
+
ro.numpy2ri.activate()
|
|
112
|
+
ro.pandas2ri.activate()
|
|
113
|
+
|
|
114
|
+
# prepare input adata for R
|
|
115
|
+
adata_deg = anndata.AnnData(
|
|
116
|
+
X = adata.layers['counts'],
|
|
117
|
+
var = pd.DataFrame(index=list(adata.var_names)),
|
|
118
|
+
obs = pd.DataFrame(index=list(adata.obs_names)))
|
|
119
|
+
adata_deg_var = adata_deg.copy()
|
|
120
|
+
sc.pp.filter_genes(adata_deg_var, min_cells=3)
|
|
121
|
+
sc.pp.filter_genes(adata_deg, min_cells=3)
|
|
122
|
+
sc.pp.normalize_total(adata_deg_var, target_sum=1e4)
|
|
123
|
+
sc.pp.log1p(adata_deg_var)
|
|
124
|
+
if n_var_genes is None:
|
|
125
|
+
sc.pp.highly_variable_genes(adata_deg_var, min_mean=0.0125, max_mean=3, min_disp=0.5)
|
|
126
|
+
elif not n_var_genes is None:
|
|
127
|
+
sc.pp.highly_variable_genes(adata_deg_var, n_top_genes=n_var_genes)
|
|
128
|
+
if var_genes is None:
|
|
129
|
+
adata_deg = adata_deg[:, adata_deg_var.var.highly_variable]
|
|
130
|
+
else:
|
|
131
|
+
adata_deg = adata_deg[:, var_genes]
|
|
132
|
+
del adata_deg_var
|
|
133
|
+
|
|
134
|
+
summary_name = 'commot-'+database_name+'-sum-'+summary
|
|
135
|
+
if summary == 'sender':
|
|
136
|
+
summary_abrv = 's'
|
|
137
|
+
else:
|
|
138
|
+
summary_abrv = 'r'
|
|
139
|
+
if not pathway_name is None:
|
|
140
|
+
comm_sum = adata.obsm[summary_name][summary_abrv+'-'+pathway_name].values.reshape(-1,1)
|
|
141
|
+
elif pathway_name is None:
|
|
142
|
+
comm_sum = adata.obsm[summary_name][summary_abrv+'-'+lr_pair[0]+'-'+lr_pair[1]].values.reshape(-1,1)
|
|
143
|
+
cell_weight = np.ones_like(comm_sum).reshape(-1,1)
|
|
144
|
+
|
|
145
|
+
# send adata to R
|
|
146
|
+
adata_r = anndata2ri.py2rpy(adata_deg)
|
|
147
|
+
ro.r.assign("adata", adata_r)
|
|
148
|
+
ro.r("X <- as.matrix( assay( adata, 'X') )")
|
|
149
|
+
ro.r.assign("pseudoTime", comm_sum)
|
|
150
|
+
ro.r.assign("cellWeight", cell_weight)
|
|
151
|
+
|
|
152
|
+
# perform analysis (tradeSeq-1.0.1 in R-3.6.3)
|
|
153
|
+
string_fitGAM = 'sce <- fitGAM(counts=X, pseudotime=pseudoTime[,1], cellWeights=cellWeight[,1], nknots=%d, verbose=TRUE)' % nknots
|
|
154
|
+
ro.r(string_fitGAM)
|
|
155
|
+
ro.r('assoRes <- data.frame( associationTest(sce, global=FALSE, lineage=TRUE) )')
|
|
156
|
+
ro.r('assoRes[is.nan(assoRes[,"waldStat_1"]),"waldStat_1"] <- 0.0')
|
|
157
|
+
ro.r('assoRes[is.nan(assoRes[,"df_1"]),"df_1"] <- 0.0')
|
|
158
|
+
ro.r('assoRes[is.nan(assoRes[,"pvalue_1"]),"pvalue_1"] <- 1.0')
|
|
159
|
+
with localconverter(ro.pandas2ri.converter):
|
|
160
|
+
df_assoRes = ro.r['assoRes']
|
|
161
|
+
ro.r('assoRes = assoRes[assoRes[,"pvalue_1"] <= %f,]' % deg_pvalue_cutoff)
|
|
162
|
+
ro.r('oAsso <- order(assoRes[,"waldStat_1"], decreasing=TRUE)')
|
|
163
|
+
if n_deg_genes is None:
|
|
164
|
+
n_deg_genes = df_assoRes.shape[0]
|
|
165
|
+
string_cluster = 'clusPat <- clusterExpressionPatterns(sce, nPoints = %d,' % n_points\
|
|
166
|
+
+ 'verbose=TRUE, genes = rownames(assoRes)[oAsso][1:min(%d,length(oAsso))],' % n_deg_genes \
|
|
167
|
+
+ ' k0s=4:5, alphas=c(0.1))'
|
|
168
|
+
ro.r(string_cluster)
|
|
169
|
+
ro.r('yhatScaled <- data.frame(clusPat$yhatScaled)')
|
|
170
|
+
with localconverter(ro.pandas2ri.converter):
|
|
171
|
+
yhat_scaled = ro.r['yhatScaled']
|
|
172
|
+
|
|
173
|
+
df_deg = df_assoRes.rename(columns={'waldStat_1':'waldStat', 'df_1':'df', 'pvalue_1':'pvalue'})
|
|
174
|
+
idx = np.argsort(-df_deg['waldStat'].values)
|
|
175
|
+
df_deg = df_deg.iloc[idx]
|
|
176
|
+
df_yhat = yhat_scaled
|
|
177
|
+
|
|
178
|
+
anndata2ri.deactivate()
|
|
179
|
+
ro.numpy2ri.deactivate()
|
|
180
|
+
ro.pandas2ri.deactivate()
|
|
181
|
+
|
|
182
|
+
return df_deg, df_yhat
|
|
183
|
+
|
|
184
|
+
def communication_deg_clustering(
|
|
185
|
+
df_deg: pd.DataFrame,
|
|
186
|
+
df_yhat: pd.DataFrame,
|
|
187
|
+
deg_clustering_npc: int = 10,
|
|
188
|
+
deg_clustering_knn: int = 5,
|
|
189
|
+
deg_clustering_res: float = 1.0,
|
|
190
|
+
n_deg_genes: int = 200,
|
|
191
|
+
p_value_cutoff: float = 0.05
|
|
192
|
+
):
|
|
193
|
+
"""
|
|
194
|
+
Cluster the communcation DE genes based on their fitted expression pattern.
|
|
195
|
+
|
|
196
|
+
Parameters
|
|
197
|
+
----------
|
|
198
|
+
df_deg
|
|
199
|
+
The deg analysis summary data frame obtained by running ``commot.tl.communication_deg_detection``.
|
|
200
|
+
Each row corresponds to one tested genes and columns include "waldStat" (Wald statistics), "df" (degrees of freedom), and "pvalue" (p-value of the Wald statistics).
|
|
201
|
+
df_yhat
|
|
202
|
+
The fitted (smoothed) gene expression pattern obtained by running ``commot.tl.communication_deg_detection``.
|
|
203
|
+
deg_clustering_npc
|
|
204
|
+
Number of PCs when performing PCA to cluster gene expression patterns
|
|
205
|
+
deg_clustering_knn
|
|
206
|
+
Number of neighbors when constructing the knn graph for leiden clustering.
|
|
207
|
+
deg_clustering_res
|
|
208
|
+
The resolution parameter for leiden clustering.
|
|
209
|
+
n_deg_genes
|
|
210
|
+
Number of top deg genes to cluster.
|
|
211
|
+
p_value_cutoff
|
|
212
|
+
The p-value cutoff for genes to be included in clustering analysis.
|
|
213
|
+
|
|
214
|
+
Returns
|
|
215
|
+
-------
|
|
216
|
+
df_deg_clus: pd.DataFrame
|
|
217
|
+
A data frame of clustered genes.
|
|
218
|
+
df_yhat_clus: pd.DataFrame
|
|
219
|
+
The fitted gene expression patterns of the clustered genes
|
|
220
|
+
|
|
221
|
+
"""
|
|
222
|
+
df_deg = df_deg[df_deg['pvalue'] <= p_value_cutoff]
|
|
223
|
+
n_deg_genes = min(n_deg_genes, df_deg.shape[0])
|
|
224
|
+
idx = np.argsort(-df_deg['waldStat'])
|
|
225
|
+
df_deg = df_deg.iloc[idx[:n_deg_genes]]
|
|
226
|
+
yhat_scaled = df_yhat.loc[df_deg.index]
|
|
227
|
+
x_pca = PCA(n_components=deg_clustering_npc, svd_solver='full').fit_transform(yhat_scaled.values)
|
|
228
|
+
cluster_labels = leiden_clustering(x_pca, k=deg_clustering_knn, resolution=deg_clustering_res, input='embedding')
|
|
229
|
+
|
|
230
|
+
data_tmp = np.concatenate((df_deg.values, cluster_labels.reshape(-1,1)),axis=1)
|
|
231
|
+
df_metadata = pd.DataFrame(data=data_tmp, index=df_deg.index,
|
|
232
|
+
columns=['waldStat','df','pvalue','cluster'] )
|
|
233
|
+
return df_metadata, yhat_scaled
|
|
234
|
+
|
|
235
|
+
def communication_impact(
|
|
236
|
+
adata: anndata.AnnData,
|
|
237
|
+
database_name: str = None,
|
|
238
|
+
pathway_name: str = None,
|
|
239
|
+
pathway_sum_only: bool = False,
|
|
240
|
+
heteromeric_delimiter: str = '_',
|
|
241
|
+
normalize: bool = False,
|
|
242
|
+
method: str = None,
|
|
243
|
+
corr_method: str = "spearman",
|
|
244
|
+
tree_method: str = "rf",
|
|
245
|
+
tree_ntrees: int = 100,
|
|
246
|
+
tree_repeat: int = 100,
|
|
247
|
+
tree_max_depth: int = 5,
|
|
248
|
+
tree_max_features: str = 'sqrt',
|
|
249
|
+
tree_learning_rate: float = 0.1,
|
|
250
|
+
tree_subsample: float = 1.0,
|
|
251
|
+
tree_combined: bool = False,
|
|
252
|
+
ds_genes: list = None,
|
|
253
|
+
bg_genes: Union[list, int] = 100
|
|
254
|
+
):
|
|
255
|
+
"""
|
|
256
|
+
Analyze impact of communication.
|
|
257
|
+
|
|
258
|
+
When using the 'treebased_score' as the method, there is potentially dilution of importance between the LR pairs if 'tree_combined' is set to True.
|
|
259
|
+
Therefore, if uniqueness of potential impact of various LR pairs on the target genes is not the focus, 'tree_combined' can be set to False.
|
|
260
|
+
If the unique impact of signaling in addition to the intra-cellular regulatory impact of target genes is not of interest, 'bg_genes' can be set to 0.
|
|
261
|
+
|
|
262
|
+
Parameters
|
|
263
|
+
----------
|
|
264
|
+
adata
|
|
265
|
+
The data matrix of shape ``n_obs`` × ``n_var``.
|
|
266
|
+
Rows correspond to cells or positions and columns to genes.
|
|
267
|
+
The full normalized dataset should be available in ``adata.raw``.
|
|
268
|
+
database_name
|
|
269
|
+
Name of the ligand-receptor database.
|
|
270
|
+
pathway_name
|
|
271
|
+
Name of the signaling pathway.
|
|
272
|
+
pathway_sum_only
|
|
273
|
+
If ``True``, examine only the total signaling activity sum over signaling pathways without looking at individual ligand-receptor pairs.
|
|
274
|
+
heteromeric_delimiter
|
|
275
|
+
The delimiter that separates heteromeric units in the ligand-receptor database.
|
|
276
|
+
normalize
|
|
277
|
+
Whether to perform normalization before determining variable genes.
|
|
278
|
+
method
|
|
279
|
+
'partial_corr': partial correlation.
|
|
280
|
+
'semipartial_corr': semipartial correlation.
|
|
281
|
+
'treebased_score': machine learning based score (ensemble of trees).
|
|
282
|
+
corr_method
|
|
283
|
+
The correlation coefficient to use when method is 'partial_corr' or 'semipartial_corr'.
|
|
284
|
+
'spearman': Spearman's r. 'pearson': Pearson's r.
|
|
285
|
+
tree_method
|
|
286
|
+
The ensemble of trees method to use when method is 'treebased_score'.
|
|
287
|
+
'gbt': gradient boosted trees. 'rf': random forest.
|
|
288
|
+
tree_ntrees
|
|
289
|
+
Number of trees when using 'treebased_score'.
|
|
290
|
+
tree_repeat
|
|
291
|
+
Number of times to repeat to account for randomness when using 'treebased_score'.
|
|
292
|
+
tree_mas_depth
|
|
293
|
+
Max depth of trees when using 'treebased_score'.
|
|
294
|
+
tree_max_features
|
|
295
|
+
Max features for trees when using 'treebased_score'.
|
|
296
|
+
tree_learning_rate
|
|
297
|
+
Learning rate when using 'treebased_score'.
|
|
298
|
+
tree_subsample
|
|
299
|
+
Subsample (between 0 and 1) when using 'treebased_score'.
|
|
300
|
+
tree_combined
|
|
301
|
+
If True, use a single model for each target gene with all features.
|
|
302
|
+
ds_genes
|
|
303
|
+
A list of genes for analyzing the correlation with cell-cell communication, for example, the highly variable genes.
|
|
304
|
+
bg_genes
|
|
305
|
+
If an integer, the top number of variable genes are used.
|
|
306
|
+
Alternatively, a list of genes.
|
|
307
|
+
|
|
308
|
+
Returns
|
|
309
|
+
-------
|
|
310
|
+
df_impact: pd.DataFrame
|
|
311
|
+
A data frame describing the correlation
|
|
312
|
+
between the ds_genes and cell-cell communication.
|
|
313
|
+
"""
|
|
314
|
+
|
|
315
|
+
# Get a list of background genes using most
|
|
316
|
+
# variable genes if only given a number.
|
|
317
|
+
adata_bg = adata.raw.to_adata()
|
|
318
|
+
adata_all = adata.raw.to_adata()
|
|
319
|
+
if normalize:
|
|
320
|
+
sc.pp.normalize_total(adata_bg, inplace=True)
|
|
321
|
+
sc.pp.log1p(adata_bg)
|
|
322
|
+
if np.isscalar(bg_genes):
|
|
323
|
+
ng_bg = int(bg_genes)
|
|
324
|
+
sc.pp.highly_variable_genes(adata_bg, n_top_genes=ng_bg)
|
|
325
|
+
adata_bg = adata_bg[:,adata_bg.var.highly_variable]
|
|
326
|
+
else:
|
|
327
|
+
adata_bg = adata_bg[:,bg_genes]
|
|
328
|
+
# Prepare downstream or upstream genes
|
|
329
|
+
ncell = adata.shape[0]
|
|
330
|
+
col_names = []
|
|
331
|
+
Ds_exps = []
|
|
332
|
+
Ds_exp_total = np.zeros([ncell], float)
|
|
333
|
+
for i in range(len(ds_genes)):
|
|
334
|
+
Ds_exp = np.array(adata_all[:,ds_genes[i]].X.toarray()).reshape(-1)
|
|
335
|
+
Ds_exps.append(Ds_exp)
|
|
336
|
+
col_names.append(ds_genes[i])
|
|
337
|
+
Ds_exp_total += Ds_exp
|
|
338
|
+
Ds_exps.append(Ds_exp_total); col_names.append('average')
|
|
339
|
+
# Impact analysis
|
|
340
|
+
df_ligrec = adata.uns['commot-'+database_name+'-info']['df_ligrec']
|
|
341
|
+
available_pathways = []
|
|
342
|
+
for i in range(df_ligrec.shape[0]):
|
|
343
|
+
_, _, tmp_pathway = df_ligrec.iloc[i,:]
|
|
344
|
+
if not tmp_pathway in available_pathways:
|
|
345
|
+
available_pathways.append(tmp_pathway)
|
|
346
|
+
pathway_genes = [[] for i in range(len(available_pathways))]
|
|
347
|
+
all_lr_genes = []
|
|
348
|
+
for i in range(df_ligrec.shape[0]):
|
|
349
|
+
tmp_lig, tmp_rec, tmp_pathway = df_ligrec.iloc[i,:]
|
|
350
|
+
idx = available_pathways.index(tmp_pathway)
|
|
351
|
+
tmp_ligs = tmp_lig.split(heteromeric_delimiter)
|
|
352
|
+
tmp_recs = tmp_rec.split(heteromeric_delimiter)
|
|
353
|
+
for lig in tmp_ligs:
|
|
354
|
+
if not lig in pathway_genes[idx]:
|
|
355
|
+
pathway_genes[idx].append(lig)
|
|
356
|
+
if not lig in all_lr_genes:
|
|
357
|
+
all_lr_genes.append(lig)
|
|
358
|
+
for rec in tmp_recs:
|
|
359
|
+
if not rec in pathway_genes[idx]:
|
|
360
|
+
pathway_genes[idx].append(rec)
|
|
361
|
+
if not rec in all_lr_genes:
|
|
362
|
+
all_lr_genes.append(rec)
|
|
363
|
+
bg_genes = list( adata_bg.var_names )
|
|
364
|
+
|
|
365
|
+
sum_names = []
|
|
366
|
+
exclude_lr_genes_list = []
|
|
367
|
+
if pathway_name is None and not pathway_sum_only:
|
|
368
|
+
for i in range(df_ligrec.shape[0]):
|
|
369
|
+
tmp_lig, tmp_rec, _ = df_ligrec.iloc[i,:]
|
|
370
|
+
sum_names.append("%s-%s" % (tmp_lig, tmp_rec))
|
|
371
|
+
exclude_lr_genes_list.append(set(tmp_lig.split(heteromeric_delimiter)).union(set(tmp_rec.split(heteromeric_delimiter))))
|
|
372
|
+
for tmp_pathway in available_pathways:
|
|
373
|
+
sum_names.append(tmp_pathway)
|
|
374
|
+
exclude_lr_genes_list.append(set(pathway_genes[available_pathways.index(tmp_pathway)]))
|
|
375
|
+
sum_names.append('total-total')
|
|
376
|
+
exclude_lr_genes_list.append(set(all_lr_genes))
|
|
377
|
+
elif not pathway_name is None and not pathway_sum_only:
|
|
378
|
+
for i in range(df_ligrec.shape[0]):
|
|
379
|
+
tmp_lig, tmp_rec, tmp_pathway = df_ligrec.iloc[i,:]
|
|
380
|
+
if tmp_pathway == pathway_name:
|
|
381
|
+
sum_names.append("%s-%s" % (tmp_lig, tmp_rec))
|
|
382
|
+
exclude_lr_genes_list.append(set(tmp_lig.split(heteromeric_delimiter)).union(set(tmp_rec.split(heteromeric_delimiter))))
|
|
383
|
+
sum_names.append(pathway_name)
|
|
384
|
+
exclude_lr_genes_list.append(set(pathway_genes[available_pathways.index(pathway_name)]))
|
|
385
|
+
|
|
386
|
+
elif pathway_sum_only:
|
|
387
|
+
sum_names = available_pathways
|
|
388
|
+
for i in range(len(available_pathways)):
|
|
389
|
+
exclude_lr_genes_list.append(set(pathway_genes[i]))
|
|
390
|
+
|
|
391
|
+
nrows = 2 * len(sum_names)
|
|
392
|
+
|
|
393
|
+
ncols = len(ds_genes) + 1
|
|
394
|
+
impact_mat = np.empty([nrows, ncols], float)
|
|
395
|
+
|
|
396
|
+
row_names_sender = []; row_names_receiver = []
|
|
397
|
+
exclude_lr_genes_list = []
|
|
398
|
+
for i in range(len(sum_names)):
|
|
399
|
+
row_names_sender.append('s-%s' % sum_names[i])
|
|
400
|
+
row_names_receiver.append('r-%s' % sum_names[i])
|
|
401
|
+
row_names = row_names_sender + row_names_receiver
|
|
402
|
+
exclude_lr_genes_list = exclude_lr_genes_list + exclude_lr_genes_list
|
|
403
|
+
|
|
404
|
+
print(nrows, ncols)
|
|
405
|
+
for j in range(ncols):
|
|
406
|
+
print(j)
|
|
407
|
+
if j == ncols-1:
|
|
408
|
+
exclude_ds_genes = set(ds_genes)
|
|
409
|
+
else:
|
|
410
|
+
exclude_ds_genes = set([ds_genes[j]])
|
|
411
|
+
if method == 'treebased_score' and tree_combined:
|
|
412
|
+
exclude_lr_genes = set(all_lr_genes)
|
|
413
|
+
exclude_genes = list(exclude_lr_genes.union(exclude_ds_genes))
|
|
414
|
+
use_genes = list( set(bg_genes) - set(exclude_genes) )
|
|
415
|
+
bg_mat = np.array( adata_bg[:,use_genes].X.toarray() )
|
|
416
|
+
sum_mat = np.concatenate((adata.obsm['commot-'+database_name+'-sum-sender'][row_names_sender].values, \
|
|
417
|
+
adata.obsm['commot-'+database_name+'-sum-receiver'][row_names_receiver].values), axis=1)
|
|
418
|
+
r = treebased_score_multifeature(sum_mat, Ds_exps[j], bg_mat,
|
|
419
|
+
n_trees = tree_ntrees, n_repeat = tree_repeat,
|
|
420
|
+
max_depth = tree_max_depth, max_features = tree_max_features,
|
|
421
|
+
learning_rate = tree_learning_rate, subsample = tree_subsample)
|
|
422
|
+
impact_mat[:,j] = r[:]
|
|
423
|
+
else:
|
|
424
|
+
for i in range(nrows):
|
|
425
|
+
row_name = row_names[i]
|
|
426
|
+
exclude_lr_genes = exclude_lr_genes_list[i]
|
|
427
|
+
|
|
428
|
+
exclude_genes = list(exclude_lr_genes.union(exclude_ds_genes))
|
|
429
|
+
use_genes = list( set(bg_genes) - set(exclude_genes) )
|
|
430
|
+
bg_mat = np.array( adata_bg[:,use_genes].X.toarray() )
|
|
431
|
+
if row_name[0] == 's':
|
|
432
|
+
sum_vec = adata.obsm['commot-'+database_name+'-sum-sender'][row_name].values.reshape(-1,1)
|
|
433
|
+
elif row_name[0] == 'r':
|
|
434
|
+
sum_vec = adata.obsm['commot-'+database_name+'-sum-receiver'][row_name].values.reshape(-1,1)
|
|
435
|
+
if method == "partial_corr":
|
|
436
|
+
r,p = partial_corr(sum_vec, Ds_exps[j].reshape(-1,1), bg_mat, method=corr_method)
|
|
437
|
+
elif method == "semipartial_corr":
|
|
438
|
+
r,p = semipartial_corr(sum_vec, Ds_exps[j].reshape(-1,1), ycov=bg_mat, method=corr_method)
|
|
439
|
+
elif method == "treebased_score":
|
|
440
|
+
r = treebased_score(sum_vec, Ds_exps[j], bg_mat,
|
|
441
|
+
n_trees = tree_ntrees, n_repeat = tree_repeat,
|
|
442
|
+
max_depth = tree_max_depth, max_features = tree_max_features,
|
|
443
|
+
learning_rate = tree_learning_rate, subsample = tree_subsample)
|
|
444
|
+
impact_mat[i,j] = r
|
|
445
|
+
df_impact = pd.DataFrame(data=impact_mat, index = row_names, columns = col_names)
|
|
446
|
+
return df_impact
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
# Has not adapted new naming scheme
|
|
450
|
+
def group_cluster_communication(
|
|
451
|
+
adata: anndata.AnnData,
|
|
452
|
+
clustering: str = None,
|
|
453
|
+
cluster_permutation_type: str = 'label',
|
|
454
|
+
keys = None,
|
|
455
|
+
p_value_cutoff: float = 0.05,
|
|
456
|
+
quantile_cutoff: float = 0.99,
|
|
457
|
+
dissimilarity_method: str = None,
|
|
458
|
+
leiden_k: int = 5,
|
|
459
|
+
leiden_resolution: float = 1.0,
|
|
460
|
+
leiden_random_seed: int = 1,
|
|
461
|
+
leiden_n_iterations: int = -1,
|
|
462
|
+
d_global_structure_weights: tuple = (0.45,0.45,0.1)
|
|
463
|
+
):
|
|
464
|
+
"""
|
|
465
|
+
Idenfitify groups of cluster-cluster communication with similar
|
|
466
|
+
pattern.
|
|
467
|
+
|
|
468
|
+
The CCC inference should have been summarized to cluster level using either :func:`commot.tl.cluster_communication` function
|
|
469
|
+
or :func:`commot.tl.cluster_communication_spatial_permutation` function. The dissimilarities among different ligand-receptor pairs or signaling pathways
|
|
470
|
+
are first quantified which will be used with the leiden clustering algorithm [Traag2019]_ to cluster these CCC networks.
|
|
471
|
+
|
|
472
|
+
Parameters
|
|
473
|
+
----------
|
|
474
|
+
adata
|
|
475
|
+
The data matrix with the cluster-cluster communication
|
|
476
|
+
info stored in ``adata.uns``.
|
|
477
|
+
clustering
|
|
478
|
+
Name of clustering with the labels stored in ``.obs[clustering]``.
|
|
479
|
+
cluster_permutation_type
|
|
480
|
+
``'label'`` if the function :func:`commot.tl.cluster_communication` was used and ``'spatial'`` if :func:`commot.tl.cluster_communication_spatial_permutation` was used.
|
|
481
|
+
keys
|
|
482
|
+
A list of keys for the analyzed communication connections as strings.
|
|
483
|
+
For example, the string ``'databaseX-pathwayX'`` represents the cluster-level CCC of signaling pathway "pathwayX" computed with the LR database "databaseX".
|
|
484
|
+
For another example, the string ``'databaseX-ligA-recA'`` represents the cluster-level CCC of the LR pair "ligA-recA" computed with the LR database "databaseX".
|
|
485
|
+
p_value_cutoff
|
|
486
|
+
The cutoff of p-value for including an edge.
|
|
487
|
+
quantile_cutoff
|
|
488
|
+
The quantile cutoff for including an edge. Set to 1 to disable this criterion.
|
|
489
|
+
The quantile_cutoff and p_value_cutoff works in the "or" logic to avoid missing
|
|
490
|
+
significant signaling connections.
|
|
491
|
+
An edge will be ignored only if it has a p-value greater than the ``p_value_cutoff`` and a score smaller than the score quantile cutoff.
|
|
492
|
+
dissimilarity_method
|
|
493
|
+
The dissimilarity measurement between graphs to use.
|
|
494
|
+
'jaccard' for Jaccard distance.
|
|
495
|
+
'jaccard_weighted' for weighted Jaccard distance.
|
|
496
|
+
'global_structure' for a metric focusing on global structure [Schieber2017]_.
|
|
497
|
+
leiden_k
|
|
498
|
+
Number of neighbors for the knn-graph for using leiden clustering algorithm.
|
|
499
|
+
leiden_resolution
|
|
500
|
+
The resolution parameter for the leiden clustering algorithm.
|
|
501
|
+
leiden_random_seed
|
|
502
|
+
The random seed for the leiden clustering algorithm.
|
|
503
|
+
leiden_n_iterations
|
|
504
|
+
The maximum number of iterations for the leiden algorithm.
|
|
505
|
+
The algorithm will run until convergence if set to -1.
|
|
506
|
+
d_global_structure_weights
|
|
507
|
+
The weights for the three terms in the global structural dissimilarity.
|
|
508
|
+
See [Schieber2017]_ for more information.
|
|
509
|
+
|
|
510
|
+
Returns
|
|
511
|
+
-------
|
|
512
|
+
communication_clusterid : np.ndarray
|
|
513
|
+
The group id of the cluster-cluster communications.
|
|
514
|
+
D : np.ndarray
|
|
515
|
+
The dissimilarity matrix for the cluster-cluster communications.
|
|
516
|
+
|
|
517
|
+
References
|
|
518
|
+
----------
|
|
519
|
+
.. [Schieber2017] Schieber, T. A., Carpi, L., Díaz-Guilera, A., Pardalos,
|
|
520
|
+
P. M., Masoller, C., & Ravetti, M. G. (2017). Quantification
|
|
521
|
+
of network structural dissimilarities. Nature communications, 8(1), 1-10.
|
|
522
|
+
.. [Traag2019] Traag, V. A., Waltman, L., & Van Eck, N. J. (2019).
|
|
523
|
+
From Louvain to Leiden: guaranteeing well-connected communities. Scientific reports, 9(1), 1-12.
|
|
524
|
+
|
|
525
|
+
"""
|
|
526
|
+
|
|
527
|
+
# Get a list of filtered communication matrices corresponding to the keys.
|
|
528
|
+
As = []
|
|
529
|
+
for key in keys:
|
|
530
|
+
if cluster_permutation_type == 'label':
|
|
531
|
+
tmp_name = 'commot_cluster-%s-%s' % (clustering,key)
|
|
532
|
+
elif cluster_permutation_type == 'spatial':
|
|
533
|
+
tmp_name = 'commot_cluster_spatial_permutation-%s-%s' % (clustering,key)
|
|
534
|
+
X_tmp = adata.uns[tmp_name]['communication_matrix'].values.copy()
|
|
535
|
+
pvalue_tmp = adata.uns[tmp_name]['communication_pvalue'].values.copy()
|
|
536
|
+
if not quantile_cutoff is None:
|
|
537
|
+
cutoff = np.quantile(X_tmp.reshape(-1), quantile_cutoff)
|
|
538
|
+
else:
|
|
539
|
+
cutoff = np.inf
|
|
540
|
+
tmp_mask = ( X_tmp < cutoff ) * ( pvalue_tmp > p_value_cutoff )
|
|
541
|
+
X_tmp[tmp_mask] = 0
|
|
542
|
+
As.append(X_tmp)
|
|
543
|
+
# Get a distance/dissimilarity matrix between the communication matrices.
|
|
544
|
+
D = np.zeros([len(keys), len(keys)], float)
|
|
545
|
+
for i in range(len(keys)-1):
|
|
546
|
+
for j in range(i+1,len(keys)):
|
|
547
|
+
if dissimilarity_method == 'jaccard':
|
|
548
|
+
d = d_graph_local_jaccard(As[i], As[j])
|
|
549
|
+
elif dissimilarity_method == 'jaccard_weighted':
|
|
550
|
+
d = d_graph_local_jaccard_weighted(As[i], As[j])
|
|
551
|
+
elif dissimilarity_method == 'global_structure':
|
|
552
|
+
w1,w2,w3 = d_global_structure_weights
|
|
553
|
+
d = d_graph_global_structure(As[i], As[j], w1=w1, w2=w2, w3=w3)
|
|
554
|
+
D[i,j] = d; D[j,i] = d
|
|
555
|
+
# Perform clustering
|
|
556
|
+
leiden_k = min(leiden_k, len(keys)-1)
|
|
557
|
+
communication_clusterid = leiden_clustering(D,
|
|
558
|
+
k = leiden_k, resolution = leiden_resolution,
|
|
559
|
+
random_seed = leiden_random_seed,
|
|
560
|
+
n_iterations = leiden_n_iterations)
|
|
561
|
+
|
|
562
|
+
return communication_clusterid, D
|
|
563
|
+
|
|
564
|
+
def group_cell_communication(
|
|
565
|
+
adata: anndata.AnnData,
|
|
566
|
+
keys = None,
|
|
567
|
+
bin_method: str = 'gaussian_mixture',
|
|
568
|
+
bin_append_zeros: str = 'full',
|
|
569
|
+
bin_random_state: int = 1,
|
|
570
|
+
bin_cutoff: float = 0,
|
|
571
|
+
knn: int = 2,
|
|
572
|
+
dissimilarity_method: str = 'graphwave',
|
|
573
|
+
kw_graphwave: dict = {'sample_number':200, 'step_size':0.1, 'heat_coefficient': 1.0, 'approximation':100, 'mechanism':'approximation', 'switch':1000, 'seed':42},
|
|
574
|
+
leiden_k: int = 5,
|
|
575
|
+
leiden_resolution: float = 1.0,
|
|
576
|
+
leiden_random_seed: int = 1,
|
|
577
|
+
leiden_n_iterations: int = -1
|
|
578
|
+
):
|
|
579
|
+
"""
|
|
580
|
+
Idenfitify groups of cell-cell communication with similar
|
|
581
|
+
pattern.
|
|
582
|
+
|
|
583
|
+
The cell-cell communication should have been computed by the function :func:`commot.tl.spatial_communication`.
|
|
584
|
+
|
|
585
|
+
Parameters
|
|
586
|
+
----------
|
|
587
|
+
adata
|
|
588
|
+
The data matrix with the cell-cell communication
|
|
589
|
+
info stored in ``adata.obsp``.
|
|
590
|
+
keys
|
|
591
|
+
A list of keys for the analyzed communication connections as strings.
|
|
592
|
+
For example, the string ``'databaseX-pathwayX'`` represents the CCC of signaling pathway "pathwayX" computed with the LR database "databaseX".
|
|
593
|
+
For another example, the string ``'databaseX-ligA-recA'`` represents the CCC of the LR pair "ligA-recA" computed with the LR database "databaseX".
|
|
594
|
+
The cell-level CCC networks corresponding to the above examples are stored in ``.obsp['commot-databaseX-pathwayX]`` and ``.obsp['commot-databaseX-ligA-recA']``.
|
|
595
|
+
bin_method
|
|
596
|
+
Method for binarize communication connections. Choices: 'gaussian_mixture', 'kmeans'.
|
|
597
|
+
bin_append_zeros
|
|
598
|
+
Number of zeros to append to the non-zero entries when running the binarization.
|
|
599
|
+
'full' use the full flattened cell-by-cell communication matrix.
|
|
600
|
+
'match' append the same number of zeros to the vector of non-zero entries.
|
|
601
|
+
bin_random_state
|
|
602
|
+
The random seed for binarization methods.
|
|
603
|
+
bin_cutoff
|
|
604
|
+
Force all connections with a weight smaller than or equal to bin_cutoff to be zero
|
|
605
|
+
, regardless of binarization result.
|
|
606
|
+
knn
|
|
607
|
+
Number of neighbors for building the spatial knn graph.
|
|
608
|
+
dissimilarity_method
|
|
609
|
+
The method for quantifying dissimilarity.
|
|
610
|
+
'graphwave', node structural embedding by GraphWave [Donnat2018]_ implemented
|
|
611
|
+
in `Karate Club
|
|
612
|
+
<https://github.com/benedekrozemberczki/karateclub/>`_.
|
|
613
|
+
kw_graphwave
|
|
614
|
+
Keywords for GraphWave. Defaults: {'sample_number':200, 'step_size':0.1, 'heat_coefficient': 1.0,
|
|
615
|
+
'approximation':100, 'mechanism':'approximation', 'switch':1000, 'seed':42} See details at `Karate Club
|
|
616
|
+
<https://github.com/benedekrozemberczki/karateclub/>`_.
|
|
617
|
+
leiden_k
|
|
618
|
+
Number of neighbors for the knn-graph to be fed to leiden clustering algorithm.
|
|
619
|
+
leiden_resolution
|
|
620
|
+
The resolution parameter for the leiden clustering algorithm.
|
|
621
|
+
leiden_random_seed
|
|
622
|
+
The random seed for the leiden clustering algorithm.
|
|
623
|
+
leiden_n_iterations
|
|
624
|
+
The maximum number of iterations for the leiden algorithm.
|
|
625
|
+
The algorithm will run until convergence if set to -1.
|
|
626
|
+
|
|
627
|
+
Returns
|
|
628
|
+
-------
|
|
629
|
+
communication_clusterid : np.ndarray
|
|
630
|
+
The group id of the cell-cell communications.
|
|
631
|
+
D : np.ndarray
|
|
632
|
+
The dissimilarity matrix for the cell-cell communications.
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
References
|
|
636
|
+
----------
|
|
637
|
+
.. [Donnat2018] Donnat, C., Zitnik, M., Hallac, D., & Leskovec, J. (2018, July). Learning structural node embeddings
|
|
638
|
+
via diffusion wavelets. In Proceedings of the 24th ACM SIGKDD International
|
|
639
|
+
Conference on Knowledge Discovery & Data Mining (pp. 1320-1329).
|
|
640
|
+
|
|
641
|
+
"""
|
|
642
|
+
|
|
643
|
+
nkey = len(keys)
|
|
644
|
+
ncell = adata.shape[0]
|
|
645
|
+
|
|
646
|
+
# Get a dissimilarity matrix D
|
|
647
|
+
if dissimilarity_method == 'graphwave':
|
|
648
|
+
if knn > 0:
|
|
649
|
+
A_knn = kneighbors_graph(adata.obsm['spatial'],
|
|
650
|
+
knn, mode = 'connectivity', include_self = False)
|
|
651
|
+
A_spatial = A_knn + A_knn.T
|
|
652
|
+
A_spatial.eliminate_zeros()
|
|
653
|
+
A_spatial.data[:] = 1
|
|
654
|
+
elif knn == 0:
|
|
655
|
+
A_spatial = sparse.csr_matrix((ncell,ncell))
|
|
656
|
+
heat_mats = []
|
|
657
|
+
for key in keys:
|
|
658
|
+
A_signal = adata.obsp['commot-%s' % key]
|
|
659
|
+
A_signal_bin = binarize_sparse_matrix(A_signal, method = bin_method,
|
|
660
|
+
append_zeros = bin_append_zeros, random_state = bin_random_state)
|
|
661
|
+
A_signal_bin_sym = A_signal_bin + A_signal_bin.T
|
|
662
|
+
A_signal_bin_sym.eliminate_zeros()
|
|
663
|
+
A_signal_bin_sym.data[:] = 1
|
|
664
|
+
A = A_spatial + A_signal_bin_sym
|
|
665
|
+
gw = karateclub.GraphWave(**kw_graphwave)
|
|
666
|
+
G = nx.from_scipy_sparse_matrix(A)
|
|
667
|
+
gw.fit(G)
|
|
668
|
+
R = gw.get_embedding()
|
|
669
|
+
heat_mats.append(R)
|
|
670
|
+
D = np.zeros([nkey,nkey],float)
|
|
671
|
+
for i in range(nkey-1):
|
|
672
|
+
for j in range(i+1, nkey):
|
|
673
|
+
d = np.sqrt( np.linalg.norm(heat_mats[i] - heat_mats[j]) ** 2 / float(ncell) )
|
|
674
|
+
D[i,j] = d; D[j,i] = d
|
|
675
|
+
|
|
676
|
+
# Perform clustering on D
|
|
677
|
+
leiden_k = min(leiden_k, len(keys)-1)
|
|
678
|
+
communication_clusterid = leiden_clustering(D,
|
|
679
|
+
k = leiden_k, resolution = leiden_resolution,
|
|
680
|
+
random_seed = leiden_random_seed,
|
|
681
|
+
n_iterations = leiden_n_iterations)
|
|
682
|
+
|
|
683
|
+
return communication_clusterid, D
|
|
684
|
+
|
|
685
|
+
|
|
686
|
+
def group_communication_direction(
|
|
687
|
+
adata: anndata.AnnData,
|
|
688
|
+
keys: list = None,
|
|
689
|
+
summary: str = 'sender',
|
|
690
|
+
knn_smoothing: int = -1,
|
|
691
|
+
normalize_vf: str = 'quantile',
|
|
692
|
+
normalize_quantile: float = 0.99,
|
|
693
|
+
dissimilarity_method: str = 'dot_product',
|
|
694
|
+
leiden_k: int = 5,
|
|
695
|
+
leiden_resolution: float = 1.0,
|
|
696
|
+
leiden_random_seed: int = 1,
|
|
697
|
+
leiden_n_iterations: int = -1
|
|
698
|
+
):
|
|
699
|
+
"""
|
|
700
|
+
Idenfitify groups of communication directions with similar
|
|
701
|
+
pattern.
|
|
702
|
+
|
|
703
|
+
The cell-cell communication should have been computed by the function :func:`commot.tl.spatial_communication`.
|
|
704
|
+
The cell-cell communication direction should have been computed by the function :func:`commot.tl.communication_direction`.
|
|
705
|
+
|
|
706
|
+
Parameters
|
|
707
|
+
----------
|
|
708
|
+
adata
|
|
709
|
+
The data matrix with the communication direction
|
|
710
|
+
info stored in ``adata.obsm``, e.g., ``.obsm['commot_sender_vf-databaseX-ligA-recA']`` stores the CCC direction of the LR pair 'ligA-recA' computed
|
|
711
|
+
with the LR database 'databaseX' summarized in the signal senders' perspective
|
|
712
|
+
keys
|
|
713
|
+
A list of keys for the analyzed communication connections as strings.
|
|
714
|
+
For example, the string ``'databaseX-pathwayX'`` represents the CCC of signaling pathway "pathwayX" computed with the LR database "databaseX".
|
|
715
|
+
For another example, the string ``'databaseX-ligA-recA'`` represents the CCC of the LR pair "ligA-recA" computed with the LR database "databaseX".
|
|
716
|
+
The computed CCC direction corresponding to the above examples (summarized as 'sent to' or 'received from' directions) should be available in
|
|
717
|
+
``.obsm['commot_sender_vf-databaseX-pathwayX]``, ``.obsm['commot_receiver_vf-databaseX-pathwayX]``and
|
|
718
|
+
``.obsm['commot_sender_vf-databaseX-ligA-recA']``, ``.obsm['commot_receiver_vf-databaseX-ligA-recA']``.
|
|
719
|
+
summary
|
|
720
|
+
If 'sender', use the vector field describing to which direction the signals are sent to.
|
|
721
|
+
If 'receiver', use the vector field describing from which direction the signals are received from.
|
|
722
|
+
knn_smoothing
|
|
723
|
+
The number of neighbors to smooth the communication direction.
|
|
724
|
+
If -1, no smoothing is performed.
|
|
725
|
+
normalize_vf
|
|
726
|
+
If 'quantile', divide all values by the length
|
|
727
|
+
given by the normalize_quantile parameter.
|
|
728
|
+
If 'unit_norm', normalize each individual vector into unit norm.
|
|
729
|
+
If None, original unit is used.
|
|
730
|
+
normalize_quantile
|
|
731
|
+
The quantile parameter to use if normalize_vf is set to 'quantile'.
|
|
732
|
+
dissimilarity_method
|
|
733
|
+
Currently, only dot_product is implemented.
|
|
734
|
+
leiden_k
|
|
735
|
+
Number of neighbors for the knn-graph to be fed to leiden clustering algorithm.
|
|
736
|
+
leiden_resolution
|
|
737
|
+
The resolution parameter for the leiden clustering algorithm.
|
|
738
|
+
leiden_random_seed
|
|
739
|
+
The random seed for the leiden clustering algorithm.
|
|
740
|
+
leiden_n_iterations
|
|
741
|
+
The maximum number of iterations for the leiden algorithm.
|
|
742
|
+
The algorithm will run until convergence if set to -1.
|
|
743
|
+
|
|
744
|
+
Returns
|
|
745
|
+
-------
|
|
746
|
+
direction_clusterid : np.ndarray
|
|
747
|
+
The group id of the communication directions.
|
|
748
|
+
D : np.ndarray
|
|
749
|
+
The dissimilarity matrix for the communication directions.
|
|
750
|
+
|
|
751
|
+
"""
|
|
752
|
+
|
|
753
|
+
# Process the vector fields
|
|
754
|
+
V_list = []
|
|
755
|
+
for key in keys:
|
|
756
|
+
V = adata.obsm['commot_%s_vf-%s' % (summary, key)]
|
|
757
|
+
V_processed = preprocess_vector_field(adata.obsm['spatial'],
|
|
758
|
+
V, knn_smoothing = knn_smoothing, normalize_vf = normalize_vf,
|
|
759
|
+
quantile = normalize_quantile)
|
|
760
|
+
V_list.append(V_processed)
|
|
761
|
+
# Get a distance matrix between the vector fields
|
|
762
|
+
nV = len(keys)
|
|
763
|
+
D = np.zeros([nV,nV], float)
|
|
764
|
+
for i in range(nV-1):
|
|
765
|
+
Vi = V_list[i]
|
|
766
|
+
for j in range(i+1,nV):
|
|
767
|
+
Vj = V_list[j]
|
|
768
|
+
if dissimilarity_method == 'dot_product':
|
|
769
|
+
d = np.exp( - ( ( Vi * Vj ).sum(axis=1) ).mean() )
|
|
770
|
+
D[i,j] = d; D[j,i] = d
|
|
771
|
+
# Cluster the vector fields with the D matrix
|
|
772
|
+
# Perform clustering
|
|
773
|
+
leiden_k = min(leiden_k, len(keys)-1)
|
|
774
|
+
direction_clusterid = leiden_clustering(D,
|
|
775
|
+
k = leiden_k, resolution = leiden_resolution,
|
|
776
|
+
random_seed = leiden_random_seed,
|
|
777
|
+
n_iterations = leiden_n_iterations)
|
|
778
|
+
|
|
779
|
+
return direction_clusterid, D
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
def communication_spatial_autocorrelation(
|
|
783
|
+
adata: anndata.AnnData,
|
|
784
|
+
keys: list = None,
|
|
785
|
+
method: str = 'Moran',
|
|
786
|
+
normalize_vf: bool = False,
|
|
787
|
+
summary: str = 'sender',
|
|
788
|
+
weight_bandwidth: float = None,
|
|
789
|
+
weight_k: int = 10,
|
|
790
|
+
weight_function: str = 'triangular',
|
|
791
|
+
weight_row_standardize: bool = False,
|
|
792
|
+
n_permutations: int = 999
|
|
793
|
+
):
|
|
794
|
+
"""
|
|
795
|
+
Spatial autocorrelation of communication directions.
|
|
796
|
+
|
|
797
|
+
The spatial autocorrelation helps to detect spatial regions within which the CCC directions are similar.
|
|
798
|
+
The cell-cell communication should have been computed by the function :func:`commot.tl.spatial_communication`.
|
|
799
|
+
The cell-cell communication direction should have been computed by the function :func:`commot.tl.communication_direction`.
|
|
800
|
+
|
|
801
|
+
Parameters
|
|
802
|
+
----------
|
|
803
|
+
adata
|
|
804
|
+
The data matrix with the communication vector fields
|
|
805
|
+
info stored in ``adata.ubsm``.
|
|
806
|
+
keys
|
|
807
|
+
A list of keys for the analyzed communication connections as strings.
|
|
808
|
+
For example, the string ``'databaseX-pathwayX'`` represents the CCC of signaling pathway "pathwayX" computed with the LR database "databaseX".
|
|
809
|
+
For another example, the string ``'databaseX-ligA-recA'`` represents the CCC of the LR pair "ligA-recA" computed with the LR database "databaseX".
|
|
810
|
+
The computed CCC direction corresponding to the above examples (summarized as 'sent to' or 'received from' directions) should be available in
|
|
811
|
+
``.obsm['commot_sender_vf-databaseX-pathwayX]``, ``.obsm['commot_receiver_vf-databaseX-pathwayX]``and
|
|
812
|
+
``.obsm['commot_sender_vf-databaseX-ligA-recA']``, ``.obsm['commot_receiver_vf-databaseX-ligA-recA']``.
|
|
813
|
+
method
|
|
814
|
+
The method to use. Currently, only Moran's I [Liu2015]_ for vectors is implemented.
|
|
815
|
+
normalize_vf
|
|
816
|
+
Whether to normalize the vector field so that the autocorrelation only reflects
|
|
817
|
+
directions.
|
|
818
|
+
summary
|
|
819
|
+
If 'sender', use the vector field describing to which direction the signals are sent.
|
|
820
|
+
If 'receiver', use the vector field describing from which direction the signals are from.
|
|
821
|
+
weight_bandwidth
|
|
822
|
+
The bandwidth for the kernel to assign knn graph weights.
|
|
823
|
+
If given, weight_k is ignored.
|
|
824
|
+
weight_k
|
|
825
|
+
The number of nearest neighbors for the knn graph.
|
|
826
|
+
weight_function
|
|
827
|
+
Kernel functions for assigning weight.
|
|
828
|
+
Choices: 'triangular','uniform','quadratic','quartic','gaussian'.
|
|
829
|
+
See libpysal.weights.Kernel of the ``libpysal`` package for details.
|
|
830
|
+
weight_row_standardize
|
|
831
|
+
Whether to standardize the weights so that the heterogeneity in local cell/position
|
|
832
|
+
density does not affect the results.
|
|
833
|
+
n_permutations
|
|
834
|
+
Number of permutations for computing p-values.
|
|
835
|
+
|
|
836
|
+
Returns
|
|
837
|
+
-------
|
|
838
|
+
moranI : np.ndarray
|
|
839
|
+
A vector of moran's I statistics for corresponding to each key in keys.
|
|
840
|
+
p_value : np.ndarray
|
|
841
|
+
The p-values.
|
|
842
|
+
|
|
843
|
+
References
|
|
844
|
+
----------
|
|
845
|
+
.. [Liu2015] Liu, Y., Tong, D., & Liu, X. (2015). Measuring spatial
|
|
846
|
+
autocorrelation of vectors. Geographical Analysis, 47(3), 300-319.
|
|
847
|
+
|
|
848
|
+
"""
|
|
849
|
+
|
|
850
|
+
moranI = []
|
|
851
|
+
p_value = []
|
|
852
|
+
X = adata.obsm['spatial']
|
|
853
|
+
for key in keys:
|
|
854
|
+
V = adata.obsm['commot_%s_vf-%s' % (summary, key)]
|
|
855
|
+
if normalize_vf:
|
|
856
|
+
V = normalize(V)
|
|
857
|
+
I,p = moranI_vector_global(X, V,
|
|
858
|
+
weight_bandwidth = weight_bandwidth,
|
|
859
|
+
weight_k = weight_k,
|
|
860
|
+
weight_function = weight_function,
|
|
861
|
+
weight_row_standardize = weight_row_standardize,
|
|
862
|
+
n_permutations = n_permutations)
|
|
863
|
+
moranI.append(I)
|
|
864
|
+
p_value.append(p)
|
|
865
|
+
moranI = np.array(moranI, float)
|
|
866
|
+
p_value = np.array(p_value, float)
|
|
867
|
+
|
|
868
|
+
return moranI, p_value
|
|
869
|
+
|
|
870
|
+
|