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

## ----init, message = FALSE----------------------------------------------------
library(methylTFR)
library(SummarizedExperiment)
library(ggplot2)
library(ComplexHeatmap)
library(circlize)

## ----palette------------------------------------------------------------------
cell_type_colors <- c(
    "Th-Mem"   = "#41B6C4",
    "Tc-Mem"   = "#4292C6",
    "Tc-Naive" = "#888FB5",
    "Th-Naive" = "#C7E9B4",
    "B-cell"   = "#AE017E",
    "NK-cell"  = "#A65628",
    "Monocyte" = "#CC4C02"
)

## ----load---------------------------------------------------------------------
load(system.file("extdata", "immuneDeviations.rda", package = "methylTFR"))
immuneDeviations

table(colData(immuneDeviations)$cell_type)

## ----provenance---------------------------------------------------------------
metadata(immuneDeviations)

## ----assays-------------------------------------------------------------------
dev_mat <- deviations(immuneDeviations)
z_mat <- deviationZScores(immuneDeviations)

round(dev_mat[seq_len(3), seq_len(4)], 4)

## ----zscale-------------------------------------------------------------------
summary(as.vector(dev_mat))
summary(apply(z_mat, 1, sd))

## ----pca, fig.height = 4.2----------------------------------------------------
pca <- prcomp(t(dev_mat), center = TRUE, scale. = FALSE)
var_expl <- round(100 * pca$sdev^2 / sum(pca$sdev^2), 1)

pca_df <- data.frame(
    PC1 = pca$x[, 1], PC2 = pca$x[, 2],
    cell_type = colData(immuneDeviations)$cell_type
)

ggplot(pca_df, aes(PC1, PC2, colour = cell_type)) +
    geom_point(size = 2, alpha = 0.85) +
    scale_colour_manual(values = cell_type_colors, name = NULL) +
    labs(
        x = sprintf("PC1 (%.1f%%)", var_expl[1]),
        y = sprintf("PC2 (%.1f%%)", var_expl[2])
    ) +
    theme_classic()

## ----variability--------------------------------------------------------------
variability <- computeZScoreVariability(immuneDeviations, method = "robust")
variability <- variability[order(-variability$variability), ]

head(variability, 8)

## ----helper-------------------------------------------------------------------
compare_subsets <- function(object, naive, memory) {
    grp_all <- colData(object)$cell_type
    keep <- grp_all %in% c(naive, memory)
    grp <- factor(as.character(grp_all[keep]), levels = c(naive, memory))

    dev_sub <- deviations(object)[, keep, drop = FALSE]
    z_sub <- deviationZScores(object)[, keep, drop = FALSE]
    is_naive <- grp == naive

    res <- differentialDeviationTest(
        deviations = dev_sub,
        groups = grp,
        alternative = "two.sided",
        parametric = TRUE,
        padjMethod = "BH"
    )
    res$diff <- res$mean_difference
    res$zdiff <- rowMeans(z_sub[, is_naive, drop = FALSE]) -
        rowMeans(z_sub[, !is_naive, drop = FALSE])
    res[order(res$p_value_adjusted), ]
}

tc_res <- compare_subsets(immuneDeviations, "Tc-Naive", "Tc-Mem")
th_res <- compare_subsets(immuneDeviations, "Th-Naive", "Th-Mem")

head(tc_res, 8)

## ----scales-------------------------------------------------------------------
range(tc_res$diff)
range(tc_res$zdiff)

sum(tc_res$p_value_adjusted < 0.05)
sum(tc_res$p_value_adjusted < 0.05 & abs(tc_res$zdiff) > 0.5)

## ----heatmap, fig.height = 6.8, fig.width = 7.5-------------------------------
top_motifs <- head(
    tc_res$motifs[
        tc_res$p_value_adjusted < 0.05 & abs(tc_res$zdiff) > 0.5
    ], 25
)

sample_order <- order(colData(immuneDeviations)$cell_type)
z_top <- as.matrix(z_mat[top_motifs, sample_order, drop = FALSE])
subset_of <- colData(immuneDeviations)$cell_type[sample_order]

z_lim <- max(abs(z_top))
z_col <- colorRamp2(
    c(-z_lim, 0, z_lim),
    c("#2166AC", "white", "#B2182B")
)

column_ann <- HeatmapAnnotation(
    `cell type` = subset_of,
    col = list(`cell type` = cell_type_colors),
    annotation_name_gp = grid::gpar(fontsize = 8),
    annotation_legend_param = list(`cell type` = list(
        title = "",
        labels_gp = grid::gpar(fontsize = 8)
    ))
)

