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.
Files changed (57) hide show
  1. dotools_py/__init__.py +33 -0
  2. dotools_py/_experimental/__init__.py +0 -0
  3. dotools_py/_experimental/_deprecated/__init__.py +0 -0
  4. dotools_py/_experimental/_deprecated/_expression.py +761 -0
  5. dotools_py/_experimental/_deprecated/_language.py +398 -0
  6. dotools_py/_experimental/_deprecated/_statistics.py +403 -0
  7. dotools_py/_experimental/gr/__init__.py +0 -0
  8. dotools_py/_experimental/gr/_generic.py +382 -0
  9. dotools_py/dt/__init__.py +2 -0
  10. dotools_py/dt/_datasets.py +112 -0
  11. dotools_py/dt/_markers.py +150 -0
  12. dotools_py/dt/example_reduced.h5ad +0 -0
  13. dotools_py/get/__init__.py +7 -0
  14. dotools_py/get/_generic.py +626 -0
  15. dotools_py/logger.py +87 -0
  16. dotools_py/pl/_Classes.py +358 -0
  17. dotools_py/pl/_Plotter.py +567 -0
  18. dotools_py/pl/_StatsPlotter.py +716 -0
  19. dotools_py/pl/__init__.py +8 -0
  20. dotools_py/pl/_dotplot.py +2062 -0
  21. dotools_py/pl/_downstream.py +868 -0
  22. dotools_py/pl/_embeddings.py +481 -0
  23. dotools_py/pl/_experimental.py +205 -0
  24. dotools_py/pl/_expression.py +581 -0
  25. dotools_py/pl/_heatmap.py +475 -0
  26. dotools_py/pl/_plot_utils.py +103 -0
  27. dotools_py/pl/_visium.py +194 -0
  28. dotools_py/pp/__init__.py +2 -0
  29. dotools_py/pp/_cellbender.py +179 -0
  30. dotools_py/pp/_importer.py +583 -0
  31. dotools_py/settings/__init__.py +1 -0
  32. dotools_py/settings/_configure.py +185 -0
  33. dotools_py/settings/_global_parameters.py +16 -0
  34. dotools_py/tl/_Statistical.py +812 -0
  35. dotools_py/tl/__init__.py +10 -0
  36. dotools_py/tl/_analysis.py +772 -0
  37. dotools_py/tl/_get_stats.py +776 -0
  38. dotools_py/tl/_rankGenes.py +1112 -0
  39. dotools_py/util_scripts/_ReadWrite_RDS.R +285 -0
  40. dotools_py/util_scripts/_run_CCA.R +91 -0
  41. dotools_py/util_scripts/_run_CellBender.sh +186 -0
  42. dotools_py/util_scripts/_run_MAST.R +118 -0
  43. dotools_py/util_scripts/_run_SCTransform.R +60 -0
  44. dotools_py/util_scripts/_run_edgeR.R +104 -0
  45. dotools_py/util_scripts/_run_scDblFinder.R +63 -0
  46. dotools_py/utility/HomoSapiens_GeneMetadata.pickle.gz +0 -0
  47. dotools_py/utility/MusMusculus_GeneMetadata.pickle.gz +0 -0
  48. dotools_py/utility/__init__.py +4 -0
  49. dotools_py/utility/_convertion.py +262 -0
  50. dotools_py/utility/_general.py +136 -0
  51. dotools_py/utility/_plotting.py +101 -0
  52. dotools_py/utility/_spatial.py +64 -0
  53. dotools_py/utils.py +404 -0
  54. dotools_py-0.0.2.dist-info/METADATA +225 -0
  55. dotools_py-0.0.2.dist-info/RECORD +57 -0
  56. dotools_py-0.0.2.dist-info/WHEEL +4 -0
  57. dotools_py-0.0.2.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,761 @@
