## ----global-options, include = FALSE------------------------------------------
knitr::opts_chunk$set(
    warning = FALSE,
    message = FALSE,
    collapse = TRUE,
    comment = "#>",
    # BiocStyle's crop hook needs magick; FALSE does not disable it, only NULL
    crop = NULL
)

cap1 <- paste(
    "Anatomy of a reverse-strand divergence. The highlighted column and",
    "both position rulers are taken from the audit result above; the",
    "segment blocks are the graph defined in this section.")
cap2 <- paste(
    "Walk coverage and the two coordinate conventions. Edge numbers are",
    "zero-based and half-open; base numbers are one-based. Ranges and",
    "totals are taken from the outcome row above.")
cap3 <- paste(
    "How the comprehensive base buckets partition each side. Both bars",
    "are drawn from the values printed above and sum to the reported",
    "source and graph base totals.")

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

## ----setup--------------------------------------------------------------------
library(panpathAudit)

## ----basic--------------------------------------------------------------------
fasta <- system.file("extdata", "example.fa", package = "panpathAudit")
gfa <- system.file("extdata", "example.gfa", package = "panpathAudit")
result <- auditGFA(fasta, gfa)
result

## ----basic-outcomes-----------------------------------------------------------
auditOutcomes(result)[, c("identifier", "status", "record_type")]

## ----result-structure---------------------------------------------------------
as.list(auditSummary(result))
provenance <- auditProvenance(result)
as.list(provenance[c("gfa_version", "path_records", "walk_records")])

## ----mixed-setup--------------------------------------------------------------
workdir <- tempfile("panpathAudit-demo-")
dir.create(workdir)

mixed_fasta <- file.path(workdir, "mixed.fa")
mixed_gfa <- file.path(workdir, "mixed.gfa")

writeLines(c(
    ">same", "ACGT",
    ">changed", "AAAA",
    ">absent", "NN"
), mixed_fasta)

writeLines(c(
    "H\tVN:Z:1.1",
    "S\t1\tACGT",
    "S\t2\tAATA",
    "S\t3\tGG",
    "P\tsame\t1+\t*",
    "P\tchanged\t2+\t*",
    "P\textra\t3+\t*"
), mixed_gfa)

## ----mixed-audit--------------------------------------------------------------
mixed <- auditGFA(mixed_fasta, mixed_gfa)
auditOutcomes(mixed)[, c(
    "identifier", "status", "record_type", "source_length", "graph_length"
)]
auditSummary(mixed)$counts

## ----divergent-setup----------------------------------------------------------
divergent_fasta <- file.path(workdir, "divergent.fa")
divergent_gfa <- file.path(workdir, "divergent.gfa")

writeLines(c(">sample", "ACGA"), divergent_fasta)
writeLines(c(
    "H\tVN:Z:1.1",
    "S\t1\tAC",
    "S\t2\tGT",
    "P\tsample\t1+,2+\t*"
), divergent_gfa)

## ----divergent-audit----------------------------------------------------------
divergent <- auditGFA(divergent_fasta, divergent_gfa)
auditOutcomes(divergent)[, c(
    "status", "divergence_kind", "source_position_1based", "segment",
    "orientation", "traversal_position_1based", "segment_position_1based"
)]

## ----divergent-end------------------------------------------------------------
truncated_fasta <- file.path(workdir, "truncated.fa")
truncated_gfa <- file.path(workdir, "truncated.gfa")

writeLines(c(">sample", "ACGT"), truncated_fasta)
writeLines(c("H\tVN:Z:1.1", "S\t1\tACG", "P\tsample\t1+\t*"), truncated_gfa)

auditOutcomes(auditGFA(truncated_fasta, truncated_gfa))[, c(
    "divergence_kind", "source_position_1based", "source_length",
    "graph_length", "segment"
)]

## ----divergent-reverse--------------------------------------------------------
reverse_fasta <- file.path(workdir, "reverse.fa")
reverse_gfa <- file.path(workdir, "reverse.gfa")

