## ----message=FALSE------------------------------------------------------------
library(betterChromVAR)
library(SummarizedExperiment)
data("NR3C1example", package="betterChromVAR")
peakSE
motifMatches

## -----------------------------------------------------------------------------
dev <- betterChromVAR(peakSE, motifMatches)
dev

## -----------------------------------------------------------------------------
fit <- fitDeviations(dev, design=~group)
DAA <- as.data.frame(limma::topTable(fit, coef=2))
DAA

## ----message=FALSE------------------------------------------------------------
idev <- getInteractionsDeviations(peakSE, motifMatches, bait="GCR", minCount=10)
table(rowData(idev)$set)

## -----------------------------------------------------------------------------
res <- discoverMotifInteractions(idev, "group")
head(res)

## -----------------------------------------------------------------------------
library(ggplot2)
ggplot(res, aes(difference, -log10(adj.P.Val), size=overlap.N, label=motif)) + 
  geom_text() + theme_bw()

## ----eval=FALSE---------------------------------------------------------------
# library(BSgenome.Hsapiens.UCSC.hg38)
# 
# # we precompute the betterChromVAR background to save computing time in case
# # we check many interactions:
# bg <- computeBackgrounds(peakSE, getBackgroundBins(peakSE))
# 
# # `motifs` is a list of motifs (e.g. a PFMatrixList, as provided in the example
# # data); we look at two potential partners of GCR:
# didevs <- lapply(c(JUND="JUND", CTCFL="CTCFL"), \(mo){
#   exploreMotifInteraction(peakSE, motifs[c("GCR", mo)], bg = bg,
#                           genome=BSgenome.Hsapiens.UCSC.hg38)
# })

## ----fig.width=10, fig.height=4-----------------------------------------------
dd <- do.call(rbind, lapply(names(didevs), \(mo){
  didev <- didevs[[mo]]
  d <- data.frame(feature=rep(row.names(didev), ncol(didev)),
                  group=rep(didev$group, each=nrow(didev)),
                  norm=as.vector(SummarizedExperiment::assay(didev, "norm")))
  d$feature <- factor(d$feature, row.names(didev))
  d$query <- mo
  d
}))
ggplot(dd, aes(feature, norm)) + geom_hline(yintercept=0, linetype="dashed") + 
  geom_boxplot(aes(fill=group)) + facet_wrap(~query, scale="free") + 
  theme_bw() + labs(x="Site type", y="Adjusted z-scores") + 
  theme(axis.text.x=element_text(angle=90, hjust=1, vjust=0.5))

## -----------------------------------------------------------------------------
design <- model.matrix(~group, data=as.data.frame(colData(peakSE)))
y <- limma::voom(assay(peakSE), design)
dea <- limma::topTable(limma::eBayes(limma::lmFit(y, design)), coef=2, number=Inf, sort.by="none")
pk <- peakLevelMotifTests(peakSE, dea, motifMatches, design=design, 
                          minCount=10)
head(pk[,c("motif","N","difference","P.Value","adj.P.Val")])

## -----------------------------------------------------------------------------
res2 <- peakLevelMotifInteractions(peakSE, motifMatches, bait="GCR", 
                                   group="group", minCount=10)
head(res2[,c("motif","overlap.N","difference","se","P.Value","adj.P.Val",
             "partner.diff")])

## ----fig.width=5, fig.height=4------------------------------------------------
fit <- fitDeviations(dev, design)
tt <- limma::topTable(fit, coef=2, number=Inf, sort.by="none")
cmp1 <- merge(data.frame(motif=row.names(tt), t.deviations=tt$t, 
                         FDR.deviations=tt$adj.P.Val),
              data.frame(pk[,c("motif","N","t","adj.P.Val")]), by="motif")
colnames(cmp1)[5:6] <- c("t.peaks", "FDR.peaks")
ggplot(cmp1, aes(t.deviations, t.peaks, label=motif)) + 
  geom_hline(yintercept=0, linetype="dashed") + 
  geom_vline(xintercept=0, linetype="dashed") +
  geom_point(aes(size=N), alpha=0.5) + geom_text(check_overlap=TRUE, vjust=-1) +
  theme_bw() + labs(x="t-value (deviations)", y="t-value (peak-level)")

## ----fig.width=5, fig.height=4------------------------------------------------
cmp2 <- merge(res[,c("motif","overlap.N","t","adj.P.Val")], 
              res2[,c("motif","t","adj.P.Val")], by="motif",
              suffixes=c(".sample",".peak"))
ggplot(cmp2, aes(t.sample, t.peak, label=motif)) + 
  geom_hline(yintercept=0, linetype="dashed") + 
  geom_vline(xintercept=0, linetype="dashed") +
  geom_point(aes(size=overlap.N), alpha=0.5) + 
  geom_text(check_overlap=TRUE, vjust=-1) + theme_bw() + 
  labs(x="t-value (sample-level)", y="t-value (peak-level)")

## -----------------------------------------------------------------------------
set.seed(1234)
nr <- nrow(peakSE)
rnd <- sapply(round(exp(runif(100, 6, 9))), function(n){
  x <- logical(nr)
  x[sample.int(nr, n)] <- TRUE
  x
})
colnames(rnd) <- paste0("random", seq_len(ncol(rnd)))
rnd <- cbind(GCR=as.vector(assay(motifMatches)[,"GCR"]), rnd)

ridev <- getInteractionsDeviations(peakSE, rnd, bait="GCR")
rres <- discoverMotifInteractions(ridev, "group")
rres2 <- peakLevelMotifInteractions(peakSE, rnd, bait="GCR", group="group")

data.frame(approach=c("deviations", "peak-level"),
           `% p<0.05`=c(sum(rres$P.Value<0.05),
                                 sum(rres2$P.Value<0.05)), check.names=FALSE)

## ----sessionInfo, echo=FALSE--------------------------------------------------
sessionInfo()

