Doublet detection with bixverse¶
Python port of the R vignette Doublet detection with bixverse. Original author: Gregor Lueg.
Intro¶
Doublets, droplets containing two or more cells, are a common artefact in
droplet-based single cell experiments. If left undetected, they masquerade as
intermediate cell states or novel populations and quietly corrupt downstream
analyses. This vignette demonstrates three doublet detection approaches
available in bixverse and benchmarks them against ground truth calls from
demuxlet, which identifies doublets
via genetic variation across pooled donors.
bixverse provides three computational doublet detection methods:
Scrublet is a simulation-based approach (Wolock, et al., 2019). It generates synthetic doublets by averaging pairs of randomly selected cells, embeds both real and synthetic cells together, and scores each real cell by the proportion of its nearest neighbours that are synthetic. A bimodal score distribution is expected: singlets cluster near zero, doublets near one. A threshold on this score determines the final calls.
Boosted doublet detection takes a different angle. Rather than scoring against the neighbours, it repeatedly simulates doublets, clusters real and synthetic cells together and flags clusters enriched for synthetic doublets. A cell is called a doublet if enough iterations vote for it. This can be more robust when the score distribution from Scrublet is not cleanly bimodal, though it introduces its own hyperparameters (and is substantially slower).
scDblFinder is a port of the scDblFinder method from Germain et al., with one modification: it uses lightGBM with the histogram trick on the feature space instead of xgboost, which tends to be faster to fit. It trains a classifier on real versus synthetic doublets and combines the classifier output with cxds co-expression scores (Bais and Kostka) into a weighted final score. Across published benchmarks it tends to be the strongest of the three.
All three methods are purely computational and work without genetic or hashing information. They complement experimental approaches like demuxlet, which require pooled donors or hashtag antibodies. They also have a failure mode if a large number of doublets dominates the original data.
import tempfile
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import polars as pl
import bixverse as bv
from bixverse.params import BoostParams, ScdblfinderParams, ScrubletParams
Loading the data¶
We use a PBMC data set with demuxlet ground truth calls. The demuxlet output
classifies each barcode as a singlet (SNG) or doublet (DBL) (or ambiguous,
but irrelevant for this situation), giving us something to benchmark against.
doublet_path = bv.io.download_demuxlet_pbmc()
tempdir_doublet = tempfile.TemporaryDirectory()
demuxlet_data = pl.read_csv(doublet_path / "demuxlet_calls.tsv", separator="\t")
demuxlet_data["Call"].value_counts().sort("Call")
| Call | count |
|---|---|
| str | u32 |
| "AMB" | 24 |
| "DBL" | 1565 |
| "SNG" | 13030 |
Load the data into bixverse. The matrix in this data set has the cells as rows.
sc = bv.io.load_mtx(
Path(tempdir_doublet.name) / "demuxlet",
bv.io.get_cell_ranger_params(doublet_path, cells_as_rows=True),
)
sc
Text pass (real): 3 buckets, ~4873 cells/bucket Text pass done: 69.64ms (unsorted order) Genes passing QC: 12_622 / 35_635 Cells passing QC: 14_537 / 14_619 Writing pass: 3 buckets Wrote bucket 1/3 (33%) Wrote bucket 2/3 (66%) Wrote bucket 3/3 (100%) Writing pass done: 110.31ms Converting the cell-based data into the gene-based format.
Counted 8_712_154 non-zeros over 12_622 genes in 4.01ms; converting in 1 phase(s).
Phase 1/1: genes 0-12622, scatter 13.97ms, compress + write 11.56ms Conversion into gene-friendly format done: 31.62ms
SingleCells( dir='/var/folders/l0/d50zd8812jg94mhtl8t2swfc0000gn/T/tmpt5h9ekvo/demuxlet', cells=14537 (kept 14537), genes=12622, hvg=False, pca=False, embeddings=none, knn=False, graph=False, magic=False, residuals=False, stale=none )
We also define a small helper to compute precision, recall and F1 against the
demuxlet calls. The doublet callers return the per-cell results with
cell_idx; we attach the barcodes and join the demuxlet calls on.
def with_calls(res_df: pl.DataFrame) -> pl.DataFrame:
return res_df.with_columns(
pl.Series("Barcode", sc.cell_ids(res_df["cell_idx"].to_numpy()))
).join(demuxlet_data, on="Barcode")
def doublet_metrics(predicted: pl.Series, actual: pl.Series) -> dict[str, float]:
pred = predicted.to_numpy()
act = (actual == "DBL").to_numpy()
tp = np.sum(pred & act)
fp = np.sum(pred & ~act)
fn = np.sum(~pred & act)
precision = tp / (tp + fp)
recall = tp / (tp + fn)
f1 = 2 * (precision * recall) / (precision + recall)
return {
"precision": round(float(precision), 4),
"recall": round(float(recall), 4),
"f1": round(float(f1), 4),
}
scrublet = bv.doublets.scrublet(
sc,
scrublet_params=ScrubletParams(expected_doublet_rate=0.12),
)
scrublet
Identifying highly variable genes... HVG (VST): 12_622 genes, 1 batches, 1 disk block(s) HVG (VST): Calculated gene statistics in 12.74ms HVG (VST): Fitted Loess in 556.88µs HVG (VST): Standardised variance in 414.67µs (179 gene(s) re-read for the clip) HVG (VST): Total run time -> 13.74ms Using 3787 highly variable genes. Done in 14.05ms
Simulating doublets...
Simulated 21805 doublets. Done in 66.36ms Running PCA... Loaded in data: 4.82ms Finished data preparation: 608.38µs Finished PCA calculations: 94.51ms Total run time PCA detection: 100.16ms Building kNN graph... Using 150 neighbours in the kNN generation.
Done with kNN generation in 357.58ms Calculating doublet scores... Automatically set threshold at doublet score = 0.2228 Detected doublet rate = 11.6% Estimated detectable doublet fraction = 84.4% Overall doublet rate: Expected = 12.0% Estimated = 13.8% Done with doublet scoring and calling 1.16ms Finished Scrublet 558.69ms
ScrubletRes( n_cells=14537, n_doublets=1691, doublet_rate=0.1163, threshold=0.2228, detectable_fraction=0.8444, overall_doublet_rate=0.1378, n_simulated=21805, pca=False, pairs=False, )
The score distribution for observed and simulated cells. A clean separation between the two modes indicates the threshold is sensible.
def plot_scrublet(res: bv.doublets.ScrubletRes, n_breaks: int = 31) -> None:
bins = np.linspace(0, 1, n_breaks)
fill, line = bv.pl.bx_colors("main", n=2)
_, axes = plt.subplots(1, 2, figsize=(9, 3.5), layout="constrained")
for ax, scores, title in zip(
axes,
(res.doublet_scores_obs, res.doublet_scores_sim),
("Observed transcriptomes", "Simulated doublets"),
strict=True,
):
ax.hist(scores, bins=bins, density=True, color=fill, edgecolor="white")
ax.axvline(res.threshold, color=line, linestyle="--", linewidth=1)
ax.set(title=title, xlabel="Doublet score", ylabel="Probability density")
plot_scrublet(scrublet)
plt.show()
How does the automatic thresholding perform against the demuxlet ground truth?
scrublet_df = with_calls(bv.doublets.get_data(scrublet))
doublet_metrics(scrublet_df["doublet"], scrublet_df["Call"])
{'precision': 0.6641, 'recall': 0.7199, 'f1': 0.6909}
If you want to add the information to the DuckDB within the object, you can just run:
sc.add_obs(bv.doublets.get_data(scrublet))
sc.obs().head()
| cell_idx | cell_id | nnz | lib_size | to_keep | doublet | doublet_score |
|---|---|---|---|---|---|---|
| u32 | str | f64 | f64 | bool | bool | f64 |
| 0 | "AAACATACAATGCC-1" | 851.0 | 2190.0 | true | true | 0.337701 |
| 1 | "AAACATACATTTCC-1" | 876.0 | 3016.0 | true | false | 0.053115 |
| 2 | "AAACATACCAGAAA-1" | 713.0 | 2481.0 | true | false | 0.017581 |
| 3 | "AAACATACCAGCTA-1" | 948.0 | 3155.0 | true | false | 0.187289 |
| 4 | "AAACATACCATGCA-1" | 337.0 | 703.0 | true | false | 0.00437 |
The Scrublet calls and scores are now columns in obs.
Manual threshold adjustment¶
The automatic threshold does not always land in the right place. If the score
distribution suggests a different cut-off, call_doublets_manual lets you
override it.
scrublet_adj = bv.doublets.call_doublets_manual(scrublet, threshold=0.25)
plot_scrublet(scrublet_adj)
plt.show()
Detected doublet rate = 10.8%
Estimated detectable doublet fraction = 81.8%
Overall doublet rate: estimated = 13.2%
scrublet_adj_df = with_calls(bv.doublets.get_data(scrublet_adj))
doublet_metrics(scrublet_adj_df["doublet"], scrublet_adj_df["Call"])
{'precision': 0.6777, 'recall': 0.6795, 'f1': 0.6786}
We have made it worse here, but maybe there are cases where the scores are not very good. Compared to the original version, Otsu's method is used to identify the threshold, but it might fail in some situations.
Running with grouping variables or within specific cell subsets¶
Scrublet (and the other methods) have two parameters if you wish to run the
detection method within a specific set of cells (cells_to_use=None) and/or
want to use a grouping variable, like running the doublet detection within
individual samples (group_by=None).
Boosted doublet detection¶
The boosted approach repeatedly simulates doublets and clusters them together with the real cells. This can work better when the Scrublet score distribution is messy or unimodal. However, by default it runs 20 iterations of the algorithm, which means 20x generation of synthetic doublets. The initial PCA is kept for subsequent reprojection; nonetheless, this makes it slower than the other methods in this vignette.
boosted_doublets = bv.doublets.doublet_detection_boost(
sc,
boost_params=BoostParams(),
)
boosted_doublets
Identifying highly variable genes... HVG (VST): 12_622 genes, 1 batches, 1 disk block(s) HVG (VST): Calculated gene statistics in 8.38ms HVG (VST): Fitted Loess in 478.21µs HVG (VST): Standardised variance in 418.00µs (179 gene(s) re-read for the clip) HVG (VST): Total run time -> 9.31ms Using 3787 highly variable genes. Done in 9.62ms == Running iteration 1 of 20 == Generating the PCA in the first iteration Loaded in data: 4.64ms Finished data preparation: 598.75µs
Finished PCA calculations: 95.37ms Total run time PCA detection: 100.95ms Finished the initial PCA in 102.33ms and storing results for subsequent iterations Using 75 neighbours in the kNN generation. Using 75 neighbours in the kNN generation.
Transformed kNN graph. Done in 25.83ms
Generated communities. Done in 211.56ms == Running iteration 2 of 20 == Using 75 neighbours in the kNN generation. Using 75 neighbours in the kNN generation.
Transformed kNN graph. Done in 15.41ms
Generated communities. Done in 201.52ms == Running iteration 3 of 20 == Using 75 neighbours in the kNN generation. Using 75 neighbours in the kNN generation.
Transformed kNN graph. Done in 14.20ms
Generated communities. Done in 188.15ms == Running iteration 4 of 20 == Using 75 neighbours in the kNN generation. Using 75 neighbours in the kNN generation. Transformed kNN graph. Done in 13.53ms
Generated communities. Done in 216.96ms == Running iteration 5 of 20 == Using 75 neighbours in the kNN generation. Using 75 neighbours in the kNN generation. Transformed kNN graph. Done in 13.54ms
Generated communities. Done in 210.92ms == Running iteration 6 of 20 == Using 75 neighbours in the kNN generation. Using 75 neighbours in the kNN generation. Transformed kNN graph. Done in 14.42ms
Generated communities. Done in 202.51ms == Running iteration 7 of 20 == Using 75 neighbours in the kNN generation. Using 75 neighbours in the kNN generation. Transformed kNN graph. Done in 13.75ms
Generated communities. Done in 187.64ms == Running iteration 8 of 20 == Using 75 neighbours in the kNN generation. Using 75 neighbours in the kNN generation. Transformed kNN graph. Done in 13.66ms
Generated communities. Done in 204.55ms == Running iteration 9 of 20 == Using 75 neighbours in the kNN generation. Using 75 neighbours in the kNN generation. Transformed kNN graph. Done in 13.63ms
Generated communities. Done in 199.06ms == Running iteration 10 of 20 == Using 75 neighbours in the kNN generation. Using 75 neighbours in the kNN generation. Transformed kNN graph. Done in 13.51ms
Generated communities. Done in 198.64ms == Running iteration 11 of 20 == Using 75 neighbours in the kNN generation. Using 75 neighbours in the kNN generation. Transformed kNN graph. Done in 13.94ms
Generated communities. Done in 197.88ms == Running iteration 12 of 20 == Using 75 neighbours in the kNN generation. Using 75 neighbours in the kNN generation. Transformed kNN graph. Done in 13.59ms
Generated communities. Done in 187.87ms == Running iteration 13 of 20 == Using 75 neighbours in the kNN generation. Using 75 neighbours in the kNN generation. Transformed kNN graph. Done in 13.37ms
Generated communities. Done in 212.78ms == Running iteration 14 of 20 == Using 75 neighbours in the kNN generation. Using 75 neighbours in the kNN generation. Transformed kNN graph. Done in 14.68ms
Generated communities. Done in 198.90ms == Running iteration 15 of 20 == Using 75 neighbours in the kNN generation. Using 75 neighbours in the kNN generation. Transformed kNN graph. Done in 14.02ms
Generated communities. Done in 195.08ms == Running iteration 16 of 20 == Using 75 neighbours in the kNN generation. Using 75 neighbours in the kNN generation. Transformed kNN graph. Done in 13.68ms
Generated communities. Done in 187.93ms == Running iteration 17 of 20 == Using 75 neighbours in the kNN generation. Using 75 neighbours in the kNN generation. Transformed kNN graph. Done in 13.97ms
Generated communities. Done in 214.87ms == Running iteration 18 of 20 == Using 75 neighbours in the kNN generation. Using 75 neighbours in the kNN generation. Transformed kNN graph. Done in 13.54ms
Generated communities. Done in 200.03ms == Running iteration 19 of 20 == Using 75 neighbours in the kNN generation. Using 75 neighbours in the kNN generation. Transformed kNN graph. Done in 13.51ms
Generated communities. Done in 190.02ms == Running iteration 20 of 20 == Using 75 neighbours in the kNN generation. Using 75 neighbours in the kNN generation. Transformed kNN graph. Done in 13.65ms
Generated communities. Done in 213.68ms Completed 20 iterations in 4.41s Detected 1549 doublets (10.7%) Total runtime: 4.43s
BoostRes( n_cells=14537, n_doublets=1549, doublet_rate=0.1066, score_range=[0.0162, 0.7135], )
Let's check how boosted works?
boosted_df = with_calls(bv.doublets.get_data(boosted_doublets))
doublet_metrics(boosted_df["doublet"], boosted_df["Call"])
{'precision': 0.6611, 'recall': 0.6564, 'f1': 0.6587}
Overall, it takes longer and has worse performance (in this data set). If you
wish to have a partially orthogonal method, it can be worthwhile nonetheless.
There is also an option to accelerate the algorithm via fast clustering. This
runs k-means clustering with sqrt(n_cells) * 4 centroids by default, the kNN
on these centroids, Louvain on the smaller kNN graph and projects the Louvain
membership back for final scoring. This comes at a cost of recall, as you can
see below. You need to check how many centroids you need to represent your
data properly. On smaller data sets, you can get away with n_cells / 10 and
compress 10 cells into one centroid... On larger data sets, you might want to
compress further.
boosted_doublets_fast = bv.doublets.doublet_detection_boost(
sc,
boost_params=BoostParams(
fast_cluster=True,
# in this case, we set the n_centroids to n_cells / 10
# you want this to not be too low
n_centroids=1500,
),
)
Identifying highly variable genes...
HVG (VST): 12_622 genes, 1 batches, 1 disk block(s)
HVG (VST): Calculated gene statistics in 7.73ms
HVG (VST): Fitted Loess in 501.42µs
HVG (VST): Standardised variance in 372.08µs (179 gene(s) re-read for the clip)
HVG (VST): Total run time -> 8.64ms
Using 3787 highly variable genes. Done in 8.92ms
== Running iteration 1 of 20 ==
Generating the PCA in the first iteration
Loaded in data: 3.94ms
Finished data preparation: 656.29µs
Finished PCA calculations: 93.45ms
Total run time PCA detection: 98.36ms
Finished the initial PCA in 99.86ms and storing results for subsequent iterations
Using 75 neighbours in the kNN generation.
Using fast clustering with 1500 centroids, k=19 on 18171 cells.
k-means with 1500 centroids: 45.77ms
Built the Knn { binary: false } graph: 1.52ms
Centroid graph: 4.32ms
Community detection: 1.15ms
Generated communities. Done in 51.27ms
== Running iteration 2 of 20 ==
Using 75 neighbours in the kNN generation. Using fast clustering with 1500 centroids, k=19 on 18171 cells.
k-means with 1500 centroids: 46.64ms
Built the Knn { binary: false } graph: 939.25µs
Centroid graph: 3.44ms
Community detection: 1.24ms
Generated communities. Done in 51.33ms
== Running iteration 3 of 20 ==
Using 75 neighbours in the kNN generation.
Using fast clustering with 1500 centroids, k=19 on 18171 cells.
k-means with 1500 centroids: 46.58ms
Built the Knn { binary: false } graph: 801.83µs
Centroid graph: 3.33ms
Community detection: 1.27ms
Generated communities. Done in 51.20ms
== Running iteration 4 of 20 ==
Using 75 neighbours in the kNN generation.
Using fast clustering with 1500 centroids, k=19 on 18171 cells.
k-means with 1500 centroids: 47.15ms
Built the Knn { binary: false } graph: 464.12µs
Centroid graph: 3.06ms
Community detection: 1.25ms
Generated communities. Done in 51.47ms
== Running iteration 5 of 20 ==
Using 75 neighbours in the kNN generation.
Using fast clustering with 1500 centroids, k=19 on 18171 cells.
k-means with 1500 centroids: 46.15ms
Built the Knn { binary: false } graph: 450.46µs
Centroid graph: 2.96ms
Community detection: 1.15ms
Generated communities. Done in 50.27ms
== Running iteration 6 of 20 ==
Using 75 neighbours in the kNN generation.
Using fast clustering with 1500 centroids, k=19 on 18171 cells.
k-means with 1500 centroids: 44.96ms
Built the Knn { binary: false } graph: 455.50µs
Centroid graph: 2.80ms
Community detection: 1.26ms
Generated communities. Done in 49.04ms
== Running iteration 7 of 20 ==
Using 75 neighbours in the kNN generation.
Using fast clustering with 1500 centroids, k=19 on 18171 cells.
k-means with 1500 centroids: 47.47ms
Built the Knn { binary: false } graph: 493.96µs
Centroid graph: 2.96ms
Community detection: 1.24ms
Generated communities. Done in 51.69ms
== Running iteration 8 of 20 ==
Using 75 neighbours in the kNN generation.
Using fast clustering with 1500 centroids, k=19 on 18171 cells.
k-means with 1500 centroids: 46.56ms
Built the Knn { binary: false } graph: 518.29µs
Centroid graph: 2.93ms
Community detection: 1.25ms
Generated communities. Done in 50.77ms
== Running iteration 9 of 20 ==
Using 75 neighbours in the kNN generation.
Using fast clustering with 1500 centroids, k=19 on 18171 cells.
k-means with 1500 centroids: 45.80ms
Built the Knn { binary: false } graph: 448.67µs
Centroid graph: 2.68ms
Community detection: 1.23ms
Generated communities. Done in 49.74ms
== Running iteration 10 of 20 ==
Using 75 neighbours in the kNN generation.
Using fast clustering with 1500 centroids, k=19 on 18171 cells.
k-means with 1500 centroids: 45.87ms
Built the Knn { binary: false } graph: 503.42µs
Centroid graph: 3.14ms
Community detection: 1.13ms
Generated communities. Done in 50.17ms
== Running iteration 11 of 20 ==
Using 75 neighbours in the kNN generation.
Using fast clustering with 1500 centroids, k=19 on 18171 cells.
k-means with 1500 centroids: 45.63ms
Built the Knn { binary: false } graph: 596.79µs
Centroid graph: 2.98ms
Community detection: 1.17ms
Generated communities. Done in 49.80ms
== Running iteration 12 of 20 ==
Using 75 neighbours in the kNN generation.
Using fast clustering with 1500 centroids, k=19 on 18171 cells.
k-means with 1500 centroids: 46.56ms
Built the Knn { binary: false } graph: 523.38µs
Centroid graph: 2.87ms
Community detection: 1.20ms
Generated communities. Done in 50.65ms
== Running iteration 13 of 20 ==
Using 75 neighbours in the kNN generation.
Using fast clustering with 1500 centroids, k=19 on 18171 cells.
k-means with 1500 centroids: 46.09ms
Built the Knn { binary: false } graph: 522.92µs
Centroid graph: 2.94ms
Community detection: 1.14ms
Generated communities. Done in 50.19ms
== Running iteration 14 of 20 ==
Using 75 neighbours in the kNN generation.
Using fast clustering with 1500 centroids, k=19 on 18171 cells.
k-means with 1500 centroids: 44.77ms
Built the Knn { binary: false } graph: 440.62µs
Centroid graph: 2.61ms
Community detection: 1.28ms
Generated communities. Done in 48.68ms
== Running iteration 15 of 20 ==
Using 75 neighbours in the kNN generation.
Using fast clustering with 1500 centroids, k=19 on 18171 cells.
k-means with 1500 centroids: 45.58ms
Built the Knn { binary: false } graph: 563.04µs
Centroid graph: 3.21ms
Community detection: 1.46ms
Generated communities. Done in 50.27ms
== Running iteration 16 of 20 ==
Using 75 neighbours in the kNN generation.
Using fast clustering with 1500 centroids, k=19 on 18171 cells.
k-means with 1500 centroids: 45.42ms
Built the Knn { binary: false } graph: 458.25µs
Centroid graph: 2.83ms
Community detection: 1.21ms
Generated communities. Done in 49.48ms
== Running iteration 17 of 20 ==
Using 75 neighbours in the kNN generation.
Using fast clustering with 1500 centroids, k=19 on 18171 cells.
k-means with 1500 centroids: 51.43ms
Built the Knn { binary: false } graph: 478.08µs
Centroid graph: 2.88ms
Community detection: 1.26ms
Generated communities. Done in 55.58ms
== Running iteration 18 of 20 ==
Using 75 neighbours in the kNN generation.
Using fast clustering with 1500 centroids, k=19 on 18171 cells.
k-means with 1500 centroids: 45.38ms
Built the Knn { binary: false } graph: 477.42µs
Centroid graph: 2.83ms
Community detection: 1.25ms
Generated communities. Done in 49.48ms
== Running iteration 19 of 20 ==
Using 75 neighbours in the kNN generation.
Using fast clustering with 1500 centroids, k=19 on 18171 cells.
k-means with 1500 centroids: 45.18ms
Built the Knn { binary: false } graph: 618.67µs
Centroid graph: 3.10ms
Community detection: 1.21ms
Generated communities. Done in 49.51ms
== Running iteration 20 of 20 ==
Using 75 neighbours in the kNN generation.
Using fast clustering with 1500 centroids, k=19 on 18171 cells.
k-means with 1500 centroids: 45.08ms
Built the Knn { binary: false } graph: 534.38µs
Centroid graph: 2.98ms
Community detection: 1.30ms
Generated communities. Done in 49.39ms
Completed 20 iterations in 1.39s
Detected 1290 doublets (8.9%)
Total runtime: 1.41s
boosted_fast_df = with_calls(bv.doublets.get_data(boosted_doublets_fast))
doublet_metrics(boosted_fast_df["doublet"], boosted_fast_df["Call"])
{'precision': 0.7093, 'recall': 0.5865, 'f1': 0.6421}
scDblFinder¶
Lastly, bixverse also provides an implementation of
scDblFinder
from Germain et al. with
one modification: instead of xgboost, we use an implementation of lightGBM
with the histogram trick on the feature space. This yields faster fitting
compared to the original xgboost approach. To run it, you can just do the
following:
scdblfinder = bv.doublets.scdblfinder(
sc,
scdblfinder_params=ScdblfinderParams(expected_doublet_rate=0.12),
# if you wish to get the features that were used to train the classifier
return_features=False,
)
scdblfinder
Running scDblFinder in Rust Selecting top-expressed genes... Using 1352 top-expressed genes. Done in 23.82ms Computing cell complexity features... Building cxds co-expression model with 500 genes...
cxds model built in 92.13ms (mean score: 211841.59) Running PCA on observed cells... Loaded in data: 9.47ms Finished data preparation: 1.40ms
Finished PCA calculations: 154.75ms Total run time PCA detection: 165.97ms Initial clustering of observed cells...
Finished initial kNN generation and clustering in 390.76ms Using k values [3, 10, 15, 20, 25, 50, 86] (max 86), including 19 PCs as features Simulating cluster-aware doublets with a heterotypic bias of 1.00... Running PCA across all observed and synthetic cells...
Building combined kNN graph (k_max=86)...
Finished generation of simulated doublets, projection on PCA space and kNN generation in 773.61ms Building feature matrix (33 features)... == Iteration 1 of 3 == Training logistic GBM classifier... Iteration 1 done in 114.39ms (obs scores: mean=0.1711, min=0.0078, max=0.9673) == Iteration 2 of 3 == Training logistic GBM classifier...
Iteration 2 done in 99.68ms (obs scores: mean=0.1702, min=0.0057, max=0.9971) == Iteration 3 of 3 == Training logistic GBM classifier... Iteration 3 done in 103.67ms (obs scores: mean=0.1646, min=0.0055, max=0.9970) Threshold optimiser: expected band: [858, 2631] doublets selected threshold: 0.2963 best cost: 0.2401 Threshold set at score = 0.2963 Detected 2265 doublets (15.6%) Total runtime: 1.80s
ScDblFinderRes( n_cells=14537, n_doublets=2265, doublet_rate=0.1558, threshold=0.2963, n_clusters=8, features=False, )
scDblFinder calls more doublets than the expected rate (16.4% against 12%). Compared with the other methods its precision is lower (0.56) and its recall higher (0.85), at a similar F1.
scdblfinder_df = with_calls(bv.doublets.get_data(scdblfinder))
doublet_metrics(scdblfinder_df["predicted_doublets"], scdblfinder_df["Call"])
{'precision': 0.5762, 'recall': 0.8365, 'f1': 0.6824}
We can also extract the other scores from scDblFinder via get_scores: the
weighted score (score_type="weighted") and the cxds scores
(score_type="cxds_scores"). The cxds scores were originally developed by
Bais and Kostka and are
used as an input into the classifier.
weighted_scores = bv.doublets.get_scores(scdblfinder, score_type="weighted")
cxds_scores = bv.doublets.get_scores(scdblfinder, score_type="cxds_scores")
pl.DataFrame({"weighted": weighted_scores, "cxds": cxds_scores}).describe()
| statistic | weighted | cxds |
|---|---|---|
| str | f64 | f64 |
| "count" | 14537.0 | 14537.0 |
| "null_count" | 0.0 | 0.0 |
| "mean" | 0.205227 | 0.137246 |
| "std" | 0.267985 | 0.121008 |
| "min" | 0.0 | 0.0 |
| "25%" | 0.025813 | 0.066592 |
| "50%" | 0.080784 | 0.10096 |
| "75%" | 0.257792 | 0.161034 |
| "max" | 0.99839 | 1.0 |
Not ported to Python yet: find_threshold_otsu, so calling doublets on the
weighted or cxds scores via Otsu's method is left out here.
Should you observe that the cxds scores are very flat or you only have a few
data points (this can occur in low complexity experiments in which the highest
expressing genes are VERY similar across all the cells, for example in cell
culture experiments), you can bump cxds_genes up. The default here is 500,
but you might want to increase this pending your experiment.
PCA solver and HVG method¶
All three methods run their own PCA on the observed and simulated cells. You
pick the solver via svd_solver. The default here is "randomised", a
randomised SVD that is approximate in the trailing components. "covariance"
builds the gene x gene cross-product over the HVGs and eigendecomposes it,
which is exact, but the doublet methods run on more genes and that matrix
grows with the square of the gene count, so it gets painfully slow here.
"auto" (the default in PcaParams) runs Lanczos on the sparse path and the
covariance solver on the dense one. "exact" runs Lanczos on the sparse path
and a full SVD on the dense one. Scrublet and the boosted method also take the
HVG method via hvg_method, including the scran trend:
ScrubletParams(
expected_doublet_rate=0.12,
hvg_method="scran",
svd_solver="covariance",
)
Conclusion¶
All methods can help to identify doublets in your data in a data-driven way. In a later re-evaluation by Xi and Li, scDblFinder came out on top across different benchmark data sets, see Germain et al., 2021. Here it has the highest recall and the lowest precision of the five runs. Which one wins on this data set is in the metrics above.
Clean up¶
tempdir_doublet.cleanup()