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,626 @@
1
+ from typing import Literal
2
+
3
+ import anndata as ad
4
+ import pandas as pd
5
+ import numpy as np
6
+ from numba import njit
7
+
8
+ from dotools_py import logger
9
+ from dotools_py.utility._general import free_memory
10
+ from dotools_py.utils import sanitize_anndata, iterase_input, check_missing
11
+ from dotools_py.settings._global_parameters import FAST_ARRAY_UTILS
12
+
13
+ if FAST_ARRAY_UTILS:
14
+ import fast_array_utils
15
+
16
+
17
+ def _expm1_anndata(adata: ad.AnnData) -> None:
18
+ """Apply expm1 transformation for the X data.
19
+
20
+ :param adata: annotated data matrix
21
+ :return: None, changes are inplace
22
+ """
23
+ import scipy as sp
24
+
25
+ if sp.sparse.issparse(adata.X):
26
+ adata.X = adata.X.copy()
27
+ adata.X.data = np.expm1(adata.X.data)
28
+ else:
29
+ adata.X = np.expm1(adata.X)
30
+
31
+
32
+ def expr(
33
+ adata: ad.AnnData,
34
+ features: str | list,
35
+ groups: str | list | None = None,
36
+ out_format: Literal["long", "wide"] = "long",
37
+ layer: str | None = None,
38
+ ) -> pd.DataFrame:
39
+ """Extract the expression of features.
40
+
41
+ This function extract the expression from an AnnData object and returns a DataFrame. If layer
42
+ is not specified the expression in `X` will be extracted. Additionally, metadata from `obs` can be added
43
+ to the dataframe.
44
+
45
+ :param adata: Annotated data matrix.
46
+ :param groups: Metadata column in `obs` to include in the DataFrame.
47
+ :param features: Name of the features in `var_names` to extract the expression of.
48
+ :param out_format: Format of the dataframe. The `wide` format will generate a DataFrame with shape n_obs x n_vars,
49
+ while the `long` format will generate an unpivot version.
50
+ :param layer: Layer in the AnnData object to extract the expression from. If set to `None` the expression in
51
+ `X` will be used.
52
+
53
+ Returns
54
+ -------
55
+ Returns a `DataFrame`. If `out_format` is set to `wide`, the index will be the cell barcodes and the column names
56
+ will be set to the gene names. If `groups` are specified, extra columns will be present. If `out_format` is set to
57
+ `long`, the following fields are included:
58
+
59
+ `genes`
60
+ Contains the gene names.
61
+ `expr`
62
+ Contains the expression values extracted.
63
+
64
+ Example
65
+ -------
66
+ >>> import dotools_py as do
67
+ >>> adata = do.dt.example_10x_processed()
68
+ >>> df = do.get.expr(adata, "CD4", "annotation")
69
+ >>> df.head(5)
70
+ annotation genes expr
71
+ 0 B_cells CD4 0.0
72
+ 1 NK CD4 0.0
73
+ 2 T_cells CD4 0.0
74
+ 3 T_cells CD4 0.0
75
+ 4 T_cells CD4 0.0
76
+ >>> df = do.get.expr(adata, "CD4", "annotation", out_format="wide")
77
+ >>> df.head(5)
78
+ CD4 annotation
79
+ CAAAGAATCAGATTGC-1-batch2 0.0 B_cells
80
+ AGCTTCCCAGTCAACT-1-batch1 0.0 NK
81
+ GAGAGGTTCCCTCTAG-1-batch1 0.0 T_cells
82
+ CTAACTTCAGATCATC-1-batch1 0.0 T_cells
83
+ CATGGTACAAACGGCA-1-batch1 0.0 T_cells
84
+
85
+ """
86
+ sanitize_anndata(adata)
87
+ features = iterase_input(features)
88
+ groups = iterase_input(groups)
89
+ assert len(features) != 0, "No features provided"
90
+ assert out_format == "wide" or out_format == "long", f'{out_format} not recognize, try "long" or "wide"'
91
+
92
+ # Remove features not present and warn
93
+ check_missing(adata, features=features, groups=groups)
94
+
95
+ # Set-up configuration
96
+ adata = adata[:, features] # Retain only the specified features
97
+ if layer is not None:
98
+ adata.X = adata.layers[layer].copy() # Select the specified layer
99
+
100
+ # Extract expression
101
+ table_expr = adata.to_df().copy()
102
+
103
+ # Add Metadata
104
+ if groups is not None:
105
+ table_expr[groups] = adata.obs[groups]
106
+ if out_format == "long":
107
+ table_expr = pd.melt(table_expr, id_vars=groups, var_name="genes", value_name="expr")
108
+ free_memory()
109
+ return table_expr
110
+
111
+
112
+ def mean_expr(
113
+ adata: ad.AnnData,
114
+ group_by: str | list,
115
+ features: list | str | None = None,
116
+ out_format: Literal["long", "wide"] = "long",
117
+ layer: str | None = None,
118
+ logcounts: bool = True,
119
+ ) -> pd.DataFrame:
120
+ """Calculate the average expression in an AnnData objects for features.
121
+
122
+ This function calculates the average expression of a set of features grouping by one
123
+ or several categories. Assume log-normalised counts. If logcounts is set to True, the
124
+ log10 transformation is undone for the mean expression calculation. The reported mean
125
+ expression is log-transformed.
126
+
127
+ :param adata: Annotated data matrix.
128
+ :param group_by: Metadata columns in `obs` to group by.
129
+ :param features: List of features in `var_name` to use. If not set, it will be calculated over all the genes.
130
+ :param out_format: Format of the Dataframe returned. This can be wide or long format.
131
+ :param layer: Layer of the AnnData to use. If not set use `X`.
132
+ :param logcounts: Set to `True` if the input is in log space.
133
+
134
+ Returns
135
+ -------
136
+ Returns a `DataFrame` with the mean expression in log1p transformation. If `out_format` is set to `wide`, the index
137
+ will be set to the gene names and the column names will be set to the groups. If `out_format` is set to `long`,
138
+ the following fields are included:
139
+
140
+ `gene`
141
+ Contains the gene names.
142
+ `groupN`
143
+ Contains the groups (For each metadata column a new column will be added).
144
+ `expr`
145
+ Contains the mean expression values after log1p transformation.
146
+
147
+ Example
148
+ -------
149
+ >>> import dotools_py as do
150
+ >>> adata = do.dt.example_10x_processed()
151
+ >>> df = do.get.mean_expr(adata, "annotation")
152
+ >>> df.head(5)
153
+ gene group0 expr
154
+ 0 ATP2A1-AS1 B_cells 0.000000
155
+ 1 STK17A B_cells 1.453713
156
+ 2 C19orf18 B_cells 0.000000
157
+ 3 TPP2 B_cells 0.126846
158
+ 4 MFSD1 B_cells 0.053630
159
+ >>> df = do.get.mean_expr(adata, "annotation", out_format="wide")
160
+ >>> df.head(5)
161
+ group0 B_cells Monocytes NK T_cells pDC
162
+ gene
163
+ A4GALT 0.222505 0.000000 0.000000 0.000000 0.000000
164
+ AAK1 0.000000 0.364976 1.126293 1.143016 0.128019
165
+ ABAT 0.182251 0.146378 0.047404 0.045826 0.158761
166
+ ABCB4 0.062785 0.000000 0.000000 0.000000 0.000000
167
+ ABCB9 0.000000 0.000000 0.027683 0.057814 0.000000
168
+
169
+ """
170
+
171
+ sanitize_anndata(adata)
172
+ features = list(adata.var_names) if len(iterase_input(features)) == 0 else iterase_input(features)
173
+ group_by = iterase_input(group_by)
174
+ check_missing(adata, features=features, groups=group_by)
175
+ assert out_format == "wide" or out_format == "long", f'{out_format} not recognize, try "long" or "wide"'
176
+
177
+ # Set-up configuration
178
+ adata = adata[:, features]
179
+ if layer is not None:
180
+ adata.X = adata.layers[layer].copy()
181
+
182
+ data = adata.copy()
183
+
184
+ if logcounts:
185
+ _expm1_anndata(data)
186
+
187
+ # Group data by the specified values
188
+ group_obs = adata.obs.groupby(group_by, as_index=False)
189
+
190
+ # Compute AverageExpression
191
+ main_df = pd.DataFrame([])
192
+ for group_name, df in group_obs:
193
+ if FAST_ARRAY_UTILS:
194
+ current_mean = fast_array_utils.stats.mean(data[df.index].X, axis=0)
195
+ current_mean = np.log1p(current_mean) if logcounts else current_mean
196
+ df_tmp = pd.DataFrame(current_mean, columns=["expr"])
197
+ else:
198
+ if logcounts:
199
+ df_tmp = np.log1p(
200
+ pd.DataFrame(data[df.index].X.mean(axis=0).T, columns=["expr"])
201
+ ) # Mean expr per gene in groupN
202
+ else:
203
+ df_tmp = pd.DataFrame(data[df.index].X.mean(axis=0).T, columns=["expr"])
204
+
205
+ df_tmp["gene"] = adata[df.index].var_names # Update with Gene names
206
+ group_name = iterase_input(group_name)
207
+ for idx, name in enumerate(group_name):
208
+ # df_tmp["group" + str(idx)] = str(name).replace("-", "_") # Update with metadata
209
+ df_tmp[group_by[idx]] = name
210
+ main_df = pd.concat([main_df, df_tmp], axis=0)
211
+ main_df["expr"] = pd.to_numeric(main_df["expr"]) # Convert to numeric values
212
+
213
+ # Move expr column to last position
214
+ expr_col = main_df.pop("expr")
215
+ main_df["expr"] = expr_col
216
+
217
+ # Change to wide format
218
+ if out_format == "wide":
219
+ main_df = pd.pivot_table(main_df, index="gene", columns=group_by, values="expr")
220
+ if len(group_by) > 1:
221
+ main_df.columns = main_df.columns.map("_".join)
222
+ free_memory()
223
+ return main_df
224
+
225
+
226
+ def dge_results(
227
+ adata: ad.AnnData,
228
+ key: str = "rank_genes_groups",
229
+ ) -> pd.DataFrame:
230
+ """Extract DEGs from AnnData object.
231
+
232
+ This function extract the results of the differential gene expression analysis results from the `uns`
233
+ attribute of an AnnData object.
234
+
235
+ :param adata: Annotated data matrix.
236
+ :param key: Key in `uns` with DGE results.
237
+
238
+ Returns
239
+ -------
240
+ Returns a DataFrame with the results of the differential gene expression analysis generated from
241
+ `rank_genes_groups`.
242
+
243
+ Example
244
+ -------
245
+ >>> import dotools_py as do
246
+ >>> adata = do.dt.example_10x_processed()
247
+ >>> do.tl.rank_genes_groups(adata, groupby="condition")
248
+ >>> df = do.get.dge_results(adata)
249
+ >>> df.head(5)
250
+ group GeneName wilcox_score ... padj pts_group pts_ref
251
+ 0 disease ZNF331 15.936105 ... 6.586861e-54 0.650000 0.096154
252
+ 1 disease EZR 15.871257 ... 9.274798e-54 0.866667 0.367308
253
+ 2 disease EIF1 14.823599 ... 6.361829e-47 0.994444 0.994231
254
+ 3 disease SRGN 14.721976 ... 2.155706e-46 0.922222 0.636538
255
+ 4 disease EGR1 12.330428 ... 1.916262e-32 0.316667 0.011538
256
+ [5 rows x 8 columns]
257
+
258
+ """
259
+ import scanpy as sc
260
+
261
+ update_columns = {
262
+ "names": "GeneName",
263
+ "scores": "statistic",
264
+ # U1 from formula, higher absolute indicate lower p-value; High score indicate high expression
265
+ "pvals": "pvals",
266
+ "group": "group",
267
+ "logfoldchanges": "log2fc",
268
+ "pvals_adj": "padj",
269
+ "pct_nz_group": "pts_group",
270
+ "pct_nz_reference": "pts_ref",
271
+ }
272
+
273
+ df_results = sc.get.rank_genes_groups_df(adata, group=None, key=key)
274
+ df_results.columns = [update_columns[col] for col in df_results.columns]
275
+ try:
276
+ if "pts_ref" not in df_results.columns:
277
+ result = adata.uns[key]
278
+ ref = result["params"]["reference"]
279
+ pts_ref = result["pts"][ref]
280
+ if "group" in df_results.columns and len(df_results.group.unique()) > 1:
281
+ df_results["pts_ref"] = df_results["GeneName"].map(pts_ref)
282
+ else:
283
+ df_results["pts_ref"] = pts_ref.reindex(index=df_results.GeneName).tolist()
284
+ except KeyError as e:
285
+ logger.warn(f"Problem generating the DGE Table: {e}")
286
+ return df_results
287
+
288
+
289
+ def subset(adata: ad.AnnData,
290
+ obs_key: str | None = None,
291
+ obs_groups: str | list | float | bool | None = None,
292
+ var_key: str | None = None,
293
+ var_groups: str | list | float | bool | None = None,
294
+ comparison: Literal[">=", ">", "==", "<", "<=", "include", "exclude"] = "include",
295
+ copy: bool = False) -> ad.AnnData:
296
+ """Subset AnnData object.
297
+
298
+ Subset an AnnData object based on `obs` or `var` column. Currently it does not allow to subset
299
+ by multiple obs/var columns at the same time.
300
+
301
+ :param adata: AnnData Object.
302
+ :param obs_key: Column in `obs` to subset for.
303
+ :param obs_groups: Groups or values to include or filter for the AnnData object.
304
+ :param var_key: Column in `var` to subset for.
305
+ :param var_groups: Groups or values to include or filter for in the AnnData object.
306
+ :param comparison: Method to filter the AnnData object.
307
+ :param copy: if set to `True`, a copy is returned, otherwise a view of the AnnData is returned.
308
+ :return: Returns a view or a new AnnData object.
309
+
310
+ Returns
311
+ -------
312
+ Returns an AnnData Object if copy is set to `True`, otherwise returns a View of an AnnData after subsetting.
313
+
314
+ Example
315
+ -------
316
+ >>> import dotools_py as do
317
+ >>> adata = do.dt.example_10x_processed()
318
+ >>> tcells = do.get.subset(adata, obs_key="annotation", obs_groups="T_cells")
319
+ >>> tcells
320
+ View of AnnData object with n_obs × n_vars = 464 × 1851
321
+ obs: 'batch', 'condition', 'n_genes_by_counts', 'log1p_n_genes_by_counts', 'total_counts', 'log1p_total_counts', 'total_counts_mt', 'log1p_total_counts_mt', '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'
322
+ var: 'mean', 'std', 'highly_variable', 'means', 'dispersions', 'dispersions_norm', 'highly_variable_nbatches', 'highly_variable_intersection'
323
+ uns: 'annotation_colors', 'annotation_recluster_colors', 'batch_colors', 'hvg', 'leiden', 'leiden_colors', 'log1p', 'neighbors', 'pca', 'umap'
324
+ obsm: 'X_CCA', 'X_pca', 'X_umap'
325
+ varm: 'PCs'
326
+ layers: 'counts', 'logcounts'
327
+ obsp: 'connectivities', 'distances'
328
+ >>> adata_subset = do.get.subset(adata, obs_key="total_counts", obs_groups=1000, comparison=">=", copy=True)
329
+ >>> adata_subset
330
+ AnnData object with n_obs × n_vars = 699 × 1851
331
+ obs: 'batch', 'condition', 'n_genes_by_counts', 'log1p_n_genes_by_counts', 'total_counts', 'log1p_total_counts', 'total_counts_mt', 'log1p_total_counts_mt', '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'
332
+ var: 'mean', 'std', 'highly_variable', 'means', 'dispersions', 'dispersions_norm', 'highly_variable_nbatches', 'highly_variable_intersection'
333
+ uns: 'annotation_colors', 'annotation_recluster_colors', 'batch_colors', 'hvg', 'leiden', 'leiden_colors', 'log1p', 'neighbors', 'pca', 'umap'
334
+ obsm: 'X_CCA', 'X_pca', 'X_umap'
335
+ varm: 'PCs'
336
+ layers: 'counts', 'logcounts'
337
+ obsp: 'connectivities', 'distances'
338
+
339
+ """
340
+ import operator
341
+
342
+ sanitize_anndata(adata)
343
+ check_missing(adata, groups=obs_key, variables=var_key)
344
+ assert comparison in [">=", ">", "==", "<", "<=", "include", "exclude"], "Not a valid comparison key"
345
+
346
+ if comparison in ["include", "exclude"]:
347
+ obs_groups = iterase_input(obs_groups)
348
+ var_groups = iterase_input(var_groups)
349
+
350
+ operations = {"==": operator.eq, "!=": operator.ne,
351
+ ">": operator.gt, ">=": operator.ge,
352
+ "<": operator.lt, "<=": operator.le}
353
+
354
+ # Subset by obs
355
+ if obs_key is not None:
356
+ if comparison == "exclude":
357
+ adata = adata[~adata.obs[obs_key].isin(obs_groups)]
358
+ elif comparison == "include":
359
+ adata = adata[adata.obs[obs_key].isin(obs_groups)]
360
+ else:
361
+ mask = operations[comparison](adata.obs[obs_key], obs_groups).values
362
+ adata = adata[mask, :]
363
+
364
+ # Subset by var
365
+ if var_key is not None:
366
+ if comparison == "exclude":
367
+ adata = adata[:, ~adata.var[var_key].isin(var_groups)]
368
+ elif comparison == "include":
369
+ adata = adata[:, adata.var[var_key].isin(var_groups)]
370
+ else:
371
+ mask = operations[comparison](adata.var[var_key], var_groups).values
372
+ adata = adata[:, mask]
373
+ if copy:
374
+ return adata.copy()
375
+ else:
376
+ return adata
377
+
378
+
379
+ @njit(parallel=True)
380
+ def _get_log2fc(group: np.ndarray, ref: np.ndarray, psc=1e-9):
381
+ return np.log2((np.expm1(group) + psc) / (np.expm1(ref) + psc))
382
+
383
+
384
+ def log2fc(
385
+ adata: ad.AnnData,
386
+ group_by: str,
387
+ reference: str,
388
+ groups: str | list | None = None,
389
+ features: str | list | None = None,
390
+ layer: str | None = None,
391
+ ) -> pd.DataFrame:
392
+ """Calculate the log2foldchanges for a set of groups.
393
+
394
+ :param adata: Annotated data matrix.
395
+ :param group_by: Column in `obs` to group by.
396
+ :param reference: Reference condition to use for the calculation.
397
+ :param groups: Alternative condititons to use. If `None`, all the condititons will be used.
398
+ :param features: Features to use for calculating the log2foldchanges. If set to `None` all features will be used.
399
+ :param layer: Layer in the AnnData to use for the calculation.
400
+
401
+ Returns
402
+ -------
403
+ Returns a DataFrame with the log2-foldchanges. One column will be added for each condition in `groups`
404
+
405
+ Example
406
+ -------
407
+ >>> import dotools_py as do
408
+ >>> adata = do.dt.example_10x_processed()
409
+ >>> df = do.get.log2fc(adata, group_by="condition", reference="healthy")
410
+ >>> df.head(5)
411
+ genes log2fc_disease
412
+ 0 ATP2A1-AS1 26.073313
413
+ 1 STK17A -0.429677
414
+ 2 C19orf18 0.775196
415
+ 3 TPP2 -22.599501
416
+ 4 MFSD1 -1.669137
417
+
418
+ """
419
+
420
+ # Get the data
421
+ features = iterase_input(features)
422
+ features = list(adata.var_names) if len(iterase_input(features)) == 0 else iterase_input(features)
423
+ groups = list(adata.obs[group_by].unique()) if len(iterase_input(groups)) == 0 else iterase_input(groups)
424
+ if reference in groups:
425
+ groups.remove(reference)
426
+
427
+ df_mean = mean_expr(adata, group_by=group_by, features=features, out_format="wide", layer=layer)
428
+
429
+ logfoldchanges = pd.DataFrame([], index=features)
430
+ for group in groups:
431
+ # Speed up with numba
432
+ foldchanges = _get_log2fc(group=df_mean[group].to_numpy(), ref=df_mean[reference].to_numpy())
433
+ logfoldchanges["log2fc_" + group] = foldchanges
434
+ logfoldchanges.reset_index(inplace=True)
435
+ logfoldchanges.rename(columns={"index": "genes"}, inplace=True)
436
+ return logfoldchanges
437
+
438
+
439
+ def pcts_cells(
440
+ adata,
441
+ group_by: str | list,
442
+ features: str | list = None,
443
+ min_expr: float = 0.0,
444
+ ) -> pd.DataFrame:
445
+ """Calculate the percentage of cells that express a feature.
446
+
447
+ :param adata: Annotated data matrix.
448
+ :param group_by: Column in `obs` to group by. Several columns can be provided.
449
+ :param features: Features to use for the calculation. If set to `None`, all features will be used.
450
+ :param min_expr: Minimum value to use for the estimation of percentages.
451
+
452
+ Returns
453
+ -------
454
+ Returns a DataFrame with the percentage of cells expressing a feature in each group.
455
+
456
+ Example
457
+ -------
458
+ >>> import dotools_py as do
459
+ >>> adata = do.dt.example_10x_processed()
460
+ >>> df = do.get.pcts_cells(adata, group_by=["condition", "annotation"])
461
+ >>> df.head(5)
462
+ genes disease_B_cells ... healthy_T_cells healthy_pDC
463
+ 0 ATP2A1-AS1 0.00 ... 0.01 0.00
464
+ 1 STK17A 0.57 ... 0.49 0.17
465
+ 2 C19orf18 0.00 ... 0.00 0.00
466
+ 3 TPP2 0.03 ... 0.18 0.17
467
+ 4 MFSD1 0.03 ... 0.06 0.50
468
+ [5 rows x 11 columns]
469
+
470
+ """
471
+ features = list(adata.var_names) if len(iterase_input(features)) == 0 else iterase_input(features)
472
+ group_by = iterase_input(group_by)
473
+ df_expr = expr(
474
+ adata, features=features, groups=group_by, out_format="wide"
475
+ ).set_index(group_by)
476
+
477
+ obs_bool = df_expr > min_expr
478
+ df_pct = (
479
+ obs_bool.groupby(level=group_by, observed=True).sum()
480
+ / obs_bool.groupby(level=group_by, observed=True).count()
481
+ ).T
482
+ if len(group_by) > 1:
483
+ df_pct.columns = ["_".join(col) for col in list(df_pct.columns)]
484
+ df_pct = df_pct.round(4)
485
+ df_pct.reset_index(inplace=True)
486
+ df_pct.rename(columns={"index": "genes"}, inplace=True)
487
+ return df_pct
488
+
489
+
490
+ def pseudobulk(
491
+ adata: ad.AnnData,
492
+ batch_key: str,
493
+ cluster_key: str,
494
+ keep_metadata: list = None,
495
+ min_cells: int = 10,
496
+ pseudobulk_approach: Literal["sum", "mean"] = "sum",
497
+ technical_replicates: int = 1,
498
+ min_counts: int = 10,
499
+ layer: str = None,
500
+ workers: int = 5,
501
+ ) -> ad.AnnData:
502
+ """Generate pseudobulk AnnData of clusters.
503
+
504
+ Generate a pseudobulk AnnData for each cluster, the input is expected to be raw counts. To generate
505
+ the pseudobulk AnnData object two modes for aggregating the counts can be used: `sum` or `mean`. Additionally,
506
+ pseudo-replicates can be generated if specified.
507
+
508
+ :param adata: Annotated data matrix.
509
+ :param batch_key: Metadata column in `obs` with batch groups.
510
+ :param cluster_key: Metadata column in `obs` with cluster groups.
511
+ :param keep_metadata: Metadata in `obs` to keep. If more than one value is available for a group the first one is taken.
512
+ :param min_cells: Minimum number of cells in a cluster for each sample in order to generate a pseudobulk.
513
+ If the cluster has less it will be excluded.
514
+ :param pseudobulk_approach: Mode of aggregations.
515
+ :param technical_replicates: Number of technical replicates to generate.
516
+ :param min_counts: Minimum number of counts for a gene to be included.
517
+ :param layer: Layer to use.
518
+ :param workers: Number of theads to use to parallelize the pseudo-bulking
519
+ :return: AnnData with pseudobulk counts for each cluster.
520
+
521
+ Example
522
+ -------
523
+ >>> import dotools_py as do
524
+ >>> adata = do.dt.example_10x_processed()
525
+ >>> pdata = do.get.pseudobulk(adata, batch_key="batch", cluster_key="annotation")
526
+ Pseudo-bulked groups: 100%|██████████| 10/10 [00:08<00:00, 1.19it/s]
527
+ OMP: Info #276: omp_set_nested routine deprecated, please use omp_set_max_active_levels instead.
528
+ 2025-08-01 16:41:13,927 - Removed 796 genes for having less than 10 total counts
529
+ >>> pdata
530
+ AnnData object with n_obs × n_vars = 7 × 1055
531
+ obs: 'annotation', 'batch', 'n_genes_by_counts', 'log1p_n_genes_by_counts', 'total_counts',
532
+ 'log1p_total_counts', 'pct_counts_in_top_50_genes', 'pct_counts_in_top_100_genes',
533
+ 'pct_counts_in_top_200_genes', 'pct_counts_in_top_500_genes'
534
+ var: 'n_cells_by_counts', 'mean_counts', 'log1p_mean_counts', 'pct_dropout_by_counts', 'total_counts',
535
+ 'log1p_total_counts'
536
+
537
+ """
538
+ import polars as pl
539
+ from joblib import Parallel, delayed
540
+ import scipy.sparse as sp
541
+ import gc
542
+ import scanpy as sc
543
+ from tqdm import tqdm
544
+ import random
545
+
546
+ keep_metadata = [] if keep_metadata is None else keep_metadata
547
+ keep_metadata = [keep_metadata] if isinstance(keep_metadata, str) else keep_metadata
548
+ keep_metadata = keep_metadata + [cluster_key, batch_key]
549
+
550
+ # Define the groups to pseudo-bulk
551
+ groups = adata.obs[[cluster_key, batch_key]]
552
+ groups = groups.groupby([cluster_key, batch_key])
553
+ groups = groups.groups
554
+
555
+ # Create dictionary to specify how to pseudobulk
556
+ aggregate_info = dict.fromkeys(adata.var_names, pseudobulk_approach)
557
+ aggregate_info.update(dict.fromkeys(keep_metadata, "first"))
558
+ del aggregate_info[batch_key]
559
+ agg_exprs = [getattr(pl.col(col), func)().alias(col) for col, func in aggregate_info.items()]
560
+
561
+ def _process_group(
562
+ cluster: str,
563
+ batch: str,
564
+ bcs: list
565
+ ) -> pl.DataFrame | None:
566
+ sdata = adata[adata.obs_names.isin(bcs), :]
567
+
568
+ if sdata.n_obs < min_cells:
569
+ logger.info(f"Excluding {cluster} in {batch} for having less than {min_cells}")
570
+ return None
571
+
572
+ if technical_replicates == 1:
573
+ mtx = sdata.to_df(layer=layer)
574
+ mtx[keep_metadata] = sdata.obs[keep_metadata].values
575
+ mtx_pl = pl.from_pandas(mtx).group_by(batch_key).agg(agg_exprs)
576
+ else:
577
+ # Generate technical replicates
578
+ random.shuffle(bcs)
579
+ idx = np.array_split(np.array(bcs), technical_replicates)
580
+ mtx_pl = None
581
+ for i, replicate in enumerate(idx):
582
+ batch_replicate = sdata[replicate, :]
583
+ mtx = batch_replicate.to_df(layer=layer)
584
+ mtx[keep_metadata] = batch_replicate.obs[keep_metadata].values
585
+
586
+ mtx_pl_tmp = pl.from_pandas(mtx)
587
+
588
+ # mtx_pl_tmp[batch_key] = mtx_pl_tmp[batch_key] + "_" + str(i)
589
+
590
+ mtx_pl_tmp = mtx_pl_tmp.with_columns(
591
+ (pl.col(batch_key) + "_" + pl.lit(str(i))).alias(batch_key)).group_by(batch_key).agg(agg_exprs)
592
+ if mtx_pl is None:
593
+ mtx_pl = mtx_pl_tmp
594
+ else:
595
+ mtx_pl = pl.concat([mtx_pl, mtx_pl_tmp], how="vertical")
596
+ # mtx_pl = pl.concat([mtx_pl_tmp, mtx_pl], how="vertical")
597
+ gc.collect()
598
+ return mtx_pl
599
+
600
+ # Process groups in parallel
601
+ with Parallel(n_jobs=workers, backend="loky") as parallel:
602
+ results = parallel(
603
+ delayed(_process_group)(cluster, batch, list(bcs))
604
+ for (cluster, batch), bcs in tqdm(groups.items(), desc="Pseudo-bulked groups")
605
+ )
606
+
607
+ # Generate the pseudo-bulked AnnData
608
+ df_main = [res for res in results if res is not None]
609
+ df_main = pl.concat(df_main, how="vertical")
610
+ df_main = df_main.to_pandas()
611
+ df_main = df_main.fillna(0) # Make sure we do not have NaNs
612
+
613
+ pdata = ad.AnnData(df_main[adata.var_names], obs=df_main[keep_metadata])
614
+ pdata.obs_names = ['psBC-' + str(idx) for idx in range(pdata.n_obs)]
615
+ pdata.var_names_make_unique()
616
+ pdata.X = np.nan_to_num(pdata.X, nan=0)
617
+ if not sp.isspmatrix_csr(pdata.X):
618
+ pdata.X = sp.csr_matrix(pdata.X)
619
+
620
+ # Remove genes that have low amount of counts
621
+ sc.pp.calculate_qc_metrics(pdata, inplace=True)
622
+ n_vars = pdata.n_vars
623
+ pdata = pdata[:, pdata.var.total_counts > min_counts].copy()
624
+ n_vars = n_vars - pdata.n_vars
625
+ logger.info(f"Removed {n_vars} genes for having less than {min_counts} total counts")
626
+ return pdata