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,194 @@
1
+ import anndata as ad
2
+ import matplotlib.pyplot as plt
3
+ import numpy as np
4
+ import pandas as pd
5
+ from tqdm import tqdm
6
+
7
+ from dotools_py.get import expr as get_expr
8
+ from dotools_py.utils import convert_path, get_subplot_shape, remove_extra, sanitize_anndata, spine_format
9
+
10
+
11
+ def layers(
12
+ adata: ad.AnnData, color: str, layers: str, ncols: int = 4, normalise: bool = False, show: bool = True, **kwargs
13
+ ) -> None | plt.Axes:
14
+ """Plot several layers.
15
+
16
+ Plot different layers in subplots. Useful for deconvolution analysis with celltype counts in layers.
17
+
18
+ :param adata: annotated data matrix.
19
+ :param color: var_names or obs column to plot.
20
+ :param layers: layers to plot.
21
+ :param ncols: number of columns in the plot.
22
+ :param normalise: do log-normalisation on the layers.
23
+ :param show: if set to False, return axis.
24
+ :param kwargs: additional arguments for `sc.pl.spatial <https://scanpy.readthedocs.io/en/latest/api/generated/scanpy.pl.spatial.html>`_.
25
+ :return: None or plt.axes.
26
+ """
27
+ import scanpy as sc
28
+ adata = adata.copy()
29
+ sanitize_anndata(adata)
30
+ if normalise:
31
+ for layer in tqdm(layers, desc="Normalised Layers"):
32
+ sc.pp.normalize_total(adata, layer=layer)
33
+ sc.pp.log1p(adata, layer=layer)
34
+ nrows, ncols, extras = get_subplot_shape(len(layers), ncols)
35
+ fig, axs = plt.subplots(nrows, ncols, figsize=(15, 8))
36
+ axs = axs.flatten()
37
+ for idx, ly in enumerate(layers):
38
+ sc.pl.spatial(adata, color=color, ax=axs[idx], layer=ly, **kwargs)
39
+ axs[idx].set_title(ly + "\n" + color)
40
+ spine_format(axs[idx], "SP")
41
+ remove_extra(extras, nrows, ncols, axs)
42
+ if not show:
43
+ return axs
44
+ else:
45
+ return None
46
+
47
+
48
+ def slides(
49
+ adata: ad.AnnData,
50
+ color: str,
51
+ batch_key: str = "batch",
52
+ ncols: int = 4,
53
+ sp_size: float = 1.5,
54
+ path: str = None,
55
+ filename: str = "Spatial.svg",
56
+ common_legend: bool = True,
57
+ order: list = None,
58
+ figsize: tuple = (15, 8),
59
+ layer: str = None,
60
+ img_key: str = "hires",
61
+ title_fontsize: int = 15,
62
+ title_fontweight: str = None,
63
+ select_samples: list | str = None,
64
+ show: bool = True,
65
+ minimal_title: bool = True,
66
+ vmax: float = None,
67
+ verbose: bool = True,
68
+ spacing: tuple = (0.3, 0.2),
69
+ **kwargs,
70
+ ) -> plt.Axes:
71
+ """Plot multiple visium slides
72
+
73
+ Plot a feature in var_names or a column from obs in multiple visium slides.
74
+
75
+ :param adata: annotated data matrix.
76
+ :param color: var_names or obs column to plot.
77
+ :param batch_key: obs column containing Batch/Sample Information. This column should have the same names system use
78
+ to save the spatial images in `adata.uns['spatial'].keys()`.
79
+ :param ncols: number of subplots per row.
80
+ :param sp_size: size of the dots.
81
+ :param path: path to save the plot.
82
+ :param filename: filename of the plot.
83
+ :param common_legend: if set to true only the legend of the last column will be shown. Otherwise, the legend of
84
+ all the subplots will be shown.
85
+ :param order: provide a list with the order of the slides to show. If not set the `obs_col` will be sorted.
86
+ :param figsize: size of the subplots.
87
+ :param layer: layer to use to plot dt. If not specified, `.X` will be used.
88
+ :param img_key: image key to use for plotting (hires or lowres).
89
+ :param title_fontsize: fontsize of the title for the subplots.
90
+ :param title_fontweight: change fontweight of the title.
91
+ :param select_samples: list with a subset of samplename that want to be plotted.
92
+ :param show: if False, return axs.
93
+ :param minimal_title: if set to true only the sample name will be shown as title, otherwise title + color
94
+ :param vmax: maximum value for continus values (e.g., expression). If common legend is set to True and vmax
95
+ is not specified, it will be automatically computed taking the p99.2 expression value across
96
+ all subplots.
97
+ :param verbose: show a progress bar when plotting multiple slides.
98
+ :param kwargs: additional arguments for the function `scanpy.pl.spatial()`.
99
+ :param spacing: spacing between subplots (height, width) padding between plots
100
+ :return: a matplotlib axes object
101
+ """
102
+ import scanpy as sc
103
+ # TODO Consider the case where we only have 1 sample
104
+ sanitize_anndata(adata)
105
+
106
+ if select_samples is not None:
107
+ if type(select_samples) is str:
108
+ select_samples = [select_samples]
109
+ adata = adata[adata.obs[batch_key].isin(select_samples)].copy()
110
+ adata.obs[batch_key] = pd.Categorical(adata.obs[batch_key].astype(str))
111
+
112
+ # Define the number of rows base on the desired number of columns
113
+ n_samples = len(adata.obs[batch_key].unique())
114
+ nrows, ncols, extras = get_subplot_shape(n_samples, ncols)
115
+
116
+ # Control the order of the samples
117
+ show_order = order
118
+ if order is None:
119
+ show_order = sorted(adata.obs[batch_key].unique()) # If no order is provided sort the samples
120
+
121
+ # Assume we plot non-categorical values
122
+ cat, cb_loc, cont = None, "right", 0
123
+
124
+ # Scale values if common legend
125
+ if vmax is None and common_legend is True:
126
+ if color in adata.var_names:
127
+ expr = get_expr(adata, color)
128
+ vmax = np.percentile(expr["expr"], 99.2)
129
+ if color in adata.obs.columns and adata.obs[color].dtype.name != "category":
130
+ vmax = np.percentile(adata.obs[color], 99.2)
131
+
132
+ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
133
+ fig, axs = plt.subplots(nrows, ncols, figsize=figsize)
134
+ plt.subplots_adjust(hspace=spacing[0], wspace=spacing[1], left=0.05) # Spacing between subplots
135
+ axs = axs.flatten()
136
+ for idx, sample in tqdm(enumerate(show_order), desc="Slide ", disable=not verbose, total=len(show_order)):
137
+ sdata = adata[adata.obs[batch_key] == sample]
138
+
139
+ if common_legend:
140
+ # Remove the legend from all subplots except the last one per row
141
+ if cont != ncols - 1 and idx != n_samples - 1:
142
+ if color in adata.obs.columns: # Is color in .obs?
143
+ cat = adata.obs[color].dtype.name # It can be continuous or categorical
144
+ if cat != "category":
145
+ # Is continuous --> Remove color bar
146
+ cb_loc = None
147
+ cont += 1
148
+ else:
149
+ # Entered when we are in the last column per row
150
+ cb_loc = "right"
151
+ cont = 0
152
+ cat = None
153
+
154
+ # Main Plotting function, based on Scanpy
155
+ sc.pl.spatial(
156
+ sdata,
157
+ ax=axs[idx],
158
+ img_key=img_key,
159
+ color=color,
160
+ library_id=sample,
161
+ size=sp_size,
162
+ colorbar_loc=cb_loc,
163
+ layer=layer,
164
+ vmax=vmax,
165
+ show=False,
166
+ **kwargs,
167
+ )
168
+
169
+ if common_legend and cat == "category":
170
+ axs[idx].get_legend().remove() # Remove legend for categorical values
171
+
172
+ # Modify axis
173
+ title_color = "" if color is None else color
174
+ """
175
+ if color == None:
176
+ title_color = ''
177
+ else:
178
+ title_color = color
179
+ """
180
+ if minimal_title:
181
+ axs[idx].set_title(sample, fontsize=title_fontsize, fontweight=title_fontweight)
182
+ # plt.suptitle(color, fontsize=23, fontweight='bold')
183
+ fig.supylabel(color, fontsize=23, fontweight="bold")
184
+ else:
185
+ axs[idx].set_title(sample + "\n" + title_color, fontsize=title_fontsize, fontweight=title_fontweight)
186
+
187
+ spine_format(axs[idx], txt="SP")
188
+ remove_extra(extras, nrows, ncols, axs) # Remove extra subplots
189
+ if path is not None:
190
+ plt.savefig(convert_path(path) / filename, bbox_inches="tight")
191
+ if show:
192
+ return None
193
+ else:
194
+ return axs
@@ -0,0 +1,2 @@
1
+ from dotools_py.pp._cellbender import run_cellbender
2
+ from dotools_py.pp._importer import importer_py, sctransform_normalise
@@ -0,0 +1,179 @@
1
+ import os
2
+ import subprocess
3
+
4
+ import anndata as ad
5
+ import numpy as np
6
+
7
+ from dotools_py import logger
8
+ from dotools_py.utils import convert_path, get_paths_utils
9
+
10
+
11
+ def _run_barcoderanks(adata: ad.AnnData) -> tuple[int, int]:
12
+ """Run BarcodeRanks from DropletUtils to estimate the lower and upper bound of true cells.
13
+
14
+ :param adata: annotated dt matrix of shape with `.X` containing raw counts.
15
+ :return: lower and upper bound
16
+ """
17
+ import rpy2.robjects as robjects
18
+ from rpy2.robjects import numpy2ri
19
+ from rpy2.robjects.conversion import localconverter
20
+ from rpy2.robjects.packages import importr
21
+
22
+ dropletutils = importr("DropletUtils")
23
+
24
+ x_py = adata.X.T
25
+ with localconverter(robjects.default_converter + numpy2ri.converter):
26
+ # Extract CSC components
27
+ x_r = robjects.FloatVector(x_py.data)
28
+ i_r = robjects.IntVector(x_py.indices)
29
+ p_r = robjects.IntVector(x_py.indptr)
30
+ dim_r = robjects.IntVector(x_py.shape)
31
+
32
+ r_dgcmatrix = robjects.r["new"]("dgCMatrix", x=x_r, i=i_r, p=p_r, Dim=dim_r)
33
+ result = dropletutils.barcodeRanks(r_dgcmatrix)
34
+ metadata = result.do_slot("metadata")
35
+ knee = metadata.rx2("knee")[0]
36
+ inflection = metadata.rx2("inflection")[0]
37
+ counts = np.array(adata.X.sum(axis=1)).ravel()
38
+ total_cells = len(np.where(counts > inflection)[0])
39
+ expected_cells = len(np.where(counts > knee)[0])
40
+ return expected_cells, total_cells
41
+
42
+
43
+ def run_cellbender(
44
+ cellranger_path: str,
45
+ output_path: str,
46
+ samplenames: list | None = None,
47
+ cuda: bool = True,
48
+ cpu_threads: int = 15,
49
+ epochs: int = 150,
50
+ lr: float = 0.00001,
51
+ estimator_multiple_cpu: bool = False,
52
+ log: bool = True,
53
+ conda_path: str | None = None,
54
+ run_dropletutils: bool = False,
55
+ ) -> None:
56
+ """Run cellbender to remove ambient RNA.
57
+
58
+ Remove ambient RNA using `Cellbender <https://cellbender.readthedocs.io/en/latest/>`_. Assumes that the FASTQ files
59
+ have been mapped with `CellRanger <https://www.10xgenomics.com/support/software/cell-ranger/latest>`_.
60
+
61
+ .. warning::
62
+ It is recommended to have access to GPU when running cellbender. Running CellBender on
63
+ CPU might lead to high running time.
64
+
65
+ :param cellranger_path: path to folder containing subfolders for each sample.
66
+ :param output_path: output folder to save the H5 files with the corrected expression matrix.
67
+ :param samplenames: list with the name of the folders in `cellranger_path`. If not set, it will be infered.
68
+ :param cuda: set to True to use GPU for the training.
69
+ :param cpu_threads: number of CPUs to use for training.
70
+ :param epochs: number of epochs to train for. The default number is 150, higher number might lead to overfitting.
71
+ :param lr: learning rate.
72
+ :param estimator_multiple_cpu: use multiple CPUs for the generation of results. It is not recommended for big
73
+ datasets.
74
+ :param log: generate a log file with the stdout from running CellBender.
75
+ :param conda_path: path to the conda environment with cellbender installed. If not provided, a conda environment
76
+ will be created in `~/.venv/cellbender`.
77
+ :param run_dropletutils: run DropletUtils to estimate the expected number of cells and total number of droplets to
78
+ use as a prior for cellbender.
79
+ :return: H5 files with the corrected expression matrix will be saved in the output folder
80
+
81
+ Example
82
+ --------
83
+ >>> import dotools_py as do
84
+ >>> in_path = "/path/to/cellranger"
85
+ >>> out_path = "/path/to/output"
86
+ >>> do.pp.run_cellbender(in_path, out_path)
87
+ """
88
+ import scanpy as sc
89
+
90
+ # Check-Ups and Information
91
+ samplenames = [samplenames] if isinstance(samplenames, str) else samplenames
92
+ assert os.path.exists(cellranger_path), f"{cellranger_path} does not exist"
93
+ assert os.path.exists(output_path), f"{output_path} does not exist"
94
+
95
+ bash_script = get_paths_utils("_run_CellBender.sh")
96
+
97
+ if estimator_multiple_cpu:
98
+ logger.info("Estimator_multiple_cpu is set to True, this is not recommended for big datasets >20-30k cells")
99
+ if epochs > 150:
100
+ logger.info(f"Training {epochs} epochs. More than 150 epochs might lead to overfitting")
101
+ if not cuda:
102
+ logger.info("Training without GPU might lead to increase running time")
103
+
104
+ # Set-Up - Check that CellBender is available
105
+ conda_path = (
106
+ convert_path(os.path.expanduser("~") + "/.venv/cellbender")
107
+ if conda_path is None
108
+ else os.path.expanduser(conda_path)
109
+ )
110
+ command = ["conda", "create", "-y", "-p", conda_path, "python=3.7"]
111
+ if not os.path.exists(conda_path):
112
+ logger.info("Path to conda env with cellbender not provided, installing cellbender...")
113
+ logger.info("This will take a few minutes")
114
+ try:
115
+ subprocess.run(
116
+ command, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
117
+ ) # Quiet installation
118
+ command = ["conda", "run", "-p", conda_path, "pip", "install", "cellbender", "lxml-html-clean"]
119
+ subprocess.run(
120
+ command, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
121
+ ) # Quiet installation
122
+ logger.info("Environment created")
123
+ logger.info(f"Conda environment create in {conda_path}")
124
+ except subprocess.CalledProcessError as err:
125
+ raise Exception("Error installing cellbender, provide a valid conda environment") from err
126
+ else:
127
+ logger.info(f"Conda environment with CellBender available using ({conda_path})")
128
+
129
+ # Run CellBender Sequentially
130
+ cellranger_path = convert_path(cellranger_path)
131
+ if samplenames is None:
132
+ samples = [d for d in os.listdir(cellranger_path) if os.path.isdir(cellranger_path / d)]
133
+ else:
134
+ samples = samplenames
135
+
136
+ logger.info(f"Running cellbender for {len(samples)} samples")
137
+ expected_cells, total_droplets = None, None
138
+ for batch in samples:
139
+ # Run one by one but sequentially
140
+ # Estimate the number of cells to be used as upper and lower bound
141
+ if run_dropletutils:
142
+ file = next((cellranger_path / batch / "outs").glob("*raw_feature_bc_matrix.h5"))
143
+ tdata = sc.read_10x_h5(file)
144
+ expected_cells, total_droplets = _run_barcoderanks(tdata) # Run with rpy2; gives a good estimate
145
+
146
+ command = [
147
+ "conda",
148
+ "run",
149
+ "-p",
150
+ str(conda_path),
151
+ "bash",
152
+ str(bash_script),
153
+ "-i",
154
+ batch,
155
+ "-o",
156
+ str(output_path),
157
+ "--cellRanger-output",
158
+ str(cellranger_path),
159
+ "--cpu-threads",
160
+ str(cpu_threads),
161
+ "--epochs",
162
+ str(epochs),
163
+ "--lr",
164
+ str(lr),
165
+ ]
166
+ command += ["--expected-cells", expected_cells] if expected_cells is not None else []
167
+ command += ["--total-droplets", total_droplets] if total_droplets is not None else []
168
+ command += ["--cuda"] if cuda else []
169
+ command += ["--log"] if log else []
170
+ command += ["--estimator_multiple_cpu"] if estimator_multiple_cpu else []
171
+
172
+ try:
173
+ logger.info(f"Running Cellbender for {batch}, might take a while")
174
+ subprocess.run(command, check=True, cwd=output_path)
175
+ except subprocess.CalledProcessError as e:
176
+ logger.info(f"Error running CellBender in conda environment: {e}")
177
+
178
+ logger.info("Finished running cellbender")
179
+ return None