1
+ from typing import Literal
2
+ from pathlib import Path
3
+ import anndata as ad
4
+ import matplotlib.pyplot as plt
5
+ import numpy as np
6
+ import seaborn as sns
7
+ import matplotlib.lines as mlines
8
+
9
+ import dotools_py.utility
10
+ from dotools_py import logger
11
+ from dotools_py.pl._StatsPlotter import StatsPlotter, TestData
12
+ from dotools_py.get import mean_expr
13
+ from dotools_py.get._generic import expr as get_expr
14
+
15
+ from dotools_py.utils import convert_path, sanitize_anndata, make_grid_spec
16
+
17
+
18
+ def barplot(
19
+ adata: ad.AnnData,
20
+ x_axis: str,
21
+ feature: str,
22
+ batch_key: str = "batch",
23
+ order: list = None,
24
+ hue: str = None,
25
+ hue_order: list = None,
26
+ layer: str = None,
27
+ figsize: tuple = (3, 4.2),
28
+ palette: str | list | dict = "tab10",
29
+ capsize: float = 0.1,
30
+ xtick_rotation: int = None,
31
+ ctrl_cond: str = None,
32
+ groups_cond: str | list = None,
33
+ groups_pvals: list = None,
34
+ title: str = None,
35
+ path: str | Path = None,
36
+ filename: str = None,
37
+ title_fontproperties: dict = None,
38
+ hue_legend_fontsize: int = 12,
39
+ hue_legend_fontweight: float | str = None,
40
+ hue_legend_cols: int = 1,
41
+ hue_legend_title: str = '',
42
+ hue_legend_loc: Literal["center left", "cemter right", "upper right", "upper left", "lower left", "lower right", "right", "lower center", "upper center", "center"] = 'center left',
43
+ show: bool = True,
44
+ marker_size: int = 6,
45
+ ax: plt.Axes = None,
46
+ logcounts: bool = True,
47
+ estimator: str | None = "LogMean",
48
+ test: Literal["wilcoxon", "t-test", "kruskal", "anova", "logreg", "t-test_overestim_var"] = "wilcoxon",
49
+ corr_method: Literal["benjamini-hochberg", "bonferroni"] = "benjamini-hochberg",
50
+ txt_size: int = 13,
51
+ txt: str = "p = ",
52
+ ylabel: str = "LogMean(nUMI)",
53
+ line_offset: float = 0.05,
54
+ ylim_max: float = None,
55
+ **kwargs,
56
+ ):
57
+ """Barplot with stats.
58
+
59
+ Show the average expression of `var_names` or a continuous value in `obs` along different categorical values
60
+ and test for significance. The mean pseudo-bulk expression per sample will be plotted as dots.
61
+
62
+ :param adata: annotated data matrix
63
+ :param x_axis: categorical `obs` column to group-by.
64
+ :param feature: feature in `var_name` or `obs`.
65
+ :param batch_key: `obs` column with batch information.
66
+ :param order: order for the x_axis categories.
67
+ :param hue: categorical `obs` column to split by each group in x_axis.
68
+ :param hue_order: order for the hue categories.
69
+ :param layer: layer in the AnnData to use.
70
+ :param figsize: figure size.
71
+ :param palette: dictionary or palette to use.
72
+ :param capsize: width of the 'caps' on error bars, relative to bar spacing.
73
+ :param xtick_rotation: rotation of the x-ticks.
74
+ :param ctrl_cond: name of the ctrl condition in the x-ticks. When hue is set, the control correspond to the categories in hue.
75
+ for each x_axis category the different hue categories will be tested.
76
+ :param groups_cond: list of the name of the groups to test in the x-ticks.
77
+ :param groups_pvals: if provided, these values will be plotted. If not set, provide a list of the groups in the x-ticks
78
+ to test.
79
+ :param title: title of the plot.
80
+ :param path: path to save the figure.
81
+ :param filename: name of the file.
82
+ :param title_fontproperties: properties of the title text.
83
+ :param hue_legend_fontsize: size of the legend text when hue is set.
84
+ :param hue_legend_fontweight: fontweight of the legend text when hue is set.
85
+ :param hue_legend_cols: number of columns for the legend when hue is set.
86
+ :param hue_legend_loc: location of the legend when hue is set.
87
+ :param hue_legend_title: title of the legend when hue is set.
88
+ :param show: if set to False, return the axis.
89
+ :param marker_size: size of the markers showing the pseudo-bulk mean expression.
90
+ :param ax: matplotlib axis.
91
+ :param logcounts: if set to True, assume input is log1p transformed
92
+ :param estimator: estimator to calculate the mean expression. If set to LogMean assume log1p.
93
+ :param test: name of the method to test for significance.
94
+ :param corr_method: correction method for multiple testing.
95
+ :param txt_size: size of the text indicating significance.
96
+ :param txt: text for indicating significance. If not set, only the p-value is shown.
97
+ :param ylabel: Y-axis label.
98
+ :param line_offset: line offset for the stat
99
+ :param ylim_max: set maximum Y limit.
100
+ :param kwargs: additional arguments passed to `sns.barplot() <https://seaborn.pydata.org/generated/seaborn.barplot.html>`_
101
+ :return: Depending on ``show``, returns the plot if set to `True` or a dictionary with the axes.
102
+
103
+ Example
104
+ -------
105
+
106
+ .. plot::
107
+ :context: close-figs
108
+
109
+ import dotools_py as do
110
+ adata = do.dt.example_10x_processed()
111
+ do.pl.barplot(adata, 'annotation', 'CD4', ctrl_cond = 'T_cells', groups_cond=['B_cells'], xtick_rotation=45)
112
+ # Take only lymphoid cells
113
+ lymphoid = adata[adata.obs['annotation'].isin(['T_cells', 'NK', 'B_cells'])].copy()
114
+ # When hue is set we test for each annotation healthy Vs disease
115
+ do.pl.barplot(lymphoid, 'annotation', 'CD4', hue = 'condition', ctrl_cond = 'healthy', groups_cond=['disease'], hue_order=['healthy', 'disease'], xtick_rotation=45, figsize=(6, 4))
116
+
117
+
118
+ """
119
+ # Checks
120
+ sanitize_anndata(adata)
121
+ groups_cond = [groups_cond] if isinstance(groups_cond, str) else groups_cond
122
+ groups_pvals = [groups_pvals] if isinstance(groups_pvals, float) else groups_pvals
123
+ feature = [feature] if isinstance(feature, str) else feature
124
+ assert len(feature) == 1, "Only 1 feature can be plotted"
125
+ feature = feature[0]
126
+
127
+ def log_estimator(values):
128
+ return np.log1p(np.mean(np.expm1(values)))
129
+
130
+ groups_to_save = [x_axis, hue] if hue is not None else [x_axis]
131
+ groups_to_save_batch = [x_axis, batch_key, hue] if hue is not None else [x_axis, batch_key]
132
+
133
+ if feature in adata.var_names:
134
+ df = get_expr(adata, feature, groups=groups_to_save, layer=layer)
135
+ df_batch = mean_expr(adata, group_by=groups_to_save_batch, features=feature, layer=layer)
136
+ df_batch.columns = ["gene"] + groups_to_save_batch + ["expr"]
137
+ elif feature in list(adata.obs.columns):
138
+ df = adata.obs[groups_to_save + [feature]]
139
+ df.columns = groups_to_save + ["expr"]
140
+ df_batch = adata.obs[[feature] + groups_to_save_batch]
141
+ df_batch = df_batch.groupby(groups_to_save_batch).agg(np.mean).fillna(0).reset_index()
142
+ df_batch["gene"] = feature
143
+ df_batch.columns = groups_to_save_batch + ["expr", "gene"]
144
+ if logcounts:
145
+ logger.warn(f"Assumming Log-counts but {feature} is in adata.obs")
146
+ else:
147
+ raise ValueError(f"{feature} is not in adata.var_names or adata.obs")
148
+
149
+ if hue is not None:
150
+ hue_order = list(adata.obs[hue].unique()) if hue_order is None else hue_order
151
+ order = list(adata.obs[x_axis].unique()) if order is None else order
152
+
153
+ # Create figure
154
+ if ax is None:
155
+ if hue is not None:
156
+ width, height = figsize # Define figure layout
157
+ fig, gs = make_grid_spec(
158
+ ax or (width, height), nrows=1, ncols=2, wspace=0.7 / width, width_ratios=[width - (0.9 + 0) + 0, 0.9]
159
+ )
160
+ ax = fig.add_subplot(gs[0])
161
+
162
+ else:
163
+ fig, ax = plt.subplots(1, 1, figsize=figsize)
164
+
165
+ if estimator == "LogMean":
166
+ bp = sns.barplot(
167
+ df, x=x_axis, y="expr", estimator=log_estimator, capsize=capsize, ax=ax, palette=palette,
168
+ hue=hue, hue_order=hue_order, order=order, legend=False, **kwargs)
169
+ else:
170
+ bp = sns.barplot(df, x=x_axis, y="expr", estimator=estimator, capsize=capsize, ax=ax, palette=palette,
171
+ hue=hue, order=order, hue_order=hue_order, legend=False, **kwargs)
172
+
173
+ dodge =True if hue else False
174
+ sns.stripplot(df_batch, x=x_axis, y="expr", alpha=0.75, color="k", s=marker_size, ax=bp, hue=hue,
175
+ hue_order=hue_order, order=order, dodge=dodge, legend=False)
176
+
177
+ if ctrl_cond is not None and groups_cond is not None:
178
+ if groups_pvals is None:
179
+ if hue is not None:
180
+ testing = TestData(data=adata,
181
+ feature=feature,
182
+ cond_key=hue,
183
+ ctrl=ctrl_cond,
184
+ groups=groups_cond,
185
+ category_key=x_axis,
186
+ category_order=order,
187
+ test=test,
188
+ test_correction=corr_method)
189
+ else:
190
+ testing = TestData(data=adata,
191
+ feature=feature,
192
+ cond_key=x_axis,
193
+ ctrl=ctrl_cond,
194
+ groups=groups_cond,
195
+ category_key=None,
196
+ category_order=None,
197
+ test=test,
198
+ test_correction=corr_method)
199
+ testing.run_test()
200
+ groups_pvals = testing.pvals # Should be the same order as for StatsPlotter
201
+
202
+ plotter = StatsPlotter(
203
+ bp,
204
+ x_axis=x_axis,
205
+ y_axis="expr",
206
+ ctrl=ctrl_cond,
207
+ groups=groups_cond,
208
+ pvals=groups_pvals,
209
+ txt_size=txt_size,
210
+ txt=txt,
211
+ kind="bar",
212
+ line_offset=line_offset,
213
+ hue=hue,
214
+ hue_order=hue_order,
215
+ )
216
+ plotter.plot_stats()
217
+
218
+ if xtick_rotation is not None:
219
+ bp.set_xticklabels(bp.get_xticklabels(), rotation=xtick_rotation, ha="right", va="top", fontweight="bold")
220
+ else:
221
+ bp.set_xticklabels(bp.get_xticklabels(), fontweight="bold")
222
+
223
+ bp.set_xlabel("")
224
+ bp.set_ylabel(ylabel, fontweight='bold')
225
+
226
+ # Correct YLim in case it was cut
227
+ if len(adata.obs[batch_key]) == 2: # There are only 1 batch per condition
228
+ pass
229
+ else:
230
+ ymax = df_batch["expr"].max() + df_batch["expr"].max() * 0.1
231
+ ymax = ylim_max if ylim_max is None else ymax
232
+ bp.set_ylim(0, ymax)
233
+
234
+ title_fontproperties = {} if title_fontproperties is None else title_fontproperties
235
+ title_size = title_fontproperties.get("size", 20)
236
+ title_font = title_fontproperties.get("weight", "bold")
237
+
238
+ # If hue is define we need a legend
239
+ if hue is not None:
240
+ axs_legend = fig.add_subplot(gs[1])
241
+ handles = []
242
+
243
+ if isinstance(palette, str):
244
+ colors = dotools_py.utility.get_hex_colormaps(palette)
245
+ colors_dict = dict(zip(hue_order, colors, strict=False))
246
+ elif isinstance(palette, dict):
247
+ colors_dict = palette
248
+ else:
249
+ raise Exception('palette can only be a string or dictionary')
250
+
251
+ handles = []
252
+ for lab, c in colors_dict.items():
253
+ handles.append(
254
+ mlines.Line2D(
255
+ [0], [0], marker=".", color=c, lw=0, label=lab, markerfacecolor=c, markeredgecolor=None,
256
+ markersize=18
257
+ )
258
+ )
259
+
260
+ legend = axs_legend.legend(
261
+ handles=handles,
262
+ frameon=False,
263
+ loc=hue_legend_loc,
264
+ ncols=hue_legend_cols,
265
+ title=hue_legend_title,
266
+ prop={"size": hue_legend_fontsize, "weight": hue_legend_fontweight},
267
+ )
268
+ legend.get_title().set_fontweight("bold")
269
+ legend.get_title().set_fontsize(hue_legend_fontsize + 2)
270
+ axs_legend.tick_params(axis="both", left=False, labelleft=False, labelright=False, bottom=False,
271
+ labelbottom=False)
272
+ axs_legend.spines[["right", "left", "top", "bottom"]].set_visible(False)
273
+ axs_legend.grid(visible=False)
274
+
275
+
276
+ if title is None:
277
+ bp.set_title(feature, fontsize=title_size, fontweight=title_font) # Title is the genename
278
+ else:
279
+ bp.set_title(title, fontsize=title_size, fontweight=title_font)
280
+ if path is not None: # If the path is provided we save it
281
+ plt.savefig(convert_path(path) / filename, bbox_inches="tight")
282
+ if show is False: # if show is false we return the axes
283
+ if hue is not None:
284
+ bp = {'mainplot_ax': bp,
285
+ 'legend_ax': axs_legend}
286
+ return bp
287
+ else:
288
+ plt.tight_layout()
289
+ return plt.show()
290
+
291
+
292
+ def boxplot(
293
+ adata: ad.AnnData,
294
+ x_axis: str,
295
+ feature: str,
296
+ order: list = None,
297
+ hue: str = None,
298
+ hue_order: list = None,
299
+ layer: str = None,
300
+ figsize: tuple = (3, 4.2),
301
+ palette: str | list = "tab10",
302
+ xtick_rotation: int = None,
303
+ ctrl_cond: str = None,
304
+ groups_cond: str | list = None,
305
+ groups_pvals: list = None,
306
+ title: str = None,
307
+ path: str = None,
308
+ filename: str = None,
309
+ title_fontproperties: dict = None,
310
+ hue_legend_fontsize: int = 12,
311
+ hue_legend_fontweight: float | str = None,
312
+ hue_legend_cols: int = 1,
313
+ hue_legend_title: str = '',
314
+ hue_legend_loc: Literal["center left", "cemter right", "upper right", "upper left", "lower left", "lower right", "right", "lower center", "upper center", "center"] = 'center left',
315
+ show: bool = True,
316
+ ax: plt.Axes = None,
317
+ showfliers: bool = False,
318
+ test: Literal["wilcoxon", "t-test", "kruskal", "anova", "logreg", "t-test_overestim_var"] = "wilcoxon",
319
+ corr_method: Literal["benjamini-hochberg", "bonferroni"] = "benjamini-hochberg",
320
+ txt_size: int = 13,
321
+ txt: str = "p = ",
322
+ ylabel="LogMean(nUMI)",
323
+ line_offset: float = 0.05,
324
+ **kwargs,
325
+ ):
326
+ """Boxplot with stats.
327
+
328
+ Show the distribution of the expression of `var_names` or a continuous value in `obs` along different categorical values
329
+ and test for significance.
330
+
331
+ :param adata: annotated data matrix
332
+ :param x_axis: categorical `obs` column to groupby.
333
+ :param feature: feature in `var_name` or `obs`.
334
+ :param order: order for the x_axis categories.
335
+ :param hue: categorical `obs` column to split by each group in x_axis.
336
+ :param hue_order: order for the hue categories.
337
+ :param layer: layer in the AnnData to use.
338
+ :param figsize: figure size.
339
+ :param palette: dictionary or palette to use.
340
+ :param xtick_rotation: rotation of the xticks.
341
+ :param ctrl_cond: name of the ctrl condition in the xticks. When hue is set, the control correspond to the categories in hue.
342
+ for each x_axis category the different hue categories will be tested.
343
+ :param groups_cond: list of the name of the groups to test in the xticks.
344
+ :param groups_pvals: if provided, these values will be plotted. If not set, provide a list of the groups in the xticks
345
+ to test.
346
+ :param title: title of the plot.
347
+ :param path: path to save the figure.
348
+ :param filename: name of the file.
349
+ :param title_fontproperties: properties of the title text.
350
+ :param hue_legend_fontsize: size of the legend text when hue is set.
351
+ :param hue_legend_fontweight: fontweight of the legend text when hue is set.
352
+ :param hue_legend_cols: number of columns for the legend when hue is set.
353
+ :param hue_legend_loc: location of the legend when hue is set.
354
+ :param hue_legend_title: title of the legend when hue is set.
355
+ :param show: if set to False, return the axis.
356
+ :param ax: matplotlib axis.
357
+ :param showfliers: if set to False, the outliers of the boxplot are not shown.
358
+ :param test: name of the method to test for significance. Available: ['wilcoxon', 't-test', 'kruskal', 'anova', 'logreg', 't-test_overestim_var'].
359
+ :param corr_method: correction method for multiple testing. Available: ['benjamini-hochberg', 'bonferroni'].
360
+ :param txt_size: size of the text indicating significance.
361
+ :param txt: text for indicating significance. If not set, only the p-value is shown.
362
+ :param ylabel: Y-axis label.
363
+ :param line_offset: offset from the stats.
364
+ :param kwargs: additional arguments passed to `sns.boxplot() <https://seaborn.pydata.org/generated/seaborn.boxplot.html>`_
365
+ :return: Depending on ``show``, returns the plot if set to `True` or a dictionary with the axes.
366
+
367
+ Example
368
+ -------
369
+
370
+ .. plot::
371
+ :context: close-figs
372
+
373
+ import dotools_py as do
374
+ adata = do.dt.example_10x_processed()
375
+ do.pl.boxplot(adata, 'annotation', 'CD4', ctrl_cond = 'pDC', groups_cond=['B_cells'], xtick_rotation=45)
376
+ # Take only lymphoid cells
377
+ lymphoid = adata[adata.obs['annotation'].isin(['T_cells', 'NK', 'B_cells'])].copy()
378
+ # When hue is set we test for each annotation healthy Vs disease
379
+ do.pl.boxplot(lymphoid, 'annotation', 'RPL11', hue = 'condition', ctrl_cond = 'healthy', groups_cond=['disease'], hue_order=['healthy', 'disease'], xtick_rotation=45, figsize=(6, 4))
380
+
381
+
382
+ """
383
+ # Checks
384
+ sanitize_anndata(adata)
385
+ groups_cond = [groups_cond] if isinstance(groups_cond, str) else groups_cond
386
+ groups_pvals = [groups_pvals] if isinstance(groups_pvals, float) else groups_pvals
387
+ feature = [feature] if isinstance(feature, str) else feature
388
+ assert len(feature) == 1, "Only 1 feature can be plotted"
389
+ feature = feature[0]
390
+
391
+ groups_to_save = [x_axis, hue] if hue is not None else [x_axis]
392
+ if feature in adata.var_names:
393
+ df = get_expr(adata, feature, groups=groups_to_save, layer=layer)
394
+ elif feature in list(adata.obs.columns):
395
+ df = adata.obs[groups_to_save + [feature]]
396
+ df.columns = groups_to_save + ["expr"]
397
+ else:
398
+ raise ValueError(f"{feature} is not in adata.var_names or adata.obs")
399
+
400
+ if hue is not None:
401
+ hue_order = list(adata.obs[hue].unique()) if hue_order is None else hue_order
402
+ order = list(adata.obs[x_axis].unique()) if order is None else order
403
+
404
+ # Create figure
405
+ if ax is None:
406
+ if hue is not None:
407
+ width, height = figsize # Define figure layout
408
+ fig, gs = make_grid_spec(
409
+ ax or (width, height), nrows=1, ncols=2, wspace=0.7 / width, width_ratios=[width - (0.9 + 0) + 0, 0.9]
410
+ )
411
+ ax = fig.add_subplot(gs[0])
412
+
413
+ else:
414
+ fig, ax = plt.subplots(1, 1, figsize=figsize)
415
+
416
+ bx = sns.boxplot(df, x=x_axis, y="expr", showfliers=showfliers, ax=ax, palette=palette,
417
+ order=order, hue=hue, hue_order=hue_order, legend=False, **kwargs)
418
+
419
+ if ctrl_cond is not None and groups_cond is not None:
420
+ if groups_pvals is None:
421
+ if hue is not None:
422
+ testing = TestData(data=adata,
423
+ feature=feature,
424
+ cond_key=hue,
425
+ ctrl=ctrl_cond,
426
+ groups=groups_cond,
427
+ category_key=x_axis,
428
+ category_order=order,
429
+ test=test,
430
+ test_correction=corr_method)
431
+ else:
432
+ testing = TestData(
433
+ adata,
434
+ feature=feature,
435
+ cond_key=x_axis,
436
+ ctrl=ctrl_cond,
437
+ groups=groups_cond,
438
+ category_order=None,
439
+ category_key=None,
440
+ test=test,
441
+ test_correction=corr_method,
442
+ )
443
+ testing.run_test()
444
+ groups_pvals = testing.pvals
445
+
446
+ plotter = StatsPlotter(
447
+ bx,
448
+ x_axis=x_axis,
449
+ y_axis="expr",
450
+ ctrl=ctrl_cond,
451
+ groups=groups_cond,
452
+ pvals=groups_pvals,
453
+ txt_size=txt_size,
454
+ txt=txt,
455
+ kind="box",
456
+ line_offset=line_offset,
457
+ hue=hue,
458
+ hue_order=hue_order
459
+ )
460
+ plotter.plot_stats()
461
+
462
+ if xtick_rotation is not None:
463
+ bx.set_xticklabels(bx.get_xticklabels(), rotation=xtick_rotation, ha="right", va="top", fontweight="bold")
464
+ else:
465
+ bx.set_xticklabels(bx.get_xticklabels(), fontweight="bold")
466
+ bx.set_xlabel("")
467
+ bx.set_ylabel(ylabel, fontweight="bold")
468
+
469
+ title_fontproperties = {} if title_fontproperties is None else title_fontproperties
470
+ title_size = title_fontproperties.get("size", 20)
471
+ title_font = title_fontproperties.get("weight", "bold")
472
+
473
+ if hue is not None:
474
+ axs_legend = fig.add_subplot(gs[1])
475
+
476
+ if isinstance(palette, str):
477
+ colors = dotools_py.utility.get_hex_colormaps(palette)
478
+ colors_dict = dict(zip(hue_order, colors, strict=False))
479
+ elif isinstance(palette, dict):
480
+ colors_dict = palette
481
+ else:
482
+ raise Exception('palette can only be a string or dictionary')
483
+
484
+ handles = []
485
+ for lab, c in colors_dict.items():
486
+ handles.append(
487
+ mlines.Line2D(
488
+ [0], [0], marker=".", color=c, lw=0, label=lab, markerfacecolor=c, markeredgecolor=None,
489
+ markersize=18
490
+ )
491
+ )
492
+
493
+ legend = axs_legend.legend(
494
+ handles=handles,
495
+ frameon=False,
496
+ loc=hue_legend_loc,
497
+ ncols=hue_legend_cols,
498
+ title=hue_legend_title,
499
+ prop={"size": hue_legend_fontsize, "weight": hue_legend_fontweight},
500
+ )
501
+ legend.get_title().set_fontweight("bold")
502
+ legend.get_title().set_fontsize(hue_legend_fontsize + 2)
503
+ axs_legend.tick_params(axis="both", left=False, labelleft=False, labelright=False, bottom=False,
504
+ labelbottom=False)
505
+ axs_legend.spines[["right", "left", "top", "bottom"]].set_visible(False)
506
+ axs_legend.grid(visible=False)
507
+
508
+ if title is None:
509
+ bx.set_title(feature, fontsize=title_size, fontweight=title_font) # Title is the genename
510
+ else:
511
+ bx.set_title(title, fontsize=title_size, fontweight=title_font)
512
+ if path is not None: # If the path is provided we save it
513
+ plt.savefig(convert_path(path) / filename, bbox_inches="tight")
514
+ if show is False: # if show is false we return the axes
515
+ if hue is not None:
516
+ bx = {'mainplot_ax': bx,
517
+ 'legend_ax': axs_legend}
518
+ return bx
519
+ else:
520
+ plt.tight_layout()
521
+ return plt.show()
522
+
523
+
524
+ def violin(
525
+ adata: ad.AnnData,
526
+ x_axis: str,
527
+ feature: str,
528
+ order: list = None,
529
+ hue: str = None,
530
+ hue_order: list = None,
531
+ layer: str = None,
532
+ figsize: tuple = (3, 4.2),
533
+ palette: str | list = "tab10",
534
+ xtick_rotation: int = None,
535
+ ctrl_cond: str = None,
536
+ groups_cond: str | list = None,
537
+ groups_pvals: list = None,
538
+ scatter: bool = False,
539
+ scatter_size: int = 2,
540
+ title: str = None,
541
+ path: str = None,
542
+ filename: str = None,
543
+ title_fontproperties: dict = None,
544
+ hue_legend_fontsize: int = 12,
545
+ hue_legend_fontweight: float | str = None,
546
+ hue_legend_cols: int = 1,
547
+ hue_legend_title: str = '',
548
+ hue_legend_loc: Literal["center left", "cemter right", "upper right", "upper left", "lower left", "lower right", "right", "lower center", "upper center", "center"] = 'center left',
549
+ show: bool = True,
550
+ ax: plt.Axes = None,
551
+ cut: float = 0,
552
+ test: Literal["wilcoxon", "t-test", "kruskal", "anova", "logreg", "t-test_overestim_var"] = "wilcoxon",
553
+ corr_method: Literal["benjamini-hochberg", "bonferroni"] = "benjamini-hochberg",
554
+ txt_size: int = 13,
555
+ txt: str = "p = ",
556
+ ylabel="LogMean(nUMI)",
557
+ line_offset: float = 0.05,
558
+ **kwargs,
559
+ ):
560
+ """Violinplot with stats.
561
+
562
+ Show the distribution of the expression of `var_names` or a continuous value in `obs` along different categorical values
563
+ and test for significance.
564
+
565
+ :param adata: annotated data matrix
566
+ :param x_axis: categorical `obs` column to groupby.
567
+ :param feature: feature in `var_name` or `obs`.
568
+ :param order: order for the x_axis categories.
569
+ :param hue: categorical `obs` column to split by each group in x_axis.
570
+ :param hue_order: order for the hue categories.
571
+ :param layer: layer in the AnnData to use.
572
+ :param figsize: figure size.
573
+ :param palette: dictionary or palette to use.
574
+ :param xtick_rotation: rotation of the xticks.
575
+ :param ctrl_cond: name of the ctrl condition in the xticks. When hue is set, the control correspond to the categories in hue.
576
+ for each x_axis category the different hue categories will be tested.
577
+ :param groups_cond: list of the name of the groups to test in the xticks
578
+ :param groups_pvals: if provided, these values will be plotted. If not set, provide a list of the groups in the
579
+ xticks to test.
580
+ :param scatter: Plot non-zero values as scatterplot on top of the violin plots.
581
+ :param scatter_size: Size of the scatterplot dots.
582
+ :param title: title of the plot.
583
+ :param path: path to save the figure.
584
+ :param filename: name of the file.
585
+ :param title_fontproperties: properties of the title text.
586
+ :param hue_legend_fontsize: size of the legend text when hue is set.
587
+ :param hue_legend_fontweight: fontweight of the legend text when hue is set.
588
+ :param hue_legend_cols: number of columns for the legend when hue is set.
589
+ :param hue_legend_loc: location of the legend when hue is set.
590
+ :param hue_legend_title: title of the legend when hue is set.
591
+ :param show: if set to False, return the axis.
592
+ :param ax: matplotlib axis.
593
+ :param cut: distance in units of bandwidth, to extend the density past extreme datapoints. Set to 0 to limit the
594
+ violin within the data range
595
+ :param test: name of the method to test for significance. Available: ['wilcoxon', 't-test', 'kruskal', 'anova', 'logreg', 't-test_overestim_var'].
596
+ :param corr_method: correction method for multiple testing. Available: ['benjamini-hochberg', 'bonferroni'].
597
+ :param txt_size: size of the text indicating significance.
598
+ :param txt: text for indicating significance. If not set, only the p-value is shown.
599
+ :param ylabel: Y-axis label.
600
+ :param line_offset: offset for the stat
601
+ :param kwargs: additional arguments passed to `sns.barplot() <https://seaborn.pydata.org/generated/seaborn.violinplot.html>`_
602
+ :return: Depending on ``show``, returns the plot if set to `True` or a dictionary with the axes.
603
+
604
+ Example
605
+ -------
606
+
607
+ .. plot::
608
+ :context: close-figs
609
+
610
+ import dotools_py as do
611
+ adata = do.dt.example_10x_processed()
612
+ do.pl.violin(adata, 'annotation', 'CD4', ctrl_cond = 'pDC', groups_cond=['B_cells'], xtick_rotation=45, scatter=True)
613
+ # Take only lymphoid cells
614
+ lymphoid = adata[adata.obs['annotation'].isin(['T_cells', 'NK', 'B_cells'])].copy()
615
+ # When hue is set we test for each annotation healthy Vs disease
616
+ do.pl.violin(lymphoid,'annotation','CD4', hue = 'condition', ctrl_cond = 'healthy', groups_cond=['disease'], hue_order=['healthy', 'disease'], xtick_rotation=45, figsize=(6, 4))
617
+
618
+
619
+ """
620
+
621
+ # Checks
622
+ sanitize_anndata(adata)
623
+ groups_cond = [groups_cond] if isinstance(groups_cond, str) else groups_cond
624
+ groups_pvals = [groups_pvals] if isinstance(groups_pvals, float) else groups_pvals
625
+ feature = [feature] if isinstance(feature, str) else feature
626
+ assert len(feature) == 1, "Only 1 feature can be plotted"
627
+ feature = feature[0]
628
+
629
+ groups_to_save = [x_axis, hue] if hue is not None else [x_axis]
630
+ if feature in adata.var_names:
631
+ df = get_expr(adata, feature, groups=groups_to_save, layer=layer)
632
+ elif feature in list(adata.obs.columns):
633
+ df = adata.obs[groups_to_save + [feature]]
634
+ df.columns = groups_to_save + ["expr"]
635
+ else:
636
+ raise ValueError(f"{feature} is not in adata.var_names or adata.obs")
637
+
638
+ if hue is not None:
639
+ hue_order = list(adata.obs[hue].unique()) if hue_order is None else hue_order
640
+ order = list(adata.obs[x_axis].unique()) if order is None else order
641
+
642
+ # Create figure
643
+ if ax is None:
644
+ if hue is not None:
645
+ width, height = figsize # Define figure layout
646
+ fig, gs = make_grid_spec(
647
+ ax or (width, height), nrows=1, ncols=2, wspace=0.7 / width, width_ratios=[width - (0.9 + 0) + 0, 0.9]
648
+ )
649
+ ax = fig.add_subplot(gs[0])
650
+
651
+ else:
652
+ fig, ax = plt.subplots(1, 1, figsize=figsize)
653
+
654
+ vln = sns.violinplot(df, x=x_axis, y="expr", ax=ax, palette=palette, cut=cut,
655
+ order=order, hue=hue, hue_order=hue_order, legend=False, **kwargs)
656
+ if scatter:
657
+ sns.stripplot(df[df.expr != 0], x=x_axis, y="expr", ax=vln, color="k", order=order, hue=hue, hue_order=hue_order, legend=False,
658
+ size=scatter_size, dodge=True, )
659
+
660
+ if ctrl_cond is not None and groups_cond is not None:
661
+ if groups_pvals is None:
662
+ if hue is not None:
663
+ testing = TestData(data=adata,
664
+ feature=feature,
665
+ cond_key=hue,
666
+ ctrl=ctrl_cond,
667
+ groups=groups_cond,
668
+ category_order=order,
669
+ category_key=x_axis,
670
+ test=test,
671
+ test_correction=corr_method)
672
+ else:
673
+ testing = TestData(
674
+ adata,
675
+ feature=feature,
676
+ cond_key=x_axis,
677
+ ctrl=ctrl_cond,
678
+ groups=groups_cond,
679
+ category_order=None,
680
+ category_key=None,
681
+ test=test,
682
+ test_correction=corr_method,
683
+ )
684
+ testing.run_test()
685
+ groups_pvals = testing.pvals
686
+
687
+ plotter = StatsPlotter(
688
+ vln,
689
+ x_axis=x_axis,
690
+ y_axis="expr",
691
+ ctrl=ctrl_cond,
692
+ groups=groups_cond,
693
+ pvals=groups_pvals,
694
+ txt_size=txt_size,
695
+ txt=txt,
696
+ kind="violin",
697
+ line_offset=line_offset,
698
+ hue=hue,
699
+ hue_order=hue_order
700
+ )
701
+ plotter.plot_stats()
702
+
703
+ if xtick_rotation is not None:
704
+ vln.set_xticklabels(vln.get_xticklabels(), rotation=xtick_rotation, ha="right", va="top", fontweight="bold")
705
+ vln.set_xlabel("")
706
+ vln.set_ylabel(ylabel, fontweight="bold")
707
+
708
+ title_fontproperties = {} if title_fontproperties is None else title_fontproperties
709
+ title_size = title_fontproperties.get("size", 20)
710
+ title_font = title_fontproperties.get("weight", "bold")
711
+
712
+ if hue is not None:
713
+ axs_legend = fig.add_subplot(gs[1])
714
+ handles = []
715
+
716
+ if isinstance(palette, str):
717
+ colors = dotools_py.utility.get_hex_colormaps(palette)
718
+ colors_dict = dict(zip(hue_order, colors, strict=False))
719
+ elif isinstance(palette, dict):
720
+ colors_dict = palette
721
+ else:
722
+ raise Exception('palette can only be a string or dictionary')
723
+
724
+ handles = []
725
+ for lab, c in colors_dict.items():
726
+ handles.append(
727
+ mlines.Line2D(
728
+ [0], [0], marker=".", color=c, lw=0, label=lab, markerfacecolor=c, markeredgecolor=None,
729
+ markersize=18
730
+ )
731
+ )
732
+
733
+ legend = axs_legend.legend(
734
+ handles=handles,
735
+ frameon=False,
736
+ loc=hue_legend_loc,
737
+ ncols=hue_legend_cols,
738
+ title=hue_legend_title,
739
+ prop={"size": hue_legend_fontsize, "weight": hue_legend_fontweight},
740
+ )
741
+ legend.get_title().set_fontweight("bold")
742
+ legend.get_title().set_fontsize(hue_legend_fontsize + 2)
743
+ axs_legend.tick_params(axis="both", left=False, labelleft=False, labelright=False, bottom=False,
744
+ labelbottom=False)
745
+ axs_legend.spines[["right", "left", "top", "bottom"]].set_visible(False)
746
+ axs_legend.grid(visible=False)
747
+
748
+ if title is None:
749
+ vln.set_title(feature, fontsize=title_size, fontweight=title_font) # Title is the genename
750
+ else:
751
+ vln.set_title(title, fontsize=title_size, fontweight=title_font)
752
+ if path is not None: # If the path is provided we save it
753
+ plt.savefig(convert_path(path) / filename, bbox_inches="tight")
754
+ if show is False: # if show is false we return the axes
755
+ if hue is not None:
756
+ vln = {'mainplot_ax': vln,
757
+ 'legend_ax': axs_legend}
758
+ return vln
759
+ else:
760
+ plt.tight_layout()
761
+ return plt.show()