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,567 @@
|
|
|
1
|
+
import anndata as ad
|
|
2
|
+
#import matplotlib.pyplot as plt
|
|
3
|
+
import numpy as np
|
|
4
|
+
from typing import Literal
|
|
5
|
+
|
|
6
|
+
import pandas as pd
|
|
7
|
+
#from scipy.cluster.hierarchy import dendrogram, linkage
|
|
8
|
+
#from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from dotools_py.utils import iterase_input, check_missing, sanitize_anndata
|
|
11
|
+
from dotools_py.get._generic import expr as get_expr
|
|
12
|
+
from dotools_py import logger
|
|
13
|
+
#import matplotlib.pyplot as plt
|
|
14
|
+
#from scipy.stats import zscore
|
|
15
|
+
|
|
16
|
+
#import dotools_py as do
|
|
17
|
+
from dotools_py.tl._get_stats import rank_genes_groups
|
|
18
|
+
from scanpy.get.get import rank_genes_groups_df
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# Base class for plots like heatmap or dotplot
|
|
22
|
+
|
|
23
|
+
class MatrixDataGenerator:
|
|
24
|
+
DEFAULT_ESTIMATOR = "mean"
|
|
25
|
+
DEFAULT_EXPR_CUTOFF = 0
|
|
26
|
+
|
|
27
|
+
def __init__(self,
|
|
28
|
+
adata: ad.AnnData,
|
|
29
|
+
x_axis: str,
|
|
30
|
+
features: str | list,
|
|
31
|
+
y_axis: str = None,
|
|
32
|
+
logcounts: bool = True,
|
|
33
|
+
layer: str = None,
|
|
34
|
+
estimator: str = None, # TODO Allow Fx
|
|
35
|
+
mean_express_only: bool = False,
|
|
36
|
+
expression_cutoff: float = None,
|
|
37
|
+
z_score: Literal["x_axis", "y_axis"] = None,
|
|
38
|
+
minmax: Literal["x_axis", "y_axis"] = None,
|
|
39
|
+
test: Literal["wilcoxon", "t-test"] = "wilcoxon",
|
|
40
|
+
correction_method: Literal["benjamini-hochberg", "bonferroni"] = "benjamini-hochberg",
|
|
41
|
+
add_stats: Literal["x_axis", "y_axis"] = None,
|
|
42
|
+
df_pvals: pd.DataFrame = None,
|
|
43
|
+
pval_cutoff: float = 0.05,
|
|
44
|
+
lfc_cutoff: float = 0.25,
|
|
45
|
+
):
|
|
46
|
+
|
|
47
|
+
sanitize_anndata(adata) # Convert string columns to categorical
|
|
48
|
+
|
|
49
|
+
self.adata = adata
|
|
50
|
+
self.x_axis = iterase_input(x_axis) # Convert to list
|
|
51
|
+
self.y_axis = iterase_input(y_axis)
|
|
52
|
+
self.group_by = self.x_axis + self.y_axis
|
|
53
|
+
self.features = iterase_input(features) # Convert to list
|
|
54
|
+
self.logcounts = logcounts # Whether input is logcounts
|
|
55
|
+
self.layer = layer
|
|
56
|
+
self.estimator = estimator if estimator is not None else self.DEFAULT_ESTIMATOR
|
|
57
|
+
self.mean_express_only = mean_express_only
|
|
58
|
+
self.expression_cutoff = expression_cutoff if expression_cutoff is not None else self.DEFAULT_EXPR_CUTOFF
|
|
59
|
+
self.z_score = z_score
|
|
60
|
+
self.minmax = minmax
|
|
61
|
+
self.test = test
|
|
62
|
+
self.correction_method = correction_method
|
|
63
|
+
self.add_stats = add_stats
|
|
64
|
+
self.df_pvals = df_pvals
|
|
65
|
+
self.pval_cutoff = pval_cutoff
|
|
66
|
+
self.lfc_cutoff = lfc_cutoff
|
|
67
|
+
|
|
68
|
+
assert not (
|
|
69
|
+
self.z_score is not None and self.minmax is not None), "Specify either Z-score or MinMax Normalisation, not both"
|
|
70
|
+
|
|
71
|
+
# Cheks
|
|
72
|
+
check_missing(self.adata, groups=self.x_axis + self.y_axis, features=self.features)
|
|
73
|
+
|
|
74
|
+
def get_expr_df(self):
|
|
75
|
+
"""Calculate the mean expression for the features per group.
|
|
76
|
+
|
|
77
|
+
:return: The df_mean and df_expr attribute are initialise containing a dataframe in long format
|
|
78
|
+
with the mean expression and expression.
|
|
79
|
+
"""
|
|
80
|
+
if all(item in list(self.adata.var_names) for item in self.features):
|
|
81
|
+
df_expr = get_expr(
|
|
82
|
+
self.adata, features=self.features, groups=self.group_by, layer=self.layer, out_format="wide"
|
|
83
|
+
)
|
|
84
|
+
df_expr.set_index(self.group_by, inplace=True) # Set Index
|
|
85
|
+
|
|
86
|
+
# If mean_express_only is True, the mean is only over the cells with expr > expression_cutoff
|
|
87
|
+
obs_bool = df_expr > self.expression_cutoff if self.mean_express_only else df_expr > float("-inf")
|
|
88
|
+
|
|
89
|
+
if self.estimator != "mean":
|
|
90
|
+
logger.warn(f"Estimator set to {self.estimator}, but mean will be used")
|
|
91
|
+
|
|
92
|
+
# Case 1: Input are features in .var_names and are log-normalise
|
|
93
|
+
if self.logcounts:
|
|
94
|
+
df_expr = np.expm1(df_expr)
|
|
95
|
+
df = np.log1p(
|
|
96
|
+
df_expr.mask(~obs_bool).groupby(level=self.group_by, observed=True).mean().fillna(0)
|
|
97
|
+
)
|
|
98
|
+
else:
|
|
99
|
+
# Case 2: Input are features in .var_names and are not log-normalise
|
|
100
|
+
df = df_expr.mask(~obs_bool).groupby(level=self.group_by, observed=True).mean().fillna(0)
|
|
101
|
+
|
|
102
|
+
elif all(item in iterase_input(self.adata.obs.columns) for item in self.features):
|
|
103
|
+
# Case 3: Input are features in .obs
|
|
104
|
+
df_expr = self.adata.obs[self.features + self.group_by]
|
|
105
|
+
df_expr.set_index(self.group_by, inplace=True) # Set Index
|
|
106
|
+
df = self.adata.obs[self.group_by + self.features].groupby(self.group_by).agg(self.estimator)
|
|
107
|
+
else:
|
|
108
|
+
raise Exception("Provide features either in var_names or obs.columns")
|
|
109
|
+
|
|
110
|
+
self.df_mean = df.reset_index()
|
|
111
|
+
self.df_expr = df_expr
|
|
112
|
+
return None
|
|
113
|
+
|
|
114
|
+
def get_pct_df(self):
|
|
115
|
+
"""Calculate the proportion of cells expressing a feature based on a cutoff.
|
|
116
|
+
|
|
117
|
+
:return: The df_pct attribute is initialise containing a dataframe in long format with the percentage
|
|
118
|
+
of cells expressing the features
|
|
119
|
+
"""
|
|
120
|
+
try:
|
|
121
|
+
obs_bool = self.df_expr > self.expression_cutoff
|
|
122
|
+
except AttributeError as e:
|
|
123
|
+
self.get_expr_df()
|
|
124
|
+
obs_bool = self.df_expr > self.expression_cutoff
|
|
125
|
+
|
|
126
|
+
df_pct = (
|
|
127
|
+
obs_bool.groupby(level=self.group_by, observed=True).sum()
|
|
128
|
+
/ obs_bool.groupby(level=self.group_by, observed=True).count()
|
|
129
|
+
)
|
|
130
|
+
self.df_pct = df_pct
|
|
131
|
+
return None
|
|
132
|
+
|
|
133
|
+
def zscore_transform(self):
|
|
134
|
+
"""Perform Z-score transformation on the data.
|
|
135
|
+
|
|
136
|
+
:return: The df_zscore attribute is initialise.
|
|
137
|
+
"""
|
|
138
|
+
if self.z_score is not None:
|
|
139
|
+
df_mean = self.df_mean.set_index(self.group_by)
|
|
140
|
+
|
|
141
|
+
if len(self.y_axis) == 0:
|
|
142
|
+
if self.z_score == "x_axis":
|
|
143
|
+
df_mean = (
|
|
144
|
+
df_mean.T
|
|
145
|
+
.apply(lambda x: (x - x.mean(axis=0)) / x.std(axis=0, ddof=0)) # Scale over the genes
|
|
146
|
+
.fillna(0).T
|
|
147
|
+
)
|
|
148
|
+
else:
|
|
149
|
+
# If y_axis is written and y_axis is not define, then is done for each gene
|
|
150
|
+
df_mean = (
|
|
151
|
+
df_mean
|
|
152
|
+
.apply(lambda x: (x - x.mean(axis=0)) / x.std(axis=0, ddof=0)) # Scale over the genes
|
|
153
|
+
.fillna(0)
|
|
154
|
+
)
|
|
155
|
+
else:
|
|
156
|
+
z_score = self.y_axis if self.z_score == "x_axis" else self.x_axis
|
|
157
|
+
df_mean = (
|
|
158
|
+
df_mean.groupby(level=z_score)
|
|
159
|
+
.apply(lambda x: (x - x.mean(axis=0)) / x.std(axis=0,
|
|
160
|
+
ddof=0)) # Scale for each gene over the alternative axis
|
|
161
|
+
.fillna(0)
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
to_drop = [
|
|
165
|
+
i for i in range(len(df_mean.index.levels))
|
|
166
|
+
if i > 0 and df_mean.index.get_level_values(i).equals(df_mean.index.get_level_values(i - 1))
|
|
167
|
+
]
|
|
168
|
+
if to_drop:
|
|
169
|
+
df_mean = df_mean.droplevel(to_drop)
|
|
170
|
+
|
|
171
|
+
df_mean = df_mean.reset_index()
|
|
172
|
+
self.df_zscore = df_mean
|
|
173
|
+
else:
|
|
174
|
+
logger.warn("Specify axis to apply Z-score")
|
|
175
|
+
return None
|
|
176
|
+
|
|
177
|
+
def minmax_transform(self):
|
|
178
|
+
"""Perform MinMax normalisation on the data.
|
|
179
|
+
|
|
180
|
+
:return: The df_minmax attribute is initialise
|
|
181
|
+
"""
|
|
182
|
+
if self.minmax is not None:
|
|
183
|
+
df_mean = self.df_mean.set_index(self.group_by)
|
|
184
|
+
|
|
185
|
+
if len(self.y_axis) == 0:
|
|
186
|
+
if self.minmax == "x_axis":
|
|
187
|
+
# Scaling by x_axis would mean that we Scale for each x_axis group
|
|
188
|
+
df_mean = (
|
|
189
|
+
df_mean.T
|
|
190
|
+
.apply(lambda x: (x - x.min(axis=0)) / (x.max(axis=0) - x.min(axis=0)))
|
|
191
|
+
.fillna(0).T
|
|
192
|
+
) # group x gene
|
|
193
|
+
else:
|
|
194
|
+
# If y_axis is written and y_axis is not define, then is done for each gene
|
|
195
|
+
df_mean = (
|
|
196
|
+
df_mean
|
|
197
|
+
.apply(lambda x: (x - x.min(axis=0)) / (x.max(axis=0) - x.min(axis=0)))
|
|
198
|
+
.fillna(0)
|
|
199
|
+
) # group x gene
|
|
200
|
+
|
|
201
|
+
else:
|
|
202
|
+
minmax = self.y_axis if self.minmax == "x_axis" else self.x_axis
|
|
203
|
+
df_mean = (
|
|
204
|
+
df_mean.groupby(level=minmax)
|
|
205
|
+
.apply(lambda x: (x - x.min(axis=0)) / (x.max(axis=0) - x.min(axis=0)))
|
|
206
|
+
.fillna(0)
|
|
207
|
+
) # group/group2 x gene
|
|
208
|
+
|
|
209
|
+
df_mean = df_mean.reset_index()
|
|
210
|
+
self.df_minmax = df_mean
|
|
211
|
+
else:
|
|
212
|
+
logger.warn("Specify axis to perform minmax normalisation")
|
|
213
|
+
return None
|
|
214
|
+
|
|
215
|
+
def test_significance(self):
|
|
216
|
+
if self.add_stats == 'y_axis':
|
|
217
|
+
assert self.y_axis is not None, "Testing y_axis but argument is None"
|
|
218
|
+
|
|
219
|
+
group_by = self.x_axis[0] if self.add_stats == "x_axis" else self.y_axis[0]
|
|
220
|
+
|
|
221
|
+
if self.df_pvals is None:
|
|
222
|
+
if len(self.y_axis) == 0:
|
|
223
|
+
# We only group by the x_axis
|
|
224
|
+
if all(item in list(self.adata.var_names) for item in self.features):
|
|
225
|
+
# All features are in adata.var_names
|
|
226
|
+
try:
|
|
227
|
+
rank_genes_groups(
|
|
228
|
+
self.adata, groupby=group_by, method=self.test, tie_correct=True,
|
|
229
|
+
corr_method=self.correction_method, layer=self.layer
|
|
230
|
+
)
|
|
231
|
+
table = rank_genes_groups_df(self.adata, group=None)
|
|
232
|
+
table = table[table["names"].isin(self.features)]
|
|
233
|
+
if len(table) == 0:
|
|
234
|
+
logger.warn("No significant group")
|
|
235
|
+
except ValueError as e:
|
|
236
|
+
logger.warn(f"Error testing, {e}")
|
|
237
|
+
table = pd.DataFrame([],
|
|
238
|
+
columns=['group', 'names', 'scores', 'logfoldchanges', 'pvals',
|
|
239
|
+
'pvals_adj', 'pct_nz_group', 'pct_nz_reference']
|
|
240
|
+
)
|
|
241
|
+
elif all(item in list(self.adata.obs.columns) for item in self.features):
|
|
242
|
+
# All features are in adata.obs.columns
|
|
243
|
+
table = pd.DataFrame([], columns=['group', 'names', 'scores', 'logfoldchanges', 'pvals',
|
|
244
|
+
'pvals_adj', 'pct_nz_group', 'pct_nz_reference'])
|
|
245
|
+
logger.warn("Testing for .obs variables not implemented")
|
|
246
|
+
else:
|
|
247
|
+
raise NotImplementedError("Provide either features in var_names or in obs, not both")
|
|
248
|
+
else:
|
|
249
|
+
alternative = self.x_axis[0] if self.add_stats == "y_axis" else self.y_axis[0]
|
|
250
|
+
# We group by the x_axis and y_axis
|
|
251
|
+
if all(item in list(self.adata.var_names) for item in self.features):
|
|
252
|
+
# All features are in adata.var_names
|
|
253
|
+
table = pd.DataFrame([])
|
|
254
|
+
for alt in self.adata.obs[alternative].unique():
|
|
255
|
+
sdata = self.adata[self.adata.obs[alternative] == alt].copy()
|
|
256
|
+
try:
|
|
257
|
+
rank_genes_groups(
|
|
258
|
+
sdata, groupby=group_by, method=self.test, tie_correct=True,
|
|
259
|
+
corr_method=self.correction_method, layer=self.layer
|
|
260
|
+
)
|
|
261
|
+
stable = rank_genes_groups_df(sdata, group=None)
|
|
262
|
+
except ValueError as e:
|
|
263
|
+
logger.warn(f"Error while testing: {e}")
|
|
264
|
+
stable = pd.DataFrame([],
|
|
265
|
+
columns=['group', 'names', 'scores', 'logfoldchanges', 'pvals',
|
|
266
|
+
'pvals_adj', 'pct_nz_group', 'pct_nz_reference', "group2"]
|
|
267
|
+
)
|
|
268
|
+
stable = stable[stable["names"].isin(self.features)]
|
|
269
|
+
stable['group2'] = alt
|
|
270
|
+
table = pd.concat([table, stable])
|
|
271
|
+
if len(table) == 0:
|
|
272
|
+
logger.warn('No Significant group')
|
|
273
|
+
elif all(item in list(self.adata.obs.columns) for item in self.features):
|
|
274
|
+
# All features are in adata.obs.columns
|
|
275
|
+
table = pd.DataFrame([], columns=['group', 'names', 'scores', 'logfoldchanges', 'pvals',
|
|
276
|
+
'pvals_adj', 'pct_nz_group', 'pct_nz_reference', "group2"])
|
|
277
|
+
logger.warn("Testing for .obs variables not implemented")
|
|
278
|
+
else:
|
|
279
|
+
raise NotImplementedError("Provide either features in var_names or in obs, not both")
|
|
280
|
+
|
|
281
|
+
table["group"] = table["group"].str.replace("-", "_") # TODO remove correction in get_expr()
|
|
282
|
+
if len(self.y_axis) != 0:
|
|
283
|
+
table["group2"] = table["group2"].str.replace("-", "_")
|
|
284
|
+
|
|
285
|
+
self.df_pvals = table # retain logfoldchanges and pvals
|
|
286
|
+
self.pvals_groupby = group_by
|
|
287
|
+
else:
|
|
288
|
+
pass
|
|
289
|
+
|
|
290
|
+
return None
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
# class MatrixPlotter:
|
|
294
|
+
# DEFAULT_CMAP = "Reds"
|
|
295
|
+
# DEFAULT_TITLE = "",
|
|
296
|
+
# DEFAULT_XTICK_ROTATION = 90
|
|
297
|
+
# DEFAULT_FIGSIZE = (5, 4)
|
|
298
|
+
#
|
|
299
|
+
# def __init__(self,
|
|
300
|
+
# adata: ad.AnnData,
|
|
301
|
+
# x_axis: str,
|
|
302
|
+
# features: str | list,
|
|
303
|
+
# kind: Literal["dotplot", "heatmap"],
|
|
304
|
+
# z_score: bool = False,
|
|
305
|
+
# min_max: bool = False,
|
|
306
|
+
# cmap: str = None,
|
|
307
|
+
# vmax: float | None = None,
|
|
308
|
+
# vmin: float | None = None,
|
|
309
|
+
# vcenter: float | None = None,
|
|
310
|
+
# title: str | None = None,
|
|
311
|
+
# size_legend_title: str = "Fraction of cells\nin group (%)",
|
|
312
|
+
# color_legend_title: str = "LogMean(nUMI)\nin group",
|
|
313
|
+
# x_ticks_rotation: int = None,
|
|
314
|
+
# swap_axis: bool = True,
|
|
315
|
+
# axis: plt.Axes = None,
|
|
316
|
+
# figsize: tuple = None,
|
|
317
|
+
# path: str | Path = None,
|
|
318
|
+
# filename: str = "plot.pdf",
|
|
319
|
+
# show: bool = True,
|
|
320
|
+
# ):
|
|
321
|
+
#
|
|
322
|
+
# self.adata = adata
|
|
323
|
+
# self.x_axis = x_axis
|
|
324
|
+
# self.y_axis = features
|
|
325
|
+
# self.kind = kind
|
|
326
|
+
# self.cmap = self.DEFAULT_CMAP if cmap is None else cmap
|
|
327
|
+
# self.vmax = vmax
|
|
328
|
+
# self.vmin = vmin
|
|
329
|
+
# self.vcenter = vcenter
|
|
330
|
+
# self.main_title = title
|
|
331
|
+
# self.size_legend_title = size_legend_title
|
|
332
|
+
# self.color_legend_title = color_legend_title
|
|
333
|
+
# self.x_ticks_rotation = x_ticks_rotation
|
|
334
|
+
# self.axis = axis
|
|
335
|
+
# self.figsize = self.DEFAULT_FIGSIZE if figsize is None else figsize
|
|
336
|
+
# self.width, self.height = self.figsize
|
|
337
|
+
#
|
|
338
|
+
# # Saving Parameters
|
|
339
|
+
# self.path = path
|
|
340
|
+
# self.filename = filename
|
|
341
|
+
# self.show = show
|
|
342
|
+
# self.swap_axis = swap_axis
|
|
343
|
+
#
|
|
344
|
+
# def make_figure(self):
|
|
345
|
+
# legends_width_spacer = 0.7 / self.width
|
|
346
|
+
# mainplot_width = self.width - (1.5 + 0)
|
|
347
|
+
#
|
|
348
|
+
#
|
|
349
|
+
#
|
|
350
|
+
# def set_layout(self):
|
|
351
|
+
# if self.z_score is not None:
|
|
352
|
+
# if self.cmap == "Reds":
|
|
353
|
+
# logger.warn(
|
|
354
|
+
# "Z-score set to True, but the cmap is Reds, setting to RdBu_r"
|
|
355
|
+
# ) # Make sure to use divergent colormap
|
|
356
|
+
# self.color_legend_title = "Z-score"
|
|
357
|
+
# self.cmap = "RdBu_r"
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
# ##########################################
|
|
366
|
+
# def heatmap(
|
|
367
|
+
# adata: ad.AnnData,
|
|
368
|
+
# x_axis: str | list,
|
|
369
|
+
# features: str | list,
|
|
370
|
+
# groups_order: list = None,
|
|
371
|
+
# z_score: Literal["x_axis", "y_axis"] = None, # x_axis is the group_by
|
|
372
|
+
# min_max: Literal["x_axis", "y_axis"] = None,
|
|
373
|
+
# path: str = None,
|
|
374
|
+
# filename: str = "Heatmap.svg",
|
|
375
|
+
# layer: str = None,
|
|
376
|
+
# swap_axes: bool = True,
|
|
377
|
+
# cmap: str = "Reds",
|
|
378
|
+
# title: str = None,
|
|
379
|
+
# title_fontprop: dict = None,
|
|
380
|
+
# clustering_method: str = "complete",
|
|
381
|
+
# clustering_metric: str = "euclidean",
|
|
382
|
+
# cluster_x_axis: bool = False,
|
|
383
|
+
# cluster_y_axis: bool = False,
|
|
384
|
+
# axs: plt.Axes = None,
|
|
385
|
+
# figsize: tuple = (5, 6),
|
|
386
|
+
# linewidth: float = 0.1,
|
|
387
|
+
# ticks_fontdict: dict = None,
|
|
388
|
+
# xticks_rotation: int = None,
|
|
389
|
+
# yticks_rotation: int = None,
|
|
390
|
+
# vmin: float = 0.0,
|
|
391
|
+
# vcenter: float = None,
|
|
392
|
+
# vmax: float = None,
|
|
393
|
+
# legend_title: str = "LogMean(nUMI)\nin group",
|
|
394
|
+
# add_stats: bool = False,
|
|
395
|
+
# df_pvals: pd.DataFrame = None,
|
|
396
|
+
# stats_x_size: float = None,
|
|
397
|
+
# square_x_size: dict = None,
|
|
398
|
+
# test: Literal["wilcoxon", "t-test"] = "wilcoxon",
|
|
399
|
+
# correction_method: Literal["benjamini-hochberg", "bonferroni"] = "benjamini-hochberg",
|
|
400
|
+
# pval_cutoff: float = 0.05,
|
|
401
|
+
# log2fc_cutoff: float = 0.0,
|
|
402
|
+
# square: bool = True,
|
|
403
|
+
# show: bool = True,
|
|
404
|
+
# logcounts: bool = True,
|
|
405
|
+
# **kargs,
|
|
406
|
+
# ) -> dict | None:
|
|
407
|
+
# """Heatmap of the mean expression of genes across a groups.
|
|
408
|
+
#
|
|
409
|
+
# Generate a heatmap of showing the average nUMI for a set of genes in different groups. Differential gene
|
|
410
|
+
# expression analysis between the different groups can be performed.
|
|
411
|
+
#
|
|
412
|
+
# :param adata: annotated data matrix.
|
|
413
|
+
# :param group_by: obs column name with categorical values.
|
|
414
|
+
# :param features: continuous value in var_names or obs.
|
|
415
|
+
# :param groups_order: order for the categories in group_by
|
|
416
|
+
# :param z_score: apply z-score transformation.
|
|
417
|
+
# :param path: path to save the plot
|
|
418
|
+
# :param filename: name of the file.
|
|
419
|
+
# :param layer: layer to use.
|
|
420
|
+
# :param swap_axes: whether to swap the axes or not.
|
|
421
|
+
# :param cmap: colormap.
|
|
422
|
+
# :param title: title for the main plot.
|
|
423
|
+
# :param title_fontprop: font properties for the title (e.g., 'weight' and 'size').
|
|
424
|
+
# :param clustering_method: clustering method to use when hierarchically clustering the x and y-axis.
|
|
425
|
+
# :param clustering_metric: metric to use when hierarchically clustering the x and y-axis.
|
|
426
|
+
# :param cluster_x_axis: hierarchically clustering the x-axis.
|
|
427
|
+
# :param cluster_y_axis: hierarchically clustering the y-axis.
|
|
428
|
+
# :param axs: matplotlib axis.
|
|
429
|
+
# :param figsize: figure size.
|
|
430
|
+
# :param linewidth: linewidth for the border of cells.
|
|
431
|
+
# :param ticks_fontdict: font properties for the x and y ticks (e.g., 'weight' and 'size').
|
|
432
|
+
# :param xticks_rotation: rotation of the x-ticks.
|
|
433
|
+
# :param yticks_rotation: rotations of the y-ticks.
|
|
434
|
+
# :param vmin: minimum value.
|
|
435
|
+
# :param vcenter: center value.
|
|
436
|
+
# :param vmax: maximum value.
|
|
437
|
+
# :param legend_title: title for the colorbar.
|
|
438
|
+
# :param add_stats: add statistical annotation. Will add a square with an '*' in the center if the expression is significantly different in a group with respect to the others.
|
|
439
|
+
# :param df_pvals: dataframe with the pvals. Should be gene x group or group x gene in case of swap_axes is False.
|
|
440
|
+
# :param stats_x_size: scaling factor to control the size of the asterisk.
|
|
441
|
+
# :param square_x_size: size and thickness of the square.
|
|
442
|
+
# :param test: test to use for test for significance.
|
|
443
|
+
# :param correction_method: multiple correction method to use.
|
|
444
|
+
# :param pval_cutoff: cutoff for the p-value.
|
|
445
|
+
# :param log2fc_cutoff: minimum cutoff for the log2FC.
|
|
446
|
+
# :param square: whether to make the cell square or not.
|
|
447
|
+
# :param show: if set to false return a dictionary with the axis.
|
|
448
|
+
# :param logcounts: whether the input is logcounts or not.
|
|
449
|
+
# :param kargs: additional arguments pass to `sns.heatmap() <https://seaborn.pydata.org/generated/seaborn.heatmap.html>`_.
|
|
450
|
+
# :return: Depending on ``show``, returns the plot if set to `True` or a dictionary with the axes.
|
|
451
|
+
#
|
|
452
|
+
# Example
|
|
453
|
+
# -------
|
|
454
|
+
#
|
|
455
|
+
# .. plot::
|
|
456
|
+
# :context: close-figs
|
|
457
|
+
#
|
|
458
|
+
# import dotools_py as do
|
|
459
|
+
# adata = do.dt.example_10x_processed()
|
|
460
|
+
# do.pl.heatmap(adata, 'annotation', ['CD4', 'CD79A'], add_stats=True)
|
|
461
|
+
#
|
|
462
|
+
# """
|
|
463
|
+
#
|
|
464
|
+
#
|
|
465
|
+
# x_axis = "annotation"
|
|
466
|
+
# features = ["CD4", "CD79A"]
|
|
467
|
+
# logcounts=True
|
|
468
|
+
# layer = None
|
|
469
|
+
# z_score = None
|
|
470
|
+
# min_max = None
|
|
471
|
+
# test = "wilcoxon"
|
|
472
|
+
# correction_method = "benjamini-hochberg"
|
|
473
|
+
# add_stats = True
|
|
474
|
+
# pval_cutoff = 0.05
|
|
475
|
+
# log2fc_cutoff = 0.25
|
|
476
|
+
# x_groups_order = None
|
|
477
|
+
#
|
|
478
|
+
# sanitize_anndata(adata)
|
|
479
|
+
#
|
|
480
|
+
# data = MatrixDataGenerator(adata=adata,
|
|
481
|
+
# x_axis=x_axis,
|
|
482
|
+
# features=features,
|
|
483
|
+
# y_axis=None, # TODO Allow
|
|
484
|
+
# logcounts=logcounts,
|
|
485
|
+
# layer=layer,
|
|
486
|
+
# estimator=None, # Always Mean
|
|
487
|
+
# mean_express_only=False,
|
|
488
|
+
# expression_cutoff=None,
|
|
489
|
+
# z_score=z_score,
|
|
490
|
+
# minmax=min_max,
|
|
491
|
+
# test=test,
|
|
492
|
+
# correction_method=correction_method,
|
|
493
|
+
# add_stats="x_axis" if add_stats else None,
|
|
494
|
+
# df_pvals=None,
|
|
495
|
+
# pval_cutoff=pval_cutoff,
|
|
496
|
+
# lfc_cutoff=log2fc_cutoff,
|
|
497
|
+
# )
|
|
498
|
+
#
|
|
499
|
+
# data.get_expr_df() # Compute mean expression
|
|
500
|
+
#
|
|
501
|
+
# if z_score is not None:
|
|
502
|
+
# data.zscore_transform()
|
|
503
|
+
# df_plot = data.df_zscore.copy()
|
|
504
|
+
# elif min_max is not None:
|
|
505
|
+
# data.minmax_transform()
|
|
506
|
+
# df_plot = data.df_minmax.copy()
|
|
507
|
+
# else:
|
|
508
|
+
# df_plot = data.df_mean.copy() # wide format
|
|
509
|
+
#
|
|
510
|
+
# df_plot = (df_plot
|
|
511
|
+
# .melt(id_vars=x_axis, var_name="genes", value_name="expr")
|
|
512
|
+
# .pivot(index=x_axis, columns="genes", values="expr")) # Convert to matrix format x_axis x features
|
|
513
|
+
#
|
|
514
|
+
# # Get the Dataframe with pvals if we want significance
|
|
515
|
+
# if add_stats:
|
|
516
|
+
# data.test_significance()
|
|
517
|
+
# df_pvals = data.df_pvals.copy()
|
|
518
|
+
# df_pvals = df_pvals[["group", "names", "pvals_adj"]].pivot(
|
|
519
|
+
# index="group", columns="names", values="pvals_adj"
|
|
520
|
+
# ).fillna(0)
|
|
521
|
+
# else:
|
|
522
|
+
# df_pvals = pd.DataFrame(np.ones(df_plot.shape), index=df_plot.index, columns=df_plot.columns)
|
|
523
|
+
#
|
|
524
|
+
#
|
|
525
|
+
# # Hierarchical clustering --> Set the order for the X and Y Axis
|
|
526
|
+
# index_order = x_groups_order if x_groups_order is not None else list(adata.obs[x_axis].cat.categories)
|
|
527
|
+
# new_index = (
|
|
528
|
+
# df_plot.index[
|
|
529
|
+
# dendrogram(linkage(df_plot.values, method=clustering_method, metric=clustering_metric), no_plot=True)["leaves"]
|
|
530
|
+
# ]
|
|
531
|
+
# if cluster_x_axis
|
|
532
|
+
# else index_order # Order from the object or user provided
|
|
533
|
+
# )
|
|
534
|
+
#
|
|
535
|
+
# new_columns = (
|
|
536
|
+
# df_plot.columns[
|
|
537
|
+
# dendrogram(linkage(df_plot.T.values, method=clustering_method, metric=clustering_metric), no_plot=True)["leaves"]
|
|
538
|
+
# ]
|
|
539
|
+
# if cluster_y_axis
|
|
540
|
+
# else features # Keep the order from the input
|
|
541
|
+
# )
|
|
542
|
+
#
|
|
543
|
+
# df_plot = df_plot.reindex(index=new_index, columns=new_columns)
|
|
544
|
+
# df_pvals = df_pvals.reindex(index=new_index, columns=new_columns)
|
|
545
|
+
#
|
|
546
|
+
# if swap_axes:
|
|
547
|
+
# df_plot = df_plot.T
|
|
548
|
+
# df_pvals = df_pvals.T
|
|
549
|
+
#
|
|
550
|
+
# annot_pvals = df_pvals.applymap(lambda x: "*" if x < pval_cutoff else "")
|
|
551
|
+
#
|
|
552
|
+
#
|
|
553
|
+
# # Initialise Plotter Class
|
|
554
|
+
#
|
|
555
|
+
#
|
|
556
|
+
#
|
|
557
|
+
#
|
|
558
|
+
#
|
|
559
|
+
# if cmap == "Reds":
|
|
560
|
+
# logger.warn(
|
|
561
|
+
# "Z-score set to True, but the cmap is Reds, setting to RdBu_r"
|
|
562
|
+
# ) # Make sure to use divergent colormap
|
|
563
|
+
# cmap = "RdBu_r"
|
|
564
|
+
# if legend_title == "LogMean(nUMI)\nin group":
|
|
565
|
+
# legend_title = "Z-score"
|
|
566
|
+
# #vmin, vcenter, vmax = round(df.min().min() * 20) / 20, 0.0, None
|
|
567
|
+
#
|