writeLines(c(">sampleB#1#chr1", "ACGTGCAACC"), reverse_fasta)
writeLines(c(
    "H\tVN:Z:1.0",
    "S\t1\tACGT", "S\t2\tTTGA", "S\t3\tCC",
    "P\tsampleB#1#chr1\t1+,2-,3+\t*"
), reverse_gfa)

reverse <- auditGFA(reverse_fasta, reverse_gfa)
auditOutcomes(reverse)[, c(
    "source_position_1based", "segment", "orientation",
    "traversal_position_1based", "segment_position_1based"
)]

## ----fig-div, echo=FALSE, fig.dim=c(7.5, 3.8), fig.cap=cap1-------------------
plot_divergence <- function(row) {
    src <- "ACGTGCAACC"
    gph <- "ACGTTCAACC"
    segs <- list(
        list(name = "1", orient = "+", from = 1, to = 4, seq = "ACGT"),
        list(name = "2", orient = "-", from = 5, to = 8, seq = "TTGA"),
        list(name = "3", orient = "+", from = 9, to = 10, seq = "CC"))
    pos <- row$source_position_1based
    n <- nchar(src)
    pal <- palette.colors(8, "Okabe-Ito")
    hit <- pal[7]; blue <- pal[3]; grey <- "#E9E9E9"; ink <- "#222222"

    old <- par(mar = c(0.2, 0.2, 0.2, 0.2))
    on.exit(par(old))
    plot.new()
    plot.window(xlim = c(-2.9, n + 0.3), ylim = c(0, 7.1))

    cell <- function(i, y0, y1, ch, fill, col) {
        rect(i - 1, y0, i, y1, col = fill, border = "white", lwd = 2)
        text(i - 0.5, (y0 + y1) / 2, ch, col = col, font = 2, cex = 1.05)
    }
    lab <- function(y, txt, cex = 0.9, col = ink)
        text(-0.25, y, txt, adj = c(1, 0.5), cex = cex, col = col)

    for (i in seq_len(n)) {
        on <- i == pos
        cell(i, 6.0, 6.9, substr(src, i, i), if (on) hit else grey,
            if (on) "white" else ink)
        cell(i, 4.9, 5.8, substr(gph, i, i), if (on) hit else grey,
            if (on) "white" else ink)
    }
    lab(6.45, "source")
    lab(5.35, "graph")

    for (sg in segs) {
        rev <- sg$orient == "-"
        rect(sg$from - 1, 3.9, sg$to, 4.6,
            col = if (rev) blue else "#D9D9D9", border = "white", lwd = 2)
        text((sg$from - 1 + sg$to) / 2, 4.25,
            sprintf("%s (%s)  %s", sg$name, sg$orient, sg$seq),
            col = if (rev) "white" else ink, cex = 0.85, font = 2)
    }
    lab(4.25, "segments")

    rs <- segs[[2]]
    k <- rs$to - rs$from + 1
    for (j in seq_len(k)) {
        x <- rs$from - 1 + j - 0.5
        on <- (rs$from + j - 1) == pos
        text(x, 3.25, j, cex = 0.9, col = if (on) hit else ink,
            font = if (on) 2 else 1)
        text(x, 2.65, k - j + 1, cex = 0.9, col = if (on) hit else ink,
            font = if (on) 2 else 1)
    }
    lab(3.25, "traversal position", 0.8)
    lab(2.65, "segment position", 0.8)
    arrows(rs$to - 0.1, 2.1, rs$from - 0.9, 2.1, length = 0.08,
        col = blue, lwd = 2)
    text((rs$from - 1 + rs$to) / 2, 1.75,
        sprintf("%s reverse-complemented = TCAA", rs$seq),
        cex = 0.8, col = blue)

    segments(pos - 0.5, 4.9, pos - 0.5, 4.62, col = hit, lwd = 2)
    text(n / 2, 0.85, sprintf(
        "divergence: source %d  |  segment %s  |  orientation %s",
        pos, row$segment, row$orientation), cex = 0.88, col = ink)
    text(n / 2, 0.3, sprintf(
        "traversal position %d  =  segment position %d",
        row$traversal_position_1based, row$segment_position_1based),
        cex = 0.88, col = hit, font = 2)
}

plot_divergence(as.data.frame(auditOutcomes(reverse)))

