## ----setup, include=FALSE-----------------------------------------------------
library(PscanR)

knitr::opts_chunk$set(
    collapse = TRUE,
    comment = "#>",
    fig.align = "center",
    warning = FALSE,
    message = FALSE
)


## ----installation, eval=FALSE-------------------------------------------------
# BiocManager::install("PscanR")

## ----read-gene-sets-----------------------------------------------------------
gene_sets <- read.delim(
    system.file(
        "extdata", "vignettes", "arabidopsis_bpc",
        "arabidopsis_bpc_gene_sets.tsv",
        package = "PscanR"
    ),
    stringsAsFactors = FALSE
)
str(gene_sets)
table(gene_sets$direction)

## ----discover-background------------------------------------------------------
ps_available_bg(keyword = "TAIR9", details = TRUE)

## ----retrieve-background------------------------------------------------------
background <- ps_retrieve_bg(
    jaspar_release = "Jaspar2020",
    org = "at",
    prom_reg = c(-1000, 0),
    assembly = "TAIR9",
    version = 2
)
length(background)

## ----promoter-scheme, message=TRUE--------------------------------------------
promoters <- c("AT1G01110.2", "AT1G01110.1", "AT1G01160.1")
annotation <- data.frame(
    GENE = sub("\\..*$", "", promoters),
    TX = promoters
)

selection <- ps_select_promoters(
    genes = c("AT1G01110", "AT1G01160"),
    promoter_ids = promoters,
    annotation = annotation,
    gene_col = "GENE", transcript_col = "TX",
    mode = "representative"
)

## ----promoter-scheme-table, echo=FALSE----------------------------------------
knitr::kable(
    selection[, c(
        "gene", "promoter_id", "scheme", "suffix_role",
        "transcript_class", "selection_source", "n_candidates", "decided_by"
    )],
    caption = "Selected promoters and the rules used for their selection."
)

## ----tair9-url, include=FALSE-------------------------------------------------
tair9_url <- paste0(
    "https://www.arabidopsis.org/download/list?",
    "dir=Genes/TAIR9_genome_release/tair9_gff3"
)

## ----select-real, eval=FALSE--------------------------------------------------
# 
# down_genes <- gene_sets$gene_id[gene_sets$direction == "down"]
# 
# # Use the TAIR9 annotation used to construct the background.
# 
# tair9_gff <- "TAIR9_GFF3_genes.gff" # path to the downloaded annotation
# 
# txdb <- txdbmaker::makeTxDbFromGFF(
#     tair9_gff, format = "gff3",
#     dataSource = "TAIR9", organism = "Arabidopsis thaliana"
# )
# genome <- BSgenome.Athaliana.TAIR.TAIR9::BSgenome.Athaliana.TAIR.TAIR9
# 
# # The background covers the five nuclear chromosomes.
# tx <- GenomicFeatures::transcripts(txdb, columns = "tx_name")
# tx <- tx[as.character(GenomicRanges::seqnames(tx)) %in% paste0("Chr", 1:5)]
# names(tx) <- GenomicRanges::mcols(tx)$tx_name
# 
# # promoters() takes the region upstream of each 5' end, so it is strand-aware
# # and anchored on the transcription start site.
# ranges <- GenomicRanges::promoters(tx, upstream = 1000, downstream = 0)
# 
# # Exclude out-of-bounds ranges before sequence extraction; getSeq() otherwise
# # raises an error. One transcript is affected here.
# inside <- GenomicRanges::start(ranges) >= 1L &
#     GenomicRanges::end(ranges) <= GenomeInfoDb::seqlengths(genome)[
#         as.character(GenomicRanges::seqnames(ranges))
#     ]
# ranges <- ranges[inside]
# 
# promoters_tair9 <- Biostrings::getSeq(genome, ranges)
# names(promoters_tair9) <- names(ranges)
# 
# # Exclude one additional promoter with more than 50% ambiguous N bases.
# promoters_tair9 <- promoters_tair9[
#     Biostrings::letterFrequency(promoters_tair9, "N", as.prob = TRUE) <= 0.5
# ]
# 
# annotation <- data.frame(
#     GENE = sub("\\..*$", "", names(promoters_tair9)),
#     TX = names(promoters_tair9)
# )
# 
# down_mapping <- ps_select_promoters(
#     genes = down_genes,
#     promoter_sequences = promoters_tair9,
#     annotation = annotation,
#     gene_col = "GENE", transcript_col = "TX",
#     mode = "representative",
#     return = "mapping"
# )
# 
# down_promoters <- promoters_tair9[down_mapping$promoter_id]

## ----load-precomputed---------------------------------------------------------
precomputed <- readRDS(system.file(
    "extdata", "vignettes", "arabidopsis_bpc", "arabidopsis_bpc_results.rds",
    package = "PscanR"
))
down_mapping <- precomputed$down_mapping

## ----selection-summary--------------------------------------------------------
ps_selection_summary(down_mapping)$overall

## ----selection-by-source------------------------------------------------------
ps_selection_summary(down_mapping)$by_source