heat <- Heatmap(
    z_top,
    name = "Z-score",
    col = z_col,
    top_annotation = column_ann,
    column_split = subset_of,
    cluster_columns = FALSE,
    cluster_rows = TRUE,
    show_row_dend = TRUE,
    show_column_names = FALSE,
    row_names_gp = grid::gpar(fontsize = 7),
    column_title_gp = grid::gpar(fontsize = 7),
    row_dend_width = grid::unit(8, "mm"),
    heatmap_legend_param = list(
        title_gp = grid::gpar(fontsize = 8, fontface = "bold"),
        labels_gp = grid::gpar(fontsize = 8),
        legend_height = grid::unit(25, "mm")
    )
)

draw(heat, merge_legend = TRUE)

## ----agreement----------------------------------------------------------------
z_cut <- 0.5

shared <- intersect(tc_res$motifs, th_res$motifs)
tc_i <- match(shared, tc_res$motifs)
th_i <- match(shared, th_res$motifs)

agree <- data.frame(
    motifs = shared,
    tc = tc_res$zdiff[tc_i],
    th = th_res$zdiff[th_i]
)

sig_tc <- tc_res$p_value_adjusted[tc_i] < 0.05 & abs(agree$tc) > z_cut
sig_th <- th_res$p_value_adjusted[th_i] < 0.05 & abs(agree$th) > z_cut

agree$category <- factor(
    ifelse(
        sig_tc & sig_th, "both",
        ifelse(sig_th, "CD4 only", ifelse(sig_tc, "CD8 only", "neither"))
    ),
    levels = c("both", "CD4 only", "CD8 only", "neither")
)

rho <- cor(agree$tc, agree$th)
round(rho, 3)
table(agree$category)

## ----agreeplot, fig.height = 4.6----------------------------------------------
category_colors <- c(
    "both" = "#D7191C",
    "CD4 only" = "#1A9641",
    "CD8 only" = "#2C7BB6",
    "neither" = "grey75"
)

ranked <- agree[order(agree$tc + agree$th), ]
labelled <- rbind(head(ranked, 4), tail(ranked, 4))

agree_ord <- agree[order(agree$category, decreasing = TRUE), ]

ggplot(agree_ord, aes(tc, th)) +
    geom_hline(yintercept = 0, linetype = "dashed", colour = "grey60") +
    geom_vline(xintercept = 0, linetype = "dashed", colour = "grey60") +
    geom_point(aes(colour = category), size = 1.8, alpha = 0.85) +
    geom_text(
        data = labelled, aes(label = motifs),
        size = 3, vjust = -0.8, check_overlap = TRUE
    ) +
    scale_colour_manual(
        values = category_colors,
        breaks = names(category_colors),
        name = "differential in"
    ) +
    labs(
        x = "CD8: Z-score difference (naive - memory)",
        y = "CD4: Z-score difference (naive - memory)",
        title = sprintf("Pearson r = %.2f", rho)
    ) +
    theme_classic() +
    theme(
        legend.position = "bottom",
        axis.title.x = element_text(colour = category_colors[["CD8 only"]]),
        axis.title.y = element_text(colour = category_colors[["CD4 only"]])
    )

## ----fpdata-------------------------------------------------------------------
load(system.file("extdata", "BATF_tf_bindsites.rda", package = "methylTFR"))
load(system.file("extdata", "BATF_gcfreqs.rda", package = "methylTFR"))
load(system.file("extdata", "gcdist_BATF.rda", package = "methylTFR"))
load(system.file("extdata", "msites_sub.rda", package = "methylTFR"))

batf_cell_type <- "T cell"
batf_colour <- cell_type_colors[["Th-Mem"]]

## ----expfootprint, fig.height = 4.2, message = FALSE--------------------------
plotExpectedFootprint(
    motif = "BATF",
    tf_bindsites = tf_bindsites,
    msites = msites_sub,
    sample_name = batf_cell_type,
    gc_dist = gcdist,
    gcfreqs = gcfreqs,
    enhancer = NULL,
    returnPlotData = FALSE
) +
    scale_colour_manual(values = c(
        Observed = batf_colour, Expected = "grey55"
    ))

## ----fpdiff, fig.height = 4.2, message = FALSE--------------------------------
plotMotifFootprint(
    motif = "BATF",
    tf_bindsites = tf_bindsites,
    msites = msites_sub,
    sample_name = batf_cell_type,
    gc_dist = gcdist,
    gcfreqs = gcfreqs,
    enhancer = NULL,
    method = "substraction",
    flankNorm = 50
) +
    scale_colour_manual(values = batf_colour)

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