## ----digests------------------------------------------------------------------
as.data.frame(auditOutcomes(divergent)[, c("source_sha256", "graph_sha256")])

## ----mapping-unmapped---------------------------------------------------------
walk_gfa <- system.file("extdata", "walk.gfa", package = "panpathAudit")

plain_fasta <- file.path(workdir, "chr1.fa")
writeLines(c(">chr1", "ACGTGT"), plain_fasta)

auditOutcomes(auditGFA(plain_fasta, walk_gfa))[, c(
    "identifier", "status", "record_type"
)]

## ----mapping------------------------------------------------------------------
mapping <- data.frame(
    mode = "pansn", sample = "sample", haplotype = "1", prefix = ""
)
mapped <- auditGFA(plain_fasta, walk_gfa, mapping = mapping)
auditOutcomes(mapped)[, c("identifier", "status", "record_type")]

## ----walks--------------------------------------------------------------------
walk_fasta <- system.file("extdata", "walk.fa", package = "panpathAudit")
walk_result <- auditGFA(walk_fasta, walk_gfa)
auditOutcomes(walk_result)[, c(
    "identifier", "status", "source_start_0based",
    "source_end_0based_exclusive", "addressed_source_bases", "source_length"
)]

## ----fig-cov, echo=FALSE, fig.dim=c(6.8, 3.6), fig.cap=cap2-------------------
plot_coverage <- function(
    row, seq = "ACGTGT", walks = list(c(0, 2), c(4, 6))) {
    n <- nchar(seq)
    pal <- palette.colors(8, "Okabe-Ito")
    green <- pal[4]; grey <- "#E9E9E9"; ink <- "#222222"; mute <- "#777777"
    covered <- rep(FALSE, n)
    for (w in walks) covered[(w[1] + 1):w[2]] <- TRUE

    old <- par(mar = c(0.2, 0.2, 0.2, 0.2))
    on.exit(par(old))
    plot.new()
    plot.window(xlim = c(-3.0, n + 0.4), ylim = c(0, 6.2))

    for (i in seq_len(n)) {
        on <- covered[i]
        rect(i - 1, 3.5, i, 4.5, col = if (on) green else grey,
            border = "white", lwd = 2)
        text(i - 0.5, 4.0, substr(seq, i, i), font = 2, cex = 1.05,
            col = if (on) "white" else mute)
    }
    text(-0.3, 4.0, "contig", adj = c(1, 0.5), cex = 0.85, col = ink)

    for (e in 0:n) {
        segments(e, 4.55, e, 4.85, col = mute, lwd = 1)
        text(e, 5.15, e, cex = 0.85, col = ink)
    }
    text(-0.3, 5.15, "0-based edges", adj = c(1, 0.5), cex = 0.85, col = ink)
    text(n / 2, 5.75, "zero-based, half-open: boundaries between bases",
        cex = 0.82, col = mute)

    for (i in seq_len(n)) text(i - 0.5, 3.1, i, cex = 0.85, col = ink)
    text(-0.3, 3.1, "1-based bases", adj = c(1, 0.5), cex = 0.85, col = ink)

    for (w in walks) {
        segments(w[1] + 0.06, 2.45, w[2] - 0.06, 2.45, col = green, lwd = 3)
        text(mean(w), 2.05, sprintf("W [%d, %d)", w[1], w[2]),
            cex = 0.8, col = green)
    }
    gap <- which(!covered)
    segments(min(gap) - 0.94, 2.45, max(gap) - 0.06, 2.45,
            col = mute, lwd = 2, lty = 3)
    text(mean(gap) - 0.5, 2.05, sprintf("not_embedded (%d)", length(gap)),
        cex = 0.8, col = mute)
    text(-0.3, 2.45, "walk ranges", adj = c(1, 0.5), cex = 0.85, col = mute)

    segments(row$source_start_0based + 0.06, 1.3,
            row$source_end_0based_exclusive - 0.06, 1.3,
            col = ink, lwd = 1.5)
    text(n / 2, 0.9, sprintf("outcome row spans [%d, %d)",
        row$source_start_0based, row$source_end_0based_exclusive),
        cex = 0.8, col = ink)
    text(n / 2, 0.3, sprintf(
        "addressed_source_bases = %d   of   source_length = %d",
        row$addressed_source_bases, row$source_length),
        cex = 0.88, col = ink, font = 2)
}

