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,716 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
from typing import Literal
|
|
3
|
+
|
|
4
|
+
import anndata as ad
|
|
5
|
+
import matplotlib.pyplot as plt
|
|
6
|
+
import numpy as np
|
|
7
|
+
import pandas as pd
|
|
8
|
+
from matplotlib.collections import PolyCollection
|
|
9
|
+
from matplotlib.patches import PathPatch
|
|
10
|
+
from scipy.stats import f_oneway, kruskal, mannwhitneyu, shapiro, ttest_ind
|
|
11
|
+
|
|
12
|
+
from dotools_py import logger
|
|
13
|
+
from dotools_py.utils import sanitize_anndata
|
|
14
|
+
|
|
15
|
+
DEFAULT_TXT_SIZE = 13
|
|
16
|
+
DEFAULT_TXT = "p ="
|
|
17
|
+
DEFAULT_LINES_OFFSET = 0.05
|
|
18
|
+
DEFAULT_TEST = "wilcoxon"
|
|
19
|
+
DEFAULT_MULTIPLE_TEST_CORRECTION = "benjamini-hochberg"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class StatsPlotter:
|
|
23
|
+
"""Class to add statistics on bar, box or violin plots.
|
|
24
|
+
|
|
25
|
+
This class add statistical annotations to bar, box and violin plots. A bracket will connect the control and tested
|
|
26
|
+
condition and will indicate the p-value. The control and conditions to be tested should be in the x_axis.
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
Parameters
|
|
30
|
+
----------
|
|
31
|
+
axis
|
|
32
|
+
matplotlib axis.
|
|
33
|
+
x_axis
|
|
34
|
+
name of the x-axis.
|
|
35
|
+
y_axis
|
|
36
|
+
name of the y-axis.
|
|
37
|
+
ctrl
|
|
38
|
+
name of the control condition. Expected to be present in the xticks.
|
|
39
|
+
groups
|
|
40
|
+
list of conditions in the xticks that have been tested.
|
|
41
|
+
txt_size
|
|
42
|
+
size of the text added.
|
|
43
|
+
txt
|
|
44
|
+
text to add before the p-value (e.g., p = ). If not set, only the p-value is added.
|
|
45
|
+
pvals
|
|
46
|
+
list of p-values for the conditions in groups. Expected to be in the same order. If hue is provided, the order will
|
|
47
|
+
depend on the groups and the x-ticks (e.g., x-ticks: healthy, disease; and groups: cell1, cell2, then pvals should be
|
|
48
|
+
cell1_healthy Vs control_healthy, cell2_healthy Vs control_healthy, cell1_disease Vs control_disease, etc.). If hue
|
|
49
|
+
is specified the number of expected values is len(x_axis groups) * len(hue groups).
|
|
50
|
+
kind
|
|
51
|
+
type of plot. Available: box, violin, bar.
|
|
52
|
+
line_offset
|
|
53
|
+
brackets are added in the highest y-value plus this offset. This offset is interpret as a percentage
|
|
54
|
+
(i.e, a line offset of 0.05 means, we add an offset of 5 % to the height).
|
|
55
|
+
hue:
|
|
56
|
+
name of the variable used to split in subgroups.
|
|
57
|
+
hue_order:
|
|
58
|
+
order of the subgroups. Needs to be specified if hue is defined.
|
|
59
|
+
|
|
60
|
+
See Also
|
|
61
|
+
--------
|
|
62
|
+
:func:`dotools_py.pl.TestData`: useful class to calculate statistics
|
|
63
|
+
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
def __init__(
|
|
67
|
+
self,
|
|
68
|
+
axis: plt.Axes,
|
|
69
|
+
x_axis: str,
|
|
70
|
+
y_axis: str,
|
|
71
|
+
ctrl: str,
|
|
72
|
+
groups: list,
|
|
73
|
+
pvals: list,
|
|
74
|
+
txt_size: int = None,
|
|
75
|
+
txt: str = None,
|
|
76
|
+
kind: str = None,
|
|
77
|
+
line_offset: float = None,
|
|
78
|
+
hue: str = None,
|
|
79
|
+
hue_order: list = None,
|
|
80
|
+
):
|
|
81
|
+
"""Initialise.
|
|
82
|
+
|
|
83
|
+
:param axis: matplotlib axis.
|
|
84
|
+
:param x_axis: name of the x-axis.
|
|
85
|
+
:param y_axis: name of the y-axis.
|
|
86
|
+
:param ctrl: name of the control condition in x-axis.
|
|
87
|
+
:param groups: list of names in the x-axis to add the stats for.
|
|
88
|
+
:param txt_size: size of the text plotted.
|
|
89
|
+
:param txt: text to add before the p-value (e.g., p = ).
|
|
90
|
+
:param pvals: list of p-values for the groups.
|
|
91
|
+
:param kind: kind of plot: box, bar, violin.
|
|
92
|
+
:param line_offset: offset from the bars/violin/boxplot for the stats.
|
|
93
|
+
:param hue: name of the hue variable.
|
|
94
|
+
:param hue_order: order for the hue variable.
|
|
95
|
+
"""
|
|
96
|
+
if kind not in ["bar", "box", "violin"]:
|
|
97
|
+
raise NotImplementedError(f"{kind} not implemented")
|
|
98
|
+
|
|
99
|
+
self.axis = axis
|
|
100
|
+
self.kind = kind
|
|
101
|
+
|
|
102
|
+
self.x_axis = x_axis
|
|
103
|
+
self.xticks = self.axis.get_xmajorticklabels()
|
|
104
|
+
self.x_tick_pos = [_tick.get_position()[0] for _tick in self.xticks]
|
|
105
|
+
self.x_ticks_labels = [_tick.get_text() for _tick in self.xticks]
|
|
106
|
+
|
|
107
|
+
self.y_axis = y_axis
|
|
108
|
+
self.yticks = self.axis.get_ymajorticklabels()
|
|
109
|
+
self.y_ticks_pos = [_tick.get_position()[0] for _tick in self.yticks]
|
|
110
|
+
self.y_ticks_labels = [_tick.get_text() for _tick in self.yticks]
|
|
111
|
+
|
|
112
|
+
self.ctrl = ctrl
|
|
113
|
+
self.groups = [groups] if isinstance(groups, str) else groups
|
|
114
|
+
|
|
115
|
+
self.txt_size = DEFAULT_TXT_SIZE if txt_size is None else txt_size
|
|
116
|
+
self.txt = DEFAULT_TXT if txt is None else txt
|
|
117
|
+
self.line_offset = (
|
|
118
|
+
DEFAULT_LINES_OFFSET if line_offset is None else line_offset
|
|
119
|
+
) # TODO should be adjusted depending on the y-values
|
|
120
|
+
|
|
121
|
+
if pvals is not None:
|
|
122
|
+
pvals = [float(p) for p in pvals]
|
|
123
|
+
self.pvals = [
|
|
124
|
+
str(np.round(p, 2))
|
|
125
|
+
if p > 0.05
|
|
126
|
+
else str(np.round(p, 4))
|
|
127
|
+
if p > 0.009
|
|
128
|
+
else f"{sys.float_info.min if p == 0 else p:0.2e}"
|
|
129
|
+
for p in pvals
|
|
130
|
+
]
|
|
131
|
+
else:
|
|
132
|
+
self.pvals = pvals # Will not do anything, might raise error?
|
|
133
|
+
|
|
134
|
+
# Set-Up hue arguments
|
|
135
|
+
self.hue = hue
|
|
136
|
+
self.hue_order = hue_order
|
|
137
|
+
|
|
138
|
+
if hue is not None:
|
|
139
|
+
if hue_order is None:
|
|
140
|
+
raise Exception('If hue is specified, hue_order need to be specified')
|
|
141
|
+
if kind == "bar":
|
|
142
|
+
hue_positions = [round(bar.get_x() + bar.get_width() / 2, 2) for bar in self.axis.patches]
|
|
143
|
+
elif kind == "box" or kind == "violin":
|
|
144
|
+
# hue_positions = []
|
|
145
|
+
# for patch in self.axis.patches:
|
|
146
|
+
# x_pos = np.unique([x[0] for x in patch.get_path().vertices]).mean() # [[x0, y0], [x1, y1]...]
|
|
147
|
+
# hue_positions.append(x_pos)
|
|
148
|
+
hue_positions = []
|
|
149
|
+
for line in self.axis.lines:
|
|
150
|
+
x_vals = line.get_xdata()
|
|
151
|
+
if len(x_vals) == 0:
|
|
152
|
+
continue
|
|
153
|
+
# Median x-value gives center of violin outline
|
|
154
|
+
x_pos = np.median(np.unique(x_vals))
|
|
155
|
+
hue_positions.append(round(x_pos, 2))
|
|
156
|
+
hue_positions = list(np.unique(hue_positions))
|
|
157
|
+
else:
|
|
158
|
+
hue_positions = []
|
|
159
|
+
hue_positions = np.sort(hue_positions)
|
|
160
|
+
|
|
161
|
+
nhues = int(len(hue_positions) / len(self.x_ticks_labels))
|
|
162
|
+
hue_labels = [x + '_' + s for x, s in
|
|
163
|
+
zip(np.repeat(self.x_ticks_labels, nhues), np.tile(hue_order, len(self.x_ticks_labels)))]
|
|
164
|
+
|
|
165
|
+
self.hue_positions = hue_positions
|
|
166
|
+
self.hue_labels = hue_labels
|
|
167
|
+
self.hue_ctrl = [lab for lab in self.hue_labels if self.ctrl in lab]
|
|
168
|
+
self.hue_groups = [
|
|
169
|
+
[lab for lab in self.hue_labels if xtk in lab and any(g in lab for g in self.groups)]
|
|
170
|
+
for xtk in self.x_ticks_labels
|
|
171
|
+
]
|
|
172
|
+
|
|
173
|
+
# Check if we have the correct number of pvals
|
|
174
|
+
# if hue is provided len(pvals) --> len(x_axis groups) * len(hue groups)
|
|
175
|
+
if self.hue:
|
|
176
|
+
assert len(self.pvals) == len(self.groups) * len(self.hue_groups), f"{len(self.pvals)} pvals provided but {len(self.groups) * len(self.hue_groups)} groups tested"
|
|
177
|
+
else:
|
|
178
|
+
assert len(self.pvals) == len(self.groups), f"{len(self.pvals)} pvals provided but {len(self.groups)} groups tested"
|
|
179
|
+
return
|
|
180
|
+
|
|
181
|
+
def _get_height(self):
|
|
182
|
+
"""Calculate the heigh of bars, violins and boxs.
|
|
183
|
+
|
|
184
|
+
:return: Self
|
|
185
|
+
"""
|
|
186
|
+
# For bars (with capsize) and boxplots
|
|
187
|
+
if self.hue:
|
|
188
|
+
heights = dict.fromkeys(self.hue_positions, 0) # Adapt to consider when hue is provided
|
|
189
|
+
else:
|
|
190
|
+
heights = dict.fromkeys(self.x_tick_pos, 0)
|
|
191
|
+
|
|
192
|
+
# ViolinPlots use Polycollection (Priority) and line2D(boxplot inside)
|
|
193
|
+
if self.kind == "violin":
|
|
194
|
+
for _, pc in enumerate(self.axis.collections):
|
|
195
|
+
if isinstance(pc, PolyCollection):
|
|
196
|
+
y_vals = pc.get_paths()[0].vertices[:, 1] # The second column is the y-values
|
|
197
|
+
x_vals = round(pc.get_paths()[0].vertices[:, 0].mean(), 2)
|
|
198
|
+
if x_vals in heights:
|
|
199
|
+
heights[x_vals] = max(
|
|
200
|
+
max(y_vals), heights[x_vals]
|
|
201
|
+
) # We expect X to be Categorical and have always pos 0, 1, 2, ...
|
|
202
|
+
if self.kind in ["bar", "box"]:
|
|
203
|
+
# Bars with errorbars and boxplots (with/without outliers)
|
|
204
|
+
for line in self.axis.lines:
|
|
205
|
+
x_data, y_data = line.get_xdata(), line.get_ydata()
|
|
206
|
+
for x, y in zip(x_data, y_data, strict=False):
|
|
207
|
+
x = round(x, 2)
|
|
208
|
+
if x in heights:
|
|
209
|
+
heights[x] = max(heights[x], y)
|
|
210
|
+
|
|
211
|
+
# Bars without errorbars
|
|
212
|
+
try:
|
|
213
|
+
for key, val in heights.items():
|
|
214
|
+
if val == 0:
|
|
215
|
+
for patch in self.axis.patches:
|
|
216
|
+
x = (patch.get_x() + patch.get_x() + patch.get_width()) / 2
|
|
217
|
+
if key == x:
|
|
218
|
+
y = patch.get_height()
|
|
219
|
+
heights[x] = max(heights[x], y)
|
|
220
|
+
except AttributeError:
|
|
221
|
+
pass
|
|
222
|
+
|
|
223
|
+
self.heights = heights
|
|
224
|
+
return
|
|
225
|
+
|
|
226
|
+
def _get_pos_pairs(self):
|
|
227
|
+
"""Get x position and y heigh for the pairs tested.
|
|
228
|
+
|
|
229
|
+
:return: Self
|
|
230
|
+
"""
|
|
231
|
+
if self.hue:
|
|
232
|
+
pairs_xpos, pairs_ypos = [], []
|
|
233
|
+
for jdx, group in enumerate(self.hue_groups):
|
|
234
|
+
# Position in X Axis [[x0_start, x0_end], [x1_start, x1_end]]
|
|
235
|
+
xpair = [[self.hue_positions[self.hue_labels.index(self.hue_ctrl[jdx])],
|
|
236
|
+
self.hue_positions[self.hue_labels.index(group[idx])]]
|
|
237
|
+
for idx in range(len(group))]
|
|
238
|
+
pairs_xpos.extend(xpair)
|
|
239
|
+
|
|
240
|
+
# Position in Y Axis [y0, y1]
|
|
241
|
+
ypair = [max([self.heights[self.hue_positions[self.hue_labels.index(self.hue_ctrl[jdx])]],
|
|
242
|
+
self.heights[self.hue_positions[self.hue_labels.index(group[idx])]]])
|
|
243
|
+
for idx in range(len(group))
|
|
244
|
+
]
|
|
245
|
+
|
|
246
|
+
pairs_ypos.extend([max(val, max(self.heights.values())) for val in ypair]) # Start in the highest spot
|
|
247
|
+
else:
|
|
248
|
+
pairs_xpos, pairs_ypos = [], []
|
|
249
|
+
for group in self.groups:
|
|
250
|
+
# Position in X Axis [[x0_start, x0_end], [x1_start, x1_end]]
|
|
251
|
+
xpair = [
|
|
252
|
+
self.x_tick_pos[self.x_ticks_labels.index(self.ctrl)],
|
|
253
|
+
self.x_tick_pos[self.x_ticks_labels.index(group)],
|
|
254
|
+
]
|
|
255
|
+
pairs_xpos.append(xpair)
|
|
256
|
+
# Position in Y Axis [y0, y1]
|
|
257
|
+
ypair = [
|
|
258
|
+
self.heights[self.x_tick_pos[self.x_ticks_labels.index(self.ctrl)]],
|
|
259
|
+
self.heights[self.x_tick_pos[self.x_ticks_labels.index(group)]],
|
|
260
|
+
]
|
|
261
|
+
pairs_ypos.append(max(max(ypair), max(self.heights.values()))) # Start in the highest spot
|
|
262
|
+
self.pairs_xpos = pairs_xpos
|
|
263
|
+
self.pairs_ypos = pairs_ypos
|
|
264
|
+
return
|
|
265
|
+
|
|
266
|
+
def _get_offsets(self):
|
|
267
|
+
"""Get the offset to add the stats.
|
|
268
|
+
|
|
269
|
+
:return: Self
|
|
270
|
+
"""
|
|
271
|
+
if self.hue:
|
|
272
|
+
pairs_offset = {
|
|
273
|
+
label: round(ypos, 2)
|
|
274
|
+
for group, ypos in zip(self.hue_groups, self.pairs_ypos)
|
|
275
|
+
for label in group}
|
|
276
|
+
plotter_offset_hue = {xtck: {group: pairs_offset[group]
|
|
277
|
+
for group in pairs_offset if xtck in group}
|
|
278
|
+
for xtck in self.x_ticks_labels}
|
|
279
|
+
|
|
280
|
+
for key, val in pairs_offset.items():
|
|
281
|
+
offset_added = self.line_offset
|
|
282
|
+
new_pos = val + val * offset_added
|
|
283
|
+
current_hue = [g for g in self.x_ticks_labels if g in key][0]
|
|
284
|
+
|
|
285
|
+
if new_pos in plotter_offset_hue[current_hue].values():
|
|
286
|
+
cont = 0
|
|
287
|
+
while new_pos in plotter_offset_hue[current_hue].values():
|
|
288
|
+
if cont == 100:
|
|
289
|
+
break
|
|
290
|
+
offset_added += 0.05
|
|
291
|
+
new_pos = val + val * offset_added
|
|
292
|
+
cont += 1
|
|
293
|
+
pairs_offset[key] = new_pos
|
|
294
|
+
plotter_offset_hue[current_hue][key] = new_pos
|
|
295
|
+
else:
|
|
296
|
+
pairs_offset = {key: round(val, 2) for key in self.groups for val in self.pairs_ypos}
|
|
297
|
+
for key, val in pairs_offset.items():
|
|
298
|
+
offset_added = self.line_offset
|
|
299
|
+
new_pos = val + val * offset_added
|
|
300
|
+
if new_pos in pairs_offset.values():
|
|
301
|
+
cont = 0
|
|
302
|
+
while new_pos in pairs_offset.values():
|
|
303
|
+
if cont == 100:
|
|
304
|
+
break
|
|
305
|
+
offset_added += 0.05
|
|
306
|
+
new_pos = val + val * offset_added
|
|
307
|
+
cont += 1
|
|
308
|
+
pairs_offset[key] = new_pos
|
|
309
|
+
self.heights_offset = list(pairs_offset.values())
|
|
310
|
+
return
|
|
311
|
+
|
|
312
|
+
def _draw_brackets(self):
|
|
313
|
+
"""Draw the brackets for the stats conecting ctrl and group.
|
|
314
|
+
|
|
315
|
+
:return: Self
|
|
316
|
+
"""
|
|
317
|
+
from matplotlib.path import Path
|
|
318
|
+
|
|
319
|
+
if self.hue:
|
|
320
|
+
rects, _extra = [], 0
|
|
321
|
+
for group in self.hue_groups:
|
|
322
|
+
for _stat in range(len(group)):
|
|
323
|
+
_stat += _extra
|
|
324
|
+
if len(self.groups) == 1:
|
|
325
|
+
stem_length = (self.heights_offset[_stat] - np.max(list(self.heights.values()))) / 3
|
|
326
|
+
else:
|
|
327
|
+
try:
|
|
328
|
+
stem_length = (self.heights_offset[_stat + 1] - self.heights_offset[_stat]) / 3
|
|
329
|
+
except IndexError:
|
|
330
|
+
stem_length = np.abs((self.heights_offset[_stat - 1] - self.heights_offset[_stat]) / 3)
|
|
331
|
+
|
|
332
|
+
verts = [
|
|
333
|
+
(self.pairs_xpos[_stat][0], self.heights_offset[_stat] - stem_length),
|
|
334
|
+
(self.pairs_xpos[_stat][0], self.heights_offset[_stat]),
|
|
335
|
+
(self.pairs_xpos[_stat][1], self.heights_offset[_stat]),
|
|
336
|
+
(self.pairs_xpos[_stat][1], self.heights_offset[_stat] - stem_length),
|
|
337
|
+
]
|
|
338
|
+
codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO]
|
|
339
|
+
patch_path = Path(verts, codes)
|
|
340
|
+
patch = PathPatch(patch_path, linewidth=1, facecolor="none", edgecolor="k", clip_on=False)
|
|
341
|
+
rects.append(patch)
|
|
342
|
+
_extra += len(group)
|
|
343
|
+
else:
|
|
344
|
+
rects = []
|
|
345
|
+
for _stat in range(len(self.groups)):
|
|
346
|
+
if len(self.groups) == 1:
|
|
347
|
+
stem_length = (self.heights_offset[_stat] - np.max(list(self.heights.values()))) / 3
|
|
348
|
+
else:
|
|
349
|
+
try:
|
|
350
|
+
stem_length = (self.heights_offset[_stat + 1] - self.heights_offset[_stat]) / 3
|
|
351
|
+
except IndexError:
|
|
352
|
+
stem_length = np.abs((self.heights_offset[_stat - 1] - self.heights_offset[_stat]) / 3)
|
|
353
|
+
|
|
354
|
+
verts = [
|
|
355
|
+
(self.pairs_xpos[_stat][0], self.heights_offset[_stat] - stem_length),
|
|
356
|
+
(self.pairs_xpos[_stat][0], self.heights_offset[_stat]),
|
|
357
|
+
(self.pairs_xpos[_stat][1], self.heights_offset[_stat]),
|
|
358
|
+
(self.pairs_xpos[_stat][1], self.heights_offset[_stat] - stem_length),
|
|
359
|
+
]
|
|
360
|
+
codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO]
|
|
361
|
+
patch_path = Path(verts, codes)
|
|
362
|
+
patch = PathPatch(patch_path, linewidth=1, facecolor="none", edgecolor="k", clip_on=False)
|
|
363
|
+
rects.append(patch)
|
|
364
|
+
self.brackets_patchs = rects
|
|
365
|
+
return
|
|
366
|
+
|
|
367
|
+
def _add_stats(self):
|
|
368
|
+
"""Plot the stats.
|
|
369
|
+
|
|
370
|
+
:return: Self
|
|
371
|
+
"""
|
|
372
|
+
for _stat, rect in enumerate(self.brackets_patchs):
|
|
373
|
+
self.axis.add_patch(rect)
|
|
374
|
+
|
|
375
|
+
# Add text in the center of the box
|
|
376
|
+
txt_x = (self.pairs_xpos[_stat][0] + self.pairs_xpos[_stat][1]) / 2
|
|
377
|
+
txt_y = self.heights_offset[_stat]
|
|
378
|
+
self.axis.text(
|
|
379
|
+
txt_x, txt_y, f"{self.txt}" + self.pvals[_stat], ha="center", va="bottom", fontsize=self.txt_size
|
|
380
|
+
)
|
|
381
|
+
|
|
382
|
+
bottom_y = self.axis.get_ylim()[0]
|
|
383
|
+
top_y = max(self.heights_offset)
|
|
384
|
+
buffer = np.abs(top_y) * 0.1
|
|
385
|
+
self.axis.set_ylim(bottom_y, top_y + buffer)
|
|
386
|
+
return
|
|
387
|
+
|
|
388
|
+
def plot_stats(self):
|
|
389
|
+
"""Method to add the statistical annotation.
|
|
390
|
+
|
|
391
|
+
:return: None
|
|
392
|
+
"""
|
|
393
|
+
self._get_height()
|
|
394
|
+
self._get_pos_pairs()
|
|
395
|
+
self._get_offsets()
|
|
396
|
+
self._draw_brackets()
|
|
397
|
+
self._add_stats()
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
class TestData:
|
|
401
|
+
"""Class to perform test in AnnData or Pandas DataFrames.
|
|
402
|
+
|
|
403
|
+
Class to perform statistical test between two or multiple conditions in an AnnData or pandas DataFrame (long format).
|
|
404
|
+
Different statistical test can be used including: wilcoxon, t-test, kruskal, anova, logreg, t-test_overestim_var.
|
|
405
|
+
Additionnally, different correction methods can be used for multiple testing (bonferroni and benjamini-hochberg)
|
|
406
|
+
|
|
407
|
+
.. note::
|
|
408
|
+
t-test_overestim_var and logreg is only available for AnnData input and anova and kruskal is only available
|
|
409
|
+
for pandas dataframe
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
Parameters
|
|
413
|
+
----------
|
|
414
|
+
data
|
|
415
|
+
annotated data matrix or pandas dataframe.
|
|
416
|
+
feature
|
|
417
|
+
var_name or obs column in the AnnData or column in the pandas dataframe to test.
|
|
418
|
+
cond_key
|
|
419
|
+
obs column or column in the dataframe with condition information.
|
|
420
|
+
ctrl
|
|
421
|
+
control condition.
|
|
422
|
+
groups
|
|
423
|
+
list of conditions
|
|
424
|
+
test
|
|
425
|
+
method to use for testing significance ('wilcoxon', 't-test', 'kruskal', 'anova', 'logreg', 't-test_overestim_var').
|
|
426
|
+
test_correction
|
|
427
|
+
correction method for multiple testing to use ('benjamini-hochberg', 'bonferroni')
|
|
428
|
+
category_key
|
|
429
|
+
column with categorical metadata to split by (e.g., cell type annotation). The test will be done for each category across each condition.
|
|
430
|
+
category_order
|
|
431
|
+
order for the categories in category_key. If not specified will be inferred
|
|
432
|
+
|
|
433
|
+
See Also
|
|
434
|
+
--------
|
|
435
|
+
:func:`dotools_py.pl.StatsPlotter`: class to plot the p-values in barplots, boxplots or violinplots
|
|
436
|
+
|
|
437
|
+
"""
|
|
438
|
+
|
|
439
|
+
_pvals = []
|
|
440
|
+
_hue_labels = []
|
|
441
|
+
|
|
442
|
+
def __init__(
|
|
443
|
+
self,
|
|
444
|
+
data: pd.DataFrame | ad.AnnData,
|
|
445
|
+
feature: str,
|
|
446
|
+
cond_key: str,
|
|
447
|
+
ctrl: str,
|
|
448
|
+
groups: list,
|
|
449
|
+
category_key: str = None,
|
|
450
|
+
category_order: list = None,
|
|
451
|
+
test: Literal["wilcoxon", "t-test", "kruskal", "anova", "logreg", "t-test_overestim_var"] = None,
|
|
452
|
+
test_correction: Literal["benjamini-hochberg","bonferroni"] = None,
|
|
453
|
+
):
|
|
454
|
+
"""Initialise,
|
|
455
|
+
|
|
456
|
+
:param data: annotated data matrix or pandas dataframe.
|
|
457
|
+
:param feature: var_names or obs column in the AnnData or column in the DataFrame.
|
|
458
|
+
:param cond_key: column with condition information.
|
|
459
|
+
:param ctrl: name of the control condition.
|
|
460
|
+
:param groups: list of the alternative conditions to test against.
|
|
461
|
+
:param category_key: column with categorical metadata to split by (e.g., cell type annotation). The test will be done for each category across each condition.
|
|
462
|
+
:param test: method to use for testing. Available: ['wilcoxon', 't-test', 'kruskal', 'anova', 'logreg', 't-test_overestim_var'].
|
|
463
|
+
:param test_correction: correction method to use. Available: ['benjamini-hochberg', 'bonferroni'].
|
|
464
|
+
"""
|
|
465
|
+
assert isinstance(data, ad.AnnData) or isinstance(data, pd.DataFrame), (
|
|
466
|
+
"Provide a DataFrame in long format or AnnData"
|
|
467
|
+
)
|
|
468
|
+
self.data = data
|
|
469
|
+
feature = [feature] if isinstance(feature, str) else feature
|
|
470
|
+
assert len(feature) == 1, f"{len(feature)} features provided. Please provide only 1"
|
|
471
|
+
self.key = feature[0] # We only plot 1 feature
|
|
472
|
+
if isinstance(data, pd.DataFrame):
|
|
473
|
+
assert cond_key in list(data.columns), f"{cond_key} not in adata.obs or df.columns"
|
|
474
|
+
if isinstance(data, ad.AnnData):
|
|
475
|
+
assert cond_key in list(data.obs.columns), f"{cond_key} not in adata.obs or df.columns"
|
|
476
|
+
self.cond_key = cond_key
|
|
477
|
+
self.ctrl = ctrl
|
|
478
|
+
self.groups = [groups] if isinstance(groups, str) else groups
|
|
479
|
+
test = DEFAULT_TEST if test is None else test
|
|
480
|
+
assert test in ["wilcoxon", "t-test", "kruskal", "anova", "logreg", "t-test_overestim_var"], (
|
|
481
|
+
f'{test} not a valid test, use: "wilcoxon", "t-test", "kruskal", "anova", "logreg", "t-test_overestim_var"'
|
|
482
|
+
)
|
|
483
|
+
self.test = test # ['wilcoxon', 't-test', 'kruskal', 'anova', 'logreg', 't-test_overestim_var']
|
|
484
|
+
test_correction = DEFAULT_MULTIPLE_TEST_CORRECTION if test_correction is None else test_correction
|
|
485
|
+
assert test_correction in ["benjamini-hochberg", "bonferroni"], (
|
|
486
|
+
f'{test_correction} not a valid test correction method, use: "benjamini-hochberg", "bonferroni"'
|
|
487
|
+
)
|
|
488
|
+
self.test_corr = test_correction # ['benjamini-hochberg', 'bonferroni']
|
|
489
|
+
self.pvals = None
|
|
490
|
+
self.correction = test_correction if test_correction is not None else DEFAULT_MULTIPLE_TEST_CORRECTION
|
|
491
|
+
self.test = test if test is not None else DEFAULT_TEST
|
|
492
|
+
self.hue = category_key
|
|
493
|
+
|
|
494
|
+
if self.hue:
|
|
495
|
+
if category_order is None:
|
|
496
|
+
if isinstance(self.data, ad.AnnData):
|
|
497
|
+
sanitize_anndata(self.data)
|
|
498
|
+
self.hue_order = list(self.data.obs[self.hue].cat.categories)
|
|
499
|
+
elif isinstance(self.data, pd.DataFrame):
|
|
500
|
+
self.hue_order = list(self.data[self.hue].unique())
|
|
501
|
+
else:
|
|
502
|
+
self.hue_order = category_order
|
|
503
|
+
|
|
504
|
+
def _test_adata(self):
|
|
505
|
+
"""Run test on AnnData.
|
|
506
|
+
|
|
507
|
+
:return: Self
|
|
508
|
+
"""
|
|
509
|
+
import scanpy as sc
|
|
510
|
+
|
|
511
|
+
pvals = []
|
|
512
|
+
if self.key in self.data.var_names:
|
|
513
|
+
if self.hue:
|
|
514
|
+
# Note StatsPlotter and TestPlotter hue has reverse meaning
|
|
515
|
+
# Note: StatsPlotter --> hue key specify the groups tested (e.g., hue = condition, we test condition for each x_ticks)
|
|
516
|
+
# Note TestPlotter --> hue key specify the x_ticks and condition_key the groups tested
|
|
517
|
+
|
|
518
|
+
sdf = pd.DataFrame([])
|
|
519
|
+
for group in self.hue_order:
|
|
520
|
+
# Warning, we test for each hue
|
|
521
|
+
# but the adding to pvals is per condition
|
|
522
|
+
subset = self.data[self.data.obs[self.hue] == group]
|
|
523
|
+
try:
|
|
524
|
+
sc.tl.rank_genes_groups(
|
|
525
|
+
subset,
|
|
526
|
+
groupby=self.cond_key,
|
|
527
|
+
method=self.test,
|
|
528
|
+
tie_correct=True,
|
|
529
|
+
reference=self.ctrl,
|
|
530
|
+
groups=self.groups,
|
|
531
|
+
corr_method=self.test_corr
|
|
532
|
+
)
|
|
533
|
+
df = sc.get.rank_genes_groups_df(subset, group=None)
|
|
534
|
+
df = df[df["names"] == self.key]
|
|
535
|
+
df['hue'] = group
|
|
536
|
+
except ValueError:
|
|
537
|
+
g = self.groups.copy()
|
|
538
|
+
n = [self.key] * len(g)
|
|
539
|
+
scores = [0] * len(g)
|
|
540
|
+
lo2fcs = [0] * len(g)
|
|
541
|
+
p_values = [1] * len(g)
|
|
542
|
+
p_adjusted = [1] * len(g)
|
|
543
|
+
hue_col = [group]
|
|
544
|
+
if len(self.groups) > 1:
|
|
545
|
+
df = pd.DataFrame([n, scores, lo2fcs, p_values, p_adjusted, hue_col], index=['names', 'scores', 'logfoldchanges', 'pvals', 'pvals_adj', 'hue']).T
|
|
546
|
+
else:
|
|
547
|
+
df = pd.DataFrame([g, n, scores, lo2fcs, p_values, p_adjusted, hue_col], index=['group', 'names', 'scores', 'logfoldchanges', 'pvals', 'pvals_adj', 'hue']).T
|
|
548
|
+
sdf = pd.concat([sdf, df])
|
|
549
|
+
|
|
550
|
+
self.pvals_catgs_order = []
|
|
551
|
+
if len(self.groups) == 1:
|
|
552
|
+
# Append keeping the order
|
|
553
|
+
for catg in self.hue_order:
|
|
554
|
+
pvals.append(sdf[sdf['hue'] == catg]['pvals_adj'].tolist()[0])
|
|
555
|
+
self.pvals_catgs_order.append(catg)
|
|
556
|
+
else:
|
|
557
|
+
sdf['hue_group'] = sdf['hue'].astype(str) + "_" + sdf['group'].astype(str)
|
|
558
|
+
sdf.set_index("hue_group", inplace=True)
|
|
559
|
+
for catg in self.hue_order: # Keep the order for the categories
|
|
560
|
+
for group in self.groups: # Keep the order for the groups
|
|
561
|
+
pvals.append(sdf.loc[catg + "_" + group, "pvals_adj"])
|
|
562
|
+
self.pvals_catgs_order.append(group + "_" + catg)
|
|
563
|
+
else:
|
|
564
|
+
sc.tl.rank_genes_groups(
|
|
565
|
+
self.data,
|
|
566
|
+
groupby=self.cond_key,
|
|
567
|
+
method=self.test,
|
|
568
|
+
tie_correct=True,
|
|
569
|
+
reference=self.ctrl,
|
|
570
|
+
groups=self.groups,
|
|
571
|
+
corr_method=self.test_corr,
|
|
572
|
+
)
|
|
573
|
+
df = sc.get.rank_genes_groups_df(self.data, group=None)
|
|
574
|
+
df = df[df["names"] == self.key]
|
|
575
|
+
|
|
576
|
+
if len(self.groups) == 1:
|
|
577
|
+
pvals += df["pvals_adj"].tolist()
|
|
578
|
+
else:
|
|
579
|
+
df.set_index("group", inplace=True)
|
|
580
|
+
for group in self.groups:
|
|
581
|
+
pvals.append(df.loc[group, "pvals_adj"])
|
|
582
|
+
|
|
583
|
+
elif self.key in self.data.obs.columns:
|
|
584
|
+
if self.hue:
|
|
585
|
+
df_tmp = self.data.obs[[self.cond_key, self.hue, self.key]]
|
|
586
|
+
self.pvals_catgs_order = []
|
|
587
|
+
for catg in self.hue_order:
|
|
588
|
+
sdf = df_tmp[df_tmp[self.hue] == catg]
|
|
589
|
+
for group in self.groups:
|
|
590
|
+
_, p = mannwhitneyu(
|
|
591
|
+
sdf[sdf[self.cond_key] == self.ctrl][self.key],
|
|
592
|
+
sdf[sdf[self.cond_key] == group][self.key],
|
|
593
|
+
use_continuity=True,
|
|
594
|
+
nan_policy="omit",
|
|
595
|
+
)
|
|
596
|
+
pvals.append(p)
|
|
597
|
+
self.pvals_catgs_order.append(group + '_' + catg)
|
|
598
|
+
else:
|
|
599
|
+
df_tmp = self.data.obs[[self.cond_key, self.key]]
|
|
600
|
+
for group in self.groups:
|
|
601
|
+
_, p = mannwhitneyu(
|
|
602
|
+
df_tmp[df_tmp[self.cond_key] == self.ctrl][self.key],
|
|
603
|
+
df_tmp[df_tmp[self.cond_key] == group][self.key],
|
|
604
|
+
use_continuity=True,
|
|
605
|
+
nan_policy="omit",
|
|
606
|
+
)
|
|
607
|
+
pvals.append(p)
|
|
608
|
+
else:
|
|
609
|
+
raise Exception(f"{self.key} is not in adata.obs or adata.var_names")
|
|
610
|
+
self.pvals = pvals
|
|
611
|
+
return None
|
|
612
|
+
|
|
613
|
+
def _test_df(self):
|
|
614
|
+
"""Run test on DataFrame.
|
|
615
|
+
|
|
616
|
+
:return:
|
|
617
|
+
"""
|
|
618
|
+
pvals = []
|
|
619
|
+
if self.hue:
|
|
620
|
+
self.pvals_catgs_order = []
|
|
621
|
+
for catg in self.hue_order:
|
|
622
|
+
subset = self.data[self.data[self.hue] == catg] # Subset for each hue category
|
|
623
|
+
|
|
624
|
+
if self.test in ["t-test", "anova"]:
|
|
625
|
+
# Test for normality
|
|
626
|
+
for group in self.groups + [self.ctrl]:
|
|
627
|
+
_, p = shapiro(subset[subset[self.cond_key] == group][self.key])
|
|
628
|
+
if p > 0.05:
|
|
629
|
+
new_test = "wilcoxon" if self.test == "t-test" else "anova"
|
|
630
|
+
logger.warn(f"Data does not follow normality but {self.test} was set, changing to {new_test}")
|
|
631
|
+
self.test = new_test
|
|
632
|
+
break
|
|
633
|
+
|
|
634
|
+
if len(self.groups) != 1 and self.test in ["t-test", "wilcoxon"]:
|
|
635
|
+
# For multiple conditions we use anova or kruskal
|
|
636
|
+
logger.warn(f"Running {self.test} but testing {len(self.groups)} conditions")
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
for group in self.groups:
|
|
640
|
+
x = subset[subset[self.cond_key] == self.ctrl][self.key]
|
|
641
|
+
y = subset[subset[self.cond_key] == group][self.key]
|
|
642
|
+
if self.test == "t-test":
|
|
643
|
+
_, p = ttest_ind(x, y)
|
|
644
|
+
elif self.test == "anova":
|
|
645
|
+
_, p = f_oneway(x, y)
|
|
646
|
+
elif self.test == "wilcoxon":
|
|
647
|
+
_, p = mannwhitneyu(x, y, use_continuity=True)
|
|
648
|
+
elif self.test == "kruskal":
|
|
649
|
+
_, p = kruskal(x, y)
|
|
650
|
+
else:
|
|
651
|
+
raise Exception(f"{self.test} not implemented")
|
|
652
|
+
pvals.append(p)
|
|
653
|
+
self.pvals_catgs_order.append(group + "_" + catg)
|
|
654
|
+
else:
|
|
655
|
+
if self.test in ["t-test", "anova"]:
|
|
656
|
+
# Test for normality
|
|
657
|
+
for group in self.groups + [self.ctrl]:
|
|
658
|
+
_, p = shapiro(self.data[self.data[self.cond_key] == group][self.key])
|
|
659
|
+
if p > 0.05:
|
|
660
|
+
new_test = "wilcoxon" if self.test == "t-test" else "anova"
|
|
661
|
+
logger.warn(f"Data does not follow normality but {self.test} was set, changing to {new_test}")
|
|
662
|
+
self.test = new_test
|
|
663
|
+
break
|
|
664
|
+
|
|
665
|
+
if len(self.groups) != 1 and self.test in ["t-test", "wilcoxon"]:
|
|
666
|
+
logger.warn(f"Running {self.test} but testing {len(self.groups)} conditions")
|
|
667
|
+
|
|
668
|
+
for group in self.groups:
|
|
669
|
+
x = self.data[self.data[self.cond_key] == self.ctrl][self.key]
|
|
670
|
+
y = self.data[self.data[self.cond_key] == group][self.key]
|
|
671
|
+
if self.test == "t-test":
|
|
672
|
+
_, p = ttest_ind(x, y)
|
|
673
|
+
elif self.test == "anova":
|
|
674
|
+
_, p = f_oneway(x, y)
|
|
675
|
+
elif self.test == "wilcoxon":
|
|
676
|
+
_, p = mannwhitneyu(x, y, use_continuity=True)
|
|
677
|
+
elif self.test == "kruskal":
|
|
678
|
+
_, p = kruskal(x, y)
|
|
679
|
+
else:
|
|
680
|
+
raise Exception(f"{self.test} not implemented")
|
|
681
|
+
pvals.append(p)
|
|
682
|
+
|
|
683
|
+
self.pvals = pvals
|
|
684
|
+
return None
|
|
685
|
+
|
|
686
|
+
def run_test(self):
|
|
687
|
+
"""Method to run test.
|
|
688
|
+
|
|
689
|
+
:return: None
|
|
690
|
+
"""
|
|
691
|
+
if isinstance(self.data, ad.AnnData):
|
|
692
|
+
self._test_adata()
|
|
693
|
+
elif isinstance(self.data, pd.DataFrame):
|
|
694
|
+
self._test_df()
|
|
695
|
+
else:
|
|
696
|
+
raise Exception("Input can only be an AnnData or DataFrame")
|
|
697
|
+
TestData._pvals = self.pvals
|
|
698
|
+
if self.hue:
|
|
699
|
+
TestData._hue_labels = self.pvals_catgs_order
|
|
700
|
+
|
|
701
|
+
@classmethod
|
|
702
|
+
def pvalues(cls):
|
|
703
|
+
"""Get list with the p-vals from the test. If category_key is not set the order of the pvals match the order of the
|
|
704
|
+
labels in groups.
|
|
705
|
+
:return:
|
|
706
|
+
"""
|
|
707
|
+
return TestData._pvals
|
|
708
|
+
|
|
709
|
+
@classmethod
|
|
710
|
+
def pvalues_labels(cls):
|
|
711
|
+
"""Get list with the labels of the group tested. The order matches the order of the `pvals` attribute. Only initialise
|
|
712
|
+
if the hue category_key is set.
|
|
713
|
+
:return:
|
|
714
|
+
"""
|
|
715
|
+
return TestData._hue_labels
|
|
716
|
+
|