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

## ----load-package-------------------------------------------------------------
library(selexprepR)

## ----real-fastq-paths---------------------------------------------------------
rounds <- c(3L, 5L, 7L)
paths <- system.file(
    "extdata", sprintf("cs_round_%02d.fastq.gz", rounds),
    package = "selexprepR", mustWork = TRUE
)
names(paths) <- sprintf("round_%02d", rounds)
reads <- read_selexprep_fastq(paths[[1L]])
length(reads)
head(reads)

## ----round-aware-inputs-------------------------------------------------------
inputs <- read_selexprep_inputs(paths)
inputs$files[, c("round_number", "mate", "reads_loaded", "sha256")]
vapply(inputs$sequences_by_round, length, integer(1))

## ----detect-layout------------------------------------------------------------
report <- selexprep_detect(inputs$sequences_by_round)
report[c(
    "status", "failure_reason", "primer_5p", "primer_3p", "extraction_mode"
)]

## ----explicit-boundaries------------------------------------------------------
published_5p <- "GGCTCTCGGGACGAC"
published_3p <- "CTGCGTTCTCCATTCTGG"
primer_5p <- reverse_complement(published_3p)
primer_3p <- reverse_complement(published_5p)

## ----file-workflow------------------------------------------------------------
experiment <- run_selexprep_files(
    paths, primer_5p = primer_5p, primer_3p = primer_3p,
    extraction_mode = "BOTH_PRIMERS_SINGLE_READ"
)
experiment
counts <- SummarizedExperiment::assay(experiment, "counts")
round_info <- SummarizedExperiment::colData(experiment)
stopifnot(identical(colnames(counts), rownames(round_info)))
data.frame(
    round = round_info$round,
    counted_reads = unname(Matrix::colSums(counts))
)
head(SummarizedExperiment::rowData(experiment))

## ----provenance-and-yields----------------------------------------------------
metadata <- S4Vectors::metadata(experiment)
metadata$extraction$input_reads
metadata$extraction$output_reads
metadata$extraction$input_yields
metadata$input_files[, c("round_number", "reads_loaded", "md5")]
metadata$manifest$manifest_version

## ----both-orientations, warning = FALSE---------------------------------------
opposite <- run_selexprep_files(
    paths,
    primer_5p = reverse_complement(primer_3p),
    primer_3p = reverse_complement(primer_5p),
    extraction_mode = "BOTH_PRIMERS_SINGLE_READ"
)
other <- SummarizedExperiment::assay(opposite, "counts")
rownames(other) <- reverse_complement(rownames(other))
sequences <- union(rownames(counts), rownames(other))
both <- Matrix::Matrix(
    0, length(sequences), ncol(counts),
    dimnames = list(sequences, colnames(counts)), sparse = TRUE
)
both[rownames(counts), ] <- counts
both[rownames(other), ] <- both[rownames(other), ] + other
rbind(
    chosen = Matrix::colSums(counts), opposite = Matrix::colSums(other),
    both = Matrix::colSums(both)
)

## ----qc-tables----------------------------------------------------------------
qc <- metadata$qc
qc$per_round
qc$flags[, c("name", "severity")]

## ----qc-retention, fig.width=6, fig.height=3.6, dpi=160, out.width="100%", fig.cap="Input and retained reads by round."----
plot(qc, experiment, which = "retention", cex = 1.2)

## ----qc-length, fig.width=6, fig.height=3.6, dpi=160, out.width="100%", fig.cap="Read-weighted lengths of the extracted regions."----
plot(qc, experiment, which = "length", cex = 1.2)

## ----qc-diversity, fig.width=6, fig.height=9.6, dpi=160, out.width="100%", fig.cap="Sequence diversity within each retained round."----
plot(qc, experiment, which = "diversity", mfrow = c(3, 1), cex = 1.15,
    mar = c(5.3, 5.5, 2.5, 1), mgp = c(3.7, 0.7, 0))

## ----demultiplex--------------------------------------------------------------
barcodes <- c(AAAAA = 3L, CCCCC = 5L, GGGGG = 7L)
tagged <- Map(function(pool, barcode) {
    paste0(barcode, as.character(pool))
}, inputs$sequences_by_round, names(barcodes))
multiplexed <- c(unlist(tagged, use.names = FALSE), "TTTTTACGT")
demultiplexed <- selexprep_demultiplex(multiplexed, barcodes)
demultiplexed$summary
length(demultiplexed$unassigned$r1)

sequences_only <- function(pools) {
    lapply(pools, function(pool) unname(as.character(pool)))
}
stopifnot(identical(
    sequences_only(demultiplexed$sequences_by_round),
    sequences_only(inputs$sequences_by_round)
))
demultiplexed_experiment <- run_selexprep(
    demultiplexed, primer_5p = primer_5p, primer_3p = primer_3p,
    extraction_mode = "BOTH_PRIMERS_SINGLE_READ"
)
stopifnot(identical(
    SummarizedExperiment::assay(demultiplexed_experiment, "counts"), counts
))

## ----save-decisions-----------------------------------------------------------
outdir <- tempfile("selexprep_example_")
dir.create(outdir)
write_library_report(metadata$library_report,
    file.path(outdir, "library_report.json"))
write_selexprep_manifest(metadata$manifest,
    file.path(outdir, "selexprep_manifest.json"))
list.files(outdir)

## ----export-counts------------------------------------------------------------
round_numbers <- sort(unique(metadata$input_files$round_number))
round_numbers
count_tables <- lapply(metadata$extraction$sequences_by_round, selexprep_count)
stopifnot(identical(
    vapply(count_tables, function(table) sum(table$reads), numeric(1)),
    Matrix::colSums(counts)
))
for (round in names(count_tables)) {
    write_selexprep_counts(count_tables[[round]],
        file.path(outdir, paste0(round, "_counts.tsv")))
}
list.files(outdir)
head(read_selexprep_counts(file.path(outdir, "round_03_counts.tsv")), 3)

## ----public-catalog-----------------------------------------------------------
selexprep_catalog("hydrocortisone")
data("selexprep_public_catalog", package = "selexprepR")
S4Vectors::metadata(selexprep_public_catalog)$snapshot_version

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

