## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

## ----install, eval = FALSE----------------------------------------------------
# if (!requireNamespace("BiocManager", quietly = TRUE)) {
#     install.packages("BiocManager")
# }
# BiocManager::install("cellchatr")

## ----setup, message = FALSE---------------------------------------------------
library(cellchatr)
library(SingleCellExperiment)

## ----lrdb---------------------------------------------------------------------
lrdb <- data.frame(
    interaction_name = c("TGFB1_TGFBR1", "VEGFA_FLT1", "CXCL12_CXCR4",
                         "IL6_IL6R", "TNF_TNFRSF1A", "MIF_CD74",
                         "CCL2_CCR2", "PDGFB_PDGFRB", "EGF_EGFR",
                         "FGF2_FGFR1"),
    ligand = c("TGFB1", "VEGFA", "CXCL12", "IL6", "TNF",
               "MIF", "CCL2", "PDGFB", "EGF", "FGF2"),
    receptor = c("TGFBR1", "FLT1", "CXCR4", "IL6R", "TNFRSF1A",
                 "CD74", "CCR2", "PDGFRB", "EGFR", "FGFR1"),
    pathway_name = c("TGFb", "VEGF", "CXCL", "IL6", "TNF",
                     "MIF", "CCL", "PDGF", "EGF", "FGF")
)
lrdb

## ----sce----------------------------------------------------------------------
set.seed(42)
genes <- unique(c(lrdb$ligand, lrdb$receptor, paste0("GENE", 1:2000)))
cell_type <- rep(c("Fibroblast", "Macrophage", "Endothelial"), each = 100)

mat <- matrix(rnorm(length(genes) * length(cell_type), mean = 1, sd = 1),
              nrow = length(genes),
              dimnames = list(genes, paste0("cell", seq_along(cell_type))))
mat[c("TGFB1", "PDGFB"), cell_type == "Fibroblast"] <-
    mat[c("TGFB1", "PDGFB"), cell_type == "Fibroblast"] + 3
mat["FLT1", cell_type == "Endothelial"] <-
    mat["FLT1", cell_type == "Endothelial"] + 3

sce <- SingleCellExperiment(
    assays = list(logcounts = mat),
    colData = DataFrame(cell_type = cell_type)
)
sce

## ----identify-----------------------------------------------------------------
res <- identifyInteractions(sce, lrdb, labels = "cell_type",
                            assay.type = "logcounts",
                            pval_threshold = 1e-6)
res
metadata(res)$overexpressed

## ----steps--------------------------------------------------------------------
oe <- findOverexpressedGenes(sce, labels = "cell_type", lrdb = lrdb,
                             pval_threshold = 1e-6)
oe
matchLRPairs(oe, lrdb)

## ----matrix-------------------------------------------------------------------
findOverexpressedGenes(Matrix::Matrix(mat, sparse = TRUE),
                       labels = cell_type, lrdb = lrdb,
                       pval_threshold = 1e-6)

## ----cellchatdb, eval = FALSE-------------------------------------------------
# library(CellChat)
# res <- identifyInteractions(sce, CellChatDB.human$interaction,
#                             labels = "cell_type")

## ----compare------------------------------------------------------------------
x <- mat["TGFB1", cell_type == "Fibroblast"]
y <- mat["TGFB1", cell_type != "Fibroblast"]
wilcox.test(x, y, alternative = "greater",
            exact = FALSE, correct = FALSE)$p.value

## ----benchmark----------------------------------------------------------------
set.seed(42)
n_genes <- 500
labels_bm <- rep(c("A", "B"), each = 100)
counts_bm <- matrix(rnorm(n_genes * 200), nrow = n_genes)
gene_names <- paste0("GENE", seq_len(n_genes))

r_wilcoxon <- function(counts, labels, gene_names, pval_threshold) {
    hit <- vapply(seq_len(nrow(counts)), function(g) {
        any(vapply(unique(labels), function(ct) {
            wilcox.test(counts[g, labels == ct], counts[g, labels != ct],
                        alternative = "greater", exact = FALSE,
                        correct = FALSE)$p.value < pval_threshold
        }, logical(1)))
    }, logical(1))
    gene_names[hit]
}

t_rust <- system.time(
    rust_res <- rust_wilcoxon_filter(counts_bm, labels_bm, gene_names, 0.05)
)
t_r <- system.time(
    r_res <- r_wilcoxon(counts_bm, labels_bm, gene_names, 0.05)
)
identical(sort(rust_res), sort(r_res))
c(rust = t_rust[["elapsed"]], base_r = t_r[["elapsed"]])

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

