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,161 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
import numpy as np
|
|
3
|
+
import pandas as pd
|
|
4
|
+
import scanpy as sc
|
|
5
|
+
import ot
|
|
6
|
+
from scipy import sparse
|
|
7
|
+
from scipy.spatial import distance_matrix
|
|
8
|
+
import anndata
|
|
9
|
+
from .._optimal_transport import cot_sparse
|
|
10
|
+
from .._optimal_transport import cot_combine_sparse
|
|
11
|
+
from .._optimal_transport import uot
|
|
12
|
+
from .._optimal_transport import usot
|
|
13
|
+
|
|
14
|
+
def pairwise_scc(X1, X2):
|
|
15
|
+
X1 = X1.argsort(axis=1).argsort(axis=1)
|
|
16
|
+
X2 = X2.argsort(axis=1).argsort(axis=1)
|
|
17
|
+
X1 = (X1-X1.mean(axis=1, keepdims=True))/X1.std(axis=1, keepdims=True)
|
|
18
|
+
X2 = (X2-X2.mean(axis=1, keepdims=True))/X2.std(axis=1, keepdims=True)
|
|
19
|
+
sccmat = np.empty([X1.shape[0], X2.shape[0]], float)
|
|
20
|
+
for i in range(X1.shape[0]):
|
|
21
|
+
for j in range(X2.shape[0]):
|
|
22
|
+
c = np.dot( X1[i,:], X2[j,:]) / float(X1.shape[1])
|
|
23
|
+
sccmat[i,j] = c
|
|
24
|
+
return sccmat
|
|
25
|
+
|
|
26
|
+
def infer_spatial_information(
|
|
27
|
+
adata_sc: anndata.AnnData,
|
|
28
|
+
adata_sp: anndata.AnnData,
|
|
29
|
+
cost_sc_sp: Optional[np.ndarray] = None,
|
|
30
|
+
cost_sc: Optional[np.ndarray] = None,
|
|
31
|
+
cost_sp: Optional[np.ndarray] = None,
|
|
32
|
+
ot_alpha: float = 0.2,
|
|
33
|
+
ot_rho: float = 0.05,
|
|
34
|
+
ot_epsilon: float = 0.01,
|
|
35
|
+
exp_pred_prone: float = 0.0,
|
|
36
|
+
loc_pred_k: int = 1,
|
|
37
|
+
return_gamma: bool = False
|
|
38
|
+
):
|
|
39
|
+
"""
|
|
40
|
+
Infer spatial information.
|
|
41
|
+
|
|
42
|
+
Given a pair of spatial data and scRNA-seq data, estimate spatial origin
|
|
43
|
+
of scRNA-seq data and impute gene expression for spatial data [Cang2020]_.
|
|
44
|
+
|
|
45
|
+
Parameters
|
|
46
|
+
----------
|
|
47
|
+
adata_sc
|
|
48
|
+
The data matrix for scRNA-seq data of shape ``n_obs(sc)`` × ``n_vars(sc)``.
|
|
49
|
+
Rows corresponds to cells and columns to genes.
|
|
50
|
+
adata_sp
|
|
51
|
+
The data matrix for spatial data of shape ``n_obs(sp)`` × ``n_vars(sp)``.
|
|
52
|
+
Rows corresponds to positions and columns to genes.
|
|
53
|
+
cost_sc_sp
|
|
54
|
+
The dissimilarity matrix between scRNA-seq data and spatial data of shape ``n_obs(sc)`` × ``n_obs(sp)``.
|
|
55
|
+
If not given, 1 - Spearman's r on common genes is used.
|
|
56
|
+
cost_sc
|
|
57
|
+
The dissimilarity matrix within scRNA-seq data of shape ``n_obs(sc)`` × ``n_obs(sc)``.
|
|
58
|
+
Only needed when structured optimal transport is used (ot_alpha > 0).
|
|
59
|
+
If not given, the Euclidean distance in PCA space is used.
|
|
60
|
+
cost_sp
|
|
61
|
+
The distance matrix within spatial data of shape ``n_obs(sp)`` × ``n_obs(sp)``.
|
|
62
|
+
Only needed when structured optimal transport is used (ot_alpha > 0).
|
|
63
|
+
If not given, the spatial distance among spatial locations is used.
|
|
64
|
+
ot_alpha
|
|
65
|
+
Weight for the structured component in optimal transport in [0,1].
|
|
66
|
+
ot_rho
|
|
67
|
+
Marginal relaxtion term (>0). Traditional OT when ot_rho=inf.
|
|
68
|
+
ot_epsilon
|
|
69
|
+
Entropy regularization term (>0). A higher value will generate a denser mapping matrix.
|
|
70
|
+
exp_pred_prone
|
|
71
|
+
The percentage of cells with low weights to ignore when predicing gene expression for each spatial data.
|
|
72
|
+
A higher percentage will increase the sparseness of the predicted spatial data due to the sparseness in the scRNA-seq data.
|
|
73
|
+
loc_pred_k
|
|
74
|
+
Number of top spatial matches for predicting spatial origin of cells.
|
|
75
|
+
return_gamma
|
|
76
|
+
Whether to return the optimal transport plan (gamma matrix)
|
|
77
|
+
|
|
78
|
+
Returns
|
|
79
|
+
-------
|
|
80
|
+
adata_sc_pred : anndata.AnnData
|
|
81
|
+
The scRNA-seq data with predicted spatial origins in ``.obsm['spatial']``.
|
|
82
|
+
adata_sp_pred : anndata.AnnData
|
|
83
|
+
The spatial data with imputed gene expression.
|
|
84
|
+
gamma : np.ndarray
|
|
85
|
+
The connectivity matrix between scRNA-seq data and spatial data which is used as weights to generate the predicted datasets adata_sc_pred and adata_sp_pred.
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
References
|
|
89
|
+
----------
|
|
90
|
+
|
|
91
|
+
.. [Cang2020] Cang, Z., & Nie, Q. (2020). Inferring spatial and signaling
|
|
92
|
+
relationships between cells from single cell transcriptomic data.
|
|
93
|
+
Nature communications, 11(1), 1-13.
|
|
94
|
+
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
# Cost matrices for optimal transport
|
|
98
|
+
if cost_sc_sp is None:
|
|
99
|
+
common_genes = list(set(adata_sc.var_names).intersection(set(adata_sp.var_names)))
|
|
100
|
+
adata_sc_common = adata_sc[:, common_genes]
|
|
101
|
+
adata_sp_common = adata_sp[:, common_genes]
|
|
102
|
+
cor_sc_sp = pairwise_scc(np.array(adata_sc_common.X.toarray()), np.array(adata_sp_common.X.toarray()))
|
|
103
|
+
cost_sc_sp = 0.5 * ( 1.0 - cor_sc_sp )
|
|
104
|
+
if cost_sc is None and ot_alpha != 0.0:
|
|
105
|
+
adata_sc_processed = adata_sc.copy()
|
|
106
|
+
sc.pp.highly_variable_genes(adata_sc_processed, n_top_genes=1000)
|
|
107
|
+
adata_sc_processed = adata_sc_processed[:, adata_sc_processed.var.highly_variable]
|
|
108
|
+
sc.pp.scale(adata_sc_processed, max_value=10)
|
|
109
|
+
sc.tl.pca(adata_sc_processed, svd_solver='arpack', n_comps=20)
|
|
110
|
+
x_pca = adata_sc_processed.obsm["X_pca"]
|
|
111
|
+
cost_sc = distance_matrix(x_pca, x_pca)
|
|
112
|
+
if cost_sp is None and ot_alpha != 0.0:
|
|
113
|
+
cost_sp = distance_matrix(adata_sp.obsm["spatial"], adata_sp.obsm["spatial"])
|
|
114
|
+
|
|
115
|
+
if ot_alpha != 0:
|
|
116
|
+
cost_sp = cost_sp / np.max(cost_sp)
|
|
117
|
+
cost_sc = cost_sc / np.max(cost_sc)
|
|
118
|
+
cost_sc_sp = cost_sc_sp / np.max(cost_sc_sp)
|
|
119
|
+
|
|
120
|
+
# Optimal transport mapping for the two datasets
|
|
121
|
+
w_mat = np.exp(-cost_sc_sp)
|
|
122
|
+
w_sc = np.sum(w_mat, axis=1); w_sp = np.sum(w_mat, axis=0)
|
|
123
|
+
w_sc = w_sc / np.sum(w_sc); w_sp = w_sp / np.sum(w_sp)
|
|
124
|
+
|
|
125
|
+
if ot_alpha == 0.0 and np.isinf(ot_rho):
|
|
126
|
+
gamma = ot.sinkhorn(w_sc, w_sp, cost_sc_sp, ot_epsilon)
|
|
127
|
+
elif ot_alpha == 0.0 and not np.isinf(ot_rho):
|
|
128
|
+
gamma = uot(w_sc, w_sp, cost_sc_sp, ot_epsilon, rho = ot_rho)
|
|
129
|
+
else:
|
|
130
|
+
gamma = usot(w_sc, w_sp, cost_sc_sp, cost_sc, cost_sp, ot_alpha,
|
|
131
|
+
epsilon = ot_epsilon, rho = ot_rho)
|
|
132
|
+
|
|
133
|
+
# Spatial data with predicted gene expression
|
|
134
|
+
gamma_sp = gamma.copy()
|
|
135
|
+
if exp_pred_prone > 0.0:
|
|
136
|
+
tmp_quantile = np.quantile(gamma_sp, exp_pred_prone, axis=0)
|
|
137
|
+
tmp_gamma_sp = gamma_sp - tmp_quantile
|
|
138
|
+
gamma_sp[np.where(tmp_gamma_sp < 0)] = 0
|
|
139
|
+
gamma_sp = gamma_sp / gamma_sp.sum(axis=0)
|
|
140
|
+
if isinstance(adata_sc.X, np.ndarray):
|
|
141
|
+
X_sp_pred = np.matmul(gamma_sp.T, np.array(adata_sc.X))
|
|
142
|
+
elif isinstance(adata_sc.X, sparse.csr_matrix):
|
|
143
|
+
X_sp_pred = sparse.csr_matrix( gamma_sp.T * adata_sc.X )
|
|
144
|
+
adata_sp_pred = anndata.AnnData(X=X_sp_pred, var=pd.DataFrame(index=adata_sc.var_names))
|
|
145
|
+
adata_sp_pred.obsm["spatial"] = adata_sp.obsm["spatial"]
|
|
146
|
+
|
|
147
|
+
# Single-cell data with predicted spatial location
|
|
148
|
+
gamma_sc = gamma.copy()
|
|
149
|
+
gamma_sc_sorted = -np.sort(-gamma_sc, axis=1)
|
|
150
|
+
k = loc_pred_k
|
|
151
|
+
for i in range(gamma_sc.shape[0]):
|
|
152
|
+
gamma_sc[i,np.where(gamma_sc[i,:] < gamma_sc_sorted[i,k])[0]] = 0
|
|
153
|
+
gamma_sc[i,:] = gamma_sc[i,:] / np.sum(gamma_sc[i,:])
|
|
154
|
+
pos_pred = np.matmul(gamma_sc, adata_sp.obsm["spatial"])
|
|
155
|
+
adata_sc_pred = adata_sc.copy()
|
|
156
|
+
adata_sc_pred.obsm["spatial"] = pos_pred
|
|
157
|
+
|
|
158
|
+
if return_gamma:
|
|
159
|
+
return adata_sc_pred, adata_sp_pred, gamma
|
|
160
|
+
else:
|
|
161
|
+
return adata_sc_pred, adata_sp_pred
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import scanpy as sc
|
|
3
|
+
import pandas as pd
|
|
4
|
+
import pkgutil
|
|
5
|
+
import io
|
|
6
|
+
import anndata
|
|
7
|
+
|
|
8
|
+
def ligand_receptor_database(
|
|
9
|
+
database = "CellChat",
|
|
10
|
+
species = "mouse",
|
|
11
|
+
heteromeric_delimiter = "_",
|
|
12
|
+
signaling_type = "Secreted Signaling" # or "Cell-Cell contact" or "ECM-Receptor" or None
|
|
13
|
+
):
|
|
14
|
+
"""
|
|
15
|
+
Extract ligand-receptor pairs from LR database.
|
|
16
|
+
|
|
17
|
+
Parameters
|
|
18
|
+
----------
|
|
19
|
+
database
|
|
20
|
+
The name of the ligand-receptor database. Use 'CellChat' for CellChatDB [Jin2021]_ of 'CellPhoneDB_v4.0' for CellPhoneDB_v4.0 [Efremova2020]_.
|
|
21
|
+
species
|
|
22
|
+
The species of the ligand-receptor pairs. Choose between 'mouse' and 'human'.
|
|
23
|
+
heteromeric_delimiter
|
|
24
|
+
The character to separate the heteromeric units of heteromeric ligands and receptors.
|
|
25
|
+
For example, if the heteromeric receptor (TGFbR1, TGFbR2) will be represented as 'TGFbR1_TGFbR2' if this parameter is set to '_'.
|
|
26
|
+
signaling_type
|
|
27
|
+
The type of signaling. Choose from 'Secreted Signaling', 'Cell-Cell Contact', and 'ECM-Receptor' for CellChatDB or 'Secreted Signaling' and 'Cell-Cell Contact' for CellPhoneDB_v4.0.
|
|
28
|
+
If None, all pairs in the database are returned.
|
|
29
|
+
|
|
30
|
+
Returns
|
|
31
|
+
-------
|
|
32
|
+
df_ligrec : pandas.DataFrame
|
|
33
|
+
A pandas DataFrame of the LR pairs with the three columns representing the ligand, receptor, and the signaling pathway name, respectively.
|
|
34
|
+
|
|
35
|
+
References
|
|
36
|
+
----------
|
|
37
|
+
|
|
38
|
+
.. [Jin2021] Jin, S., Guerrero-Juarez, C. F., Zhang, L., Chang, I., Ramos, R., Kuan, C. H., ... & Nie, Q. (2021).
|
|
39
|
+
Inference and analysis of cell-cell communication using CellChat. Nature communications, 12(1), 1-20.
|
|
40
|
+
.. [Efremova2020] Efremova, M., Vento-Tormo, M., Teichmann, S. A., & Vento-Tormo, R. (2020).
|
|
41
|
+
CellPhoneDB: inferring cell–cell communication from combined expression of multi-subunit ligand–receptor complexes. Nature protocols, 15(4), 1484-1506.
|
|
42
|
+
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
if database == "CellChat":
|
|
46
|
+
data = pkgutil.get_data(__name__, "_data/LRdatabase/CellChat/CellChatDB.ligrec."+species+".csv")
|
|
47
|
+
df_ligrec = pd.read_csv(io.BytesIO(data), index_col=0)
|
|
48
|
+
if not signaling_type is None:
|
|
49
|
+
df_ligrec = df_ligrec[df_ligrec.iloc[:,3] == signaling_type]
|
|
50
|
+
elif database == 'CellPhoneDB_v4.0':
|
|
51
|
+
data = pkgutil.get_data(__name__, "_data/LRdatabase/CellPhoneDB_v4.0/CellPhoneDBv4.0."+species+".csv")
|
|
52
|
+
df_ligrec = pd.read_csv(io.BytesIO(data), index_col=0)
|
|
53
|
+
if not signaling_type is None:
|
|
54
|
+
df_ligrec = df_ligrec[df_ligrec.iloc[:,3] == signaling_type]
|
|
55
|
+
|
|
56
|
+
return df_ligrec
|
|
57
|
+
|
|
58
|
+
def filter_lr_database(
|
|
59
|
+
df_ligrec: pd.DataFrame,
|
|
60
|
+
adata: anndata.AnnData,
|
|
61
|
+
heteromeric: bool = True,
|
|
62
|
+
heteromeric_delimiter: str = "_",
|
|
63
|
+
heteromeric_rule: str = "min",
|
|
64
|
+
filter_criteria: str = "min_cell_pct",
|
|
65
|
+
min_cell: int = 100,
|
|
66
|
+
min_cell_pct: float = 0.05
|
|
67
|
+
):
|
|
68
|
+
"""
|
|
69
|
+
Filter ligand-receptor pairs.
|
|
70
|
+
|
|
71
|
+
Parameters
|
|
72
|
+
----------
|
|
73
|
+
df_ligrec
|
|
74
|
+
The pandas dataframe of ligand-receptor database with three columns being ligand, receptor, and pathway name respectively.
|
|
75
|
+
adata
|
|
76
|
+
The AnnData object of gene expression. Unscaled data (minimum being zero) is expected.
|
|
77
|
+
heteromeric
|
|
78
|
+
Whether the ligands and receptors are described as heteromeric.
|
|
79
|
+
heteromeric_delimiter
|
|
80
|
+
If heteromeric notations are used for ligands and receptors, the character separating the heteromeric units.
|
|
81
|
+
heteromeric_rule
|
|
82
|
+
When heteromeric is True, the rule to quantify the level of a heteromeric ligand or receptor. Choose from minimum ('min') and average ('ave').
|
|
83
|
+
filter_criteria
|
|
84
|
+
Use either cell percentage ('min_cell_pct') or cell numbers (min_cell) to filter genes.
|
|
85
|
+
min_cell
|
|
86
|
+
If filter_criteria is 'min_cell', the LR-pairs with both ligand and receptor detected in greater than or equal to min_cell cells are kept.
|
|
87
|
+
min_cell_pct
|
|
88
|
+
If filter_criteria is 'min_cell_pct', the LR-pairs with both ligand and receptor detected in greater than or equal to min_cell_pct percentage of cells are kepts.
|
|
89
|
+
|
|
90
|
+
Returns
|
|
91
|
+
-------
|
|
92
|
+
df_ligrec_filtered: pd.DataFrame
|
|
93
|
+
A pandas DataFrame of the filtered ligand-receptor pairs.
|
|
94
|
+
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
data_genes = set(adata.var_names)
|
|
98
|
+
ncell = adata.shape[0]
|
|
99
|
+
all_genes = list(adata.var_names)
|
|
100
|
+
gene_ncell = np.array( (adata.X > 0).sum(axis=0) ).reshape(-1)
|
|
101
|
+
gene_mean = np.array( adata.X.mean(axis=0) )
|
|
102
|
+
ligrec_list = []
|
|
103
|
+
genes_keep = []
|
|
104
|
+
if not heteromeric:
|
|
105
|
+
tmp_genes = set(df_ligrec.iloc[:,0]).union(set(df_ligrec.iloc[:,1]))
|
|
106
|
+
tmp_genes = list(tmp_genes.intersection(data_genes))
|
|
107
|
+
for gene in tmp_genes:
|
|
108
|
+
if not gene in all_genes: continue
|
|
109
|
+
if filter_criteria == 'min_cell_prc':
|
|
110
|
+
if gene_ncell[all_genes.index(gene)] / ncell >= min_cell_pct:
|
|
111
|
+
genes_keep.append(gene)
|
|
112
|
+
elif filter_criteria == 'min_cell':
|
|
113
|
+
if gene_ncell[all_genes.index(gene)] >= min_cell:
|
|
114
|
+
genes_keep.append(gene)
|
|
115
|
+
elif heteromeric:
|
|
116
|
+
tmp_genes = list(set(df_ligrec.iloc[:,0]).union(set(df_ligrec.iloc[:,1])))
|
|
117
|
+
for het_gene in tmp_genes:
|
|
118
|
+
genes = het_gene.split(heteromeric_delimiter)
|
|
119
|
+
gene_found = True
|
|
120
|
+
for gene in genes:
|
|
121
|
+
if not gene in all_genes:
|
|
122
|
+
gene_found = False
|
|
123
|
+
if not gene_found: continue
|
|
124
|
+
keep = True
|
|
125
|
+
if filter_criteria == 'min_cell_pct' and heteromeric_rule == 'min':
|
|
126
|
+
for gene in genes:
|
|
127
|
+
if gene_ncell[all_genes.index(gene)] / ncell < min_cell_pct:
|
|
128
|
+
keep = False
|
|
129
|
+
elif filter_criteria == 'min_cell' and heteromeric_rule == 'min':
|
|
130
|
+
for gene in genes:
|
|
131
|
+
if gene_ncell[all_genes.index(gene)] < min_cell:
|
|
132
|
+
keep = False
|
|
133
|
+
elif heteromeric_rule == 'ave':
|
|
134
|
+
ave_ncell = []
|
|
135
|
+
for gene in genes:
|
|
136
|
+
ave_ncell.append( gene_ncell[all_genes.index(gene)] )
|
|
137
|
+
if filter_criteria == 'min_cell_pct':
|
|
138
|
+
if np.mean(ave_ncell) / ncell < min_cell_pct:
|
|
139
|
+
keep = False
|
|
140
|
+
elif filter_criteria == 'min_cell':
|
|
141
|
+
if np.mean(ave_ncell) < min_cell:
|
|
142
|
+
keep = False
|
|
143
|
+
if keep:
|
|
144
|
+
genes_keep.append(het_gene)
|
|
145
|
+
for i in range(df_ligrec.shape[0]):
|
|
146
|
+
if df_ligrec.iloc[i,0] in genes_keep and df_ligrec.iloc[i,1] in genes_keep:
|
|
147
|
+
ligrec_list.append(list(df_ligrec.iloc[i,:]))
|
|
148
|
+
|
|
149
|
+
return pd.DataFrame(data=ligrec_list)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from ._spatial_communication import spatial_communication
|
|
2
|
+
from ._spatial_communication import communication_direction
|
|
3
|
+
from ._spatial_communication import cluster_communication
|
|
4
|
+
from ._spatial_communication import cluster_communication_spatial_permutation
|
|
5
|
+
from ._spatial_communication import cluster_position
|
|
6
|
+
from ._downstream_analysis import communication_deg_detection
|
|
7
|
+
from ._downstream_analysis import communication_deg_clustering
|
|
8
|
+
from ._downstream_analysis import communication_impact
|
|
9
|
+
from ._downstream_analysis import group_cluster_communication
|
|
10
|
+
from ._downstream_analysis import group_cell_communication
|
|
11
|
+
from ._downstream_analysis import group_communication_direction
|
|
12
|
+
from ._downstream_analysis import communication_spatial_autocorrelation
|