DOTools-py 1.0.0__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 (51) hide show
  1. dotools_py/__init__.py +33 -0
  2. dotools_py/_experimental/__init__.py +0 -0
  3. dotools_py/_experimental/_deprecated/_ReadWrite_RDS.R +203 -0
  4. dotools_py/_experimental/_deprecated/_run_MAST.R +116 -0
  5. dotools_py/_experimental/gr/__init__.py +0 -0
  6. dotools_py/_experimental/gr/_generic.py +382 -0
  7. dotools_py/dt/__init__.py +2 -0
  8. dotools_py/dt/_datasets.py +112 -0
  9. dotools_py/dt/_markers.py +150 -0
  10. dotools_py/dt/example_reduced.h5ad +0 -0
  11. dotools_py/get/__init__.py +7 -0
  12. dotools_py/get/_generic.py +630 -0
  13. dotools_py/logger.py +87 -0
  14. dotools_py/pl/_Plotter.py +567 -0
  15. dotools_py/pl/_StatsPlotter.py +716 -0
  16. dotools_py/pl/__init__.py +8 -0
  17. dotools_py/pl/_dotplot.py +2062 -0
  18. dotools_py/pl/_downstream.py +833 -0
  19. dotools_py/pl/_embeddings.py +471 -0
  20. dotools_py/pl/_experimental.py +191 -0
  21. dotools_py/pl/_expression.py +754 -0
  22. dotools_py/pl/_heatmap.py +456 -0
  23. dotools_py/pl/_visium.py +193 -0
  24. dotools_py/pp/__init__.py +2 -0
  25. dotools_py/pp/_cellbender.py +179 -0
  26. dotools_py/pp/_importer.py +575 -0
  27. dotools_py/settings/__init__.py +1 -0
  28. dotools_py/settings/_configure.py +185 -0
  29. dotools_py/settings/_global_parameters.py +16 -0
  30. dotools_py/tl/__init__.py +10 -0
  31. dotools_py/tl/_analysis.py +768 -0
  32. dotools_py/tl/_get_stats.py +694 -0
  33. dotools_py/tl/_rankGenes.py +1113 -0
  34. dotools_py/tl/_statistics.py +384 -0
  35. dotools_py/util_scripts/_run_CCA.R +91 -0
  36. dotools_py/util_scripts/_run_CellBender.sh +186 -0
  37. dotools_py/util_scripts/_run_SCTransform.R +60 -0
  38. dotools_py/util_scripts/_run_edgeR.R +104 -0
  39. dotools_py/util_scripts/_run_scDblFinder.R +63 -0
  40. dotools_py/utility/HomoSapiens_GeneMetadata.pickle.gz +0 -0
  41. dotools_py/utility/MusMusculus_GeneMetadata.pickle.gz +0 -0
  42. dotools_py/utility/__init__.py +4 -0
  43. dotools_py/utility/_general.py +260 -0
  44. dotools_py/utility/_language.py +368 -0
  45. dotools_py/utility/_plotting.py +101 -0
  46. dotools_py/utility/_spatial.py +64 -0
  47. dotools_py/utils.py +418 -0
  48. dotools_py-1.0.0.dist-info/METADATA +231 -0
  49. dotools_py-1.0.0.dist-info/RECORD +51 -0
  50. dotools_py-1.0.0.dist-info/WHEEL +4 -0
  51. dotools_py-1.0.0.dist-info/licenses/LICENSE +21 -0