## ----small-scan---------------------------------------------------------------
small_example <- readRDS(system.file(
    "extdata", "vignettes", "arabidopsis_bpc", "promoter_selection_example.rds",
    package = "PscanR"
))
small_sequences <- ps_select_promoters(
    genes = small_example$genes,
    promoter_sequences = small_example$promoter_sequences,
    annotation = small_example$annotation, gene_col = "GENE",
    transcript_col = "TX", scheme = "tair", mode = "representative",
    return = "sequences"
)
small_background <- precomputed$results_subset[1:2]
small_results <- pscan(small_sequences, small_background)
ps_results_table(small_results)

## ----scan, eval=FALSE---------------------------------------------------------
# 
# BPPARAM <- BiocParallel::SerialParam() # Execute in the current R process.
# 
# # Portable parallel execution with four independent R workers:
# # BPPARAM <- BiocParallel::SnowParam(workers = 4, type = "SOCK")
# 
# # Forked execution on supported Unix-like systems:
# # BPPARAM <- BiocParallel::MulticoreParam(workers = 4)
# 
# results <- pscan(
#     down_promoters, background,
#     BPPARAM = BPPARAM
# )

## ----results-table, eval=FALSE------------------------------------------------
# enrichment <- ps_results_table(results)

## ----load-results-------------------------------------------------------------
# Saved enrichment table for downregulated promoters.
enrichment <- precomputed$enrichment_down
dim(enrichment)

# A motif subset of the PSMatrixList retains the per-promoter results.
results_subset <- precomputed$results_subset
results_subset

## ----subset-names-------------------------------------------------------------
TFBSTools::name(results_subset)

## ----results-table-shown------------------------------------------------------
head(enrichment[order(-enrichment$ZSCORE), ], 6)

## ----bg-table-----------------------------------------------------------------
ps_get_bg_table(results_subset)

## ----top-motifs, fig.width=8, fig.height=5, dpi=120---------------------------

table(ps_motif_class(results_subset))

ps_motif_barplot(results_subset, group = "class")

## ----barplot-composable, eval=FALSE-------------------------------------------
# ps_motif_barplot(results_subset, group = "class") +
#     ggplot2::labs(title = "Downregulated promoters")

## ----accessors----------------------------------------------------------------
abi5 <- results_subset[["MA0931.1"]]
TFBSTools::name(abi5)

ps_zscore(abi5)
ps_pvalue(abi5)
c(background = ps_bg_avg(abi5), foreground = ps_fg_avg(abi5))
ps_hits_size(abi5)

## ----hits-table---------------------------------------------------------------
head(ps_hits_table(abi5), 5)

## ----z-table------------------------------------------------------------------
z <- ps_z_table(results_subset)
dim(z)
round(z[1:4, 1:5], 2)

## ----zscore-heatmap, fig.width=9, fig.height=7, dpi=110-----------------------
ps_zscore_heatmap(
    results_subset, FDR = 0.01,
    show_rownames = FALSE, treeheight_row = 0
)

## ----hitpos-map, fig.width=9, fig.height=7, dpi=110---------------------------
ps_hitpos_map(
    results_subset, FDR = 0.01, shift = -1000,
    show_rownames = FALSE, treeheight_row = 0
)

## ----density-plot, fig.width=7.5, fig.height=4.6, dpi=120---------------------
ps_density_plot(
    abi5,
    shift = -1000, st = "strict",
    window = c(-1000, 0), bins = 20
)

## ----density-plot-bpc6, fig.width=7.5, fig.height=4.6, dpi=120----------------
bpc6_hits <- results_subset[["MA1402.1"]]

ps_density_plot(
    bpc6_hits,
    shift = -1000, st = "strict",
    window = c(-1000, 0), bins = 20
)

## ----hit-score-plot, fig.width=9.5, fig.height=4.6, dpi=115-------------------
ps_hit_score_plot(
    results_subset[c("MA1402.1", "MA0931.1")],
    shift = -1000
)

## ----pscan-filtered, eval=FALSE-----------------------------------------------
# bpc6 <- background[[which(TFBSTools::ID(background) == "MA1402.1")]]
# 
# filtered <- pscan_filtered(
#     down_promoters, bpc6, n = 1,
#     background = background,
#     BPPARAM = BiocParallel::SerialParam()
# )
# ps_results_table(filtered)

## ----filtered-table, echo=FALSE-----------------------------------------------
ft <- precomputed$filtered_bpc6$table
ft <- head(ft[order(-ft$ZSCORE), ], 10)
knitr::kable(
    data.frame(
        motif_id = ft$motif_id, NAME = ft$NAME,
        ZSCORE = round(ft$ZSCORE, 2),
        P.VALUE = format(ft$P.VALUE, scientific = TRUE, digits = 3)
    ),
    row.names = FALSE, align = c("l", "l", "r", "r"),
    caption = paste(
        "Enrichment within the", precomputed$filtered_bpc6$n_retained,
        "promoters with a high-scoring BPC6 match."
    )
)

## ----workflow, eval=FALSE-----------------------------------------------------
# background <- ps_retrieve_bg(
#     "Jaspar2020", "at", c(-1000, 0), "TAIR9", version = 2
# )
# down_promoters <- ps_select_promoters(
#     genes = down_genes, promoter_sequences = promoters_tair9,
#     annotation = annotation, gene_col = "GENE", transcript_col = "TX",
#     mode = "representative", return = "sequences"
# )
# results <- pscan(down_promoters, background)
# ps_results_table(results)

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