plot_coverage(as.data.frame(auditOutcomes(walk_result)))

## ----dnastringset, eval = requireNamespace("Biostrings", quietly = TRUE)------
chr1 <- Biostrings::DNAStringSet(c(chr1 = "ACGTGT"))
from_memory <- auditGFA(chr1, walk_gfa, mapping = mapping)
auditOutcomes(from_memory)[, c("identifier", "status", "record_type")]
auditProvenance(from_memory)$fasta

## ----comprehensive------------------------------------------------------------
detailed <- auditGFA(mixed_fasta, mixed_gfa, statistics = "comprehensive")
names(auditStatistics(detailed))

global <- auditStatistics(detailed)$global
global$bases

## ----fig-part, echo=FALSE, fig.dim=c(6.8, 2.9), fig.cap=cap3------------------
plot_partition <- function(bases, global) {
    pal <- palette.colors(8, "Okabe-Ito")
    spec <- list(
        matched        = list(col = pal[4], lab = "matched"),
        substituted    = list(col = pal[7], lab = "substituted"),
        source_only    = list(col = pal[2], lab = "source_only"),
        graph_only     = list(col = pal[2], lab = "graph_only"),
        not_embedded   = list(col = "#BBBBBB", lab = "not_embedded"),
        missing_path   = list(col = pal[3], lab = "missing_path"),
        missing_source = list(col = pal[8], lab = "missing_source"))
    sides <- list(
        source = c("matched", "substituted", "source_only",
                "not_embedded", "missing_path"),
        graph  = c("matched", "substituted", "graph_only", "missing_source"))
    totals <- c(source = global$source_bases, graph = global$graph_bases)
    used <- character()

    old <- par(mar = c(0.2, 0.2, 0.2, 0.2))
    on.exit(par(old))
    plot.new()
    xmax <- max(totals)
    plot.window(xlim = c(-2.7, xmax + 0.3), ylim = c(-1.7, 3.0))
    ys <- c(source = 2.05, graph = 0.85)

    for (nm in names(sides)) {
        x <- 0
        y <- ys[[nm]]
        for (k in sides[[nm]]) {
            v <- bases[[k]]
            if (is.null(v) || v <= 0) next
            used <- c(used, k)
            rect(x, y - 0.38, x + v, y + 0.38, col = spec[[k]]$col,
                border = "white", lwd = 2)
            text(x + v / 2, y, v, col = "white", font = 2, cex = 0.95)
            x <- x + v
        }
        text(-0.3, y, sprintf("%s bases", nm), adj = c(1, 0.5), cex = 0.9)
        text(xmax + 0.25, y, totals[[nm]], adj = c(0, 0.5), cex = 0.85,
            col = "#777777")
    }

    used <- unique(used)
    per <- xmax / max(length(used), 1)
    for (i in seq_along(used)) {
        k <- used[[i]]
        x0 <- (i - 1) * per
        rect(x0, -0.75, x0 + 0.42, -0.42, col = spec[[k]]$col,
            border = "white")
        text(x0 + 0.58, -0.58, spec[[k]]$lab, adj = c(0, 0.5), cex = 0.72)
    }
    text(xmax / 2, -1.35,
        "matched and substituted are aligned columns, on both sides",
        cex = 0.75, col = "#777777")
}

plot_partition(global$bases, global)

## ----comprehensive-rows-------------------------------------------------------
auditOutcomes(detailed)[, c(
    "identifier", "status", "matched", "substituted", "edit_distance",
    "alignment_status"
)]

## ----telemetry----------------------------------------------------------------
as.list(auditTelemetry(detailed))

## ----diagnostics--------------------------------------------------------------
diagnostics <- tryCatch(
    auditGFA(file.path(tempdir(), "missing.fa"), gfa),
    panpathAudit_error = function(error) error$diagnostics
)
diagnostics[, c("category", "code", "message")]

## ----citation-----------------------------------------------------------------
citation("panpathAudit")

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

