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.
- dotools_py/__init__.py +33 -0
- dotools_py/_experimental/__init__.py +0 -0
- dotools_py/_experimental/_deprecated/__init__.py +0 -0
- dotools_py/_experimental/_deprecated/_expression.py +761 -0
- dotools_py/_experimental/_deprecated/_language.py +398 -0
- dotools_py/_experimental/_deprecated/_statistics.py +403 -0
- dotools_py/_experimental/gr/__init__.py +0 -0
- dotools_py/_experimental/gr/_generic.py +382 -0
- dotools_py/dt/__init__.py +2 -0
- dotools_py/dt/_datasets.py +112 -0
- dotools_py/dt/_markers.py +150 -0
- dotools_py/dt/example_reduced.h5ad +0 -0
- dotools_py/get/__init__.py +7 -0
- dotools_py/get/_generic.py +626 -0
- dotools_py/logger.py +87 -0
- dotools_py/pl/_Classes.py +358 -0
- dotools_py/pl/_Plotter.py +567 -0
- dotools_py/pl/_StatsPlotter.py +716 -0
- dotools_py/pl/__init__.py +8 -0
- dotools_py/pl/_dotplot.py +2062 -0
- dotools_py/pl/_downstream.py +868 -0
- dotools_py/pl/_embeddings.py +481 -0
- dotools_py/pl/_experimental.py +205 -0
- dotools_py/pl/_expression.py +581 -0
- dotools_py/pl/_heatmap.py +475 -0
- dotools_py/pl/_plot_utils.py +103 -0
- dotools_py/pl/_visium.py +194 -0
- dotools_py/pp/__init__.py +2 -0
- dotools_py/pp/_cellbender.py +179 -0
- dotools_py/pp/_importer.py +583 -0
- dotools_py/settings/__init__.py +1 -0
- dotools_py/settings/_configure.py +185 -0
- dotools_py/settings/_global_parameters.py +16 -0
- dotools_py/tl/_Statistical.py +812 -0
- dotools_py/tl/__init__.py +10 -0
- dotools_py/tl/_analysis.py +772 -0
- dotools_py/tl/_get_stats.py +776 -0
- dotools_py/tl/_rankGenes.py +1112 -0
- dotools_py/util_scripts/_ReadWrite_RDS.R +285 -0
- dotools_py/util_scripts/_run_CCA.R +91 -0
- dotools_py/util_scripts/_run_CellBender.sh +186 -0
- dotools_py/util_scripts/_run_MAST.R +118 -0
- dotools_py/util_scripts/_run_SCTransform.R +60 -0
- dotools_py/util_scripts/_run_edgeR.R +104 -0
- dotools_py/util_scripts/_run_scDblFinder.R +63 -0
- dotools_py/utility/HomoSapiens_GeneMetadata.pickle.gz +0 -0
- dotools_py/utility/MusMusculus_GeneMetadata.pickle.gz +0 -0
- dotools_py/utility/__init__.py +4 -0
- dotools_py/utility/_convertion.py +262 -0
- dotools_py/utility/_general.py +136 -0
- dotools_py/utility/_plotting.py +101 -0
- dotools_py/utility/_spatial.py +64 -0
- dotools_py/utils.py +404 -0
- dotools_py-0.0.2.dist-info/METADATA +225 -0
- dotools_py-0.0.2.dist-info/RECORD +57 -0
- dotools_py-0.0.2.dist-info/WHEEL +4 -0
- dotools_py-0.0.2.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
import shutil
|
|
2
|
+
from typing import Literal
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import anndata as ad
|
|
6
|
+
|
|
7
|
+
from dotools_py import logger
|
|
8
|
+
from dotools_py.utils import convert_path
|
|
9
|
+
|
|
10
|
+
class RDSConverter:
|
|
11
|
+
"""Class to convert between AnnData and Seurat/SCE.
|
|
12
|
+
|
|
13
|
+
This class allows convertion between AnnData, SeuratObject and SingleCellExperiment Object.
|
|
14
|
+
|
|
15
|
+
Parameters
|
|
16
|
+
----------
|
|
17
|
+
input_obj
|
|
18
|
+
The input AnnData Object or the path to an H5AD or RDS Object.
|
|
19
|
+
out_obj
|
|
20
|
+
Format of the output object.
|
|
21
|
+
batch_key
|
|
22
|
+
Column in the AnnData with batch information.
|
|
23
|
+
rds_batch_key
|
|
24
|
+
Column in the Seurat object with batch information.
|
|
25
|
+
path
|
|
26
|
+
The path to the folder where the object will be saved.
|
|
27
|
+
filename
|
|
28
|
+
Name of the output RDS/H5AD file.
|
|
29
|
+
get_anndata
|
|
30
|
+
Whether to return the AnnData or not when using to_h5ad
|
|
31
|
+
|
|
32
|
+
Example
|
|
33
|
+
-------
|
|
34
|
+
|
|
35
|
+
>>> import os
|
|
36
|
+
>>> import dotools_py as do
|
|
37
|
+
>>> os.makedirs("/tmp/Converter", exist_ok=True)
|
|
38
|
+
>>> adata = do.dt.example_10x_processed()
|
|
39
|
+
>>> converter = do.utility.RDSConverter(input_obj=adata, out_obj="seurat", path="/tmp/Converter", filename="adata.rds")
|
|
40
|
+
>>> converter.to_rds()
|
|
41
|
+
>>> os.listdir("/tmp/Converter")
|
|
42
|
+
['adata.rds']
|
|
43
|
+
>>> converter = do.utility.RDSConverter(input_obj="/tmp/Converter/adata.rds", out_obj="anndata")
|
|
44
|
+
>>> adata = converter.to_h5ad()
|
|
45
|
+
>>> adata
|
|
46
|
+
AnnData object with n_obs × n_vars = 700 × 1851
|
|
47
|
+
obs: 'nCount_originalexp', 'nFeature_originalexp', 'batch', 'condition', 'n_genes_by_counts',
|
|
48
|
+
'log1p_n_genes_by_counts', 'total_counts', 'log1p_total_counts', 'total_counts_mt', 'log1p_total_counts_mt',
|
|
49
|
+
'pct_counts_mt', 'total_counts_ribo', 'log1p_total_counts_ribo', 'pct_counts_ribo', 'n_genes', 'n_counts', 'doublet_class', 'doublet_score', 'leiden', 'cell_type', 'autoAnnot', 'celltypist_conf_score', 'annotation', 'annotation_recluster', 'ident'
|
|
50
|
+
var: 'highly_variable'
|
|
51
|
+
uns: 'X_name'
|
|
52
|
+
obsm: 'X_cca', 'X_pca', 'X_umap'
|
|
53
|
+
layers: 'logcounts', 'counts'
|
|
54
|
+
obsp: 'connectivities', 'distances'
|
|
55
|
+
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
def __init__(self,
|
|
59
|
+
input_obj: str | Path | ad.AnnData = None,
|
|
60
|
+
out_obj: Literal["anndata", "seurat", "sce"] = "anndata",
|
|
61
|
+
batch_key: str = "batch",
|
|
62
|
+
rds_batch_key: str = "orig.ident",
|
|
63
|
+
path: str | Path = None,
|
|
64
|
+
filename: str = None,
|
|
65
|
+
get_anndata: bool = True,
|
|
66
|
+
):
|
|
67
|
+
import uuid
|
|
68
|
+
|
|
69
|
+
self.input = input_obj
|
|
70
|
+
self.out = out_obj
|
|
71
|
+
self.batch_key = batch_key
|
|
72
|
+
self.path = convert_path(path) if path is not None else None
|
|
73
|
+
self.filename = filename
|
|
74
|
+
self.orig = rds_batch_key
|
|
75
|
+
self.get_anndata = get_anndata
|
|
76
|
+
|
|
77
|
+
self._infer_input()
|
|
78
|
+
|
|
79
|
+
if self.input_type == "anndata" and not isinstance(self.input, ad.AnnData):
|
|
80
|
+
self.input = ad.read_h5ad(self.input)
|
|
81
|
+
|
|
82
|
+
self._get_hvg_graphs()
|
|
83
|
+
|
|
84
|
+
tmp_folder = Path("/tmp") / f"Convertion_{uuid.uuid4().hex}"
|
|
85
|
+
tmp_folder.mkdir(parents=True, exist_ok=False)
|
|
86
|
+
self.tmp_folder = tmp_folder
|
|
87
|
+
return
|
|
88
|
+
|
|
89
|
+
def __enter__(self):
|
|
90
|
+
from rpy2 import robjects as ro
|
|
91
|
+
ro.r("invisible(gc())")
|
|
92
|
+
return self
|
|
93
|
+
|
|
94
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
95
|
+
from rpy2 import robjects as ro
|
|
96
|
+
import shutil
|
|
97
|
+
import gc
|
|
98
|
+
|
|
99
|
+
# Clean temporary folder if it still exists
|
|
100
|
+
if hasattr(self, "tmp_folder") and self.tmp_folder.exists():
|
|
101
|
+
shutil.rmtree(self.tmp_folder, ignore_errors=True)
|
|
102
|
+
|
|
103
|
+
ro.r("rm(list = ls())")
|
|
104
|
+
ro.r("invisible(gc())")
|
|
105
|
+
gc.collect()
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
return False
|
|
109
|
+
|
|
110
|
+
def _infer_input(self):
|
|
111
|
+
"""Infer the type of the input object.
|
|
112
|
+
|
|
113
|
+
:return: Returns None. The input_type and rds_obj attribute will be set.
|
|
114
|
+
"""
|
|
115
|
+
from rpy2 import robjects as ro
|
|
116
|
+
rds_obj = None
|
|
117
|
+
if isinstance(self.input, ad.AnnData):
|
|
118
|
+
input_type = "anndata"
|
|
119
|
+
elif isinstance(self.input, str) or isinstance(self.input, Path):
|
|
120
|
+
if ".h5ad" in self.input.lower():
|
|
121
|
+
input_type = "anndata"
|
|
122
|
+
elif ".rds" in self.input.lower():
|
|
123
|
+
rds_obj = ro.r["readRDS"](self.input)
|
|
124
|
+
rds_class = str(ro.r['class'](rds_obj)[0])
|
|
125
|
+
input_type = "seurat" if "seurat" == rds_class.lower() else "sce"
|
|
126
|
+
else:
|
|
127
|
+
raise Exception("Provide a valid Path to *.h5ad or *.rds file")
|
|
128
|
+
else:
|
|
129
|
+
raise Exception("Provide a valid input: AnnData Object or Path")
|
|
130
|
+
|
|
131
|
+
self.input_type = input_type
|
|
132
|
+
self.rds_obj = rds_obj
|
|
133
|
+
return
|
|
134
|
+
|
|
135
|
+
def _get_hvg_graphs(self):
|
|
136
|
+
import scipy.sparse as sp
|
|
137
|
+
from rpy2 import robjects as ro
|
|
138
|
+
from rpy2.robjects.packages import importr
|
|
139
|
+
SEURAT_OBJ = importr("SeuratObject")
|
|
140
|
+
|
|
141
|
+
slot = ro.r["slot"]
|
|
142
|
+
as_matrix = ro.r["as.matrix"]
|
|
143
|
+
names = ro.r["names"]
|
|
144
|
+
|
|
145
|
+
hvg, snn, nn = None, None, None
|
|
146
|
+
if self.input_type == "anndata":
|
|
147
|
+
if "distances" in self.input.obsp:
|
|
148
|
+
nn = self.input.obsp["distances"]
|
|
149
|
+
if "connectivities" in self.input.obsp:
|
|
150
|
+
snn = self.input.obsp["connectivities"]
|
|
151
|
+
if "highly_variable" in self.input.var.columns:
|
|
152
|
+
hvg = self.input.var.highly_variable
|
|
153
|
+
hvg = list(hvg[hvg == True].index)
|
|
154
|
+
elif self.input_type == "seurat":
|
|
155
|
+
rds_obj = self.rds_obj
|
|
156
|
+
assays = list(SEURAT_OBJ.Assays(rds_obj)) # Get all Assays
|
|
157
|
+
hvg, snn, nn = [], [], []
|
|
158
|
+
for assay in assays:
|
|
159
|
+
rds_obj = ro.r["DefaultAssay<-"](**{"object": rds_obj, "value": assay})
|
|
160
|
+
if len(hvg) == 0: # Extract HVGs
|
|
161
|
+
hvg = list(SEURAT_OBJ.VariableFeatures(rds_obj))
|
|
162
|
+
neighbors_assays = names(slot(rds_obj, "graphs"))
|
|
163
|
+
if len(neighbors_assays) != 0:
|
|
164
|
+
if assay + "_snn" in neighbors_assays:
|
|
165
|
+
snn = sp.csr_matrix(as_matrix(slot(rds_obj, "graphs").rx2(assay + "_snn")))
|
|
166
|
+
if assay + "_nn" in neighbors_assays:
|
|
167
|
+
nn = sp.csr_matrix(as_matrix(slot(rds_obj, "graphs").rx2(assay + "_nn")))
|
|
168
|
+
else:
|
|
169
|
+
logger.warn("SingleCellExperiment does not contain HighlyVariableFeatures or graphs")
|
|
170
|
+
|
|
171
|
+
self.hvg = hvg
|
|
172
|
+
self.snn = snn
|
|
173
|
+
self.nn = nn
|
|
174
|
+
return
|
|
175
|
+
|
|
176
|
+
def to_h5ad(self) -> ad.AnnData | None:
|
|
177
|
+
from rpy2 import robjects as ro
|
|
178
|
+
from rpy2.robjects.packages import importr
|
|
179
|
+
ZELLKONVERTER = importr("zellkonverter")
|
|
180
|
+
|
|
181
|
+
logger.info("Generating AnnData from RDS")
|
|
182
|
+
|
|
183
|
+
if self.input_type == "seurat": # Convert Seurat to SCE for ZELLKONVERTER
|
|
184
|
+
sce_obj = ro.r["DefaultAssay<-"](**{"object": self.rds_obj, "value": "RNA"})
|
|
185
|
+
as_sce = ro.r["as.SingleCellExperiment"]
|
|
186
|
+
sce_obj = as_sce(sce_obj)
|
|
187
|
+
else:
|
|
188
|
+
sce_obj = self.rds_obj
|
|
189
|
+
|
|
190
|
+
# TODO - Change everything to be self-contained
|
|
191
|
+
ZELLKONVERTER.writeH5AD(sce_obj, str(self.tmp_folder / "adata.h5ad"))
|
|
192
|
+
adata = ad.read_h5ad(self.tmp_folder / "adata.h5ad")
|
|
193
|
+
shutil.rmtree(str(self.tmp_folder))
|
|
194
|
+
|
|
195
|
+
# Add missing information
|
|
196
|
+
logger.info("Transferring HVGs and Graphs")
|
|
197
|
+
if self.hvg is not None:
|
|
198
|
+
adata.var["highly_variable"] = [True if g in self.hvg else False for g in adata.var_names]
|
|
199
|
+
if self.snn is not None:
|
|
200
|
+
adata.obsp["connectivities"] = self.snn
|
|
201
|
+
if self.nn is not None:
|
|
202
|
+
adata.obsp["distances"] = self.nn
|
|
203
|
+
|
|
204
|
+
# Rename reductions
|
|
205
|
+
for key in [key for key in adata.obsm.keys()]:
|
|
206
|
+
new_key = "X_" + key.lower().replace(".", "_").replace("-", "_")
|
|
207
|
+
adata.obsm[new_key] = adata.obsm[key].values
|
|
208
|
+
del adata.obsm[key]
|
|
209
|
+
|
|
210
|
+
# Rename orig.ident if present
|
|
211
|
+
if self.orig in list(adata.obs.columns):
|
|
212
|
+
logger.info(f"Renaming orig.ident to {self.batch_key}")
|
|
213
|
+
adata.obs[self.batch_key] = adata.obs[self.orig].copy()
|
|
214
|
+
del adata.obs[self.orig]
|
|
215
|
+
|
|
216
|
+
# Default is X with raw counts
|
|
217
|
+
if all(adata.X.data % 1 == 0):
|
|
218
|
+
adata.layers["counts"] = adata.X.copy()
|
|
219
|
+
|
|
220
|
+
if self.path is not None:
|
|
221
|
+
assert self.filename is not None, "Provide a filename"
|
|
222
|
+
adata.write(self.path / self.filename)
|
|
223
|
+
|
|
224
|
+
if self.get_anndata:
|
|
225
|
+
return adata
|
|
226
|
+
else:
|
|
227
|
+
return None
|
|
228
|
+
|
|
229
|
+
def to_rds(self):
|
|
230
|
+
from rpy2 import robjects as ro
|
|
231
|
+
from rpy2.robjects import pandas2ri
|
|
232
|
+
from rpy2.robjects import StrVector
|
|
233
|
+
from rpy2.robjects.packages import importr
|
|
234
|
+
SEURAT_OBJ = importr("SeuratObject")
|
|
235
|
+
ZELLKONVERTER = importr("zellkonverter")
|
|
236
|
+
SEURAT = importr("Seurat")
|
|
237
|
+
|
|
238
|
+
assert self.path is not None, "Convertion to RDS without providing path and filename for the output"
|
|
239
|
+
|
|
240
|
+
as_seurat = ro.r["as.Seurat"]
|
|
241
|
+
slot = ro.r["slot"]
|
|
242
|
+
names = ro.r["names"]
|
|
243
|
+
get_item = ro.r["[["]
|
|
244
|
+
|
|
245
|
+
set_col = ro.r["$<-"]
|
|
246
|
+
|
|
247
|
+
if self.rds_obj is None:
|
|
248
|
+
# We come from AnnData
|
|
249
|
+
self.input.write(self.tmp_folder / "adata.h5ad")
|
|
250
|
+
self.input = None # Clean Memory
|
|
251
|
+
sce_obj = ZELLKONVERTER.readH5AD(str(self.tmp_folder / "adata.h5ad"))
|
|
252
|
+
shutil.rmtree(str(self.tmp_folder))
|
|
253
|
+
|
|
254
|
+
if self.out == "seurat":
|
|
255
|
+
logger.info(f"Generating Seurat from AnnData")
|
|
256
|
+
|
|
257
|
+
# Rename Assay to RNA
|
|
258
|
+
seu_obj = SEURAT_OBJ.as_Seurat(sce_obj)
|
|
259
|
+
del sce_obj
|
|
260
|
+
|
|
261
|
+
old_assay_name = list(SEURAT_OBJ.Assays(seu_obj))[0] # Should only contain one assay
|
|
262
|
+
if old_assay_name != "RNA":
|
|
263
|
+
assay_obj = get_item(seu_obj, old_assay_name)
|
|
264
|
+
seu_obj = self._set_item(seu_obj, "RNA", assay_obj)
|
|
265
|
+
seu_obj = ro.r["DefaultAssay<-"](**{"object": seu_obj, "value": "RNA"})
|
|
266
|
+
seu_obj = self._set_item(seu_obj, old_assay_name, ro.NULL)
|
|
267
|
+
|
|
268
|
+
# Replace orig.ident with batch_key
|
|
269
|
+
meta_data = slot(seu_obj, "meta.data")
|
|
270
|
+
batch_column = get_item(meta_data, self.batch_key)
|
|
271
|
+
meta_data = set_col(meta_data, self.orig, batch_column)
|
|
272
|
+
seu_obj = self._set_slot(seu_obj, "meta.data", meta_data)
|
|
273
|
+
|
|
274
|
+
# Add HVG
|
|
275
|
+
logger.info("Transferring HVGs")
|
|
276
|
+
if self.hvg is not None:
|
|
277
|
+
hvg_r = StrVector(self.hvg)
|
|
278
|
+
rna_assay = self._set_slot(slot(seu_obj, "assays").rx2("RNA"), "var.features", hvg_r)
|
|
279
|
+
assays = slot(seu_obj, "assays")
|
|
280
|
+
assays[0] = rna_assay
|
|
281
|
+
seu_obj = self._set_slot(seu_obj, "assays", assays)
|
|
282
|
+
|
|
283
|
+
# Rename reductions to remove X_ and make lowercase
|
|
284
|
+
reductions = slot(seu_obj, "reductions")
|
|
285
|
+
reduction_names = names(reductions)
|
|
286
|
+
reduction_names_py = [str(n) for n in reduction_names]
|
|
287
|
+
clean_names = [ro.r["tolower"](ro.r["sub"]("^X_", "", n))[0] for n in reduction_names_py]
|
|
288
|
+
for old_name, new_name in zip(reduction_names_py, clean_names):
|
|
289
|
+
reduction_obj = get_item(reductions, old_name)
|
|
290
|
+
reductions = self._set_item(reductions, new_name, reduction_obj)
|
|
291
|
+
reductions = self._set_item(reductions, old_name, ro.NULL)
|
|
292
|
+
seu_obj = self._set_slot(seu_obj, "reductions", reductions)
|
|
293
|
+
|
|
294
|
+
# Add graphs
|
|
295
|
+
logger.info("Transferring Graphs")
|
|
296
|
+
if self.snn is not None and self.nn is not None:
|
|
297
|
+
snn_graph = self._csr_to_seurat_graph(self.snn, seu_obj, assay_used="RNA")
|
|
298
|
+
nn_graph = self._csr_to_seurat_graph(self.nn, seu_obj, assay_used="RNA")
|
|
299
|
+
graphs = slot(seu_obj, "graphs")
|
|
300
|
+
graphs = self._set_item(graphs, "RNA_snn", snn_graph)
|
|
301
|
+
graphs = self._set_item(graphs, "RNA_nn", nn_graph)
|
|
302
|
+
obj_to_save = self._set_slot(seu_obj, "graphs", graphs)
|
|
303
|
+
else:
|
|
304
|
+
obj_to_save = seu_obj
|
|
305
|
+
elif self.out == "sce":
|
|
306
|
+
logger.info(f"Generating SCE from AnnData")
|
|
307
|
+
obj_to_save = sce_obj
|
|
308
|
+
else:
|
|
309
|
+
raise Exception("Save to_rds but output format is anndata")
|
|
310
|
+
else:
|
|
311
|
+
if self.input_type == "sce":
|
|
312
|
+
logger.info(f"Generating Seurat from SCE")
|
|
313
|
+
obj_to_save = as_seurat(self.rds_obj)
|
|
314
|
+
else:
|
|
315
|
+
raise Exception("Input Object is already a Seurat Object")
|
|
316
|
+
|
|
317
|
+
ro.r["saveRDS"](obj_to_save, str(self.path / self.filename))
|
|
318
|
+
del seu_obj
|
|
319
|
+
del obj_to_save
|
|
320
|
+
return
|
|
321
|
+
|
|
322
|
+
@staticmethod
|
|
323
|
+
def _csr_to_seurat_graph(csr, seu_obj, assay_used="RNA"):
|
|
324
|
+
from rpy2 import robjects as ro
|
|
325
|
+
from rpy2.robjects import pandas2ri, numpy2ri, IntVector, FloatVector, StrVector
|
|
326
|
+
from rpy2.robjects.packages import importr
|
|
327
|
+
import scipy.sparse as sp
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
Matrix = importr("Matrix") # imports Matrix package
|
|
331
|
+
|
|
332
|
+
as_graph = ro.r["as.Graph"]
|
|
333
|
+
|
|
334
|
+
if not hasattr(csr, "tocsc"):
|
|
335
|
+
csr = sp.csr_matrix(csr.values)
|
|
336
|
+
|
|
337
|
+
coo = csr.tocoo()
|
|
338
|
+
|
|
339
|
+
with ro.conversion.localconverter(ro.default_converter + pandas2ri.converter + numpy2ri.converter):
|
|
340
|
+
i_r = IntVector(coo.row + 1)
|
|
341
|
+
j_r = IntVector(coo.col + 1)
|
|
342
|
+
x_r = FloatVector(coo.data)
|
|
343
|
+
dims_r = IntVector(csr.shape)
|
|
344
|
+
|
|
345
|
+
ro.r.assign("seu_obj", seu_obj)
|
|
346
|
+
ro.r("cell_barcodes <- colnames(seu_obj)")
|
|
347
|
+
cell_barcodes = ro.r("cell_barcodes")
|
|
348
|
+
|
|
349
|
+
r_dgc = Matrix.sparseMatrix(
|
|
350
|
+
i=i_r,
|
|
351
|
+
j=j_r,
|
|
352
|
+
x=x_r,
|
|
353
|
+
dims=dims_r,
|
|
354
|
+
giveCsparse=True
|
|
355
|
+
)
|
|
356
|
+
ro.r.assign("r_dgc", r_dgc)
|
|
357
|
+
ro.r.assign("rownames", StrVector(cell_barcodes))
|
|
358
|
+
ro.r.assign("colnames", StrVector(cell_barcodes))
|
|
359
|
+
ro.r("dimnames(r_dgc) <- list(rownames, colnames)")
|
|
360
|
+
r_dgc = ro.r("r_dgc") # retrieve back with dimnames
|
|
361
|
+
|
|
362
|
+
graph = as_graph(x = r_dgc)
|
|
363
|
+
graph = RDSConverter._set_slot(graph, "assay.used", ro.StrVector([assay_used]))
|
|
364
|
+
return graph
|
|
365
|
+
|
|
366
|
+
@staticmethod
|
|
367
|
+
def _set_item(obj, key, value):
|
|
368
|
+
import rpy2.robjects as ro
|
|
369
|
+
ro.globalenv["obj"] = obj
|
|
370
|
+
ro.globalenv["key"] = key
|
|
371
|
+
ro.globalenv["value"] = value
|
|
372
|
+
ro.r("obj[[key]] <- value")
|
|
373
|
+
return ro.r("obj")
|
|
374
|
+
|
|
375
|
+
@staticmethod
|
|
376
|
+
def _set_slot(obj, slot_name, value):
|
|
377
|
+
import rpy2.robjects as ro
|
|
378
|
+
from rpy2.robjects import pandas2ri
|
|
379
|
+
"""Safely set an S4 slot in R (e.g., Seurat@meta.data)."""
|
|
380
|
+
|
|
381
|
+
# Handle None as R NULL
|
|
382
|
+
if value is None:
|
|
383
|
+
ro.r.assign("obj", obj)
|
|
384
|
+
ro.r.assign("slot_name", slot_name)
|
|
385
|
+
ro.r("slot(obj, slot_name) <- NULL")
|
|
386
|
+
return ro.r("obj")
|
|
387
|
+
|
|
388
|
+
# Convert pandas DataFrame or NumPy arrays to R equivalents
|
|
389
|
+
with ro.conversion.localconverter(ro.default_converter + pandas2ri.converter):
|
|
390
|
+
value_r = ro.conversion.py2rpy(value)
|
|
391
|
+
|
|
392
|
+
# Assign into R environment and set slot safely via R code
|
|
393
|
+
ro.r.assign("obj", obj)
|
|
394
|
+
ro.r.assign("slot_name", slot_name)
|
|
395
|
+
ro.r.assign("value_r", value_r)
|
|
396
|
+
ro.r("slot(obj, slot_name) <- value_r")
|
|
397
|
+
|
|
398
|
+
return ro.r("obj")
|