## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 10,
  fig.height = 4
)

## ----load---------------------------------------------------------------------
library(multipletR)

## ----peek-input---------------------------------------------------------------
gem_file <- system.file("extdata", "PC65_gem_classification.csv",
  package = "multipletR"
)
head(read.csv(gem_file))

## ----detect, fig.alt = "Diagnostic plots colored by 10X and by multipletR classification"----
res <- detect_multiplets(
  fileIn = gem_file,
  fileOut = tempfile(fileext = ".csv"),
  plotPercent = TRUE,
  plotTotalReads = TRUE
)

## ----result-------------------------------------------------------------------
head(res)
table(res$our_classification)

## ----compare-counts-----------------------------------------------------------
# Cell Ranger's multiplet calls (from the GEM file)
sum(read.csv(gem_file)$call == "Multiplet")
# multipletR's multiplet calls
sum(res$our_classification == "Multiplet")

## ----composition--------------------------------------------------------------
mult <- res[res$our_classification == "Multiplet", ]
summary(mult$pct_human)
summary(mult$pct_mouse)

## ----adjust-------------------------------------------------------------------
res_strict <- detect_multiplets(
  fileIn      = gem_file,
  fileOut     = tempfile(fileext = ".csv"),
  overlapDrop = 5, # stop expanding sooner
  modeDiff    = 0.5 # stricter on distribution similarity
)

## ----install-optional, eval = FALSE-------------------------------------------
# pkg <- c("SingleCellExperiment", "Seurat")
# for (. in pkg) if (!requireNamespace(., quietly = TRUE)) BiocManager::install(.)

## ----seurat-------------------------------------------------------------------
# toy counts: 20 genes x the detected barcodes (stand-in for a real matrix)
counts <- matrix(
  rpois(20 * nrow(res), 5),
  nrow = 20,
  dimnames = list(paste0("gene", 1:20), res$barcode)
)
seu <- Seurat::CreateSeuratObject(counts)

# annotate only (keep all cells) to inspect the multiplets first
seu <- remove_multiplets(seu, res, remove = FALSE)
table(seu$multipletR_class)

# or annotate and remove in one step, ready for downstream analysis
seu_clean <- remove_multiplets(seu, res, remove = TRUE)
table(seu_clean$multipletR_class)

## ----sce----------------------------------------------------------------------
sce <- SingleCellExperiment::SingleCellExperiment(
  assays = list(counts = counts)
)
sce <- remove_multiplets(sce, res, remove = FALSE)
table(sce$multipletR_class)

# the Seurat and SCE classifications are identical
identical(
  unname(seu$multipletR_class),
  unname(sce$multipletR_class)
)

## ----session-info-------------------------------------------------------------
sessionInfo()

