DOTools-py 0.0.2__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.
- dotools_py/__init__.py +33 -0
- dotools_py/_experimental/__init__.py +0 -0
- dotools_py/_experimental/_deprecated/__init__.py +0 -0
- dotools_py/_experimental/_deprecated/_expression.py +761 -0
- dotools_py/_experimental/_deprecated/_language.py +398 -0
- dotools_py/_experimental/_deprecated/_statistics.py +403 -0
- dotools_py/_experimental/gr/__init__.py +0 -0
- dotools_py/_experimental/gr/_generic.py +382 -0
- dotools_py/dt/__init__.py +2 -0
- dotools_py/dt/_datasets.py +112 -0
- dotools_py/dt/_markers.py +150 -0
- dotools_py/dt/example_reduced.h5ad +0 -0
- dotools_py/get/__init__.py +7 -0
- dotools_py/get/_generic.py +626 -0
- dotools_py/logger.py +87 -0
- dotools_py/pl/_Classes.py +358 -0
- dotools_py/pl/_Plotter.py +567 -0
- dotools_py/pl/_StatsPlotter.py +716 -0
- dotools_py/pl/__init__.py +8 -0
- dotools_py/pl/_dotplot.py +2062 -0
- dotools_py/pl/_downstream.py +868 -0
- dotools_py/pl/_embeddings.py +481 -0
- dotools_py/pl/_experimental.py +205 -0
- dotools_py/pl/_expression.py +581 -0
- dotools_py/pl/_heatmap.py +475 -0
- dotools_py/pl/_plot_utils.py +103 -0
- dotools_py/pl/_visium.py +194 -0
- dotools_py/pp/__init__.py +2 -0
- dotools_py/pp/_cellbender.py +179 -0
- dotools_py/pp/_importer.py +583 -0
- dotools_py/settings/__init__.py +1 -0
- dotools_py/settings/_configure.py +185 -0
- dotools_py/settings/_global_parameters.py +16 -0
- dotools_py/tl/_Statistical.py +812 -0
- dotools_py/tl/__init__.py +10 -0
- dotools_py/tl/_analysis.py +772 -0
- dotools_py/tl/_get_stats.py +776 -0
- dotools_py/tl/_rankGenes.py +1112 -0
- dotools_py/util_scripts/_ReadWrite_RDS.R +285 -0
- dotools_py/util_scripts/_run_CCA.R +91 -0
- dotools_py/util_scripts/_run_CellBender.sh +186 -0
- dotools_py/util_scripts/_run_MAST.R +118 -0
- dotools_py/util_scripts/_run_SCTransform.R +60 -0
- dotools_py/util_scripts/_run_edgeR.R +104 -0
- dotools_py/util_scripts/_run_scDblFinder.R +63 -0
- dotools_py/utility/HomoSapiens_GeneMetadata.pickle.gz +0 -0
- dotools_py/utility/MusMusculus_GeneMetadata.pickle.gz +0 -0
- dotools_py/utility/__init__.py +4 -0
- dotools_py/utility/_convertion.py +262 -0
- dotools_py/utility/_general.py +136 -0
- dotools_py/utility/_plotting.py +101 -0
- dotools_py/utility/_spatial.py +64 -0
- dotools_py/utils.py +404 -0
- dotools_py-0.0.2.dist-info/METADATA +225 -0
- dotools_py-0.0.2.dist-info/RECORD +57 -0
- dotools_py-0.0.2.dist-info/WHEEL +4 -0
- dotools_py-0.0.2.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,776 @@
|
|
|
1
|
+
import itertools
|
|
2
|
+
import os
|
|
3
|
+
import shutil
|
|
4
|
+
import subprocess
|
|
5
|
+
import uuid
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Literal
|
|
8
|
+
|
|
9
|
+
import anndata as ad
|
|
10
|
+
import numpy as np
|
|
11
|
+
import pandas as pd
|
|
12
|
+
|
|
13
|
+
from dotools_py import logger
|
|
14
|
+
from dotools_py.tl._rankGenes import rank_genes_groups
|
|
15
|
+
from dotools_py.utils import convert_path, get_paths_utils, sanitize_anndata, iterase_input
|
|
16
|
+
from dotools_py.get import mean_expr, dge_results
|
|
17
|
+
from dotools_py.get import log2fc as get_log2fc
|
|
18
|
+
from dotools_py.get import pcts_cells as get_pct_cells
|
|
19
|
+
from dotools_py.get import pseudobulk as pseudobulking
|
|
20
|
+
|
|
21
|
+
# DGE Analysis
|
|
22
|
+
def run_mast(
|
|
23
|
+
adata: ad.AnnData,
|
|
24
|
+
cond_key: str,
|
|
25
|
+
reference: str,
|
|
26
|
+
disease: str | list,
|
|
27
|
+
covariates: str | list | None = None
|
|
28
|
+
) -> pd.DataFrame:
|
|
29
|
+
"""Run MAST Test for sc/snRNAseq.
|
|
30
|
+
|
|
31
|
+
:param adata: Annotated Data matrix.
|
|
32
|
+
:param cond_key: Metadata column in `obs` with condition groups.
|
|
33
|
+
:param reference: Reference condition.
|
|
34
|
+
:param disease: Disease conditions.
|
|
35
|
+
:param covariates: Extra covariates to account for.
|
|
36
|
+
:return: Returns a `DataFrame`. The following fields are included:
|
|
37
|
+
|
|
38
|
+
`GeneName`
|
|
39
|
+
Name of the genes
|
|
40
|
+
`pvals` and `padj`
|
|
41
|
+
The adjusted p-value uses Benjamini-Hochberg correction method.
|
|
42
|
+
`log2fc`
|
|
43
|
+
Log2FoldChamge
|
|
44
|
+
`pts_ref` and `pts_group`
|
|
45
|
+
Percentage of cells in the reference in the disease group expressing the gene
|
|
46
|
+
`groups`
|
|
47
|
+
Column containing the group tested
|
|
48
|
+
|
|
49
|
+
See Also
|
|
50
|
+
--------
|
|
51
|
+
:func:`dotools_py.tl.rank_genes_groups`: run DEA at single-cell level
|
|
52
|
+
:func:`dotools_py.tl.grouped_ttest`: run DEA at pseudobulk level
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
Example
|
|
56
|
+
-------
|
|
57
|
+
>>> import dotools_py as do
|
|
58
|
+
>>> adata = do.dt.example_10x_processed()
|
|
59
|
+
>>> df = do.tl.run_mast(adata, "condition", "healthy", "disease")
|
|
60
|
+
>>> df.head(5)
|
|
61
|
+
GeneName pvals log2fc padj pts_ref pts_group groups
|
|
62
|
+
0 A4GALT 0.001722 -1.018231 0.015546 0.003846 0.000000 disease
|
|
63
|
+
1 AAK1 0.019197 0.517996 0.105754 0.457692 0.516667 disease
|
|
64
|
+
2 ABAT 0.551787 1.530515 0.842536 0.000000 0.000000 disease
|
|
65
|
+
3 ABCB4 0.581264 -1.968762 0.842536 0.176923 0.050000 disease
|
|
66
|
+
4 ABCB9 0.458918 -1.468043 0.808238 0.121154 0.044444 disease
|
|
67
|
+
|
|
68
|
+
"""
|
|
69
|
+
rscript = get_paths_utils("_Run_MAST.R")
|
|
70
|
+
|
|
71
|
+
tmpdir_path = Path("/tmp") / f"MAST_Test_{uuid.uuid4().hex}"
|
|
72
|
+
tmpdir_path.mkdir(parents=True, exist_ok=False)
|
|
73
|
+
|
|
74
|
+
if "logcounts" not in adata.layers.keys():
|
|
75
|
+
logger.warn("Layer 'logcounts' not available setting X to logcounts")
|
|
76
|
+
adata.layers["logcounts"] = adata.X.copy()
|
|
77
|
+
|
|
78
|
+
del adata.uns, adata.raw
|
|
79
|
+
adata.write(tmpdir_path / "adata.h5ad")
|
|
80
|
+
|
|
81
|
+
in_path = os.path.join(tmpdir_path, "adata.h5ad")
|
|
82
|
+
|
|
83
|
+
disease = [disease] if isinstance(disease, str) else disease
|
|
84
|
+
|
|
85
|
+
dge_main = pd.DataFrame()
|
|
86
|
+
for alternative in disease:
|
|
87
|
+
logger.info(f"Running test for {alternative}")
|
|
88
|
+
|
|
89
|
+
cmd = [
|
|
90
|
+
"Rscript",
|
|
91
|
+
rscript,
|
|
92
|
+
"--input=" + in_path,
|
|
93
|
+
"--out=" + str(tmpdir_path) + "/dge_mast.csv",
|
|
94
|
+
"--key=" + cond_key,
|
|
95
|
+
"--ref=" + reference,
|
|
96
|
+
"--disease=" + alternative,
|
|
97
|
+
]
|
|
98
|
+
cmd += ["--covariates=" + covariates] if covariates is not None else []
|
|
99
|
+
subprocess.call(cmd)
|
|
100
|
+
dge = pd.read_csv(os.path.join(tmpdir_path, "dge_mast.csv"))
|
|
101
|
+
|
|
102
|
+
# Pcts
|
|
103
|
+
pct = get_pct_cells(adata, group_by=cond_key, features=dge["primerid"])
|
|
104
|
+
pct.columns = ["pts_" + col if col != "genes" else "GeneName" for col in pct.columns]
|
|
105
|
+
lfcs = get_log2fc(adata, group_by=cond_key, reference=reference, groups=alternative)
|
|
106
|
+
lfcs.rename(columns={"genes": "GeneName"}, inplace=True)
|
|
107
|
+
|
|
108
|
+
dge["groups"] = alternative
|
|
109
|
+
|
|
110
|
+
if "Unnamed: 0" in dge.columns:
|
|
111
|
+
del dge["Unnamed: 0"]
|
|
112
|
+
|
|
113
|
+
dge.rename(columns={"primerid":"GeneName"}, inplace=True)
|
|
114
|
+
dge = pd.merge(dge, lfcs, on="GeneName")
|
|
115
|
+
dge = pd.merge(dge, pct, on="GeneName")
|
|
116
|
+
|
|
117
|
+
dge.rename(
|
|
118
|
+
columns={
|
|
119
|
+
"pts_" + reference: "pts_ref",
|
|
120
|
+
"pts_" + alternative: "pts_group",
|
|
121
|
+
"log2fc_" + alternative: "log2fc"
|
|
122
|
+
|
|
123
|
+
},
|
|
124
|
+
inplace=True
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
dge_main = pd.concat([dge_main, dge])
|
|
128
|
+
|
|
129
|
+
shutil.rmtree(tmpdir_path)
|
|
130
|
+
|
|
131
|
+
return dge_main
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _run_test(
|
|
135
|
+
adata: ad.AnnData,
|
|
136
|
+
method: str,
|
|
137
|
+
groupby: str,
|
|
138
|
+
reference: str,
|
|
139
|
+
groups: list,
|
|
140
|
+
covariates: list = None,
|
|
141
|
+
) -> pd.DataFrame:
|
|
142
|
+
"""Run DGE test.
|
|
143
|
+
|
|
144
|
+
:param adata: Annotated data matrix.
|
|
145
|
+
:param method: Test to use.
|
|
146
|
+
:param groupby: Column in `obs` to group by.
|
|
147
|
+
:param reference: Reference condition.
|
|
148
|
+
:param groups: Alternative conditions.
|
|
149
|
+
:param covariates: Covariates to correct for in MAST test.
|
|
150
|
+
:return: dataframe with DGE results.
|
|
151
|
+
"""
|
|
152
|
+
groups = iterase_input(groups)
|
|
153
|
+
|
|
154
|
+
if method.lower() == "mast":
|
|
155
|
+
logger.info("Running MAST test")
|
|
156
|
+
assert reference != "rest", "Specify a reference when using MAST test"
|
|
157
|
+
dge = run_mast(adata, cond_key=groupby, reference=reference, disease=groups, covariates=covariates)
|
|
158
|
+
|
|
159
|
+
elif method in ["wilcoxon", "logreg", "t-test", "t-test_overestim_var"]:
|
|
160
|
+
logger.info(f"Running {method} test.")
|
|
161
|
+
try:
|
|
162
|
+
rank_genes_groups(
|
|
163
|
+
adata, groupby=groupby, method=method, tie_correct=True, pts=True, reference=reference, groups=groups
|
|
164
|
+
)
|
|
165
|
+
dge = dge_results(adata)
|
|
166
|
+
if "group" not in dge.columns:
|
|
167
|
+
dge["group"] = groups[0]
|
|
168
|
+
except ValueError as e:
|
|
169
|
+
logger.warn(f"Error running test:\n{e}")
|
|
170
|
+
dge = None
|
|
171
|
+
else:
|
|
172
|
+
raise NameError(f"{method} not implemented. Use: mast, wilcoxon, logreg, t-test, t-test_overestim_var")
|
|
173
|
+
return dge
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def rank_genes_condition(
|
|
177
|
+
adata: ad.AnnData,
|
|
178
|
+
groupby: str,
|
|
179
|
+
subset_by: str = None,
|
|
180
|
+
reference: str = "rest",
|
|
181
|
+
groups: list | str = None,
|
|
182
|
+
method: Literal["wilcoxon", "mast", "t-test", "logreg", "t-test_overestim_var"] = "wilcoxon",
|
|
183
|
+
pval_cutoff: float = 0.05,
|
|
184
|
+
log2fc_cutoff: float = 0.25,
|
|
185
|
+
path: str = None,
|
|
186
|
+
filename: str = "DGE.xlsx",
|
|
187
|
+
layer: str = None,
|
|
188
|
+
covariates: list = None,
|
|
189
|
+
get_results: bool = True,
|
|
190
|
+
key_added: str = "rank_genes_condition",
|
|
191
|
+
) -> None | pd.DataFrame:
|
|
192
|
+
"""Run DGE Analysis.
|
|
193
|
+
|
|
194
|
+
Run differential expression analysis. Besides the methods implemented in scanpy (wilcoxon, t-test, logreg and
|
|
195
|
+
t-test_overestim_var), the `MAST <https://genomebiology.biomedcentral.com/articles/10.1186/s13059-015-0844-5>`_
|
|
196
|
+
test can be used. If subset_by is provided the DGE analysis will be run over each group.
|
|
197
|
+
Benjamini-Hochberg correction method is used for multiple testing.
|
|
198
|
+
|
|
199
|
+
After running DGE analysis and if path is provided an ExcelSheet will be generated with 3 sheets: 1) AllGenes
|
|
200
|
+
containing all the genes, 2) UpregGenes containing upregulated genes and 3) DownregGenes containing downregulated
|
|
201
|
+
genes. The up- and down-regulated genes are filtered depending on the pval_cutoff and log2fc_cutoff. The results will
|
|
202
|
+
be saved in the uns attribute under `rank_genes_condition`.
|
|
203
|
+
|
|
204
|
+
:param adata: Annotated data matrix.
|
|
205
|
+
:param groupby: Column in `obs` with conditions to test.
|
|
206
|
+
:param subset_by: Column in `obs` to subset by. (e.g., column with cell-type annotation)
|
|
207
|
+
:param reference: Reference condition.
|
|
208
|
+
:param groups: Alternative conditions.
|
|
209
|
+
:param method: Method to test.
|
|
210
|
+
:param pval_cutoff: P-value cutoff to filter when generating the ExcelSheet.
|
|
211
|
+
:param log2fc_cutoff: log2 foldchange cutoff to filter when generating the ExcelSheet.
|
|
212
|
+
:param path: Path to save ExcelSheet.
|
|
213
|
+
:param filename: Name of the ExcelSheet.
|
|
214
|
+
:param layer: Layer of the AnnData to use.
|
|
215
|
+
:param covariates: list with extra covariates to correct for in the MAST test.
|
|
216
|
+
:param get_results: Return a dataframe with results.
|
|
217
|
+
:param key_added: Key to use in uns.
|
|
218
|
+
:return: Returns a `DataFrame` if `get_results` is set to `True` with the results from the differential expression
|
|
219
|
+
analysis. If a path is provided, the DataFrame will be saved under the specified path.
|
|
220
|
+
The following fields are included:
|
|
221
|
+
|
|
222
|
+
`GeneName`
|
|
223
|
+
Name of the genes
|
|
224
|
+
`pvals` and `padj`
|
|
225
|
+
The adjusted p-value uses Benjamini-Hochberg correction method.
|
|
226
|
+
`log2fc`
|
|
227
|
+
Log2FoldChange
|
|
228
|
+
`pts_ref` and `pts_group`
|
|
229
|
+
Percentage of cells in the reference in the disease group expressing the gene
|
|
230
|
+
`groups`
|
|
231
|
+
Column containing the group tested
|
|
232
|
+
`groupby`
|
|
233
|
+
The column name is set to `groupby` and contains the cluster groups.
|
|
234
|
+
`adata.uns['rank_genes_condition' | key_added]`
|
|
235
|
+
Dataframe with results of the differential expression analysis.
|
|
236
|
+
|
|
237
|
+
See Also
|
|
238
|
+
--------
|
|
239
|
+
:func:`dotools_py.tl.rank_genes_pseudobulk`: run DEA at pseudobulk level between condition for all clusters
|
|
240
|
+
:func:`dotools_py.tl.rank_genes_consensus`: run DEA at pseudobulk and single-cell level between condition for all clusters
|
|
241
|
+
|
|
242
|
+
"""
|
|
243
|
+
sanitize_anndata(adata)
|
|
244
|
+
adata_copy = adata.copy()
|
|
245
|
+
if layer is not None:
|
|
246
|
+
adata_copy.X = adata_copy.layers[layer].copy()
|
|
247
|
+
|
|
248
|
+
groups = list(adata_copy.obs[groupby].unique()) if groups is None else iterase_input(groups)
|
|
249
|
+
if reference in groups:
|
|
250
|
+
groups.remove(reference)
|
|
251
|
+
|
|
252
|
+
if subset_by:
|
|
253
|
+
categories = list(adata_copy.obs[subset_by].cat.categories)
|
|
254
|
+
dge = pd.DataFrame([])
|
|
255
|
+
for catg in categories:
|
|
256
|
+
logger.info(f"Running DGEs for {catg}.")
|
|
257
|
+
sdata = adata_copy[adata_copy.obs[subset_by] == catg]
|
|
258
|
+
dge_s = _run_test(
|
|
259
|
+
sdata, method=method, groupby=groupby, reference=reference, groups=groups, covariates=covariates,
|
|
260
|
+
)
|
|
261
|
+
if dge_s is None:
|
|
262
|
+
continue
|
|
263
|
+
dge_s[subset_by] = catg
|
|
264
|
+
dge = pd.concat([dge, dge_s])
|
|
265
|
+
else:
|
|
266
|
+
logger.info("Running DGEs.")
|
|
267
|
+
dge = _run_test(
|
|
268
|
+
adata_copy, method=method, groupby=groupby, reference=reference, groups=groups, covariates=covariates,
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
adata.uns[key_added] = dge # Save inplace
|
|
272
|
+
if path is not None:
|
|
273
|
+
out_path = convert_path(path) / filename
|
|
274
|
+
logger.info(f"Saving DGE ExcelSheet in {str(out_path.name)}")
|
|
275
|
+
with pd.ExcelWriter(out_path) as writer:
|
|
276
|
+
dge.to_excel(writer, sheet_name="AllGenes", index=False)
|
|
277
|
+
for case in groups:
|
|
278
|
+
dge_up = dge[
|
|
279
|
+
(dge["padj"] < pval_cutoff) & (dge["log2fc"] > log2fc_cutoff) & (dge[dge["group"] == case])
|
|
280
|
+
]
|
|
281
|
+
dge_down = dge[
|
|
282
|
+
(dge["padj"] < pval_cutoff) & (dge["log2fc"] < -log2fc_cutoff) & (dge[dge["group"] == case])
|
|
283
|
+
]
|
|
284
|
+
|
|
285
|
+
dge_up.to_excel(writer, sheet_name=f"UpregGenes_{case}", index=False)
|
|
286
|
+
dge_down.to_excel(writer, sheet_name=f"DownregGenes_{case}", index=False)
|
|
287
|
+
if get_results:
|
|
288
|
+
return dge
|
|
289
|
+
else:
|
|
290
|
+
return None
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def grouped_ttest(
|
|
294
|
+
adata: ad.AnnData,
|
|
295
|
+
annot_key: str = "annotation",
|
|
296
|
+
cond_key: str = "condition",
|
|
297
|
+
batch_key: str = "batch",
|
|
298
|
+
reference: str = "rest",
|
|
299
|
+
groups: str | list = None,
|
|
300
|
+
equal_var: bool = True,
|
|
301
|
+
key_added: str = "grouped_ttest",
|
|
302
|
+
layer: str = None,
|
|
303
|
+
get_results: bool = False,
|
|
304
|
+
) -> None | pd.DataFrame :
|
|
305
|
+
"""Calculate grouped t-test.
|
|
306
|
+
|
|
307
|
+
This function calculate a grouped t-test for all the genes in each group in annot_key. For each gene,
|
|
308
|
+
the average expression per sample is employed for the test. If more than two conditions are available,
|
|
309
|
+
the test will be applied to all possible combinations (for instance, for cond A, B and C; the grouped
|
|
310
|
+
t-test will be computed for A-Vs-B; A-Vs-C and B-Vs-C). Results are saved as a dataframe in the
|
|
311
|
+
uns attribute.
|
|
312
|
+
|
|
313
|
+
:param adata: Annotated data matrix.
|
|
314
|
+
:param annot_key: Column in `obs` with the cell type annotation.
|
|
315
|
+
:param cond_key: Column in `obs` with the conditions.
|
|
316
|
+
:param batch_key: Column in `obs` with the sample IDs.
|
|
317
|
+
:param reference: Reference condition.
|
|
318
|
+
:param groups: Alternative conditions.
|
|
319
|
+
:param equal_var: If set to `True`, assume equal variance for both populations tested.
|
|
320
|
+
:param key_added: Key to use in uns.
|
|
321
|
+
:param layer: Layer of the AnnData object to use.
|
|
322
|
+
:param get_results: Return a DataFrame with the results.
|
|
323
|
+
|
|
324
|
+
Returns
|
|
325
|
+
-------
|
|
326
|
+
Returns a `DataFrame` if `get_results` is set to `True` with the results from the differential expression
|
|
327
|
+
analysis. The `DataFrame` with the results are also saved in the AnnData in:
|
|
328
|
+
|
|
329
|
+
`adata.uns['grouped_ttest' | key_added]`.
|
|
330
|
+
|
|
331
|
+
See Also
|
|
332
|
+
--------
|
|
333
|
+
:func:`dotools_py.tl.rank_genes_groups`: run DEA at single-cell level between condition for all genes
|
|
334
|
+
|
|
335
|
+
"""
|
|
336
|
+
from scipy.stats import ttest_ind
|
|
337
|
+
|
|
338
|
+
if layer is not None:
|
|
339
|
+
adata.X = adata.layers[layer].copy() # Select the specified layer
|
|
340
|
+
groups = iterase_input(groups)
|
|
341
|
+
|
|
342
|
+
main_df = pd.DataFrame([])
|
|
343
|
+
for cell in adata.obs[annot_key].unique():
|
|
344
|
+
subset = adata[adata.obs[annot_key] == cell] # Select a cell type
|
|
345
|
+
df_expr = mean_expr(subset, [annot_key, cond_key, batch_key], layer=layer) # Mean vals in log space
|
|
346
|
+
|
|
347
|
+
if reference == "rest":
|
|
348
|
+
cond_comb = [
|
|
349
|
+
comb for comb in itertools.combinations(adata.obs[cond_key].unique(), 2)
|
|
350
|
+
] # Get all conditions combinations
|
|
351
|
+
else:
|
|
352
|
+
groups = groups if len(groups) != 0 else iterase_input(adata.obs[cond_key].unique())
|
|
353
|
+
if reference in groups:
|
|
354
|
+
groups.remove(reference)
|
|
355
|
+
cond_comb = [(reference, g) for g in groups]
|
|
356
|
+
|
|
357
|
+
# Compute t-test for all possible combinations
|
|
358
|
+
for comb in cond_comb:
|
|
359
|
+
df_a = df_expr[df_expr[cond_key] == comb[0]]
|
|
360
|
+
df_b = df_expr[df_expr[cond_key] == comb[1]]
|
|
361
|
+
|
|
362
|
+
df_a_wide = df_a.pivot(index="gene", values="expr", columns=batch_key)
|
|
363
|
+
df_b_wide = df_b.pivot(index="gene", values="expr", columns=batch_key)
|
|
364
|
+
|
|
365
|
+
p_values = pd.DataFrame(df_a_wide.index, columns=["gene"])
|
|
366
|
+
p_values["statistic"] = pd.DataFrame(ttest_ind(df_a_wide, df_b_wide, axis=1, equal_var=equal_var)[0]).fillna(0)
|
|
367
|
+
p_values["pval"] = pd.DataFrame(ttest_ind(df_a_wide, df_b_wide, axis=1, equal_var=equal_var)[1]).fillna(1)
|
|
368
|
+
p_values["condition"] = "-Vs-".join(comb)
|
|
369
|
+
p_values["annotation"] = cell
|
|
370
|
+
|
|
371
|
+
main_df = pd.concat([main_df, p_values], axis=0)
|
|
372
|
+
|
|
373
|
+
adata.uns[key_added] = main_df
|
|
374
|
+
if get_results:
|
|
375
|
+
return main_df
|
|
376
|
+
else:
|
|
377
|
+
return None
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def go_analysis(
|
|
381
|
+
df: pd.DataFrame,
|
|
382
|
+
gene_key: str,
|
|
383
|
+
pval_key: str,
|
|
384
|
+
log2fc_key: str,
|
|
385
|
+
pval_cutoff: float = 0.05,
|
|
386
|
+
log2fc_cutoff: float = 0.25,
|
|
387
|
+
path: str = None,
|
|
388
|
+
filename: str = "",
|
|
389
|
+
specie: Literal["Mouse", "Human"] = "Mouse",
|
|
390
|
+
go_catgs: str | list = ("GO_Molecular_Function_2023", "GO_Cellular_Component_2023", "GO_Biological_Process_2023"),
|
|
391
|
+
) -> None | pd.DataFrame:
|
|
392
|
+
"""Run Gene Ontology using EnrichR API.
|
|
393
|
+
|
|
394
|
+
Perform gene ontology analysis base on the `EnrichR <https://maayanlab.cloud/Enrichr/>`_ interface.
|
|
395
|
+
|
|
396
|
+
:param df: Dataframe with results of differential gene expression analysis.
|
|
397
|
+
:param gene_key: Column with genes.
|
|
398
|
+
:param pval_key: Column with pvals.
|
|
399
|
+
:param log2fc_key: Column with log2 foldchanges.
|
|
400
|
+
:param pval_cutoff: Cutoff for pvals.
|
|
401
|
+
:param log2fc_cutoff: Cutoff for log2 foldchanges.
|
|
402
|
+
:param path: Folder where output Excel files will be saved. A SubFolder called GSA_Tables will be created
|
|
403
|
+
:param filename: Suffix for the filename. Format GSA_CellType_Suffix.xlsx
|
|
404
|
+
:param specie: Available Human, Mouse, Yeast, Fly, Fish, Worm.
|
|
405
|
+
:param go_catgs: Gene Ontology Classes to use
|
|
406
|
+
:return: Return a `DataFrame` with Gene Ontology Analysis results. If a path is provided the results will be saved.
|
|
407
|
+
"""
|
|
408
|
+
import gseapy
|
|
409
|
+
|
|
410
|
+
go_catgs = iterase_input(go_catgs)
|
|
411
|
+
|
|
412
|
+
logger.info("Running GSA on Up- and Down-regulated genes")
|
|
413
|
+
df_up = df[(df[pval_key] < pval_cutoff) & (df[log2fc_key] > log2fc_cutoff)]
|
|
414
|
+
df_down = df[(df[pval_key] < pval_cutoff) & (df[log2fc_key] < -log2fc_cutoff)]
|
|
415
|
+
|
|
416
|
+
res_up = gseapy.enrichr(gene_list=list(df_up[gene_key]), organism=specie, gene_sets=go_catgs).results
|
|
417
|
+
res_up["state"] = "enriched"
|
|
418
|
+
res_down = gseapy.enrichr(gene_list=list(df_down[gene_key]), organism=specie, gene_sets=go_catgs).results
|
|
419
|
+
res_down["state"] = "depleted"
|
|
420
|
+
res = pd.concat([res_up, res_down])
|
|
421
|
+
|
|
422
|
+
if path is not None:
|
|
423
|
+
output_path = convert_path(path) / filename
|
|
424
|
+
res.to_excel(output_path, index=False)
|
|
425
|
+
return None
|
|
426
|
+
else:
|
|
427
|
+
return res
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def rank_genes_pseudobulk(
|
|
432
|
+
adata: ad.AnnData,
|
|
433
|
+
ctrl_cond: str,
|
|
434
|
+
disease_cond: str,
|
|
435
|
+
cluster_key: str,
|
|
436
|
+
method: Literal["deseq2", "edger"] = "deseq2",
|
|
437
|
+
batch_key: str = "batch",
|
|
438
|
+
condition_key: str = "condition",
|
|
439
|
+
design: str = "~condition",
|
|
440
|
+
layer: str = "counts",
|
|
441
|
+
min_cells: int = 50,
|
|
442
|
+
pseudobulk_approach: Literal["sum", "mean"] = "sum",
|
|
443
|
+
technical_replicates: int = 1,
|
|
444
|
+
min_counts: int = 10,
|
|
445
|
+
workers: int = 8,
|
|
446
|
+
path: str = None,
|
|
447
|
+
filename: str = "DEA_Pseudobulk.xlsx",
|
|
448
|
+
get_results: bool = True,
|
|
449
|
+
key_added: str = "rank_genes_pseudobulk",
|
|
450
|
+
) -> None | pd.DataFrame:
|
|
451
|
+
"""Running DEA using pseudobulk approach.
|
|
452
|
+
|
|
453
|
+
Perform differential expression analysis (DEA) using DESeq2 or EdgeR. This functions has a similar behavior as
|
|
454
|
+
:func:`dotools_py.tl.rank_genes_condition()`. For each cluster it will test for differential gene expression between two conditions.
|
|
455
|
+
The input is expected to be raw counts.
|
|
456
|
+
|
|
457
|
+
:param adata: Annotated data matrix.
|
|
458
|
+
:param ctrl_cond: Control condition.
|
|
459
|
+
:param disease_cond: Disease condition.
|
|
460
|
+
:param cluster_key: Metadata column in `obs` with cluster groups.
|
|
461
|
+
:param method: Differential expression method to use, DESeq2 or EdgeR.
|
|
462
|
+
:param batch_key: Metadata column in `obs` with batch groups
|
|
463
|
+
:param condition_key: Metadata column in `obs` with condition groups.
|
|
464
|
+
:param design: Design factors for DESeq2.
|
|
465
|
+
:param layer: Layer to use. Expected raw counts.
|
|
466
|
+
:param min_cells: Minimum number of cells per batch/sample required when generating the pseudo-bulk. If there are
|
|
467
|
+
fewer cells, DESeq2 / EdgeR will not be run on the cluster.
|
|
468
|
+
:param pseudobulk_approach: How to generate the pseudobulk counts.
|
|
469
|
+
:param technical_replicates: How many technical replicates should be generated per sample.
|
|
470
|
+
:param min_counts: Minimum number of total counts for a gene to be tested after pseudo-bulking.
|
|
471
|
+
:param workers: Number of CPUs to use for DESEq2.
|
|
472
|
+
:param path: Path to save the file.
|
|
473
|
+
:param filename: Name of the file.
|
|
474
|
+
:param get_results: Get dataframe with DEA results.
|
|
475
|
+
:param key_added: Name of the uns attribute with the results.
|
|
476
|
+
:return: Returns a `DataFrame` with DEA results if `get_results` is set to True. The following field will also be set:
|
|
477
|
+
|
|
478
|
+
`adata.uns['rank_genes_pseudobulk' | key_added]`
|
|
479
|
+
Dataframe with results of the differential expression analysis
|
|
480
|
+
|
|
481
|
+
See Also
|
|
482
|
+
--------
|
|
483
|
+
:func:`dotools_py.tl.rank_genes_condition`: run DEA at single-cell level between condition for all clusters
|
|
484
|
+
:func:`dotools_py.tl.rank_genes_consensus`: run DEA at pseudobulk and single-cell level between condition for all clusters
|
|
485
|
+
|
|
486
|
+
"""
|
|
487
|
+
|
|
488
|
+
from pydeseq2.dds import DeseqDataSet
|
|
489
|
+
from pydeseq2.default_inference import DefaultInference
|
|
490
|
+
from pydeseq2.ds import DeseqStats
|
|
491
|
+
|
|
492
|
+
# Step 1 - Generate Pseudo-bulk data
|
|
493
|
+
logger.info("Generating Pseudo-bulk data")
|
|
494
|
+
pdata_cts = pseudobulking(
|
|
495
|
+
adata,
|
|
496
|
+
batch_key=batch_key,
|
|
497
|
+
cluster_key=cluster_key,
|
|
498
|
+
min_cells=min_cells,
|
|
499
|
+
pseudobulk_approach=pseudobulk_approach,
|
|
500
|
+
technical_replicates=technical_replicates,
|
|
501
|
+
min_counts=min_counts,
|
|
502
|
+
layer=layer,
|
|
503
|
+
keep_metadata=[condition_key],
|
|
504
|
+
workers=workers
|
|
505
|
+
)
|
|
506
|
+
|
|
507
|
+
sanitize_anndata(pdata_cts)
|
|
508
|
+
|
|
509
|
+
# Step 2 - Run test
|
|
510
|
+
if method == "deseq2":
|
|
511
|
+
logger.info("Run DESeq2")
|
|
512
|
+
inference = DefaultInference(n_cpus=workers)
|
|
513
|
+
df_main = pd.DataFrame([])
|
|
514
|
+
for ct in pdata_cts.obs[cluster_key].unique():
|
|
515
|
+
try:
|
|
516
|
+
pdata = pdata_cts[pdata_cts.obs[cluster_key] == ct].copy()
|
|
517
|
+
pdata.X = pdata.X.toarray()
|
|
518
|
+
if pdata.n_obs == 0:
|
|
519
|
+
logger.warn(f"Could not test for {ct}")
|
|
520
|
+
continue
|
|
521
|
+
dds = DeseqDataSet(adata=pdata, design=design, refit_cooks=True, inference=inference)
|
|
522
|
+
dds.deseq2()
|
|
523
|
+
stat_res = DeseqStats(dds, contrast=[condition_key, disease_cond, ctrl_cond], inference=inference)
|
|
524
|
+
stat_res.summary()
|
|
525
|
+
results = stat_res.results_df.copy()
|
|
526
|
+
results.loc[results.padj.isna(), "padj"] = 1 # Replace NaN with 1
|
|
527
|
+
results["group"] = pdata.obs[cluster_key].unique()[0]
|
|
528
|
+
df_main = pd.concat([df_main, results])
|
|
529
|
+
except ValueError as e:
|
|
530
|
+
logger.info(f"Test could not be computed for {ct} due to {e}")
|
|
531
|
+
|
|
532
|
+
elif method == "edger":
|
|
533
|
+
logger.info("Run edgeR")
|
|
534
|
+
rscript = get_paths_utils("_run_edgeR.R")
|
|
535
|
+
tmpdir_path = Path("/tmp") / f"EdgeR_Test_{uuid.uuid4().hex}"
|
|
536
|
+
tmpdir_path.mkdir(parents=True, exist_ok=False)
|
|
537
|
+
|
|
538
|
+
df_main = pd.DataFrame()
|
|
539
|
+
for ct in pdata_cts.obs[cluster_key].unique():
|
|
540
|
+
try:
|
|
541
|
+
logger.info(f"Running DEA for {ct}")
|
|
542
|
+
pdata = pdata_cts[pdata_cts.obs[cluster_key] == ct].copy()
|
|
543
|
+
del pdata.uns, pdata.raw
|
|
544
|
+
pdata.write(tmpdir_path / f"adata_{ct}.h5ad")
|
|
545
|
+
in_path = os.path.join(tmpdir_path, f"adata_{ct}.h5ad")
|
|
546
|
+
cmd = [
|
|
547
|
+
"Rscript",
|
|
548
|
+
rscript,
|
|
549
|
+
"--input=" + in_path,
|
|
550
|
+
"--out=" + str(tmpdir_path) + f"/dge_{ct}_edgeR.csv",
|
|
551
|
+
"--batch=" + batch_key,
|
|
552
|
+
"--condition=" + condition_key,
|
|
553
|
+
"--ref=" + ctrl_cond,
|
|
554
|
+
"--disease=" + disease_cond,
|
|
555
|
+
]
|
|
556
|
+
subprocess.call(cmd)
|
|
557
|
+
dge = pd.read_csv(os.path.join(tmpdir_path, f"dge_{ct}_edgeR.csv"))
|
|
558
|
+
dge["group"] = pdata.obs[cluster_key].unique()[0]
|
|
559
|
+
df_main = pd.concat([df_main, dge])
|
|
560
|
+
except Exception as e:
|
|
561
|
+
logger.info(f"Test could not be computed for {ct} due to {e}")
|
|
562
|
+
|
|
563
|
+
else:
|
|
564
|
+
raise Exception(f'{method} not implemented, use "deseq2" or "edger"')
|
|
565
|
+
|
|
566
|
+
if path is not None:
|
|
567
|
+
df_main.to_excel(convert_path(path) / filename)
|
|
568
|
+
|
|
569
|
+
adata.uns[key_added] = df_main
|
|
570
|
+
if get_results:
|
|
571
|
+
return df_main
|
|
572
|
+
else:
|
|
573
|
+
return None
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def rank_genes_consensus(
|
|
577
|
+
adata: ad.AnnData,
|
|
578
|
+
ctrl_cond: str,
|
|
579
|
+
disease_cond: str,
|
|
580
|
+
cluster_key: str,
|
|
581
|
+
batch_key: str = "batch",
|
|
582
|
+
condition_key: str = "condition",
|
|
583
|
+
design: str = "~condition",
|
|
584
|
+
count_layer: str = "counts",
|
|
585
|
+
logcounts_layer: str = "logcounts",
|
|
586
|
+
min_cells: int = 50,
|
|
587
|
+
pseudobulk_approach: Literal["sum", "mean"] = "sum",
|
|
588
|
+
technical_replicates: int = 1,
|
|
589
|
+
min_counts: int = 10,
|
|
590
|
+
workers: int = 8,
|
|
591
|
+
path: str | Path = None,
|
|
592
|
+
filename: str = "DEA.xlsx",
|
|
593
|
+
test_pseudobulk: Literal["deseq2", "edger"] = "deseq2",
|
|
594
|
+
test: Literal["wilcoxon", "mast", "t-test", "logreg", "t-test_overestim_var"] = "wilcoxon",
|
|
595
|
+
mast_covariates: list = None,
|
|
596
|
+
pval_cutoff: float = 0.05,
|
|
597
|
+
get_results: bool = True,
|
|
598
|
+
key_added: str = "rank_genes_consensus",
|
|
599
|
+
) -> None | pd.DataFrame :
|
|
600
|
+
"""Run single-cell and pseudo-bulk differential expression analysis.
|
|
601
|
+
|
|
602
|
+
This function performs differential gene expression analysis between two conditions for
|
|
603
|
+
an all the clusters in the AnnData object using a single-cell level and pseudo-bulk level approach.
|
|
604
|
+
For the single-cell level, it will test for DEGs using wilcoxon, MAST, t-test, logistic regression or
|
|
605
|
+
t-test overestimate. For the pseudobulk level it will test for DEGs using DESeq2 or edgeR.
|
|
606
|
+
|
|
607
|
+
A dataframe will be produce with the results of both tests including the foldchanges, p-values, statistics,
|
|
608
|
+
percentage of cells in each group expressing the gene and the mean expression per sample in each cluster for each gene.
|
|
609
|
+
The dataframe will be saved in the `uns` attribute and can also be saved if a path a filename is provided.
|
|
610
|
+
|
|
611
|
+
:param adata: Annotated data matrix.
|
|
612
|
+
:param ctrl_cond: Control condition.
|
|
613
|
+
:param disease_cond: Disease or alternative condition to test.
|
|
614
|
+
:param cluster_key: Metadata column in obs with clustering groups.
|
|
615
|
+
:param batch_key: Metadata column in obs with batch groups.
|
|
616
|
+
:param condition_key: Metadata column in obs with condition groups.
|
|
617
|
+
:param design: Design for the differential expression analysis in DESeq2.
|
|
618
|
+
:param count_layer: Layer with counts. Required for DESeq2.
|
|
619
|
+
:param logcounts_layer: Layer with logcounts.
|
|
620
|
+
:param min_cells: Minimum number of cells per batch/sample required when generating the pseudo-bulk. If there are
|
|
621
|
+
fewer cells, DESeq2 / EdgeR will not be run on the cluster.
|
|
622
|
+
:param pseudobulk_approach: How to generate the pseudobulk counts.
|
|
623
|
+
:param technical_replicates: How many technical replicates should be generated per sample.
|
|
624
|
+
:param min_counts: Minimum number of total counts for a gene to be tested in DESeq2 after pseudobulking.
|
|
625
|
+
:param workers: Number of CPUs to use for DESEq2.
|
|
626
|
+
:param path: Path to save results.
|
|
627
|
+
:param filename: Name of the file.
|
|
628
|
+
:param test_pseudobulk: Test to use for doing differential expression analysis on pseudobulk level.
|
|
629
|
+
:param test: Test to use for doing differential expression analysis on single-cell level.
|
|
630
|
+
:param mast_covariates: Covariates for MAST test.
|
|
631
|
+
:param pval_cutoff: Cutoff for considering a gene significant.
|
|
632
|
+
:param get_results: Get a dataframe with the consensus results
|
|
633
|
+
:param key_added: Name of the uns attribute with the results
|
|
634
|
+
:return: Returns a `DataFrame` with DEA results if `get_results` is set to True. The following field will also be set:
|
|
635
|
+
|
|
636
|
+
`adata.uns['rank_genes_consensus' | key_added]`
|
|
637
|
+
Dataframe with results of the differential expression analysis
|
|
638
|
+
|
|
639
|
+
See Also
|
|
640
|
+
--------
|
|
641
|
+
:func:`dotools_py.tl.rank_genes_condition`: run DEA at single-cell level between condition for all clusters
|
|
642
|
+
:func:`dotools_py.tl.rank_genes_pseudobulk`: run DEA at pseudobulk level between condition for all clusters
|
|
643
|
+
|
|
644
|
+
"""
|
|
645
|
+
# Run single-cell dge
|
|
646
|
+
logger.info(f"Running {test}")
|
|
647
|
+
df_sc = rank_genes_condition(
|
|
648
|
+
adata,
|
|
649
|
+
groupby=condition_key,
|
|
650
|
+
subset_by=cluster_key,
|
|
651
|
+
reference=ctrl_cond,
|
|
652
|
+
groups=disease_cond,
|
|
653
|
+
method=test,
|
|
654
|
+
layer=logcounts_layer,
|
|
655
|
+
covariates=mast_covariates,
|
|
656
|
+
get_results=True,
|
|
657
|
+
)
|
|
658
|
+
|
|
659
|
+
# Run pseudobulk
|
|
660
|
+
logger.info(f"Running {test_pseudobulk}")
|
|
661
|
+
df_pseudobulk = rank_genes_pseudobulk(
|
|
662
|
+
adata,
|
|
663
|
+
method=test_pseudobulk,
|
|
664
|
+
ctrl_cond=ctrl_cond,
|
|
665
|
+
disease_cond=disease_cond,
|
|
666
|
+
cluster_key=cluster_key,
|
|
667
|
+
batch_key=batch_key,
|
|
668
|
+
condition_key=condition_key,
|
|
669
|
+
design=design,
|
|
670
|
+
layer=count_layer,
|
|
671
|
+
min_cells=min_cells,
|
|
672
|
+
min_counts=min_counts,
|
|
673
|
+
pseudobulk_approach=pseudobulk_approach,
|
|
674
|
+
technical_replicates=technical_replicates,
|
|
675
|
+
workers=workers,
|
|
676
|
+
)
|
|
677
|
+
logger.info("Generating consensus DataFrame")
|
|
678
|
+
|
|
679
|
+
if test_pseudobulk == "edger":
|
|
680
|
+
df_pseudobulk.set_index("Unnamed: 0", inplace=True)
|
|
681
|
+
df_pseudobulk.index.name = None
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
# CleanUp
|
|
685
|
+
df_pseudobulk["GeneName"] = df_pseudobulk.index
|
|
686
|
+
df_pseudobulk.rename(
|
|
687
|
+
columns={
|
|
688
|
+
"log2FoldChange": f"log2fc_{test_pseudobulk}",
|
|
689
|
+
"stat": f"stat_{test_pseudobulk}",
|
|
690
|
+
"pvalue": f"pval_{test_pseudobulk}",
|
|
691
|
+
"padj": f"padj_{test_pseudobulk}",
|
|
692
|
+
"logFC": f"log2fc_{test_pseudobulk}",
|
|
693
|
+
"F": f"stat_{test_pseudobulk}",
|
|
694
|
+
"PValue": f"pval_{test_pseudobulk}",
|
|
695
|
+
"FDR": f"padj_{test_pseudobulk}",
|
|
696
|
+
},
|
|
697
|
+
inplace=True,
|
|
698
|
+
)
|
|
699
|
+
|
|
700
|
+
df_pseudobulk = df_pseudobulk[
|
|
701
|
+
[
|
|
702
|
+
"GeneName",
|
|
703
|
+
f"log2fc_{test_pseudobulk}",
|
|
704
|
+
f"stat_{test_pseudobulk}",
|
|
705
|
+
f"pval_{test_pseudobulk}",
|
|
706
|
+
f"padj_{test_pseudobulk}",
|
|
707
|
+
"group",
|
|
708
|
+
]
|
|
709
|
+
].reset_index(drop=True)
|
|
710
|
+
|
|
711
|
+
# Add missing genes for the consensus
|
|
712
|
+
missing = (
|
|
713
|
+
df_pseudobulk.groupby("group")["GeneName"]
|
|
714
|
+
.apply(lambda x: list(set(adata.var_names) - set(x)))
|
|
715
|
+
.reset_index(name="missing_values")
|
|
716
|
+
)
|
|
717
|
+
tmp = pd.DataFrame([])
|
|
718
|
+
cols_names = [
|
|
719
|
+
f"log2fc_{test_pseudobulk}",
|
|
720
|
+
f"stat_{test_pseudobulk}",
|
|
721
|
+
f"pval_{test_pseudobulk}",
|
|
722
|
+
f"padj_{test_pseudobulk}",
|
|
723
|
+
]
|
|
724
|
+
for idx, row in missing.iterrows():
|
|
725
|
+
new_rows = pd.DataFrame(row["missing_values"], columns=["GeneName"])
|
|
726
|
+
template = pd.DataFrame(np.zeros((new_rows.shape[0], 4)), columns=cols_names)
|
|
727
|
+
template["group"] = row["group"]
|
|
728
|
+
template[f"pval_{test_pseudobulk}"] = 1
|
|
729
|
+
template[f"padj_{test_pseudobulk}"] = 1
|
|
730
|
+
new_rows = new_rows.join(template)
|
|
731
|
+
tmp = pd.concat([tmp, new_rows])
|
|
732
|
+
df_pseudobulk = pd.concat([df_pseudobulk, tmp])
|
|
733
|
+
|
|
734
|
+
# If a group was not tested we also need to add it
|
|
735
|
+
missing = [c for c in df_sc[cluster_key].unique() if c not in df_pseudobulk["group"].unique()]
|
|
736
|
+
tmp = pd.DataFrame([])
|
|
737
|
+
for m in missing:
|
|
738
|
+
new_rows = pd.DataFrame(list(adata.var_names), columns=["GeneName"])
|
|
739
|
+
template = pd.DataFrame(np.zeros((new_rows.shape[0], 4)), columns=cols_names)
|
|
740
|
+
template["group"] = m
|
|
741
|
+
template[f"pval_{test_pseudobulk}"] = 1
|
|
742
|
+
template[f"padj_{test_pseudobulk}"] = 1
|
|
743
|
+
new_rows = new_rows.join(template)
|
|
744
|
+
tmp = pd.concat([tmp, new_rows])
|
|
745
|
+
df_pseudobulk = pd.concat([df_pseudobulk, tmp])
|
|
746
|
+
df_pseudobulk.rename(columns={"group": cluster_key}, inplace=True)
|
|
747
|
+
df_sc = df_sc[df_sc.group == disease_cond]
|
|
748
|
+
assert df_sc.shape[0] == df_pseudobulk.shape[0]
|
|
749
|
+
df_consensus = df_sc.merge(df_pseudobulk, on=["GeneName", cluster_key])
|
|
750
|
+
|
|
751
|
+
df_consensus["sc_signicant"] = ["Yes" if pval < pval_cutoff else "No" for pval in df_consensus["padj"]]
|
|
752
|
+
df_consensus["psc_signicant"] = [
|
|
753
|
+
"Yes" if pval < pval_cutoff else "No" for pval in df_consensus[f"padj_{test_pseudobulk}"]
|
|
754
|
+
]
|
|
755
|
+
df_consensus["consensus_significant"] = df_consensus.apply(
|
|
756
|
+
lambda row: "Yes" if row["sc_signicant"] == "Yes" and row["psc_signicant"] == "Yes" else "No", axis=1
|
|
757
|
+
)
|
|
758
|
+
|
|
759
|
+
# Mean per cluster for each sample correct
|
|
760
|
+
df_mean = mean_expr(adata, group_by=[condition_key, cluster_key], features=list(adata.var_names))
|
|
761
|
+
df_mean[condition_key] = "MeanExpr_" + df_mean[condition_key].astype(str)
|
|
762
|
+
df_mean = df_mean.pivot(index=["gene", cluster_key], columns=condition_key, values="expr").reset_index()
|
|
763
|
+
df_mean.rename(columns={"gene": "GeneName", cluster_key: cluster_key}, inplace=True)
|
|
764
|
+
df_mean = df_mean.reset_index(drop=True)
|
|
765
|
+
|
|
766
|
+
df_consensus = df_consensus.merge(df_mean, on=["GeneName", cluster_key])
|
|
767
|
+
|
|
768
|
+
adata.uns[key_added] = df_consensus
|
|
769
|
+
|
|
770
|
+
if path is not None:
|
|
771
|
+
df_consensus.to_excel(convert_path(path) / filename, index=False)
|
|
772
|
+
|
|
773
|
+
if get_results:
|
|
774
|
+
return df_consensus
|
|
775
|
+
else:
|
|
776
|
+
return None
|