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,403 @@
1
+ import os
2
+ from typing import Literal
3
+
4
+ import numpy as np
5
+ import pandas as pd
6
+ import anndata as ad
7
+ from scipy.sparse import issparse
8
+
9
+ from dotools_py import logger
10
+ from dotools_py.get._generic import mean_expr
11
+ from dotools_py.get._generic import expr as get_expr
12
+
13
+
14
+ class MastTest:
15
+ """Class to perform MAST test.
16
+
17
+ This class allows to run the MAST test on an AnnData object. Requires the R package MAST to be installed.
18
+ The test assumes that the expression data is log-normalised.
19
+
20
+ Parameters
21
+ ----------
22
+ adata
23
+ Annotated data matrix.
24
+ condition_key
25
+ Column in `obs` with the conditions for each cell.
26
+ reference
27
+ Condition to be used as the reference.
28
+ group
29
+ Condition to be used as the alternative to test against. Only one condition can be accepted.
30
+ layer
31
+ Layer in the AnnData to use for testing.
32
+ covariates
33
+ Additional covariates to consider for the MAST test.
34
+ n_cpus
35
+ Number of cores to used for the inference.
36
+ method
37
+ Method to used for the inference. See `Mast::zlm <https://rglab.github.io/MAST/reference/zlm.html>`_.
38
+ formula
39
+ Formula for the test.
40
+ ebayes
41
+ If set to `True`, regularize variance using empirical bayes method.
42
+ parallel
43
+ If set to `True`, then multiple cores will be used in fitting.
44
+ silent
45
+ Silence common problems with fitting some genes.
46
+
47
+ Example
48
+ -------
49
+
50
+ >>> import dotools_py as do
51
+ >>> adata = do.dt.example_10x_processed()
52
+ >>> tester = do.tl.MastTest(adata=adata, condition_key="condition", reference="healthy", group="disease", layer="logcounts", n_cpus=5, method="bayesglm", parallel=True, formula="~condition")
53
+ >>> tester.fit()
54
+ 2025-09-24 13:27:56,435 - Reference level is set to healthy
55
+ [2025-09-24 13:27:56] `fData` has no primerid. I'll make something up.
56
+ [2025-09-24 13:27:56] `cData` has no wellKey. I'll make something up.
57
+ [2025-09-24 13:27:56] Assuming data assay in position 1, with name et is log-transformed.
58
+ [2025-09-24 13:27:59] Done!
59
+ [2025-09-24 13:27:59] Combining coefficients and standard errors
60
+ [2025-09-24 13:27:59] Calculating log-fold changes
61
+ [2025-09-24 13:27:59] Calculating likelihood ratio tests
62
+ [2025-09-24 13:27:59] Refitting on reduced model...
63
+ [2025-09-24 13:28:03] Done!
64
+ >>> tester.pvalues.head(3)
65
+ GeneName pvals padj
66
+ 1 A4GALT 0.001722 0.015546
67
+ 2 AAK1 0.019197 0.105754
68
+ 3 ABAT 0.551787 0.842536
69
+ >>> tester.dge_table.head(3)
70
+ GeneName log2fc pvals padj pts_group pts_ref
71
+ 0 A4GALT 26.073313 0.001722 0.015546 0.022222 0.000000
72
+ 1 AAK1 -0.429676 0.019197 0.105754 0.338889 0.457692
73
+ 2 ABAT 0.775196 0.551787 0.842536 0.033333 0.023077
74
+ >>> tester.formula
75
+ Out[17]: '~condition'
76
+ >>> tester.mast_version()
77
+ 2025-09-24 13:30:45,484 - MAST v1.33.0
78
+
79
+ """
80
+ def __init__(self,
81
+ adata: ad.AnnData,
82
+ condition_key: str,
83
+ reference: str,
84
+ group: str,
85
+ layer: str = None,
86
+ covariates: list = None,
87
+ n_cpus: int = 20,
88
+ method: Literal["glm", "glmer", "bayesglm"] = "bayesglm",
89
+ ebayes: bool = True,
90
+ parallel: bool = True,
91
+ silent: bool = True,
92
+ formula: str = None,
93
+ ):
94
+ """Initialise the class.
95
+
96
+ :param adata: AnnData object to be used for testing
97
+ :param condition_key: column in `obs` with conditions
98
+ :param reference: reference condition
99
+ :param group: alternative condition to test against
100
+ :param layer: layer to use for testing
101
+ :param covariates: covariates to correct for in the MAST test
102
+ :param n_cpus: number of cores to used for the inference
103
+ :param method: method to use for the inference
104
+ :param ebayes: If set to `True`, regularize variance using empirical bayes method.
105
+ :param parallel: allow parallelization
106
+ :param silent: reduce verbosity
107
+ :param formula: formula to use for the inference
108
+ """
109
+
110
+ os.environ["OMP_NUM_THREADS"] = "1" # Avoid problems with running R code
111
+
112
+ # TODO account when group is a list and several conditions are available
113
+
114
+ adata_copy = adata.copy()
115
+ self.adata = adata_copy
116
+ self.condition_key = condition_key
117
+ self.reference = reference
118
+ self.group = group
119
+ self.layer = layer
120
+ self.covariates = covariates
121
+ self.n_cpus = n_cpus
122
+ self.method = method
123
+ self.ebayes = ebayes
124
+ self.parallel = parallel
125
+ self.silent = silent
126
+ self._formula = formula
127
+ self.pvals = None
128
+
129
+ self._set_rpy2_logger()
130
+
131
+
132
+ def fit(self):
133
+ """Fit the model.
134
+
135
+ :return: The attribute p-values will be set containing the p-values and the adjusted p-values.
136
+ """
137
+ # Import rpy2
138
+ try:
139
+ import os
140
+ os.environ["R_MAX_VSIZE"] = "128GB"
141
+ from rpy2 import robjects as ro
142
+ from rpy2.robjects import numpy2ri, pandas2ri, r, DataFrame, StrVector, FloatVector
143
+ from rpy2.robjects.conversion import get_conversion, localconverter
144
+ from rpy2.robjects.packages import importr
145
+ except ImportError:
146
+ raise ImportError("MastTest requires rpy2 to be installed.")
147
+
148
+ # Import R packages
149
+ try:
150
+ MAST = importr("MAST")
151
+ except ImportError as e:
152
+ raise ImportError("MASTTest requires MAST to be installed") from e
153
+
154
+ base = importr("base")
155
+ stats = importr("stats")
156
+ SummarizedExperiment = importr("SummarizedExperiment")
157
+
158
+ self.adata.obs[self.condition_key] = pd.Categorical(self.adata.obs[self.condition_key],
159
+ categories=[self.reference, self.group])
160
+
161
+ # Generate a dataframe with expression matrix
162
+ with localconverter(get_conversion() + numpy2ri.converter):
163
+ X = self.adata.X if self.layer is None else self.adata.layers[self.layer] # Assume this is log-counts
164
+ X = X.T.toarray() if issparse(X) else X.T
165
+
166
+ # Transfer obs and vars to R
167
+ if self.adata.var.shape[1] == 0:
168
+ self.adata.var["genes"] = self.adata.var_names
169
+
170
+ with localconverter(get_conversion() + pandas2ri.converter + numpy2ri.converter) as cv:
171
+ # X_r = cv.py2rpy(pd.DataFrame(X, index=self.adata.var_names, columns=self.adata.obs_names))
172
+ X_r = cv.py2rpy(X)
173
+ obs_r = cv.py2rpy(self.adata.obs)
174
+ var_r = cv.py2rpy(self.adata.var)
175
+
176
+ levels = r('levels')(obs_r.rx2(self.condition_key))
177
+ logger.warn(f"Reference level is set to {levels[0]}")
178
+
179
+ # Generate SingleCellAssay
180
+ logger.info("Generating MAST Object")
181
+ sca = MAST.FromMatrix(base.as_matrix(X_r), obs_r, var_r)
182
+
183
+
184
+ # Re-organise to set reference as first level
185
+ col_data = SummarizedExperiment.colData(sca)
186
+ condition_vector = r['slot'](col_data, 'listData').rx2(self.condition_key)
187
+ condition_vector = stats.relevel(x=condition_vector, ref=self.reference)
188
+ col_data.slots[self.condition_key] = condition_vector
189
+ sca.slots['colData'] = col_data
190
+
191
+ if self._formula is None:
192
+ if self.covariates is None:
193
+ latent_variables = base.c(self.condition_key)
194
+ else:
195
+ # Pass "condition" plus all elements in covariates as separate arguments
196
+ latent_variables = base.c(self.condition_key, *self.covariates)
197
+ formula = stats.as_formula(object=base.paste0(" ~ ", base.paste(latent_variables, collapse="+")))
198
+ logger.info(f"formula is None, setting to {formula}")
199
+ else:
200
+ formula = stats.as_formula(str(self._formula))
201
+
202
+ logger.info("Running Inference")
203
+ #ro.r(f'options(mc.cores = {self.n_cpus})') # Allow parallelisation
204
+ zlmCond = MAST.zlm(formula=formula,
205
+ sca=sca,
206
+ method=self.method,
207
+ ebayes=self.ebayes,
208
+ ebayesControl=r('NULL'),
209
+ force=False,
210
+ hook=r('NULL'),
211
+ parallel=self.parallel,
212
+ onlyCoef=False,
213
+ silent=self.silent,
214
+ )
215
+ logger.info("Done")
216
+ #ro.r('options(mc.cores = 1)') # Set to one thread again
217
+ summary = r['summary']
218
+ zlm_summary = summary(zlmCond, doLRT=base.paste0(self.condition_key, self.group))
219
+
220
+ summaryDt = zlm_summary.rx2('datatable') # equivalent to summaryCond$datatable
221
+
222
+ with localconverter(ro.default_converter + pandas2ri.converter):
223
+ summary_df = pandas2ri.rpy2py(summaryDt)
224
+
225
+ # 1. Subset where component == 'H'
226
+ filtered = summary_df[summary_df['component'] == 'H']
227
+ # 2. Extract p-values
228
+ p_val = filtered[['Pr(>Chisq)']].copy()
229
+ p_val.columns = ['pvals']
230
+ # 3. Extract gene IDs (assuming 1st column is 'primerid')
231
+ genes = filtered[['primerid']].copy()
232
+ # 4. Adjust p-values using R's p.adjust
233
+ p_adjust = ro.r['p.adjust']
234
+ from rpy2.robjects import FloatVector
235
+ pvals_r = FloatVector(p_val['pvals'].values)
236
+ padj_r = p_adjust(pvals_r, method='fdr')
237
+ with localconverter(ro.default_converter + pandas2ri.converter):
238
+ padj = pandas2ri.rpy2py(padj_r)
239
+ p_val['padj'] = padj
240
+
241
+ r_names = StrVector(genes["primerid"])
242
+ r_pvals = FloatVector(p_val['pvals'])
243
+ r_padj = FloatVector(p_val['padj'])
244
+
245
+ # Create R data.frame
246
+ df = DataFrame({
247
+ 'names': r_names,
248
+ 'pvals': r_pvals,
249
+ 'padj': r_padj,
250
+ })
251
+ with localconverter(ro.default_converter + pandas2ri.converter):
252
+ df_py = pandas2ri.rpy2py(df)
253
+
254
+ df_py.rename(columns = {"names":"GeneName"}, inplace=True)
255
+ self.pvals = df_py
256
+ self._formula = formula
257
+
258
+ @property
259
+ def dge_table(self) -> pd.DataFrame:
260
+ """Generate table summarising the results from the DGE analysis.
261
+
262
+ Returns
263
+ --------
264
+ Returns a dataframe with the following columns:
265
+
266
+ `GeneName`
267
+ Contains the genes that have been tested.
268
+ `log2fc`
269
+ Contains the log-foldchanges.
270
+ `pvals`
271
+ Contains the p-values.
272
+ `padj`
273
+ Contains the adjusted p-values. Correction performed with Benjamini-Hochberg.
274
+ `pts_group`
275
+ Percentage of cells in the group expressing the gene.
276
+ `pts_ref`
277
+ Percentage of cells in the reference condition expressing the gene.
278
+
279
+ """
280
+ df_mean = mean_expr(self.adata, group_by=self.condition_key, out_format="wide")
281
+ logfoldchanges = np.log2((np.expm1(df_mean[self.group] + 1e-9)) /
282
+ (np.expm1(df_mean[self.reference]) + 1e-9))
283
+ # add small value to remove 0's
284
+ df_expr = get_expr(
285
+ self.adata, features=self.adata.var_names, groups=self.condition_key, layer=self.layer, out_format="wide"
286
+ ).set_index(self.condition_key)
287
+
288
+ obs_bool = df_expr > 0.0
289
+ df_pct = (
290
+ obs_bool.groupby(level=self.condition_key, observed=True).sum()
291
+ / obs_bool.groupby(level=self.condition_key, observed=True).count()
292
+ ).T
293
+ df_pct.reset_index(inplace=True)
294
+ df_pct.rename(columns={self.reference: "pts_ref",
295
+ self.group: "pts_group",
296
+ "index": "GeneName",}, inplace=True)
297
+ logfoldchanges = pd.DataFrame(logfoldchanges, columns=["log2fc"]).reset_index()
298
+ logfoldchanges.rename(columns={"gene": "GeneName"}, inplace=True)
299
+
300
+ table = pd.merge(logfoldchanges, df_pct, on="GeneName")
301
+
302
+
303
+ table = pd.merge(table, self.pvals, on="GeneName")
304
+ table = table[["GeneName", "log2fc", "pvals", "padj", "pts_group", "pts_ref"]]
305
+ return table
306
+
307
+
308
+ @property
309
+ def formula(self) -> str | None:
310
+ """Formula used to fit the model.
311
+
312
+ :return: Returns the formula used to fit the model.
313
+ """
314
+ if self._formula is None:
315
+ logger.info("formula not initialise, run fit()")
316
+ return None
317
+ else:
318
+ return str(self._formula).strip()
319
+
320
+
321
+ @property
322
+ def pvalues(self) -> pd.DataFrame | None:
323
+ """Dataframe with the p-values from the test.
324
+
325
+ :return: Returns a dataframe with the p-values and adjusted p-values from the test.
326
+ """
327
+ if self.pvals is None:
328
+ logger.info("pvals not calculated, run fit()")
329
+ return None
330
+ else:
331
+ return self.pvals
332
+
333
+
334
+ @staticmethod
335
+ def _set_rpy2_logger() -> None:
336
+ """Manage the logger from rpy2.
337
+
338
+ :return: None
339
+ """
340
+ import logging
341
+ from datetime import datetime
342
+
343
+ class RemovePrefixFilter(logging.Filter):
344
+ def filter(self, record):
345
+ prefix = "R callback write-console: "
346
+ if record.msg.startswith(prefix):
347
+ record.msg = record.msg[len(prefix):]
348
+ return True # Keep the record
349
+
350
+ # Get rpy2 logger
351
+ rpy2_logger = logging.getLogger('rpy2')
352
+ # Remove existing handlers
353
+ for handler in rpy2_logger.handlers[:]:
354
+ rpy2_logger.removeHandler(handler)
355
+
356
+ # Create and add our handler
357
+ handler = logging.StreamHandler()
358
+ handler.setLevel(logging.INFO)
359
+
360
+ # Simple formatter: just message with timestamp prefix added here
361
+ formatter = logging.Formatter('%(message)s')
362
+ handler.setFormatter(formatter)
363
+
364
+ # Add the filter to strip prefix
365
+ handler.addFilter(RemovePrefixFilter())
366
+
367
+ # Add handler and set level
368
+ rpy2_logger.addHandler(handler)
369
+ rpy2_logger.setLevel(logging.INFO)
370
+
371
+ # Wrap the handler's emit to add timestamp
372
+ old_emit = handler.emit
373
+
374
+ def emit_with_timestamp(record):
375
+ timestamp = datetime.now().strftime("[%Y-%m-%d %H:%M:%S]")
376
+ record.msg = f"{timestamp} {record.msg}"
377
+ #old_emit(record) #TODO test if hiving this is fine
378
+
379
+ handler.emit = emit_with_timestamp
380
+ return None
381
+
382
+ @staticmethod
383
+ def mast_version():
384
+ """Get the version from MAST used.
385
+
386
+ :return: Returns None.
387
+ """
388
+ from rpy2.robjects.packages import importr
389
+ try:
390
+ MAST = importr("MAST")
391
+ except ImportError as e:
392
+ raise ImportError("MASTTest requires MAST to be installed") from e
393
+ logger.info("MAST v" + MAST.__version__)
394
+
395
+ def __exit__(self, exc_type, exc_val, exc_tb):
396
+ from rpy2 import robjects as ro
397
+ import gc
398
+
399
+ ro.r("rm(list = ls())")
400
+ ro.r("invisible(gc())")
401
+ gc.collect()
402
+
403
+ return False
File without changes