R wrappers#

This notebook validates the R-backed wrappers that live under sctk.r. The main example runs scDblFinder on the full data/kang.h5ad dataset through the Python API.

SoupX is not run here because this repository currently only includes a filtered cell matrix. A biologically meaningful SoupX run needs a raw droplet matrix plus the filtered cell matrix.

from __future__ import annotations

import os
import time
from pathlib import Path

os.environ.setdefault("NUMBA_CACHE_DIR", "/tmp/sctk_numba_cache")
os.environ.setdefault("MPLCONFIGDIR", "/tmp/sctk_mpl_config")
os.environ.setdefault("XDG_CACHE_HOME", "/tmp/sctk_xdg_cache")

import numpy as np
import scanpy as sc

import sctk
from sctk.r import require_r_package

Check R packages#

sctk.r loads R lazily. Importing sctk should not require these packages, but calling the wrapper does.

for package in ["SingleCellExperiment", "scDblFinder", "BiocParallel"]:
    require_r_package(package)
    print(f"{package}: ok")
SingleCellExperiment: ok
scDblFinder: ok
BiocParallel: ok

Load the Kang dataset#

The checked-in documentation notebook expects data/kang.h5ad to exist locally, but the data file itself is ignored by git.

data_path = Path("data/kang.h5ad")
if not data_path.exists():
    data_path = Path("../data/kang.h5ad")

adata = sc.read_h5ad(data_path)
adata.layers["counts"] = adata.X.copy()

print(f"shape: {adata.shape}")
print(f"obs columns: {list(adata.obs.columns)}")
print(f"X type: {type(adata.X).__name__}")
shape: (24673, 15706)
obs columns: ['label', 'cluster', 'cell_type', 'replicate']
X type: csc_matrix

Run scDblFinder#

The wrapper writes scDblFinder_score and scDblFinder_class into adata.obs. replicate is used as the sample/batch column for this dataset.

started = time.perf_counter()

sctk.r.pp.scdblfinder(
    adata,
    layer="counts",
    batch_key="replicate",
    n_jobs=4,
    seed=0,
    drop_doublets=False,
)

elapsed = time.perf_counter() - started
print(f"elapsed seconds: {elapsed:.2f}")
elapsed seconds: 62.24

Validate and summarize results#

score_key = "scDblFinder_score"
class_key = "scDblFinder_class"

assert score_key in adata.obs
assert class_key in adata.obs
assert len(adata.obs[score_key]) == adata.n_obs
assert len(adata.obs[class_key]) == adata.n_obs

scores = adata.obs[score_key].to_numpy(dtype=float)
classes = adata.obs[class_key].astype(str)
assert np.isfinite(scores).all()
assert set(classes.unique()).intersection({"singlet", "doublet"})

summary = classes.value_counts().rename_axis("class").to_frame("n_cells")
summary["fraction"] = summary["n_cells"] / adata.n_obs
display(summary)

print("score min:", float(np.min(scores)))
print("score median:", float(np.median(scores)))
print("score max:", float(np.max(scores)))
print("score mean:", float(np.mean(scores)))
n_cells fraction
class
singlet 23384 0.947757
doublet 1289 0.052243
score min: 1.4013116924616043e-05
score median: 0.004307479131966829
score max: 0.9999845027923584
score mean: 0.07357047294085267