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
dotools_py/logger.py ADDED
@@ -0,0 +1,87 @@
1
+ import logging
2
+ import sys
3
+
4
+ logger = logging.getLogger("dotools")
5
+
6
+
7
+ def _setup_logger() -> None:
8
+ """Logger settings.
9
+
10
+ :return:
11
+ """
12
+ if not logger.handlers:
13
+ handler = logging.StreamHandler(sys.stdout)
14
+ formatter = logging.Formatter("%(asctime)s - %(message)s")
15
+ handler.setFormatter(formatter)
16
+ logger.addHandler(handler)
17
+ logger.propagate = False
18
+ set_verbosity(2)
19
+ return None
20
+
21
+
22
+ def set_verbosity(level: int = 2) -> None:
23
+ """Set verbosity.
24
+
25
+ :param level: 0 - Silent;
26
+ 1 - Info/Warnings;
27
+ 2 - Info/Warnings + Scanpy Info/Warnings;
28
+ 3 - Debug mode
29
+ :return:
30
+ """
31
+ import scanpy as sc
32
+
33
+ if level == 0:
34
+ # Completely silent
35
+ logger.setLevel(logging.CRITICAL + 1) # Higher than CRITICAL
36
+ sc.settings.verbosity = 0
37
+ #sc.settings._root_logger.setLevel(logging.CRITICAL + 1)
38
+ elif level == 1:
39
+ logger.setLevel(logging.INFO)
40
+ sc.settings.verbosity = 0
41
+ #sc.settings._root_logger.setLevel(logging.CRITICAL + 1)
42
+ elif level == 2:
43
+ logger.setLevel(logging.INFO)
44
+ #sc.settings._root_logger.setLevel(logging.INFO)
45
+ sc.settings.verbosity = 3
46
+ elif level == 3:
47
+ logger.setLevel(logging.DEBUG)
48
+ sc.settings.verbosity = 4
49
+ #sc.settings._root_logger.setLevel(logging.DEBUG)
50
+ else:
51
+ raise ValueError("Verbosity must be 0, 1, 2, or 3.")
52
+ return None
53
+
54
+
55
+ # ---- Custom logging functions ----
56
+
57
+
58
+ def info(msg: str):
59
+ """Produce an info message.
60
+
61
+ :param msg:
62
+ :return:
63
+ """
64
+ logger.info(msg)
65
+
66
+
67
+ def warn(msg: str):
68
+ """Produce a warn message.
69
+
70
+ :param msg:
71
+ :return:
72
+ """
73
+ logger.warning(msg)
74
+ return None
75
+
76
+
77
+ def debug(msg: str):
78
+ """Produce a debug message.
79
+
80
+ :param msg:
81
+ :return:
82
+ """
83
+ logger.debug(msg)
84
+ return None
85
+
86
+
87
+ _setup_logger()
@@ -0,0 +1,358 @@
1
+ from pathlib import Path
2
+
3
+ import anndata as ad
4
+ import pandas as pd
5
+ import numpy as np
6
+
7
+ import matplotlib.pyplot as plt
8
+ from matplotlib import gridspec
9
+
10
+ from dotools_py.utils import sanitize_anndata, iterase_input, convert_path
11
+ from dotools_py.pl._plot_utils import _AxesSubplot
12
+
13
+ from matplotlib.colors import Colormap
14
+ from collections.abc import Sequence
15
+ from matplotlib.axes import Axes
16
+ from matplotlib.figure import Figure
17
+
18
+
19
+
20
+ class BaseSeaborn:
21
+ """
22
+ Utility class to plot data from an AnnData Object using seaborn.
23
+ """
24
+
25
+ MIN_FIGURE_HEIGHT = 4.2
26
+ DEFAULT_WSPACE = 0.0
27
+ DEFAULT_LEGEND_WIDTH = 1.5
28
+ DEFAULT_CMAP = "tab10"
29
+
30
+ DEFAULT_TITLE_SIZE = 20
31
+ DEFAULT_TITLE_FONTWEIGHT = "bold"
32
+
33
+ DEFAULT_XTICKS_SIZE = 12
34
+ DEFAULT_XTICKS_FONTWEIGHT = "bold"
35
+ DEFAULT_XTICKS_ROTATION = None
36
+
37
+ DEFAULT_LEGEND_TITLE_FONTSIZE = 12
38
+ DEFAULT_LEGEND_TITLE_FONTWEIGHT = "bold"
39
+
40
+ def __init__(
41
+ self,
42
+ adata: ad.AnnData,
43
+ x_axis: str,
44
+ feature: str,
45
+ batch_key: str = None,
46
+ xticks_order: list = None,
47
+ hue: str = None,
48
+ hue_order: list = None,
49
+ layer: str = None,
50
+ logcounts: bool = True,
51
+ figsize: tuple = (3, 4.2),
52
+ ax: plt.Axes = None,
53
+ cmap: str | Colormap | dict = None,
54
+ title: str = None,
55
+ title_fontproperties: dict = None,
56
+ xticks_properties: dict = None,
57
+ legend_properties: dict = None,
58
+ path: str | Path = None,
59
+ filename: str = "figure.svg",
60
+ show: bool = True
61
+ ):
62
+ """Initialize class.
63
+
64
+ :param adata: Annotated data matrix.
65
+ :param x_axis: Name of a categorical column in `adata.obs` to groupby.
66
+ :param feature: A valid feature in `adata.var_names` or column in `adata.obs` with continuous values.
67
+ :param batch_key: Name of a categorical column in `adata.obs` that contains the sample names.
68
+ :param xticks_order: Order for the categories in `adata.obs[x_axis]`.
69
+ :param hue: Name of a second categorical column in `adata.obs` to use additionally to groupby.
70
+ :param hue_order: List with orders for the categories in `hue`. If it is not set, the order will be inferred.
71
+ :param layer: Name of the AnnData object layer that wants to be plotted. The default `adata.X` is plotted. If
72
+ layer is set to a valid layer name, then the layer is plotted.
73
+ :param logcounts: If set to `True`, consider that the values in `adata.X` or `adata.layers[layer]` if layer is
74
+ set is log1p transformed.
75
+ :param figsize: Figure size, the format is (width, height).
76
+ :param ax: Matplotlib axes to use for plotting. If not set, a new figure will be generated.
77
+ :param cmap: String denoting matplotlib colormap. A dictionary with the categories available in
78
+ `adata.obs[x_axis]` or `adata.obs[hue]` if hue is not None can also be provided. The format is
79
+ {category:color}.
80
+ :param title: Title for the figure.
81
+ :param title_fontproperties: Dictionary which should contain 'size' and 'weight' to define the fontsize and
82
+ fontweight of the title of the figure.
83
+ :param xticks_properties: Dictionary which should contain 'size' and 'weight' to define the fontsize and
84
+ fontweight of the xticks of the figure.
85
+ :param legend_properties: Dictionary which should contain 'size' and 'weight' to define the fontsize and
86
+ fontweight of the title of the legend.
87
+ :param path: Path to the folder to save the figure.
88
+ :param filename: Name of file to use when saving the figure.
89
+ :param show: If set to `False`, returns a dictionary with the matplotlib axes.
90
+ """
91
+ from dotools_py.utility._plotting import get_hex_colormaps
92
+
93
+ sanitize_anndata(adata)
94
+
95
+ # Data Section
96
+ self.adata = adata
97
+ self.x_axis = x_axis
98
+ self.feature = iterase_input(feature) # We always assume we have a list
99
+ self.batch_key = batch_key
100
+
101
+ self.xticks_order = xticks_order if xticks_order is not None else list(adata.obs[x_axis].unique())
102
+ self.hue = hue
103
+ if hue is None:
104
+ self.hue_order = None
105
+ else:
106
+ self.hue_order = hue_order if hue_order is not None else list(adata.obs[hue].unique())
107
+
108
+ self.layer = layer
109
+ self.logcounts = logcounts
110
+
111
+
112
+ # Figure paramters
113
+ self.figsize = figsize
114
+ self.fig = None,
115
+ self.gs = None
116
+ self.width, self.height = figsize if figsize is not None else (None, None)
117
+ self.ax = ax
118
+ self.legends_width = self.DEFAULT_LEGEND_WIDTH
119
+ self.cmap = self.DEFAULT_CMAP if cmap is None else cmap
120
+
121
+ if isinstance(self.cmap, str):
122
+ tmp = self.hue_order if hue_order is not None else self.xticks_order
123
+ colors_dict = dict(zip(tmp, get_hex_colormaps(self.cmap), strict=False))
124
+ elif isinstance(self.cmap, dict):
125
+ colors_dict = self.cmap
126
+ else:
127
+ raise Exception('palette can only be a string or dictionary')
128
+
129
+ self.cmap_dict = colors_dict
130
+
131
+ # Title Properties
132
+ self.title = title if title is not None else feature
133
+ title_fontproperties = {} if title_fontproperties is None else title_fontproperties
134
+ self.title_size = title_fontproperties.get("size", self.DEFAULT_TITLE_SIZE)
135
+ self.title_fontweight = title_fontproperties.get("weight", self.DEFAULT_TITLE_FONTWEIGHT)
136
+
137
+ # X-ticks Properties
138
+ xticks_properties = {} if xticks_properties is None else xticks_properties
139
+ self.xticks_fontsize = xticks_properties.get("size", self.DEFAULT_XTICKS_SIZE)
140
+ self.xticks_fontweight = xticks_properties.get("weight", self.DEFAULT_XTICKS_FONTWEIGHT)
141
+ rotation = xticks_properties.get("rotation", self.DEFAULT_XTICKS_ROTATION)
142
+ self.rotation = {"rotation": rotation, "ha": "right", "va": "top"} if rotation is not None else {}
143
+
144
+ # Legend Properties
145
+ legend_properties = {} if legend_properties is None else legend_properties
146
+ self.legend_title = legend_properties.get("size", self.DEFAULT_LEGEND_TITLE_FONTSIZE)
147
+ self.legend_title_fontweight = legend_properties.get("weight", self.DEFAULT_LEGEND_TITLE_FONTWEIGHT)
148
+ self.legend_fontsize = legend_properties.get("size", self.DEFAULT_LEGEND_TITLE_FONTSIZE - 2)
149
+
150
+ # Saving
151
+ self.path = path
152
+ self.filename = filename
153
+ self.show = show
154
+ self.dict_axis = None
155
+
156
+ return
157
+
158
+ def make_figure(
159
+ self,
160
+ nrows: int = 1,
161
+ ncols: int = 1
162
+ ) -> None:
163
+ """Generate figure.
164
+
165
+ :param nrows: Number of rows.
166
+ :param ncols: Number of Columns
167
+ :return: Returns None.
168
+ """
169
+ mainplot_width = self.width - self.legends_width
170
+
171
+ fig, gs = self.make_grid_spec(
172
+ self.ax or (self.width, self.height),
173
+ nrows=nrows, ncols=ncols, wspace=0.7 / self.width,
174
+ width_ratios=[mainplot_width, self.legends_width] if ncols == 2 else [mainplot_width]
175
+ )
176
+
177
+ self.fig = fig
178
+ self.gs = gs
179
+ return None
180
+
181
+ def legend(
182
+ self,
183
+ show: bool = False,
184
+ width: float = 1.5,
185
+ title: str = None,
186
+ ) -> None:
187
+ """Set legend parameters.
188
+
189
+ :param show: If set to `False`, the legend is deactivated.
190
+ :param width: width of the figure reserve for the legend.
191
+ :param title: title of the legend.
192
+ :return: Returns None.
193
+ """
194
+ if not show:
195
+ # Deactivate legend by setting the width to 0
196
+ self.legends_width = 0
197
+ else:
198
+ self.legend_title = title
199
+ self.legends_width = width
200
+ return None
201
+
202
+ @staticmethod
203
+ def make_grid_spec(
204
+ ax_or_figsize: tuple[int, int] | _AxesSubplot,
205
+ *,
206
+ nrows: int,
207
+ ncols: int,
208
+ wspace: float | None = None,
209
+ hspace: float | None = None,
210
+ width_ratios: Sequence[float] | None = None,
211
+ height_ratios: Sequence[float] | None = None,
212
+ ) -> tuple[Figure, gridspec.GridSpecBase]:
213
+ """Adapted from Scanpy"""
214
+
215
+ kw = dict(wspace=wspace, hspace=hspace, width_ratios=width_ratios, height_ratios=height_ratios)
216
+ if isinstance(ax_or_figsize, tuple):
217
+ fig = plt.figure(figsize=ax_or_figsize)
218
+ return fig, gridspec.GridSpec(nrows, ncols, **kw)
219
+ else:
220
+ ax = ax_or_figsize
221
+ ax.axis("off")
222
+ ax.set_frame_on(False)
223
+ ax.set_xticks([])
224
+ ax.set_yticks([])
225
+ return ax.figure, ax.get_subplotspec().subgridspec(nrows, ncols, **kw)
226
+
227
+ def saving_return_axis(self) -> dict[str, Axes] | plt.Axes | None:
228
+ """Return axis and save figure.
229
+
230
+ :return: Returns a dictionary with the matplotlib axes or matplotlib axes if `show` is set to False.
231
+ """
232
+ if self.path is not None:
233
+ plt.savefig(convert_path(self.path) / self.filename, bbox_inches="tight")
234
+ if self.show:
235
+ plt.tight_layout()
236
+ return plt.show()
237
+ else:
238
+ return self.dict_axis
239
+
240
+
241
+ def set_xticks(self, ax: plt.Axes) -> None:
242
+ """Set properties for the xticks.
243
+
244
+ :param ax: Matplotlib Axes.
245
+ :return: Returns None.
246
+ """
247
+ ax.set_xticklabels(ax.get_xticklabels(), fontweight=self.xticks_fontweight, **self.rotation)
248
+ return None
249
+
250
+
251
+ def set_title(self, ax: plt.Axes) -> None:
252
+ """Set the properties for the title.
253
+
254
+ :param ax: Matplotlib Axes.
255
+ :return: Returns None
256
+ """
257
+ ax.set_title(self.title, fontsize=self.title_size, fontweight=self.title_fontweight)
258
+ return None
259
+
260
+ def get_expression(self, keep: list) -> pd.DataFrame:
261
+ """Get the expression.
262
+
263
+ :param keep: Columns in `adata.obs` to keep.
264
+ :return: Returns a DataFrame with the expression extracted from the AnnData object.
265
+ """
266
+ from dotools_py.get._generic import expr as get_expr
267
+ keep = iterase_input(keep)
268
+ if all(feature in list(self.adata.var_names) for feature in self.feature):
269
+ df = get_expr(self.adata, self.feature, groups=keep, layer=self.layer)
270
+ elif all(feature in list(self.adata.obs.columns) for feature in self.feature):
271
+ df = self.adata.obs[keep + self.feature]
272
+ # df["expr"] = df[self.feature[0]]
273
+ df = df.rename(columns={self.feature[0]: "expr"})
274
+ else:
275
+ raise ValueError(f"{self.feature} needs to be in adata.var_names or adata.obs")
276
+ return df
277
+
278
+
279
+ def get_mean_expression(self) -> pd.DataFrame:
280
+ """Get the mean expression.
281
+
282
+ :return: Returns a DataFrame with the mean expression.
283
+ """
284
+ from dotools_py.get._generic import mean_expr as get_mean_expr
285
+
286
+ hue = iterase_input(self.hue)
287
+ group_by = [self.x_axis, self.batch_key] + hue
288
+
289
+ if all(feature in list(self.adata.var_names) for feature in self.feature):
290
+ df_mean = get_mean_expr(self.adata, group_by=group_by, features=self.feature, layer=self.layer)
291
+ elif all(feature in list(self.adata.obs.columns) for feature in self.feature):
292
+ df_mean = self.adata.obs[self.feature + group_by]
293
+ df_mean = df_mean.groupby(group_by).agg(np.mean).fillna(0).reset_index()
294
+ df_mean["gene"] = self.feature[0]
295
+ df_mean["expr"] = df_mean[self.feature[0]]
296
+ else:
297
+ raise ValueError(f"{self.feature} is not in adata.var_names or adata.obs")
298
+ return df_mean
299
+
300
+ @staticmethod
301
+ def log_estimator(values: np.ndarray):
302
+ """Compute mean of log1p transform data.
303
+
304
+ :param values: values to calculate the mean expression on.
305
+ :return: Returns a numpy array with the mean expression log1p transform
306
+ """
307
+ return np.log1p(np.mean(np.expm1(values)))
308
+
309
+
310
+ # def _pseudobuk_mode(
311
+ # # Data
312
+ # adata: ad.AnnData,
313
+ # x_axis: str,
314
+ # feature: str,
315
+ # batch_key: str,
316
+ # hue: str,
317
+ # layer: str = "counts",
318
+ #
319
+ # # Statistics
320
+ # ctrl_cond: str = None,
321
+ # groups_cond: str | list = None,
322
+ # groups_pvals: float | list = None,
323
+ # test: Literal["edger", "deseq", "cluster_ttest"] = "edger",
324
+ # mode: Literal["sum"] = "sum",
325
+ #
326
+ # # Fx specific
327
+ # design: str = "~condition",
328
+ # pseudobulk: bool = False
329
+ #
330
+ # ):
331
+ # from dotools_py.tl._Statistical import DGEAnalysis
332
+ #
333
+ # if len(groups_pvals) == 0:
334
+ # tester = DGEAnalysis(
335
+ # data=adata,
336
+ # group_by=x_axis,
337
+ # batch_key=batch_key,
338
+ # pseudobulk_mode=mode,
339
+ # pseudobulk_groups=hue,
340
+ # is_pseudobulk=pseudobulk,
341
+ # )
342
+ # tester._get_pseudobulk()
343
+ #
344
+ # if test == "cluster_ttest":
345
+ # tester.cluster_ttest(reference=ctrl_cond, groups=groups_cond, layer=layer)
346
+ # elif test == "edger":
347
+ # tester.edger(
348
+ # design=design, reference=ctrl_cond, groups=groups_cond, layer=layer)
349
+ # elif test == "deseq":
350
+ # tester.deseq(
351
+ # design=design, reference=ctrl_cond, groups=groups_cond, layer=layer)
352
+ # else:
353
+ # raise ValueError(f"{test} is not a valid test, use: ['edger', 'deseq', 'cluster_ttest']")
354
+ #
355
+ # tester.get_dge()
356
+ #
357
+
358
+