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

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

## ----load, message = FALSE----------------------------------------------------
library(MRCCC)
library(SummarizedExperiment)

## ----pseudobulk, message = FALSE----------------------------------------------
library(SingleCellExperiment)
library(scuttle)
set.seed(2)
cells <- data.frame(donor = rep(sprintf("donor%02d", 1:12), each = 40),
                    cellType = rep(c("NK", "Monocyte"), times = 240))
counts <- matrix(rpois(3 * nrow(cells), 5), nrow = 3,
                 dimnames = list(c("LIG1", "REC1", "PW01"), NULL))
sce <- SingleCellExperiment(assays = list(counts = counts),
                            colData = cells)
pseudo <- aggregateAcrossCells(sce,
                               ids = colData(sce)[, c("donor", "cellType")])

## One object per cell type, with donors as column names and counts divided
## by a library-size factor, as in the paper.
byCellType <- function(type) {
    x <- pseudo[, pseudo$cellType == type]
    colnames(x) <- x$donor
    sizeFactor <- colSums(counts(x)) / median(colSums(counts(x)))
    assay(x, "normcounts") <- sweep(counts(x), 2, sizeFactor, "/")
    x
}
sender <- byCellType("NK")
sender

## ----vcf, message = FALSE-----------------------------------------------------
library(VariantAnnotation)
vcfFile <- system.file("extdata", "chr22.vcf.gz",
                       package = "VariantAnnotation")
vcf <- readVcf(vcfFile, "hg19")
gt <- geno(vcf)$GT
toDosage <- function(g) {
    alleles <- strsplit(g, "[|/]")
    vapply(alleles, function(a) {
        if (any(a == ".")) NA_real_ else sum(a != "0")
    }, numeric(1))
}
dosage <- matrix(toDosage(gt), nrow = nrow(gt), dimnames = dimnames(gt))
vcfGenotypes <- SummarizedExperiment(assays = list(dosage = dosage),
                                     rowRanges = rowRanges(vcf))
vcfGenotypes
assay(vcfGenotypes, "dosage")[1:3, ]

## ----simulate-----------------------------------------------------------------
sim <- simulateMRCCC(n = 300, betaX = 0.3, betaXZ = 0.3, seed = 1)
sim$sender
sim$genotypes
head(colData(sim$receiver))

## ----select-------------------------------------------------------------------
covs <- c("sex", "age", "PC1", "PC2")
ligandSNPs <- selectInstruments(sim$sender, "LIG1", sim$genotypes,
                                covariates = covs)
ligandSNPs

## ----build--------------------------------------------------------------------
dat <- buildTriplet(sim$sender, sim$receiver, sim$genotypes,
                    ligand = "LIG1", receptor = "REC1",
                    pathway = sim$pathwayGenes, covariates = covs,
                    pathwayName = "Simulated pathway",
                    senderName = "Sender", receiverName = "Receiver")
dat

## ----accessorsData------------------------------------------------------------
head(ligandExpression(dat))
dim(ligandGenotypes(dat))
head(covariates(dat), 3)
metadata(dat)$receptorInstruments

## ----constructor--------------------------------------------------------------
dat2 <- MRCCCData(ligandExpression = ligandExpression(dat),
                  receptorExpression = rev(receptorExpression(dat)),
                  pathwayActivity = pathwayActivity(dat),
                  ligandGenotypes = ligandGenotypes(dat),
                  receptorGenotypes = receptorGenotypes(dat),
                  covariates = covariates(dat))
identical(receptorExpression(dat2), receptorExpression(dat))

## ----hyper--------------------------------------------------------------------
mrcccHyperparameters(nu1 = 1e-3)

## ----fit----------------------------------------------------------------------
fit <- mrccc(dat, seed = 1)
fit

## ----accessorsFit-------------------------------------------------------------
pip(fit)
pipMCSE(fit)
effectSizes(fit)
instrumentStrength(fit)
convergence(fit)

## ----summary------------------------------------------------------------------
summary(fit)

## ----ci-----------------------------------------------------------------------
credibleIntervals(fit)
signProbabilities(fit)
signReversal(fit)

## ----curve--------------------------------------------------------------------
plotEffectCurve(fit)

## ----onek1k-------------------------------------------------------------------
ex <- onek1kExample()
ex$sender
ex$receiver
ex$triplets

## ----realFit------------------------------------------------------------------
realCovs <- c("sex", "ageBin", "PC1", "PC2", "PC3")
il18 <- buildTriplet(ex$sender, ex$receiver, ex$genotypes,
                     ligand = "IL18", receptor = "IL18R1",
                     pathway = "interleukinPC1", covariates = realCovs,
                     pathwayName = "Signaling by Interleukin",
                     senderName = "NK cells", receiverName = "Monocytes")
il18
fitIL18 <- mrccc(il18, nIter = 50000, seed = 1)
fitIL18

## ----realSummaries------------------------------------------------------------
firstStageEffects(fitIL18)
signProbabilities(fitIL18)
credibleIntervals(fitIL18, included = TRUE)
signReversal(fitIL18)

## ----screen-------------------------------------------------------------------
settings <- data.frame(betaX = c(0.3, 0.3, 0, 0), betaXZ = c(0.3, 0, 0, 0))
simTriplets <- lapply(seq_len(nrow(settings)), function(k) {
    s <- simulateMRCCC(n = 300, betaX = settings$betaX[k],
                       betaXZ = settings$betaXZ[k], seed = 10 + k)
    buildTriplet(s$sender, s$receiver, s$genotypes,
                 ligand = "LIG1", receptor = "REC1",
                 pathway = s$pathwayGenes, covariates = covs,
                 pathwayName = "Simulated pathway")
})
names(simTriplets) <- c("main+interaction", "main only", "null 1", "null 2")
fits <- mrcccScreen(simTriplets, nIter = 20000, nChains = 2, seed = 1)
screenTable(fits, alpha = 0.10)

## ----bfdr---------------------------------------------------------------------
bfdrSelect(fits, alpha = 0.10)

## ----screenReal, eval = FALSE-------------------------------------------------
# realTriplets <- lapply(seq_len(nrow(ex$triplets)), function(k) {
#     buildTriplet(ex$sender, ex$receiver, ex$genotypes,
#                  ligand = ex$triplets$ligand[k],
#                  receptor = ex$triplets$receptor[k],
#                  pathway = "interleukinPC1", covariates = realCovs,
#                  pathwayName = "Signaling by Interleukin")
# })
# names(realTriplets) <- paste(ex$triplets$ligand, ex$triplets$receptor,
#                              sep = "-")
# realFits <- mrcccScreen(realTriplets, nIter = 100000, seed = 1,
#                         BPPARAM = BiocParallel::MulticoreParam(4))
# screenTable(realFits, alpha = 0.10)

## ----draws--------------------------------------------------------------------
head(posteriorDraws(fit))

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