dotools_py/__init__.py ADDED
@@ -0,0 +1,33 @@
1
+ import os
2
+ from importlib.metadata import version
3
+
4
+ from . import dt, pl, pp, settings, tl, utility, get
5
+
6
+ __all__ = ["pl", "pp", "tl", "dt", "get", "utility", "settings"]
7
+
8
+ __version__ = version("DOTools_py")
9
+
10
+
11
+ def _is_run_from_ipython():
12
+ """Determine whether we're currently in IPython."""
13
+ import builtins
14
+
15
+ return getattr(builtins, "__IPYTHON__", False)
16
+
17
+
18
+ def is_interactive():
19
+ try:
20
+ if _is_run_from_ipython():
21
+ return True
22
+ from IPython import get_ipython
23
+
24
+ ip = get_ipython()
25
+ return ip is not None and ip.__class__.__name__ in ("ZMQInteractiveShell", "TerminalInteractiveShell")
26
+ except ImportError:
27
+ return False
28
+
29
+
30
+ if not is_interactive():
31
+ settings.session_settings(verbosity=0, interactive=False)
32
+ if is_interactive() and os.environ.get("READTHEDOCS", "").lower() != "true":
33
+ settings.session_settings()
File without changes
@@ -0,0 +1,203 @@
1
+ #######################################################################################
2
+ # Description: Convert RDS Object (SCE/Seurat) to AnnData #
3
+ # #
4
+ # Author: David Rodriguez Morales #
5
+ # Date Created: 16-07-2025 #
6
+ # Date Modified: 16-07-2025 #
7
+ # Version: 1.0 #
8
+ # R Version: 4.3.2 (Seurat 5.3.0) #
9
+ #######################################################################################
10
+
11
+ suppressWarnings(suppressMessages(library(optparse)))
12
+ suppressWarnings(suppressMessages(library(zellkonverter)))
13
+ suppressWarnings(suppressMessages(library(Seurat)))
14
+
15
+
16
+ option_list <- list(
17
+ make_option("--input", type = "character", default = NULL,
18
+ help = "Absolute path to RDS object", metavar = "character"),
19
+ make_option("--out", type = "character", default = NULL,
20
+ help = "Absolute path to the directory where the output files will be saved",
21
+ metavar = "character"),
22
+ make_option("--type", type = "character", default = 'SeuratObject',
23
+ help = "Type of Object to convert to (SingleCellExperiment or SeuratObject)",
24
+ metavar = "character"),
25
+ make_option("--operation", type = "character", default = NULL,
26
+ help = "Type of convertion: read (RDS --> AnnData) or write (AnnData --> RDS)",
27
+ metavar = "character"),
28
+ make_option("--batch_key", type = "character", default = "batch",
29
+ help = "Batch key in AnnData", metavar = "character")
30
+ )
31
+
32
+ opt_parser <- OptionParser(usage = "usage: %prog [options]
33
+ Convertion between SingleCellExperiment, Seurat and AnnData
34
+ Objects.", option_list = option_list)
35
+
36
+ opt <- parse_args(opt_parser)
37
+
38
+ if (is.null(opt$input)) {
39
+ print_help(opt_parser)
40
+ stop("Please provide the specified arguments", call. = FALSE)
41
+ } else if (is.null(opt$out)) {
42
+ print_help(opt_parser)
43
+ stop("Please provide the specified arguments", call. = FALSE)
44
+ } else if (is.null(opt$type)) {
45
+ print_help(opt_parser)
46
+ stop("Please provide the specified arguments", call. = FALSE)
47
+ } else if (is.null(opt$operation)) {
48
+ print_help(opt_parser)
49
+ stop("Please provide the specified arguments", call. = FALSE)
50
+ }
51
+
52
+ TransformObjectType <- function(obj, type) {
53
+ if (is(obj, "Seurat")) {
54
+ obj_type <- "SeuratObject"
55
+ } else if (is(obj, "SingleCellExperiment")) {
56
+ obj_type <- "SingleCellExperiment"
57
+ }
58
+
59
+ if (obj_type == type) {
60
+ return(obj) # The class we want is the same
61
+ } else if (obj_type == "SingleCellExperiment" && type == "SeuratObject") {
62
+ seu.obj <- as.Seurat(obj, counts = "counts", data = "logcounts") # We have SCE and want SeuratObject
63
+ return(seu.obj)
64
+ } else if (obj_type == "SeuratObject" && type == "SingleCellExperiment") {
65
+ sce <- Seurat::as.SingleCellExperiment(obj) #We have SeuratObject and want SingleCellExperiment
66
+ return(sce)
67
+ }
68
+ }
69
+
70
+
71
+ if (opt$operation == 'read') { # Convert RDS to AnnData
72
+ message("Convert RDS Object to AnnData Object")
73
+ input.obj <- readRDS(opt$input)
74
+ output.obj <- TransformObjectType(input.obj, "SingleCellExperiment")
75
+ writeH5AD(output.obj, opt$out)
76
+
77
+ # Transfer missing information
78
+ if (is(input.obj, "Seurat")) {
79
+ tmp_folder <- strsplit(opt$input, "/")[[1]]
80
+ tmp_folder <- tmp_folder[-length(tmp_folder)]
81
+ tmp_folder <- paste(tmp_folder, collapse = "/")
82
+
83
+ # Get Variable Features
84
+ hvg <- VariableFeatures(input.obj)
85
+ if (length(hvg) >0) {
86
+ write.csv(as.data.frame(hvg), paste0(tmp_folder, "/VariableFeatures.csv"))
87
+ }
88
+
89
+ # Get SNN
90
+ assay_name <- names(input.obj@assays)
91
+ graph_names <- names(input.obj@graphs)
92
+ for (assay in graph_names) {
93
+ if (grepl("_snn", assay)) {
94
+ snn <- as.matrix(input.obj@graphs[[assay]])
95
+ data.table::fwrite(snn, paste0(tmp_folder, "/Connectivities.csv")) # Save SNN
96
+ }
97
+ else if (grepl("_nn", assay)) {
98
+ nn <- as.matrix(input.obj@graphs[[assay]])
99
+ data.table::fwrite(nn, paste0(tmp_folder, "/Distances.csv")) # Save NN
100
+ }
101
+ }
102
+ }
103
+
104
+
105
+ } else if (opt$operation == 'write') { # Convert AnnData to RDS
106
+ message("Convert AnnData Object to RDS Object")
107
+ input.obj <- readH5AD(opt$input)
108
+ output.obj <- TransformObjectType(input.obj, opt$type)
109
+
110
+ # Transfer missing information
111
+ if (opt$type == "SeuratObject") {
112
+
113
+ # Rename Assay to RNA
114
+ message("Generating RNA assay")
115
+ assay_name <- names(output.obj@assays)
116
+ output.obj[["RNA"]] <- output.obj[[assay_name]]
117
+ DefaultAssay(output.obj) <- "RNA"
118
+ output.obj[[assay_name]] <- NULL
119
+
120
+ # Replace orig.ident with batch_key
121
+ message("Saving batch information")
122
+ output.obj$orig.ident <- output.obj@meta.data[opt$batch_key]
123
+
124
+ # Transfer other missing elements
125
+ tmp_folder <- strsplit(opt$input, "/")[[1]]
126
+ tmp_folder <- tmp_folder[-length(tmp_folder)]
127
+ tmp_folder <- paste(tmp_folder, collapse = "/")
128
+
129
+ # VariableFeatures
130
+ message("Getting highly variable genes")
131
+ hvg <- tryCatch({
132
+ hvg <- read.csv(paste0(tmp_folder, "/VariableFeatures.csv"))
133
+ hvg <- hvg[hvg$highly_variable == "True", "X"]
134
+ }, error = function(e) {
135
+ message("Error while transfering HVGs: ", e$message)
136
+ return(NULL) })
137
+
138
+ if (!is.null(hvg)) {
139
+ output.obj@assays$RNA@var.features <- hvg
140
+ }
141
+
142
+ # Rename reductions to remove X_ and make lowercase
143
+ message("Renaming reduction assays")
144
+ reductions_names <- names(output.obj@reductions)
145
+ reductions_names_clean <- tolower(sub("^X_", "", reductions_names))
146
+
147
+ for (i in 1:length(reductions_names)) {
148
+ output.obj@reductions[reductions_names_clean[[i]]] <- output.obj@reductions[reductions_names[[i]]]
149
+ output.obj@reductions[reductions_names[[i]]] <- NULL
150
+ }
151
+
152
+ # Connectivities -> snn
153
+ message("Getting SNN Graph")
154
+ snn <- tryCatch({
155
+ connectivities <- data.table::fread(paste0(tmp_folder, "/Connectivities.csv"),
156
+ check.names = FALSE, stringsAsFactors = FALSE)
157
+ connectivities <- as.matrix(connectivities)
158
+
159
+ if ("V1" %in% colnames(connectivities)){
160
+ connectivities$V1 <- NULL
161
+ }
162
+ rownames(connectivities) <- colnames(connectivities)
163
+ connectivities_sparse <- as(connectivities, "dgCMatrix")
164
+ snn <- as.Graph(x = connectivities_sparse)
165
+ slot(snn, name = "assay.used") <- "RNA"
166
+
167
+ snn
168
+
169
+ }, error = function(e) {
170
+ message("Error while transfering SNN Graph: ", e$message)
171
+ return(NULL) })
172
+
173
+ if (!is.null(snn)) {
174
+ output.obj@graphs$RNA_snn <- snn
175
+ }
176
+
177
+ # distances -> nn
178
+ message("Getting NN Graph")
179
+ nn <- tryCatch({
180
+ distances <- data.table::fread(paste0(tmp_folder, "/Distances.csv"), check.names = FALSE,
181
+ stringsAsFactors = FALSE)
182
+ if ("V1" %in% colnames(distances)){
183
+ distances$V1 <- NULL
184
+ }
185
+ distances <- as.matrix(distances)
186
+ rownames(distances) <- colnames(distances)
187
+ distances_sparse <- as(distances, "dgCMatrix")
188
+ nn <- as.Graph(x = distances_sparse)
189
+ slot(nn, name = "assay.used") <- "RNA"
190
+ nn
191
+ }, error = function(e) {
192
+ message("Error while transfering NN Graph: ", e$message)
193
+ return(NULL) })
194
+
195
+ if (!is.null(nn)) {
196
+ output.obj@graphs$RNA_nn <- nn
197
+ }
198
+ }
199
+
200
+ saveRDS(output.obj, opt$out)
201
+ } else {
202
+ stop("Only read and write operations are permitted")
203
+ }
@@ -0,0 +1,116 @@
1
+ #######################################################################################
2
+ # Description: Running MAST test for scRNA-seq from AnnData #
3
+ # #
4
+ # Author: David Rodriguez Morales #
5
+ # Date Created: 08-06-2025 #
6
+ # Date Modified: 08-06-2025 #
7
+ # Version: 1.0 #
8
+ # R Version: 4.3.2 #
9
+ #######################################################################################
10
+
11
+ suppressWarnings(suppressMessages(library(optparse)))
12
+ suppressWarnings(suppressMessages(library(zellkonverter)))
13
+ suppressWarnings(suppressMessages(library(SingleCellExperiment)))
14
+ suppressWarnings(suppressMessages(library(Biobase)))
15
+ suppressWarnings(suppressMessages(library(MAST)))
16
+
17
+
18
+ option_list <- list(
19
+ make_option(c("--input"), type = "character", default = NULL,
20
+ help = "Absolute path to Anndata object (H5AD File)", metavar = "character"),
21
+ make_option(c("--out"), type = "character", default = NULL,
22
+ help = "Absolute path to the directory where the output files will be saved",
23
+ metavar = "character"),
24
+ make_option(c("--key"), type = "character", default = NULL,
25
+ help = "Column name in .obs attribute in the anndata that contains the condition information",
26
+ metavar = "character"),
27
+ make_option(c("--ref"), type = "character", default = NULL,
28
+ help = "Name of reference condition",
29
+ metavar = "character"),
30
+ make_option(c("--disease"), type = "character", default = NULL,
31
+ help = "Name of alternative condition",
32
+ metavar = "character"),
33
+ make_option(c("--covariates"), type = "character", default = NULL,
34
+ help = "Extra column with covariates to consider",
35
+ metavar = "character")
36
+ )
37
+
38
+ opt_parser <- OptionParser(usage = "usage: %prog [options]
39
+
40
+ Perform differential gene expression using the MAST test on an Anndata object and output a
41
+ CSV file with the differentially expressed genes.",
42
+ option_list = option_list)
43
+
44
+ opt <- parse_args(opt_parser)
45
+
46
+ if (is.null(opt$input)) {
47
+ print_help(opt_parser)
48
+ stop("Please provide the specified arguments", call. = FALSE)
49
+ } else if (is.null(opt$out)) {
50
+ print_help(opt_parser)
51
+ stop("Please provide the specified arguments", call. = FALSE)
52
+ } else if (is.null(opt$key)) {
53
+ print_help(opt_parser)
54
+ stop("Please provide the specified arguments", call. = FALSE)
55
+ }else if (is.null(opt$ref)) {
56
+ print_help(opt_parser)
57
+ stop("Please provide the specified arguments", call. = FALSE)
58
+ }else if (is.null(opt$disease)) {
59
+ print_help(opt_parser)
60
+ stop("Please provide the specified arguments", call. = FALSE)
61
+ }
62
+
63
+
64
+ message('Reading AnnData in R')
65
+ sce <- zellkonverter::readH5AD(opt$input)
66
+
67
+ # Re-organise to set reference as first level
68
+ condition <- factor(x = SummarizedExperiment::colData(sce)[[opt$key]])
69
+ condition <- relevel(x = condition, ref = opt$ref)
70
+ sce$condition <- condition
71
+ latent.vars <- c('condition', opt$covariates)
72
+
73
+ # Generate SingleCellAssay for MAST
74
+ sca <- FromMatrix(exprsArray = as.matrix(logcounts(sce)),
75
+ cData = as.data.frame(colData(sce)),
76
+ fData = as.data.frame(rowData(sce))
77
+ )
78
+
79
+ formula <- as.formula(object = paste0(" ~ ", paste(latent.vars, collapse = "+")))
80
+
81
+
82
+ # Run Test
83
+ message('Running MAST Test')
84
+ zlmCond <- MAST::zlm(formula = formula, sca = sca)
85
+ summaryCond <- MAST::summary(object = zlmCond, doLRT = paste0(opt$key, opt$disease))
86
+ summaryDt <- summaryCond$datatable
87
+
88
+ # Generate Results dataframe
89
+ p_val <- as.data.frame(summaryDt[summaryDt[["component"]] == "H", 'Pr(>Chisq)'])
90
+ names(p_val) <- 'pvals'
91
+ genes <- as.data.frame(summaryDt[summaryDt[["component"]] == "H", 1])
92
+ p_val[['padj']] <- p.adjust(p_val$pvals, method = 'fdr')
93
+
94
+
95
+ log1pdata.mean.fxn <- function(x) {return(log(x = (rowSums(x = expm1(x = x)) + 1)/NCOL(x), base = 2))}
96
+ counts_mat <- as.matrix(counts(sce)) # convert to dense matrix if sparse
97
+ logcounts_mat <- as.matrix(logcounts(sce))
98
+ idx1 <- which(condition == opt$ref)
99
+ idx2 <- which(condition == opt$disease)
100
+ mean1 <- log1pdata.mean.fxn(logcounts_mat[,idx1])
101
+ mean2 <- log1pdata.mean.fxn(logcounts_mat[,idx2])
102
+ log2fc <- as.data.frame(mean2 - mean1)
103
+ pct1 <- rowMeans(counts_mat[, idx1, drop=FALSE] > 0)
104
+ pct2 <- rowMeans(counts_mat[, idx2, drop=FALSE] > 0)
105
+
106
+ df <-data.frame(
107
+ names = genes,
108
+ pvals = p_val$pvals,
109
+ log2c = log2fc,
110
+ padj = p_val$padj,
111
+ pts_ref = pct1,
112
+ pts_group = pct2
113
+ )
114
+
115
+ message('Saving DGE Table')
116
+ write.csv(df, opt$out)
File without changes