## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
has_seurat <- requireNamespace("Seurat", quietly = TRUE)
# CRAN allows at most 2 cores; by default doubletrs uses all of them.
options(doubletrs.threads = 2)

## -----------------------------------------------------------------------------
library(doubletrs)

## ----eval = has_seurat--------------------------------------------------------
seu <- SeuratObject::pbmc_small

## ----eval = has_seurat, fig.width = 6, fig.height = 3.5-----------------------
set.seed(1)
sweep <- paramSweep(seu, PCs = 1:5)
stats <- summarizeSweep(sweep)
bcmvn <- find.pK(stats)
pK <- as.numeric(as.character(bcmvn$pK[which.max(bcmvn$BCmetric)]))
pK

## ----eval = has_seurat--------------------------------------------------------
homotypic <- modelHomotypic(seu$RNA_snn_res.1)
nExp <- round(0.075 * ncol(seu) * (1 - homotypic))
nExp

## ----eval = has_seurat--------------------------------------------------------
set.seed(1)
seu <- doubletFinder(seu, PCs = 1:5, pN = 0.25, pK = pK, nExp = nExp)
calls <- grep("^DF.classifications", colnames(seu@meta.data), value = TRUE)
table(seu@meta.data[[calls]])

## -----------------------------------------------------------------------------
set.seed(1)
counts <- abs(Matrix::rsparsematrix(200, 100, density = 0.2))
doublets <- simulate_doublets(counts, n = 33)
dim(doublets)

# Stand-in for PCs of the merged matrix: real cells first, then doublets.
pcs <- matrix(rnorm(133 * 5), ncol = 5)
pann <- compute_pann(pcs, n_real = 100, k = 10)
summary(pann)

