From 6a7952cef0c18273b07512740fb38bc460246d0b Mon Sep 17 00:00:00 2001 From: plotgardenerNeo contributors Date: Thu, 12 Nov 2026 15:36:17 -0600 Subject: [PATCH 1/2] Add plotgardenerNeo core modifications --- .Rbuildignore | 4 + .gitignore | 4 + DESCRIPTION | 5 +- NAMESPACE | 16 + NEWS.md | 88 ++ R/annoGenomeLabel.R | 75 +- R/annoPixels.R | 19 +- R/annoXaxis.R | 64 +- R/annoYaxis.R | 69 +- R/assembly.R | 27 +- R/axisFunctions.R | 51 + R/hicFunctions.R | 57 +- R/neoAssembly.R | 300 +++++ R/neoSignal.R | 202 ++++ R/pageCreate.R | 3 + R/pageExport.R | 119 ++ R/pageGuideHide.R | 43 +- R/pagePlotRemove.R | 38 +- R/pageRedraw.R | 35 + R/plotGenes.R | 25 +- R/plotHicRectangle.R | 62 +- R/plotHicSquare.R | 204 +++- R/plotHicTriangle.R | 129 ++- R/plotLegend.R | 4 + R/plotMultiSignal.R | 35 +- R/plotNeo.R | 1341 ++++++++++++++++++++++ R/plotSignal.R | 163 +-- R/plotTranscripts.R | 26 +- R/plotgardener.R | 2 + R/readCool.R | 369 ++++-- R/readNeoGenes.R | 379 ++++++ R/readNeoHic.R | 548 +++++++++ R/readingFunctions.R | 19 +- man/annoNeoDomains.Rd | 67 ++ man/annoNeoFragmentLabels.Rd | 120 ++ man/annoXaxis.Rd | 27 + man/annoYaxis.Rd | 27 + man/assembly.Rd | 9 +- man/dot-checkCool.Rd | 9 +- man/dot-coolAutoNorm.Rd | 19 + man/dot-coolAutoResolution.Rd | 8 +- man/dot-coolMatchChrom.Rd | 19 + man/dot-coolRegion.Rd | 8 +- man/dot-pullBinChunks.Rd | 12 +- man/getNeoSignal.Rd | 46 + man/getNeoV4C.Rd | 30 + man/mapNeoFeatures.Rd | 33 + man/pageExport.Rd | 59 + man/pageGuideHide.Rd | 21 +- man/pagePlotRemove.Rd | 10 +- man/pageRedraw.Rd | 16 + man/plotGenes.Rd | 10 + man/plotHicRectangle.Rd | 16 +- man/plotHicSquare.Rd | 89 +- man/plotHicTriangle.Rd | 20 +- man/plotLegend.Rd | 5 + man/plotMultiSignal.Rd | 14 +- man/plotNeoAssembly.Rd | 104 ++ man/plotNeoGenes.Rd | 190 +++ man/plotNeoHic.Rd | 40 + man/plotSignal.Rd | 19 +- man/plotTranscripts.Rd | 7 +- man/readCool.Rd | 14 +- man/readCoolNorms.Rd | 17 +- man/readNeoAssembly.Rd | 66 ++ man/readNeoHic.Rd | 85 ++ tests/testthat/helper-mcool.R | 73 ++ tests/testthat/test-annoPixels-factors.R | 27 + tests/testthat/test-axis-fixes.R | 70 ++ tests/testthat/test-hic-interchrom.R | 82 ++ tests/testthat/test-hic-raster.R | 63 + tests/testthat/test-neo.R | 1049 +++++++++++++++++ tests/testthat/test-pageExport.R | 48 + tests/testthat/test-readCool.R | 190 +++ tests/testthat/test-reading-order.R | 30 + tests/testthat/test-readingFunctions.R | 22 +- tests/testthat/test-signal-fixes.R | 70 ++ vignettes/neo_reconstruction.Rmd | 304 +++++ 78 files changed, 7364 insertions(+), 425 deletions(-) create mode 100644 R/axisFunctions.R create mode 100644 R/neoAssembly.R create mode 100644 R/neoSignal.R create mode 100644 R/pageExport.R create mode 100644 R/pageRedraw.R create mode 100644 R/plotNeo.R create mode 100644 R/readNeoGenes.R create mode 100644 R/readNeoHic.R create mode 100644 man/annoNeoDomains.Rd create mode 100644 man/annoNeoFragmentLabels.Rd create mode 100644 man/dot-coolAutoNorm.Rd create mode 100644 man/dot-coolMatchChrom.Rd create mode 100644 man/getNeoSignal.Rd create mode 100644 man/getNeoV4C.Rd create mode 100644 man/mapNeoFeatures.Rd create mode 100644 man/pageExport.Rd create mode 100644 man/pageRedraw.Rd create mode 100644 man/plotNeoAssembly.Rd create mode 100644 man/plotNeoGenes.Rd create mode 100644 man/plotNeoHic.Rd create mode 100644 man/readNeoAssembly.Rd create mode 100644 man/readNeoHic.Rd create mode 100644 tests/testthat/helper-mcool.R create mode 100644 tests/testthat/test-annoPixels-factors.R create mode 100644 tests/testthat/test-axis-fixes.R create mode 100644 tests/testthat/test-hic-interchrom.R create mode 100644 tests/testthat/test-hic-raster.R create mode 100644 tests/testthat/test-neo.R create mode 100644 tests/testthat/test-pageExport.R create mode 100644 tests/testthat/test-readCool.R create mode 100644 tests/testthat/test-reading-order.R create mode 100644 tests/testthat/test-signal-fixes.R create mode 100644 vignettes/neo_reconstruction.Rmd diff --git a/.Rbuildignore b/.Rbuildignore index 272c50b10..7b8df3192 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -7,3 +7,7 @@ ^LICENSE\.md$ ^icons$ ^\.github$ +^\.Rlib$ +^scripts$ +^DEV_PLAN\.md$ +^install_deps\.log$ diff --git a/.gitignore b/.gitignore index e43efbdf8..61da19830 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,11 @@ .Rhistory .RData .Ruserdata +.Rlib/ +install_deps.log src/*.o src/*.so src/*.dll .DS_Store +install_extra.log +Rplots.pdf diff --git a/DESCRIPTION b/DESCRIPTION index 68017d517..f6b34b534 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: plotgardener Title: Coordinate-Based Genomic Visualization Package for R -Version: 1.15.1 +Version: 1.15.1.9000 Date: 2024-06-28 Authors@R: c( person("Nicole", "Kramer", email = "nekramer27@gmail.com", @@ -65,12 +65,15 @@ Suggests: BSgenome, BSgenome.Hsapiens.UCSC.hg19, ComplexHeatmap, + digest, + ensembldb, GenomicFeatures, ggplot2, InteractionSet, knitr, org.Hs.eg.db, rtracklayer, + Rsamtools, plotgardenerData, pdftools, png, diff --git a/NAMESPACE b/NAMESPACE index 0fb725326..72bfe44d1 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -4,6 +4,8 @@ export(annoDomains) export(annoGenomeLabel) export(annoHeatmapLegend) export(annoHighlight) +export(annoNeoDomains) +export(annoNeoFragmentLabels) export(annoPixels) export(annoSegments) export(annoText) @@ -16,8 +18,12 @@ export(calcSignalRange) export(colorby) export(defaultPackages) export(genomes) +export(getNeoSignal) +export(getNeoV4C) export(mapColors) +export(mapNeoFeatures) export(pageCreate) +export(pageExport) export(pageGuideHide) export(pageGuideHorizontal) export(pageGuideShow) @@ -26,6 +32,7 @@ export(pageLayoutCol) export(pageLayoutRow) export(pagePlotPlace) export(pagePlotRemove) +export(pageRedraw) export(pgParams) export(plotCircle) export(plotGG) @@ -38,6 +45,9 @@ export(plotIdeogram) export(plotLegend) export(plotManhattan) export(plotMultiSignal) +export(plotNeoAssembly) +export(plotNeoHic) +export(plotNeoGenes) export(plotPairs) export(plotPairsArches) export(plotPolygon) @@ -54,6 +64,8 @@ export(readCoolBpResolutions) export(readCoolChroms) export(readCoolNorms) export(readHic) +export(readNeoAssembly) +export(readNeoHic) import(grid) importFrom(GenomeInfoDb,keepStandardChromosomes) importFrom(GenomicRanges,GRanges) @@ -76,6 +88,7 @@ importFrom(ggplotify,as.grob) importFrom(ggplotify,base2grob) importFrom(glue,glue) importFrom(glue,glue_collapse) +importFrom(grDevices,as.raster) importFrom(grDevices,colorRampPalette) importFrom(grDevices,dev.size) importFrom(methods,hasArg) @@ -90,10 +103,13 @@ importFrom(rlang,abort) importFrom(rlang,arg_match) importFrom(rlang,inform) importFrom(rlang,warn) +importFrom(stats,aggregate) importFrom(stats,na.omit) importFrom(strawr,readHicBpResolutions) importFrom(strawr,straw) importFrom(tools,file_ext) importFrom(utils,str) importFrom(withr,with_pdf) +S3method(print,neoAssembly) +S3method(print,neoHic) useDynLib(plotgardener) diff --git a/NEWS.md b/NEWS.md index 34ab53bb3..3a5c19cc5 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,91 @@ +# DEVELOPMENT VERSION +## NEW FEATURES + +* Added `pageExport()` for writing the current page to PDF, PNG, TIFF, JPEG, + or SVG without a user `dev.off()` call. +* `pageGuideHide()` and `pagePlotRemove()` now defer removals until + `pageExport()`/`pageRedraw()` instead of calling `grid.remove()` on the + active device, avoiding extra PDF pages. +* `plotHicSquare()`, `plotHicRectangle()`, and `plotHicTriangle()` gain + `raster = c("auto", "never", "always")` and `raster.max` for rasterizing + large contact maps. +* `plotSignal()` gains `label.position`, `label.offset`, numeric baselines, + and `baseline.lty`. Baselines are now drawn after signal/cutoff grobs so + filled tracks cannot cover them. +* `plotMultiSignal()` now honors a user-supplied `range` and passes through + label/baseline styling parameters. +* `annoYaxis()` and `annoXaxis()` gain `tcl`, `label.offset`, + `axisLine.lwd/col/lty`, and `tick.lwd/col/lty` for flexible axis styling. + Default tick length is now shorter (`tcl = 0.25`) and default tick/axis + line width is thinner (`0.5`). +* `plotNeoGenes()` now uses IGV-style display modes. `displayMode = "auto"` + collapses genes to solid blocks at whole-chromosome scale and expands to + gene bodies, exon blocks, UTR/CDS heights, and strand arrows when zoomed + in. It supports `chromstart`/`chromend` neo-coordinate windows, arbitrary + GTF/GFF GENCODE versions, `TxDb`/`OrgDb` annotations, `geneOrder`, + `labelClusters`, `geneBackground`, configurable colors, gene highlights, + label collision suppression, row-overflow warnings, and `geneMode` + layouts: `"expand"` draws all genes normally, `"focus"` fades non-priority + genes with `focus.alpha`, and `"compact"` draws all genes on one line. + GTF/GFF files are read with `readGFF()` by default and can use an optional + disk cache. +* Added `getNeoSignal()` and `getNeoV4C()` for mapping bigWig, GRanges, + data-frame, and virtual-4C signal tracks into neo-chromosome coordinates, + with optional binning and aggregation. +* `plotNeoHic(flip = "horizontal")` reverses the x-axis for neo Hi-C plots. +* `annoNeoDomains()` and `plotNeoAssembly()` expose separate seam color, + width, and line type, and `annoNeoFragmentLabels(label.colors=)` supports + per-fragment label colors. +* Interchromosomal `plotHicSquare()` plots are no longer mirrored and store + explicit x/y chromosome metadata for `annoGenomeLabel()`. Add + `aspect = "fixed"` for equal basepairs-per-inch on unequal-length + chromosomes. +* Added SV-impacted neo-chromosome reconstruction helpers: + `readNeoAssembly()`, `mapNeoFeatures()`, `readNeoHic()`, `plotNeoHic()`, + `plotNeoAssembly()`, `annoNeoDomains()`, and `annoNeoFragmentLabels()`. + `readNeoHic()` stitches fragment-pair contacts from `.hic`, `.cool`, or + `.mcool` files into a concatenated neo-chromosome coordinate system. + `annoNeoDomains()` draws the solid outer neo-chromosome domain and dotted + internal fragment seams used in the neo-triangle examples. + +* `plotTranscripts()` adds `labelPriority` and centers labels on the + in-bounds transcript portion. +* `plotGenes()` adds `labelClusters`/`labelClusterRot` for dense gene + clusters. +* Added `plotNeoGenes()` for gene/transcript models mapped into neo + coordinates, including strand flips, gene highlights, and selected labels. `readNeoHic()` now reports + fragment-pair contact counts and warns when inter-fragment pairs have no + source contacts. +* `assembly()` accepts an `EnsDb` object and converts it to a TxDb for + plotting. +* `read_rangeData()` respects named `chrom`/`start`/`end` or `chrom`/`pos` + columns in any order. +* `annoPixels()` handles factor chromosome columns with different level sets. +* `plotLegend()` documents the cairosvg/SVG rendering caveat. + +## BUG FIXES + +* `readCool()` now returns all pixels in the final bin of a region. The +previous pixel-range calculation stopped at the first pixel of the last bin. +* `readCool()` applies cooler balancing weights multiplicatively +(`counts * weight1 * weight2`) instead of dividing by them. This also applies +to `sweight`, `KR`, `VC`, and `VC_SQRT` weights. +* `readCoolNorms()` now returns the exact column names stored in the file +(for example `weight`, `sweight`, `KR`, or `obj_weight`) instead of mapping +`weight` to `BALANCE`. +* `readCool()` accepts chromosome names with or without a `chr` prefix and +matches regions that do not start exactly on a bin boundary. +* `readCool()` now reads interchromosomal mcool pixels when the requested +`chrom` comes after `altchrom` in the file, and expands both coordinates for +same-chromosome off-diagonal regions. +* `readCool()` supports `norm = "auto"`, and `plotHicSquare()`, +`plotHicRectangle()`, and `plotHicTriangle()` now use `norm = "auto"` by +default. For `.hic` files this resolves to `"KR"`; for `.(m)cool` files it +chooses an available weight. +* Hi-C plotting no longer requests negative `chromstart` values from +`.hic`/`.(m)cool` files when padding a region near the start of a chromosome. +* `.checkCool()` recognizes `.mcool` files with extra root-level groups. + # VERSION 1.11.2 ## NEW FEATURES diff --git a/R/annoGenomeLabel.R b/R/annoGenomeLabel.R index 3c6cf5b81..794b03c64 100644 --- a/R/annoGenomeLabel.R +++ b/R/annoGenomeLabel.R @@ -172,20 +172,77 @@ annoGenomeLabel <- function(plot, fontsize = 10, fontcolor = "black", # ASSIGN PARAMETERS BASED ON PLOT INPUT # ========================================================================= - chrom <- genomeLabelInternal$plot$chrom - chromstart <- genomeLabelInternal$plot$chromstart - chromend <- genomeLabelInternal$plot$chromend - assembly <- genomeLabelInternal$plot$assembly + plotObject <- genomeLabelInternal$plot + chrom <- if (!is.null(plotObject$xchrom)) { + plotObject$xchrom + } else { + plotObject$chrom + } + chromstart <- if (!is.null(plotObject$xchromstart)) { + plotObject$xchromstart + } else { + plotObject$chromstart + } + chromend <- if (!is.null(plotObject$xchromend)) { + plotObject$xchromend + } else { + plotObject$chromend + } + assembly <- plotObject$assembly x <- genomeLabelInternal$x y <- genomeLabelInternal$y - length <- genomeLabelInternal$plot$width + length <- plotObject$width if (genomeLabelInternal$axis == "y") { - length <- genomeLabelInternal$plot$height - chrom <- genomeLabelInternal$plot$altchrom - chromstart <- genomeLabelInternal$plot$grobs$vp$yscale[1] - chromend <- genomeLabelInternal$plot$grobs$vp$yscale[2] + length <- plotObject$height + chrom <- if (!is.null(plotObject$ychrom)) { + plotObject$ychrom + } else { + plotObject$altchrom + } + chromstart <- if (!is.null(plotObject$ychromstart)) { + plotObject$ychromstart + } else { + plotObject$grobs$vp$yscale[1] + } + chromend <- if (!is.null(plotObject$ychromend)) { + plotObject$ychromend + } else { + plotObject$grobs$vp$yscale[2] + } } + ## Account for padded axis ranges (for example interchromosomal + ## plotHicSquare(aspect = "fixed")). + if (genomeLabelInternal$axis == "x" && + !is.null(plotObject$xaxisRange)) { + axisRange <- range(plotObject$xaxisRange) + actualRange <- range(c(chromstart, chromend)) + if (diff(axisRange) > 0) { + fracStart <- (actualRange[1] - axisRange[1]) / diff(axisRange) + fracLength <- diff(actualRange) / diff(axisRange) + x <- misc_defaultUnits(x, "x", genomeLabelInternal$default.units) + + plotObject$width * fracStart + length <- plotObject$width * fracLength + } + } + if (genomeLabelInternal$axis == "y" && + !is.null(plotObject$yaxisRange)) { + axisRange <- range(plotObject$yaxisRange) + actualRange <- range(c(chromstart, chromend)) + if (diff(axisRange) > 0) { + if (plotObject$yaxisRange[1] < plotObject$yaxisRange[2]) { + offsetTop <- (axisRange[2] - actualRange[2]) / diff(axisRange) + } else { + offsetTop <- (actualRange[1] - axisRange[1]) / diff(axisRange) + } + fracLength <- diff(actualRange) / diff(axisRange) + y <- misc_defaultUnits(y, "y", genomeLabelInternal$default.units, + funName = "annoGenomeLabel") + + plotObject$height * offsetTop + length <- plotObject$height * fracLength + } + } + just <- justConversion(just = genomeLabelInternal$just) ## Whole genome Manhattan plot spacing diff --git a/R/annoPixels.R b/R/annoPixels.R index b3acdf72a..058c003e1 100644 --- a/R/annoPixels.R +++ b/R/annoPixels.R @@ -218,29 +218,36 @@ annoPixels <- function(plot, data, type = "box", half = "inherit", ## Define a function that subsets loop data for hic region subset_loops <- function(hic, loopData, object, plotObject) { + ## Avoid factor-level mismatches when the plot chromosome came from + ## pgParams(gene=) and the loop data contains all chromosomes. + loopData[, "chrom1"] <- as.character(loopData[, "chrom1"]) + loopData[, "chrom2"] <- as.character(loopData[, "chrom2"]) + plotChrom <- as.character(object$chrom) + plotAltchrom <- as.character(object$altchrom) + ## chrom always in col1 ## altchrom always in col4 ## triangle hic plots will not have altchrom parameters if (is(hic, "hicTriangle")) { loops_subset <- loopData[which( - loopData[, "chrom1"] == object$chrom & - loopData[, "chrom2"] == object$chrom & + loopData[, "chrom1"] == plotChrom & + loopData[, "chrom2"] == plotChrom & loopData[, "start1"] >= object$chromstart & loopData[, "end1"] <= object$chromend & loopData[, "start2"] >= object$chromstart & loopData[, "end2"] <= object$chromend), ] } else if (is(hic, "hicRectangle")){ loops_subset <- loopData[which( - loopData[, "chrom1"] == object$chrom & - loopData[, "chrom2"] == object$chrom & + loopData[, "chrom1"] == plotChrom & + loopData[, "chrom2"] == plotChrom & loopData[, "start1"] >= plotObject$chromstartAdjusted & loopData[, "end1"] <= plotObject$chromendAdjusted & loopData[, "start2"] >= plotObject$chromstartAdjusted & loopData[, "end2"] <= plotObject$chromendAdjusted), ] } else { loops_subset <- loopData[which( - loopData[, "chrom1"] == object$chrom & - loopData[, "chrom2"] == object$altchrom & + loopData[, "chrom1"] == plotChrom & + loopData[, "chrom2"] == plotAltchrom & loopData[, "start1"] >= object$chromstart & loopData[, "end1"] <= object$chromend & loopData[, "start2"] >= object$altchromstart & diff --git a/R/annoXaxis.R b/R/annoXaxis.R index d15a70f07..6de1a2421 100644 --- a/R/annoXaxis.R +++ b/R/annoXaxis.R @@ -7,6 +7,14 @@ #' main = TRUE, #' scipen = 999, #' axisLine = FALSE, +#' tcl = 0.25, +#' label.offset = 0.35, +#' axisLine.lwd = 0.5, +#' axisLine.col = NULL, +#' axisLine.lty = NULL, +#' tick.lwd = 0.5, +#' tick.col = NULL, +#' tick.lty = NULL, #' params = NULL, #' ... #' ) @@ -28,6 +36,17 @@ #' Default value is \code{scipen = 999}. #' @param axisLine A logical value indicating whether to show the axis line. #' Default value is \code{axisLine = FALSE}. +#' @param tcl Tick length in lines. Default value is \code{tcl = 0.25}. +#' @param label.offset Label offset from the tick ends in lines. +#' Default value is \code{label.offset = 0.35}. +#' @param axisLine.lwd Axis line width. Default value is +#' \code{axisLine.lwd = 0.5}. +#' @param axisLine.col Axis line color. +#' @param axisLine.lty Axis line type. +#' @param tick.lwd Tick line width. Default value is +#' \code{tick.lwd = 0.5}. +#' @param tick.col Tick line color. +#' @param tick.lty Tick line type. #' @param params An optional \link[plotgardener]{pgParams} object #' containing relevant function parameters. #' @param ... Additional grid graphical parameters. See \link[grid]{gpar}. @@ -70,7 +89,12 @@ #' pageGuideHide() #' @export annoXaxis <- function(plot, at = NULL, label = TRUE, main = TRUE, - scipen = 999, axisLine = FALSE, params = NULL, ...) { + scipen = 999, axisLine = FALSE, + tcl = 0.25, label.offset = 0.35, + axisLine.lwd = 0.5, axisLine.col = NULL, + axisLine.lty = NULL, + tick.lwd = 0.5, tick.col = NULL, tick.lty = NULL, + params = NULL, ...) { # ========================================================================= # PARSE PARAMETERS @@ -110,16 +134,6 @@ annoXaxis <- function(plot, at = NULL, label = TRUE, main = TRUE, xAxis <- structure(list(grobs = NULL), class = "xaxis") - # ========================================================================= - # CREATE GROB WITHOUT DRAWING - # ========================================================================= - - xGrob <- xaxisGrob( - at = xInternal$at, label = xInternal$label, - main = xInternal$main, gp = xInternal$gp, - vp = xInternal$plot$grobs$vp - ) - # ========================================================================= # GET CENTER OF INPUT PLOT VIEWPORT BASED ON INPUT PLOT TYPE AND JUST # ========================================================================= @@ -137,6 +151,26 @@ annoXaxis <- function(plot, at = NULL, label = TRUE, main = TRUE, xInternal$at <- c(plotVP$xscale[1], plotVP$xscale[2]) } + # ========================================================================= + # CREATE GROB + # ========================================================================= + + xGrob <- xaxisGrob( + at = xInternal$at, label = xInternal$label, + main = xInternal$main, gp = xInternal$gp + ) + xGrob <- .modifyAxisGrob( + axisGrob = xGrob, main = xInternal$main, + tcl = xInternal$tcl, label.offset = xInternal$label.offset, + axisLine = xInternal$axisLine, + axisLine.lwd = xInternal$axisLine.lwd, + axisLine.col = xInternal$axisLine.col, + axisLine.lty = xInternal$axisLine.lty, + tick.lwd = xInternal$tick.lwd, + tick.col = xInternal$tick.col, + tick.lty = xInternal$tick.lty + ) + # ========================================================================= # VIEWPORTS # ========================================================================= @@ -170,16 +204,12 @@ annoXaxis <- function(plot, at = NULL, label = TRUE, main = TRUE, ) } - # ========================================================================= # PLOT # ========================================================================= - xGrob <- grid.xaxis( - at = xInternal$at, label = xInternal$label, - main = xInternal$main, gp = xInternal$gp, vp = vp - ) - if (!xInternal$axisLine) grid.remove(paste0(xGrob$name, "::major")) + xGrob$vp <- vp + grid.draw(xGrob) xaxis_grobs <- gTree(vp = vp, children = gList(xGrob)) xAxis$grobs <- xaxis_grobs diff --git a/R/annoYaxis.R b/R/annoYaxis.R index 79388b27e..195d3566a 100644 --- a/R/annoYaxis.R +++ b/R/annoYaxis.R @@ -7,6 +7,14 @@ #' main = TRUE, #' scipen = 999, #' axisLine = FALSE, +#' tcl = 0.25, +#' label.offset = 0.35, +#' axisLine.lwd = 0.5, +#' axisLine.col = NULL, +#' axisLine.lty = NULL, +#' tick.lwd = 0.5, +#' tick.col = NULL, +#' tick.lty = NULL, #' params = NULL, #' ... #' ) @@ -28,6 +36,17 @@ #' Default value is \code{scipen = 999}. #' @param axisLine A logical value indicating whether to show the axis line. #' Default value is \code{axisLine = FALSE}. +#' @param tcl Tick length in lines. Default value is \code{tcl = 0.25}. +#' @param label.offset Label offset from the tick ends in lines. +#' Default value is \code{label.offset = 0.35}. +#' @param axisLine.lwd Axis line width. Default value is +#' \code{axisLine.lwd = 0.5}. +#' @param axisLine.col Axis line color. +#' @param axisLine.lty Axis line type. +#' @param tick.lwd Tick line width. Default value is +#' \code{tick.lwd = 0.5}. +#' @param tick.col Tick line color. +#' @param tick.lty Tick line type. #' @param params An optional \link[plotgardener]{pgParams} object #' containing relevant function parameters. #' @param ... Additional grid graphical parameters. See \link[grid]{gpar}. @@ -74,7 +93,12 @@ #' pageGuideHide() #' @export annoYaxis <- function(plot, at = NULL, label = TRUE, main = TRUE, - scipen = 999, axisLine = FALSE, params = NULL, ...) { + scipen = 999, axisLine = FALSE, + tcl = 0.25, label.offset = 0.35, + axisLine.lwd = 0.5, axisLine.col = NULL, + axisLine.lty = NULL, + tick.lwd = 0.5, tick.col = NULL, tick.lty = NULL, + params = NULL, ...) { # ========================================================================= # PARSE PARAMETERS @@ -113,23 +137,13 @@ annoYaxis <- function(plot, at = NULL, label = TRUE, main = TRUE, yAxis <- structure(list(grobs = NULL), class = "yaxis") - # ========================================================================= - # CREATE GROB WITHOUT DRAWING - # ========================================================================= - - yGrob <- yaxisGrob( - at = yInternal$at, label = yInternal$label, - main = yInternal$main, gp = yInternal$gp, - vp = yInternal$plot$grobs$vp - ) - # ========================================================================= # GET CENTER OF INPUT PLOT VIEWPORT BASED ON INPUT PLOT TYPE AND JUST # ========================================================================= # Get appropriate plot viewport plotVP <- getAnnoViewport(plot = yInternal$plot) - + adjusted_vp <- adjust_vpCoords(viewport = plotVP) # ========================================================================= @@ -140,6 +154,26 @@ annoYaxis <- function(plot, at = NULL, label = TRUE, main = TRUE, yInternal$at <- c(plotVP$yscale[1], plotVP$yscale[2]) } + # ========================================================================= + # CREATE GROB + # ========================================================================= + + yGrob <- yaxisGrob( + at = yInternal$at, label = yInternal$label, + main = yInternal$main, gp = yInternal$gp + ) + yGrob <- .modifyAxisGrob( + axisGrob = yGrob, main = yInternal$main, + tcl = yInternal$tcl, label.offset = yInternal$label.offset, + axisLine = yInternal$axisLine, + axisLine.lwd = yInternal$axisLine.lwd, + axisLine.col = yInternal$axisLine.col, + axisLine.lty = yInternal$axisLine.lty, + tick.lwd = yInternal$tick.lwd, + tick.col = yInternal$tick.col, + tick.lty = yInternal$tick.lty + ) + # ========================================================================= # VIEWPORTS # ========================================================================= @@ -177,16 +211,7 @@ annoYaxis <- function(plot, at = NULL, label = TRUE, main = TRUE, # PLOT # ========================================================================= - yGrob <- yaxisGrob( - at = yInternal$at, label = yInternal$label, - main = yInternal$main, gp = yInternal$gp, - vp = vp - ) - - if (!yInternal$axisLine){ - yGrob <- removeGrob(yGrob, "major") - } - + yGrob$vp <- vp grid.draw(yGrob) yaxis_grobs <- gTree(vp = vp, children = gList(yGrob)) diff --git a/R/assembly.R b/R/assembly.R index 225e93b8d..b12facb70 100644 --- a/R/assembly.R +++ b/R/assembly.R @@ -11,7 +11,10 @@ #' ) #' #' @param Genome String indicating the name of the genome assembly. -#' @param TxDb String of existing TxDb package name or a TxDb object. +#' @param TxDb String of existing TxDb package name, a TxDb object, or an +#' \link[ensembldb]{EnsDb} object. EnsDb objects are converted to a TxDb for +#' plotting; provide \code{OrgDb} and set \code{gene.id.column = "ENSEMBL"} +#' if gene symbols are desired. #' @param OrgDb String of the desired OrgDb package name. #' @param gene.id.column String of the TxDb column name that refers to #' the given TxDb gene IDs. @@ -31,8 +34,8 @@ #' OrgDb = "org.Hs.eg.db", #' BSgenome = "BSgenome.Hsapiens.NCBI.GRCh38" #' ) -#' @seealso \link[GenomicFeatures]{TxDb}, \link[AnnotationDbi]{OrgDb-class}, -#' \link[BSgenome]{BSgenome} +#' @seealso \link[GenomicFeatures]{TxDb}, \link[ensembldb]{EnsDb}, +#' \link[AnnotationDbi]{OrgDb-class}, \link[BSgenome]{BSgenome} #' #' @export assembly <- function(Genome, TxDb, OrgDb, gene.id.column = "ENTREZID", @@ -47,6 +50,24 @@ assembly <- function(Genome, TxDb, OrgDb, gene.id.column = "ENTREZID", if (is(object$TxDb, "TxDb")) { object$TxDb$packageName <- paste0("TxDb.", Genome) + } else if (is(object$TxDb, "EnsDb")) { + if (!requireNamespace("ensembldb", quietly = TRUE) || + !requireNamespace("GenomicFeatures", quietly = TRUE)) { + stop("`ensembldb` and `GenomicFeatures` are required to use an ", + "EnsDb object in `assembly()`.", call. = FALSE) + } + object$EnsDb <- object$TxDb + tx <- ensembldb::transcripts(object$TxDb) + object$TxDb <- GenomicFeatures::makeTxDbFromGRanges(tx) + object$TxDb$packageName <- paste0("EnsDb.", Genome) + if (is.null(object$OrgDb) || + (is.character(object$OrgDb) && length(object$OrgDb) == 1 && + is.na(object$OrgDb))) { + object$gene.id.column <- "GENEID" + object$display.column <- "GENEID" + } else if (identical(object$gene.id.column, "ENTREZID")) { + object$gene.id.column <- "ENSEMBL" + } } if (!is.null(BSgenome)) { diff --git a/R/axisFunctions.R b/R/axisFunctions.R new file mode 100644 index 000000000..9aa1f72f8 --- /dev/null +++ b/R/axisFunctions.R @@ -0,0 +1,51 @@ +#' @keywords internal +.modifyAxisGrob <- function(axisGrob, main = TRUE, tcl = 0.5, + label.offset = 0.5, + axisLine.lwd = NULL, axisLine.col = NULL, + axisLine.lty = NULL, + tick.lwd = NULL, tick.col = NULL, + tick.lty = NULL, + axisLine = TRUE) { + direction <- if (isTRUE(main)) -1 else 1 + + ## Axis line + if (!axisLine) { + axisGrob <- removeGrob(axisGrob, "major") + } else { + gp <- axisGrob$children$major$gp + if (!is.null(axisLine.lwd)) gp$lwd <- axisLine.lwd + if (!is.null(axisLine.col)) gp$col <- axisLine.col + if (!is.null(axisLine.lty)) gp$lty <- axisLine.lty + axisGrob$children$major$gp <- gp + } + + ## Ticks + if (!is.null(axisGrob$children$ticks)) { + gp <- axisGrob$children$ticks$gp + if (!is.null(tick.lwd)) gp$lwd <- tick.lwd + if (!is.null(tick.col)) gp$col <- tick.col + if (!is.null(tick.lty)) gp$lty <- tick.lty + axisGrob$children$ticks$gp <- gp + + if (inherits(axisGrob, "yaxis")) { + axisGrob$children$ticks$x1 <- unit(direction * tcl, "lines") + } else { + axisGrob$children$ticks$y1 <- unit(direction * tcl, "lines") + } + } + + ## Labels + if (!is.null(axisGrob$children$labels)) { + if (inherits(axisGrob, "yaxis")) { + axisGrob$children$labels$x <- unit( + direction * (tcl + label.offset), "lines" + ) + } else { + axisGrob$children$labels$y <- unit( + direction * (tcl + label.offset), "lines" + ) + } + } + + axisGrob +} diff --git a/R/hicFunctions.R b/R/hicFunctions.R index 7e05a70b9..a727f2465 100644 --- a/R/hicFunctions.R +++ b/R/hicFunctions.R @@ -117,11 +117,15 @@ read_data <- function(hic, hicPlot, norm, assembly, type, quiet) { if (!("data.frame" %in% class(hic))) { # .hic file if (file_ext(hic) == "hic"){ + if (identical(norm, "auto")){ + norm <- "KR" + } if (!is.null(hicPlot$chromstart) & !is.null(hicPlot$chromend) & !is.na(hicPlot$resolution)) { - readchromstart <- hicPlot$chromstart - hicPlot$resolution + readchromstart <- max(0, hicPlot$chromstart - hicPlot$resolution) readchromend <- hicPlot$chromend + hicPlot$resolution - readaltchromstart <- hicPlot$altchromstart - hicPlot$resolution + readaltchromstart <- max(0, hicPlot$altchromstart - + hicPlot$resolution) readaltchromend <- hicPlot$altchromend + hicPlot$resolution hic <- suppressWarnings(readHic( file = hic, chrom = hicPlot$chrom, @@ -144,12 +148,18 @@ read_data <- function(hic, hicPlot, norm, assembly, type, quiet) { if (!is.null(hicPlot$chromstart) & !is.null(hicPlot$chromend) & !is.na(hicPlot$resolution)){ - readchromstart <- hicPlot$chromstart - hicPlot$resolution + readchromstart <- max(0, hicPlot$chromstart - hicPlot$resolution) readchromend <- hicPlot$chromend + hicPlot$resolution - readaltchromstart <- hicPlot$altchromstart - hicPlot$resolution + readaltchromstart <- max(0, hicPlot$altchromstart - + hicPlot$resolution) readaltchromend <- hicPlot$altchromend + hicPlot$resolution # .(m)cool file + if (!identical(type, "observed")){ + warning("`matrix` types other than \"observed\" are not ", + "supported for .(m)cool files. Using observed ", + "counts.", call. = FALSE) + } hic <- suppressWarnings(readCool( file = hic, chrom = hicPlot$chrom, chromstart = readchromstart, @@ -253,4 +263,41 @@ scale_data <- function(upper, zrange) { } return(upper) -} \ No newline at end of file +} +## Build a rasterGrob from sparse Hi-C pixel coordinates and colors. +# @param squares data frame with x, y, and color columns +# @param xmin,xmax,ymin,ymax native coordinate limits +# @param resolution pixel size +# @param maxDim maximum raster dimension; returns NULL if exceeded +# @return rasterGrob or NULL +.hicRasterGrob <- function(squares, xmin, xmax, ymin, ymax, resolution, + maxDim = 2000) { + if (nrow(squares) == 0) { + return(NULL) + } + nx <- ceiling((xmax - xmin) / resolution) + ny <- ceiling((ymax - ymin) / resolution) + if (nx <= 0 || ny <= 0 || nx > maxDim || ny > maxDim) { + return(NULL) + } + + colors <- matrix("#00000000", nrow = ny, ncol = nx) + ix <- floor((as.numeric(squares$x) - xmin) / resolution) + 1 + iy <- floor((as.numeric(squares$y) - ymin) / resolution) + 1 + keep <- ix >= 1 & ix <= nx & iy >= 1 & iy <= ny + if (!any(keep)) { + return(NULL) + } + colors[cbind(iy[keep], ix[keep])] <- as.character(squares$color[keep]) + + ## Raster row 1 is the top of the image, so flip matrix rows. + image <- as.raster(colors[rev(seq_len(ny)), , drop = FALSE]) + rasterGrob( + image, + x = xmin, y = ymin, + width = nx * resolution, height = ny * resolution, + just = c("left", "bottom"), + default.units = "native", + interpolate = FALSE + ) +} diff --git a/R/neoAssembly.R b/R/neoAssembly.R new file mode 100644 index 000000000..c4893e36d --- /dev/null +++ b/R/neoAssembly.R @@ -0,0 +1,300 @@ +#' Read an SV neo-chromosome assembly topology +#' +#' Parse an assembly file from a neoloop/SV workflow and build a +#' `neoAssembly` object describing the concatenated neo-chromosome. +#' +#' @param file Path to an `.assemblies.txt` file. +#' @param id Assembly ID to extract, for example `"C1"`. +#' @param assembly Genome assembly name. Default value is +#' \code{assembly = "hg38"}. +#' @param extend Number of basepairs to extend the first and last fragment. +#' Default value is \code{extend = 0}. +#' @param prefix Prefix to add to chromosome names that do not already have +#' one. Default value is \code{prefix = "chr"}. +#' @param quiet A logical indicating whether to print messages. +#' +#' @return A `neoAssembly` object: a list with \code{id}, \code{fragments}, +#' \code{total_length}, and \code{assembly}. \code{fragments} is a data frame +#' with columns \code{id}, \code{chrom}, \code{chrom_raw}, \code{start}, +#' \code{end}, \code{flipped}, \code{offset}, and \code{length}. +#' +#' @details +#' Assembly lines are usually produced by NeoLoopFinder's +#' \code{assemble-complexSVs}. Each line contains an assembly ID, zero or more +#' SV records (\code{type,chrA,b1,strandA,chrB,b2,strandB}), and two span +#' coordinates (\code{chr,position}). Consecutive node pairs define fragments; +#' a fragment is flipped when its entry position is greater than its exit +#' position. See \code{vignette("neo_reconstruction")} for a full description +#' and examples. +#' +#' @references +#' Wang X, Xu J, Zhang B, Hou Y, Song F, Lyu H, Yue F. Genome-wide detection of +#' enhancer-hijacking events from chromatin interaction data in rearranged +#' genomes. Nature Methods (2021). +#' +#' @examples +#' \dontrun{ +#' neo <- readNeoAssembly( +#' file = "HM1_merged.assemblies.txt", +#' id = "C1", +#' assembly = "hg38", +#' extend = 200000 +#' ) +#' neo +#' } +#' @export +readNeoAssembly <- function(file, id, assembly = "hg38", extend = 0, + prefix = "chr", quiet = FALSE) { + + if (missing(file) || is.null(file)) { + stop("argument \"file\" is missing, with no default.", call. = FALSE) + } + if (missing(id) || is.null(id)) { + stop("argument \"id\" is missing, with no default.", call. = FALSE) + } + if (!file.exists(file)) { + stop("Assembly file does not exist: ", file, call. = FALSE) + } + if (!is.numeric(extend) || length(extend) != 1 || extend < 0) { + stop("`extend` must be a single non-negative number.", call. = FALSE) + } + + lines <- readLines(file, warn = FALSE) + lines <- lines[nzchar(trimws(lines))] + id <- as.character(id) + target <- lines[startsWith(lines, paste0(id, "\t")) | + startsWith(lines, paste0(id, " "))] + + if (length(target) == 0) { + stop("Assembly ID '", id, "' not found in ", file, call. = FALSE) + } + + parts <- strsplit(target[1], "\t", fixed = TRUE)[[1]] + parts <- trimws(parts) + parts <- parts[nzchar(parts)] + if (length(parts) < 3) { + stop("Malformed assembly line for ID '", id, "'.", call. = FALSE) + } + + parseSpan <- function(x) { + pieces <- trimws(strsplit(x, ",", fixed = TRUE)[[1]]) + if (length(pieces) < 2) { + stop("Malformed assembly span: ", x, call. = FALSE) + } + list(chrom = pieces[1], pos = as.numeric(pieces[2])) + } + + span1 <- parseSpan(parts[length(parts) - 1]) + span2 <- parseSpan(parts[length(parts)]) + + svStrings <- character(0) + if (length(parts) > 3) { + svStrings <- parts[2:(length(parts) - 2)] + } + + nodesChrom <- span1$chrom + nodesPos <- span1$pos + + if (length(svStrings) > 0) { + for (sv in svStrings) { + svParts <- trimws(strsplit(sv, ",", fixed = TRUE)[[1]]) + if (length(svParts) < 6) { + stop("Malformed SV entry: ", sv, call. = FALSE) + } + nodesChrom <- c(nodesChrom, svParts[2], svParts[5]) + nodesPos <- c(nodesPos, as.numeric(svParts[3]), + as.numeric(svParts[6])) + } + } + + nodesChrom <- c(nodesChrom, span2$chrom) + nodesPos <- c(nodesPos, span2$pos) + + if (length(nodesChrom) %% 2 != 0) { + stop("Assembly topology has an odd number of nodes.", call. = FALSE) + } + + nFragments <- length(nodesChrom) / 2 + fragments <- vector("list", nFragments) + currentOffset <- 0 + + formatChrom <- function(chrom) { + chrom <- as.character(chrom) + if (startsWith(chrom, "chr")) { + chrom + } else { + paste0(prefix, chrom) + } + } + + for (i in seq_len(nFragments)) { + idx1 <- (i - 1) * 2 + 1 + idx2 <- idx1 + 1 + rawChrom <- nodesChrom[idx1] + posEnter <- nodesPos[idx1] + posExit <- nodesPos[idx2] + flipped <- posEnter > posExit + start <- min(posEnter, posExit) + end <- max(posEnter, posExit) + + if (extend > 0 && i == 1) { + if (flipped) { + end <- end + extend + } else { + start <- max(0, start - extend) + } + } + if (extend > 0 && i == nFragments) { + if (flipped) { + start <- max(0, start - extend) + } else { + end <- end + extend + } + } + + fragLength <- end - start + if (fragLength <= 0) { + stop("Fragment ", i, " has a non-positive length.", call. = FALSE) + } + + fragments[[i]] <- data.frame( + id = i, + chrom = formatChrom(rawChrom), + chrom_raw = as.character(rawChrom), + start = start, + end = end, + flipped = flipped, + offset = currentOffset, + length = fragLength, + stringsAsFactors = FALSE + ) + currentOffset <- currentOffset + fragLength + } + + fragments <- do.call(rbind, fragments) + rownames(fragments) <- NULL + + neo <- structure( + list( + id = id, + file = normalizePath(file, mustWork = TRUE), + assembly = assembly, + extend = extend, + fragments = fragments, + total_length = currentOffset + ), + class = c("neoAssembly", "list") + ) + + if (!quiet) { + message("neoAssembly[", id, "] ", nFragments, " fragments, ", + currentOffset, " bp") + } + + neo +} + +#' @export +print.neoAssembly <- function(x, ...) { + cat("neoAssembly", x$id, "\n") + cat(" fragments:", nrow(x$fragments), "\n") + cat(" total length:", x$total_length, "bp\n") + cat(" assembly:", x$assembly, "\n") + invisible(x) +} + +#' Map genomic features to neo-chromosome coordinates +#' +#' @param data A data frame with columns \code{chrom}, \code{start}, and +#' \code{end}, or a \link[GenomicRanges]{GRanges} object. +#' @param neo A `neoAssembly` object from \code{readNeoAssembly()}. +#' +#' @return A data frame with \code{chrom = "neo"}, neo-coordinate +#' \code{start}/\code{end}, and a \code{fragment} column. Features that span +#' multiple fragments are split across fragments. If a \code{strand} column is +#' present, it is flipped for reverse-complemented fragments. +#' +#' @examples +#' \dontrun{ +#' neo <- readNeoAssembly("HM1_merged.assemblies.txt", "C1", extend = 200000) +#' features <- data.frame( +#' chrom = "chr12", start = 65822483, end = 65968291, +#' name = "HMGA2", strand = "+" +#' ) +#' mapNeoFeatures(features, neo) +#' } +#' @export +mapNeoFeatures <- function(data, neo) { + + if (!inherits(neo, "neoAssembly")) { + stop("`neo` must be a `neoAssembly` object.", call. = FALSE) + } + + if (inherits(data, "GRanges")) { + df <- as.data.frame(data) + if ("seqnames" %in% colnames(df)) { + df$chrom <- as.character(df$seqnames) + df$seqnames <- NULL + } + } else { + df <- as.data.frame(data, stringsAsFactors = FALSE) + } + + required <- c("chrom", "start", "end") + if (!all(required %in% colnames(df))) { + stop("`data` must contain `chrom`, `start`, and `end` columns.", + call. = FALSE) + } + + fragments <- neo$fragments + mappedParts <- list() + + for (i in seq_len(nrow(fragments))) { + frag <- fragments[i, ] + subsetDf <- df[df$chrom == frag$chrom | df$chrom == frag$chrom_raw, , + drop = FALSE] + if (nrow(subsetDf) == 0) { + next + } + + subsetDf <- subsetDf[subsetDf$start <= frag$end & + subsetDf$end >= frag$start, , drop = FALSE] + if (nrow(subsetDf) == 0) { + next + } + + originalStart <- subsetDf$start + originalEnd <- subsetDf$end + clippedStart <- pmax(originalStart, frag$start) + clippedEnd <- pmin(originalEnd, frag$end) + + if (frag$flipped) { + subsetDf$start <- frag$offset + (frag$end - clippedEnd) + subsetDf$end <- frag$offset + (frag$end - clippedStart) + if ("strand" %in% colnames(subsetDf)) { + subsetDf$strand <- ifelse( + subsetDf$strand == "+", "-", + ifelse(subsetDf$strand == "-", "+", subsetDf$strand) + ) + } + } else { + subsetDf$start <- frag$offset + (clippedStart - frag$start) + subsetDf$end <- frag$offset + (clippedEnd - frag$start) + } + + subsetDf$chrom <- "neo" + subsetDf$fragment <- frag$id + mappedParts[[length(mappedParts) + 1]] <- subsetDf + } + + if (length(mappedParts) == 0) { + return(data.frame( + chrom = character(0), start = numeric(0), end = numeric(0), + fragment = integer(0) + )) + } + + mapped <- do.call(rbind, mappedParts) + rownames(mapped) <- NULL + mapped +} diff --git a/R/neoSignal.R b/R/neoSignal.R new file mode 100644 index 000000000..2e7d52885 --- /dev/null +++ b/R/neoSignal.R @@ -0,0 +1,202 @@ +#' Map a signal track onto neo-chromosome coordinates +#' +#' Maps bigWig, `GRanges`, or data-frame signal data through the +#' neo-chromosome topology and optionally bins it in neo coordinates. This +#' handles RNA-seq, ChIP-seq, and other genome-wide signal tracks in the same +#' way, including fragments that are inverted. +#' +#' @param data A bigWig path, `GRanges` object, or data frame with +#' `chrom`, `start`, `end`, and a signal column. +#' @param neo A `neoAssembly` object. +#' @param binSize Bin size in basepairs for the neo-coordinate output. Use +#' `NULL` to keep the input intervals. Default value is `1000`. +#' @param fun Aggregation function for binning: `"mean"`, `"median"`, +#' `"sum"`, `"max"`, or `"min"`. Default value is `"mean"`. +#' @param value.col Name of the signal column. If `NULL`, the function looks +#' for `"score"`, `"balanced"`, `"value"`, or the last numeric column. +#' @param chromstart,chromend Optional neo-coordinate window. Only intervals +#' overlapping this window are returned. +#' @param ... Additional arguments passed to `readBigwig()`. +#' +#' @return A data frame with `chrom`, `start`, `end`, and `score`. +#' @export +getNeoSignal <- function(data, neo, binSize = 1000, + fun = c("mean", "median", "sum", "max", "min"), + value.col = NULL, + chromstart = NULL, chromend = NULL, ...) { + if (!inherits(neo, "neoAssembly")) { + stop("`neo` must be a `neoAssembly` object.", call. = FALSE) + } + fun <- match.arg(fun) + + ## Read a bigWig fragment by fragment, or accept pre-read data -------- + if (is.character(data) && length(data) == 1) { + if (!file.exists(data)) { + stop("Signal file does not exist: ", data, call. = FALSE) + } + isBigWig <- grepl("\\.(bw|bigwig|bigWig)(\\.gz)?$", data, + ignore.case = TRUE) + if (isBigWig) { + parts <- lapply(seq_len(nrow(neo$fragments)), function(i) { + frag <- neo$fragments[i, ] + bw <- readBigwig( + file = data, chrom = frag$chrom, + chromstart = max(1, frag$start), chromend = frag$end, + ... + ) + if (nrow(bw) == 0) { + return(NULL) + } + df <- as.data.frame(bw) + if ("seqnames" %in% colnames(df)) { + df$chrom <- as.character(df$seqnames) + df$seqnames <- NULL + } + mapNeoFeatures(df, neo) + }) + parts <- Filter(NROW, parts) + if (length(parts) == 0) { + return(data.frame( + chrom = character(0), start = numeric(0), + end = numeric(0), score = numeric(0) + )) + } + raw <- do.call(rbind, parts) + } else { + ## Text table input (for example a virtual-4C table). + if (!requireNamespace("data.table", quietly = TRUE)) { + stop("`data.table` is required to read tabular signal files.", + call. = FALSE) + } + raw <- as.data.frame(data.table::fread(data)) + raw <- .neoSignalFrame(raw, neo, value.col) + } + } else if (inherits(data, "GRanges")) { + raw <- as.data.frame(data) + raw <- .neoSignalFrame(raw, neo, value.col) + } else { + raw <- .neoSignalFrame(as.data.frame(data), neo, value.col) + } + + if (nrow(raw) == 0) { + return(data.frame( + chrom = character(0), start = numeric(0), + end = numeric(0), score = numeric(0) + )) + } + + if (is.null(binSize)) { + out <- data.frame( + chrom = "neo", start = raw$start, end = raw$end, + score = raw$score, stringsAsFactors = FALSE + ) + } else { + if (!is.numeric(binSize) || length(binSize) != 1 || binSize <= 0) { + stop("`binSize` must be a positive number or NULL.", + call. = FALSE) + } + raw$bin <- floor(raw$start / binSize) * binSize + binned <- stats::aggregate( + score ~ bin, data = raw, FUN = fun, na.rm = TRUE + ) + out <- data.frame( + chrom = "neo", + start = binned$bin, + end = binned$bin + binSize - 1, + score = binned$score, + stringsAsFactors = FALSE + ) + } + + out <- out[order(out$start), , drop = FALSE] + rownames(out) <- NULL + if (!is.null(chromstart) || !is.null(chromend)) { + lo <- if (is.null(chromstart)) -Inf else chromstart + hi <- if (is.null(chromend)) Inf else chromend + out <- out[out$end >= lo & out$start <= hi, , drop = FALSE] + } + out +} + +.neoSignalFrame <- function(df, neo, value.col = NULL) { + if (!all(c("chrom", "start", "end") %in% colnames(df)) && + !all(c("seqnames", "start", "end") %in% colnames(df))) { + stop("Signal data must contain `chrom`, `start`, and `end` columns.", + call. = FALSE) + } + if ("seqnames" %in% colnames(df)) { + df$chrom <- as.character(df$seqnames) + df$seqnames <- NULL + } + if (!"chrom" %in% colnames(df)) { + stop("Signal data must contain a `chrom` column.", call. = FALSE) + } + + if (!is.null(value.col)) { + if (!value.col %in% colnames(df)) { + stop("`value.col` not found in signal data: ", value.col, + call. = FALSE) + } + score <- df[[value.col]] + } else { + candidates <- c("score", "balanced", "value") + hit <- candidates[candidates %in% colnames(df)][1] + if (is.na(hit)) { + numericCols <- names(df)[vapply(df, is.numeric, logical(1))] + numericCols <- setdiff(numericCols, c("start", "end")) + hit <- utils::tail(numericCols, 1) + } + if (is.na(hit) || length(hit) == 0) { + stop("Could not determine a signal column; supply `value.col`.", + call. = FALSE) + } + score <- df[[hit]] + } + + mapped <- mapNeoFeatures( + data.frame( + chrom = as.character(df$chrom), + start = as.numeric(df$start), + end = as.numeric(df$end), + score = as.numeric(score), + stringsAsFactors = FALSE + ), + neo + ) + mapped[, c("chrom", "start", "end", "score"), drop = FALSE] +} + +#' Map a virtual-4C table onto neo-chromosome coordinates +#' +#' Convenience wrapper around `getNeoSignal()` for cooltools virtual-4C TSV +#' files. The table is mapped through the neo topology and adjacent intervals +#' are clipped so they do not overlap. +#' +#' @param file Path to a virtual-4C TSV file. +#' @param neo A `neoAssembly` object. +#' @param value.col Signal column. Default value is `"balanced"`. +#' @param binSize Optional bin size. Default value is `NULL`, which keeps the +#' table's own intervals. +#' @param fun Aggregation function when `binSize` is supplied. +#' @param ... Additional arguments passed to `getNeoSignal()`. +#' +#' @return A data frame with `chrom`, `start`, `end`, and `score`. +#' @export +getNeoV4C <- function(file, neo, value.col = "balanced", binSize = NULL, + fun = "mean", ...) { + out <- getNeoSignal( + data = file, neo = neo, binSize = binSize, + fun = fun, value.col = value.col, ... + ) + if (nrow(out) == 0) { + return(out) + } + out <- out[order(out$start), , drop = FALSE] + out$end <- pmin( + out$end - 1, + c(out$start[-1] - 1, Inf) + ) + out <- out[out$start <= out$end, , drop = FALSE] + rownames(out) <- NULL + out +} diff --git a/R/pageCreate.R b/R/pageCreate.R index 5a1cc5e76..50c749c33 100644 --- a/R/pageCreate.R +++ b/R/pageCreate.R @@ -91,6 +91,8 @@ pageCreate <- function(width = 8.5, height = 11, default.units = "inches", grid.newpage() assign("pg_vpTree", list(), envir = pgEnv) + assign("guides_hidden", FALSE, envir = pgEnv) + assign("removed_plots", character(0), envir = pgEnv) # ========================================================================= # PARSE PARAMETERS @@ -169,6 +171,7 @@ pageCreate <- function(width = 8.5, height = 11, default.units = "inches", assign("page_units", page_units, envir = pgEnv) page_width <- as.numeric(page$width) + assign("page_width", page_width, envir = pgEnv) # ========================================================================= # VIEWPORT diff --git a/R/pageExport.R b/R/pageExport.R new file mode 100644 index 000000000..aa36a01d7 --- /dev/null +++ b/R/pageExport.R @@ -0,0 +1,119 @@ +#' Export the current plotgardener page without calling dev.off() +#' +#' Grab the current page and write it to a file using a new graphics device. +#' The device is opened and closed internally, so users do not need to call +#' \code{dev.off()}. +#' +#' @param file Output file path. The device is inferred from the extension +#' (`.pdf`, `.png`, `.tiff`, `.jpeg`, or `.svg`). +#' @param width Output width. Defaults to the current page width. +#' @param height Output height. Defaults to the current page height. +#' @param units Units for \code{width} and \code{height}. Defaults to the +#' current page units. +#' @param dpi Resolution for raster devices. Default value is +#' \code{dpi = 300}. +#' @param bg Background color for the output device. +#' Default value is \code{bg = "white"}. +#' @param guides Logical value indicating whether to include page guides in +#' the export. Default value is \code{guides = TRUE}. +#' @param device Optional device name. If \code{NULL}, inferred from +#' \code{file}. +#' @param ... Additional arguments passed to the graphics device. +#' +#' @return Invisibly returns the output file path. +#' +#' @examples +#' \dontrun{ +#' pageCreate(width = 3, height = 3, default.units = "inches") +#' plotRect(x = 0.5, y = 0.5, width = 2, height = 2, fill = "green") +#' pageExport("figure.pdf") +#' pageExport("figure.png", dpi = 300) +#' } +#' @export +pageExport <- function(file, width = NULL, height = NULL, units = NULL, + dpi = 300, bg = "white", guides = TRUE, + device = NULL, ...) { + + if (missing(file) || is.null(file)) { + stop("argument \"file\" is missing, with no default.", call. = FALSE) + } + if (!exists("guide_grobs", envir = pgEnv)) { + stop("Cannot export without a `plotgardener` page.", call. = FALSE) + } + + if (is.null(width)) { + width <- get("page_width", envir = pgEnv) + } + if (is.null(height)) { + height <- get("page_height", envir = pgEnv) + } + if (is.null(units)) { + units <- get("page_units", envir = pgEnv) + } + rasterUnits <- if (identical(units, "inches")) "in" else units + if (!rasterUnits %in% c("in", "cm", "mm")) { + rasterUnits <- "in" + } + + ext <- tolower(tools::file_ext(file)) + if (is.null(device)) { + device <- switch(ext, + pdf = "pdf", + png = "png", + tif = "tiff", + tiff = "tiff", + jpg = "jpeg", + jpeg = "jpeg", + svg = "svg", + stop("Unsupported output extension: .", ext, call. = FALSE) + ) + } + + hideGuides <- !isTRUE(guides) || + isTRUE(get("guides_hidden", envir = pgEnv)) + removed <- get("removed_plots", envir = pgEnv) + needsRemoval <- hideGuides || length(removed) > 0 + + ## `wrap.grobs = TRUE` preserves repeated grob names faithfully. When + ## deferred removals are requested, use the unwrapped tree so individual + ## guide/plot grobs can be removed by name. + pageGrob <- grid.grab(wrap.grobs = !needsRemoval) + if (needsRemoval) { + if (hideGuides && "guide_grobs" %in% pageGrob$childrenOrder) { + pageGrob <- removeGrob(pageGrob, "guide_grobs") + } + for (grobName in removed) { + if (grobName %in% pageGrob$childrenOrder) { + pageGrob <- removeGrob(pageGrob, grobName) + } + } + } + + oldDevice <- grDevices::dev.cur() + if (device == "pdf") { + grDevices::pdf(file = file, width = width, height = height, bg = bg, ...) + } else if (device == "png") { + grDevices::png(file = file, width = width, height = height, + units = rasterUnits, res = dpi, bg = bg, ...) + } else if (device == "tiff") { + grDevices::tiff(file = file, width = width, height = height, + units = rasterUnits, res = dpi, bg = bg, ...) + } else if (device == "jpeg") { + grDevices::jpeg(file = file, width = width, height = height, + units = rasterUnits, res = dpi, bg = bg, ...) + } else if (device == "svg") { + grDevices::svg(file = file, width = width, height = height, bg = bg, ...) + } else { + stop("Unsupported device: ", device, call. = FALSE) + } + on.exit({ + if (grDevices::dev.cur() != oldDevice) { + grDevices::dev.off() + } + }, add = TRUE) + + grid.newpage() + grid.draw(pageGrob) + + invisible(file) +} diff --git a/R/pageGuideHide.R b/R/pageGuideHide.R index b1cb0685d..3e84c87e9 100644 --- a/R/pageGuideHide.R +++ b/R/pageGuideHide.R @@ -1,5 +1,13 @@ #' Remove guides from a plotgardener page #' +#' Hides page guides without calling `grid.remove()` on the active device. +#' The hidden state is applied by \code{pageExport()} and \code{pageRedraw()}, +#' so exporting a PDF or PNG does not create a second page. +#' +#' @param redraw Logical value indicating whether to redraw immediately on a +#' screen device. File devices defer the change to \code{pageExport()}. +#' Default value is \code{redraw = TRUE}. +#' #' @return None. #' #' @examples @@ -8,33 +16,20 @@ #' #' ## Hide page guides #' pageGuideHide() -#' -#' @note -#' Please note that due to the implementation of `grid` removal functions, -#' using `pageGuideHide` within a `pdf` call will result in the rendering of a -#' separate, new page with the plot guides removed. To avoid this artifact, -#' hide guides in the `pageCreate` function call with `showGuides = FALSE`. -#' +#' +#' ## Export with guides omitted +#' \dontrun{ +#' pageExport("figure.pdf") +#' } #' @export -pageGuideHide <- function() { +pageGuideHide <- function(redraw = TRUE) { if (length(get("guide_grobs", envir = pgEnv)$children) == 0) { stop("No `plotgardener` page guides exist.") } - ## Get the list of grobs from the guide grobs gTree and convert to gPaths - grob_list <- lapply( - get("guide_grobs", envir = pgEnv)$children, - convert_gpath - ) - ## Get the last grob - last_grob <- grob_list[length(grob_list)] - - ## Remove the last grob from the list of grobs - grob_list <- grob_list[-length(grob_list)] - - ## Remove all grobs except last one, not redrawing each time (to save time) - invisible(lapply(grob_list, grid.remove, redraw = FALSE)) - - ## Remove last grob with redrawing, now removing all the grobs - invisible(lapply(last_grob, grid.remove)) + assign("guides_hidden", TRUE, envir = pgEnv) + if (isTRUE(redraw) && !.isFileDevice()) { + pageRedraw() + } + invisible(NULL) } diff --git a/R/pagePlotRemove.R b/R/pagePlotRemove.R index 183c9a189..b0620d71e 100644 --- a/R/pagePlotRemove.R +++ b/R/pagePlotRemove.R @@ -1,7 +1,14 @@ #' Remove plotgardener plots and annotations #' +#' Records a plot for deferred removal instead of calling `grid.remove()` on +#' the active device. The removal is applied by \code{pageExport()} or +#' \code{pageRedraw()}, avoiding extra pages in PDF output. +#' #' @param plot Plot object to be removed, defined by the output #' of a plotgardener plotting function. +#' @param redraw Logical value indicating whether to redraw immediately on a +#' screen device. File devices defer the change to \code{pageExport()}. +#' Default value is \code{redraw = TRUE}. #' #' @examples #' ## Load Hi-C data @@ -27,19 +34,21 @@ #' @return None. #' #' @export -pagePlotRemove <- function(plot) { - - if (is(plot, "yaxis") | is(plot, "xaxis")){ - grid.remove(gPath(plot$grobs$childrenOrder)) +pagePlotRemove <- function(plot, redraw = TRUE) { + + removed <- get("removed_plots", envir = pgEnv) + + if (is(plot, "yaxis") | is(plot, "xaxis")) { + removed <- c(removed, plot$grobs$childrenOrder) } else { - grid.remove(gPath(plot$grobs$name)) - + removed <- c(removed, plot$grobs$name) + pg_vpTree <- get("pg_vpTree", envir = pgEnv) pg_vpTree[grep(plot$grobs$name, pg_vpTree)] <- NULL assign("pg_vpTree", pg_vpTree, envir = pgEnv) - - ## Need to remove outer viewport of bb_hicTriangle/bb_hicRectangle plot - ## and domain Clips + + ## Keep viewport bookkeeping compatible with the previous behavior, + ## but do not remove the plotted grob from the device. if (is(plot, "hicTriangle") | is(plot, "hicRectangle")) { vp_name <- plot$grobs$vp$name @@ -53,14 +62,19 @@ pagePlotRemove <- function(plot) { suppressMessages(seekViewport(vp_name)) suppressMessages(popViewport()) } - } else if (is(plot, "signal")){ - if (grepl("_v", plot$grobs$vp$name)){ + } else if (is(plot, "signal")) { + if (grepl("_v", plot$grobs$vp$name)) { vp_name <- plot$grobs$vp$name vp_name <- gsub("_v", "_vClip", vp_name) suppressMessages(seekViewport(vp_name)) suppressMessages(popViewport()) } - } + } } + assign("removed_plots", unique(removed), envir = pgEnv) + if (isTRUE(redraw) && !.isFileDevice()) { + pageRedraw() + } + invisible(NULL) } diff --git a/R/pageRedraw.R b/R/pageRedraw.R new file mode 100644 index 000000000..6e7731282 --- /dev/null +++ b/R/pageRedraw.R @@ -0,0 +1,35 @@ +#' @keywords internal +.isFileDevice <- function() { + device <- names(grDevices::dev.cur()) + any(grepl("pdf|png|jpeg|jpg|tiff|svg|postscript", + device, ignore.case = TRUE)) +} + +#' Redraw the current plotgardener page +#' +#' Redraw the current page after deferred guide hiding or plot removal. This +#' is primarily useful on screen devices; for file devices, use +#' \code{pageExport()}, which applies the deferred removals to a single page. +#' +#' @return Invisibly returns the grabbed page grob. +#' @export +pageRedraw <- function() { + if (!exists("guide_grobs", envir = pgEnv)) { + stop("Cannot redraw without a `plotgardener` page.", call. = FALSE) + } + + pageGrob <- grid.grab(wrap.grobs = FALSE) + if (isTRUE(get("guides_hidden", envir = pgEnv)) && + "guide_grobs" %in% pageGrob$childrenOrder) { + pageGrob <- removeGrob(pageGrob, "guide_grobs") + } + for (grobName in get("removed_plots", envir = pgEnv)) { + if (grobName %in% pageGrob$childrenOrder) { + pageGrob <- removeGrob(pageGrob, grobName) + } + } + + grid.newpage() + grid.draw(pageGrob) + invisible(pageGrob) +} diff --git a/R/plotGenes.R b/R/plotGenes.R index 53059a9de..cbd0749b6 100644 --- a/R/plotGenes.R +++ b/R/plotGenes.R @@ -9,6 +9,8 @@ #' fontcolor = c("#669fd9", "#abcc8e"), #' fill = c("#669fd9", "#abcc8e"), #' geneOrder = NULL, +#' labelClusters = FALSE, +#' labelClusterRot = 45, #' geneHighlights = NULL, #' geneBackground = "grey", #' strandLabels = TRUE, @@ -42,6 +44,12 @@ #' The first value will color the plus strand plot elements and #' the second label will color the minus strand plot elements. #' Default value is \code{fill = c("#669fd9", "#abcc8e")}. +#' @param labelClusters A logical value indicating whether to draw all gene +#' labels without overlap suppression. Useful for dense gene clusters; +#' labels may be rotated with \code{labelClusterRot}. +#' Default value is \code{labelClusters = FALSE}. +#' @param labelClusterRot Rotation in degrees for labels when +#' \code{labelClusters = TRUE}. Default value is \code{labelClusterRot = 45}. #' @param geneOrder An ordered character vector of gene names to #' prioritize when labeling genes. #' @param geneHighlights A two-column dataframe with a column named "gene" @@ -166,7 +174,8 @@ plotGenes <- function(chrom, chromstart = NULL, chromend = NULL, assembly = "hg38", fontsize = 8, fontcolor = c("#669fd9", "#abcc8e"), fill = c("#669fd9", "#abcc8e"), - geneOrder = NULL, geneHighlights = NULL, + geneOrder = NULL, labelClusters = FALSE, + labelClusterRot = 45, geneHighlights = NULL, geneBackground = "grey", strandLabels = TRUE, stroke = 0.1, bg = NA, x = NULL, y = NULL, width = NULL, height = unit(0.6, "inches"), @@ -832,7 +841,12 @@ plotGenes <- function(chrom, chromstart = NULL, chromend = NULL, ), vp = vp_gene, default.units = "native", - check.overlap = TRUE + rot = if (isTRUE(genesInternal$labelClusters)) { + genesInternal$labelClusterRot + } else { + 0 + }, + check.overlap = !isTRUE(genesInternal$labelClusters) ) assign("gene_grobs", @@ -890,7 +904,12 @@ plotGenes <- function(chrom, chromstart = NULL, chromend = NULL, ), vp = vp_gene, default.units = "native", - check.overlap = TRUE + rot = if (isTRUE(genesInternal$labelClusters)) { + genesInternal$labelClusterRot + } else { + 0 + }, + check.overlap = !isTRUE(genesInternal$labelClusters) ) assign("gene_grobs", addGrob(get("gene_grobs", envir = pgEnv), diff --git a/R/plotHicRectangle.R b/R/plotHicRectangle.R index 1f49b0fb3..732e68f85 100644 --- a/R/plotHicRectangle.R +++ b/R/plotHicRectangle.R @@ -4,7 +4,7 @@ #' data, #' resolution = "auto", #' zrange = NULL, -#' norm = "KR", +#' norm = "auto", #' matrix = "observed", #' chrom, #' chromstart = NULL, @@ -21,6 +21,8 @@ #' just = c("left", "top"), #' default.units = "inches", #' draw = TRUE, +#' raster = c("auto", "never", "always"), +#' raster.max = 2000, #' params = NULL, #' quiet = FALSE #' ) @@ -37,8 +39,9 @@ #' max or min. #' @param norm Character value specifying hic data normalization method, #' if giving .hic or .(m)cool file. This value must be found in the .hic -#' or .(m)cool file. -#' Default value is \code{norm = "KR"}. +#' or .(m)cool file. \code{"auto"} chooses \code{"KR"} for .hic files and an +#' an available bins column for .(m)cool files (see \code{readCoolNorms()}). +#' Default value is \code{norm = "auto"}. #' @param matrix Character value indicating the type of matrix to output for #' .hic files. #' Default value is \code{matrix = "observed"}. Options are: @@ -86,6 +89,11 @@ #' as numerics. Default value is \code{default.units = "inches"}. #' @param draw A logical value indicating whether graphics output should #' be produced. Default value is \code{draw = TRUE}. +#' @param raster Rasterization mode for Hi-C pixels. \code{"auto"} rasterizes +#' large maps, \code{"never"} always uses vector rectangles, and +#' \code{"always"} always rasterizes when possible. +#' @param raster.max Maximum raster dimension. Default value is +#' \code{raster.max = 2000}. #' @param params An optional \link[plotgardener]{pgParams} object containing #' relevant function parameters. #' @param quiet A logical indicating whether or not to print messages. @@ -156,7 +164,7 @@ #' #' @export plotHicRectangle <- function(data, resolution = "auto", zrange = NULL, - norm = "KR", matrix = "observed", chrom, + norm = "auto", matrix = "observed", chrom, chromstart = NULL, chromend = NULL, assembly = "hg38", palette = colorRampPalette(brewer.pal( @@ -168,6 +176,8 @@ plotHicRectangle <- function(data, resolution = "auto", zrange = NULL, width = NULL, height = NULL, just = c("left", "top"), default.units = "inches", draw = TRUE, + raster = c("auto", "never", "always"), + raster.max = 2000, params = NULL, quiet = FALSE) { # ========================================================================= @@ -570,15 +580,36 @@ plotHicRectangle <- function(data, resolution = "auto", zrange = NULL, if (!is.null(hicPlot$chromstart) & !is.null(hicPlot$chromend)) { if (nrow(hic) > 0) { - hic_squares <- rectGrob( - x = hic$x, - y = hic$y, - just = c("left", "bottom"), - width = hicPlot$resolution, - height = hicPlot$resolution, - gp = gpar(col = NA, fill = hic$color), - default.units = "native" + rasterMode <- match.arg( + rhicInternal$raster, + c("auto", "never", "always") ) + useRaster <- rasterMode == "always" || + (rasterMode == "auto" && nrow(hic) > 5000) + rasterGrob <- NULL + if (useRaster) { + rasterGrob <- .hicRasterGrob( + squares = hic, + xmin = min(scale[[1]]), xmax = max(scale[[1]]), + ymin = min(scale[[1]]), ymax = max(scale[[1]]), + resolution = hicPlot$resolution, + maxDim = rhicInternal$raster.max + ) + } + + if (!is.null(rasterGrob)) { + hic_squares <- rasterGrob + } else { + hic_squares <- rectGrob( + x = hic$x, + y = hic$y, + just = c("left", "bottom"), + width = hicPlot$resolution, + height = hicPlot$resolution, + gp = gpar(col = NA, fill = hic$color), + default.units = "native" + ) + } assign("hic_grobs3", addGrob( @@ -615,6 +646,13 @@ plotHicRectangle <- function(data, resolution = "auto", zrange = NULL, hicPlot$chromstart <- rhicInternal$chromstart hicPlot$chromend <- rhicInternal$chromend + hicPlot$xchrom <- hicPlot$chrom + hicPlot$xchromstart <- hicPlot$chromstart + hicPlot$xchromend <- hicPlot$chromend + hicPlot$ychrom <- hicPlot$chrom + hicPlot$ychromstart <- hicPlot$chromstart + hicPlot$ychromend <- hicPlot$chromend + # ========================================================================= # RETURN OBJECT # ========================================================================= diff --git a/R/plotHicSquare.R b/R/plotHicSquare.R index e2c787854..2b86aedab 100644 --- a/R/plotHicSquare.R +++ b/R/plotHicSquare.R @@ -4,7 +4,7 @@ #' data, #' resolution = "auto", #' zrange = NULL, -#' norm = "KR", +#' norm = "auto", #' matrix = "observed", #' chrom, #' chromstart = NULL, @@ -17,6 +17,8 @@ #' colorTrans = "linear", #' half = "both", #' yaxisDir = "increase", +#' xaxisDir = "increase", +#' aspect = c("free", "fixed"), #' bg = NA, #' x = NULL, #' y = NULL, @@ -25,6 +27,8 @@ #' just = c("left", "top"), #' default.units = "inches", #' draw = TRUE, +#' raster = c("auto", "never", "always"), +#' raster.max = 2000, #' params = NULL, #' quiet = FALSE #' ) @@ -41,7 +45,9 @@ #' to the max or min. #' @param norm Character value specifying hic data normalization method, #' if giving .hic or .(m)cool file. This value must be found in the .hic or -#' .(m)cool file. Default value is \code{norm = "KR"}. +#' .(m)cool file. \code{"auto"} chooses \code{"KR"} for .hic files and an +#' an available bins column for .(m)cool files (see \code{readCoolNorms()}). +#' Default value is \code{norm = "auto"}. #' @param matrix Character value indicating the type of matrix to output for #' .hic files. #' Default value is \code{matrix = "observed"}. Options are: @@ -50,11 +56,13 @@ #' \item{\code{"oe"}: }{Observed/expected counts.} #' \item{\code{"log2oe"}: }{Log2 transformed observed/expected counts.} #' } -#' @param chrom Chromosome of region to be plotted, as a string. +#' @param chrom Chromosome of region to be plotted, as a string. For +#' interchromosomal plots this is the **x-axis** chromosome. #' @param chromstart Integer start position on chromosome to be plotted. #' @param chromend Integer end position on chromosome to be plotted. #' @param altchrom Alternate chromosome for off-diagonal plotting -#' or interchromosomal plotting, as a string. +#' or interchromosomal plotting, as a string. For interchromosomal plots this +#' is the **y-axis** chromosome. #' @param altchromstart Alternate chromosome integer start position #' for off-diagonal plotting or interchromosomal plotting. #' @param altchromend Alternate chromosome integer end position @@ -72,18 +80,30 @@ #' @param half A character value indicating which diagonal regions to plot. #' For intrachromosomal plotting, options are \code{"both"}, \code{"top"}, #' or \code{"bottom"}. For off-diagonal or interchromosomal plotting, -#' options are \code{"top"} or \code{"bottom"}. +#' options are \code{"top"} or \code{"bottom"}. For interchromosomal plots, +#' \code{half} does not select a triangle; it controls the y-axis origin +#' together with \code{yaxisDir}. See the interchromosomal orientation +#' section below. #' Default value is \code{half = "both"}. #' \describe{ #' \item{\code{"both"}: }{Both diagonal halves.} #' \item{\code{"top"}: }{Half above the diagonal.} #' \item{\code{"bottom"}: }{Half below the diagonal.} #' } +#' @param xaxisDir A string specifying the genomic direction of the x-axis. +#' Options are \code{"increase"} or \code{"decrease"}. +#' Default value is \code{xaxisDir = "increase"}. +#' @param aspect Aspect mode for interchromosomal plots. \code{"free"} +#' stretches each chromosome to fill its axis; \code{"fixed"} uses the same +#' basepairs-per-inch on both axes, centering padding on the shorter +#' chromosome. Default value is \code{aspect = "free"}. #' @param yaxisDir A string specifying the genomic direction of the y-axis. #' Options are \code{"increase"}, where the bottom left corner of the Hi-C map #' indicates the origin, and \code{"decrease"}, where the top left corner of the #' Hi-C map indicates the origin. This will change the direction of the diagonal -#' for intrachromosomal maps. +#' for intrachromosomal maps. For interchromosomal maps, combine +#' \code{yaxisDir} with \code{half} as described in the interchromosomal +#' orientation section below. #' Default value is \code{yaxisDir = "increase"}. #' @param bg Character value indicating background color. #' Default value is \code{bg = NA}. @@ -107,6 +127,11 @@ #' numerics. Default value is \code{default.units = "inches"}. #' @param draw A logical value indicating whether graphics output should be #' produced. Default value is \code{draw = TRUE}. +#' @param raster Rasterization mode for Hi-C pixels. \code{"auto"} rasterizes +#' large maps, \code{"never"} always uses vector rectangles, and +#' \code{"always"} always rasterizes when possible. +#' @param raster.max Maximum number of raster rows/columns. Larger matrices +#' fall back to vector rectangles. Default value is \code{raster.max = 2000}. #' @param params An optional \link[plotgardener]{pgParams} object containing #' relevant function parameters. #' @param quiet A logical indicating whether or not to print messages. @@ -153,6 +178,52 @@ #' #' ## Hide page guides #' pageGuideHide() +#' @section Interchromosomal orientation: +#' For an interchromosomal plot, \code{chrom} is always the x-axis and +#' \code{altchrom} is always the y-axis: +#' \preformatted{ +#' x = chrom +#' y = altchrom +#' } +#' +#' When building a grid of chromosomes, a cell at row \code{i} and column +#' \code{j} must therefore use the column chromosome as \code{chrom} and +#' the row chromosome as \code{altchrom}: +#' \preformatted{ +#' plotHicSquare( +#' data = hic, +#' chrom = chroms[j], # x-axis: grid column +#' altchrom = chroms[i], # y-axis: grid row +#' chromstart = 0, chromend = max_len, +#' altchromstart = 0, altchromend = max_len, +#' x = x0 + (j - 1) * cell, +#' y = y0 + (i - 1) * cell, +#' width = cell, height = cell, +#' half = "top", yaxisDir = "decrease", +#' just = c("left", "top") +#' ) +#' } +#' Passing \code{chrom = chroms[i]} and \code{altchrom = chroms[j]} instead +#' transposes every off-diagonal square. +#' +#' For interchromosomal plots, \code{half} controls the y-axis origin in +#' combination with \code{yaxisDir}: +#' \describe{ +#' \item{\code{half = "bottom"}, \code{yaxisDir = "decrease"}: }{ +#' origin at the lower-left} +#' \item{\code{half = "top"}, \code{yaxisDir = "decrease"}: }{ +#' origin at the upper-left; y increases downward} +#' \item{\code{half = "bottom"}, \code{yaxisDir = "increase"}: }{ +#' origin at the upper-left} +#' \item{\code{half = "top"}, \code{yaxisDir = "increase"}: }{ +#' origin at the lower-left} +#' } +#' The combination \code{half = "top", yaxisDir = "decrease"} matches the +#' orientation used by common 3D genome browsers, where the upper-left corner +#' is the matrix origin and y increases downward. \code{xaxisDir} controls +#' whether x increases to the right (\code{"increase"}) or to the left +#' (\code{"decrease"}). +#' #' @details #' A square Hi-C plot can be placed on a plotgardener coordinate page #' by providing plot placement parameters: @@ -173,7 +244,7 @@ #' #' @export plotHicSquare <- function(data, resolution = "auto", zrange = NULL, - norm = "KR", matrix = "observed", chrom, + norm = "auto", matrix = "observed", chrom, chromstart = NULL, chromend = NULL, altchrom = NULL, altchromstart = NULL, altchromend = NULL, @@ -182,17 +253,23 @@ plotHicSquare <- function(data, resolution = "auto", zrange = NULL, n = 9, "YlGnBu" )), colorTrans = "linear", - half = "both", yaxisDir = "increase", bg = NA, + half = "both", yaxisDir = "increase", + xaxisDir = "increase", + aspect = c("free", "fixed"), bg = NA, x = NULL, y = NULL, width = NULL, height = NULL, just = c("left", "top"), default.units = "inches", - draw = TRUE, params = NULL, quiet = FALSE) { + draw = TRUE, + raster = c("auto", "never", "always"), + raster.max = 2000, + params = NULL, quiet = FALSE) { # ========================================================================= # FUNCTIONS # ========================================================================= ## Define a function that catches errors for plotHicSquare - errorcheck_plotHicSquare <- function(hic, hicPlot, norm, yaxisDir) { + errorcheck_plotHicSquare <- function(hic, hicPlot, norm, yaxisDir, + aspect = "free") { ###### hic/cool/mcool/norm hicErrors(hic = hic, norm = norm) @@ -221,7 +298,8 @@ plotHicSquare <- function(data, resolution = "auto", zrange = NULL, !is.null(hicPlot$altchromend)) { ## Check to see if region is square - if ((hicPlot$chromend - hicPlot$chromstart) != + if (!identical(aspect, "fixed") && + (hicPlot$chromend - hicPlot$chromstart) != (hicPlot$altchromend - hicPlot$altchromstart)) { warning("Trying to plot non-square region.", call. = FALSE) } @@ -327,31 +405,45 @@ plotHicSquare <- function(data, resolution = "auto", zrange = NULL, } ## Define a function that sets viewport xscale and yscale - vp_scale <- function(hicPlot, yaxisDir) { + vp_scale <- function(hicPlot, yaxisDir, xaxisDir = "increase", + aspect = "free") { if (!is.null(hicPlot$chromstart) & !is.null(hicPlot$chromend)) { if (is.null(hicPlot$altchrom)) { xscale <- c(hicPlot$chromstart, hicPlot$chromend) yscale <- xscale + } else if (hicPlot$chrom == hicPlot$altchrom) { + xscale <- c(hicPlot$chromstart, hicPlot$chromend) + yscale <- xscale } else { + ## Always x = chrom, y = altchrom for interchromosomal maps. + xscale <- c(hicPlot$chromstart, hicPlot$chromend) + yscale <- c(hicPlot$altchromstart, hicPlot$altchromend) if (hicPlot$half == "bottom") { - xscale <- c(hicPlot$chromstart, hicPlot$chromend) - yscale <- c(hicPlot$altchromstart, hicPlot$altchromend) + yscale <- rev(yscale) } - - if (hicPlot$half == "top") { - xscale <- c(hicPlot$altchromstart, hicPlot$altchromend) - yscale <- c(hicPlot$chromstart, hicPlot$chromend) + if (identical(aspect, "fixed")) { + xRange <- diff(range(xscale)) + yRange <- diff(range(yscale)) + maxRange <- max(xRange, yRange) + xCenter <- mean(range(xscale)) + yCenter <- mean(range(yscale)) + xscale <- c(xCenter - maxRange / 2, + xCenter + maxRange / 2) + yscale <- c(yCenter - maxRange / 2, + yCenter + maxRange / 2) } } } else { xscale <- c(0, 1) yscale <- c(0, 1) } - - if (yaxisDir == "decrease"){ + + if (yaxisDir == "decrease") { yscale <- rev(yscale) } - + if (xaxisDir == "decrease") { + xscale <- rev(xscale) + } return(list(xscale, yscale)) } @@ -487,7 +579,8 @@ plotHicSquare <- function(data, resolution = "auto", zrange = NULL, hic = hicInternal$data, hicPlot = hicPlot, norm = hicInternal$norm, - yaxisDir = hicInternal$yaxisDir + yaxisDir = hicInternal$yaxisDir, + aspect = match.arg(hicInternal$aspect, c("free", "fixed")) ) # ========================================================================= @@ -589,9 +682,13 @@ plotHicSquare <- function(data, resolution = "auto", zrange = NULL, # MAKE SYMMETRIC # ========================================================================= - hicFlip <- hic[, c("y", "x", "counts")] - colnames(hicFlip) <- c("x", "y", "counts") - hic <- unique(rbind(hic, hicFlip)) + ## Only symmetrize intrachromosomal maps. An interchromosomal matrix + ## (chrom != altchrom) is a single rectangle, not two mirrored triangles. + if (is.null(hicPlot$altchrom) || hicPlot$chrom == hicPlot$altchrom) { + hicFlip <- hic[, c("y", "x", "counts")] + colnames(hicFlip) <- c("x", "y", "counts") + hic <- unique(rbind(hic, hicFlip)) + } colnames(hic) <- c("x", "y", "counts") # ========================================================================= @@ -646,7 +743,10 @@ plotHicSquare <- function(data, resolution = "auto", zrange = NULL, # ========================================================================= ## Get viewport xscale and yscale - scale <- vp_scale(hicPlot = hicPlot, yaxisDir = hicInternal$yaxisDir) + scale <- vp_scale(hicPlot = hicPlot, yaxisDir = hicInternal$yaxisDir, + xaxisDir = hicInternal$xaxisDir, + aspect = match.arg(hicInternal$aspect, + c("free", "fixed"))) ## If placing information is provided but plot == TRUE, set up it's own ## viewport separate from bb_makepage @@ -720,16 +820,40 @@ plotHicSquare <- function(data, resolution = "auto", zrange = NULL, if (!is.null(shapes[[1]])) { - ## Make square grobs and add to grob gTree - hic_squares <- rectGrob( - x = shapes[[1]]$x, - y = shapes[[1]]$y, - just = c("left", "bottom"), - width = hicPlot$resolution, - height = hicPlot$resolution, - gp = gpar(col = NA, fill = shapes[[1]]$color), - default.units = "native" + rasterMode <- match.arg( + hicInternal$raster, + c("auto", "never", "always") ) + useRaster <- rasterMode == "always" || + (rasterMode == "auto" && nrow(shapes[[1]]) > 5000) + rasterGrob <- NULL + if (useRaster && + (is.null(hicPlot$altchrom) || + hicPlot$chrom == hicPlot$altchrom) && + hicInternal$yaxisDir == "increase") { + rasterGrob <- .hicRasterGrob( + squares = shapes[[1]], + xmin = min(scale[[1]]), xmax = max(scale[[1]]), + ymin = min(scale[[2]]), ymax = max(scale[[2]]), + resolution = hicPlot$resolution, + maxDim = hicInternal$raster.max + ) + } + + if (!is.null(rasterGrob)) { + hic_squares <- rasterGrob + } else { + ## Make square grobs and add to grob gTree + hic_squares <- rectGrob( + x = shapes[[1]]$x, + y = shapes[[1]]$y, + just = c("left", "bottom"), + width = hicPlot$resolution, + height = hicPlot$resolution, + gp = gpar(col = NA, fill = shapes[[1]]$color), + default.units = "native" + ) + } assign("hic_grobs", addGrob( @@ -780,6 +904,16 @@ plotHicSquare <- function(data, resolution = "auto", zrange = NULL, hicPlot$altchromend <- hicPlot$chromend } + hicPlot$xchrom <- hicPlot$chrom + hicPlot$xchromstart <- hicPlot$chromstart + hicPlot$xchromend <- hicPlot$chromend + hicPlot$ychrom <- hicPlot$altchrom + hicPlot$ychromstart <- hicPlot$altchromstart + hicPlot$ychromend <- hicPlot$altchromend + hicPlot$xaxisDir <- hicInternal$xaxisDir + hicPlot$xaxisRange <- scale[[1]] + hicPlot$yaxisRange <- scale[[2]] + message("hicSquare[", vp$name, "]") invisible(hicPlot) } diff --git a/R/plotHicTriangle.R b/R/plotHicTriangle.R index 0da764167..4c5cd0afd 100644 --- a/R/plotHicTriangle.R +++ b/R/plotHicTriangle.R @@ -4,7 +4,7 @@ #' data, #' resolution = "auto", #' zrange = NULL, -#' norm = "KR", +#' norm = "auto", #' matrix = "observed", #' chrom, #' chromstart = NULL, @@ -13,6 +13,7 @@ #' palette = colorRampPalette(brewer.pal(n = 9, "YlGnBu")), #' colorTrans = "linear", #' flip = FALSE, +#' xaxisDir = "increase", #' bg = NA, #' x = NULL, #' y = NULL, @@ -21,6 +22,8 @@ #' just = c("left", "top"), #' default.units = "inches", #' draw = TRUE, +#' raster = c("auto", "never", "always"), +#' raster.max = 2000, #' params = NULL, #' quiet = FALSE #' ) @@ -37,7 +40,9 @@ #' will be set to the max or min. #' @param norm Character value specifying hic data normalization method, #' if giving .hic or .(m)cool file. This value must be found in the .hic or -#' .(m)cool file. Default value is \code{norm = "KR"}. +#' .(m)cool file. \code{"auto"} chooses \code{"KR"} for .hic files and an +#' an available bins column for .(m)cool files (see \code{readCoolNorms()}). +#' Default value is \code{norm = "auto"}. #' @param matrix Character value indicating the type of matrix to output for #' .hic files. #' Default value is \code{matrix = "observed"}. Options are: @@ -60,6 +65,10 @@ #' Default value is \code{colorTrans = "linear"}. #' @param flip A logical indicating whether to flip the orientation of #' the Hi-C matrix over the x-axis. Default value is \code{flip = FALSE}. +#' @param xaxisDir A string specifying the genomic direction of the x-axis. +#' Options are \code{"increase"} or \code{"decrease"}. A value of +#' \code{"decrease"} mirrors the triangle horizontally. +#' Default value is \code{xaxisDir = "increase"}. #' @param bg Character value indicating background color. #' Default value is \code{bg = NA}. #' @param x A numeric or unit object specifying triangle Hi-C plot x-location. @@ -84,6 +93,10 @@ #' numerics. Default value is \code{default.units = "inches"}. #' @param draw A logical value indicating whether graphics output should #' be produced. Default value is \code{draw = TRUE}. +#' @param raster Rasterization mode for regular Hi-C pixels. Edge-clipped +#' pixels remain vector. \code{"auto"} rasterizes large maps. +#' @param raster.max Maximum raster dimension. Default value is +#' \code{raster.max = 2000}. #' @param params An optional \link[plotgardener]{pgParams} object containing #' relevant function parameters. #' @param quiet A logical indicating whether or not to print messages. @@ -151,18 +164,20 @@ #' #' @export plotHicTriangle <- function(data, resolution = "auto", zrange = NULL, - norm = "KR", matrix = "observed", chrom, + norm = "auto", matrix = "observed", chrom, chromstart = NULL, chromend = NULL, assembly = "hg38", palette = colorRampPalette(brewer.pal( n = 9, "YlGnBu" )), colorTrans = "linear", flip = FALSE, - bg = NA, + xaxisDir = "increase", bg = NA, x = NULL, y = NULL, width = NULL, height = NULL, just = c("left", "top"), default.units = "inches", draw = TRUE, + raster = c("auto", "never", "always"), + raster.max = 2000, params = NULL, quiet = FALSE) { # ========================================================================= @@ -491,6 +506,10 @@ plotHicTriangle <- function(data, resolution = "auto", zrange = NULL, plotType = "triangle Hi-C plot") hicPlot <- scaleChecks[[1]] thicInternal <- scaleChecks[[2]] + ## NOTE: Horizontal flipping for triangles is implemented by mirroring + ## the pixel coordinates below, not by reversing the viewport xscale. + ## The rotated triangle viewport uses the x/y scales geometrically, so a + ## reversed scale would move the drawn triangle out of its clip region. # ========================================================================= # ADJUST RESOLUTION @@ -524,6 +543,22 @@ plotHicTriangle <- function(data, resolution = "auto", zrange = NULL, # ========================================================================= hic <- subset_data(hic = hic, hicPlot = hicPlot) + + # ========================================================================= + # HORIZONTAL FLIP + # ========================================================================= + + ## Mirror each pixel across the vertical centre of the plot. For the + ## lower triangle this is (x, y) -> (L - y - res, L - x - res), which + ## maps the lower triangle onto itself while mirroring the signal. + if (identical(thicInternal$xaxisDir, "decrease") && nrow(hic) > 0) { + mirror <- hicPlot$chromstart + hicPlot$chromend - + hicPlot$resolution + oldX <- hic$x + oldY <- hic$y + hic$x <- mirror - oldY + hic$y <- mirror - oldX + } # ========================================================================= # GET LOWER TRIANGULAR FOR FLIP @@ -744,24 +779,62 @@ plotHicTriangle <- function(data, resolution = "auto", zrange = NULL, triangles <- hic[which(hic[, "y"] == hic[, "x"]), ] if (nrow(squares) > 0) { - - ## Make square grobs and add to grob gTree - hic_squares <- rectGrob( - x = squares$x, - y = squares$y, - just = c("left", "bottom"), - width = squares$width, - height = squares$height, - gp = gpar(col = NA, fill = squares$color), - default.units = "native" - ) - assign("hic_grobs2", - addGrob( - gTree = get("hic_grobs2", envir = pgEnv), - child = hic_squares - ), - envir = pgEnv + rasterMode <- match.arg( + thicInternal$raster, + c("auto", "never", "always") ) + regular <- abs(as.numeric(squares$width) - + hicPlot$resolution) < 1e-8 & + abs(as.numeric(squares$height) - + hicPlot$resolution) < 1e-8 + regularSquares <- squares[regular, , drop = FALSE] + edgeSquares <- squares[!regular, , drop = FALSE] + + useRaster <- rasterMode == "always" || + (rasterMode == "auto" && nrow(regularSquares) > 5000) + rasterGrob <- NULL + if (useRaster && nrow(regularSquares) > 0) { + rasterGrob <- .hicRasterGrob( + squares = regularSquares, + xmin = min(thicInternal$xscale), + xmax = max(thicInternal$xscale), + ymin = min(thicInternal$xscale), + ymax = max(thicInternal$xscale), + resolution = hicPlot$resolution, + maxDim = thicInternal$raster.max + ) + } + + if (!is.null(rasterGrob)) { + assign("hic_grobs2", + addGrob( + gTree = get("hic_grobs2", envir = pgEnv), + child = rasterGrob + ), + envir = pgEnv + ) + } else { + edgeSquares <- squares + } + + if (nrow(edgeSquares) > 0) { + hic_squares <- rectGrob( + x = edgeSquares$x, + y = edgeSquares$y, + just = c("left", "bottom"), + width = edgeSquares$width, + height = edgeSquares$height, + gp = gpar(col = NA, fill = edgeSquares$color), + default.units = "native" + ) + assign("hic_grobs2", + addGrob( + gTree = get("hic_grobs2", envir = pgEnv), + child = hic_squares + ), + envir = pgEnv + ) + } } if (nrow(triangles) > 0) { @@ -802,6 +875,20 @@ plotHicTriangle <- function(data, resolution = "auto", zrange = NULL, hicPlot$grobs <- get("hic_grobs2", envir = pgEnv) + hicPlot$xchrom <- hicPlot$chrom + hicPlot$xchromstart <- hicPlot$chromstart + hicPlot$xchromend <- hicPlot$chromend + hicPlot$ychrom <- hicPlot$chrom + hicPlot$ychromstart <- hicPlot$chromstart + hicPlot$ychromend <- hicPlot$chromend + hicPlot$xaxisDir <- thicInternal$xaxisDir + hicPlot$xaxisRange <- if (identical(thicInternal$xaxisDir, "decrease")) { + rev(thicInternal$xscale) + } else { + thicInternal$xscale + } + hicPlot$yaxisRange <- thicInternal$xscale + # ========================================================================= # RETURN OBJECT # ========================================================================= diff --git a/R/plotLegend.R b/R/plotLegend.R index a01de2c4b..ac53a46cb 100644 --- a/R/plotLegend.R +++ b/R/plotLegend.R @@ -67,6 +67,10 @@ #' @return Returns a \code{legend} object containing relevant #' placement and \link[grid]{grob} information. #' +#' @note Some SVG renderers, notably cairosvg, may fail to render filled +#' legend keys even though the grobs are present. Use the PDF/PNG device or +#' an alternative SVG backend such as svglite if legend keys disappear. +#' #' @examples #' ## Load BED data #' library(plotgardenerData) diff --git a/R/plotMultiSignal.R b/R/plotMultiSignal.R index 80321e4f3..eaaee9b1b 100644 --- a/R/plotMultiSignal.R +++ b/R/plotMultiSignal.R @@ -15,10 +15,13 @@ #' range = NULL, #' scale = FALSE, #' label = NULL, +#' label.position = NULL, +#' label.offset = 0.01, #' bg = NA, #' baseline = TRUE, #' baseline.color = "grey", #' baseline.lwd = 1, +#' baseline.lty = 1, #' orientation = "h", #' x = NULL, #' y = NULL, @@ -66,14 +69,20 @@ #' top right of the signal tracks. Otherwise, the label will be drawn in the #' top left of the plot. For more customizable labels, #' use \link[plotgardener]{plotText}. +#' @param label.position Label position for each track. See +#' \link[plotgardener]{plotSignal}. +#' @param label.offset Offset from the plot edge in npc units. #' @param bg Character value indicating background color. #' Default value is \code{bg = NA}. #' @param baseline Logical value indicating whether to include a -#' baseline along the x-axis. Default value is \code{baseline = TRUE}. +#' baseline along the x-axis. A numeric value can be supplied to place the +#' baseline at a specific y-value. Default value is \code{baseline = TRUE}. #' @param baseline.color Baseline color. #' Default value is \code{baseline.color = "grey"}. #' @param baseline.lwd Baseline line width. #' Default value is \code{baseline.lwd = 1}. +#' @param baseline.lty Baseline line type. +#' Default value is \code{baseline.lty = 1}. #' @param orientation A string specifying signal track orientations. #' Default value is \code{orientation = "h"}. Options are: #' \describe{ @@ -171,10 +180,13 @@ plotMultiSignal<- function(data, range = NULL, scale = FALSE, label = NULL, + label.position = NULL, + label.offset = 0.01, bg = NA, baseline = TRUE, baseline.color = "grey", baseline.lwd = 1, + baseline.lty = 1, orientation = "h", x = NULL, y = NULL, @@ -328,12 +340,16 @@ plotMultiSignal<- function(data, end = multisigInternal$chromend) - range <- calcSignalRange(data = signal, - chrom = multisigInternal$chrom, - chromstart = multisigInternal$chromstart, - chromend = multisigInternal$chromend, - assembly = multisigInternal$assembly, - negData = multisigInternal$negData) + if (is.null(multisigInternal$range)) { + range <- calcSignalRange(data = signal, + chrom = multisigInternal$chrom, + chromstart = multisigInternal$chromstart, + chromend = multisigInternal$chromend, + assembly = multisigInternal$assembly, + negData = multisigInternal$negData) + } else { + range <- multisigInternal$range + } # ========================================================================= # SET PLACEMENT COORDINATES, COLORS, AND LABELS @@ -386,6 +402,8 @@ plotMultiSignal<- function(data, orientation = multisigInternal$orientation, scale = multisigInternal$scale, label = lab, + label.position = multisigInternal$label.position, + label.offset = multisigInternal$label.offset, binSize = multisigInternal$binSize, binCap = multisigInternal$binCap, negData = multisigInternal$negData, @@ -398,7 +416,8 @@ plotMultiSignal<- function(data, bg = multisigInternal$bg, baseline = multisigInternal$baseline, baseline.color = multisigInternal$baseline.color, - baseline.lwd = multisigInternal$baseline.lwd, + baseline.lwd = multisigInternal$baseline.lwd, + baseline.lty = multisigInternal$baseline.lty, just = multisigInternal$just, default.units = multisigInternal$default.units, draw = draw)) diff --git a/R/plotNeo.R b/R/plotNeo.R new file mode 100644 index 000000000..8fbeb44a0 --- /dev/null +++ b/R/plotNeo.R @@ -0,0 +1,1341 @@ +#' Draw an SV neo-chromosome assembly backbone +#' +#' Draw a directional fragment backbone for a `neoAssembly` object. Each +#' fragment is drawn as an arrow pointing in its neo-chromosome orientation. +#' +#' @param neo A `neoAssembly` object from \code{readNeoAssembly()}. +#' @param x A numeric or unit object specifying the backbone x-location. +#' @param y A numeric, unit object, or character containing a "b" combined +#' with a numeric value specifying the backbone y-location. +#' @param width A numeric or unit object specifying the backbone width. +#' @param height A numeric or unit object specifying the backbone height. +#' @param just Justification of the backbone relative to its (x, y) location. +#' Default value is \code{just = c("left", "top")}. +#' @param default.units A string indicating the default units to use if +#' \code{x}, \code{y}, \code{width}, or \code{height} are only given as +#' numerics. Default value is \code{default.units = "inches"}. +#' @param fill Fill color(s) for fragments. A single value, a vector of +#' length equal to the number of fragments, or a named vector keyed by +#' chromosome name. Default value is \code{fill = "#D4EEF9"}. +#' @param linecolor Fragment outline color. Default value is +#' \code{linecolor = "white"}. +#' @param lwd Fragment outline line width. Default value is \code{lwd = 0.5}. +#' @param fragment.height Fraction of \code{height} used by the fragment +#' arrows. Default value is \code{fragment.height = 0.6}. +#' @param arrow.size Arrow-tip size in page units. If \code{NULL}, the tip is +#' sized relative to each fragment. +#' @param labels Logical value indicating whether to draw fragment labels, or +#' a character vector of labels. Default value is \code{labels = TRUE}. +#' @param label.fontsize Fragment label font size. +#' Default value is \code{label.fontsize = 7}. +#' @param label.fontcolor Fragment label color. +#' Default value is \code{label.fontcolor = "black"}. +#' @param show.seams Logical value indicating whether to draw fragment +#' boundaries. Default value is \code{show.seams = TRUE}. +#' @param seam.color Fragment boundary color. +#' Default value is \code{seam.color = "grey40"}. +#' @param seam.lwd Fragment boundary line width. Default value is +#' \code{seam.lwd = 0.5}. +#' @param seam.lty Fragment boundary line type. Default value is +#' \code{seam.lty = 1}. +#' @param params An optional \link[plotgardener]{pgParams} object. +#' @param ... Additional grid graphical parameters. See \link[grid]{gpar}. +#' +#' @return Invisibly returns a list containing the fragment polygons, labels, +#' and boundary segments. +#' +#' @examples +#' \dontrun{ +#' neo <- readNeoAssembly("HM1_merged.assemblies.txt", "C1", extend = 200000) +#' pageCreate(width = 6, height = 2, default.units = "inches") +#' plotNeoAssembly(neo, x = 0.5, y = 0.5, width = 3, height = 0.2) +#' } +#' @export +plotNeoAssembly <- function(neo, x, y, width, height, + just = c("left", "top"), + default.units = "inches", + fill = "#D4EEF9", linecolor = "white", lwd = 0.5, + fragment.height = 0.6, arrow.size = NULL, + labels = TRUE, label.fontsize = 7, + label.fontcolor = "black", + show.seams = TRUE, seam.color = "grey40", + seam.lwd = 0.5, seam.lty = 1, + params = NULL, ...) { + + if (!inherits(neo, "neoAssembly")) { + stop("`neo` must be a `neoAssembly` object.", call. = FALSE) + } + if (missing(x) || missing(y) || missing(width) || missing(height)) { + stop("`x`, `y`, `width`, and `height` must be supplied.", + call. = FALSE) + } + + check_page(error = "Cannot plot a neo assembly without a `plotgardener` page.") + + assemblyInternal <- parseParams( + params = params, + defaultArgs = formals(eval(match.call()[[1]])), + declaredArgs = lapply(match.call()[-1], eval.parent, n = 2), + class = "neoAssemblyInternal" + ) + assemblyInternal$just <- justConversion(just = assemblyInternal$just) + + page_units <- get("page_units", envir = pgEnv) + + xNum <- convertX( + misc_defaultUnits(assemblyInternal$x, "x", assemblyInternal$default.units), + unitTo = page_units, valueOnly = TRUE + ) + yNum <- convertY( + misc_defaultUnits(assemblyInternal$y, "y", assemblyInternal$default.units), + unitTo = page_units, valueOnly = TRUE + ) + widthNum <- convertWidth( + misc_defaultUnits(assemblyInternal$width, "width", + assemblyInternal$default.units), + unitTo = page_units, valueOnly = TRUE + ) + heightNum <- convertHeight( + misc_defaultUnits(assemblyInternal$height, "height", + assemblyInternal$default.units), + unitTo = page_units, valueOnly = TRUE + ) + + just <- assemblyInternal$just + xLeft <- xNum - just[1] * widthNum + yTop <- yNum - (1 - just[2]) * heightNum + + fragments <- neo$fragments + nFragments <- nrow(fragments) + totalLength <- neo$total_length + + fragWidths <- fragments$length / totalLength * widthNum + fragX1 <- xLeft + fragments$offset / totalLength * widthNum + fragX2 <- xLeft + (fragments$offset + fragments$length) / + totalLength * widthNum + + fragmentHeight <- assemblyInternal$fragment.height * heightNum + if (fragmentHeight <= 0) { + stop("`fragment.height` must produce a positive fragment height.", + call. = FALSE) + } + yBottom <- yTop + (heightNum - fragmentHeight) / 2 + yCenter <- yTop + heightNum / 2 + yTopArrow <- yBottom + fragmentHeight + + ## Resolve fill colors + fillColors <- assemblyInternal$fill + if (length(fillColors) == 1) { + fillColors <- rep(fillColors, nFragments) + } else if (!is.null(names(fillColors)) && + all(fragments$chrom %in% names(fillColors))) { + fillColors <- unname(fillColors[fragments$chrom]) + } else { + fillColors <- rep_len(fillColors, nFragments) + } + + polygons <- vector("list", nFragments) + for (i in seq_len(nFragments)) { + x1 <- fragX1[i] + x2 <- fragX2[i] + tip <- if (is.null(assemblyInternal$arrow.size)) { + min(0.1, (x2 - x1) * 0.15) + } else { + assemblyInternal$arrow.size + } + tip <- min(tip, (x2 - x1) * 0.45) + + if (fragments$flipped[i]) { + px <- c(x2, x1 + tip, x1, x1 + tip, x2) + py <- c(yBottom, yBottom, yCenter, yTopArrow, yTopArrow) + } else { + px <- c(x1, x2 - tip, x2, x2 - tip, x1) + py <- c(yBottom, yBottom, yCenter, yTopArrow, yTopArrow) + } + + polygons[[i]] <- plotPolygon( + x = px, y = py, + fill = fillColors[i], + linecolor = assemblyInternal$linecolor, + lwd = assemblyInternal$lwd, + default.units = page_units, ... + ) + } + + labelGrobs <- list() + if (!identical(assemblyInternal$labels, FALSE)) { + if (isTRUE(assemblyInternal$labels)) { + labelText <- fragments$chrom_raw + } else { + labelText <- rep_len(assemblyInternal$labels, nFragments) + } + for (i in seq_len(nFragments)) { + labelGrobs[[i]] <- plotText( + label = labelText[i], + x = (fragX1[i] + fragX2[i]) / 2, + y = yCenter, + just = c("center", "center"), + fontsize = assemblyInternal$label.fontsize, + fontcolor = assemblyInternal$label.fontcolor, + default.units = page_units + ) + } + } + + seamGrobs <- list() + if (isTRUE(assemblyInternal$show.seams)) { + boundaries <- xLeft + cumsum(fragments$length) / totalLength * widthNum + boundaries <- boundaries[-length(boundaries)] + for (i in seq_along(boundaries)) { + seamGrobs[[i]] <- plotSegments( + x0 = boundaries[i], y0 = yTop, + x1 = boundaries[i], y1 = yTop + heightNum, + linecolor = assemblyInternal$seam.color, + lwd = assemblyInternal$seam.lwd, + lty = assemblyInternal$seam.lty, + default.units = page_units + ) + } + } + + message("neoAssembly[", neo$id, "]") + invisible(list( + fragments = polygons, + labels = labelGrobs, + seams = seamGrobs + )) +} + +#' Add flexible labels to an SV neo-chromosome assembly +#' +#' This is a label-only companion to \code{plotNeoAssembly()}. It is useful +#' when fragment labels need custom y-offsets, gaps, fonts, rotation, or +#' inversion highlighting without adding more arguments to the backbone +#' function. +#' +#' @param neo A `neoAssembly` object. +#' @param x A numeric or unit object specifying the label row x-location. +#' @param y A numeric or unit object specifying the label row y-location. +#' @param width A numeric or unit object specifying the label row width. +#' @param height A numeric or unit object specifying the label row height. +#' Default value is \code{height = 0}. +#' @param just Justification of the label row relative to (x, y). +#' Default value is \code{just = c("left", "top")}. +#' @param default.units Default units for numeric \code{x}, \code{y}, +#' \code{width}, and \code{height}. Default value is +#' \code{default.units = "inches"}. +#' @param labels Logical value or character vector of labels. +#' If \code{TRUE}, labels are generated from \code{label.style}. +#' Default value is \code{labels = TRUE}. +#' @param label.style Label style when \code{labels = TRUE}: \code{"chrom"} +#' (chromosome name), \code{"coordinate"} (chromosome and Mb coordinates), or +#' \code{"fragment"} (fragment number). Default value is +#' \code{label.style = "chrom"}. +#' @param label.fontsize Label font size. Default value is +#' \code{label.fontsize = 7}. +#' @param label.fontcolor Label color. Can be a vector recycled across +#' fragments. Default value is \code{label.fontcolor = "black"}. +#' @param label.colors Optional explicit per-fragment colors. Overrides +#' \code{label.fontcolor} and inversion coloring. +#' @param label.fontfamily Label font family. Default value is +#' \code{label.fontfamily = ""}. +#' @param label.fontface Label font face. Default value is +#' \code{label.fontface = 1}. +#' @param label.rot Label rotation in degrees. Default value is +#' \code{label.rot = 0}. +#' @param label.position Label position relative to the fragment row: +#' \code{"center"}, \code{"above"}, or \code{"below"}. +#' Default value is \code{label.position = "center"}. +#' @param label.offset Vertical offset in page units for \code{"above"} or +#' \code{"below"} positions. Default value is \code{label.offset = 0.1}. +#' @param show.inversion Logical value indicating whether flipped fragments +#' should be marked. Default value is \code{show.inversion = FALSE}. +#' @param inversion.suffix Suffix appended to flipped-fragment labels. +#' Default value is \code{inversion.suffix = " (inv)"}. +#' @param inversion.color Color for flipped-fragment labels. Default value is +#' \code{inversion.color = "red"}. +#' @param params An optional \link[plotgardener]{pgParams} object. +#' @param ... Additional arguments passed to \code{plotText()}. +#' +#' @return Invisibly returns a list of \code{plotText()} objects. +#' +#' @examples +#' \dontrun{ +#' plotNeoAssembly(neo, x = 1, y = 3, width = 3, height = 0.15, +#' labels = FALSE) +#' annoNeoFragmentLabels( +#' neo, x = 1, y = 3.25, width = 3, +#' label.style = "coordinate", +#' label.position = "below", +#' label.offset = 0.05, +#' label.fontface = "italic", +#' show.inversion = TRUE +#' ) +#' } +#' @export +annoNeoFragmentLabels <- function(neo, x, y, width, height = 0, + just = c("left", "top"), + default.units = "inches", + labels = TRUE, label.style = "chrom", + label.fontsize = 7, + label.fontcolor = "black", + label.colors = NULL, + label.fontfamily = "", + label.fontface = 1, + label.rot = 0, + label.position = "center", + label.offset = 0.1, + show.inversion = FALSE, + inversion.suffix = " (inv)", + inversion.color = "red", + params = NULL, ...) { + + if (!inherits(neo, "neoAssembly")) { + stop("`neo` must be a `neoAssembly` object.", call. = FALSE) + } + if (missing(x) || missing(y) || missing(width)) { + stop("`x`, `y`, and `width` must be supplied.", call. = FALSE) + } + label.position <- match.arg(label.position, + c("center", "above", "below")) + label.style <- match.arg(label.style, + c("chrom", "coordinate", "fragment")) + check_page(error = "Cannot annotate a neo assembly without a `plotgardener` page.") + + labelInternal <- parseParams( + params = params, + defaultArgs = formals(eval(match.call()[[1]])), + declaredArgs = lapply(match.call()[-1], eval.parent, n = 2), + class = "neoLabelInternal" + ) + labelInternal$just <- justConversion(just = labelInternal$just) + + page_units <- get("page_units", envir = pgEnv) + xNum <- convertX( + misc_defaultUnits(labelInternal$x, "x", labelInternal$default.units), + unitTo = page_units, valueOnly = TRUE + ) + yNum <- convertY( + misc_defaultUnits(labelInternal$y, "y", labelInternal$default.units), + unitTo = page_units, valueOnly = TRUE + ) + widthNum <- convertWidth( + misc_defaultUnits(labelInternal$width, "width", + labelInternal$default.units), + unitTo = page_units, valueOnly = TRUE + ) + heightNum <- convertHeight( + misc_defaultUnits(labelInternal$height, "height", + labelInternal$default.units), + unitTo = page_units, valueOnly = TRUE + ) + + just <- labelInternal$just + xLeft <- xNum - just[1] * widthNum + yTop <- yNum - (1 - just[2]) * heightNum + yCenter <- yTop + heightNum / 2 + + fragments <- neo$fragments + nFragments <- nrow(fragments) + fragWidths <- fragments$length / neo$total_length * widthNum + fragCenters <- xLeft + (fragments$offset + fragments$length / 2) / + neo$total_length * widthNum + + if (isTRUE(labels)) { + labelText <- switch(label.style, + chrom = fragments$chrom_raw, + coordinate = { + left <- ifelse(fragments$flipped, + fragments$end, fragments$start) / 1e6 + right <- ifelse(fragments$flipped, + fragments$start, fragments$end) / 1e6 + paste0(fragments$chrom_raw, ": ", + sprintf("%.2f", left), "-", + sprintf("%.2f", right), " Mb") + }, + fragment = paste0("fragment ", fragments$id) + ) + } else { + labelText <- rep_len(labels, nFragments) + } + + if (isTRUE(show.inversion) && !isTRUE(labels)) { + labelText[fragments$flipped] <- paste0( + labelText[fragments$flipped], inversion.suffix + ) + } else if (isTRUE(show.inversion) && isTRUE(labels)) { + labelText[fragments$flipped] <- paste0( + labelText[fragments$flipped], inversion.suffix + ) + } + + if (!is.null(label.colors)) { + labelColors <- rep_len(label.colors, nFragments) + } else { + labelColors <- rep_len(label.fontcolor, nFragments) + if (isTRUE(show.inversion)) { + labelColors[fragments$flipped] <- inversion.color + } + } + + yLabel <- switch(label.position, + center = rep(yCenter, nFragments), + above = rep(yTop - label.offset, nFragments), + below = rep(yTop + heightNum + label.offset, nFragments) + ) + + grobs <- lapply(seq_len(nFragments), function(i) { + plotText( + label = labelText[i], + x = fragCenters[i], + y = yLabel[i], + just = c("center", "center"), + fontsize = label.fontsize, + fontcolor = labelColors[i], + fontfamily = label.fontfamily, + fontface = label.fontface, + rot = label.rot, + default.units = page_units, ... + ) + }) + + invisible(grobs) +} + +#' +#' This mirrors the visual convention used by the neo-triangle examples: +#' a solid domain outline around the full neo-chromosome and dotted domain +#' outlines at each internal fragment seam. +#' +#' @param plot A Hi-C plot object from \code{plotHicSquare()}, +#' \code{plotHicTriangle()}, or \code{plotHicRectangle()}. +#' @param neo A `neoAssembly` object. +#' @param outer Logical value indicating whether to draw the outer +#' neo-chromosome domain outline. Default value is \code{outer = TRUE}. +#' @param seams Logical value indicating whether to draw internal fragment +#' seams. Default value is \code{seams = TRUE}. +#' @param linecolor Domain line color. Default value is +#' \code{linecolor = "black"}. +#' @param lwd Domain line width. Default value is \code{lwd = 0.5}. +#' @param lty Outer domain line type. Default value is \code{lty = 1}. +#' @param seam.color Seam line color. Defaults to \code{linecolor}. +#' @param seam.lwd Seam line width. Defaults to \code{lwd}. +#' @param seam.lty Seam line type. Default value is \code{seam.lty = 2} +#' (dotted). +#' @param ... Additional arguments passed to \code{annoDomains()}. +#' +#' @return Invisibly returns a list with \code{outer} and \code{seams} +#' \code{annoDomains} objects. +#' +#' @examples +#' \dontrun{ +#' neoHic <- readNeoHic("HM1_merged.mcool", neo, resolution = 5000) +#' h <- plotNeoHic(neoHic, type = "triangle", x = 1, y = 1, +#' width = 2, height = 1) +#' annoNeoDomains(h, neo) +#' } +#' @export +annoNeoDomains <- function(plot, neo, outer = TRUE, seams = TRUE, + linecolor = "black", lwd = 0.5, lty = 1, + seam.color = NULL, seam.lwd = NULL, + seam.lty = 2, ...) { + + if (!inherits(neo, "neoAssembly")) { + stop("`neo` must be a `neoAssembly` object.", call. = FALSE) + } + if (!is(plot, "hicSquare") && !is(plot, "hicTriangle") && + !is(plot, "hicRectangle")) { + stop("`plot` must be a Hi-C plot object.", call. = FALSE) + } + + totalLength <- neo$total_length + if (is.null(seam.color)) seam.color <- linecolor + if (is.null(seam.lwd)) seam.lwd <- lwd + outerGrobs <- NULL + seamGrobs <- list() + + if (isTRUE(outer)) { + masterDomain <- data.frame( + chrom = "neo", + start = 0, + end = totalLength + ) + outerGrobs <- annoDomains( + plot = plot, data = masterDomain, + linecolor = linecolor, lwd = lwd, lty = lty, fill = NA, ... + ) + } + + if (isTRUE(seams)) { + boundaries <- cumsum(neo$fragments$length) + boundaries <- boundaries[-length(boundaries)] + ## Triangle plots mirror the pixel data rather than the viewport, so + ## seam annotations must be mirrored explicitly to stay aligned. + if (is(plot, "hicTriangle") && + identical(plot$xaxisDir, "decrease")) { + boundaries <- totalLength - boundaries + } + seamGrobs <- lapply(boundaries, function(boundary) { + seamDomain <- data.frame( + chrom = c("neo", "neo"), + start = c(0, boundary), + end = c(boundary, totalLength) + ) + annoDomains( + plot = plot, data = seamDomain, + linecolor = seam.color, lwd = seam.lwd, lty = seam.lty, + fill = NA, ... + ) + }) + } + + invisible(list(outer = outerGrobs, seams = seamGrobs)) +} + +#' Plot IGV-style gene models in neo-chromosome coordinates +#' +#' Draws gene models through the neo-chromosome topology, using IGV-style +#' display modes. At whole-chromosome scale genes collapse to solid blocks; +#' when zoomed in, gene bodies and exon blocks are shown. Input can be a +#' GTF/GFF file, a `GRanges` object, or a data frame. Using a GTF/GFF file +#' allows arbitrary GENCODE releases without requiring a matching TxDb +#' package. +#' +#' @param data A GTF/GFF path, `GRanges` object, data frame, or a +#' `TxDb`/`EnsDb` annotation object. Data frames need `chrom`, `start`, +#' `end`, and optionally `strand`, `gene`, `transcript`, and `feature` +#' columns. +#' @param neo A `neoAssembly` object. +#' @param txdb Optional `TxDb` or `EnsDb` annotation. If `data` is a +#' `TxDb`/`EnsDb`, it is used automatically. +#' @param orgdb Optional `OrgDb` used to map gene IDs to symbols. +#' @param assembly Assembly name or object used to resolve default +#' `TxDb`/`OrgDb` packages. Defaults to `neo$assembly`. +#' @param gene.id.column,display.column Column names used when reading a +#' `TxDb` annotation. +#' @param geneOrder Optional character vector giving label priority order. +#' @param labelClusters Logical value indicating whether labels should be +#' rotated to reduce overlap. Default value is `FALSE`. +#' @param labelClusterRot Rotation in degrees for clustered labels. +#' Default value is 45. +#' @param geneBackground Color for non-highlighted genes when +#' `geneHighlights` is supplied. Default value is `"grey"`. +#' @param geneMode Gene layout mode. `"expand"` draws all genes at full +#' opacity in packed rows. `"focus"` draws priority genes (`geneHighlights`, +#' `geneOrder`, or named `labels`) at full opacity and all other genes at +#' `focus.alpha`. `"compact"` draws all genes on a single line. +#' Default value is `"expand"`. +#' @param focus.alpha Alpha applied to non-priority genes in focus mode. +#' Default value is 0.5. +#' @param reader GTF/GFF reader: `"auto"`, `"readGFF"`, `"import"`, or +#' `"tabix"`. Default value is `"auto"`. +#' @param cache Optional cache directory for parsed annotations, or `TRUE` +#' for the plotgardener user cache. Default value is `NULL` (no cache). +#' @param x,y,width,height Placement parameters. +#' @param just Justification. Default value is \code{c("left", "top")}. +#' @param default.units Default units. Default value is \code{"inches"}. +#' @param displayMode Gene display mode. \code{"auto"} chooses +#' \code{"collapsed"} or \code{"expanded"} from basepairs per inch. +#' \code{"squished"} uses expanded detail with shorter rows. +#' Default value is \code{displayMode = "auto"}. +#' @param chromstart,chromend Neo-coordinate window to display. Defaults to +#' the full neo-chromosome. +#' @param color Gene color. Can be a single color or a named vector by gene. +#' Default value is \code{"black"}. +#' @param highlight.color Color for highlighted genes. +#' Default value is \code{"red"}. +#' @param geneHighlights Optional character vector of gene names, a named +#' color vector, or a data frame with `gene` and `color` columns. Genes named +#' without colors use \code{highlight.color}. +#' @param gene.type Gene biotypes to retain when a \code{gene_type} column is +#' available, e.g. \code{"protein_coding"}. Use \code{NULL} to keep all +#' biotypes. Default value is \code{"protein_coding"}. +#' @param labels Logical value or character vector of gene names to label. +#' Default value is \code{FALSE} so the track stays clean. +#' @param label.fontsize Gene label font size. Default value is 5. +#' @param label.fontcolor Gene label color for non-highlighted genes. +#' Default value is \code{"black"}. +#' @param label.position Label position: \code{"above"} or \code{"center"}. +#' Default value is \code{"above"}. +#' @param label.overlap Logical value indicating whether labels should be +#' stacked into extra levels to avoid collisions. Default value is +#' \code{TRUE}. +#' @param show.strand Strand display: \code{"arrows"}, \code{"labels"}, or +#' \code{"none"}. Logical \code{TRUE}/\code{FALSE} are accepted for backward +#' compatibility. Default value is \code{"arrows"}. +#' @param strand.color Strand-label color. Default value is \code{"black"}. +#' @param arrow.spacing Spacing between strand chevrons in points. +#' Default value is 30. +#' @param body.lwd Gene-body line width in expanded mode. Default value is +#' 0.8. +#' @param exon.height Exon block height as a fraction of row height. +#' Default value is 0.7. +#' @param feature.min.px Minimum feature width in pixels at 72 dpi. +#' Default value is 3. +#' @param exon.min.px Minimum exon width in pixels at 72 dpi. +#' Default value is 1. +#' @param exon.min.width Deprecated point-based exon width override. When +#' supplied, it takes precedence over \code{exon.min.px}. +#' @param row.height Optional explicit row height in \code{default.units}. +#' @param auto.collapse.bp.per.inch Basepairs per inch above which +#' \code{displayMode = "auto"} collapses genes. Default value is 50000. +#' @param max.rows Maximum number of gene rows. Default value is 4. +#' @param params An optional \link[plotgardener]{pgParams} object. +#' @param ... Additional arguments passed to \code{plotText()}. +#' +#' @return Invisibly returns a list with the gene rows, grobs, display mode, +#' and displayed window. +#' @export +plotNeoGenes <- function(data = NULL, neo, x, y, width, height, + txdb = NULL, orgdb = NULL, + assembly = NULL, + gene.id.column = NULL, display.column = NULL, + just = c("left", "top"), + default.units = "inches", + displayMode = c("auto", "collapsed", "expanded", + "squished"), + chromstart = 0, chromend = NULL, + color = "black", highlight.color = "red", + geneHighlights = NULL, gene.type = "protein_coding", + geneOrder = NULL, labelClusters = FALSE, + labelClusterRot = 45, + geneBackground = "grey", + geneMode = c("expand", "focus", "compact"), + focus.alpha = 0.5, + labels = FALSE, label.fontsize = 5, + label.fontcolor = "black", + label.position = c("above", "center"), + label.overlap = TRUE, + show.strand = c("arrows", "labels", "none"), + strand.color = "black", + arrow.spacing = 30, + body.lwd = 0.8, exon.height = 0.7, + feature.min.px = 3, exon.min.px = 1, + exon.min.width = NULL, + row.height = NULL, + auto.collapse.bp.per.inch = 50e3, + max.rows = 4, + reader = c("auto", "readGFF", "import", "tabix"), + cache = NULL, + params = NULL, ...) { + if (!inherits(neo, "neoAssembly")) { + stop("`neo` must be a `neoAssembly` object.", call. = FALSE) + } + + ## Parse parameters ------------------------------------------------------ + geneInternal <- parseParams( + params = params, + defaultArgs = formals(eval(match.call()[[1]])), + declaredArgs = lapply(match.call()[-1], eval.parent, n = 2), + class = "neoGeneInternal" + ) + geneInternal$just <- justConversion(just = geneInternal$just) + if (is.null(geneInternal$assembly)) { + geneInternal$assembly <- neo$assembly + } + assembly <- geneInternal$assembly + + displayMode <- match.arg( + geneInternal$displayMode, + c("auto", "collapsed", "expanded", "squished") + ) + label.position <- match.arg(geneInternal$label.position, + c("above", "center")) + reader <- match.arg(geneInternal$reader, + c("auto", "readGFF", "import", "tabix")) + geneMode <- match.arg(geneInternal$geneMode, + c("expand", "focus", "compact")) + showStrand <- geneInternal$show.strand + if (is.logical(showStrand)) { + showStrand <- if (isTRUE(showStrand)) "labels" else "none" + } + showStrand <- match.arg(showStrand, c("arrows", "labels", "none")) + if (is.null(geneInternal$chromend)) { + geneInternal$chromend <- neo$total_length + } + + ## Resolve the annotation source ---------------------------------------- + ## A TxDb/EnsDb can be passed as `data`, via `txdb=`, or left to the + ## default assembly packages. A GTF/GFF path uses the fast reader. + if (methods::is(data, "TxDb") || inherits(data, "EnsDb")) { + if (is.null(txdb)) { + txdb <- data + } + data <- NULL + } + + featureTypes <- c("gene", "exon", "CDS", "UTR", + "five_prime_UTR", "three_prime_UTR") + featureTags <- c("gene_id", "gene_name", "gene_type", + "transcript_id", "transcript_type") + + if (is.null(data)) { + if (is.null(txdb)) { + stop("Either `data` or `txdb` must be supplied.", call. = FALSE) + } + df <- .readNeoGenesTxDb( + txdb = txdb, orgdb = orgdb, neo = neo, + assemblyName = geneInternal$assembly, + gene.id.column = gene.id.column, + display.column = display.column + ) + } else if (is.character(data) && length(data) == 1 && + file.exists(data)) { + df <- .readNeoGenesGFF( + file = data, neo = neo, + type = featureTypes, tags = featureTags, + reader = reader, cache = cache + ) + } else if (inherits(data, "GRanges")) { + df <- as.data.frame(data) + df$chrom <- as.character(df$seqnames) + df$seqnames <- NULL + if ("type" %in% colnames(df)) { + df$feature <- as.character(df$type) + } else if ("feature" %in% colnames(df)) { + df$feature <- as.character(df$feature) + } else { + df$feature <- "exon" + } + if (!"gene" %in% colnames(df)) { + df$gene <- if ("gene_name" %in% colnames(df)) { + as.character(df$gene_name) + } else if ("gene_id" %in% colnames(df)) { + as.character(df$gene_id) + } else { + paste0("gene", seq_len(nrow(df))) + } + } + if (!"transcript" %in% colnames(df)) { + df$transcript <- df$gene + } + } else { + df <- as.data.frame(data, stringsAsFactors = FALSE) + if (!all(c("chrom", "start", "end") %in% colnames(df))) { + stop("`data` must contain `chrom`, `start`, and `end` columns.", + call. = FALSE) + } + if (!"feature" %in% colnames(df)) { + if ("type" %in% colnames(df)) { + df$feature <- as.character(df$type) + } else { + df$feature <- "exon" + } + } + if (!"gene" %in% colnames(df)) { + df$gene <- if ("name" %in% colnames(df)) { + df$name + } else { + paste0("gene", seq_len(nrow(df))) + } + } + if (!"transcript" %in% colnames(df)) { + df$transcript <- df$gene + } + } + if (!"strand" %in% colnames(df)) { + df$strand <- "*" + } + if (!"gene_type" %in% colnames(df) && "gene_biotype" %in% colnames(df)) { + df$gene_type <- df$gene_biotype + } + df$gene <- as.character(df$gene) + df$feature <- as.character(df$feature) + df$strand <- as.character(df$strand) + + ## Restrict to requested gene biotypes (GENCODE `gene_type`). TxDb + ## annotations often have no biotype column; only filter when the column + ## actually carries values. + if (!is.null(geneInternal$gene.type) && + "gene_type" %in% colnames(df) && + any(!is.na(df$gene_type) & nzchar(as.character(df$gene_type)))) { + df <- df[as.character(df$gene_type) %in% geneInternal$gene.type, , + drop = FALSE] + } + if (nrow(df) == 0) { + return(invisible(list(genes = NULL, grobs = list(), + displayMode = displayMode, + chromstart = geneInternal$chromstart, + chromend = geneInternal$chromend))) + } + + feature <- toupper(df$feature) + exonRows <- df[feature == "EXON", , drop = FALSE] + cdsRows <- df[feature == "CDS", , drop = FALSE] + geneRows <- df[feature == "GENE", , drop = FALSE] + if (nrow(exonRows) == 0) { + exonRows <- geneRows + } + if (nrow(exonRows) == 0) { + exonRows <- df + } + + mapRows <- function(rows) { + if (nrow(rows) == 0) { + return(NULL) + } + mapped <- mapNeoFeatures(rows, neo) + if (nrow(mapped) == 0) { + return(NULL) + } + mapped$gene <- as.character(mapped$gene) + mapped$strand <- as.character(mapped$strand) + mapped$key <- paste(mapped$gene, mapped$fragment, mapped$strand, + sep = "|") + mapped + } + mappedExons <- mapRows(exonRows) + mappedCDS <- mapRows(cdsRows) + if (is.null(mappedExons)) { + return(invisible(list(genes = NULL, grobs = list(), + displayMode = displayMode, + chromstart = geneInternal$chromstart, + chromend = geneInternal$chromend))) + } + + exonSplit <- split(mappedExons, mappedExons$key) + cdsSplit <- if (!is.null(mappedCDS)) split(mappedCDS, mappedCDS$key) else list() + keys <- names(exonSplit) + genes <- lapply(keys, function(key) { + g <- exonSplit[[key]] + exons <- IRanges::reduce(IRanges::IRanges(g$start, g$end)) + cds <- NULL + if (!is.null(cdsSplit[[key]])) { + cg <- cdsSplit[[key]] + cds <- IRanges::reduce(IRanges::IRanges(cg$start, cg$end)) + } + data.frame( + gene = g$gene[1], + strand = g$strand[1], + fragment = g$fragment[1], + start = min(g$start), + end = max(g$end), + exonStart = I(list(IRanges::start(exons))), + exonEnd = I(list(IRanges::end(exons))), + cdsStart = I(list(if (is.null(cds)) numeric(0) else + IRanges::start(cds))), + cdsEnd = I(list(if (is.null(cds)) numeric(0) else + IRanges::end(cds))), + nExons = length(exons), + stringsAsFactors = FALSE + ) + }) + genes <- do.call(rbind, genes) + genes <- genes[order(genes$start), , drop = FALSE] + + ## Clip to the displayed neo-coordinate window. + chromstart <- max(0, geneInternal$chromstart) + chromend <- min(neo$total_length, geneInternal$chromend) + if (chromend <= chromstart) { + stop("`chromend` must be greater than `chromstart`.", call. = FALSE) + } + genes <- genes[genes$end >= chromstart & genes$start <= chromend, , + drop = FALSE] + if (nrow(genes) == 0) { + return(invisible(list(genes = genes, grobs = list(), + displayMode = displayMode, + chromstart = chromstart, + chromend = chromend))) + } + genes$start <- pmax(genes$start, chromstart) + genes$end <- pmin(genes$end, chromend) + + ## Greedy row packing with explicit overflow handling. + packGenes <- function(genes, maxRows, overflow = c("drop", "last")) { + overflow <- match.arg(overflow) + genes$row <- 0L + rowEnds <- numeric(0) + for (i in seq_len(nrow(genes))) { + placed <- FALSE + for (r in seq_along(rowEnds)) { + if (genes$start[i] >= rowEnds[r]) { + genes$row[i] <- r + rowEnds[r] <- genes$end[i] + placed <- TRUE + break + } + } + if (!placed) { + rowEnds <- c(rowEnds, genes$end[i]) + genes$row[i] <- length(rowEnds) + } + } + if (any(genes$row > maxRows)) { + if (overflow == "last") { + genes$row[genes$row > maxRows] <- maxRows + } else { + warning("Not enough rows for all genes; increase `max.rows`.", + call. = FALSE) + genes <- genes[genes$row <= maxRows, , drop = FALSE] + } + } + genes + } + if (geneMode == "compact") { + genes$row <- 1L + } else { + genes <- packGenes( + genes, geneInternal$max.rows, + overflow = if (geneMode == "focus") "last" else "drop" + ) + } + if (nrow(genes) == 0) { + return(invisible(list(genes = genes, grobs = list(), + displayMode = displayMode, + chromstart = chromstart, + chromend = chromend))) + } + + ## Placement in page units ---------------------------------------------- + page_units <- get("page_units", envir = pgEnv) + xNum <- convertX(misc_defaultUnits(geneInternal$x, "x", + geneInternal$default.units), + unitTo = page_units, valueOnly = TRUE) + yNum <- convertY(misc_defaultUnits(geneInternal$y, "y", + geneInternal$default.units), + unitTo = page_units, valueOnly = TRUE) + widthNum <- convertWidth(misc_defaultUnits(geneInternal$width, "width", + geneInternal$default.units), + unitTo = page_units, valueOnly = TRUE) + heightNum <- convertHeight(misc_defaultUnits(geneInternal$height, + "height", + geneInternal$default.units), + unitTo = page_units, valueOnly = TRUE) + just <- geneInternal$just + xLeft <- xNum - just[1] * widthNum + yTop <- yNum - (1 - just[2]) * heightNum + + ## Choose display mode from actual basepairs-per-inch. + widthIn <- convertWidth(unit(widthNum, page_units), unitTo = "inches", + valueOnly = TRUE) + if (widthIn <= 0) { + stop("`width` must be positive.", call. = FALSE) + } + bpPerInch <- (chromend - chromstart) / widthIn + if (displayMode == "auto") { + displayMode <- if (bpPerInch > geneInternal$auto.collapse.bp.per.inch) { + "collapsed" + } else { + "expanded" + } + } + + nRows <- max(genes$row) + if (!is.null(geneInternal$row.height)) { + rowHeight <- convertHeight( + misc_defaultUnits(geneInternal$row.height, "height", + geneInternal$default.units), + unitTo = page_units, valueOnly = TRUE + ) + } else { + rowHeight <- heightNum / nRows + } + if (displayMode == "squished") { + rowHeight <- rowHeight * 0.6 + } + if (rowHeight * nRows > heightNum) { + warning("`row.height` exceeds the track height; using equal rows.", + call. = FALSE) + rowHeight <- heightNum / nRows + } + yOffset <- (heightNum - rowHeight * nRows) / 2 + + toX <- function(pos) { + xLeft + (pos - chromstart) / (chromend - chromstart) * widthNum + } + featureMinWidth <- convertWidth(unit(geneInternal$feature.min.px, + "points"), + unitTo = page_units, valueOnly = TRUE) + if (!is.null(geneInternal$exon.min.width)) { + exonMinWidth <- convertWidth(unit(geneInternal$exon.min.width, + "points"), + unitTo = page_units, valueOnly = TRUE) + } else { + exonMinWidth <- convertWidth(unit(geneInternal$exon.min.px, + "points"), + unitTo = page_units, valueOnly = TRUE) + } + exonMinBp <- exonMinWidth / widthNum * (chromend - chromstart) + ## Gene colors ---------------------------------------------------------- + colorMap <- NULL + if (!is.null(geneInternal$geneHighlights)) { + geneHighlights <- geneInternal$geneHighlights + if (is.data.frame(geneHighlights)) { + colorMap <- stats::setNames( + as.character(geneHighlights$color), + as.character(geneHighlights$gene) + ) + } else if (!is.null(names(geneHighlights))) { + colorMap <- as.character(geneHighlights) + names(colorMap) <- names(geneHighlights) + } else { + colorMap <- stats::setNames( + rep_len(geneInternal$highlight.color, length(geneHighlights)), + as.character(geneHighlights) + ) + } + } + geneColor <- function(g) { + if (!is.null(colorMap) && g %in% names(colorMap)) { + return(unname(colorMap[g])) + } + if (!is.null(colorMap)) { + return(geneInternal$geneBackground) + } + if (length(geneInternal$color) > 1 && + !is.null(names(geneInternal$color)) && + g %in% names(geneInternal$color)) { + return(unname(geneInternal$color[g])) + } + if (length(geneInternal$color) == 1) { + geneInternal$color + } else { + geneInternal$color[1] + } + } + isHighlighted <- vapply(genes$gene, function(g) { + (!is.null(colorMap) && g %in% names(colorMap)) || + (length(geneInternal$color) > 1 && + !is.null(names(geneInternal$color)) && + g %in% names(geneInternal$color)) + }, logical(1)) + geneCols <- unname(vapply(genes$gene, geneColor, character(1))) + + ## Priority genes keep full exon detail in compact mode. + priorityNames <- character(0) + if (!is.null(colorMap)) { + priorityNames <- c(priorityNames, names(colorMap)) + } + if (is.character(geneInternal$labels)) { + priorityNames <- c(priorityNames, geneInternal$labels) + } + if (!is.null(geneInternal$geneOrder)) { + priorityNames <- c(priorityNames, geneInternal$geneOrder) + } + priorityNames <- unique(priorityNames) + priorityIndex <- genes$gene %in% priorityNames + if (geneMode == "focus" && !any(priorityIndex)) { + priorityIndex <- rep(TRUE, nrow(genes)) + } + + ## Label layout --------------------------------------------------------- + ## Priority: explicit `geneOrder`, then highlighted genes, then the rest. + labelPriority <- seq_len(nrow(genes)) + ord <- if (is.null(geneInternal$geneOrder)) { + rep(NA_integer_, nrow(genes)) + } else { + match(genes$gene, geneInternal$geneOrder) + } + labelPriority <- order(is.na(ord), ord, !isHighlighted, labelPriority) + labelPriority <- match(seq_len(nrow(genes)), labelPriority) + drawLabel <- if (isTRUE(geneInternal$labels)) { + rep(TRUE, nrow(genes)) + } else if (is.character(geneInternal$labels)) { + genes$gene %in% geneInternal$labels + } else { + rep(FALSE, nrow(genes)) + } + if (geneMode == "focus") { + drawLabel <- drawLabel & priorityIndex + } + labelLevel <- integer(nrow(genes)) + labelHeight <- convertHeight( + grobHeight(textGrob("Hg", gp = gpar( + fontsize = geneInternal$label.fontsize + ))), + unitTo = page_units, valueOnly = TRUE + ) + if (isTRUE(geneInternal$label.overlap) && + !isTRUE(geneInternal$labelClusters) && + any(drawLabel) && label.position == "above") { + labelIdx <- which(drawLabel) + labelCx <- vapply(labelIdx, function(i) { + toX((genes$start[i] + genes$end[i]) / 2) + }, numeric(1)) + labelW <- vapply(labelIdx, function(i) { + convertWidth( + grobWidth(textGrob( + genes$gene[i], + gp = gpar(fontsize = geneInternal$label.fontsize) + )), + unitTo = page_units, valueOnly = TRUE + ) + }, numeric(1)) + for (r in unique(genes$row[labelIdx])) { + sub <- which(genes$row[labelIdx] == r) + sub <- sub[order(labelPriority[labelIdx[sub]], labelCx[sub])] + placedCx <- list() + placedW <- list() + for (j in sub) { + lev <- 0L + repeat { + key <- as.character(lev) + ok <- TRUE + if (!is.null(placedCx[[key]])) { + ok <- all(abs(labelCx[j] - placedCx[[key]]) >= + (labelW[j] + placedW[[key]]) / 2 + 0.005) + } + if (ok) break + lev <- lev + 1L + } + placedCx[[as.character(lev)]] <- + c(placedCx[[as.character(lev)]], labelCx[j]) + placedW[[as.character(lev)]] <- + c(placedW[[as.character(lev)]], labelW[j]) + labelLevel[labelIdx[j]] <- lev + } + } + } + + ## Drawing helpers ------------------------------------------------------ + clipIntervals <- function(starts, ends) { + if (length(starts) == 0) { + return(list(start = numeric(0), end = numeric(0))) + } + keep <- ends >= chromstart & starts <= chromend + list( + start = pmax(starts[keep], chromstart), + end = pmin(ends[keep], chromend) + ) + } + mergeIntervals <- function(starts, ends, minGap) { + if (length(starts) == 0) { + return(list(start = numeric(0), end = numeric(0))) + } + ord <- order(starts) + starts <- starts[ord] + ends <- ends[ord] + ms <- starts[1] + me <- ends[1] + if (length(starts) > 1) { + for (e in 2:length(starts)) { + if (starts[e] - me[length(me)] < minGap) { + me[length(me)] <- max(me[length(me)], ends[e]) + } else { + ms <- c(ms, starts[e]) + me <- c(me, ends[e]) + } + } + } + list(start = ms, end = me) + } + + grobs <- list() + for (i in seq_len(nrow(genes))) { + g <- genes[i, ] + center <- yTop + yOffset + (g$row - 0.5) * rowHeight + col <- geneCols[i] + alpha <- if (geneMode == "focus" && !priorityIndex[i]) { + geneInternal$focus.alpha + } else { + 1 + } + x1 <- toX(g$start) + x2 <- toX(g$end) + labelTop <- center + + if (displayMode == "collapsed") { + blockHeight <- rowHeight * 0.45 + geneWidthPx <- x2 - x1 + blockWidth <- max(geneWidthPx, featureMinWidth) + blockX <- if (blockWidth > geneWidthPx) { + (x1 + x2) / 2 - blockWidth / 2 + } else { + x1 + } + grobs[[length(grobs) + 1]] <- plotRect( + x = blockX, y = center - blockHeight / 2, + width = blockWidth, height = blockHeight, + just = c("left", "top"), + fill = col, linecolor = col, lwd = 0.2, alpha = alpha, + default.units = page_units + ) + labelTop <- center - blockHeight / 2 + if (showStrand == "arrows" && blockWidth > blockHeight) { + tipSize <- min(blockHeight * 0.7, blockWidth * 0.35) + tipShift <- tipSize * 0.5 + if (g$strand == "-") { + tipX <- blockX - tipShift + arrowX <- c(tipX + tipSize, tipX, tipX + tipSize) + } else { + tipX <- blockX + blockWidth + tipShift + arrowX <- c(tipX - tipSize, tipX, tipX - tipSize) + } + grobs[[length(grobs) + 1]] <- plotPolygon( + x = arrowX, + y = c(center - blockHeight / 2, center, + center + blockHeight / 2), + fill = col, linecolor = col, lwd = 0.2, alpha = alpha, + default.units = page_units + ) + } + } else { + exons <- clipIntervals(g$exonStart[[1]], g$exonEnd[[1]]) + if (g$nExons <= 1) { + blockHeight <- rowHeight * geneInternal$exon.height + blockWidth <- max(x2 - x1, featureMinWidth) + blockX <- if (blockWidth > x2 - x1) { + (x1 + x2) / 2 - blockWidth / 2 + } else { + x1 + } + grobs[[length(grobs) + 1]] <- plotRect( + x = blockX, y = center - blockHeight / 2, + width = blockWidth, height = blockHeight, + just = c("left", "top"), + fill = col, linecolor = col, lwd = 0.2, alpha = alpha, + default.units = page_units + ) + labelTop <- center - blockHeight / 2 + if (showStrand == "arrows" && blockWidth > blockHeight) { + tipSize <- min(blockHeight * 0.7, blockWidth * 0.35) + tipShift <- tipSize * 0.5 + if (g$strand == "-") { + tipX <- blockX - tipShift + arrowX <- c(tipX + tipSize, tipX, tipX + tipSize) + } else { + tipX <- blockX + blockWidth + tipShift + arrowX <- c(tipX - tipSize, tipX, tipX - tipSize) + } + grobs[[length(grobs) + 1]] <- plotPolygon( + x = arrowX, + y = c(center - blockHeight / 2, center, + center + blockHeight / 2), + fill = col, linecolor = col, lwd = 0.2, alpha = alpha, + default.units = page_units + ) + } + } else { + grobs[[length(grobs) + 1]] <- plotSegments( + x0 = x1, y0 = center, x1 = x2, y1 = center, + linecolor = col, lwd = geneInternal$body.lwd, + alpha = alpha, default.units = page_units + ) + fullHalf <- rowHeight * geneInternal$exon.height / 2 + utrHalf <- fullHalf / 2 + exons <- mergeIntervals(exons$start, exons$end, exonMinBp) + cds <- clipIntervals(g$cdsStart[[1]], g$cdsEnd[[1]]) + cds <- mergeIntervals(cds$start, cds$end, exonMinBp) + hasCDS <- length(cds$start) > 0 + + exonHalf <- if (hasCDS) utrHalf else fullHalf + for (e in seq_along(exons$start)) { + exonWidth <- max(toX(exons$end[e]) - toX(exons$start[e]), + exonMinWidth) + grobs[[length(grobs) + 1]] <- plotRect( + x = toX(exons$start[e]), y = center - exonHalf, + width = exonWidth, height = exonHalf * 2, + just = c("left", "top"), + fill = col, linecolor = col, lwd = 0.2, alpha = alpha, + default.units = page_units + ) + } + if (hasCDS) { + for (e in seq_along(cds$start)) { + cdsWidth <- max(toX(cds$end[e]) - toX(cds$start[e]), + exonMinWidth) + grobs[[length(grobs) + 1]] <- plotRect( + x = toX(cds$start[e]), y = center - fullHalf, + width = cdsWidth, height = fullHalf * 2, + just = c("left", "top"), + fill = col, linecolor = col, lwd = 0.2, + alpha = alpha, default.units = page_units + ) + } + } + labelTop <- center - fullHalf + + if (showStrand == "arrows") { + step <- convertWidth(unit(geneInternal$arrow.spacing, + "points"), + unitTo = page_units, + valueOnly = TRUE) + if (step > 0 && (x2 - x1) > step) { + arrowHalf <- rowHeight * 0.12 + arrowSize <- min(step * 0.32, rowHeight * 0.24) + arrowXs <- seq(x1 + step / 2, x2 - step / 2, + by = step) + for (ax in arrowXs) { + if (g$strand == "-") { + ax0 <- ax + arrowSize / 2 + } else { + ax0 <- ax - arrowSize / 2 + } + grobs[[length(grobs) + 1]] <- plotSegments( + x0 = ax0, y0 = center - arrowHalf, + x1 = ax, y1 = center, + linecolor = col, lwd = 0.3, + alpha = alpha, default.units = page_units + ) + grobs[[length(grobs) + 1]] <- plotSegments( + x0 = ax, y0 = center, + x1 = ax0, y1 = center + arrowHalf, + linecolor = col, lwd = 0.3, + alpha = alpha, default.units = page_units + ) + } + } + } + } + } + + if (showStrand == "labels" && + !(geneMode == "focus" && !priorityIndex[i])) { + strandLabel <- if (g$strand == "-") { + "-" + } else if (g$strand == "+") { + "+" + } else { + "*" + } + grobs[[length(grobs) + 1]] <- plotText( + label = strandLabel, x = x1 - 0.02, y = center, + just = c("right", "center"), + fontsize = geneInternal$label.fontsize, + fontcolor = geneInternal$strand.color, + default.units = page_units, ... + ) + } + + if (drawLabel[i]) { + labelCx <- toX((g$start + g$end) / 2) + if (label.position == "center") { + labelY <- center + labelJust <- c("center", "center") + } else { + labelY <- labelTop - 0.015 - + labelLevel[i] * (labelHeight + 0.005) + labelJust <- c("center", "bottom") + if (labelLevel[i] > 0) { + grobs[[length(grobs) + 1]] <- plotSegments( + x0 = labelCx, y0 = labelTop, + x1 = labelCx, y1 = labelY, + linecolor = "grey60", lwd = 0.3, + default.units = page_units + ) + } + } + labelCol <- if (isHighlighted[i]) col else + geneInternal$label.fontcolor + grobs[[length(grobs) + 1]] <- plotText( + label = g$gene, x = labelCx, y = labelY, + just = labelJust, + fontsize = geneInternal$label.fontsize, + fontcolor = labelCol, + rot = if (isTRUE(geneInternal$labelClusters)) { + geneInternal$labelClusterRot + } else { + 0 + }, + check.overlap = FALSE, + default.units = page_units, ... + ) + } + } + + invisible(list( + genes = genes, grobs = grobs, displayMode = displayMode, + chromstart = chromstart, chromend = chromend, + bpPerInch = bpPerInch, geneMode = geneMode + )) +} diff --git a/R/plotSignal.R b/R/plotSignal.R index 1e9cadd7c..e25316891 100644 --- a/R/plotSignal.R +++ b/R/plotSignal.R @@ -15,10 +15,13 @@ #' range = NULL, #' scale = FALSE, #' label = NULL, +#' label.position = NULL, +#' label.offset = 0.01, #' bg = NA, #' baseline = TRUE, #' baseline.color = "grey", #' baseline.lwd = 1, +#' baseline.lty = 1, #' orientation = "h", #' x = NULL, #' y = NULL, @@ -67,14 +70,25 @@ #' of the plot. Otherwise, the label will be drawn in the top left of the plot. #' For more customizable labels, use \link[plotgardener]{plotText}. #' Default value is \code{label = NULL}. +#' @param label.position Label position. Options are \code{"top-left"}, +#' \code{"top-right"}, \code{"bottom-left"}, \code{"bottom-right"}, +#' \code{"left"}, and \code{"right"}. If \code{NULL}, the historical +#' behavior is used (\code{"top-right"} when \code{scale = TRUE}, +#' otherwise \code{"top-left"}). Default value is +#' \code{label.position = NULL}. +#' @param label.offset Offset from the plot edge in npc units. +#' Default value is \code{label.offset = 0.01}. #' @param bg Character value indicating background color. #' Default value is \code{bg = NA}. #' @param baseline Logical value indicating whether to include a -#' baseline along the x-axis. Default value is \code{baseline = TRUE}. +#' baseline along the x-axis. A numeric value can be supplied to place the +#' baseline at a specific y-value. Default value is \code{baseline = TRUE}. #' @param baseline.color Baseline color. #' Default value is \code{baseline.color = "grey"}. #' @param baseline.lwd Baseline line width. #' Default value is \code{baseline.lwd = 1}. +#' @param baseline.lty Baseline line type. +#' Default value is \code{baseline.lty = 1}. #' @param orientation A string specifying signal track orientation. #' Default value is \code{orientation = "h"}. Options are: #' \describe{ @@ -182,8 +196,10 @@ plotSignal <- function(data, binSize = NA, binCap = TRUE, negData = FALSE, chrom, chromstart = NULL, chromend = NULL, assembly = "hg38", linecolor = "#37a7db", fill = NA, ymax = 1, range = NULL, scale = FALSE, - label = NULL, bg = NA, baseline = TRUE, - baseline.color = "grey", baseline.lwd = 1, + label = NULL, label.position = NULL, + label.offset = 0.01, bg = NA, baseline = TRUE, + baseline.color = "grey", baseline.lwd = 1, + baseline.lty = 1, orientation = "h", x = NULL, y = NULL, width = NULL, height = NULL, just = c("left", "top"), default.units = "inches", draw = TRUE, @@ -1006,44 +1022,8 @@ plotSignal <- function(data, binSize = NA, binCap = TRUE, negData = FALSE, } - lineGrob <- segmentsGrob( - x0 = unit(0, "npc"), x1 = unit(1, "npc"), - y0 = 0, y1 = 0, - gp = gpar( - col = sigInternal$baseline.color, - lwd = sigInternal$baseline.lwd - ), - default.units = "native" - ) - assign("signal_grobs", - addGrob( - gTree = get("signal_grobs", envir = pgEnv), - child = lineGrob - ), - envir = pgEnv - ) } else { if (nrow(posSignal) >= 2) { - if (sigInternal$baseline == TRUE) { - baselineGrob <- segmentsGrob( - x0 = unit(0, "npc"), - x1 = unit(1, "npc"), - y0 = 0, y1 = 0, - gp = gpar( - col = sigInternal$baseline.color, - lwd = sigInternal$baseline.lwd - ), - default.units = "native" - ) - assign("signal_grobs", - addGrob( - gTree = get("signal_grobs", envir = pgEnv), - child = baselineGrob - ), - envir = pgEnv - ) - } - sigGrob( signal = posSignal2, fillCol = sigInternal$fill[1], lineCol = sigInternal$linecolor[1], @@ -1081,9 +1061,45 @@ plotSignal <- function(data, binSize = NA, binCap = TRUE, negData = FALSE, warning("Not enough data within range to plot.", call. = FALSE) } } - # ===================================================================== - # SCALE - # ===================================================================== + + ## Draw the baseline after all signal/cutoff grobs so fills do not + ## cover it. `baseline` may be logical or a numeric y-value. + drawBaseline <- FALSE + baselineValue <- sigInternal$baseline + baselineY <- 0 + if (is.numeric(baselineValue) && length(baselineValue) == 1) { + drawBaseline <- TRUE + baselineY <- as.numeric(baselineValue) + } else if (isTRUE(baselineValue)) { + drawBaseline <- TRUE + } + if (drawBaseline && + baselineY >= signal_track$range[1] && + baselineY <= signal_track$range[2]) { + baselineGrob <- segmentsGrob( + x0 = unit(0, "npc"), x1 = unit(1, "npc"), + y0 = baselineY, y1 = baselineY, + gp = gpar( + col = sigInternal$baseline.color, + lwd = sigInternal$baseline.lwd, + lty = sigInternal$baseline.lty + ), + default.units = "native" + ) + assign("signal_grobs", + addGrob( + gTree = get("signal_grobs", envir = pgEnv), + child = baselineGrob + ), + envir = pgEnv + ) + } + + } + + # ===================================================================== + # SCALE + # ===================================================================== ## Add scale of the range of data in the top left corner if (sigInternal$scale == TRUE) { @@ -1109,34 +1125,51 @@ plotSignal <- function(data, binSize = NA, binCap = TRUE, negData = FALSE, # LABEL # ===================================================================== - if (!is.null(sigInternal$label)){ - if (sigInternal$scale == TRUE){ - labelGrob <- textGrob( - label = sigInternal$label, - just = c("right", "top"), x = 1, y = 1, - gp = sigInternal$gp - ) - } else { - labelGrob <- textGrob( - label = sigInternal$label, - just = c("left", "top"), x = 0, y = 1, - gp = sigInternal$gp - ) + if (!is.null(sigInternal$label)) { + labelPosition <- sigInternal$label.position + if (is.null(labelPosition)) { + labelPosition <- if (sigInternal$scale == TRUE) { + "top-right" + } else { + "top-left" + } } - - ## Add grob to gtree + labelPosition <- match.arg( + labelPosition, + c("top-left", "top-right", "bottom-left", "bottom-right", + "left", "right") + ) + offset <- sigInternal$label.offset + labelSpec <- switch(labelPosition, + "top-left" = list(x = offset, y = 1 - offset, + just = c("left", "top")), + "top-right" = list(x = 1 - offset, y = 1 - offset, + just = c("right", "top")), + "bottom-left" = list(x = offset, y = offset, + just = c("left", "bottom")), + "bottom-right" = list(x = 1 - offset, y = offset, + just = c("right", "bottom")), + "left" = list(x = offset, y = 0.5, + just = c("left", "center")), + "right" = list(x = 1 - offset, y = 0.5, + just = c("right", "center")) + ) + labelGrob <- textGrob( + label = sigInternal$label, + x = labelSpec$x, y = labelSpec$y, + just = labelSpec$just, + gp = sigInternal$gp + ) + assign("signal_grobs", - addGrob( - gTree = get("signal_grobs", envir = pgEnv), - child = labelGrob - ), - envir = pgEnv + addGrob( + gTree = get("signal_grobs", envir = pgEnv), + child = labelGrob + ), + envir = pgEnv ) - } - } - # ========================================================================= # IF PLOT == TRUE, DRAW GROBS # ========================================================================= diff --git a/R/plotTranscripts.R b/R/plotTranscripts.R index 2337dbcf7..c3c43d557 100644 --- a/R/plotTranscripts.R +++ b/R/plotTranscripts.R @@ -16,6 +16,7 @@ #' transcriptFilter = NULL, #' fontsize = 8, #' labels = "transcript", +#' labelPriority = NULL, #' stroke = 0.1, #' bg = NA, #' x = NULL, @@ -68,6 +69,9 @@ #' Default value is \code{fontsize = 8}. #' @param labels A character value describing the format of #' transcript text labels. Default value is \code{labels = "trancript"}. +#' @param labelPriority Optional character vector of transcript or gene names +#' to prioritize when labels overlap. Default value is +#' \code{labelPriority = NULL}. #' Options are: #' \describe{ #' \item{\code{NULL}: }{No labels.} @@ -170,7 +174,8 @@ plotTranscripts <- function(chrom, chromstart = NULL, chromend = NULL, transcriptHighlights = NULL, transcriptFilter = NULL, fontsize = 8, - labels = "transcript", stroke = 0.1, bg = NA, + labels = "transcript", labelPriority = NULL, + stroke = 0.1, bg = NA, x = NULL, y = NULL, width = NULL, height = NULL, just = c("left", "top"), default.units = "inches", draw = TRUE, @@ -688,10 +693,12 @@ plotTranscripts <- function(chrom, chromstart = NULL, chromend = NULL, ## Get representative transcript names transcriptNames <- rowData[duplicated(rowData$TXNAME) == FALSE, ] - ## Add column with center location of each transcript label - transcriptNames$labelLoc <- rowMeans( - transcriptNames[c("TXSTART", "TXEND")] - ) + ## Center labels on the in-bounds portion of each transcript + labelStart <- pmax(transcriptNames$TXSTART, + transcriptsInternal$xscale[1]) + labelEnd <- pmin(transcriptNames$TXEND, + transcriptsInternal$xscale[2]) + transcriptNames$labelLoc <- (labelStart + labelEnd) / 2 if (transcriptsInternal$labels == "transcript") { label <- transcriptNames$TXNAME @@ -706,6 +713,15 @@ plotTranscripts <- function(chrom, chromstart = NULL, chromend = NULL, ) } + ## Draw user-prioritized labels first so they win overlap checks + if (!is.null(transcriptsInternal$labelPriority)) { + priority <- label %in% + transcriptsInternal$labelPriority + labelOrder <- order(!priority) + transcriptNames <- transcriptNames[labelOrder, , drop = FALSE] + label <- label[labelOrder] + } + ## Get which names aren't cutoff checkedLabels <- apply(data.frame( "label" = label, diff --git a/R/plotgardener.R b/R/plotgardener.R index 948c3aefd..1e6af0270 100644 --- a/R/plotgardener.R +++ b/R/plotgardener.R @@ -37,11 +37,13 @@ #' @docType package #' @name plotgardener #' @useDynLib plotgardener +#' @importFrom grDevices as.raster #' @importFrom grDevices colorRampPalette #' @importFrom grDevices dev.size #' @importFrom curl has_internet #' @importFrom methods hasArg #' @importFrom methods is +#' @importFrom stats aggregate #' @importFrom stats na.omit #' @importFrom utils str #' @importFrom Rcpp sourceCpp diff --git a/R/readCool.R b/R/readCool.R index f73350fee..c572d7b90 100755 --- a/R/readCool.R +++ b/R/readCool.R @@ -23,26 +23,24 @@ lvl1contents <- h5ls(file, recursive = 1) expectedContents <- c("bins", "chroms", "indexes", "pixels") + rootNames <- unique(lvl1contents$name) - ## Check if it is mcool or cool - if (nrow(lvl1contents) == 1){ - ## mcool file has 1 row-resolutions - + ## Check if it is mcool or cool. An mcool file has a root-level + ## `resolutions` group; it can contain additional root groups, so do not + ## rely on the number of root rows. + if ("resolutions" %in% rootNames){ ## Get deeper contents of mcool lvl2contents <- h5ls(file, recursive = 3) |> pull(name) |> unique() ## Check for expected datasets and resolutions - - if (all(expectedContents %in% lvl2contents) & - lvl1contents$name == "resolutions"){ + if (all(expectedContents %in% lvl2contents)){ return(".mcool") - } - + } } else { ## check that cool file contains expected datasets - if (all(expectedContents %in% lvl1contents$name)){ + if (all(expectedContents %in% rootNames)){ return(".cool") } } @@ -92,15 +90,20 @@ readCoolBpResolutions <- function(file){ #' @author Sarah Parker, Nicole Kramer #' #' @details -#' The "BALANCE" normalization refers to applying the pre-calculated matrix -#' balancing weights in the `weight` dataset of `file`, typically present -#' in files created using cooler. VC is vanilla coverage, -#' VC_SQRT is square root of vanilla coverage, -#' and KR is Knight-Ruiz normalization. +#' The `weight` column is the standard cooler balancing weight, typically +#' present in files created using `cooler balance`. +#' VC is vanilla coverage, VC_SQRT is square root of vanilla coverage, +#' and KR is Knight-Ruiz normalization. Other columns such as `sweight`, +#' `CNV`, or `obj_weight` are returned by their stored names. Use +#' `readCoolNorms()` to see the exact column names available in a file. +#' +#' Cooler weights are multiplicative: balanced counts are calculated as +#' \code{observed * weight1 * weight2}. Contacts involving bins with +#' non-finite weights are dropped; the bins remain in the coordinate space. #' #' Please note that if using a file from HiC-Pro, ICE normalizations will come #' from files stored in a separate folder, and thus will not contain any -#' normalizations explicitly called "ICE" or "BALANCE" since values are +#' normalizations explicitly called "ICE" or "weight" since values are #' included already normalized. This normalization can be specified as "NONE". #' #' @param file A character value specifying the path to the .(m)cool file @@ -118,9 +121,8 @@ readCoolNorms <- function(file, resolution = NULL){ readBpNorm <- function(resolutionPath, file){ bpNorm <- h5read(file, name = paste0(resolutionPath, "/bins")) |> names() - bpNorm <- bpNorm[!(bpNorm %in% c("chrom", "start", "end"))] |> - gsub("weight","BALANCE", x = _) |> # replace "weight" with "BALANCE" - c("NONE") # add "NONE" for raw counts + bpNorm <- bpNorm[!(bpNorm %in% c("chrom", "start", "end"))] + bpNorm <- unique(c(bpNorm, "NONE")) # add "NONE" for raw counts return(bpNorm) } @@ -235,6 +237,31 @@ readCoolChroms <- function(file, resolution = NULL){ } +#' Choose an available normalization from a .(m)cool file +#' +#' @param file Path to .(m)cool file +#' @param resolution Resolution to inspect +#' +#' @return A character value naming an available normalization. +.coolAutoNorm <- function(file, resolution = NULL){ + fileNorms <- readCoolNorms(file, resolution = resolution) + + if ("KR" %in% fileNorms){ + return("KR") + } + if ("weight" %in% fileNorms){ + return("weight") + } + if ("sweight" %in% fileNorms){ + return("sweight") + } + available <- setdiff(fileNorms, "NONE") + if (length(available) > 0){ + return(available[1]) + } + return("NONE") +} + #' Determine best resolution for size of region for .(m)cool files #' #' @param file Path to .(m)cool file @@ -313,6 +340,7 @@ readCoolChroms <- function(file, resolution = NULL){ .coolRegion <- function(file, chrom, resolution){ chromInfo <- readCoolChroms(file, resolution = resolution) + chrom <- .coolMatchChrom(chrom, chromInfo) chromLength <- chromInfo[chromInfo$name == chrom, "length"] return(list(1, chromLength)) @@ -326,7 +354,7 @@ readCoolChroms <- function(file, resolution = NULL){ #' @param binChunkSize Size of bin chunk, for comparison against the end of #' the bin chunk #' @param datasetPath Dataset path, for specifying resolution in .mcool file -#' @param end1bin Bin where end1 starts +#' @param endPixel Last pixel index to read (1-based, inclusive) #' @param start2bin Bin for chr2 starts #' @param end2bin Bin for end2 starts #' @@ -335,15 +363,12 @@ readCoolChroms <- function(file, resolution = NULL){ #' #' @importFrom rhdf5 h5read .pullBinChunks <- function(binChunk, file, bin_offsets, binChunkSize, - datasetPath, end1bin, + datasetPath, endPixel, start2bin, end2bin){ - binChunkEnd <- binChunk + binChunkSize - 1 + binChunkEnd <- min(binChunk + binChunkSize - 1, endPixel) - if (binChunkEnd > bin_offsets[end1bin+1]+1){ - binChunkEnd <- bin_offsets[end1bin+1]+1 - } - if (binChunkEnd > binChunk){ + if (binChunkEnd >= binChunk){ bin2s <- h5read(file, name = paste0(datasetPath,"/pixels/bin2_id"), index = list(binChunk:binChunkEnd)) @@ -358,8 +383,35 @@ readCoolChroms <- function(file, resolution = NULL){ } -#' Error checking function for .(m)cool files -#' +#' Match a user chromosome name to a chromosome name in a .(m)cool file +#' +#' @param chrom User-supplied chromosome name. +#' @param chromInfo Chromosome data frame from \code{readCoolChroms()}. +#' +#' @return The matching chromosome name, or \code{NULL} if no match is found. +.coolMatchChrom <- function(chrom, chromInfo){ + if (is.null(chrom) || length(chrom) == 0){ + return(NULL) + } + chrom <- as.character(chrom) + if (chrom %in% chromInfo$name){ + return(chrom) + } + + ## Accept `chr1` for files that use `1` and vice versa. + altChrom <- if (startsWith(chrom, "chr")){ + sub("^chr", "", chrom) + } else { + paste0("chr", chrom) + } + if (altChrom %in% chromInfo$name){ + return(altChrom) + } + + return(NULL) +} + + #' @param file Path to .(m)cool file #' @param chrom User-inputted chromosome #' @param chromstart User-inputted chromstart, can still be NULL at this point. @@ -393,7 +445,7 @@ readCoolChroms <- function(file, resolution = NULL){ ## Chroms chromInfo <- readCoolChroms(file, resolution = resolution) - if (!chrom %in% chromInfo$name){ + if (is.null(.coolMatchChrom(chrom, chromInfo))){ abort(c( glue("chrom={chrom} not found in {file}."), "i" = glue("Check file chromosome names with \\ @@ -406,7 +458,8 @@ readCoolChroms <- function(file, resolution = NULL){ ## Check that chromstart is in bounds if (!is.null(chromstart)){ - chromLength <- chromInfo[chromInfo$name == chrom, "length"] + fileChrom <- .coolMatchChrom(chrom, chromInfo) + chromLength <- chromInfo[chromInfo$name == fileChrom, "length"] if (chromstart < 0 | chromstart > chromLength){ abort(c(glue("chromstart must be between 0 and chromosome end."), "i" = "{chrom} length is {chromLength} bp.")) @@ -414,7 +467,7 @@ readCoolChroms <- function(file, resolution = NULL){ } if (!is.null(altchrom)){ - if (!altchrom %in% chromInfo$name){ + if (is.null(.coolMatchChrom(altchrom, chromInfo))){ abort(c( glue("altchrom={altchrom} not found in {file}."), "i" = glue("Check file chromosome names with \\ @@ -430,8 +483,10 @@ readCoolChroms <- function(file, resolution = NULL){ regionErrors(chromstart = altchromstart, chromend = altchromend) - altchromLength <- chromInfo[chromInfo$name == altchrom, "length"] - if (altchromstart < 0 | altchromstart > altchromLength){ + fileAltchrom <- .coolMatchChrom(altchrom, chromInfo) + altchromLength <- chromInfo[chromInfo$name == fileAltchrom, "length"] + if (!is.null(altchromstart) && + (altchromstart < 0 | altchromstart > altchromLength)){ abort(c(glue("altchromstart must be between 0 and alt chromosome end."), "i" = "{altchrom} length is {altchromLength} bp.")) } @@ -439,7 +494,8 @@ readCoolChroms <- function(file, resolution = NULL){ ## If giving same chrom and altchrom, need to specify ## chromstart/chromend and altchromstart/altchromend - if (chrom == altchrom) { + if (.coolMatchChrom(chrom, chromInfo) == + .coolMatchChrom(altchrom, chromInfo)) { if (is.null(chromstart) | is.null(chromend) | is.null(altchromstart) | @@ -493,9 +549,18 @@ readCoolChroms <- function(file, resolution = NULL){ #' the size of the region. #' @param zrange A numeric vector of length 2 specifying the range of #' interaction scores, where extreme values will be set to the max or min. -#' @param norm Character value specifying hic data normalization method. -#' This value must be found in the .(m)cool file. +#' @param norm Character value specifying the exact name of a column in the +#' `bins` group of the .(m)cool file (for example `"weight"`, `"sweight"`, +#' `"KR"`, or `"NONE"`). Use \code{readCoolNorms()} to see the actual column +#' names in a file. \code{"NONE"} returns raw counts; \code{"auto"} chooses +#' \code{"KR"} if available, then \code{"weight"}, then \code{"sweight"}, then +#' the first available weight, then \code{"NONE"}. #' Default value is \code{norm = "NONE"}. +#' @details +#' Cooler normalization weights are multiplicative: +#' \code{balanced[i, j] = observed[i, j] * weight[i] * weight[j]}. +#' Contacts involving bins with non-finite weights are dropped; the bins +#' themselves remain in the coordinate space. #' @param binChunkSize A numeric specifying the number of bin indices to read #' from a file for a given region at a given resolution. If the total amount of #' data is larger than the \code{binChunkSize}, data will be read in multiple @@ -573,6 +638,13 @@ readCool <- function(file, chrom, chromstart = NULL, chromend = NULL, ) } + if (identical(rcool$norm, "auto")) { + rcool$norm <- .coolAutoNorm( + file = rcool$file, + resolution = rcool$resolution + ) + } + # ========================================================================= # CATCH ERRORS # ========================================================================= @@ -587,6 +659,21 @@ readCool <- function(file, chrom, chromstart = NULL, chromend = NULL, resolution = rcool$resolution ) + # ========================================================================= + # FILE TYPE AND CHROMOSOME NAMES + # ========================================================================= + + fileType <- .checkCool(rcool$file) + chrInfo <- readCoolChroms(rcool$file, rcool$resolution) + + ## Match user chromosome names to the names used by the file. `.mcool` + ## files from some pipelines use `1` while plotgardener users often use + ## `chr1` (and vice versa). + rcool$chrom <- .coolMatchChrom(rcool$chrom, chrInfo) + if (!is.null(rcool$altchrom)){ + rcool$altchrom <- .coolMatchChrom(rcool$altchrom, chrInfo) + } + # ========================================================================= # SET REGION PARAMETERS # ========================================================================= @@ -614,8 +701,13 @@ readCool <- function(file, chrom, chromstart = NULL, chromend = NULL, if (rcool$chrom == rcool$altchrom) { + ## For same-chromosome off-diagonal regions, read the full + ## symmetric span on both coordinates. Otherwise bin1 spans the + ## full region while bin2 is restricted to the smaller region. rcool$chromstart <- min(rcool$chromstart, rcool$altchromstart) rcool$chromend <- max(rcool$chromend, rcool$altchromend) + rcool$altchromstart <- rcool$chromstart + rcool$altchromend <- rcool$chromend } } else { rcool$altchrom <- rcool$chrom @@ -627,8 +719,6 @@ readCool <- function(file, chrom, chromstart = NULL, chromend = NULL, # EXTRACT SPARSE UPPER TRIANGULAR COUNT MATRIX # ========================================================================= - fileType <- .checkCool(rcool$file) - chrInfo <- readCoolChroms(rcool$file, rcool$resolution) datasetPath <- "" if (fileType == ".mcool"){ datasetPath <- paste0("/resolutions/", as.integer(rcool$resolution)) @@ -636,112 +726,165 @@ readCool <- function(file, chrom, chromstart = NULL, chromend = NULL, ## Find bin IDs for both chrom locations ----------------------------------- ## adjust starts and ends to start of bins - + + outputChrom <- rcool$chrom + outputAltchrom <- rcool$altchrom + + ## Get vector of chromosome offsets + chrom_offsets <- h5read(rcool$file, + name = paste0(datasetPath, "/indexes/chrom_offset")) + + ## Cooler stores only the upper triangle, ordered by chromosome index. + ## When the requested `chrom` comes after `altchrom`, read the rectangle in + ## storage order and swap x/y back afterward. Without this, interchromosomal + ## queries in reverse chromosome order silently return zero pixels. + swappedChroms <- FALSE + if (rcool$chrom != rcool$altchrom) { + chr1Order <- chrom_offsets[chrInfo[chrInfo$name == rcool$chrom, + "index"]] + chr2Order <- chrom_offsets[chrInfo[chrInfo$name == rcool$altchrom, + "index"]] + if (chr1Order > chr2Order) { + swappedChroms <- TRUE + oldChrom <- rcool$chrom + oldStart <- rcool$chromstart + oldEnd <- rcool$chromend + rcool$chrom <- rcool$altchrom + rcool$chromstart <- rcool$altchromstart + rcool$chromend <- rcool$altchromend + rcool$altchrom <- oldChrom + rcool$altchromstart <- oldStart + rcool$altchromend <- oldEnd + } + } + start1 <- (rcool$chromstart %/% rcool$resolution) * rcool$resolution start2 <- (rcool$altchromstart %/% rcool$resolution) * rcool$resolution end1 <- (rcool$chromend %/% rcool$resolution) * rcool$resolution end2 <- (rcool$altchromend %/% rcool$resolution) * rcool$resolution - - ## Get vector of chromosome offsets - chrom_offsets <- h5read(rcool$file, - name = paste0(datasetPath, "/indexes/chrom_offset")) + + ## Find the bin containing a coordinate. `findInterval()` is robust to + ## regions that do not start exactly on a bin boundary. + findBin <- function(coord, starts, chromOffset){ + bin <- findInterval(coord, starts) + bin <- max(1L, min(bin, length(starts))) + return(as.integer(chromOffset + bin - 1)) + } ## find bin id for chr1:start1:end1 chr1indx <- chrInfo[chrInfo$name == rcool$chrom, "index"] - ## get start1 bin + ## get start1 and end1 bins chr1_starts <- h5read(rcool$file, name = paste0(datasetPath, "/bins/start"), index = list((chrom_offsets[chr1indx]+1): chrom_offsets[chr1indx+1])) - start1bin <- which(chr1_starts == start1) + chrom_offsets[chr1indx] - 1 - - ## get end1 bin (i.e. bin where end1 starts) - end1bin <- which(chr1_starts == end1) + chrom_offsets[chr1indx] - 1 + start1bin <- findBin(start1, chr1_starts, chrom_offsets[chr1indx]) + end1bin <- findBin(end1, chr1_starts, chrom_offsets[chr1indx]) + if (end1bin < start1bin){ + end1bin <- start1bin + } ## find bin id for chr2:start2:end2 chr2indx <- chrInfo[chrInfo$name == rcool$altchrom, "index"] - ## get start2 bin + ## get start2 and end2 bins chr2_starts <- h5read(rcool$file, name = paste0(datasetPath,"/bins/start"), index = list((chrom_offsets[chr2indx]+1): chrom_offsets[chr2indx+1])) - start2bin <- which(chr2_starts == start2) + chrom_offsets[chr2indx] - 1 - - ## get end2 bin - end2bin <- which(chr2_starts == end2) + chrom_offsets[chr2indx] - 1 + start2bin <- findBin(start2, chr2_starts, chrom_offsets[chr2indx]) + end2bin <- findBin(end2, chr2_starts, chrom_offsets[chr2indx]) + if (end2bin < start2bin){ + end2bin <- start2bin + } ## Extract counts and match locations -------------------------------------- - ## Get bin offsets for counts + ## Get bin offsets for counts. `bin_offsets` has length nbins + 1; the + ## pixels for bin `b` (0-based) are `bin_offsets[b + 1] + 1` through + ## `bin_offsets[b + 2]`. The old code stopped one bin early and dropped + ## most of the last bin's pixels. bin_offsets <- h5read(rcool$file, name = paste0(datasetPath,"/indexes/bin1_offset")) + firstPixel <- bin_offsets[start1bin + 1] + 1 + lastPixel <- bin_offsets[end1bin + 2] + ## Pull all bin2 ids for interactions with all bin1s between start1 and end1 - ## Read 5 million indices at a time for more efficient calling - allBin1s <- (bin_offsets[start1bin+1]+1):(bin_offsets[end1bin+1]+1) + ## Read `binChunkSize` indices at a time for more efficient calling + if (lastPixel >= firstPixel) { + if ((lastPixel - firstPixel + 1) > rcool$binChunkSize){ + binChunks <- seq(firstPixel, lastPixel, by = rcool$binChunkSize) + + count_idx <- na.omit(unlist(lapply(binChunks, .pullBinChunks, + file = rcool$file, + bin_offsets = bin_offsets, binChunkSize = rcool$binChunkSize, + datasetPath = datasetPath, endPixel = lastPixel, + start2bin = start2bin, end2bin = end2bin))) + } else { + bin2s <- h5read(rcool$file, + name = paste0(datasetPath,"/pixels/bin2_id"), + index = list(firstPixel:lastPixel)) + + ## Find indexes for interactions with all bin2s between start2 and end2 + count_idx <- which(bin2s %in% start2bin:end2bin) + + firstPixel - 1 + } + } else { + count_idx <- integer(0) + } - if (length(allBin1s) > rcool$binChunkSize){ - binChunks <- seq(bin_offsets[start1bin+1]+1, - bin_offsets[end1bin+1]+1, - binChunkSize) - + ## Pull out bin1 ids, bin2 ids, and counts for all interactions in slice + if (length(count_idx) > 0){ + bin1ids <- h5read(rcool$file, + name = paste0(datasetPath,"/pixels/bin1_id"), + index = list(count_idx)) - count_idx <- na.omit(unlist(lapply(binChunks, .pullBinChunks, - file = rcool$file, - bin_offsets = bin_offsets, binChunkSize = rcool$binChunkSize, - datasetPath = datasetPath, end1bin = end1bin, - start2bin = start2bin, end2bin = end2bin))) + bin2ids <- h5read(rcool$file, + name = paste0(datasetPath,"/pixels/bin2_id"), + index = list(count_idx)) + counts <- h5read(rcool$file, + name = paste0(datasetPath,"/pixels/count"), + index = list(count_idx)) |> + #defaults to integer, needs to be numeric to convert to NA correctly + as.numeric() } else { - bin2s <- h5read(rcool$file, - name = paste0(datasetPath,"/pixels/bin2_id"), - index = list(allBin1s)) - - ## Find indexes for interactions with all bin2s between start2 and end2 - count_idx <- which(bin2s %in% start2bin:end2bin) + - bin_offsets[start1bin+1] + bin1ids <- integer(0) + bin2ids <- integer(0) + counts <- numeric(0) } - ## Pull out bin1 ids, bin2 ids, and counts for all interactions in slice - bin1ids <- h5read(rcool$file, name = paste0(datasetPath,"/pixels/bin1_id"), - index = list(count_idx)) - - bin2ids <- h5read(rcool$file, name = paste0(datasetPath,"/pixels/bin2_id"), - index = list(count_idx)) - - counts <- h5read(rcool$file, name = paste0(datasetPath,"/pixels/count"), - index = list(count_idx)) |> - #defaults to integer, needs to be numeric to convert to NA correctly - as.numeric() - - ## Multiply by normalization factors, if applicable - if (rcool$norm == "BALANCE"){ - bin1norm <- h5read(rcool$file, - name = paste0(datasetPath,"/bins/weight"), - list(as.numeric(bin1ids+1))) - bin2norm <- h5read(rcool$file, - name = paste0(datasetPath,"/bins/weight"), - list(as.numeric(bin2ids+1))) - counts <- counts / (bin1norm * bin2norm) - } else if (rcool$norm != "NONE"){ - bin1norm <- h5read(rcool$file, - name = paste0(datasetPath,"/bins/", rcool$norm), - list(as.numeric(bin1ids+1))) - bin2norm <- h5read(rcool$file, - name = paste0(datasetPath,"/bins/", rcool$norm), - list(as.numeric(bin2ids+1))) - counts <- counts / (bin1norm * bin2norm) + ## Multiply by normalization factors, if applicable. Cooler weights are + ## multiplicative: balanced = observed * weight_i * weight_j. + if (rcool$norm != "NONE" && length(counts) > 0){ + weights <- h5read(rcool$file, + name = paste0(datasetPath,"/bins/", rcool$norm)) + bin1norm <- weights[as.numeric(bin1ids) + 1] + bin2norm <- weights[as.numeric(bin2ids) + 1] + counts <- counts * bin1norm * bin2norm + counts[!is.finite(counts)] <- NA_real_ } ## Get genomic locations for each bin id - xs <- h5read(rcool$file, - name = paste0(datasetPath,"/bins/start"), - index = list(as.numeric(bin1ids+1))) - ys <- h5read(rcool$file, - name = paste0(datasetPath,"/bins/start"), - index = list(as.numeric(bin2ids+1))) + if (length(count_idx) > 0){ + xs <- h5read(rcool$file, + name = paste0(datasetPath,"/bins/start"), + index = list(as.numeric(bin1ids+1))) + ys <- h5read(rcool$file, + name = paste0(datasetPath,"/bins/start"), + index = list(as.numeric(bin2ids+1))) + } else { + xs <- numeric(0) + ys <- numeric(0) + } + if (swappedChroms) { + tmp <- xs + xs <- ys + ys <- tmp + } + ## create sparse upper triangular matrix upper <- data.frame(x = xs, y = ys, counts = counts) @@ -754,13 +897,13 @@ readCool <- function(file, chrom, chromstart = NULL, chromend = NULL, # FORMAT DATA IN PROPER ORDER AND WITH LABELS # ========================================================================= - ## Rename columns based on chrom/altchrom - if (rcool$chrom == rcool$altchrom){ - colnames(upper) <- c(paste0(rcool$chrom, "_A"), - paste0(rcool$altchrom, "_B"), + ## Rename columns based on original chrom/altchrom + if (outputChrom == outputAltchrom){ + colnames(upper) <- c(paste0(outputChrom, "_A"), + paste0(outputAltchrom, "_B"), "counts") } else { - colnames(upper) <- c(rcool$chrom, rcool$altchrom, "counts") + colnames(upper) <- c(outputChrom, outputAltchrom, "counts") } # ========================================================================= diff --git a/R/readNeoGenes.R b/R/readNeoGenes.R new file mode 100644 index 000000000..246ba9ddd --- /dev/null +++ b/R/readNeoGenes.R @@ -0,0 +1,379 @@ +## Internal gene-annotation readers for plotNeoGenes(). +## +## The GTF/GFF path is intentionally separate from the renderer so that the +## expensive parse can be cached and reused across plots/samples. + +.neoGeneSessionCache <- new.env(parent = emptyenv()) + +.neoGeneRegions <- function(neo) { + GenomicRanges::GRanges( + seqnames = neo$fragments$chrom, + ranges = IRanges::IRanges( + start = neo$fragments$start, + end = neo$fragments$end + ) + ) +} + +.neoGeneRegionFrame <- function(neo) { + data.frame( + chrom = as.character(neo$fragments$chrom), + chrom_raw = as.character(neo$fragments$chrom_raw), + start = as.numeric(neo$fragments$start), + end = as.numeric(neo$fragments$end), + stringsAsFactors = FALSE + ) +} + +.neoGeneCacheKey <- function(file, regions, type, tags) { + info <- file.info(file) + key <- paste( + normalizePath(file, mustWork = FALSE), + ifelse(is.na(info$size), "", info$size), + ifelse(is.na(info$mtime), "", as.numeric(info$mtime)), + paste(regions$chrom, regions$chrom_raw, regions$start, regions$end, + sep = ":", collapse = ";"), + paste(type, collapse = ","), + paste(tags, collapse = ","), + sep = "|" + ) + if (requireNamespace("digest", quietly = TRUE)) { + return(digest::digest(key, algo = "xxhash64")) + } + key <- gsub("[^A-Za-z0-9._-]+", "_", key) + substr(key, 1, 180) +} + +.neoGeneCacheGet <- function(cache, key) { + if (is.null(cache)) { + return(NULL) + } + if (isTRUE(cache)) { + dir <- tools::R_user_dir("plotgardener", which = "cache") + } else { + dir <- cache + } + if (!dir.exists(dir)) { + dir.create(dir, recursive = TRUE, showWarnings = FALSE) + } + path <- file.path(dir, paste0("neo_genes_", key, ".rds")) + if (file.exists(path)) { + return(readRDS(path)) + } + NULL +} + +.neoGeneCacheSet <- function(cache, key, value) { + if (is.null(cache)) { + return(invisible(NULL)) + } + if (isTRUE(cache)) { + dir <- tools::R_user_dir("plotgardener", which = "cache") + } else { + dir <- cache + } + if (!dir.exists(dir)) { + dir.create(dir, recursive = TRUE, showWarnings = FALSE) + } + path <- file.path(dir, paste0("neo_genes_", key, ".rds")) + saveRDS(value, path) + invisible(path) +} + +.neoGeneSubsetRegions <- function(df, regions) { + if (nrow(df) == 0) { + return(df) + } + keep <- rep(FALSE, nrow(df)) + for (i in seq_len(nrow(regions))) { + keep <- keep | ( + (df$chrom == regions$chrom[i] | + df$chrom == regions$chrom_raw[i]) & + df$start <= regions$end[i] & + df$end >= regions$start[i] + ) + } + df[keep, , drop = FALSE] +} + +.neoGeneNormalize <- function(df, regions = NULL) { + if (is.null(df) || nrow(df) == 0) { + return(data.frame( + chrom = character(0), start = numeric(0), end = numeric(0), + strand = character(0), gene = character(0), + transcript = character(0), feature = character(0), + gene_type = character(0), stringsAsFactors = FALSE + )) + } + df <- as.data.frame(df, stringsAsFactors = FALSE) + + chromCol <- intersect(c("chrom", "seqid", "seqnames"), colnames(df))[1] + featureCol <- intersect(c("feature", "type"), colnames(df))[1] + geneCol <- intersect(c("gene", "gene_name", "name"), colnames(df))[1] + idCol <- intersect(c("gene_id", "geneId", "GENEID"), colnames(df))[1] + txCol <- intersect(c("transcript", "transcript_id", "TXNAME", "TXID"), + colnames(df))[1] + typeCol <- intersect(c("gene_type", "gene_biotype", "TXTYPE"), + colnames(df))[1] + + chrom <- if (!is.na(chromCol)) as.character(df[[chromCol]]) else NA_character_ + gene <- if (!is.na(geneCol)) as.character(df[[geneCol]]) else NA_character_ + if (!is.na(idCol)) { + ids <- as.character(df[[idCol]]) + gene[is.na(gene) | !nzchar(gene)] <- ids[is.na(gene) | !nzchar(gene)] + } + gene[is.na(gene) | !nzchar(gene)] <- paste0("gene", seq_len(nrow(df)))[ + is.na(gene) | !nzchar(gene) + ] + transcript <- if (!is.na(txCol)) as.character(df[[txCol]]) else gene + transcript[is.na(transcript) | !nzchar(transcript)] <- + gene[is.na(transcript) | !nzchar(transcript)] + + out <- data.frame( + chrom = chrom, + start = as.numeric(df$start), + end = as.numeric(df$end), + strand = if ("strand" %in% colnames(df)) { + as.character(df$strand) + } else { + "*" + }, + gene = gene, + transcript = transcript, + feature = if (!is.na(featureCol)) { + as.character(df[[featureCol]]) + } else { + "exon" + }, + gene_type = if (!is.na(typeCol)) { + as.character(df[[typeCol]]) + } else { + NA_character_ + }, + stringsAsFactors = FALSE + ) + out$strand[is.na(out$strand) | !nzchar(out$strand)] <- "*" + out <- out[!is.na(out$chrom) & !is.na(out$start) & !is.na(out$end), , + drop = FALSE] + + ## GENCODE carries gene_type on every row, but some GTF/GFF files only + ## put it on the gene rows. Fill it down by gene_id/gene name. + hasType <- !is.na(out$gene_type) & nzchar(as.character(out$gene_type)) + if (any(hasType) && any(!hasType)) { + typeMap <- tapply( + as.character(out$gene_type[hasType]), + out$gene[hasType], + function(x) x[1] + ) + fillIdx <- !hasType & out$gene %in% names(typeMap) + out$gene_type[fillIdx] <- unname(typeMap[out$gene[fillIdx]]) + } + + ## Drop duplicate feature rows (common in TxDb joins). + key <- paste(out$chrom, out$start, out$end, out$strand, out$gene, + out$transcript, out$feature, sep = "|") + out <- out[!duplicated(key), , drop = FALSE] + + if (!is.null(regions)) { + out <- .neoGeneSubsetRegions(out, regions) + } + out +} + +.neoGeneReadGFF <- function(file, regions, type, tags, reader) { + regionsGR <- GenomicRanges::GRanges( + seqnames = regions$chrom, + ranges = IRanges::IRanges(regions$start, regions$end) + ) + if (reader == "readGFF") { + if (!requireNamespace("rtracklayer", quietly = TRUE)) { + stop("`rtracklayer` is required to read GTF/GFF files.", + call. = FALSE) + } + ## `readGFF` applies the seqid/type filters during the native scan and + ## only materializes the requested columns/tags. It is much lighter + ## than import(..., which = regions), which parses the whole file into + ## a GRanges first. + df <- suppressWarnings(rtracklayer::readGFF( + file, + filter = list( + seqid = unique(c(regions$chrom, regions$chrom_raw)), + type = type + ), + columns = c("seqid", "start", "end", "strand", "type"), + tags = tags + )) + return(.neoGeneNormalize(df, regions)) + } + + if (reader == "tabix") { + if (!requireNamespace("Rsamtools", quietly = TRUE) || + !requireNamespace("rtracklayer", quietly = TRUE)) { + stop("`Rsamtools` and `rtracklayer` are required for the tabix ", + "reader.", call. = FALSE) + } + if (!file.exists(paste0(file, ".tbi"))) { + stop("Tabix index not found: ", paste0(file, ".tbi"), + call. = FALSE) + } + format <- if (grepl("\\.gff3?(\\.gz)?$", file, ignore.case = TRUE)) { + "GFF3" + } else { + "GTF" + } + tbx <- Rsamtools::TabixFile(file) + present <- Rsamtools::seqnamesTabix(tbx) + queryGR <- regionsGR[ + as.character(GenomicRanges::seqnames(regionsGR)) %in% present + ] + if (length(queryGR) == 0) { + return(.neoGeneNormalize(NULL)) + } + gr <- suppressWarnings(rtracklayer::import( + tbx, format = format, which = queryGR, + feature.type = type + )) + return(.neoGeneNormalize(as.data.frame(gr), regions)) + } + + ## Fallback: the original full-file import. + if (!requireNamespace("rtracklayer", quietly = TRUE)) { + stop("`rtracklayer` is required to read GTF/GFF files.", + call. = FALSE) + } + gr <- suppressMessages(rtracklayer::import( + file, feature.type = type, which = regionsGR + )) + .neoGeneNormalize(as.data.frame(gr), regions) +} + +.readNeoGenesGFF <- function(file, neo, type, tags, + reader = c("auto", "readGFF", "import", + "tabix"), + cache = NULL) { + reader <- match.arg(reader) + regions <- .neoGeneRegionFrame(neo) + if (reader == "auto") { + if (file.exists(paste0(file, ".tbi")) && + requireNamespace("Rsamtools", quietly = TRUE)) { + reader <- "tabix" + } else if (requireNamespace("rtracklayer", quietly = TRUE)) { + reader <- "readGFF" + } else { + reader <- "import" + } + } + + key <- .neoGeneCacheKey(file, regions, type, tags) + cached <- .neoGeneCacheGet(cache, key) + if (!is.null(cached)) { + return(cached) + } + sessionKey <- paste(reader, key, sep = "|") + if (exists(sessionKey, envir = .neoGeneSessionCache, inherits = FALSE)) { + cached <- get(sessionKey, envir = .neoGeneSessionCache, + inherits = FALSE) + .neoGeneCacheSet(cache, key, cached) + return(cached) + } + + df <- .neoGeneReadGFF(file, regions, type, tags, reader) + assign(sessionKey, df, envir = .neoGeneSessionCache) + .neoGeneCacheSet(cache, key, df) + df +} + +.readNeoGenesTxDb <- function(txdb, orgdb, neo, assemblyName, + gene.id.column = NULL, + display.column = NULL) { + if (!requireNamespace("GenomicFeatures", quietly = TRUE) || + !requireNamespace("AnnotationDbi", quietly = TRUE)) { + stop("`GenomicFeatures` and `AnnotationDbi` are required for TxDb ", + "gene annotation.", call. = FALSE) + } + if (is.null(display.column)) { + display.column <- if (is.null(orgdb)) "GENEID" else "SYMBOL" + } + if (is.null(gene.id.column)) { + gene.id.column <- if (identical(display.column, "GENEID")) { + "GENEID" + } else { + "ENTREZID" + } + } + asm <- assembly( + Genome = assemblyName, + TxDb = txdb, + OrgDb = if (is.null(orgdb)) NA else orgdb, + gene.id.column = gene.id.column, + display.column = display.column + ) + regions <- .neoGeneRegionFrame(neo) + chroms <- unique(regions$chrom) + parts <- lapply(chroms, function(ch) { + rr <- regions[regions$chrom == ch, , drop = FALSE] + getExons( + assembly = asm, + chromosome = ch, + start = min(rr$start), + stop = max(rr$end) + ) + }) + parts <- Filter(function(x) !is.null(x) && nrow(x) > 0, parts) + if (length(parts) == 0) { + return(.neoGeneNormalize(NULL)) + } + d <- do.call(rbind, parts) + + displayCol <- if (display.column %in% colnames(d)) { + display.column + } else if ("SYMBOL" %in% colnames(d)) { + "SYMBOL" + } else { + "GENEID" + } + gene <- as.character(d[[displayCol]]) + gene[is.na(gene) | !nzchar(gene)] <- as.character(d$GENEID)[ + is.na(gene) | !nzchar(gene) + ] + transcript <- if ("TXNAME" %in% colnames(d)) { + as.character(d$TXNAME) + } else { + as.character(d$TXID) + } + transcript[is.na(transcript) | !nzchar(transcript)] <- + gene[is.na(transcript) | !nzchar(transcript)] + + exons <- data.frame( + chrom = as.character(d$TXCHROM), + start = as.numeric(d$EXONSTART), + end = as.numeric(d$EXONEND), + strand = as.character(d$TXSTRAND), + gene = gene, + transcript = transcript, + feature = "exon", + gene_type = if ("TXTYPE" %in% colnames(d)) { + as.character(d$TXTYPE) + } else { + NA_character_ + }, + stringsAsFactors = FALSE + ) + + if (all(c("CDSSTART", "CDSEND") %in% colnames(d))) { + cdsKeep <- !is.na(d$CDSSTART) & !is.na(d$CDSEND) + cds <- data.frame( + chrom = as.character(d$TXCHROM)[cdsKeep], + start = as.numeric(d$CDSSTART)[cdsKeep], + end = as.numeric(d$CDSEND)[cdsKeep], + strand = as.character(d$TXSTRAND)[cdsKeep], + gene = gene[cdsKeep], + transcript = transcript[cdsKeep], + feature = "CDS", + gene_type = exons$gene_type[cdsKeep], + stringsAsFactors = FALSE + ) + exons <- rbind(exons, cds) + } + .neoGeneNormalize(exons, regions) +} diff --git a/R/readNeoHic.R b/R/readNeoHic.R new file mode 100644 index 000000000..dcde5b917 --- /dev/null +++ b/R/readNeoHic.R @@ -0,0 +1,548 @@ +#' @keywords internal +.neoFileType <- function(file) { + ext <- tolower(tools::file_ext(file)) + if (ext == "hic") { + "hic" + } else if (ext %in% c("cool", "mcool")) { + "cool" + } else { + stop("`data` must be a .hic, .cool, or .mcool file.", call. = FALSE) + } +} + +#' @keywords internal +.neoFileResolutions <- function(file, fileType) { + if (fileType == "hic") { + strawr::readHicBpResolutions(file) + } else { + readCoolBpResolutions(file) + } +} + +#' @keywords internal +.neoAutoResolution <- function(file, fileType, neo, targetBins = 1000) { + resolutions <- .neoFileResolutions(file, fileType) + target <- neo$total_length / targetBins + resolutions[which.min(abs(resolutions - target))] +} + +#' @keywords internal +.neoMapPosition <- function(position, fragments, resolution, chrom = NULL) { + candidates <- fragments + if (!is.null(chrom)) { + candidates <- candidates[candidates$chrom == chrom, , drop = FALSE] + } + if (nrow(candidates) == 0) { + return(list(neo = NA_real_, fragment = NA_integer_)) + } + + exact <- which(position >= candidates$start & position < candidates$end) + if (length(exact) == 0) { + return(list(neo = NA_real_, fragment = NA_integer_)) + } + exact <- exact[1] + + frag <- candidates[exact, ] + if (frag$flipped) { + neoPosition <- frag$offset + (frag$end - (position + resolution)) + } else { + neoPosition <- frag$offset + (position - frag$start) + } + + neoPosition <- max(frag$offset, + min(neoPosition, frag$offset + frag$length - resolution)) + list(neo = neoPosition, fragment = frag$id) +} + +#' @keywords internal +.neoReadPair <- function(data, fileType, fi, fj, resolution, norm, matrix, + assembly) { + if (fileType == "hic") { + start1 <- max(1, fi$start) + end1 <- max(start1 + 1, fi$end) + start2 <- max(1, fj$start) + end2 <- max(start2 + 1, fj$end) + + if (fi$id == fj$id) { + readHic( + file = data, chrom = fi$chrom, + chromstart = start1, chromend = end1, + resolution = resolution, norm = norm, matrix = matrix, + assembly = assembly, zrange = NULL, quiet = TRUE + ) + } else { + readHic( + file = data, chrom = fi$chrom, + chromstart = start1, chromend = end1, + altchrom = fj$chrom, + altchromstart = start2, altchromend = end2, + resolution = resolution, norm = norm, matrix = matrix, + assembly = assembly, zrange = NULL, quiet = TRUE + ) + } + } else { + start1 <- max(0, fi$start) + end1 <- max(start1 + 1, fi$end) + start2 <- max(0, fj$start) + end2 <- max(start2 + 1, fj$end) + + if (fi$id == fj$id) { + readCool( + file = data, chrom = fi$chrom, + chromstart = start1, chromend = end1, + resolution = resolution, norm = norm, + zrange = NULL, quiet = TRUE + ) + } else { + readCool( + file = data, chrom = fi$chrom, + chromstart = start1, chromend = end1, + altchrom = fj$chrom, + altchromstart = start2, altchromend = end2, + resolution = resolution, norm = norm, + zrange = NULL, quiet = TRUE + ) + } + } +} + +#' @keywords internal +.neoEstimateResolution <- function(data) { + starts <- sort(unique(c(data$start1, data$start2))) + diffs <- diff(starts) + diffs <- diffs[diffs > 0] + if (length(diffs) == 0) { + stop("Cannot estimate `resolution` from the data frame; supply a ", + "numeric resolution.", call. = FALSE) + } + as.numeric(min(diffs)) +} + +#' @keywords internal +.neoNormalizePairData <- function(data) { + data <- as.data.frame(data, stringsAsFactors = FALSE) + cn <- colnames(data) + + if (all(c("chrom1", "start1", "chrom2", "start2") %in% cn)) { + countCol <- if ("counts" %in% cn) { + "counts" + } else if ("count" %in% cn) { + "count" + } else { + stop("`data` must contain a `counts` or `count` column.", + call. = FALSE) + } + out <- data.frame( + chrom1 = as.character(data$chrom1), + start1 = as.numeric(data$start1), + chrom2 = as.character(data$chrom2), + start2 = as.numeric(data$start2), + counts = as.numeric(data[[countCol]]), + stringsAsFactors = FALSE + ) + } else if (all(c("chrom", "start1", "start2") %in% cn)) { + countCol <- if ("counts" %in% cn) { + "counts" + } else if ("count" %in% cn) { + "count" + } else { + stop("`data` must contain a `counts` or `count` column.", + call. = FALSE) + } + out <- data.frame( + chrom1 = as.character(data$chrom), + start1 = as.numeric(data$start1), + chrom2 = as.character(data$chrom), + start2 = as.numeric(data$start2), + counts = as.numeric(data[[countCol]]), + stringsAsFactors = FALSE + ) + } else if (ncol(data) >= 5 && + is.character(data[[1]]) && is.numeric(data[[2]]) && + is.character(data[[3]]) && is.numeric(data[[4]]) && + is.numeric(data[[5]])) { + ## Accept `readCool()`/`readHic()` interchromosomal-like output: + ## chrom1, start1, chrom2, start2, counts + out <- data.frame( + chrom1 = as.character(data[[1]]), + start1 = as.numeric(data[[2]]), + chrom2 = as.character(data[[3]]), + start2 = as.numeric(data[[4]]), + counts = as.numeric(data[[5]]), + stringsAsFactors = FALSE + ) + } else { + stop("`data` must be a data frame with columns ", + "`chrom1`, `start1`, `chrom2`, `start2`, `counts`, or ", + "`chrom`, `start1`, `start2`, `counts`.", call. = FALSE) + } + + out +} + +#' @keywords internal +.neoMakeHic <- function(matrixDf, neo, resolution, norm, matrix, file, + zrange, quiet, pairCounts = NULL) { + if (!is.null(zrange)) { + matrixDf <- scale_data(upper = matrixDf, zrange = zrange) + } + + neoHic <- structure( + list( + matrix = matrixDf, + neo = neo, + resolution = resolution, + norm = norm, + matrix_type = matrix, + file = file, + pair_counts = pairCounts + ), + class = c("neoHic", "list") + ) + + if (!quiet) { + message("neoHic[", nrow(matrixDf), " pixels at ", + resolution, " bp]") + } + + neoHic +} + + +#' Reconstruct an SV-impacted contact matrix in neo-chromosome coordinates +#' +#' @param data Path to a `.hic`, `.cool`, or `.mcool` file, or a data frame +#' of precomputed genomic contacts with columns \code{chrom1}, \code{start1}, +#' \code{chrom2}, \code{start2}, and \code{counts}. A data frame with +#' \code{chrom}, \code{start1}, \code{start2}, and \code{counts} is also +#' accepted for intrachromosomal data. +#' @param neo A `neoAssembly` object from \code{readNeoAssembly()}, or a path +#' to an assembly file. If a path is supplied, \code{id} is required. +#' @param id Assembly ID when \code{neo} is an assembly file path. +#' @param resolution Resolution in basepairs, or \code{"auto"} to choose +#' a resolution close to 1000 bins across the neo-chromosome. For data frame +#' input, \code{"auto"} estimates the smallest positive spacing between bins. +#' @param norm Normalization to pass to \code{readHic()} or \code{readCool()}. +#' Default value is \code{norm = "NONE"}. +#' @param matrix Matrix type for `.hic` files. Default value is +#' \code{matrix = "observed"}. +#' @param zrange Optional numeric vector of length 2 used to clip the final +#' reconstructed counts. Default value is \code{zrange = NULL}. +#' @param assembly Genome assembly for `.hic` files and for reading an +#' assembly file path. Default value is \code{assembly = "hg38"}. +#' @param extend Basepairs to extend the first and last fragments when +#' \code{neo} is a file path. Default value is \code{extend = 0}. +#' @param prefix Prefix for chromosome names when \code{neo} is a file path. +#' Default value is \code{prefix = "chr"}. +#' @param quiet A logical indicating whether to print progress messages. +#' +#' @return A `neoHic` object: a list with \code{matrix} (a data frame of +#' \code{x}, \code{y}, \code{counts} in neo coordinates), \code{neo}, +#' \code{resolution}, \code{norm}, and \code{matrix_type}. +#' +#' @details +#' For file input, the reconstruction reads each fragment pair from the source +#' file and maps genomic bin starts onto the concatenated neo-chromosome. +#' Contacts are assigned only to the fragment pair being read, so pixels from +#' adjacent fragments are not double-counted. For data frame input, each row's +#' genomic coordinates are mapped to neo coordinates using the same rules. +#' +#' @examples +#' \dontrun{ +#' neo <- readNeoAssembly("HM1_merged.assemblies.txt", "C1", extend = 200000) +#' neoHic <- readNeoHic("HM1_merged.mcool", neo, resolution = 5000) +#' plotNeoHic(neoHic, type = "triangle") +#' +#' ## Or pass the assembly path and ID directly +#' neoHic2 <- readNeoHic( +#' "HM1_merged.mcool", +#' "HM1_merged.assemblies.txt", id = "C1", +#' extend = 200000, resolution = 5000 +#' ) +#' } +#' @export +readNeoHic <- function(data, neo, id = NULL, resolution = "auto", + norm = "NONE", matrix = "observed", zrange = NULL, + assembly = "hg38", extend = 0, prefix = "chr", + quiet = FALSE) { + + if (missing(data) || is.null(data)) { + stop("argument \"data\" is missing, with no default.", call. = FALSE) + } + if (is.character(neo)) { + if (is.null(id)) { + stop("`id` must be supplied when `neo` is an assembly file path.", + call. = FALSE) + } + neo <- readNeoAssembly( + file = neo, id = id, assembly = assembly, + extend = extend, prefix = prefix, quiet = quiet + ) + } + if (!inherits(neo, "neoAssembly")) { + stop("`neo` must be a `neoAssembly` object or an assembly file path.", + call. = FALSE) + } + + if (is.data.frame(data)) { + pairData <- .neoNormalizePairData(data) + if (identical(resolution, "auto")) { + resolution <- .neoEstimateResolution(pairData) + } + if (!is.numeric(resolution) || length(resolution) != 1 || + resolution <= 0) { + stop("`resolution` must be a positive number or \"auto\".", + call. = FALSE) + } + resolution <- as.numeric(resolution) + + fragments <- neo$fragments + mx <- lapply(seq_len(nrow(pairData)), function(k) { + .neoMapPosition(pairData$start1[k], fragments, + resolution = resolution, + chrom = pairData$chrom1[k]) + }) + my <- lapply(seq_len(nrow(pairData)), function(k) { + .neoMapPosition(pairData$start2[k], fragments, + resolution = resolution, + chrom = pairData$chrom2[k]) + }) + keep <- vapply(seq_len(nrow(pairData)), function(k) { + !is.na(mx[[k]]$fragment) && !is.na(my[[k]]$fragment) + }, logical(1)) + + if (!any(keep)) { + matrixDf <- data.frame( + x = numeric(0), y = numeric(0), counts = numeric(0) + ) + } else { + nx <- vapply(mx[keep], `[[`, numeric(1), "neo") + ny <- vapply(my[keep], `[[`, numeric(1), "neo") + matrixDf <- data.frame( + x = pmin(nx, ny), + y = pmax(nx, ny), + counts = pairData$counts[keep], + stringsAsFactors = FALSE + ) + matrixDf <- aggregate(counts ~ x + y, data = matrixDf, FUN = sum) + } + + return(.neoMakeHic( + matrixDf = matrixDf, neo = neo, resolution = resolution, + norm = norm, matrix = matrix, file = NA_character_, + zrange = zrange, quiet = quiet + )) + } + + if (!is.character(data) || length(data) != 1) { + stop("`data` must be a file path or data frame.", call. = FALSE) + } + if (!file.exists(data)) { + stop("Data file does not exist: ", data, call. = FALSE) + } + + fileType <- .neoFileType(data) + if (identical(resolution, "auto")) { + resolution <- .neoAutoResolution( + file = data, fileType = fileType, neo = neo + ) + } + if (!is.numeric(resolution) || length(resolution) != 1 || + resolution <= 0) { + stop("`resolution` must be a positive number or \"auto\".", + call. = FALSE) + } + resolution <- as.numeric(resolution) + + fragments <- neo$fragments + nFragments <- nrow(fragments) + parts <- list() + pairStats <- list() + + for (i in seq_len(nFragments)) { + for (j in i:nFragments) { + fi <- fragments[i, ] + fj <- fragments[j, ] + if (!quiet) { + message("neo pair ", i, "-", j, ": ", + fi$chrom, ":", fi$start, "-", fi$end, " / ", + fj$chrom, ":", fj$start, "-", fj$end) + } + + pairData <- .neoReadPair( + data = data, fileType = fileType, fi = fi, fj = fj, + resolution = resolution, norm = norm, matrix = matrix, + assembly = assembly + ) + + if (nrow(pairData) == 0) { + pairStats[[length(pairStats) + 1]] <- data.frame( + fragment1 = i, fragment2 = j, + pixels = 0L, counts = 0, stringsAsFactors = FALSE + ) + next + } + + x <- as.numeric(pairData[[1]]) + y <- as.numeric(pairData[[2]]) + counts <- as.numeric(pairData[[3]]) + + mx <- lapply(x, .neoMapPosition, + fragments = fragments, resolution = resolution, + chrom = fi$chrom) + my <- lapply(y, .neoMapPosition, + fragments = fragments, resolution = resolution, + chrom = fj$chrom) + + keep <- vapply(seq_along(x), function(k) { + fx <- mx[[k]]$fragment + fy <- my[[k]]$fragment + if (is.na(fx) || is.na(fy)) { + FALSE + } else if (i == j) { + fx == i && fy == i + } else { + (fx == i && fy == j) || (fx == j && fy == i) + } + }, logical(1)) + + if (!any(keep)) { + pairStats[[length(pairStats) + 1]] <- data.frame( + fragment1 = i, fragment2 = j, + pixels = 0L, counts = 0, stringsAsFactors = FALSE + ) + next + } + + nx <- vapply(mx[keep], `[[`, numeric(1), "neo") + ny <- vapply(my[keep], `[[`, numeric(1), "neo") + + parts[[length(parts) + 1]] <- data.frame( + x = pmin(nx, ny), + y = pmax(nx, ny), + counts = counts[keep], + stringsAsFactors = FALSE + ) + pairStats[[length(pairStats) + 1]] <- data.frame( + fragment1 = i, fragment2 = j, + pixels = sum(keep), counts = sum(counts[keep]), + stringsAsFactors = FALSE + ) + } + } + + if (length(parts) == 0) { + matrixDf <- data.frame( + x = numeric(0), y = numeric(0), counts = numeric(0) + ) + } else { + matrixDf <- do.call(rbind, parts) + matrixDf <- aggregate(counts ~ x + y, data = matrixDf, FUN = sum) + } + + pairCounts <- if (length(pairStats) > 0) { + do.call(rbind, pairStats) + } else { + NULL + } + if (!quiet && !is.null(pairCounts)) { + emptyInter <- pairCounts$fragment1 != pairCounts$fragment2 & + pairCounts$pixels == 0 + if (any(emptyInter)) { + warning( + "No inter-fragment contacts found for fragment pairs: ", + paste0(pairCounts$fragment1[emptyInter], "-", + pairCounts$fragment2[emptyInter], collapse = ", "), + ". The source Hi-C file may have no contacts in those ", + "fragment intervals.", call. = FALSE + ) + } + } + + .neoMakeHic( + matrixDf = matrixDf, neo = neo, resolution = resolution, + norm = norm, matrix = matrix, + file = normalizePath(data, mustWork = TRUE), + zrange = zrange, quiet = quiet, + pairCounts = pairCounts + ) +} + +#' @export +print.neoHic <- function(x, ...) { + cat("neoHic\n") + cat(" matrix:", nrow(x$matrix), "pixels\n") + cat(" resolution:", x$resolution, "bp\n") + cat(" norm:", x$norm, "\n") + cat(" neo length:", x$neo$total_length, "bp\n") + if (!is.null(x$pair_counts)) { + cat(" fragment-pair pixels:\n") + print(x$pair_counts, row.names = FALSE) + } + invisible(x) +} + +#' Plot a reconstructed neo-chromosome contact matrix +#' +#' @param neoHic A `neoHic` object from \code{readNeoHic()}. +#' @param type Hi-C plot type: \code{"triangle"}, \code{"square"}, or +#' \code{"rectangle"}. Default value is \code{type = "triangle"}. +#' @param flip Orientation. \code{"none"} or \code{FALSE} leaves the plot +#' unchanged, \code{"horizontal"} mirrors the x-axis so the opposite +#' chromosome is on the left, and \code{TRUE} retains the legacy vertical +#' triangle flip. Default value is \code{flip = "none"}. +#' @param ... Additional arguments passed to the corresponding +#' \code{plotHic*} function. +#' +#' @return The plot object returned by \code{plotHicTriangle()}, +#' \code{plotHicSquare()}, or \code{plotHicRectangle()}. +#' +#' @examples +#' \dontrun{ +#' neoHic <- readNeoHic("HM1_merged.mcool", neo, resolution = 5000) +#' plotNeoHic(neoHic, type = "square", x = 1, y = 1, width = 2, height = 2) +#' } +#' @export +plotNeoHic <- function(neoHic, type = c("triangle", "square", "rectangle"), + flip = c("none", "horizontal"), ...) { + if (!inherits(neoHic, "neoHic")) { + stop("`neoHic` must be a `neoHic` object.", call. = FALSE) + } + type <- match.arg(type) + flip <- flip[1] + verticalFlip <- FALSE + if (is.logical(flip)) { + verticalFlip <- isTRUE(flip) + flip <- "none" + } else { + flip <- match.arg(flip, c("none", "horizontal")) + } + + args <- list( + data = neoHic$matrix, + chrom = "neo", + chromstart = 0, + chromend = neoHic$neo$total_length, + resolution = neoHic$resolution, + ... + ) + if (verticalFlip) { + args$flip <- TRUE + } + if (identical(flip, "horizontal")) { + if (type == "rectangle") { + warning("Horizontal flipping is currently supported for triangle ", + "and square neo-Hi-C plots.", call. = FALSE) + } else { + args$xaxisDir <- "decrease" + } + } + + fun <- switch(type, + triangle = plotHicTriangle, + square = plotHicSquare, + rectangle = plotHicRectangle + ) + + do.call(fun, args) +} diff --git a/R/readingFunctions.R b/R/readingFunctions.R index 3dcf006a5..afd5e053b 100644 --- a/R/readingFunctions.R +++ b/R/readingFunctions.R @@ -46,8 +46,14 @@ read_rangeData <- function(data, assembly, chrom = NULL, if (type == "range"){ ## Rename columns if necessary - colnames(data)[seq(1, 3)] <- c("chrom", "start", "end") - + if (!all(c("chrom", "start", "end") %in% colnames(data))) { + colnames(data)[seq(1, 3)] <- c("chrom", "start", "end") + } + ## Put the expected columns first without changing other columns + data <- data[, c("chrom", "start", "end", + setdiff(colnames(data), + c("chrom", "start", "end"))), drop = FALSE] + ## Check column input types columnClasses <- list("start" = TRUE, "end" = TRUE) if (!is(data[, "start"], "integer") & @@ -72,8 +78,13 @@ read_rangeData <- function(data, assembly, chrom = NULL, } else if (type == "GWAS") { - ## Rename chrom and position columns - colnames(data)[seq(1, 2)] <- c("chrom", "pos") + ## Rename chrom and position columns if necessary + if (!all(c("chrom", "pos") %in% colnames(data))) { + colnames(data)[seq(1, 2)] <- c("chrom", "pos") + } + data <- data[, c("chrom", "pos", + setdiff(colnames(data), + c("chrom", "pos"))), drop = FALSE] ## column data types will be checked in plotManhattan errorchecks } diff --git a/man/annoNeoDomains.Rd b/man/annoNeoDomains.Rd new file mode 100644 index 000000000..1ccd3b0f8 --- /dev/null +++ b/man/annoNeoDomains.Rd @@ -0,0 +1,67 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/plotNeo.R +\name{annoNeoDomains} +\alias{annoNeoDomains} +\title{This mirrors the visual convention used by the neo-triangle examples: +a solid domain outline around the full neo-chromosome and dotted domain +outlines at each internal fragment seam.} +\usage{ +annoNeoDomains( + plot, + neo, + outer = TRUE, + seams = TRUE, + linecolor = "black", + lwd = 0.5, + lty = 1, + seam.color = NULL, + seam.lwd = NULL, + seam.lty = 2, + ... +) +} +\arguments{ +\item{plot}{A Hi-C plot object from \code{plotHicSquare()}, +\code{plotHicTriangle()}, or \code{plotHicRectangle()}.} + +\item{neo}{A `neoAssembly` object.} + +\item{outer}{Logical value indicating whether to draw the outer +neo-chromosome domain outline. Default value is \code{outer = TRUE}.} + +\item{seams}{Logical value indicating whether to draw internal fragment +seams. Default value is \code{seams = TRUE}.} + +\item{linecolor}{Domain line color. Default value is +\code{linecolor = "black"}.} + +\item{lwd}{Domain line width. Default value is \code{lwd = 0.5}.} + +\item{lty}{Outer domain line type. Default value is \code{lty = 1}.} + +\item{seam.color}{Seam line color. Defaults to \code{linecolor}.} + +\item{seam.lwd}{Seam line width. Defaults to \code{lwd}.} + +\item{seam.lty}{Seam line type. Default value is \code{seam.lty = 2} +(dotted).} + +\item{...}{Additional arguments passed to \code{annoDomains()}.} +} +\value{ +Invisibly returns a list with \code{outer} and \code{seams} +\code{annoDomains} objects. +} +\description{ +This mirrors the visual convention used by the neo-triangle examples: +a solid domain outline around the full neo-chromosome and dotted domain +outlines at each internal fragment seam. +} +\examples{ +\dontrun{ +neoHic <- readNeoHic("HM1_merged.mcool", neo, resolution = 5000) +h <- plotNeoHic(neoHic, type = "triangle", x = 1, y = 1, + width = 2, height = 1) +annoNeoDomains(h, neo) +} +} diff --git a/man/annoNeoFragmentLabels.Rd b/man/annoNeoFragmentLabels.Rd new file mode 100644 index 000000000..fb1e1bc47 --- /dev/null +++ b/man/annoNeoFragmentLabels.Rd @@ -0,0 +1,120 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/plotNeo.R +\name{annoNeoFragmentLabels} +\alias{annoNeoFragmentLabels} +\title{Add flexible labels to an SV neo-chromosome assembly} +\usage{ +annoNeoFragmentLabels( + neo, + x, + y, + width, + height = 0, + just = c("left", "top"), + default.units = "inches", + labels = TRUE, + label.style = "chrom", + label.fontsize = 7, + label.fontcolor = "black", + label.colors = NULL, + label.fontfamily = "", + label.fontface = 1, + label.rot = 0, + label.position = "center", + label.offset = 0.1, + show.inversion = FALSE, + inversion.suffix = " (inv)", + inversion.color = "red", + params = NULL, + ... +) +} +\arguments{ +\item{neo}{A `neoAssembly` object.} + +\item{x}{A numeric or unit object specifying the label row x-location.} + +\item{y}{A numeric or unit object specifying the label row y-location.} + +\item{width}{A numeric or unit object specifying the label row width.} + +\item{height}{A numeric or unit object specifying the label row height. +Default value is \code{height = 0}.} + +\item{just}{Justification of the label row relative to (x, y). +Default value is \code{just = c("left", "top")}.} + +\item{default.units}{Default units for numeric \code{x}, \code{y}, +\code{width}, and \code{height}. Default value is +\code{default.units = "inches"}.} + +\item{labels}{Logical value or character vector of labels. +If \code{TRUE}, labels are generated from \code{label.style}. +Default value is \code{labels = TRUE}.} + +\item{label.style}{Label style when \code{labels = TRUE}: \code{"chrom"} +(chromosome name), \code{"coordinate"} (chromosome and Mb coordinates), or +\code{"fragment"} (fragment number). Default value is +\code{label.style = "chrom"}.} + +\item{label.fontsize}{Label font size. Default value is +\code{label.fontsize = 7}.} + +\item{label.fontcolor}{Label color. Can be a vector recycled across +fragments. Default value is \code{label.fontcolor = "black"}.} + +\item{label.colors}{Optional explicit per-fragment colors. Overrides +\code{label.fontcolor} and inversion coloring.} + +\item{label.fontfamily}{Label font family. Default value is +\code{label.fontfamily = ""}.} + +\item{label.fontface}{Label font face. Default value is +\code{label.fontface = 1}.} + +\item{label.rot}{Label rotation in degrees. Default value is +\code{label.rot = 0}.} + +\item{label.position}{Label position relative to the fragment row: +\code{"center"}, \code{"above"}, or \code{"below"}. +Default value is \code{label.position = "center"}.} + +\item{label.offset}{Vertical offset in page units for \code{"above"} or +\code{"below"} positions. Default value is \code{label.offset = 0.1}.} + +\item{show.inversion}{Logical value indicating whether flipped fragments +should be marked. Default value is \code{show.inversion = FALSE}.} + +\item{inversion.suffix}{Suffix appended to flipped-fragment labels. +Default value is \code{inversion.suffix = " (inv)"}.} + +\item{inversion.color}{Color for flipped-fragment labels. Default value is +\code{inversion.color = "red"}.} + +\item{params}{An optional \link[plotgardener]{pgParams} object.} + +\item{...}{Additional arguments passed to \code{plotText()}.} +} +\value{ +Invisibly returns a list of \code{plotText()} objects. +} +\description{ +This is a label-only companion to \code{plotNeoAssembly()}. It is useful +when fragment labels need custom y-offsets, gaps, fonts, rotation, or +inversion highlighting without adding more arguments to the backbone +function. +} +\examples{ +\dontrun{ +plotNeoAssembly(neo, x = 1, y = 3, width = 3, height = 0.15, + labels = FALSE) +annoNeoFragmentLabels( + neo, x = 1, y = 3.25, width = 3, + label.style = "coordinate", + label.position = "below", + label.offset = 0.05, + label.fontface = "italic", + show.inversion = TRUE +) +} +} diff --git a/man/annoXaxis.Rd b/man/annoXaxis.Rd index 129ddfc23..e083edb06 100644 --- a/man/annoXaxis.Rd +++ b/man/annoXaxis.Rd @@ -11,6 +11,14 @@ annoXaxis( main = TRUE, scipen = 999, axisLine = FALSE, + tcl = 0.25, + label.offset = 0.35, + axisLine.lwd = 0.5, + axisLine.col = NULL, + axisLine.lty = NULL, + tick.lwd = 0.5, + tick.col = NULL, + tick.lty = NULL, params = NULL, ... ) @@ -39,6 +47,25 @@ Default value is \code{scipen = 999}.} \item{axisLine}{A logical value indicating whether to show the axis line. Default value is \code{axisLine = FALSE}.} +\item{tcl}{Tick length in lines. Default value is \code{tcl = 0.25}.} + +\item{label.offset}{Label offset from the tick ends in lines. +Default value is \code{label.offset = 0.35}.} + +\item{axisLine.lwd}{Axis line width. Default value is +\code{axisLine.lwd = 0.5}.} + +\item{axisLine.col}{Axis line color.} + +\item{axisLine.lty}{Axis line type.} + +\item{tick.lwd}{Tick line width. Default value is +\code{tick.lwd = 0.5}.} + +\item{tick.col}{Tick line color.} + +\item{tick.lty}{Tick line type.} + \item{params}{An optional \link[plotgardener]{pgParams} object containing relevant function parameters.} diff --git a/man/annoYaxis.Rd b/man/annoYaxis.Rd index d6d84b4d3..29f68512f 100644 --- a/man/annoYaxis.Rd +++ b/man/annoYaxis.Rd @@ -11,6 +11,14 @@ annoYaxis( main = TRUE, scipen = 999, axisLine = FALSE, + tcl = 0.25, + label.offset = 0.35, + axisLine.lwd = 0.5, + axisLine.col = NULL, + axisLine.lty = NULL, + tick.lwd = 0.5, + tick.col = NULL, + tick.lty = NULL, params = NULL, ... ) @@ -39,6 +47,25 @@ Default value is \code{scipen = 999}.} \item{axisLine}{A logical value indicating whether to show the axis line. Default value is \code{axisLine = FALSE}.} +\item{tcl}{Tick length in lines. Default value is \code{tcl = 0.25}.} + +\item{label.offset}{Label offset from the tick ends in lines. +Default value is \code{label.offset = 0.35}.} + +\item{axisLine.lwd}{Axis line width. Default value is +\code{axisLine.lwd = 0.5}.} + +\item{axisLine.col}{Axis line color.} + +\item{axisLine.lty}{Axis line type.} + +\item{tick.lwd}{Tick line width. Default value is +\code{tick.lwd = 0.5}.} + +\item{tick.col}{Tick line color.} + +\item{tick.lty}{Tick line type.} + \item{params}{An optional \link[plotgardener]{pgParams} object containing relevant function parameters.} diff --git a/man/assembly.Rd b/man/assembly.Rd index bbefd46d5..b543862bc 100644 --- a/man/assembly.Rd +++ b/man/assembly.Rd @@ -17,7 +17,10 @@ assembly( \arguments{ \item{Genome}{String indicating the name of the genome assembly.} -\item{TxDb}{String of existing TxDb package name or a TxDb object.} +\item{TxDb}{String of existing TxDb package name, a TxDb object, or an +\link[ensembldb]{EnsDb} object. EnsDb objects are converted to a TxDb for +plotting; provide \code{OrgDb} and set \code{gene.id.column = "ENSEMBL"} +if gene symbols are desired.} \item{OrgDb}{String of the desired OrgDb package name.} @@ -48,6 +51,6 @@ newAssembly <- assembly( ) } \seealso{ -\link[GenomicFeatures]{TxDb}, \link[AnnotationDbi]{OrgDb-class}, -\link[BSgenome]{BSgenome} +\link[GenomicFeatures]{TxDb}, \link[ensembldb]{EnsDb}, +\link[AnnotationDbi]{OrgDb-class}, \link[BSgenome]{BSgenome} } diff --git a/man/dot-checkCool.Rd b/man/dot-checkCool.Rd index 227c146af..c28a836fb 100644 --- a/man/dot-checkCool.Rd +++ b/man/dot-checkCool.Rd @@ -9,13 +9,14 @@ \arguments{ \item{file}{Path to .(m)cool file} } +\value{ +A character string, either \code{".cool"} or \code{".mcool"}, + indicating the file type. Aborts with an error if the file is not a + valid .(m)cool file. +} \description{ Check for .(m)cool file and contents } \author{ Sarah Parker } - -\value{ -A character string, either \code{".cool"} or \code{".mcool"}, indicating the file type. Aborts with an error if the file is not a valid .(m)cool file. -} diff --git a/man/dot-coolAutoNorm.Rd b/man/dot-coolAutoNorm.Rd new file mode 100644 index 000000000..76e798d7e --- /dev/null +++ b/man/dot-coolAutoNorm.Rd @@ -0,0 +1,19 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/readCool.R +\name{.coolAutoNorm} +\alias{.coolAutoNorm} +\title{Choose an available normalization from a .(m)cool file} +\usage{ +.coolAutoNorm(file, resolution = NULL) +} +\arguments{ +\item{file}{Path to .(m)cool file} + +\item{resolution}{Resolution to inspect} +} +\value{ +A character value naming an available normalization. +} +\description{ +Choose an available normalization from a .(m)cool file +} diff --git a/man/dot-coolAutoResolution.Rd b/man/dot-coolAutoResolution.Rd index ac9d4fa49..cab38edfa 100644 --- a/man/dot-coolAutoResolution.Rd +++ b/man/dot-coolAutoResolution.Rd @@ -13,10 +13,10 @@ \item{chromend}{Chromend of region} } +\value{ +A numeric value specifying the automatically determined resolution + in base pairs. +} \description{ Determine best resolution for size of region for .(m)cool files } - -\value{ -A numeric value specifying the automatically determined resolution in base pairs. -} diff --git a/man/dot-coolMatchChrom.Rd b/man/dot-coolMatchChrom.Rd new file mode 100644 index 000000000..0b3efb5b9 --- /dev/null +++ b/man/dot-coolMatchChrom.Rd @@ -0,0 +1,19 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/readCool.R +\name{.coolMatchChrom} +\alias{.coolMatchChrom} +\title{Match a user chromosome name to a chromosome name in a .(m)cool file} +\usage{ +.coolMatchChrom(chrom, chromInfo) +} +\arguments{ +\item{chrom}{User-supplied chromosome name.} + +\item{chromInfo}{Chromosome data frame from \code{readCoolChroms()}.} +} +\value{ +The matching chromosome name, or \code{NULL} if no match is found. +} +\description{ +Match a user chromosome name to a chromosome name in a .(m)cool file +} diff --git a/man/dot-coolRegion.Rd b/man/dot-coolRegion.Rd index e4a0efb07..3b100170d 100644 --- a/man/dot-coolRegion.Rd +++ b/man/dot-coolRegion.Rd @@ -14,11 +14,11 @@ \item{resolution}{Resolution to read chromsome info from} } +\value{ +A list of length two containing the chromosome start position (1) + and the chromosome length. +} \description{ Add (alt)chromstart and (alt)chromend for NULL (alt)chrom region of .(m)cool files } - -\value{ -A list of length two containing the chromosome start position (1) and the chromosome length. -} diff --git a/man/dot-pullBinChunks.Rd b/man/dot-pullBinChunks.Rd index 530812d33..13436032d 100644 --- a/man/dot-pullBinChunks.Rd +++ b/man/dot-pullBinChunks.Rd @@ -10,7 +10,7 @@ bin_offsets, binChunkSize, datasetPath, - end1bin, + endPixel, start2bin, end2bin ) @@ -27,16 +27,16 @@ the bin chunk} \item{datasetPath}{Dataset path, for specifying resolution in .mcool file} -\item{end1bin}{Bin where end1 starts} +\item{endPixel}{Last pixel index to read (1-based, inclusive)} \item{start2bin}{Bin for chr2 starts} \item{end2bin}{Bin for end2 starts} } +\value{ +An integer vector of pixel indices corresponding to interactions + within the specified bin chunk, or \code{NA} if none are found. +} \description{ Read in data for a bin chunk } - -\value{ -An integer vector of pixel indices corresponding to interactions within the specified bin chunk, or \code{NA} if none are found. -} diff --git a/man/getNeoSignal.Rd b/man/getNeoSignal.Rd new file mode 100644 index 000000000..f60f981e6 --- /dev/null +++ b/man/getNeoSignal.Rd @@ -0,0 +1,46 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/neoSignal.R +\name{getNeoSignal} +\alias{getNeoSignal} +\title{Map a signal track onto neo-chromosome coordinates} +\usage{ +getNeoSignal( + data, + neo, + binSize = 1000, + fun = c("mean", "median", "sum", "max", "min"), + value.col = NULL, + chromstart = NULL, + chromend = NULL, + ... +) +} +\arguments{ +\item{data}{A bigWig path, `GRanges` object, or data frame with +`chrom`, `start`, `end`, and a signal column.} + +\item{neo}{A `neoAssembly` object.} + +\item{binSize}{Bin size in basepairs for the neo-coordinate output. Use +`NULL` to keep the input intervals. Default value is `1000`.} + +\item{fun}{Aggregation function for binning: `"mean"`, `"median"`, +`"sum"`, `"max"`, or `"min"`. Default value is `"mean"`.} + +\item{value.col}{Name of the signal column. If `NULL`, the function looks +for `"score"`, `"balanced"`, `"value"`, or the last numeric column.} + +\item{chromstart, chromend}{Optional neo-coordinate window. Only intervals +overlapping this window are returned.} + +\item{...}{Additional arguments passed to `readBigwig()`.} +} +\value{ +A data frame with `chrom`, `start`, `end`, and `score`. +} +\description{ +Maps bigWig, `GRanges`, or data-frame signal data through the +neo-chromosome topology and optionally bins it in neo coordinates. This +handles RNA-seq, ChIP-seq, and other genome-wide signal tracks in the same +way, including fragments that are inverted. +} diff --git a/man/getNeoV4C.Rd b/man/getNeoV4C.Rd new file mode 100644 index 000000000..572e54411 --- /dev/null +++ b/man/getNeoV4C.Rd @@ -0,0 +1,30 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/neoSignal.R +\name{getNeoV4C} +\alias{getNeoV4C} +\title{Map a virtual-4C table onto neo-chromosome coordinates} +\usage{ +getNeoV4C(file, neo, value.col = "balanced", binSize = NULL, fun = "mean", ...) +} +\arguments{ +\item{file}{Path to a virtual-4C TSV file.} + +\item{neo}{A `neoAssembly` object.} + +\item{value.col}{Signal column. Default value is `"balanced"`.} + +\item{binSize}{Optional bin size. Default value is `NULL`, which keeps the +table's own intervals.} + +\item{fun}{Aggregation function when `binSize` is supplied.} + +\item{...}{Additional arguments passed to `getNeoSignal()`.} +} +\value{ +A data frame with `chrom`, `start`, `end`, and `score`. +} +\description{ +Convenience wrapper around `getNeoSignal()` for cooltools virtual-4C TSV +files. The table is mapped through the neo topology and adjacent intervals +are clipped so they do not overlap. +} diff --git a/man/mapNeoFeatures.Rd b/man/mapNeoFeatures.Rd new file mode 100644 index 000000000..950fb9aaa --- /dev/null +++ b/man/mapNeoFeatures.Rd @@ -0,0 +1,33 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/neoAssembly.R +\name{mapNeoFeatures} +\alias{mapNeoFeatures} +\title{Map genomic features to neo-chromosome coordinates} +\usage{ +mapNeoFeatures(data, neo) +} +\arguments{ +\item{data}{A data frame with columns \code{chrom}, \code{start}, and +\code{end}, or a \link[GenomicRanges]{GRanges} object.} + +\item{neo}{A `neoAssembly` object from \code{readNeoAssembly()}.} +} +\value{ +A data frame with \code{chrom = "neo"}, neo-coordinate +\code{start}/\code{end}, and a \code{fragment} column. Features that span +multiple fragments are split across fragments. If a \code{strand} column is +present, it is flipped for reverse-complemented fragments. +} +\description{ +Map genomic features to neo-chromosome coordinates +} +\examples{ +\dontrun{ +neo <- readNeoAssembly("HM1_merged.assemblies.txt", "C1", extend = 200000) +features <- data.frame( + chrom = "chr12", start = 65822483, end = 65968291, + name = "HMGA2", strand = "+" +) +mapNeoFeatures(features, neo) +} +} diff --git a/man/pageExport.Rd b/man/pageExport.Rd new file mode 100644 index 000000000..a5aaa9d92 --- /dev/null +++ b/man/pageExport.Rd @@ -0,0 +1,59 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/pageExport.R +\name{pageExport} +\alias{pageExport} +\title{Export the current plotgardener page without calling dev.off()} +\usage{ +pageExport( + file, + width = NULL, + height = NULL, + units = NULL, + dpi = 300, + bg = "white", + guides = TRUE, + device = NULL, + ... +) +} +\arguments{ +\item{file}{Output file path. The device is inferred from the extension +(`.pdf`, `.png`, `.tiff`, `.jpeg`, or `.svg`).} + +\item{width}{Output width. Defaults to the current page width.} + +\item{height}{Output height. Defaults to the current page height.} + +\item{units}{Units for \code{width} and \code{height}. Defaults to the +current page units.} + +\item{dpi}{Resolution for raster devices. Default value is +\code{dpi = 300}.} + +\item{bg}{Background color for the output device. +Default value is \code{bg = "white"}.} + +\item{guides}{Logical value indicating whether to include page guides in +the export. Default value is \code{guides = TRUE}.} + +\item{device}{Optional device name. If \code{NULL}, inferred from +\code{file}.} + +\item{...}{Additional arguments passed to the graphics device.} +} +\value{ +Invisibly returns the output file path. +} +\description{ +Grab the current page and write it to a file using a new graphics device. +The device is opened and closed internally, so users do not need to call +\code{dev.off()}. +} +\examples{ +\dontrun{ +pageCreate(width = 3, height = 3, default.units = "inches") +plotRect(x = 0.5, y = 0.5, width = 2, height = 2, fill = "green") +pageExport("figure.pdf") +pageExport("figure.png", dpi = 300) +} +} diff --git a/man/pageGuideHide.Rd b/man/pageGuideHide.Rd index dec937292..084205afe 100644 --- a/man/pageGuideHide.Rd +++ b/man/pageGuideHide.Rd @@ -4,19 +4,20 @@ \alias{pageGuideHide} \title{Remove guides from a plotgardener page} \usage{ -pageGuideHide() +pageGuideHide(redraw = TRUE) +} +\arguments{ +\item{redraw}{Logical value indicating whether to redraw immediately on a +screen device. File devices defer the change to \code{pageExport()}. +Default value is \code{redraw = TRUE}.} } \value{ None. } \description{ -Remove guides from a plotgardener page -} -\note{ -Please note that due to the implementation of `grid` removal functions, -using `pageGuideHide` within a `pdf` call will result in the rendering of a -separate, new page with the plot guides removed. To avoid this artifact, -hide guides in the `pageCreate` function call with `showGuides = FALSE`. +Hides page guides without calling `grid.remove()` on the active device. +The hidden state is applied by \code{pageExport()} and \code{pageRedraw()}, +so exporting a PDF or PNG does not create a second page. } \examples{ ## Make a page @@ -25,4 +26,8 @@ pageCreate(width = 7, height = 4, default.units = "inches") ## Hide page guides pageGuideHide() +## Export with guides omitted +\dontrun{ +pageExport("figure.pdf") +} } diff --git a/man/pagePlotRemove.Rd b/man/pagePlotRemove.Rd index 4cb2af776..8d68382d6 100644 --- a/man/pagePlotRemove.Rd +++ b/man/pagePlotRemove.Rd @@ -4,17 +4,23 @@ \alias{pagePlotRemove} \title{Remove plotgardener plots and annotations} \usage{ -pagePlotRemove(plot) +pagePlotRemove(plot, redraw = TRUE) } \arguments{ \item{plot}{Plot object to be removed, defined by the output of a plotgardener plotting function.} + +\item{redraw}{Logical value indicating whether to redraw immediately on a +screen device. File devices defer the change to \code{pageExport()}. +Default value is \code{redraw = TRUE}.} } \value{ None. } \description{ -Remove plotgardener plots and annotations +Records a plot for deferred removal instead of calling `grid.remove()` on +the active device. The removal is applied by \code{pageExport()} or +\code{pageRedraw()}, avoiding extra pages in PDF output. } \examples{ ## Load Hi-C data diff --git a/man/pageRedraw.Rd b/man/pageRedraw.Rd new file mode 100644 index 000000000..25c5cdb16 --- /dev/null +++ b/man/pageRedraw.Rd @@ -0,0 +1,16 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/pageRedraw.R +\name{pageRedraw} +\alias{pageRedraw} +\title{Redraw the current plotgardener page} +\usage{ +pageRedraw() +} +\value{ +Invisibly returns the grabbed page grob. +} +\description{ +Redraw the current page after deferred guide hiding or plot removal. This +is primarily useful on screen devices; for file devices, use +\code{pageExport()}, which applies the deferred removals to a single page. +} diff --git a/man/plotGenes.Rd b/man/plotGenes.Rd index 40ceb4bb9..b83c0394f 100644 --- a/man/plotGenes.Rd +++ b/man/plotGenes.Rd @@ -13,6 +13,8 @@ plotGenes( fontcolor = c("#669fd9", "#abcc8e"), fill = c("#669fd9", "#abcc8e"), geneOrder = NULL, + labelClusters = FALSE, + labelClusterRot = 45, geneHighlights = NULL, geneBackground = "grey", strandLabels = TRUE, @@ -57,6 +59,14 @@ Default value is \code{fill = c("#669fd9", "#abcc8e")}.} \item{geneOrder}{An ordered character vector of gene names to prioritize when labeling genes.} +\item{labelClusters}{A logical value indicating whether to draw all gene +labels without overlap suppression. Useful for dense gene clusters; +labels may be rotated with \code{labelClusterRot}. +Default value is \code{labelClusters = FALSE}.} + +\item{labelClusterRot}{Rotation in degrees for labels when +\code{labelClusters = TRUE}. Default value is \code{labelClusterRot = 45}.} + \item{geneHighlights}{A two-column dataframe with a column named "gene" containing gene names as strings to highlight and a named column "color" containing corresponding highlight colors.} diff --git a/man/plotHicRectangle.Rd b/man/plotHicRectangle.Rd index 94402a1c6..6d7360c72 100644 --- a/man/plotHicRectangle.Rd +++ b/man/plotHicRectangle.Rd @@ -8,7 +8,7 @@ plotHicRectangle( data, resolution = "auto", zrange = NULL, - norm = "KR", + norm = "auto", matrix = "observed", chrom, chromstart = NULL, @@ -25,6 +25,8 @@ plotHicRectangle( just = c("left", "top"), default.units = "inches", draw = TRUE, + raster = c("auto", "never", "always"), + raster.max = 2000, params = NULL, quiet = FALSE ) @@ -45,8 +47,9 @@ max or min.} \item{norm}{Character value specifying hic data normalization method, if giving .hic or .(m)cool file. This value must be found in the .hic -or .(m)cool file. -Default value is \code{norm = "KR"}.} +or .(m)cool file. \code{"auto"} chooses \code{"KR"} for .hic files and an +an available bins column for .(m)cool files (see \code{readCoolNorms()}). +Default value is \code{norm = "auto"}.} \item{matrix}{Character value indicating the type of matrix to output for .hic files. @@ -111,6 +114,13 @@ as numerics. Default value is \code{default.units = "inches"}.} \item{draw}{A logical value indicating whether graphics output should be produced. Default value is \code{draw = TRUE}.} +\item{raster}{Rasterization mode for Hi-C pixels. \code{"auto"} rasterizes +large maps, \code{"never"} always uses vector rectangles, and +\code{"always"} always rasterizes when possible.} + +\item{raster.max}{Maximum raster dimension. Default value is +\code{raster.max = 2000}.} + \item{params}{An optional \link[plotgardener]{pgParams} object containing relevant function parameters.} diff --git a/man/plotHicSquare.Rd b/man/plotHicSquare.Rd index 498c5f17d..2b80e87a5 100644 --- a/man/plotHicSquare.Rd +++ b/man/plotHicSquare.Rd @@ -8,7 +8,7 @@ plotHicSquare( data, resolution = "auto", zrange = NULL, - norm = "KR", + norm = "auto", matrix = "observed", chrom, chromstart = NULL, @@ -21,6 +21,8 @@ plotHicSquare( colorTrans = "linear", half = "both", yaxisDir = "increase", + xaxisDir = "increase", + aspect = c("free", "fixed"), bg = NA, x = NULL, y = NULL, @@ -29,6 +31,8 @@ plotHicSquare( just = c("left", "top"), default.units = "inches", draw = TRUE, + raster = c("auto", "never", "always"), + raster.max = 2000, params = NULL, quiet = FALSE ) @@ -49,7 +53,9 @@ to the max or min.} \item{norm}{Character value specifying hic data normalization method, if giving .hic or .(m)cool file. This value must be found in the .hic or -.(m)cool file. Default value is \code{norm = "KR"}.} +.(m)cool file. \code{"auto"} chooses \code{"KR"} for .hic files and an +an available bins column for .(m)cool files (see \code{readCoolNorms()}). +Default value is \code{norm = "auto"}.} \item{matrix}{Character value indicating the type of matrix to output for .hic files. @@ -60,14 +66,16 @@ Default value is \code{matrix = "observed"}. Options are: \item{\code{"log2oe"}: }{Log2 transformed observed/expected counts.} }} -\item{chrom}{Chromosome of region to be plotted, as a string.} +\item{chrom}{Chromosome of region to be plotted, as a string. For +interchromosomal plots this is the **x-axis** chromosome.} \item{chromstart}{Integer start position on chromosome to be plotted.} \item{chromend}{Integer end position on chromosome to be plotted.} \item{altchrom}{Alternate chromosome for off-diagonal plotting -or interchromosomal plotting, as a string.} +or interchromosomal plotting, as a string. For interchromosomal plots this +is the **y-axis** chromosome.} \item{altchromstart}{Alternate chromosome integer start position for off-diagonal plotting or interchromosomal plotting.} @@ -91,7 +99,10 @@ Default value is \code{colorTrans = "linear"}.} \item{half}{A character value indicating which diagonal regions to plot. For intrachromosomal plotting, options are \code{"both"}, \code{"top"}, or \code{"bottom"}. For off-diagonal or interchromosomal plotting, -options are \code{"top"} or \code{"bottom"}. +options are \code{"top"} or \code{"bottom"}. For interchromosomal plots, +\code{half} does not select a triangle; it controls the y-axis origin +together with \code{yaxisDir}. See the interchromosomal orientation +section below. Default value is \code{half = "both"}. \describe{ \item{\code{"both"}: }{Both diagonal halves.} @@ -103,9 +114,20 @@ Default value is \code{half = "both"}. Options are \code{"increase"}, where the bottom left corner of the Hi-C map indicates the origin, and \code{"decrease"}, where the top left corner of the Hi-C map indicates the origin. This will change the direction of the diagonal -for intrachromosomal maps. +for intrachromosomal maps. For interchromosomal maps, combine +\code{yaxisDir} with \code{half} as described in the interchromosomal +orientation section below. Default value is \code{yaxisDir = "increase"}.} +\item{xaxisDir}{A string specifying the genomic direction of the x-axis. +Options are \code{"increase"} or \code{"decrease"}. +Default value is \code{xaxisDir = "increase"}.} + +\item{aspect}{Aspect mode for interchromosomal plots. \code{"free"} +stretches each chromosome to fill its axis; \code{"fixed"} uses the same +basepairs-per-inch on both axes, centering padding on the shorter +chromosome. Default value is \code{aspect = "free"}.} + \item{bg}{Character value indicating background color. Default value is \code{bg = NA}.} @@ -136,6 +158,13 @@ numerics. Default value is \code{default.units = "inches"}.} \item{draw}{A logical value indicating whether graphics output should be produced. Default value is \code{draw = TRUE}.} +\item{raster}{Rasterization mode for Hi-C pixels. \code{"auto"} rasterizes +large maps, \code{"never"} always uses vector rectangles, and +\code{"always"} always rasterizes when possible.} + +\item{raster.max}{Maximum number of raster rows/columns. Larger matrices +fall back to vector rectangles. Default value is \code{raster.max = 2000}.} + \item{params}{An optional \link[plotgardener]{pgParams} object containing relevant function parameters.} @@ -164,6 +193,54 @@ plotHicSquare(data, chrom, chromstart = NULL, chromend = NULL) } } +\section{Interchromosomal orientation}{ + +For an interchromosomal plot, \code{chrom} is always the x-axis and +\code{altchrom} is always the y-axis: +\preformatted{ + x = chrom + y = altchrom +} + +When building a grid of chromosomes, a cell at row \code{i} and column +\code{j} must therefore use the column chromosome as \code{chrom} and +the row chromosome as \code{altchrom}: +\preformatted{ + plotHicSquare( + data = hic, + chrom = chroms[j], # x-axis: grid column + altchrom = chroms[i], # y-axis: grid row + chromstart = 0, chromend = max_len, + altchromstart = 0, altchromend = max_len, + x = x0 + (j - 1) * cell, + y = y0 + (i - 1) * cell, + width = cell, height = cell, + half = "top", yaxisDir = "decrease", + just = c("left", "top") + ) +} +Passing \code{chrom = chroms[i]} and \code{altchrom = chroms[j]} instead +transposes every off-diagonal square. + +For interchromosomal plots, \code{half} controls the y-axis origin in +combination with \code{yaxisDir}: +\describe{ +\item{\code{half = "bottom"}, \code{yaxisDir = "decrease"}: }{ + origin at the lower-left} +\item{\code{half = "top"}, \code{yaxisDir = "decrease"}: }{ + origin at the upper-left; y increases downward} +\item{\code{half = "bottom"}, \code{yaxisDir = "increase"}: }{ + origin at the upper-left} +\item{\code{half = "top"}, \code{yaxisDir = "increase"}: }{ + origin at the lower-left} +} +The combination \code{half = "top", yaxisDir = "decrease"} matches the +orientation used by common 3D genome browsers, where the upper-left corner +is the matrix origin and y increases downward. \code{xaxisDir} controls +whether x increases to the right (\code{"increase"}) or to the left +(\code{"decrease"}). +} + \examples{ ## Load Hi-C data library(plotgardenerData) diff --git a/man/plotHicTriangle.Rd b/man/plotHicTriangle.Rd index b2183aa0f..38ec6a5a3 100644 --- a/man/plotHicTriangle.Rd +++ b/man/plotHicTriangle.Rd @@ -8,7 +8,7 @@ plotHicTriangle( data, resolution = "auto", zrange = NULL, - norm = "KR", + norm = "auto", matrix = "observed", chrom, chromstart = NULL, @@ -17,6 +17,7 @@ plotHicTriangle( palette = colorRampPalette(brewer.pal(n = 9, "YlGnBu")), colorTrans = "linear", flip = FALSE, + xaxisDir = "increase", bg = NA, x = NULL, y = NULL, @@ -25,6 +26,8 @@ plotHicTriangle( just = c("left", "top"), default.units = "inches", draw = TRUE, + raster = c("auto", "never", "always"), + raster.max = 2000, params = NULL, quiet = FALSE ) @@ -45,7 +48,9 @@ will be set to the max or min.} \item{norm}{Character value specifying hic data normalization method, if giving .hic or .(m)cool file. This value must be found in the .hic or -.(m)cool file. Default value is \code{norm = "KR"}.} +.(m)cool file. \code{"auto"} chooses \code{"KR"} for .hic files and an +an available bins column for .(m)cool files (see \code{readCoolNorms()}). +Default value is \code{norm = "auto"}.} \item{matrix}{Character value indicating the type of matrix to output for .hic files. @@ -77,6 +82,11 @@ Default value is \code{colorTrans = "linear"}.} \item{flip}{A logical indicating whether to flip the orientation of the Hi-C matrix over the x-axis. Default value is \code{flip = FALSE}.} +\item{xaxisDir}{A string specifying the genomic direction of the x-axis. +Options are \code{"increase"} or \code{"decrease"}. A value of +\code{"decrease"} mirrors the triangle horizontally. +Default value is \code{xaxisDir = "increase"}.} + \item{bg}{Character value indicating background color. Default value is \code{bg = NA}.} @@ -109,6 +119,12 @@ numerics. Default value is \code{default.units = "inches"}.} \item{draw}{A logical value indicating whether graphics output should be produced. Default value is \code{draw = TRUE}.} +\item{raster}{Rasterization mode for regular Hi-C pixels. Edge-clipped +pixels remain vector. \code{"auto"} rasterizes large maps.} + +\item{raster.max}{Maximum raster dimension. Default value is +\code{raster.max = 2000}.} + \item{params}{An optional \link[plotgardener]{pgParams} object containing relevant function parameters.} diff --git a/man/plotLegend.Rd b/man/plotLegend.Rd index 2a697b157..4f1a3af7a 100644 --- a/man/plotLegend.Rd +++ b/man/plotLegend.Rd @@ -93,6 +93,11 @@ placement and \link[grid]{grob} information. \description{ Plot a legend } +\note{ +Some SVG renderers, notably cairosvg, may fail to render filled +legend keys even though the grobs are present. Use the PDF/PNG device or +an alternative SVG backend such as svglite if legend keys disappear. +} \examples{ ## Load BED data library(plotgardenerData) diff --git a/man/plotMultiSignal.Rd b/man/plotMultiSignal.Rd index d636f6d0b..8b93ac626 100644 --- a/man/plotMultiSignal.Rd +++ b/man/plotMultiSignal.Rd @@ -19,10 +19,13 @@ plotMultiSignal( range = NULL, scale = FALSE, label = NULL, + label.position = NULL, + label.offset = 0.01, bg = NA, baseline = TRUE, baseline.color = "grey", baseline.lwd = 1, + baseline.lty = 1, orientation = "h", x = NULL, y = NULL, @@ -85,11 +88,17 @@ top right of the signal tracks. Otherwise, the label will be drawn in the top left of the plot. For more customizable labels, use \link[plotgardener]{plotText}.} +\item{label.position}{Label position for each track. See +\link[plotgardener]{plotSignal}.} + +\item{label.offset}{Offset from the plot edge in npc units.} + \item{bg}{Character value indicating background color. Default value is \code{bg = NA}.} \item{baseline}{Logical value indicating whether to include a -baseline along the x-axis. Default value is \code{baseline = TRUE}.} +baseline along the x-axis. A numeric value can be supplied to place the +baseline at a specific y-value. Default value is \code{baseline = TRUE}.} \item{baseline.color}{Baseline color. Default value is \code{baseline.color = "grey"}.} @@ -97,6 +106,9 @@ Default value is \code{baseline.color = "grey"}.} \item{baseline.lwd}{Baseline line width. Default value is \code{baseline.lwd = 1}.} +\item{baseline.lty}{Baseline line type. +Default value is \code{baseline.lty = 1}.} + \item{orientation}{A string specifying signal track orientations. Default value is \code{orientation = "h"}. Options are: \describe{ diff --git a/man/plotNeoAssembly.Rd b/man/plotNeoAssembly.Rd new file mode 100644 index 000000000..7091b5e61 --- /dev/null +++ b/man/plotNeoAssembly.Rd @@ -0,0 +1,104 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/plotNeo.R +\name{plotNeoAssembly} +\alias{plotNeoAssembly} +\title{Draw an SV neo-chromosome assembly backbone} +\usage{ +plotNeoAssembly( + neo, + x, + y, + width, + height, + just = c("left", "top"), + default.units = "inches", + fill = "#D4EEF9", + linecolor = "white", + lwd = 0.5, + fragment.height = 0.6, + arrow.size = NULL, + labels = TRUE, + label.fontsize = 7, + label.fontcolor = "black", + show.seams = TRUE, + seam.color = "grey40", + seam.lwd = 0.5, + seam.lty = 1, + params = NULL, + ... +) +} +\arguments{ +\item{neo}{A `neoAssembly` object from \code{readNeoAssembly()}.} + +\item{x}{A numeric or unit object specifying the backbone x-location.} + +\item{y}{A numeric, unit object, or character containing a "b" combined +with a numeric value specifying the backbone y-location.} + +\item{width}{A numeric or unit object specifying the backbone width.} + +\item{height}{A numeric or unit object specifying the backbone height.} + +\item{just}{Justification of the backbone relative to its (x, y) location. +Default value is \code{just = c("left", "top")}.} + +\item{default.units}{A string indicating the default units to use if +\code{x}, \code{y}, \code{width}, or \code{height} are only given as +numerics. Default value is \code{default.units = "inches"}.} + +\item{fill}{Fill color(s) for fragments. A single value, a vector of +length equal to the number of fragments, or a named vector keyed by +chromosome name. Default value is \code{fill = "#D4EEF9"}.} + +\item{linecolor}{Fragment outline color. Default value is +\code{linecolor = "white"}.} + +\item{lwd}{Fragment outline line width. Default value is \code{lwd = 0.5}.} + +\item{fragment.height}{Fraction of \code{height} used by the fragment +arrows. Default value is \code{fragment.height = 0.6}.} + +\item{arrow.size}{Arrow-tip size in page units. If \code{NULL}, the tip is +sized relative to each fragment.} + +\item{labels}{Logical value indicating whether to draw fragment labels, or +a character vector of labels. Default value is \code{labels = TRUE}.} + +\item{label.fontsize}{Fragment label font size. +Default value is \code{label.fontsize = 7}.} + +\item{label.fontcolor}{Fragment label color. +Default value is \code{label.fontcolor = "black"}.} + +\item{show.seams}{Logical value indicating whether to draw fragment +boundaries. Default value is \code{show.seams = TRUE}.} + +\item{seam.color}{Fragment boundary color. +Default value is \code{seam.color = "grey40"}.} + +\item{seam.lwd}{Fragment boundary line width. Default value is +\code{seam.lwd = 0.5}.} + +\item{seam.lty}{Fragment boundary line type. Default value is +\code{seam.lty = 1}.} + +\item{params}{An optional \link[plotgardener]{pgParams} object.} + +\item{...}{Additional grid graphical parameters. See \link[grid]{gpar}.} +} +\value{ +Invisibly returns a list containing the fragment polygons, labels, +and boundary segments. +} +\description{ +Draw a directional fragment backbone for a `neoAssembly` object. Each +fragment is drawn as an arrow pointing in its neo-chromosome orientation. +} +\examples{ +\dontrun{ +neo <- readNeoAssembly("HM1_merged.assemblies.txt", "C1", extend = 200000) +pageCreate(width = 6, height = 2, default.units = "inches") +plotNeoAssembly(neo, x = 0.5, y = 0.5, width = 3, height = 0.2) +} +} diff --git a/man/plotNeoGenes.Rd b/man/plotNeoGenes.Rd new file mode 100644 index 000000000..7bafb0722 --- /dev/null +++ b/man/plotNeoGenes.Rd @@ -0,0 +1,190 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/plotNeo.R +\name{plotNeoGenes} +\alias{plotNeoGenes} +\title{Plot IGV-style gene models in neo-chromosome coordinates} +\usage{ +plotNeoGenes( + data = NULL, + neo, + x, + y, + width, + height, + txdb = NULL, + orgdb = NULL, + assembly = NULL, + gene.id.column = NULL, + display.column = NULL, + just = c("left", "top"), + default.units = "inches", + displayMode = c("auto", "collapsed", "expanded", "squished"), + chromstart = 0, + chromend = NULL, + color = "black", + highlight.color = "red", + geneHighlights = NULL, + gene.type = "protein_coding", + geneOrder = NULL, + labelClusters = FALSE, + labelClusterRot = 45, + geneBackground = "grey", + geneMode = c("expand", "focus", "compact"), + focus.alpha = 0.5, + labels = FALSE, + label.fontsize = 5, + label.fontcolor = "black", + label.position = c("above", "center"), + label.overlap = TRUE, + show.strand = c("arrows", "labels", "none"), + strand.color = "black", + arrow.spacing = 30, + body.lwd = 0.8, + exon.height = 0.7, + feature.min.px = 3, + exon.min.px = 1, + exon.min.width = NULL, + row.height = NULL, + auto.collapse.bp.per.inch = 50000, + max.rows = 4, + reader = c("auto", "readGFF", "import", "tabix"), + cache = NULL, + params = NULL, + ... +) +} +\arguments{ +\item{data}{A GTF/GFF path, `GRanges` object, data frame, or a +`TxDb`/`EnsDb` annotation object. Data frames need `chrom`, `start`, +`end`, and optionally `strand`, `gene`, `transcript`, and `feature` +columns.} + +\item{neo}{A `neoAssembly` object.} + +\item{x, y, width, height}{Placement parameters.} + +\item{txdb}{Optional `TxDb` or `EnsDb` annotation. If `data` is a +`TxDb`/`EnsDb`, it is used automatically.} + +\item{orgdb}{Optional `OrgDb` used to map gene IDs to symbols.} + +\item{assembly}{Assembly name or object used to resolve default +`TxDb`/`OrgDb` packages. Defaults to `neo$assembly`.} + +\item{gene.id.column, display.column}{Column names used when reading a +`TxDb` annotation.} + +\item{just}{Justification. Default value is \code{c("left", "top")}.} + +\item{default.units}{Default units. Default value is \code{"inches"}.} + +\item{displayMode}{Gene display mode. \code{"auto"} chooses +\code{"collapsed"} or \code{"expanded"} from basepairs per inch. +\code{"squished"} uses expanded detail with shorter rows. +Default value is \code{displayMode = "auto"}.} + +\item{chromstart, chromend}{Neo-coordinate window to display. Defaults to +the full neo-chromosome.} + +\item{color}{Gene color. Can be a single color or a named vector by gene. +Default value is \code{"black"}.} + +\item{highlight.color}{Color for highlighted genes. +Default value is \code{"red"}.} + +\item{geneHighlights}{Optional character vector of gene names, a named +color vector, or a data frame with `gene` and `color` columns. Genes named +without colors use \code{highlight.color}.} + +\item{gene.type}{Gene biotypes to retain when a \code{gene_type} column is +available, e.g. \code{"protein_coding"}. Use \code{NULL} to keep all +biotypes. Default value is \code{"protein_coding"}.} + +\item{geneOrder}{Optional character vector giving label priority order.} + +\item{labelClusters}{Logical value indicating whether labels should be +rotated to reduce overlap. Default value is `FALSE`.} + +\item{labelClusterRot}{Rotation in degrees for clustered labels. +Default value is 45.} + +\item{geneBackground}{Color for non-highlighted genes when +`geneHighlights` is supplied. Default value is `"grey"`.} + +\item{geneMode}{Gene layout mode. `"expand"` draws all genes at full +opacity in packed rows. `"focus"` draws priority genes (`geneHighlights`, +`geneOrder`, or named `labels`) at full opacity and all other genes at +`focus.alpha`. `"compact"` draws all genes on a single line. +Default value is `"expand"`.} + +\item{focus.alpha}{Alpha applied to non-priority genes in focus mode. +Default value is 0.5.} + +\item{labels}{Logical value or character vector of gene names to label. +Default value is \code{FALSE} so the track stays clean.} + +\item{label.fontsize}{Gene label font size. Default value is 5.} + +\item{label.fontcolor}{Gene label color for non-highlighted genes. +Default value is \code{"black"}.} + +\item{label.position}{Label position: \code{"above"} or \code{"center"}. +Default value is \code{"above"}.} + +\item{label.overlap}{Logical value indicating whether labels should be +stacked into extra levels to avoid collisions. Default value is +\code{TRUE}.} + +\item{show.strand}{Strand display: \code{"arrows"}, \code{"labels"}, or +\code{"none"}. Logical \code{TRUE}/\code{FALSE} are accepted for backward +compatibility. Default value is \code{"arrows"}.} + +\item{strand.color}{Strand-label color. Default value is \code{"black"}.} + +\item{arrow.spacing}{Spacing between strand chevrons in points. +Default value is 30.} + +\item{body.lwd}{Gene-body line width in expanded mode. Default value is +0.8.} + +\item{exon.height}{Exon block height as a fraction of row height. +Default value is 0.7.} + +\item{feature.min.px}{Minimum feature width in pixels at 72 dpi. +Default value is 3.} + +\item{exon.min.px}{Minimum exon width in pixels at 72 dpi. +Default value is 1.} + +\item{exon.min.width}{Deprecated point-based exon width override. When +supplied, it takes precedence over \code{exon.min.px}.} + +\item{row.height}{Optional explicit row height in \code{default.units}.} + +\item{auto.collapse.bp.per.inch}{Basepairs per inch above which +\code{displayMode = "auto"} collapses genes. Default value is 50000.} + +\item{max.rows}{Maximum number of gene rows. Default value is 4.} + +\item{reader}{GTF/GFF reader: `"auto"`, `"readGFF"`, `"import"`, or +`"tabix"`. Default value is `"auto"`.} + +\item{cache}{Optional cache directory for parsed annotations, or `TRUE` +for the plotgardener user cache. Default value is `NULL` (no cache).} + +\item{params}{An optional \link[plotgardener]{pgParams} object.} + +\item{...}{Additional arguments passed to \code{plotText()}.} +} +\value{ +Invisibly returns a list with the gene rows, grobs, display mode, +and displayed window. +} +\description{ +Draws gene models through the neo-chromosome topology, using IGV-style +display modes. At whole-chromosome scale genes collapse to solid blocks; +when zoomed in, gene bodies and exon blocks are shown. Input can be a +GTF/GFF file, a `GRanges` object, or a data frame. Using a GTF/GFF file +allows arbitrary GENCODE releases without requiring a matching TxDb +package. +} diff --git a/man/plotNeoHic.Rd b/man/plotNeoHic.Rd new file mode 100644 index 000000000..2c0294ebe --- /dev/null +++ b/man/plotNeoHic.Rd @@ -0,0 +1,40 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/readNeoHic.R +\name{plotNeoHic} +\alias{plotNeoHic} +\title{Plot a reconstructed neo-chromosome contact matrix} +\usage{ +plotNeoHic( + neoHic, + type = c("triangle", "square", "rectangle"), + flip = c("none", "horizontal"), + ... +) +} +\arguments{ +\item{neoHic}{A `neoHic` object from \code{readNeoHic()}.} + +\item{type}{Hi-C plot type: \code{"triangle"}, \code{"square"}, or +\code{"rectangle"}. Default value is \code{type = "triangle"}.} + +\item{flip}{Orientation. \code{"none"} or \code{FALSE} leaves the plot +unchanged, \code{"horizontal"} mirrors the x-axis so the opposite +chromosome is on the left, and \code{TRUE} retains the legacy vertical +triangle flip. Default value is \code{flip = "none"}.} + +\item{...}{Additional arguments passed to the corresponding +\code{plotHic*} function.} +} +\value{ +The plot object returned by \code{plotHicTriangle()}, +\code{plotHicSquare()}, or \code{plotHicRectangle()}. +} +\description{ +Plot a reconstructed neo-chromosome contact matrix +} +\examples{ +\dontrun{ +neoHic <- readNeoHic("HM1_merged.mcool", neo, resolution = 5000) +plotNeoHic(neoHic, type = "square", x = 1, y = 1, width = 2, height = 2) +} +} diff --git a/man/plotSignal.Rd b/man/plotSignal.Rd index abd7f7ff1..7d05bb865 100644 --- a/man/plotSignal.Rd +++ b/man/plotSignal.Rd @@ -19,10 +19,13 @@ plotSignal( range = NULL, scale = FALSE, label = NULL, + label.position = NULL, + label.offset = 0.01, bg = NA, baseline = TRUE, baseline.color = "grey", baseline.lwd = 1, + baseline.lty = 1, orientation = "h", x = NULL, y = NULL, @@ -86,11 +89,22 @@ of the plot. Otherwise, the label will be drawn in the top left of the plot. For more customizable labels, use \link[plotgardener]{plotText}. Default value is \code{label = NULL}.} +\item{label.position}{Label position. Options are \code{"top-left"}, +\code{"top-right"}, \code{"bottom-left"}, \code{"bottom-right"}, +\code{"left"}, and \code{"right"}. If \code{NULL}, the historical +behavior is used (\code{"top-right"} when \code{scale = TRUE}, +otherwise \code{"top-left"}). Default value is +\code{label.position = NULL}.} + +\item{label.offset}{Offset from the plot edge in npc units. +Default value is \code{label.offset = 0.01}.} + \item{bg}{Character value indicating background color. Default value is \code{bg = NA}.} \item{baseline}{Logical value indicating whether to include a -baseline along the x-axis. Default value is \code{baseline = TRUE}.} +baseline along the x-axis. A numeric value can be supplied to place the +baseline at a specific y-value. Default value is \code{baseline = TRUE}.} \item{baseline.color}{Baseline color. Default value is \code{baseline.color = "grey"}.} @@ -98,6 +112,9 @@ Default value is \code{baseline.color = "grey"}.} \item{baseline.lwd}{Baseline line width. Default value is \code{baseline.lwd = 1}.} +\item{baseline.lty}{Baseline line type. +Default value is \code{baseline.lty = 1}.} + \item{orientation}{A string specifying signal track orientation. Default value is \code{orientation = "h"}. Options are: \describe{ diff --git a/man/plotTranscripts.Rd b/man/plotTranscripts.Rd index d56f297f5..d25deafe2 100644 --- a/man/plotTranscripts.Rd +++ b/man/plotTranscripts.Rd @@ -20,6 +20,7 @@ plotTranscripts( transcriptFilter = NULL, fontsize = 8, labels = "transcript", + labelPriority = NULL, stroke = 0.1, bg = NA, x = NULL, @@ -86,7 +87,11 @@ display (default is \code{NULL}, no filtering)} Default value is \code{fontsize = 8}.} \item{labels}{A character value describing the format of -transcript text labels. Default value is \code{labels = "trancript"}. +transcript text labels. Default value is \code{labels = "trancript"}.} + +\item{labelPriority}{Optional character vector of transcript or gene names +to prioritize when labels overlap. Default value is +\code{labelPriority = NULL}. Options are: \describe{ \item{\code{NULL}: }{No labels.} diff --git a/man/readCool.Rd b/man/readCool.Rd index 76973c511..3f633d44f 100644 --- a/man/readCool.Rd +++ b/man/readCool.Rd @@ -45,8 +45,12 @@ the size of the region.} \item{zrange}{A numeric vector of length 2 specifying the range of interaction scores, where extreme values will be set to the max or min.} -\item{norm}{Character value specifying hic data normalization method. -This value must be found in the .(m)cool file. +\item{norm}{Character value specifying the exact name of a column in the +`bins` group of the .(m)cool file (for example `"weight"`, `"sweight"`, +`"KR"`, or `"NONE"`). Use \code{readCoolNorms()} to see the actual column +names in a file. \code{"NONE"} returns raw counts; \code{"auto"} chooses +\code{"KR"} if available, then \code{"weight"}, then \code{"sweight"}, then +the first available weight, then \code{"NONE"}. Default value is \code{norm = "NONE"}.} \item{binChunkSize}{A numeric specifying the number of bin indices to read @@ -67,6 +71,12 @@ format with the following columns: \code{chrom}, \code{altchrom}, \description{ Read a .(m)cool file and return Hi-C data as a dataframe } +\details{ +Cooler normalization weights are multiplicative: +\code{balanced[i, j] = observed[i, j] * weight[i] * weight[j]}. +Contacts involving bins with non-finite weights are dropped; the bins +themselves remain in the coordinate space. +} \examples{ ## .cool file diff --git a/man/readCoolNorms.Rd b/man/readCoolNorms.Rd index 336f44bae..bd33638b9 100644 --- a/man/readCoolNorms.Rd +++ b/man/readCoolNorms.Rd @@ -19,15 +19,20 @@ A vector or list of vectors of available normalizations Read normalizations included in .(m)cool files } \details{ -The "BALANCE" normalization refers to applying the pre-calculated matrix -balancing weights in the `weight` dataset of `file`, typically present -in files created using cooler. VC is vanilla coverage, -VC_SQRT is square root of vanilla coverage, -and KR is Knight-Ruiz normalization. +The `weight` column is the standard cooler balancing weight, typically +present in files created using `cooler balance`. +VC is vanilla coverage, VC_SQRT is square root of vanilla coverage, +and KR is Knight-Ruiz normalization. Other columns such as `sweight`, +`CNV`, or `obj_weight` are returned by their stored names. Use +`readCoolNorms()` to see the exact column names available in a file. + +Cooler weights are multiplicative: balanced counts are calculated as +\code{observed * weight1 * weight2}. Contacts involving bins with +non-finite weights are dropped; the bins remain in the coordinate space. Please note that if using a file from HiC-Pro, ICE normalizations will come from files stored in a separate folder, and thus will not contain any -normalizations explicitly called "ICE" or "BALANCE" since values are +normalizations explicitly called "ICE" or "weight" since values are included already normalized. This normalization can be specified as "NONE". } \author{ diff --git a/man/readNeoAssembly.Rd b/man/readNeoAssembly.Rd new file mode 100644 index 000000000..0f7e1d323 --- /dev/null +++ b/man/readNeoAssembly.Rd @@ -0,0 +1,66 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/neoAssembly.R +\name{readNeoAssembly} +\alias{readNeoAssembly} +\title{Read an SV neo-chromosome assembly topology} +\usage{ +readNeoAssembly( + file, + id, + assembly = "hg38", + extend = 0, + prefix = "chr", + quiet = FALSE +) +} +\arguments{ +\item{file}{Path to an `.assemblies.txt` file.} + +\item{id}{Assembly ID to extract, for example `"C1"`.} + +\item{assembly}{Genome assembly name. Default value is +\code{assembly = "hg38"}.} + +\item{extend}{Number of basepairs to extend the first and last fragment. +Default value is \code{extend = 0}.} + +\item{prefix}{Prefix to add to chromosome names that do not already have +one. Default value is \code{prefix = "chr"}.} + +\item{quiet}{A logical indicating whether to print messages.} +} +\value{ +A `neoAssembly` object: a list with \code{id}, \code{fragments}, +\code{total_length}, and \code{assembly}. \code{fragments} is a data frame +with columns \code{id}, \code{chrom}, \code{chrom_raw}, \code{start}, +\code{end}, \code{flipped}, \code{offset}, and \code{length}. +} +\description{ +Parse an assembly file from a neoloop/SV workflow and build a +`neoAssembly` object describing the concatenated neo-chromosome. +} +\details{ +Assembly lines are usually produced by NeoLoopFinder's +\code{assemble-complexSVs}. Each line contains an assembly ID, zero or more +SV records (\code{type,chrA,b1,strandA,chrB,b2,strandB}), and two span +coordinates (\code{chr,position}). Consecutive node pairs define fragments; +a fragment is flipped when its entry position is greater than its exit +position. See \code{vignette("neo_reconstruction")} for a full description +and examples. +} +\examples{ +\dontrun{ +neo <- readNeoAssembly( + file = "HM1_merged.assemblies.txt", + id = "C1", + assembly = "hg38", + extend = 200000 +) +neo +} +} +\references{ +Wang X, Xu J, Zhang B, Hou Y, Song F, Lyu H, Yue F. Genome-wide detection of +enhancer-hijacking events from chromatin interaction data in rearranged +genomes. Nature Methods (2021). +} diff --git a/man/readNeoHic.Rd b/man/readNeoHic.Rd new file mode 100644 index 000000000..1ae3c4625 --- /dev/null +++ b/man/readNeoHic.Rd @@ -0,0 +1,85 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/readNeoHic.R +\name{readNeoHic} +\alias{readNeoHic} +\title{Reconstruct an SV-impacted contact matrix in neo-chromosome coordinates} +\usage{ +readNeoHic( + data, + neo, + id = NULL, + resolution = "auto", + norm = "NONE", + matrix = "observed", + zrange = NULL, + assembly = "hg38", + extend = 0, + prefix = "chr", + quiet = FALSE +) +} +\arguments{ +\item{data}{Path to a `.hic`, `.cool`, or `.mcool` file, or a data frame +of precomputed genomic contacts with columns \code{chrom1}, \code{start1}, +\code{chrom2}, \code{start2}, and \code{counts}. A data frame with +\code{chrom}, \code{start1}, \code{start2}, and \code{counts} is also +accepted for intrachromosomal data.} + +\item{neo}{A `neoAssembly` object from \code{readNeoAssembly()}, or a path +to an assembly file. If a path is supplied, \code{id} is required.} + +\item{id}{Assembly ID when \code{neo} is an assembly file path.} + +\item{resolution}{Resolution in basepairs, or \code{"auto"} to choose +a resolution close to 1000 bins across the neo-chromosome. For data frame +input, \code{"auto"} estimates the smallest positive spacing between bins.} + +\item{norm}{Normalization to pass to \code{readHic()} or \code{readCool()}. +Default value is \code{norm = "NONE"}.} + +\item{matrix}{Matrix type for `.hic` files. Default value is +\code{matrix = "observed"}.} + +\item{zrange}{Optional numeric vector of length 2 used to clip the final +reconstructed counts. Default value is \code{zrange = NULL}.} + +\item{assembly}{Genome assembly for `.hic` files and for reading an +assembly file path. Default value is \code{assembly = "hg38"}.} + +\item{extend}{Basepairs to extend the first and last fragments when +\code{neo} is a file path. Default value is \code{extend = 0}.} + +\item{prefix}{Prefix for chromosome names when \code{neo} is a file path. +Default value is \code{prefix = "chr"}.} + +\item{quiet}{A logical indicating whether to print progress messages.} +} +\value{ +A `neoHic` object: a list with \code{matrix} (a data frame of +\code{x}, \code{y}, \code{counts} in neo coordinates), \code{neo}, +\code{resolution}, \code{norm}, and \code{matrix_type}. +} +\description{ +Reconstruct an SV-impacted contact matrix in neo-chromosome coordinates +} +\details{ +For file input, the reconstruction reads each fragment pair from the source +file and maps genomic bin starts onto the concatenated neo-chromosome. +Contacts are assigned only to the fragment pair being read, so pixels from +adjacent fragments are not double-counted. For data frame input, each row's +genomic coordinates are mapped to neo coordinates using the same rules. +} +\examples{ +\dontrun{ +neo <- readNeoAssembly("HM1_merged.assemblies.txt", "C1", extend = 200000) +neoHic <- readNeoHic("HM1_merged.mcool", neo, resolution = 5000) +plotNeoHic(neoHic, type = "triangle") + +## Or pass the assembly path and ID directly +neoHic2 <- readNeoHic( + "HM1_merged.mcool", + "HM1_merged.assemblies.txt", id = "C1", + extend = 200000, resolution = 5000 +) +} +} diff --git a/tests/testthat/helper-mcool.R b/tests/testthat/helper-mcool.R new file mode 100644 index 000000000..1116318f3 --- /dev/null +++ b/tests/testthat/helper-mcool.R @@ -0,0 +1,73 @@ +## Tests for the .cool/.mcool reader. These use a small synthetic HDF5 file so +## they do not depend on network access or an external cooler executable. + +make_test_mcool <- function(path, chromNames = c("chr1", "chr2")) { + skip_if_not_installed("rhdf5") + + ## Two chromosomes: chr1 has 10 bins, chr2 has 8 bins (100 bp bins) + nBins1 <- 10L + nBins2 <- 8L + starts1 <- seq(0L, by = 100L, length.out = nBins1) + starts2 <- seq(0L, by = 100L, length.out = nBins2) + starts <- c(starts1, starts2) + ends <- starts + 100L + chromIds <- c(rep(0L, nBins1), rep(1L, nBins2)) + nbins <- length(starts) + + ## Sparse upper-triangular pixels + pixels <- expand.grid( + bin1_id = seq_len(nbins) - 1L, + bin2_id = seq_len(nbins) - 1L + ) + pixels <- pixels[pixels$bin1_id <= pixels$bin2_id, ] + pixels <- pixels[order(pixels$bin1_id, pixels$bin2_id), ] + rownames(pixels) <- NULL + pixels$count <- as.integer(seq_len(nrow(pixels)) %% 7L + 1L) + + bin1Tab <- tabulate(pixels$bin1_id + 1L, nbins = nbins) + bin1Offset <- as.integer(c(0L, cumsum(bin1Tab))) + chromOffset <- as.integer(c(0L, nBins1, nBins1 + nBins2)) + + ## Deliberately include a masked bin (NaN weight) and a second weight type + weight <- c(1, 0.5, 2, 4, 0.25, 1, 1, 1, 1, NaN, + 1, 1, 0.5, 0.5, 2, 2, 1, 1) + sweight <- c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1) + + h5 <- rhdf5::h5createFile(path) + rhdf5::h5createGroup(path, "resolutions") + rhdf5::h5createGroup(path, "resolutions/100") + rhdf5::h5createGroup(path, "resolutions/100/bins") + rhdf5::h5createGroup(path, "resolutions/100/chroms") + rhdf5::h5createGroup(path, "resolutions/100/indexes") + rhdf5::h5createGroup(path, "resolutions/100/pixels") + ## Extra root groups must not confuse .checkCool() + rhdf5::h5createGroup(path, "extra_root_group") + + rhdf5::h5write(chromIds, path, "resolutions/100/bins/chrom") + rhdf5::h5write(starts, path, "resolutions/100/bins/start") + rhdf5::h5write(ends, path, "resolutions/100/bins/end") + rhdf5::h5write(weight, path, "resolutions/100/bins/weight") + rhdf5::h5write(sweight, path, "resolutions/100/bins/sweight") + + rhdf5::h5write(chromNames, path, "resolutions/100/chroms/name") + rhdf5::h5write(c(max(ends[chromIds == 0]), max(ends[chromIds == 1])), + path, "resolutions/100/chroms/length") + + rhdf5::h5write(bin1Offset, path, "resolutions/100/indexes/bin1_offset") + rhdf5::h5write(chromOffset, path, "resolutions/100/indexes/chrom_offset") + + rhdf5::h5write(pixels$bin1_id, path, "resolutions/100/pixels/bin1_id") + rhdf5::h5write(pixels$bin2_id, path, "resolutions/100/pixels/bin2_id") + rhdf5::h5write(pixels$count, path, "resolutions/100/pixels/count") + rhdf5::h5closeAll() + + list( + path = path, + pixels = pixels, + starts = starts, + weight = weight, + sweight = sweight, + nBins1 = nBins1 + ) +} diff --git a/tests/testthat/test-annoPixels-factors.R b/tests/testthat/test-annoPixels-factors.R new file mode 100644 index 000000000..3de26f6ae --- /dev/null +++ b/tests/testthat/test-annoPixels-factors.R @@ -0,0 +1,27 @@ +test_that("annoPixels handles factor chromosome levels from different sources", { + pairData <- expand.grid(x = seq(0, 90, 10), y = seq(0, 90, 10)) + pairData <- pairData[pairData$x <= pairData$y, ] + pairData$counts <- 1 + + pageCreate(width = 3, height = 3, default.units = "inches", + showGuides = FALSE) + hic <- suppressWarnings(plotHicRectangle( + data = pairData, resolution = 10, zrange = c(0, 2), + chrom = "chr1", chromstart = 0, chromend = 100, + assembly = "hg38", + x = 0.5, y = 0.5, width = 2, height = 2, + just = c("left", "top") + )) + + loops <- data.frame( + chrom1 = factor(c("chr1", "chr2"), levels = c("chr1", "chr2")), + start1 = c(10, 20), + end1 = c(20, 30), + chrom2 = factor(c("chr1", "chr2"), levels = c("chr1", "chr2")), + start2 = c(10, 20), + end2 = c(20, 30) + ) + expect_silent(suppressMessages( + annoPixels(plot = hic, data = loops) + )) +}) diff --git a/tests/testthat/test-axis-fixes.R b/tests/testthat/test-axis-fixes.R new file mode 100644 index 000000000..53c6ad6f1 --- /dev/null +++ b/tests/testthat/test-axis-fixes.R @@ -0,0 +1,70 @@ +test_that("annoYaxis supports tick and axis-line styling", { + signalData <- data.frame( + chrom = "chr1", + start = seq(1, 901, by = 100), + end = seq(100, 1000, by = 100), + score = rep(10, 10) + ) + pageCreate(width = 4, height = 3, default.units = "inches", + showGuides = FALSE) + sig <- plotSignal( + signalData, chrom = "chr1", chromstart = 1, chromend = 1000, + assembly = "hg38", binSize = 100, + x = 0.5, y = 0.5, width = 3, height = 1, draw = FALSE + ) + yax <- annoYaxis( + plot = sig, at = c(0, 10), axisLine = TRUE, + tcl = 1, label.offset = 0.25, + axisLine.lwd = 2, axisLine.col = "blue", + tick.lwd = 3, tick.col = "red" + ) + + yGrob <- yax$grobs$children[[1]] + expect_equal(yGrob$children$ticks$x1, unit(-1, "lines")) + expect_equal(yGrob$children$labels$x, unit(-1.25, "lines")) + expect_equal(yGrob$children$major$gp$lwd, 2) + expect_equal(yGrob$children$major$gp$col, "blue") + expect_equal(yGrob$children$ticks$gp$lwd, 3) + expect_equal(yGrob$children$ticks$gp$col, "red") +}) + +test_that("annoXaxis axisLine = FALSE removes the axis line without grid.remove", { + signalData <- data.frame( + chrom = "chr1", + start = seq(1, 901, by = 100), + end = seq(100, 1000, by = 100), + score = rep(10, 10) + ) + pageCreate(width = 4, height = 3, default.units = "inches", + showGuides = FALSE) + sig <- plotSignal( + signalData, chrom = "chr1", chromstart = 1, chromend = 1000, + assembly = "hg38", binSize = 100, + x = 0.5, y = 0.5, width = 3, height = 1, draw = FALSE + ) + xax <- annoXaxis(plot = sig, at = c(1, 1000), axisLine = FALSE) + xGrob <- xax$grobs$children[[1]] + expect_false("major" %in% names(xGrob$children)) +}) + +test_that("annoYaxis defaults use shorter ticks and thinner lines", { + signalData <- data.frame( + chrom = "chr1", + start = seq(1, 901, by = 100), + end = seq(100, 1000, by = 100), + score = rep(10, 10) + ) + pageCreate(width = 4, height = 3, default.units = "inches", + showGuides = FALSE) + sig <- plotSignal( + signalData, chrom = "chr1", chromstart = 1, chromend = 1000, + assembly = "hg38", binSize = 100, + x = 0.5, y = 0.5, width = 3, height = 1, draw = FALSE + ) + yax <- annoYaxis(plot = sig, at = c(0, 10), axisLine = TRUE) + yGrob <- yax$grobs$children[[1]] + expect_equal(yGrob$children$ticks$x1, unit(-0.25, "lines")) + expect_equal(yGrob$children$labels$x, unit(-0.6, "lines")) + expect_equal(yGrob$children$major$gp$lwd, 0.5) + expect_equal(yGrob$children$ticks$gp$lwd, 0.5) +}) diff --git a/tests/testthat/test-hic-interchrom.R b/tests/testthat/test-hic-interchrom.R new file mode 100644 index 000000000..4421b716b --- /dev/null +++ b/tests/testthat/test-hic-interchrom.R @@ -0,0 +1,82 @@ +test_that("plotHicSquare does not mirror interchromosomal matrices", { + pairData <- data.frame( + x = rep(seq(100, 300, by = 100), each = 3), + y = rep(seq(500, 700, by = 100), 3), + counts = rep(1, 9) + ) + + pageCreate(width = 3, height = 3, default.units = "inches", + showGuides = FALSE) + hic <- plotHicSquare( + data = pairData, resolution = 100, zrange = c(0, 2), + chrom = "chr4", chromstart = 0, chromend = 400, + altchrom = "chr14", altchromstart = 400, altchromend = 800, + assembly = "hg38", half = "top", + x = 0.5, y = 0.5, width = 2, height = 2, + just = c("left", "top"), draw = FALSE + ) + + expect_equal(hic$xchrom, "chr4") + expect_equal(hic$ychrom, "chr14") + expect_equal(hic$xchromstart, 0) + expect_equal(hic$ychromstart, 400) + + ## No symmetrization: one rectangle per input pixel + rectGrob <- hic$grobs$children[[2]] + expect_equal(length(rectGrob$x), nrow(pairData)) +}) + +test_that("annoGenomeLabel uses explicit interchromosomal axis metadata", { + pairData <- data.frame( + x = rep(seq(100, 300, by = 100), each = 3), + y = rep(seq(500, 700, by = 100), 3), + counts = rep(1, 9) + ) + + pageCreate(width = 3, height = 3, default.units = "inches", + showGuides = FALSE) + hic <- plotHicSquare( + data = pairData, resolution = 100, zrange = c(0, 2), + chrom = "chr4", chromstart = 0, chromend = 400, + altchrom = "chr14", altchromstart = 400, altchromend = 800, + assembly = "hg38", half = "top", + x = 0.5, y = 0.5, width = 2, height = 2, + just = c("left", "top"), draw = FALSE + ) + + labels <- annoGenomeLabel( + hic, axis = "y", scale = "Kb", + x = 0.45, y = 0.5, just = c("right", "top") + ) + expect_s3_class(labels, "genomeLabel") +}) + +test_that("plotHicSquare fixed aspect uses equal basepairs per axis", { + pairData <- data.frame( + x = rep(seq(100, 300, by = 100), each = 3), + y = rep(seq(500, 900, by = 200), 3), + counts = rep(1, 9) + ) + + pageCreate(width = 3, height = 3, default.units = "inches", + showGuides = FALSE) + hic <- plotHicSquare( + data = pairData, resolution = 100, zrange = c(0, 2), + chrom = "chr4", chromstart = 0, chromend = 400, + altchrom = "chr14", altchromstart = 400, altchromend = 1000, + assembly = "hg38", half = "top", aspect = "fixed", + x = 0.5, y = 0.5, width = 2, height = 2, + just = c("left", "top"), draw = FALSE + ) + + expect_equal(diff(range(hic$xaxisRange)), + diff(range(hic$yaxisRange))) + expect_equal(diff(range(hic$xaxisRange)), 600) + + xlab <- annoGenomeLabel(hic, axis = "x", x = 0.5, y = 2.8, + just = c("left", "top")) + ylab <- annoGenomeLabel(hic, axis = "y", x = 0.45, y = 0.5, + just = c("right", "top")) + expect_s3_class(xlab, "genomeLabel") + expect_s3_class(ylab, "genomeLabel") +}) diff --git a/tests/testthat/test-hic-raster.R b/tests/testthat/test-hic-raster.R new file mode 100644 index 000000000..a044391b7 --- /dev/null +++ b/tests/testthat/test-hic-raster.R @@ -0,0 +1,63 @@ +test_that("plotHicSquare rasterizes when requested", { + pairData <- expand.grid(x = seq(0, 90, 10), y = seq(0, 90, 10)) + pairData <- pairData[pairData$x <= pairData$y, ] + pairData$counts <- 1 + + pageCreate(width = 3, height = 3, default.units = "inches", + showGuides = FALSE) + hic <- plotHicSquare( + data = pairData, resolution = 10, zrange = c(0, 2), + chrom = "chr1", chromstart = 0, chromend = 100, + assembly = "hg38", raster = "always", + x = 0.5, y = 0.5, width = 2, height = 2, + just = c("left", "top"), draw = FALSE + ) + expect_s3_class(hic$grobs$children[[2]], "rastergrob") + + hicVector <- plotHicSquare( + data = pairData, resolution = 10, zrange = c(0, 2), + chrom = "chr1", chromstart = 0, chromend = 100, + assembly = "hg38", raster = "never", + x = 0.5, y = 0.5, width = 2, height = 2, + just = c("left", "top"), draw = FALSE + ) + expect_s3_class(hicVector$grobs$children[[2]], "rect") +}) + +test_that("plotHicRectangle rasterizes when requested", { + pairData <- expand.grid(x = seq(0, 90, 10), y = seq(0, 90, 10)) + pairData <- pairData[pairData$x <= pairData$y, ] + pairData$counts <- 1 + + pageCreate(width = 3, height = 3, default.units = "inches", + showGuides = FALSE) + hic <- suppressWarnings(plotHicRectangle( + data = pairData, resolution = 10, zrange = c(0, 2), + chrom = "chr1", chromstart = 0, chromend = 100, + assembly = "hg38", raster = "always", + x = 0.5, y = 0.5, width = 2, height = 2, + just = c("left", "top"), draw = FALSE + )) + expect_s3_class(hic$grobs$children[[2]], "rastergrob") +}) + +test_that("plotHicTriangle rasterizes regular pixels", { + pairData <- expand.grid(x = seq(0, 90, 10), y = seq(0, 90, 10)) + pairData <- pairData[pairData$x <= pairData$y, ] + pairData$counts <- 1 + + pageCreate(width = 3, height = 3, default.units = "inches", + showGuides = FALSE) + hic <- plotHicTriangle( + data = pairData, resolution = 10, zrange = c(0, 2), + chrom = "chr1", chromstart = 0, chromend = 100, + assembly = "hg38", raster = "always", + x = 0.5, y = 0.5, width = 2, height = 1, + just = c("left", "top"), draw = FALSE + ) + expect_true(any(vapply( + hic$grobs$children, + function(g) inherits(g, "rastergrob"), + logical(1) + ))) +}) diff --git a/tests/testthat/test-neo.R b/tests/testthat/test-neo.R new file mode 100644 index 000000000..95e2a6948 --- /dev/null +++ b/tests/testthat/test-neo.R @@ -0,0 +1,1049 @@ +test_that("readNeoAssembly parses fragments, offsets, and flips", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", + assembly + ) + + neo <- readNeoAssembly(assembly, "C1", extend = 0, quiet = TRUE) + + expect_s3_class(neo, "neoAssembly") + expect_equal(neo$total_length, 800) + expect_equal(nrow(neo$fragments), 2) + expect_equal(neo$fragments$chrom, c("chr1", "chr2")) + expect_equal(neo$fragments$flipped, c(TRUE, FALSE)) + expect_equal(neo$fragments$offset, c(0, 400)) + expect_equal(neo$fragments$length, c(400, 400)) +}) + +test_that("readNeoAssembly extends only the first and last fragments", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", + assembly + ) + + neo <- readNeoAssembly(assembly, "C1", extend = 100, quiet = TRUE) + + expect_equal(neo$fragments$length, c(500, 500)) + expect_equal(neo$fragments$offset, c(0, 500)) + expect_equal(neo$total_length, 1000) +}) + +test_that("mapNeoFeatures flips coordinates and strand", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + + features <- data.frame( + chrom = c("chr1", "chr2"), + start = c(0, 0), + end = c(100, 100), + name = c("f1", "f2"), + strand = c("+", "+") + ) + mapped <- mapNeoFeatures(features, neo) + + expect_equal(mapped$chrom, c("neo", "neo")) + expect_equal(mapped$fragment, c(1L, 2L)) + expect_equal(mapped$start, c(300, 400)) + expect_equal(mapped$end, c(400, 500)) + expect_equal(mapped$strand, c("-", "+")) +}) + +test_that("readNeoHic reconstructs a mcool matrix in neo coordinates", { + mcool <- withr::local_tempfile(fileext = ".mcool") + fx <- make_test_mcool(mcool) + + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + + neoHic <- readNeoHic( + mcool, neo, resolution = 100, norm = "NONE", quiet = TRUE + ) + + expect_s3_class(neoHic, "neoHic") + expect_equal(neoHic$resolution, 100) + expect_equal(neoHic$neo$total_length, 800) + expect_equal(nrow(neoHic$pair_counts), 3) + expect_true(all(c("fragment1", "fragment2", "pixels", "counts") %in% + colnames(neoHic$pair_counts))) + expect_true(all(neoHic$matrix$x <= neoHic$matrix$y)) + expect_false(any(duplicated(neoHic$matrix[, c("x", "y")]))) + + expected <- fx$pixels[ + (fx$pixels$bin1_id %in% 0:3 & fx$pixels$bin2_id %in% 0:3) | + (fx$pixels$bin1_id %in% 0:3 & fx$pixels$bin2_id %in% 10:13) | + (fx$pixels$bin1_id %in% 10:13 & fx$pixels$bin2_id %in% 10:13), + ] + expect_equal(sum(neoHic$matrix$counts), sum(expected$count)) + + getCount <- function(x, y) { + neoHic$matrix$counts[neoHic$matrix$x == x & neoHic$matrix$y == y] + } + ## chr1 bin 0 (flipped to neo 300) vs chr2 bin 10 (neo 400) + expect_equal( + getCount(300, 400), + fx$pixels$count[fx$pixels$bin1_id == 0 & fx$pixels$bin2_id == 10] + ) + ## chr1 bin 1 (flipped to neo 200) vs chr2 bin 11 (neo 500) + expect_equal( + getCount(200, 500), + fx$pixels$count[fx$pixels$bin1_id == 1 & fx$pixels$bin2_id == 11] + ) +}) + +test_that("plotNeoHic creates a plot object", { + mcool <- withr::local_tempfile(fileext = ".mcool") + fx <- make_test_mcool(mcool) + + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + neoHic <- readNeoHic( + mcool, neo, resolution = 100, norm = "NONE", quiet = TRUE + ) + + pageCreate(width = 4, height = 3, default.units = "inches", + showGuides = FALSE) + plot <- plotNeoHic( + neoHic, type = "triangle", + x = 0.5, y = 0.5, width = 2, height = 1.5, + just = c("left", "top"), draw = FALSE + ) + expect_s3_class(plot, "hicTriangle") +}) + +test_that("readNeoHic accepts an assembly path and ID", { + mcool <- withr::local_tempfile(fileext = ".mcool") + fx <- make_test_mcool(mcool) + + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", + assembly + ) + + neoHic <- readNeoHic( + mcool, assembly, id = "C1", + resolution = 100, norm = "NONE", quiet = TRUE + ) + expect_s3_class(neoHic, "neoHic") + expect_equal(neoHic$neo$id, "C1") + expect_true(nrow(neoHic$matrix) > 0) +}) + +test_that("readNeoHic accepts precomputed genomic pair data", { + mcool <- withr::local_tempfile(fileext = ".mcool") + fx <- make_test_mcool(mcool) + + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + + binChrom <- ifelse(fx$pixels$bin1_id < fx$nBins1, "chr1", "chr2") + binChrom2 <- ifelse(fx$pixels$bin2_id < fx$nBins1, "chr1", "chr2") + pairData <- data.frame( + chrom1 = binChrom, + start1 = fx$starts[fx$pixels$bin1_id + 1], + chrom2 = binChrom2, + start2 = fx$starts[fx$pixels$bin2_id + 1], + counts = fx$pixels$count + ) + pairData <- pairData[ + (pairData$chrom1 == "chr1" & pairData$start1 < 400 & + pairData$chrom2 == "chr1" & pairData$start2 < 400) | + (pairData$chrom1 == "chr1" & pairData$start1 < 400 & + pairData$chrom2 == "chr2" & pairData$start2 < 400) | + (pairData$chrom1 == "chr2" & pairData$start1 < 400 & + pairData$chrom2 == "chr2" & pairData$start2 < 400), + ] + + fromFile <- readNeoHic( + mcool, neo, resolution = 100, norm = "NONE", quiet = TRUE + ) + fromDf <- readNeoHic( + pairData, neo, resolution = 100, quiet = TRUE + ) + + expect_equal(fromDf$matrix, fromFile$matrix) +}) + +test_that("annoNeoFragmentLabels supports coordinate and inversion labels", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + labels <- annoNeoFragmentLabels( + neo, + x = 0.5, y = 0.5, width = 3, + label.style = "coordinate", + label.position = "below", + label.offset = 0.05, + label.fontface = "italic", + show.inversion = TRUE + ) + expect_type(labels, "list") + expect_length(labels, 2) +}) + +test_that("plotNeoHic can flip the x-axis horizontally", { + mcool <- withr::local_tempfile(fileext = ".mcool") + fx <- make_test_mcool(mcool) + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines("C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", assembly) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + neoHic <- readNeoHic(mcool, neo, resolution = 100, + norm = "NONE", quiet = TRUE) + + pageCreate(width = 3, height = 3, default.units = "inches", + showGuides = FALSE) + hic <- plotNeoHic( + neoHic, type = "square", flip = "horizontal", + x = 0.5, y = 0.5, width = 2, height = 2, + draw = FALSE, zrange = c(0, 2) + ) + expect_equal(hic$xaxisRange, c(neo$total_length, 0)) + expect_equal(hic$xaxisDir, "decrease") + + tri <- plotNeoHic( + neoHic, type = "triangle", flip = "horizontal", + x = 0.5, y = 0.5, width = 2, height = 1, + draw = FALSE, zrange = c(0, 2) + ) + expect_equal(tri$xaxisRange, c(neo$total_length, 0)) + expect_equal(tri$xaxisDir, "decrease") +}) + +test_that("plotNeoGenes draws IGV-style gene bodies and exon blocks", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + + genes <- data.frame( + chrom = c("chr1", "chr1", "chr2", "chr2"), + start = c(100, 150, 100, 300), + end = c(120, 200, 180, 350), + strand = c("+", "+", "-", "-"), + gene = c("GENE1", "GENE1", "GENE2", "GENE3"), + feature = "exon", + gene_type = c("protein_coding", "protein_coding", + "protein_coding", "lncRNA") + ) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + res <- plotNeoGenes( + genes, neo, x = 0.5, y = 0.5, width = 3, height = 0.5, + labels = "GENE1", geneHighlights = "GENE1", + gene.type = "protein_coding", show.strand = TRUE, max.rows = 2 + ) + + ## lncRNA GENE3 is filtered out by gene.type + expect_setequal(unique(res$genes$gene), c("GENE1", "GENE2")) + ## Each gene is one row with a list of reduced exon intervals + expect_equal(nrow(res$genes), 2) + expect_equal(length(res$genes$exonStart[[1]]), 2) + ## IGV style: body segments plus exon rectangles + classes <- vapply(res$grobs, function(g) class(g)[1], character(1)) + expect_true("segments" %in% classes) + expect_true("rect" %in% classes) + ## Highlighted gene is red, non-highlighted gene stays black + expect_equal(res$grobs[[1]]$gp$col, "red") + grobCols <- vapply(res$grobs, function(g) { + if (is.null(g$gp$col)) NA_character_ else as.character(g$gp$col)[1] + }, character(1)) + expect_true("red" %in% grobCols) + expect_true("black" %in% grobCols) + + ## Exon blocks are centred on the gene body, not offset above it + body <- res$grobs[[1]] + exon <- res$grobs[[which(classes == "rect")[1]]] + expect_equal(as.numeric(exon$y), + as.numeric(body$y0) + as.numeric(exon$height) / 2) + expect_equal(exon$just, c(0, 1)) +}) + +test_that("plotNeoGenes can hide strand labels", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + genes <- data.frame( + chrom = "chr2", start = 100, end = 200, strand = "+", + gene = "GENE1", feature = "exon" + ) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + noStrand <- plotNeoGenes( + genes, neo, x = 0.5, y = 0.5, width = 3, height = 0.3, + labels = FALSE, show.strand = FALSE + ) + strand <- plotNeoGenes( + genes, neo, x = 0.5, y = 1, width = 3, height = 0.3, + labels = FALSE, show.strand = TRUE + ) + expect_false(any(vapply(noStrand$grobs, + function(g) identical(g$label, "+"), logical(1)))) + expect_true(any(vapply(strand$grobs, + function(g) identical(g$label, "+"), logical(1)))) +}) + +test_that("plotNeoAssembly and annoNeoDomains expose seam styling", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + + pageCreate(width = 4, height = 3, default.units = "inches", + showGuides = FALSE) + asm <- plotNeoAssembly( + neo, x = 0.5, y = 0.5, width = 3, height = 0.2, + labels = FALSE, seam.color = "purple", seam.lwd = 2, + seam.lty = 3 + ) + expect_equal(asm$seams[[1]]$gp$col, "purple") + expect_equal(asm$seams[[1]]$gp$lwd, 2) + expect_equal(asm$seams[[1]]$gp$lty, 3) + + domainPlot <- plotNeoHic( + readNeoHic( + { + mcool <- withr::local_tempfile(fileext = ".mcool") + make_test_mcool(mcool) + mcool + }, + neo, resolution = 100, norm = "NONE", quiet = TRUE + ), + type = "triangle", + x = 0.5, y = 1, width = 3, height = 1, + draw = FALSE, zrange = c(0, 2) + ) + domains <- annoNeoDomains( + domainPlot, neo, seam.color = "green", seam.lwd = 1.5, + seam.lty = 2 + ) + expect_equal(length(domains$seams), 1) + seamKids <- domains$seams[[1]]$grobs$children + expect_true(length(seamKids) > 0) + expect_equal(seamKids[[1]]$gp$col, "green") + expect_equal(seamKids[[1]]$gp$lwd, 1.5) + expect_equal(seamKids[[1]]$gp$lty, 2) +}) + +test_that("annoNeoFragmentLabels accepts explicit per-fragment colors", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + labels <- annoNeoFragmentLabels( + neo, x = 0.5, y = 0.5, width = 3, + labels = c("frag1", "frag2"), + label.colors = c("red", "green") + ) + expect_equal(labels[[1]]$gp$col, "red") + expect_equal(labels[[2]]$gp$col, "green") +}) + +test_that("plotNeoGenes reads arbitrary GTF files", { + skip_if_not_installed("rtracklayer") + gtf <- withr::local_tempfile(fileext = ".gtf") + writeLines(c( + 'chr1\tTEST\tgene\t100\t200\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', + 'chr1\tTEST\texon\t100\t120\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', + 'chr1\tTEST\texon\t180\t200\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', + 'chr1\tTEST\tgene\t300\t400\t.\t+\t.\tgene_id "G2"; gene_name "GENE2"; gene_type "lncRNA";', + 'chr1\tTEST\texon\t300\t400\t.\t+\t.\tgene_id "G2"; gene_name "GENE2"; gene_type "lncRNA";' + ), gtf) + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + res <- plotNeoGenes( + gtf, neo, x = 0.5, y = 0.5, width = 3, height = 0.3, + labels = "GENE1", gene.type = "protein_coding" + ) + expect_equal(unique(res$genes$gene), "GENE1") + expect_equal(length(res$genes$exonStart[[1]]), 2) +}) + +test_that("collapsed display mode draws solid gene blocks without exon ticks", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + genes <- data.frame( + chrom = "chr2", start = c(100, 300), end = c(200, 400), + strand = "+", gene = c("GENE1", "GENE2"), feature = "exon" + ) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + res <- plotNeoGenes( + genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.4, + displayMode = "collapsed", labels = FALSE, + show.strand = "none", max.rows = 2 + ) + + expect_equal(res$displayMode, "collapsed") + classes <- vapply(res$grobs, function(g) class(g)[1], character(1)) + expect_true(all(classes == "rect")) + minPx <- convertWidth(unit(3, "points"), unitTo = "inches", + valueOnly = TRUE) + widths <- vapply(res$grobs, function(g) as.numeric(g$width), numeric(1)) + expect_true(all(widths >= minPx - 1e-8)) +}) + +test_that("expanded display mode draws body lines and exon blocks", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + genes <- data.frame( + chrom = "chr2", start = c(100, 150), end = c(120, 220), + strand = "+", gene = "GENE1", feature = "exon" + ) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + res <- plotNeoGenes( + genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.4, + displayMode = "expanded", labels = FALSE, + show.strand = "none", max.rows = 1 + ) + + expect_equal(res$displayMode, "expanded") + classes <- vapply(res$grobs, function(g) class(g)[1], character(1)) + expect_true("segments" %in% classes) + expect_true("rect" %in% classes) + exon <- res$grobs[[which(classes == "rect")[1]]] + expect_equal(exon$just, c(0, 1)) + minPx <- convertWidth(unit(1, "points"), unitTo = "inches", + valueOnly = TRUE) + expect_gte(as.numeric(exon$width), minPx - 1e-8) +}) + +test_that("auto display mode switches on basepairs per inch", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + genes <- data.frame( + chrom = "chr2", start = 100, end = 200, strand = "+", + gene = "GENE1", feature = "exon" + ) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + collapsed <- plotNeoGenes( + genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, + displayMode = "auto", auto.collapse.bp.per.inch = 1, + labels = FALSE, show.strand = "none" + ) + expanded <- plotNeoGenes( + genes, neo, x = 0.5, y = 1, width = 2, height = 0.3, + displayMode = "auto", auto.collapse.bp.per.inch = 1e9, + labels = FALSE, show.strand = "none" + ) + expect_equal(collapsed$displayMode, "collapsed") + expect_equal(expanded$displayMode, "expanded") +}) + +test_that("chromstart and chromend clip and rescale the neo window", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + genes <- data.frame( + chrom = "chr2", start = c(100, 300), end = c(200, 400), + strand = "+", gene = c("GENE1", "GENE2"), feature = "exon" + ) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + res <- plotNeoGenes( + genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, + displayMode = "collapsed", chromstart = 620, chromend = 800, + labels = FALSE, show.strand = "none" + ) + expect_equal(res$genes$gene, "GENE2") + expect_equal(res$chromstart, 620) + expect_equal(res$chromend, 800) + ## chr2 fragment starts at neo 400, so 300 bp is neo 700. The window + ## starts at 620 and spans 180 bp. + expect_equal(as.numeric(res$grobs[[1]]$x), 0.5 + 80 / 180 * 2) +}) + +test_that("plotNeoGenes warns and drops genes when rows overflow", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + genes <- data.frame( + chrom = "chr2", start = c(100, 100, 100), end = c(300, 300, 300), + strand = "+", gene = c("G1", "G2", "G3"), feature = "exon" + ) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + expect_warning( + res <- plotNeoGenes( + genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, + displayMode = "collapsed", labels = FALSE, + show.strand = "none", max.rows = 1 + ), + "Not enough rows" + ) + expect_equal(nrow(res$genes), 1) +}) + +test_that("plotNeoGenes suppresses overlapping labels", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + genes <- data.frame( + chrom = "chr2", start = c(100, 150), end = c(140, 190), + strand = "+", gene = c("GENE1", "GENE2"), feature = "exon" + ) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + res <- plotNeoGenes( + genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, + displayMode = "collapsed", labels = c("GENE1", "GENE2"), + show.strand = "none", label.overlap = TRUE, max.rows = 1 + ) + texts <- Filter(function(g) class(g)[1] == "text", res$grobs) + labels <- vapply(texts, function(g) as.character(g$label), character(1)) + ys <- vapply(texts, function(g) as.numeric(g$y), numeric(1)) + expect_equal(sort(labels), c("GENE1", "GENE2")) + expect_false(isTRUE(all.equal(ys[1], ys[2]))) +}) + +test_that("single-exon genes are solid blocks in expanded mode", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + genes <- data.frame( + chrom = "chr2", start = 100, end = 200, strand = "+", + gene = "GENE1", feature = "exon" + ) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + res <- plotNeoGenes( + genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, + displayMode = "expanded", labels = FALSE, show.strand = "none" + ) + classes <- vapply(res$grobs, function(g) class(g)[1], character(1)) + expect_false("segments" %in% classes) + expect_true("rect" %in% classes) +}) + +test_that("UTR and CDS blocks use half and full heights", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + genes <- data.frame( + chrom = "chr2", + start = c(100, 160, 120, 160), + end = c(140, 220, 140, 200), + strand = "+", + gene = "GENE1", + feature = c("exon", "exon", "CDS", "CDS") + ) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + res <- plotNeoGenes( + genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, + displayMode = "expanded", labels = FALSE, show.strand = "none", + max.rows = 1 + ) + classes <- vapply(res$grobs, function(g) class(g)[1], character(1)) + heights <- vapply(res$grobs[classes == "rect"], + function(g) as.numeric(g$height), numeric(1)) + expect_equal(length(heights), 4) + expect_equal(heights[1] / heights[3], 0.5) + expect_equal(heights[2] / heights[4], 0.5) +}) + +test_that("strand arrows are emitted in collapsed mode", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + genes <- data.frame( + chrom = "chr2", start = 100, end = 300, strand = "+", + gene = "GENE1", feature = "exon" + ) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + res <- plotNeoGenes( + genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, + displayMode = "collapsed", labels = FALSE, + show.strand = "arrows" + ) + classes <- vapply(res$grobs, function(g) class(g)[1], character(1)) + expect_true("polygon" %in% classes) +}) + +test_that("plotNeoGenes reads CDS and UTR features from a GTF", { + skip_if_not_installed("rtracklayer") + gtf <- withr::local_tempfile(fileext = ".gtf") + writeLines(c( + 'chr2\tTEST\tgene\t100\t300\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', + 'chr2\tTEST\texon\t100\t140\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', + 'chr2\tTEST\texon\t200\t300\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', + 'chr2\tTEST\tCDS\t120\t140\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', + 'chr2\tTEST\tCDS\t200\t280\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', + 'chr2\tTEST\tUTR\t100\t120\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', + 'chr2\tTEST\tUTR\t280\t300\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";' + ), gtf) + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + res <- plotNeoGenes( + gtf, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, + displayMode = "expanded", labels = FALSE, show.strand = "none" + ) + expect_equal(nrow(res$genes), 1) + expect_equal(length(res$genes$cdsStart[[1]]), 2) + expect_equal(length(res$genes$exonStart[[1]]), 2) +}) + +test_that("plotNeoGenes accepts GRanges input", { + skip_if_not_installed("GenomicRanges") + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + gr <- GenomicRanges::GRanges( + "chr2", + IRanges::IRanges(100, 200), + strand = "+", + gene = "GENE1", + feature = "exon" + ) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + res <- plotNeoGenes( + gr, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, + displayMode = "expanded", labels = FALSE, show.strand = "none" + ) + expect_equal(nrow(res$genes), 1) + expect_equal(res$genes$gene, "GENE1") +}) + +test_that("squished display mode uses shorter rows than expanded", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + genes <- data.frame( + chrom = "chr2", start = 100, end = 200, strand = "+", + gene = "GENE1", feature = "exon" + ) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + expanded <- plotNeoGenes( + genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.4, + displayMode = "expanded", labels = FALSE, show.strand = "none" + ) + squished <- plotNeoGenes( + genes, neo, x = 0.5, y = 1, width = 2, height = 0.4, + displayMode = "squished", labels = FALSE, show.strand = "none" + ) + expect_equal(squished$displayMode, "squished") + expandedRect <- expanded$grobs[[which(vapply( + expanded$grobs, function(g) class(g)[1] == "rect", logical(1) + ))[1]]] + squishedRect <- squished$grobs[[which(vapply( + squished$grobs, function(g) class(g)[1] == "rect", logical(1) + ))[1]]] + expect_lt(as.numeric(squishedRect$height), as.numeric(expandedRect$height)) +}) + +test_that("geneBackground controls non-highlighted genes", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines( + "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", + assembly + ) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + genes <- data.frame( + chrom = "chr2", start = c(100, 300), end = c(200, 400), + strand = "+", gene = c("GENE1", "GENE2"), feature = "exon" + ) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + res <- plotNeoGenes( + genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, + displayMode = "collapsed", labels = FALSE, show.strand = "none", + geneHighlights = "GENE1", geneBackground = "grey" + ) + cols <- vapply(res$grobs, function(g) { + if (is.null(g$gp$col)) NA_character_ else as.character(g$gp$col)[1] + }, character(1)) + expect_true("red" %in% cols) + expect_true("grey" %in% cols) +}) + +test_that("geneOrder prioritizes labels", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines("C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", assembly) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + genes <- data.frame( + chrom = "chr2", start = c(100, 150), end = c(140, 190), + strand = "+", gene = c("LONGNAME1", "LONGNAME2"), feature = "exon" + ) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + res <- plotNeoGenes( + genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, + displayMode = "collapsed", labels = c("LONGNAME1", "LONGNAME2"), + geneOrder = c("LONGNAME2", "LONGNAME1"), show.strand = "none", + label.overlap = TRUE, max.rows = 1 + ) + texts <- Filter(function(g) class(g)[1] == "text", res$grobs) + labels <- vapply(texts, function(g) as.character(g$label), character(1)) + ys <- vapply(texts, function(g) as.numeric(g$y), numeric(1)) + ## Priority label stays on the lower level; the other is stacked above. + ## plotText stores bottom-based y, so the priority label sits lower. + expect_lt(ys[match("LONGNAME2", labels)], + ys[match("LONGNAME1", labels)]) +}) + +test_that("labelClusters draws rotated labels without stacking", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines("C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", assembly) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + genes <- data.frame( + chrom = "chr2", start = c(100, 150), end = c(140, 190), + strand = "+", gene = c("LONGNAME1", "LONGNAME2"), feature = "exon" + ) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + res <- plotNeoGenes( + genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, + displayMode = "collapsed", labels = c("LONGNAME1", "LONGNAME2"), + labelClusters = TRUE, labelClusterRot = 45, + show.strand = "none", label.overlap = TRUE, max.rows = 1 + ) + texts <- Filter(function(g) class(g)[1] == "text", res$grobs) + expect_equal(length(texts), 2) + ys <- vapply(texts, function(g) as.numeric(g$y), numeric(1)) + rots <- vapply(texts, function(g) as.numeric(g$grobs$rot), numeric(1)) + expect_equal(length(unique(ys)), 1) + expect_true(all(rots == 45)) +}) + +test_that("plotNeoGenes supports TxDb and OrgDb annotation", { + skip_if_not_installed("TxDb.Hsapiens.UCSC.hg38.knownGene") + skip_if_not_installed("org.Hs.eg.db") + suppressPackageStartupMessages({ + library(TxDb.Hsapiens.UCSC.hg38.knownGene) + library(org.Hs.eg.db) + }) + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines("C1\t12,65820000\t12,65830000", assembly) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + res <- plotNeoGenes( + data = TxDb.Hsapiens.UCSC.hg38.knownGene, + orgdb = org.Hs.eg.db, + neo = neo, x = 0.5, y = 0.5, width = 3, height = 0.5, + displayMode = "expanded", labels = "HMGA2", show.strand = "none" + ) + expect_true(any(res$genes$gene == "HMGA2")) + + res2 <- plotNeoGenes( + txdb = TxDb.Hsapiens.UCSC.hg38.knownGene, + orgdb = org.Hs.eg.db, + neo = neo, x = 0.5, y = 1.1, width = 3, height = 0.5, + displayMode = "collapsed", labels = FALSE, show.strand = "none" + ) + expect_true(any(res2$genes$gene == "HMGA2")) +}) + +test_that("GTF readers agree and cache the parsed annotation", { + skip_if_not_installed("rtracklayer") + gtf <- withr::local_tempfile(fileext = ".gtf") + writeLines(c( + 'chr2\tTEST\tgene\t100\t300\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', + 'chr2\tTEST\texon\t100\t140\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', + 'chr2\tTEST\texon\t200\t300\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";' + ), gtf) + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines("C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", assembly) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + fast <- plotNeoGenes( + gtf, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, + displayMode = "expanded", labels = FALSE, show.strand = "none", + reader = "readGFF" + ) + fallback <- plotNeoGenes( + gtf, neo, x = 0.5, y = 1, width = 2, height = 0.3, + displayMode = "expanded", labels = FALSE, show.strand = "none", + reader = "import" + ) + expect_equal(fast$genes$gene, fallback$genes$gene) + expect_equal(fast$genes$start, fallback$genes$start) + expect_equal(fast$genes$end, fallback$genes$end) + + cache <- withr::local_tempdir() + plotNeoGenes( + gtf, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, + displayMode = "collapsed", labels = FALSE, show.strand = "none", + reader = "readGFF", cache = cache + ) + expect_equal(length(list.files(cache)), 1) +}) + +test_that("tabix reader returns the same annotation", { + skip_if_not_installed("rtracklayer") + skip_if_not_installed("Rsamtools") + gtf <- withr::local_tempfile(fileext = ".gtf") + writeLines(c( + 'chr2\tTEST\tgene\t100\t300\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', + 'chr2\tTEST\texon\t100\t140\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', + 'chr2\tTEST\texon\t200\t300\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";' + ), gtf) + ## Tabix requires position-sorted input. + lines <- readLines(gtf) + fields <- strsplit(lines, "\t", fixed = TRUE) + ord <- order( + vapply(fields, `[`, character(1), 1), + as.numeric(vapply(fields, `[`, character(1), 4)) + ) + sorted <- withr::local_tempfile(fileext = ".gtf") + writeLines(lines[ord], sorted) + gz <- paste0(sorted, ".gz") + withr::defer(unlink(c(gz, paste0(gz, ".tbi")))) + Rsamtools::bgzip(sorted, dest = gz, overwrite = TRUE) + Rsamtools::indexTabix(gz, format = "gff") + + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines("C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", assembly) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + res <- plotNeoGenes( + gz, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, + displayMode = "expanded", labels = FALSE, show.strand = "none", + reader = "tabix" + ) + expect_equal(res$genes$gene, "GENE1") + expect_equal(length(res$genes$exonStart[[1]]), 2) +}) + +test_that("focus mode fades non-priority genes but keeps their exons", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines("C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", assembly) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + genes <- data.frame( + chrom = "chr2", + start = c(100, 220, 320, 370), + end = c(140, 300, 360, 390), + strand = "+", + gene = c("GENE1", "GENE1", "GENE2", "GENE2"), + feature = "exon" + ) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + res <- plotNeoGenes( + genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, + displayMode = "expanded", geneMode = "focus", focus.alpha = 0.5, + geneHighlights = "GENE1", geneBackground = "grey", + labels = "GENE1", show.strand = "arrows", max.rows = 1 + ) + expect_equal(res$geneMode, "focus") + rects <- Filter(function(g) class(g)[1] == "rect", res$grobs) + cols <- vapply(rects, function(g) as.character(g$gp$col)[1], character(1)) + alphas <- vapply(rects, function(g) as.numeric(g$gp$alpha)[1], numeric(1)) + expect_true(any(cols == "red" & alphas == 1)) + expect_true(any(cols == "grey" & alphas == 0.5)) + segments <- Filter(function(g) class(g)[1] == "segments", res$grobs) + segCols <- vapply(segments, function(g) as.character(g$gp$col)[1], + character(1)) + segAlphas <- vapply(segments, function(g) as.numeric(g$gp$alpha)[1], + numeric(1)) + expect_true(any(segCols == "grey" & segAlphas == 0.5)) + texts <- Filter(function(g) class(g)[1] == "text", res$grobs) + expect_equal(length(texts), 1) + expect_equal(texts[[1]]$label, "GENE1") +}) + +test_that("compact mode draws all genes in a single row", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines("C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", assembly) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + genes <- data.frame( + chrom = "chr2", + start = c(100, 220, 320, 370), + end = c(140, 300, 360, 390), + strand = "+", + gene = c("GENE1", "GENE1", "GENE2", "GENE2"), + feature = "exon" + ) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + res <- plotNeoGenes( + genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, + displayMode = "expanded", geneMode = "compact", + geneHighlights = "GENE1", show.strand = "none", max.rows = 4 + ) + expect_equal(res$geneMode, "compact") + expect_true(all(res$genes$row == 1)) + rects <- Filter(function(g) class(g)[1] == "rect", res$grobs) + cols <- vapply(rects, function(g) as.character(g$gp$col)[1], character(1)) + expect_true("red" %in% cols) + expect_true("grey" %in% cols) +}) + +test_that("focus mode keeps overflowing background genes on the last row", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines("C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", assembly) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + genes <- data.frame( + chrom = "chr2", start = c(100, 100, 100), end = c(300, 300, 300), + strand = "+", gene = c("GENE1", "GENE2", "GENE3"), feature = "exon" + ) + + pageCreate(width = 4, height = 2, default.units = "inches", + showGuides = FALSE) + res <- plotNeoGenes( + genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, + displayMode = "expanded", geneMode = "focus", + geneHighlights = "GENE1", labels = FALSE, + show.strand = "none", max.rows = 1 + ) + expect_equal(nrow(res$genes), 3) + expect_true(all(res$genes$row == 1)) +}) + +test_that("getNeoSignal maps and bins bigWig-like signal", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines("C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", assembly) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + signal <- data.frame( + chrom = c("chr1", "chr2"), + start = c(100, 100), end = c(200, 200), + score = c(2, 4) + ) + res <- getNeoSignal(signal, neo, binSize = 100) + expect_equal(res$chrom, rep("neo", 2)) + expect_equal(res$start, c(200, 500)) + expect_equal(res$end, c(299, 599)) + expect_equal(res$score, c(2, 4)) + + gr <- GenomicRanges::GRanges( + c("chr1", "chr2"), + IRanges::IRanges(c(100, 100), c(200, 200)), + score = c(2, 4) + ) + grRes <- getNeoSignal(gr, neo, binSize = 100) + expect_equal(grRes$start, c(200, 500)) + + window <- getNeoSignal(signal, neo, binSize = 100, + chromstart = 450, chromend = 650) + expect_equal(window$start, 500) +}) + +test_that("getNeoV4C maps virtual-4C tables", { + assembly <- withr::local_tempfile(fileext = ".assemblies.txt") + writeLines("C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", assembly) + neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) + tsv <- withr::local_tempfile(fileext = ".tsv") + writeLines(c( + "chrom\tstart\tend\tbalanced", + "chr2\t100\t200\t1.5", + "chr2\t200\t300\t2.5" + ), tsv) + res <- getNeoV4C(tsv, neo) + expect_equal(res$chrom, rep("neo", 2)) + expect_equal(res$start, c(500, 600)) + expect_equal(res$score, c(1.5, 2.5)) + expect_true(all(res$end < c(600, 700))) +}) diff --git a/tests/testthat/test-pageExport.R b/tests/testthat/test-pageExport.R new file mode 100644 index 000000000..55917a646 --- /dev/null +++ b/tests/testthat/test-pageExport.R @@ -0,0 +1,48 @@ +test_that("pageExport writes a single-page PDF without dev.off", { + pageCreate(width = 3, height = 3, default.units = "inches", + showGuides = TRUE) + plotRect(x = 0.5, y = 0.5, width = 2, height = 2, + fill = "green", default.units = "inches") + + out <- withr::local_tempfile(fileext = ".pdf") + pageExport(out) + expect_true(file.exists(out)) + expect_gt(file.info(out)$size, 0) + + raw <- readBin(out, what = "raw", n = file.info(out)$size) + pages <- length(grepRaw(charToRaw("/Type /Page /Parent"), raw, + all = TRUE)) + expect_equal(pages, 1) +}) + +test_that("pageExport supports raster output and guide hiding", { + pageCreate(width = 3, height = 3, default.units = "inches", + showGuides = TRUE) + plotRect(x = 0.5, y = 0.5, width = 2, height = 2, + fill = "green", default.units = "inches") + + out <- withr::local_tempfile(fileext = ".png") + pageExport(out, dpi = 100, guides = FALSE) + expect_true(file.exists(out)) + expect_gt(file.info(out)$size, 0) +}) + +test_that("pageGuideHide and pagePlotRemove are deferred to export", { + pageCreate(width = 3, height = 3, default.units = "inches", + showGuides = TRUE) + r <- plotRect(x = 0.5, y = 0.5, width = 1, height = 1, + fill = "green", default.units = "inches") + pageGuideHide(redraw = FALSE) + pagePlotRemove(r, redraw = FALSE) + + expect_true(get("guides_hidden", envir = plotgardener:::pgEnv)) + expect_true(r$grobs$name %in% + get("removed_plots", envir = plotgardener:::pgEnv)) + + out <- withr::local_tempfile(fileext = ".pdf") + pageExport(out) + raw <- readBin(out, what = "raw", n = file.info(out)$size) + pages <- length(grepRaw(charToRaw("/Type /Page /Parent"), raw, + all = TRUE)) + expect_equal(pages, 1) +}) diff --git a/tests/testthat/test-readCool.R b/tests/testthat/test-readCool.R new file mode 100644 index 000000000..561130749 --- /dev/null +++ b/tests/testthat/test-readCool.R @@ -0,0 +1,190 @@ +test_that(".checkCool recognizes mcool files with extra root groups", { + tmp <- withr::local_tempfile(fileext = ".mcool") + fx <- make_test_mcool(tmp) + expect_equal(.checkCool(tmp), ".mcool") +}) + +test_that("readCool returns every pixel in a multi-bin region", { + tmp <- withr::local_tempfile(fileext = ".mcool") + fx <- make_test_mcool(tmp) + + got <- readCool( + file = tmp, chrom = "chr1", + chromstart = 0, chromend = 300, + resolution = 100, norm = "NONE" + ) + + expected <- fx$pixels[ + fx$pixels$bin1_id %in% 0:3 & fx$pixels$bin2_id %in% 0:3, + ] + expect_equal(nrow(got), nrow(expected)) + expect_setequal(got$counts, expected$count) + + ## The last bin (bin 3) must actually be present + expect_true(any(got[[1]] == 300 | got[[2]] == 300)) +}) + +test_that("readCool uses multiplicative cooler weights", { + tmp <- withr::local_tempfile(fileext = ".mcool") + fx <- make_test_mcool(tmp) + + got <- readCool( + file = tmp, chrom = "chr1", + chromstart = 0, chromend = 300, + resolution = 100, norm = "weight" + ) + + expected <- fx$pixels[ + fx$pixels$bin1_id %in% 0:3 & fx$pixels$bin2_id %in% 0:3, + ] + expectedCounts <- expected$count * + fx$weight[expected$bin1_id + 1] * + fx$weight[expected$bin2_id + 1] + + expect_equal(got$counts, expectedCounts) +}) + +test_that("readCool supports sweight and auto normalization", { + tmp <- withr::local_tempfile(fileext = ".mcool") + fx <- make_test_mcool(tmp) + + expect_equal(readCoolBpResolutions(tmp), 100) + expect_true("sweight" %in% readCoolNorms(tmp, resolution = 100)) + expect_true("weight" %in% readCoolNorms(tmp, resolution = 100)) + + expect_equal(.coolAutoNorm(tmp, resolution = 100), "weight") + + got <- readCool( + file = tmp, chrom = "chr1", + chromstart = 0, chromend = 200, + resolution = 100, norm = "sweight" + ) + expect_true(nrow(got) > 0) + + gotAuto <- readCool( + file = tmp, chrom = "chr1", + chromstart = 0, chromend = 200, + resolution = 100, norm = "auto" + ) + expect_true(nrow(gotAuto) > 0) + + gotWeight <- readCool( + file = tmp, chrom = "chr1", + chromstart = 0, chromend = 200, + resolution = 100, norm = "weight" + ) + expect_true(nrow(gotWeight) > 0) +}) + +test_that("readCool matches chromosome names with and without chr", { + tmp <- withr::local_tempfile(fileext = ".mcool") + fx <- make_test_mcool(tmp) + + got <- readCool( + file = tmp, chrom = "1", + chromstart = 0, chromend = 200, + resolution = 100, norm = "NONE" + ) + expect_true(nrow(got) > 0) + expect_true(all(grepl("chr1", colnames(got)[1:2]))) +}) + +test_that("readCool handles regions that are not bin-aligned", { + tmp <- withr::local_tempfile(fileext = ".mcool") + fx <- make_test_mcool(tmp) + + got <- readCool( + file = tmp, chrom = "chr1", + chromstart = 51, chromend = 349, + resolution = 100, norm = "NONE" + ) + expected <- fx$pixels[ + fx$pixels$bin1_id %in% 0:3 & fx$pixels$bin2_id %in% 0:3, + ] + expect_equal(nrow(got), nrow(expected)) +}) + +test_that("readCool returns interchromosomal contacts", { + tmp <- withr::local_tempfile(fileext = ".mcool") + fx <- make_test_mcool(tmp) + + got <- readCool( + file = tmp, chrom = "chr1", + chromstart = 0, chromend = 300, + altchrom = "chr2", altchromstart = 0, altchromend = 300, + resolution = 100, norm = "NONE" + ) + + expected <- fx$pixels[ + fx$pixels$bin1_id %in% 0:3 & fx$pixels$bin2_id %in% 10:13, + ] + expect_equal(nrow(got), nrow(expected)) + expect_setequal(got$counts, expected$count) +}) + +test_that("readCool chunked reading matches unchunked reading", { + tmp <- withr::local_tempfile(fileext = ".mcool") + fx <- make_test_mcool(tmp) + + full <- readCool( + file = tmp, chrom = "chr1", + chromstart = 0, chromend = 500, + resolution = 100, norm = "NONE" + ) + chunked <- readCool( + file = tmp, chrom = "chr1", + chromstart = 0, chromend = 500, + resolution = 100, norm = "NONE", + binChunkSize = 5 + ) + + expect_equal(chunked, full) +}) + +test_that("readCool drops contacts with non-finite weights", { + tmp <- withr::local_tempfile(fileext = ".mcool") + fx <- make_test_mcool(tmp) + + got <- readCool( + file = tmp, chrom = "chr1", + chromstart = 900, chromend = 1000, + resolution = 100, norm = "weight" + ) + + ## bin 9 has a NaN weight, so all of its contacts should be dropped + expect_equal(nrow(got), 0) +}) + +test_that("readCool reads interchromosomal pixels in reverse chromosome order", { + tmp <- withr::local_tempfile(fileext = ".mcool") + fx <- make_test_mcool(tmp) + + ## chr2 comes after chr1 in the file, so this query is in reverse order. + got <- readCool( + file = tmp, chrom = "chr2", + chromstart = 0, chromend = 300, + altchrom = "chr1", altchromstart = 0, altchromend = 300, + resolution = 100, norm = "NONE" + ) + expected <- fx$pixels[ + fx$pixels$bin1_id %in% 0:3 & fx$pixels$bin2_id %in% 10:13, + ] + expect_equal(nrow(got), nrow(expected)) + expect_setequal(got$counts, expected$count) +}) + +test_that("readCool expands same-chromosome off-diagonal regions symmetrically", { + tmp <- withr::local_tempfile(fileext = ".mcool") + fx <- make_test_mcool(tmp) + + got <- readCool( + file = tmp, chrom = "chr1", + chromstart = 0, chromend = 300, + altchrom = "chr1", altchromstart = 500, altchromend = 800, + resolution = 100, norm = "NONE" + ) + expected <- fx$pixels[ + fx$pixels$bin1_id %in% 0:8 & fx$pixels$bin2_id %in% 0:8, + ] + expect_equal(nrow(got), nrow(expected)) +}) diff --git a/tests/testthat/test-reading-order.R b/tests/testthat/test-reading-order.R new file mode 100644 index 000000000..df16271c7 --- /dev/null +++ b/tests/testthat/test-reading-order.R @@ -0,0 +1,30 @@ +test_that("read_rangeData respects named range columns in any order", { + df <- data.frame( + start = c(1, 10), + chrom = c("chr1", "chr2"), + end = c(5, 20), + score = c(1, 2) + ) + out <- plotgardener:::read_rangeData( + data = df, assembly = "hg38", type = "range" + ) + expect_equal(colnames(out)[1:3], c("chrom", "start", "end")) + expect_equal(out$chrom, c("chr1", "chr2")) + expect_equal(out$start, c(1, 10)) + expect_equal(out$end, c(5, 20)) +}) + +test_that("read_rangeData respects named GWAS columns in any order", { + df <- data.frame( + p = c(0.1, 0.2), + chrom = c("chr1", "chr2"), + pos = c(100, 200), + snp = c("rs1", "rs2") + ) + out <- plotgardener:::read_rangeData( + data = df, assembly = "hg38", type = "GWAS" + ) + expect_equal(colnames(out)[1:2], c("chrom", "pos")) + expect_equal(out$chrom, c("chr1", "chr2")) + expect_equal(out$pos, c(100, 200)) +}) diff --git a/tests/testthat/test-readingFunctions.R b/tests/testthat/test-readingFunctions.R index dc53c42c1..6621781c0 100644 --- a/tests/testthat/test-readingFunctions.R +++ b/tests/testthat/test-readingFunctions.R @@ -85,8 +85,12 @@ test_that("readCool", { ## .cool file coolFile <- file.path(tempdir(), "Rao2014-IMR90-MboI-allreps-filtered.1000kb.cool") - download.file(url = "https://usgs2.osn.mghpcc.org/cooler01/examples/hg19/Rao2014-IMR90-MboI-allreps-filtered.1000kb.cool", - destfile = coolFile, mode = "wb") + downloaded <- tryCatch({ + download.file(url = "https://usgs2.osn.mghpcc.org/cooler01/examples/hg19/Rao2014-IMR90-MboI-allreps-filtered.1000kb.cool", + destfile = coolFile, mode = "wb") + TRUE + }, error = function(e) FALSE) + if (!downloaded) skip("Could not download the .cool test file.") on.exit(unlink(coolFile)) # File type @@ -98,13 +102,13 @@ test_that("readCool", { expect_error(readCoolChroms(file = coolFile, resolution = 5000), "resolution") # Norms - expect_equal(readCoolNorms(file = coolFile), c("BALANCE", "NONE")) + expect_equal(readCoolNorms(file = coolFile), c("weight", "NONE")) # Chroms cool_chroms <- readCoolChroms(file = coolFile) |> pull(name) expect_setequal(cool_chroms, paste0("chr", c(seq(1:22), "X", "Y", "M"))) - expect_error(.checkCoolErrors(file = coolFile, chrom = "2", + expect_error(.checkCoolErrors(file = coolFile, chrom = "chrZZ", chromstart = NULL, chromend = NULL, zrange = NULL, altchrom = NULL, altchromstart = NULL, altchromend = NULL, @@ -113,8 +117,12 @@ test_that("readCool", { ## .mcool file mcoolFile <- file.path(tempdir(), "LEUK_HEK_PJA27_inter_30.mcool") - download.file(url = "https://zenodo.org/records/10906240/files/LEUK_HEK_PJA27_inter_30.mcool?download=1", - destfile = mcoolFile, mode = "wb") + downloaded <- tryCatch({ + download.file(url = "https://zenodo.org/records/10906240/files/LEUK_HEK_PJA27_inter_30.mcool?download=1", + destfile = mcoolFile, mode = "wb") + TRUE + }, error = function(e) FALSE) + if (!downloaded) skip("Could not download the .mcool test file.") on.exit(unlink(mcoolFile)) # File type @@ -136,7 +144,7 @@ test_that("readCool", { # Chroms expect_type(readCoolChroms(file = mcoolFile), "list") - expect_error(.checkCoolErrors(file = mcoolFile, chrom = "chr2", + expect_error(.checkCoolErrors(file = mcoolFile, chrom = "chrZZ", chromstart = NULL, chromend = NULL, zrange = NULL, altchrom = NULL, altchromstart = NULL, altchromend = NULL, diff --git a/tests/testthat/test-signal-fixes.R b/tests/testthat/test-signal-fixes.R new file mode 100644 index 000000000..49e18ce4b --- /dev/null +++ b/tests/testthat/test-signal-fixes.R @@ -0,0 +1,70 @@ +test_that("plotSignal baseline is drawn last and can be disabled", { + signalData <- data.frame( + chrom = "chr1", + start = seq(1, 901, by = 100), + end = seq(100, 1000, by = 100), + score = rep(10, 10) + ) + + pageCreate(width = 4, height = 3, default.units = "inches", + showGuides = FALSE) + withBaseline <- plotSignal( + signalData, chrom = "chr1", chromstart = 1, chromend = 1000, + assembly = "hg38", fill = "steelblue", binSize = 100, + x = 0.5, y = 0.5, width = 3, height = 1, + draw = FALSE, baseline = TRUE + ) + withoutBaseline <- plotSignal( + signalData, chrom = "chr1", chromstart = 1, chromend = 1000, + assembly = "hg38", fill = "steelblue", binSize = 100, + x = 0.5, y = 1.6, width = 3, height = 1, + draw = FALSE, baseline = FALSE + ) + + expect_equal( + length(withBaseline$grobs$children), + length(withoutBaseline$grobs$children) + 1 + ) +}) + +test_that("plotSignal label position is configurable", { + signalData <- data.frame( + chrom = "chr1", + start = seq(1, 901, by = 100), + end = seq(100, 1000, by = 100), + score = rep(10, 10) + ) + pageCreate(width = 4, height = 3, default.units = "inches", + showGuides = FALSE) + sig <- plotSignal( + signalData, chrom = "chr1", chromstart = 1, chromend = 1000, + assembly = "hg38", binSize = 100, + x = 0.5, y = 0.5, width = 3, height = 1, + draw = FALSE, label = "custom", label.position = "bottom-right" + ) + expect_true(any(vapply( + sig$grobs$children, + function(g) identical(g$label, "custom"), + logical(1) + ))) +}) + +test_that("plotMultiSignal honors a user-supplied range", { + signalData <- data.frame( + chrom = "chr1", + start = seq(1, 901, by = 100), + end = seq(100, 1000, by = 100), + score = rep(10, 10) + ) + pageCreate(width = 4, height = 3, default.units = "inches", + showGuides = FALSE) + sigs <- plotMultiSignal( + list(signalData, signalData), + chrom = "chr1", chromstart = 1, chromend = 1000, + assembly = "hg38", range = c(0, 250), binSize = 100, + x = 0.5, y = 0.5, width = 3, height = 2, + draw = FALSE, label = c("A", "B") + ) + expect_equal(sigs[[1]]$range, c(0, 250)) + expect_equal(sigs[[2]]$range, c(0, 250)) +}) diff --git a/vignettes/neo_reconstruction.Rmd b/vignettes/neo_reconstruction.Rmd new file mode 100644 index 000000000..9206038dc --- /dev/null +++ b/vignettes/neo_reconstruction.Rmd @@ -0,0 +1,304 @@ +--- +title: "Reconstructing SV-impacted Hi-C maps with plotgardener" +output: rmarkdown::html_vignette +vignette: > + %\VignetteIndexEntry{Reconstructing SV-impacted Hi-C maps with plotgardener} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + +```{r setup, include=FALSE} +knitr::opts_chunk$set( + collapse = TRUE, + comment = "#>", + eval = FALSE +) +``` + +This vignette describes how to go from structural variant (SV) assemblies to a +reconstructed neo-chromosome Hi-C map. The assembly file format is the one +produced by [NeoLoopFinder](https://github.com/XiaoTaoWang/NeoLoopFinder) +`assemble-complexSVs`. + +## 1. Get SV assemblies from NeoLoopFinder + +NeoLoopFinder expects a six-column SV list: + +```text +chr7 chr14 ++ 14000000 37500000 translocation +chr7 chr14 -- 7901149 37573191 translocation +``` + +The columns are: + +1. `chrA`: chromosome of the first breakpoint. +2. `chrB`: chromosome of the second breakpoint. +3. `orientation`: `++`, `+-`, `-+`, or `--`. +4. `b1`: first breakpoint position on `chrA`. +5. `b2`: second breakpoint position on `chrB`. +6. `type`: `deletion`, `inversion`, `duplication`, or `translocation`. + +Then run `assemble-complexSVs`, for example: + +```bash +assemble-complexSVs \ + -O SKNMC \ + -B SKNMC-EagleC.SV.txt \ + --balance-type CNV \ + --protocol insitu \ + --nproc 6 \ + -H SKNMC-MboI-allReps-filtered.mcool::resolutions/25000 \ + SKNMC-MboI-allReps-filtered.mcool::resolutions/10000 \ + SKNMC-MboI-allReps-filtered.mcool::resolutions/5000 +``` + +This produces `SKNMC.assemblies.txt`. A typical file looks like this: + +```text +A0 inversion,8,132915000,+,8,130825000,+ deletion,8,130800000,-,8,129520000,+ 8,132155000 8,129375000 +A1 inversion,11,84315000,-,11,83565000,- inversion,11,84315000,+,11,83565000,+ 11,85050000 11,82625000 +C0 translocation,1,10260000,+,X,21495000,- 1,9380000 X,22205000 +C1 translocation,1,10260000,-,X,21495000,+ 1,10630000 X,20080000 +``` + +## 2. Understand the assembly file format + +Each non-empty line is one assembly: + +```text + +``` + +The fields are tab-separated: + +- `assembly_id`: a unique ID such as `C1`, `A0`, or `C16`. +- `SV records`: zero or more SV records, each formatted as + `type,chrA,b1,strandA,chrB,b2,strandB`. +- `span1`: the first assembled span, formatted as `chr,position`. +- `span2`: the last assembled span, formatted as `chr,position`. + +The SV records and spans define the ordered nodes of the neo-chromosome: + +```text +span1 position + -> SV1 chrA position + -> SV1 chrB position + -> SV2 chrA position + -> SV2 chrB position + -> ... + -> span2 position +``` + +Consecutive node pairs become fragments. A fragment is marked as flipped when +its entry position is greater than its exit position. For example: + +```text +C1 translocation,12,65690000,-,14,68280000,+ 12,66455000 14,67645000 +``` + +This gives: + +| fragment | chromosome | interval | orientation | +|---|---|---|---| +| 1 | chr12 | 65690000-66455000 | flipped | +| 2 | chr14 | 67645000-68280000 | flipped | + +`readNeoAssembly()` reproduces this topology, applies optional end extension, +and assigns cumulative `offset` and `length` values in the concatenated +neo-chromosome. + +```{r read-assembly, eval=FALSE} +library(plotgardener) + +neo <- readNeoAssembly( + file = "HM1_merged.assemblies.txt", + id = "C1", + assembly = "hg38", + extend = 200000 +) +neo +neo$fragments +``` + +### Custom assembly files + +You can also create an assembly file yourself. It must contain at least one +tab-separated line with an ID, the SV record(s), and the two spans: + +```text +C1 translocation,1,0,-,2,0,+ 1,400 2,400 +``` + +Here `chr1:0-400` is reverse-complemented and `chr2:0-400` is forward, giving a +400 bp + 400 bp neo-chromosome. + +### Chromosome names and coordinates + +- `readNeoAssembly()` adds a `chr` prefix when it is missing. Set + `prefix = ""` if your data uses unprefixed names. +- Positions are used as supplied. `.hic` readers are 1-based and `.cool` + readers use 0-based bin starts; plotgardener handles the source-specific + bin starts when mapping. +- `extend` adds bases only to the first and last fragments, matching the + common NeoLoopFinder visualization convention. + +## 3. Reconstruct the neo-chromosome matrix + +`readNeoHic()` reads each fragment pair from a `.hic`, `.cool`, or `.mcool` +file and maps the contacts into neo-chromosome coordinates. + +Use the exact normalization column stored in the file. For NeoLoopFinder +workflows, this is often `sweight` (from `correct-cnv`) or `weight` (ICE): + +```{r read-neohic, eval=FALSE} +neo <- readNeoAssembly( + file = "HM1_merged.assemblies.txt", + id = "C1", + extend = 200000 +) + +neoHic <- readNeoHic( + data = "HM1_merged-Arima-R1-filtered.mcool", + neo = neo, + resolution = 5000, + norm = "sweight" +) + +neoHic +head(neoHic$matrix) +``` + +You can also pass the assembly file and ID directly: + +```{r read-neohic-path, eval=FALSE} +neoHic <- readNeoHic( + data = "HM1_merged-Arima-R1-filtered.mcool", + neo = "HM1_merged.assemblies.txt", id = "C1", + extend = 200000, resolution = 5000, norm = "sweight" +) +``` + +`readNeoHic()` also accepts a precomputed genomic pair data frame with +columns `chrom1`, `start1`, `chrom2`, `start2`, and `counts`: + +```{r read-neohic-df, eval=FALSE} +neoHic <- readNeoHic( + data = pairData, neo = neo, + resolution = 5000 +) +``` + +Check the available columns with: + +```{r norms, eval=FALSE} +readCoolNorms( + "HM1_merged-Arima-R1-filtered.mcool", + resolution = 5000 +) +``` + +The reconstruction keeps bins in the coordinate space but drops contacts whose +normalization weight is missing or non-finite, matching the usual NeoLoopFinder +visualization behavior. + +## 4. Plot the reconstruction + +```{r plot-neo, eval=FALSE} +pageCreate(width = 5.5, height = 6, default.units = "inches", + showGuides = FALSE) + +hicPlot <- plotNeoHic( + neoHic, + type = "triangle", + x = 1, y = 0.9, width = 3.4, height = 1.9, + just = c("left", "top"), + zrange = c(0, 0.005), + palette = colorRampPalette(c("white", "#FFDFDF", "#FF7575", + "#FF2626", "#F70000")) +) + +## Solid outer neo-chromosome domain + dotted internal seams +annoNeoDomains(hicPlot, neo) + +## Fragment backbone with directional arrows +plotNeoAssembly( + neo, + x = 1, y = 3.05, width = 3.4, height = 0.16, + just = c("left", "top"), + fill = "#D4EEF9", + labels = TRUE, + show.seams = TRUE +) +``` + +For more control over fragment labels, turn labels off in the backbone and use +`annoNeoFragmentLabels()`: + +```{r neo-labels, eval=FALSE} +plotNeoAssembly( + neo, + x = 1, y = 3.05, width = 3.4, height = 0.16, + just = c("left", "top"), + labels = FALSE +) +annoNeoFragmentLabels( + neo, + x = 1, y = 3.3, width = 3.4, + label.style = "coordinate", + label.position = "below", + label.offset = 0.05, + label.fontsize = 7, + label.fontface = "italic", + label.fontcolor = "black", + show.inversion = TRUE, + inversion.color = "red" +) +``` + +`annoNeoFragmentLabels()` supports chromosome, coordinate, or fragment-number +labels, custom fonts/colors/rotation, vertical offsets, and inversion marking. + +`annoNeoDomains()` is the functional equivalent of the dotted seam/domain +annotations in the NeoLoopFinder triangle examples: + +- outer domain outline: solid, controlled by `lty` +- internal fragment seams: dotted, controlled by `seam.lty` + +## 5. Map genes and other features + +`mapNeoFeatures()` maps BED-like data or a `GRanges` object into the +neo-chromosome coordinate system: + +```{r map-features, eval=FALSE} +genes <- data.frame( + chrom = "chr12", + start = 65822483, + end = 65968291, + name = "HMGA2", + strand = "+" +) + +mapNeoFeatures(genes, neo) +``` + +For features that span a fragment boundary, the feature is split across +fragments. Strand is inverted for reverse-complemented fragments. + +## 6. Practical notes + +- Use a resolution that gives a reasonable number of bins across the + neo-chromosome. `resolution = "auto"` targets roughly 1,000 bins. +- For NeoLoopFinder, run `correct-cnv` first if you want `sweight` + normalization. +- If your `.cool`/`.mcool` chromosome names lack `chr`, either add the prefix + as recommended by NeoLoopFinder or let `readNeoAssembly()` add it to the + assembly side and use `readCoolNorms()` to verify the file side. +- `readNeoHic()` uses the existing `readHic()`/`readCool()` readers, so the + raw contact extraction is the same as for ordinary plotgardener Hi-C plots. + +## References + +- Wang X, Xu J, Zhang B, Hou Y, Song F, Lyu H, Yue F. Genome-wide detection of + enhancer-hijacking events from chromatin interaction data in rearranged + genomes. *Nature Methods* (2021). +- NeoLoopFinder: From 7e50afafdc7244091143bb4aac0692c30d804bd7 Mon Sep 17 00:00:00 2001 From: plotgardenerNeo contributors Date: Thu, 12 Nov 2026 16:30:51 -0600 Subject: [PATCH 2/2] Add core plotgardener fixes and rendering updates --- DESCRIPTION | 2 - NAMESPACE | 12 - NEWS.md | 30 - R/neoAssembly.R | 300 ------- R/neoSignal.R | 202 ----- R/plotNeo.R | 1341 ------------------------------ R/readNeoGenes.R | 379 --------- R/readNeoHic.R | 548 ------------ man/annoNeoDomains.Rd | 67 -- man/annoNeoFragmentLabels.Rd | 120 --- man/getNeoSignal.Rd | 46 - man/getNeoV4C.Rd | 30 - man/mapNeoFeatures.Rd | 33 - man/plotNeoAssembly.Rd | 104 --- man/plotNeoGenes.Rd | 190 ----- man/plotNeoHic.Rd | 40 - man/readNeoAssembly.Rd | 66 -- man/readNeoHic.Rd | 85 -- tests/testthat/test-neo.R | 1049 ----------------------- vignettes/neo_reconstruction.Rmd | 304 ------- 20 files changed, 4948 deletions(-) delete mode 100644 R/neoAssembly.R delete mode 100644 R/neoSignal.R delete mode 100644 R/plotNeo.R delete mode 100644 R/readNeoGenes.R delete mode 100644 R/readNeoHic.R delete mode 100644 man/annoNeoDomains.Rd delete mode 100644 man/annoNeoFragmentLabels.Rd delete mode 100644 man/getNeoSignal.Rd delete mode 100644 man/getNeoV4C.Rd delete mode 100644 man/mapNeoFeatures.Rd delete mode 100644 man/plotNeoAssembly.Rd delete mode 100644 man/plotNeoGenes.Rd delete mode 100644 man/plotNeoHic.Rd delete mode 100644 man/readNeoAssembly.Rd delete mode 100644 man/readNeoHic.Rd delete mode 100644 tests/testthat/test-neo.R delete mode 100644 vignettes/neo_reconstruction.Rmd diff --git a/DESCRIPTION b/DESCRIPTION index f6b34b534..e520132f3 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -65,7 +65,6 @@ Suggests: BSgenome, BSgenome.Hsapiens.UCSC.hg19, ComplexHeatmap, - digest, ensembldb, GenomicFeatures, ggplot2, @@ -73,7 +72,6 @@ Suggests: knitr, org.Hs.eg.db, rtracklayer, - Rsamtools, plotgardenerData, pdftools, png, diff --git a/NAMESPACE b/NAMESPACE index 72bfe44d1..802179620 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -4,8 +4,6 @@ export(annoDomains) export(annoGenomeLabel) export(annoHeatmapLegend) export(annoHighlight) -export(annoNeoDomains) -export(annoNeoFragmentLabels) export(annoPixels) export(annoSegments) export(annoText) @@ -18,10 +16,7 @@ export(calcSignalRange) export(colorby) export(defaultPackages) export(genomes) -export(getNeoSignal) -export(getNeoV4C) export(mapColors) -export(mapNeoFeatures) export(pageCreate) export(pageExport) export(pageGuideHide) @@ -45,9 +40,6 @@ export(plotIdeogram) export(plotLegend) export(plotManhattan) export(plotMultiSignal) -export(plotNeoAssembly) -export(plotNeoHic) -export(plotNeoGenes) export(plotPairs) export(plotPairsArches) export(plotPolygon) @@ -64,8 +56,6 @@ export(readCoolBpResolutions) export(readCoolChroms) export(readCoolNorms) export(readHic) -export(readNeoAssembly) -export(readNeoHic) import(grid) importFrom(GenomeInfoDb,keepStandardChromosomes) importFrom(GenomicRanges,GRanges) @@ -110,6 +100,4 @@ importFrom(strawr,straw) importFrom(tools,file_ext) importFrom(utils,str) importFrom(withr,with_pdf) -S3method(print,neoAssembly) -S3method(print,neoHic) useDynLib(plotgardener) diff --git a/NEWS.md b/NEWS.md index 3a5c19cc5..1be6f65f1 100644 --- a/NEWS.md +++ b/NEWS.md @@ -18,44 +18,14 @@ `axisLine.lwd/col/lty`, and `tick.lwd/col/lty` for flexible axis styling. Default tick length is now shorter (`tcl = 0.25`) and default tick/axis line width is thinner (`0.5`). -* `plotNeoGenes()` now uses IGV-style display modes. `displayMode = "auto"` - collapses genes to solid blocks at whole-chromosome scale and expands to - gene bodies, exon blocks, UTR/CDS heights, and strand arrows when zoomed - in. It supports `chromstart`/`chromend` neo-coordinate windows, arbitrary - GTF/GFF GENCODE versions, `TxDb`/`OrgDb` annotations, `geneOrder`, - `labelClusters`, `geneBackground`, configurable colors, gene highlights, - label collision suppression, row-overflow warnings, and `geneMode` - layouts: `"expand"` draws all genes normally, `"focus"` fades non-priority - genes with `focus.alpha`, and `"compact"` draws all genes on one line. - GTF/GFF files are read with `readGFF()` by default and can use an optional - disk cache. -* Added `getNeoSignal()` and `getNeoV4C()` for mapping bigWig, GRanges, - data-frame, and virtual-4C signal tracks into neo-chromosome coordinates, - with optional binning and aggregation. -* `plotNeoHic(flip = "horizontal")` reverses the x-axis for neo Hi-C plots. -* `annoNeoDomains()` and `plotNeoAssembly()` expose separate seam color, - width, and line type, and `annoNeoFragmentLabels(label.colors=)` supports - per-fragment label colors. * Interchromosomal `plotHicSquare()` plots are no longer mirrored and store explicit x/y chromosome metadata for `annoGenomeLabel()`. Add `aspect = "fixed"` for equal basepairs-per-inch on unequal-length chromosomes. -* Added SV-impacted neo-chromosome reconstruction helpers: - `readNeoAssembly()`, `mapNeoFeatures()`, `readNeoHic()`, `plotNeoHic()`, - `plotNeoAssembly()`, `annoNeoDomains()`, and `annoNeoFragmentLabels()`. - `readNeoHic()` stitches fragment-pair contacts from `.hic`, `.cool`, or - `.mcool` files into a concatenated neo-chromosome coordinate system. - `annoNeoDomains()` draws the solid outer neo-chromosome domain and dotted - internal fragment seams used in the neo-triangle examples. - * `plotTranscripts()` adds `labelPriority` and centers labels on the in-bounds transcript portion. * `plotGenes()` adds `labelClusters`/`labelClusterRot` for dense gene clusters. -* Added `plotNeoGenes()` for gene/transcript models mapped into neo - coordinates, including strand flips, gene highlights, and selected labels. `readNeoHic()` now reports - fragment-pair contact counts and warns when inter-fragment pairs have no - source contacts. * `assembly()` accepts an `EnsDb` object and converts it to a TxDb for plotting. * `read_rangeData()` respects named `chrom`/`start`/`end` or `chrom`/`pos` diff --git a/R/neoAssembly.R b/R/neoAssembly.R deleted file mode 100644 index c4893e36d..000000000 --- a/R/neoAssembly.R +++ /dev/null @@ -1,300 +0,0 @@ -#' Read an SV neo-chromosome assembly topology -#' -#' Parse an assembly file from a neoloop/SV workflow and build a -#' `neoAssembly` object describing the concatenated neo-chromosome. -#' -#' @param file Path to an `.assemblies.txt` file. -#' @param id Assembly ID to extract, for example `"C1"`. -#' @param assembly Genome assembly name. Default value is -#' \code{assembly = "hg38"}. -#' @param extend Number of basepairs to extend the first and last fragment. -#' Default value is \code{extend = 0}. -#' @param prefix Prefix to add to chromosome names that do not already have -#' one. Default value is \code{prefix = "chr"}. -#' @param quiet A logical indicating whether to print messages. -#' -#' @return A `neoAssembly` object: a list with \code{id}, \code{fragments}, -#' \code{total_length}, and \code{assembly}. \code{fragments} is a data frame -#' with columns \code{id}, \code{chrom}, \code{chrom_raw}, \code{start}, -#' \code{end}, \code{flipped}, \code{offset}, and \code{length}. -#' -#' @details -#' Assembly lines are usually produced by NeoLoopFinder's -#' \code{assemble-complexSVs}. Each line contains an assembly ID, zero or more -#' SV records (\code{type,chrA,b1,strandA,chrB,b2,strandB}), and two span -#' coordinates (\code{chr,position}). Consecutive node pairs define fragments; -#' a fragment is flipped when its entry position is greater than its exit -#' position. See \code{vignette("neo_reconstruction")} for a full description -#' and examples. -#' -#' @references -#' Wang X, Xu J, Zhang B, Hou Y, Song F, Lyu H, Yue F. Genome-wide detection of -#' enhancer-hijacking events from chromatin interaction data in rearranged -#' genomes. Nature Methods (2021). -#' -#' @examples -#' \dontrun{ -#' neo <- readNeoAssembly( -#' file = "HM1_merged.assemblies.txt", -#' id = "C1", -#' assembly = "hg38", -#' extend = 200000 -#' ) -#' neo -#' } -#' @export -readNeoAssembly <- function(file, id, assembly = "hg38", extend = 0, - prefix = "chr", quiet = FALSE) { - - if (missing(file) || is.null(file)) { - stop("argument \"file\" is missing, with no default.", call. = FALSE) - } - if (missing(id) || is.null(id)) { - stop("argument \"id\" is missing, with no default.", call. = FALSE) - } - if (!file.exists(file)) { - stop("Assembly file does not exist: ", file, call. = FALSE) - } - if (!is.numeric(extend) || length(extend) != 1 || extend < 0) { - stop("`extend` must be a single non-negative number.", call. = FALSE) - } - - lines <- readLines(file, warn = FALSE) - lines <- lines[nzchar(trimws(lines))] - id <- as.character(id) - target <- lines[startsWith(lines, paste0(id, "\t")) | - startsWith(lines, paste0(id, " "))] - - if (length(target) == 0) { - stop("Assembly ID '", id, "' not found in ", file, call. = FALSE) - } - - parts <- strsplit(target[1], "\t", fixed = TRUE)[[1]] - parts <- trimws(parts) - parts <- parts[nzchar(parts)] - if (length(parts) < 3) { - stop("Malformed assembly line for ID '", id, "'.", call. = FALSE) - } - - parseSpan <- function(x) { - pieces <- trimws(strsplit(x, ",", fixed = TRUE)[[1]]) - if (length(pieces) < 2) { - stop("Malformed assembly span: ", x, call. = FALSE) - } - list(chrom = pieces[1], pos = as.numeric(pieces[2])) - } - - span1 <- parseSpan(parts[length(parts) - 1]) - span2 <- parseSpan(parts[length(parts)]) - - svStrings <- character(0) - if (length(parts) > 3) { - svStrings <- parts[2:(length(parts) - 2)] - } - - nodesChrom <- span1$chrom - nodesPos <- span1$pos - - if (length(svStrings) > 0) { - for (sv in svStrings) { - svParts <- trimws(strsplit(sv, ",", fixed = TRUE)[[1]]) - if (length(svParts) < 6) { - stop("Malformed SV entry: ", sv, call. = FALSE) - } - nodesChrom <- c(nodesChrom, svParts[2], svParts[5]) - nodesPos <- c(nodesPos, as.numeric(svParts[3]), - as.numeric(svParts[6])) - } - } - - nodesChrom <- c(nodesChrom, span2$chrom) - nodesPos <- c(nodesPos, span2$pos) - - if (length(nodesChrom) %% 2 != 0) { - stop("Assembly topology has an odd number of nodes.", call. = FALSE) - } - - nFragments <- length(nodesChrom) / 2 - fragments <- vector("list", nFragments) - currentOffset <- 0 - - formatChrom <- function(chrom) { - chrom <- as.character(chrom) - if (startsWith(chrom, "chr")) { - chrom - } else { - paste0(prefix, chrom) - } - } - - for (i in seq_len(nFragments)) { - idx1 <- (i - 1) * 2 + 1 - idx2 <- idx1 + 1 - rawChrom <- nodesChrom[idx1] - posEnter <- nodesPos[idx1] - posExit <- nodesPos[idx2] - flipped <- posEnter > posExit - start <- min(posEnter, posExit) - end <- max(posEnter, posExit) - - if (extend > 0 && i == 1) { - if (flipped) { - end <- end + extend - } else { - start <- max(0, start - extend) - } - } - if (extend > 0 && i == nFragments) { - if (flipped) { - start <- max(0, start - extend) - } else { - end <- end + extend - } - } - - fragLength <- end - start - if (fragLength <= 0) { - stop("Fragment ", i, " has a non-positive length.", call. = FALSE) - } - - fragments[[i]] <- data.frame( - id = i, - chrom = formatChrom(rawChrom), - chrom_raw = as.character(rawChrom), - start = start, - end = end, - flipped = flipped, - offset = currentOffset, - length = fragLength, - stringsAsFactors = FALSE - ) - currentOffset <- currentOffset + fragLength - } - - fragments <- do.call(rbind, fragments) - rownames(fragments) <- NULL - - neo <- structure( - list( - id = id, - file = normalizePath(file, mustWork = TRUE), - assembly = assembly, - extend = extend, - fragments = fragments, - total_length = currentOffset - ), - class = c("neoAssembly", "list") - ) - - if (!quiet) { - message("neoAssembly[", id, "] ", nFragments, " fragments, ", - currentOffset, " bp") - } - - neo -} - -#' @export -print.neoAssembly <- function(x, ...) { - cat("neoAssembly", x$id, "\n") - cat(" fragments:", nrow(x$fragments), "\n") - cat(" total length:", x$total_length, "bp\n") - cat(" assembly:", x$assembly, "\n") - invisible(x) -} - -#' Map genomic features to neo-chromosome coordinates -#' -#' @param data A data frame with columns \code{chrom}, \code{start}, and -#' \code{end}, or a \link[GenomicRanges]{GRanges} object. -#' @param neo A `neoAssembly` object from \code{readNeoAssembly()}. -#' -#' @return A data frame with \code{chrom = "neo"}, neo-coordinate -#' \code{start}/\code{end}, and a \code{fragment} column. Features that span -#' multiple fragments are split across fragments. If a \code{strand} column is -#' present, it is flipped for reverse-complemented fragments. -#' -#' @examples -#' \dontrun{ -#' neo <- readNeoAssembly("HM1_merged.assemblies.txt", "C1", extend = 200000) -#' features <- data.frame( -#' chrom = "chr12", start = 65822483, end = 65968291, -#' name = "HMGA2", strand = "+" -#' ) -#' mapNeoFeatures(features, neo) -#' } -#' @export -mapNeoFeatures <- function(data, neo) { - - if (!inherits(neo, "neoAssembly")) { - stop("`neo` must be a `neoAssembly` object.", call. = FALSE) - } - - if (inherits(data, "GRanges")) { - df <- as.data.frame(data) - if ("seqnames" %in% colnames(df)) { - df$chrom <- as.character(df$seqnames) - df$seqnames <- NULL - } - } else { - df <- as.data.frame(data, stringsAsFactors = FALSE) - } - - required <- c("chrom", "start", "end") - if (!all(required %in% colnames(df))) { - stop("`data` must contain `chrom`, `start`, and `end` columns.", - call. = FALSE) - } - - fragments <- neo$fragments - mappedParts <- list() - - for (i in seq_len(nrow(fragments))) { - frag <- fragments[i, ] - subsetDf <- df[df$chrom == frag$chrom | df$chrom == frag$chrom_raw, , - drop = FALSE] - if (nrow(subsetDf) == 0) { - next - } - - subsetDf <- subsetDf[subsetDf$start <= frag$end & - subsetDf$end >= frag$start, , drop = FALSE] - if (nrow(subsetDf) == 0) { - next - } - - originalStart <- subsetDf$start - originalEnd <- subsetDf$end - clippedStart <- pmax(originalStart, frag$start) - clippedEnd <- pmin(originalEnd, frag$end) - - if (frag$flipped) { - subsetDf$start <- frag$offset + (frag$end - clippedEnd) - subsetDf$end <- frag$offset + (frag$end - clippedStart) - if ("strand" %in% colnames(subsetDf)) { - subsetDf$strand <- ifelse( - subsetDf$strand == "+", "-", - ifelse(subsetDf$strand == "-", "+", subsetDf$strand) - ) - } - } else { - subsetDf$start <- frag$offset + (clippedStart - frag$start) - subsetDf$end <- frag$offset + (clippedEnd - frag$start) - } - - subsetDf$chrom <- "neo" - subsetDf$fragment <- frag$id - mappedParts[[length(mappedParts) + 1]] <- subsetDf - } - - if (length(mappedParts) == 0) { - return(data.frame( - chrom = character(0), start = numeric(0), end = numeric(0), - fragment = integer(0) - )) - } - - mapped <- do.call(rbind, mappedParts) - rownames(mapped) <- NULL - mapped -} diff --git a/R/neoSignal.R b/R/neoSignal.R deleted file mode 100644 index 2e7d52885..000000000 --- a/R/neoSignal.R +++ /dev/null @@ -1,202 +0,0 @@ -#' Map a signal track onto neo-chromosome coordinates -#' -#' Maps bigWig, `GRanges`, or data-frame signal data through the -#' neo-chromosome topology and optionally bins it in neo coordinates. This -#' handles RNA-seq, ChIP-seq, and other genome-wide signal tracks in the same -#' way, including fragments that are inverted. -#' -#' @param data A bigWig path, `GRanges` object, or data frame with -#' `chrom`, `start`, `end`, and a signal column. -#' @param neo A `neoAssembly` object. -#' @param binSize Bin size in basepairs for the neo-coordinate output. Use -#' `NULL` to keep the input intervals. Default value is `1000`. -#' @param fun Aggregation function for binning: `"mean"`, `"median"`, -#' `"sum"`, `"max"`, or `"min"`. Default value is `"mean"`. -#' @param value.col Name of the signal column. If `NULL`, the function looks -#' for `"score"`, `"balanced"`, `"value"`, or the last numeric column. -#' @param chromstart,chromend Optional neo-coordinate window. Only intervals -#' overlapping this window are returned. -#' @param ... Additional arguments passed to `readBigwig()`. -#' -#' @return A data frame with `chrom`, `start`, `end`, and `score`. -#' @export -getNeoSignal <- function(data, neo, binSize = 1000, - fun = c("mean", "median", "sum", "max", "min"), - value.col = NULL, - chromstart = NULL, chromend = NULL, ...) { - if (!inherits(neo, "neoAssembly")) { - stop("`neo` must be a `neoAssembly` object.", call. = FALSE) - } - fun <- match.arg(fun) - - ## Read a bigWig fragment by fragment, or accept pre-read data -------- - if (is.character(data) && length(data) == 1) { - if (!file.exists(data)) { - stop("Signal file does not exist: ", data, call. = FALSE) - } - isBigWig <- grepl("\\.(bw|bigwig|bigWig)(\\.gz)?$", data, - ignore.case = TRUE) - if (isBigWig) { - parts <- lapply(seq_len(nrow(neo$fragments)), function(i) { - frag <- neo$fragments[i, ] - bw <- readBigwig( - file = data, chrom = frag$chrom, - chromstart = max(1, frag$start), chromend = frag$end, - ... - ) - if (nrow(bw) == 0) { - return(NULL) - } - df <- as.data.frame(bw) - if ("seqnames" %in% colnames(df)) { - df$chrom <- as.character(df$seqnames) - df$seqnames <- NULL - } - mapNeoFeatures(df, neo) - }) - parts <- Filter(NROW, parts) - if (length(parts) == 0) { - return(data.frame( - chrom = character(0), start = numeric(0), - end = numeric(0), score = numeric(0) - )) - } - raw <- do.call(rbind, parts) - } else { - ## Text table input (for example a virtual-4C table). - if (!requireNamespace("data.table", quietly = TRUE)) { - stop("`data.table` is required to read tabular signal files.", - call. = FALSE) - } - raw <- as.data.frame(data.table::fread(data)) - raw <- .neoSignalFrame(raw, neo, value.col) - } - } else if (inherits(data, "GRanges")) { - raw <- as.data.frame(data) - raw <- .neoSignalFrame(raw, neo, value.col) - } else { - raw <- .neoSignalFrame(as.data.frame(data), neo, value.col) - } - - if (nrow(raw) == 0) { - return(data.frame( - chrom = character(0), start = numeric(0), - end = numeric(0), score = numeric(0) - )) - } - - if (is.null(binSize)) { - out <- data.frame( - chrom = "neo", start = raw$start, end = raw$end, - score = raw$score, stringsAsFactors = FALSE - ) - } else { - if (!is.numeric(binSize) || length(binSize) != 1 || binSize <= 0) { - stop("`binSize` must be a positive number or NULL.", - call. = FALSE) - } - raw$bin <- floor(raw$start / binSize) * binSize - binned <- stats::aggregate( - score ~ bin, data = raw, FUN = fun, na.rm = TRUE - ) - out <- data.frame( - chrom = "neo", - start = binned$bin, - end = binned$bin + binSize - 1, - score = binned$score, - stringsAsFactors = FALSE - ) - } - - out <- out[order(out$start), , drop = FALSE] - rownames(out) <- NULL - if (!is.null(chromstart) || !is.null(chromend)) { - lo <- if (is.null(chromstart)) -Inf else chromstart - hi <- if (is.null(chromend)) Inf else chromend - out <- out[out$end >= lo & out$start <= hi, , drop = FALSE] - } - out -} - -.neoSignalFrame <- function(df, neo, value.col = NULL) { - if (!all(c("chrom", "start", "end") %in% colnames(df)) && - !all(c("seqnames", "start", "end") %in% colnames(df))) { - stop("Signal data must contain `chrom`, `start`, and `end` columns.", - call. = FALSE) - } - if ("seqnames" %in% colnames(df)) { - df$chrom <- as.character(df$seqnames) - df$seqnames <- NULL - } - if (!"chrom" %in% colnames(df)) { - stop("Signal data must contain a `chrom` column.", call. = FALSE) - } - - if (!is.null(value.col)) { - if (!value.col %in% colnames(df)) { - stop("`value.col` not found in signal data: ", value.col, - call. = FALSE) - } - score <- df[[value.col]] - } else { - candidates <- c("score", "balanced", "value") - hit <- candidates[candidates %in% colnames(df)][1] - if (is.na(hit)) { - numericCols <- names(df)[vapply(df, is.numeric, logical(1))] - numericCols <- setdiff(numericCols, c("start", "end")) - hit <- utils::tail(numericCols, 1) - } - if (is.na(hit) || length(hit) == 0) { - stop("Could not determine a signal column; supply `value.col`.", - call. = FALSE) - } - score <- df[[hit]] - } - - mapped <- mapNeoFeatures( - data.frame( - chrom = as.character(df$chrom), - start = as.numeric(df$start), - end = as.numeric(df$end), - score = as.numeric(score), - stringsAsFactors = FALSE - ), - neo - ) - mapped[, c("chrom", "start", "end", "score"), drop = FALSE] -} - -#' Map a virtual-4C table onto neo-chromosome coordinates -#' -#' Convenience wrapper around `getNeoSignal()` for cooltools virtual-4C TSV -#' files. The table is mapped through the neo topology and adjacent intervals -#' are clipped so they do not overlap. -#' -#' @param file Path to a virtual-4C TSV file. -#' @param neo A `neoAssembly` object. -#' @param value.col Signal column. Default value is `"balanced"`. -#' @param binSize Optional bin size. Default value is `NULL`, which keeps the -#' table's own intervals. -#' @param fun Aggregation function when `binSize` is supplied. -#' @param ... Additional arguments passed to `getNeoSignal()`. -#' -#' @return A data frame with `chrom`, `start`, `end`, and `score`. -#' @export -getNeoV4C <- function(file, neo, value.col = "balanced", binSize = NULL, - fun = "mean", ...) { - out <- getNeoSignal( - data = file, neo = neo, binSize = binSize, - fun = fun, value.col = value.col, ... - ) - if (nrow(out) == 0) { - return(out) - } - out <- out[order(out$start), , drop = FALSE] - out$end <- pmin( - out$end - 1, - c(out$start[-1] - 1, Inf) - ) - out <- out[out$start <= out$end, , drop = FALSE] - rownames(out) <- NULL - out -} diff --git a/R/plotNeo.R b/R/plotNeo.R deleted file mode 100644 index 8fbeb44a0..000000000 --- a/R/plotNeo.R +++ /dev/null @@ -1,1341 +0,0 @@ -#' Draw an SV neo-chromosome assembly backbone -#' -#' Draw a directional fragment backbone for a `neoAssembly` object. Each -#' fragment is drawn as an arrow pointing in its neo-chromosome orientation. -#' -#' @param neo A `neoAssembly` object from \code{readNeoAssembly()}. -#' @param x A numeric or unit object specifying the backbone x-location. -#' @param y A numeric, unit object, or character containing a "b" combined -#' with a numeric value specifying the backbone y-location. -#' @param width A numeric or unit object specifying the backbone width. -#' @param height A numeric or unit object specifying the backbone height. -#' @param just Justification of the backbone relative to its (x, y) location. -#' Default value is \code{just = c("left", "top")}. -#' @param default.units A string indicating the default units to use if -#' \code{x}, \code{y}, \code{width}, or \code{height} are only given as -#' numerics. Default value is \code{default.units = "inches"}. -#' @param fill Fill color(s) for fragments. A single value, a vector of -#' length equal to the number of fragments, or a named vector keyed by -#' chromosome name. Default value is \code{fill = "#D4EEF9"}. -#' @param linecolor Fragment outline color. Default value is -#' \code{linecolor = "white"}. -#' @param lwd Fragment outline line width. Default value is \code{lwd = 0.5}. -#' @param fragment.height Fraction of \code{height} used by the fragment -#' arrows. Default value is \code{fragment.height = 0.6}. -#' @param arrow.size Arrow-tip size in page units. If \code{NULL}, the tip is -#' sized relative to each fragment. -#' @param labels Logical value indicating whether to draw fragment labels, or -#' a character vector of labels. Default value is \code{labels = TRUE}. -#' @param label.fontsize Fragment label font size. -#' Default value is \code{label.fontsize = 7}. -#' @param label.fontcolor Fragment label color. -#' Default value is \code{label.fontcolor = "black"}. -#' @param show.seams Logical value indicating whether to draw fragment -#' boundaries. Default value is \code{show.seams = TRUE}. -#' @param seam.color Fragment boundary color. -#' Default value is \code{seam.color = "grey40"}. -#' @param seam.lwd Fragment boundary line width. Default value is -#' \code{seam.lwd = 0.5}. -#' @param seam.lty Fragment boundary line type. Default value is -#' \code{seam.lty = 1}. -#' @param params An optional \link[plotgardener]{pgParams} object. -#' @param ... Additional grid graphical parameters. See \link[grid]{gpar}. -#' -#' @return Invisibly returns a list containing the fragment polygons, labels, -#' and boundary segments. -#' -#' @examples -#' \dontrun{ -#' neo <- readNeoAssembly("HM1_merged.assemblies.txt", "C1", extend = 200000) -#' pageCreate(width = 6, height = 2, default.units = "inches") -#' plotNeoAssembly(neo, x = 0.5, y = 0.5, width = 3, height = 0.2) -#' } -#' @export -plotNeoAssembly <- function(neo, x, y, width, height, - just = c("left", "top"), - default.units = "inches", - fill = "#D4EEF9", linecolor = "white", lwd = 0.5, - fragment.height = 0.6, arrow.size = NULL, - labels = TRUE, label.fontsize = 7, - label.fontcolor = "black", - show.seams = TRUE, seam.color = "grey40", - seam.lwd = 0.5, seam.lty = 1, - params = NULL, ...) { - - if (!inherits(neo, "neoAssembly")) { - stop("`neo` must be a `neoAssembly` object.", call. = FALSE) - } - if (missing(x) || missing(y) || missing(width) || missing(height)) { - stop("`x`, `y`, `width`, and `height` must be supplied.", - call. = FALSE) - } - - check_page(error = "Cannot plot a neo assembly without a `plotgardener` page.") - - assemblyInternal <- parseParams( - params = params, - defaultArgs = formals(eval(match.call()[[1]])), - declaredArgs = lapply(match.call()[-1], eval.parent, n = 2), - class = "neoAssemblyInternal" - ) - assemblyInternal$just <- justConversion(just = assemblyInternal$just) - - page_units <- get("page_units", envir = pgEnv) - - xNum <- convertX( - misc_defaultUnits(assemblyInternal$x, "x", assemblyInternal$default.units), - unitTo = page_units, valueOnly = TRUE - ) - yNum <- convertY( - misc_defaultUnits(assemblyInternal$y, "y", assemblyInternal$default.units), - unitTo = page_units, valueOnly = TRUE - ) - widthNum <- convertWidth( - misc_defaultUnits(assemblyInternal$width, "width", - assemblyInternal$default.units), - unitTo = page_units, valueOnly = TRUE - ) - heightNum <- convertHeight( - misc_defaultUnits(assemblyInternal$height, "height", - assemblyInternal$default.units), - unitTo = page_units, valueOnly = TRUE - ) - - just <- assemblyInternal$just - xLeft <- xNum - just[1] * widthNum - yTop <- yNum - (1 - just[2]) * heightNum - - fragments <- neo$fragments - nFragments <- nrow(fragments) - totalLength <- neo$total_length - - fragWidths <- fragments$length / totalLength * widthNum - fragX1 <- xLeft + fragments$offset / totalLength * widthNum - fragX2 <- xLeft + (fragments$offset + fragments$length) / - totalLength * widthNum - - fragmentHeight <- assemblyInternal$fragment.height * heightNum - if (fragmentHeight <= 0) { - stop("`fragment.height` must produce a positive fragment height.", - call. = FALSE) - } - yBottom <- yTop + (heightNum - fragmentHeight) / 2 - yCenter <- yTop + heightNum / 2 - yTopArrow <- yBottom + fragmentHeight - - ## Resolve fill colors - fillColors <- assemblyInternal$fill - if (length(fillColors) == 1) { - fillColors <- rep(fillColors, nFragments) - } else if (!is.null(names(fillColors)) && - all(fragments$chrom %in% names(fillColors))) { - fillColors <- unname(fillColors[fragments$chrom]) - } else { - fillColors <- rep_len(fillColors, nFragments) - } - - polygons <- vector("list", nFragments) - for (i in seq_len(nFragments)) { - x1 <- fragX1[i] - x2 <- fragX2[i] - tip <- if (is.null(assemblyInternal$arrow.size)) { - min(0.1, (x2 - x1) * 0.15) - } else { - assemblyInternal$arrow.size - } - tip <- min(tip, (x2 - x1) * 0.45) - - if (fragments$flipped[i]) { - px <- c(x2, x1 + tip, x1, x1 + tip, x2) - py <- c(yBottom, yBottom, yCenter, yTopArrow, yTopArrow) - } else { - px <- c(x1, x2 - tip, x2, x2 - tip, x1) - py <- c(yBottom, yBottom, yCenter, yTopArrow, yTopArrow) - } - - polygons[[i]] <- plotPolygon( - x = px, y = py, - fill = fillColors[i], - linecolor = assemblyInternal$linecolor, - lwd = assemblyInternal$lwd, - default.units = page_units, ... - ) - } - - labelGrobs <- list() - if (!identical(assemblyInternal$labels, FALSE)) { - if (isTRUE(assemblyInternal$labels)) { - labelText <- fragments$chrom_raw - } else { - labelText <- rep_len(assemblyInternal$labels, nFragments) - } - for (i in seq_len(nFragments)) { - labelGrobs[[i]] <- plotText( - label = labelText[i], - x = (fragX1[i] + fragX2[i]) / 2, - y = yCenter, - just = c("center", "center"), - fontsize = assemblyInternal$label.fontsize, - fontcolor = assemblyInternal$label.fontcolor, - default.units = page_units - ) - } - } - - seamGrobs <- list() - if (isTRUE(assemblyInternal$show.seams)) { - boundaries <- xLeft + cumsum(fragments$length) / totalLength * widthNum - boundaries <- boundaries[-length(boundaries)] - for (i in seq_along(boundaries)) { - seamGrobs[[i]] <- plotSegments( - x0 = boundaries[i], y0 = yTop, - x1 = boundaries[i], y1 = yTop + heightNum, - linecolor = assemblyInternal$seam.color, - lwd = assemblyInternal$seam.lwd, - lty = assemblyInternal$seam.lty, - default.units = page_units - ) - } - } - - message("neoAssembly[", neo$id, "]") - invisible(list( - fragments = polygons, - labels = labelGrobs, - seams = seamGrobs - )) -} - -#' Add flexible labels to an SV neo-chromosome assembly -#' -#' This is a label-only companion to \code{plotNeoAssembly()}. It is useful -#' when fragment labels need custom y-offsets, gaps, fonts, rotation, or -#' inversion highlighting without adding more arguments to the backbone -#' function. -#' -#' @param neo A `neoAssembly` object. -#' @param x A numeric or unit object specifying the label row x-location. -#' @param y A numeric or unit object specifying the label row y-location. -#' @param width A numeric or unit object specifying the label row width. -#' @param height A numeric or unit object specifying the label row height. -#' Default value is \code{height = 0}. -#' @param just Justification of the label row relative to (x, y). -#' Default value is \code{just = c("left", "top")}. -#' @param default.units Default units for numeric \code{x}, \code{y}, -#' \code{width}, and \code{height}. Default value is -#' \code{default.units = "inches"}. -#' @param labels Logical value or character vector of labels. -#' If \code{TRUE}, labels are generated from \code{label.style}. -#' Default value is \code{labels = TRUE}. -#' @param label.style Label style when \code{labels = TRUE}: \code{"chrom"} -#' (chromosome name), \code{"coordinate"} (chromosome and Mb coordinates), or -#' \code{"fragment"} (fragment number). Default value is -#' \code{label.style = "chrom"}. -#' @param label.fontsize Label font size. Default value is -#' \code{label.fontsize = 7}. -#' @param label.fontcolor Label color. Can be a vector recycled across -#' fragments. Default value is \code{label.fontcolor = "black"}. -#' @param label.colors Optional explicit per-fragment colors. Overrides -#' \code{label.fontcolor} and inversion coloring. -#' @param label.fontfamily Label font family. Default value is -#' \code{label.fontfamily = ""}. -#' @param label.fontface Label font face. Default value is -#' \code{label.fontface = 1}. -#' @param label.rot Label rotation in degrees. Default value is -#' \code{label.rot = 0}. -#' @param label.position Label position relative to the fragment row: -#' \code{"center"}, \code{"above"}, or \code{"below"}. -#' Default value is \code{label.position = "center"}. -#' @param label.offset Vertical offset in page units for \code{"above"} or -#' \code{"below"} positions. Default value is \code{label.offset = 0.1}. -#' @param show.inversion Logical value indicating whether flipped fragments -#' should be marked. Default value is \code{show.inversion = FALSE}. -#' @param inversion.suffix Suffix appended to flipped-fragment labels. -#' Default value is \code{inversion.suffix = " (inv)"}. -#' @param inversion.color Color for flipped-fragment labels. Default value is -#' \code{inversion.color = "red"}. -#' @param params An optional \link[plotgardener]{pgParams} object. -#' @param ... Additional arguments passed to \code{plotText()}. -#' -#' @return Invisibly returns a list of \code{plotText()} objects. -#' -#' @examples -#' \dontrun{ -#' plotNeoAssembly(neo, x = 1, y = 3, width = 3, height = 0.15, -#' labels = FALSE) -#' annoNeoFragmentLabels( -#' neo, x = 1, y = 3.25, width = 3, -#' label.style = "coordinate", -#' label.position = "below", -#' label.offset = 0.05, -#' label.fontface = "italic", -#' show.inversion = TRUE -#' ) -#' } -#' @export -annoNeoFragmentLabels <- function(neo, x, y, width, height = 0, - just = c("left", "top"), - default.units = "inches", - labels = TRUE, label.style = "chrom", - label.fontsize = 7, - label.fontcolor = "black", - label.colors = NULL, - label.fontfamily = "", - label.fontface = 1, - label.rot = 0, - label.position = "center", - label.offset = 0.1, - show.inversion = FALSE, - inversion.suffix = " (inv)", - inversion.color = "red", - params = NULL, ...) { - - if (!inherits(neo, "neoAssembly")) { - stop("`neo` must be a `neoAssembly` object.", call. = FALSE) - } - if (missing(x) || missing(y) || missing(width)) { - stop("`x`, `y`, and `width` must be supplied.", call. = FALSE) - } - label.position <- match.arg(label.position, - c("center", "above", "below")) - label.style <- match.arg(label.style, - c("chrom", "coordinate", "fragment")) - check_page(error = "Cannot annotate a neo assembly without a `plotgardener` page.") - - labelInternal <- parseParams( - params = params, - defaultArgs = formals(eval(match.call()[[1]])), - declaredArgs = lapply(match.call()[-1], eval.parent, n = 2), - class = "neoLabelInternal" - ) - labelInternal$just <- justConversion(just = labelInternal$just) - - page_units <- get("page_units", envir = pgEnv) - xNum <- convertX( - misc_defaultUnits(labelInternal$x, "x", labelInternal$default.units), - unitTo = page_units, valueOnly = TRUE - ) - yNum <- convertY( - misc_defaultUnits(labelInternal$y, "y", labelInternal$default.units), - unitTo = page_units, valueOnly = TRUE - ) - widthNum <- convertWidth( - misc_defaultUnits(labelInternal$width, "width", - labelInternal$default.units), - unitTo = page_units, valueOnly = TRUE - ) - heightNum <- convertHeight( - misc_defaultUnits(labelInternal$height, "height", - labelInternal$default.units), - unitTo = page_units, valueOnly = TRUE - ) - - just <- labelInternal$just - xLeft <- xNum - just[1] * widthNum - yTop <- yNum - (1 - just[2]) * heightNum - yCenter <- yTop + heightNum / 2 - - fragments <- neo$fragments - nFragments <- nrow(fragments) - fragWidths <- fragments$length / neo$total_length * widthNum - fragCenters <- xLeft + (fragments$offset + fragments$length / 2) / - neo$total_length * widthNum - - if (isTRUE(labels)) { - labelText <- switch(label.style, - chrom = fragments$chrom_raw, - coordinate = { - left <- ifelse(fragments$flipped, - fragments$end, fragments$start) / 1e6 - right <- ifelse(fragments$flipped, - fragments$start, fragments$end) / 1e6 - paste0(fragments$chrom_raw, ": ", - sprintf("%.2f", left), "-", - sprintf("%.2f", right), " Mb") - }, - fragment = paste0("fragment ", fragments$id) - ) - } else { - labelText <- rep_len(labels, nFragments) - } - - if (isTRUE(show.inversion) && !isTRUE(labels)) { - labelText[fragments$flipped] <- paste0( - labelText[fragments$flipped], inversion.suffix - ) - } else if (isTRUE(show.inversion) && isTRUE(labels)) { - labelText[fragments$flipped] <- paste0( - labelText[fragments$flipped], inversion.suffix - ) - } - - if (!is.null(label.colors)) { - labelColors <- rep_len(label.colors, nFragments) - } else { - labelColors <- rep_len(label.fontcolor, nFragments) - if (isTRUE(show.inversion)) { - labelColors[fragments$flipped] <- inversion.color - } - } - - yLabel <- switch(label.position, - center = rep(yCenter, nFragments), - above = rep(yTop - label.offset, nFragments), - below = rep(yTop + heightNum + label.offset, nFragments) - ) - - grobs <- lapply(seq_len(nFragments), function(i) { - plotText( - label = labelText[i], - x = fragCenters[i], - y = yLabel[i], - just = c("center", "center"), - fontsize = label.fontsize, - fontcolor = labelColors[i], - fontfamily = label.fontfamily, - fontface = label.fontface, - rot = label.rot, - default.units = page_units, ... - ) - }) - - invisible(grobs) -} - -#' -#' This mirrors the visual convention used by the neo-triangle examples: -#' a solid domain outline around the full neo-chromosome and dotted domain -#' outlines at each internal fragment seam. -#' -#' @param plot A Hi-C plot object from \code{plotHicSquare()}, -#' \code{plotHicTriangle()}, or \code{plotHicRectangle()}. -#' @param neo A `neoAssembly` object. -#' @param outer Logical value indicating whether to draw the outer -#' neo-chromosome domain outline. Default value is \code{outer = TRUE}. -#' @param seams Logical value indicating whether to draw internal fragment -#' seams. Default value is \code{seams = TRUE}. -#' @param linecolor Domain line color. Default value is -#' \code{linecolor = "black"}. -#' @param lwd Domain line width. Default value is \code{lwd = 0.5}. -#' @param lty Outer domain line type. Default value is \code{lty = 1}. -#' @param seam.color Seam line color. Defaults to \code{linecolor}. -#' @param seam.lwd Seam line width. Defaults to \code{lwd}. -#' @param seam.lty Seam line type. Default value is \code{seam.lty = 2} -#' (dotted). -#' @param ... Additional arguments passed to \code{annoDomains()}. -#' -#' @return Invisibly returns a list with \code{outer} and \code{seams} -#' \code{annoDomains} objects. -#' -#' @examples -#' \dontrun{ -#' neoHic <- readNeoHic("HM1_merged.mcool", neo, resolution = 5000) -#' h <- plotNeoHic(neoHic, type = "triangle", x = 1, y = 1, -#' width = 2, height = 1) -#' annoNeoDomains(h, neo) -#' } -#' @export -annoNeoDomains <- function(plot, neo, outer = TRUE, seams = TRUE, - linecolor = "black", lwd = 0.5, lty = 1, - seam.color = NULL, seam.lwd = NULL, - seam.lty = 2, ...) { - - if (!inherits(neo, "neoAssembly")) { - stop("`neo` must be a `neoAssembly` object.", call. = FALSE) - } - if (!is(plot, "hicSquare") && !is(plot, "hicTriangle") && - !is(plot, "hicRectangle")) { - stop("`plot` must be a Hi-C plot object.", call. = FALSE) - } - - totalLength <- neo$total_length - if (is.null(seam.color)) seam.color <- linecolor - if (is.null(seam.lwd)) seam.lwd <- lwd - outerGrobs <- NULL - seamGrobs <- list() - - if (isTRUE(outer)) { - masterDomain <- data.frame( - chrom = "neo", - start = 0, - end = totalLength - ) - outerGrobs <- annoDomains( - plot = plot, data = masterDomain, - linecolor = linecolor, lwd = lwd, lty = lty, fill = NA, ... - ) - } - - if (isTRUE(seams)) { - boundaries <- cumsum(neo$fragments$length) - boundaries <- boundaries[-length(boundaries)] - ## Triangle plots mirror the pixel data rather than the viewport, so - ## seam annotations must be mirrored explicitly to stay aligned. - if (is(plot, "hicTriangle") && - identical(plot$xaxisDir, "decrease")) { - boundaries <- totalLength - boundaries - } - seamGrobs <- lapply(boundaries, function(boundary) { - seamDomain <- data.frame( - chrom = c("neo", "neo"), - start = c(0, boundary), - end = c(boundary, totalLength) - ) - annoDomains( - plot = plot, data = seamDomain, - linecolor = seam.color, lwd = seam.lwd, lty = seam.lty, - fill = NA, ... - ) - }) - } - - invisible(list(outer = outerGrobs, seams = seamGrobs)) -} - -#' Plot IGV-style gene models in neo-chromosome coordinates -#' -#' Draws gene models through the neo-chromosome topology, using IGV-style -#' display modes. At whole-chromosome scale genes collapse to solid blocks; -#' when zoomed in, gene bodies and exon blocks are shown. Input can be a -#' GTF/GFF file, a `GRanges` object, or a data frame. Using a GTF/GFF file -#' allows arbitrary GENCODE releases without requiring a matching TxDb -#' package. -#' -#' @param data A GTF/GFF path, `GRanges` object, data frame, or a -#' `TxDb`/`EnsDb` annotation object. Data frames need `chrom`, `start`, -#' `end`, and optionally `strand`, `gene`, `transcript`, and `feature` -#' columns. -#' @param neo A `neoAssembly` object. -#' @param txdb Optional `TxDb` or `EnsDb` annotation. If `data` is a -#' `TxDb`/`EnsDb`, it is used automatically. -#' @param orgdb Optional `OrgDb` used to map gene IDs to symbols. -#' @param assembly Assembly name or object used to resolve default -#' `TxDb`/`OrgDb` packages. Defaults to `neo$assembly`. -#' @param gene.id.column,display.column Column names used when reading a -#' `TxDb` annotation. -#' @param geneOrder Optional character vector giving label priority order. -#' @param labelClusters Logical value indicating whether labels should be -#' rotated to reduce overlap. Default value is `FALSE`. -#' @param labelClusterRot Rotation in degrees for clustered labels. -#' Default value is 45. -#' @param geneBackground Color for non-highlighted genes when -#' `geneHighlights` is supplied. Default value is `"grey"`. -#' @param geneMode Gene layout mode. `"expand"` draws all genes at full -#' opacity in packed rows. `"focus"` draws priority genes (`geneHighlights`, -#' `geneOrder`, or named `labels`) at full opacity and all other genes at -#' `focus.alpha`. `"compact"` draws all genes on a single line. -#' Default value is `"expand"`. -#' @param focus.alpha Alpha applied to non-priority genes in focus mode. -#' Default value is 0.5. -#' @param reader GTF/GFF reader: `"auto"`, `"readGFF"`, `"import"`, or -#' `"tabix"`. Default value is `"auto"`. -#' @param cache Optional cache directory for parsed annotations, or `TRUE` -#' for the plotgardener user cache. Default value is `NULL` (no cache). -#' @param x,y,width,height Placement parameters. -#' @param just Justification. Default value is \code{c("left", "top")}. -#' @param default.units Default units. Default value is \code{"inches"}. -#' @param displayMode Gene display mode. \code{"auto"} chooses -#' \code{"collapsed"} or \code{"expanded"} from basepairs per inch. -#' \code{"squished"} uses expanded detail with shorter rows. -#' Default value is \code{displayMode = "auto"}. -#' @param chromstart,chromend Neo-coordinate window to display. Defaults to -#' the full neo-chromosome. -#' @param color Gene color. Can be a single color or a named vector by gene. -#' Default value is \code{"black"}. -#' @param highlight.color Color for highlighted genes. -#' Default value is \code{"red"}. -#' @param geneHighlights Optional character vector of gene names, a named -#' color vector, or a data frame with `gene` and `color` columns. Genes named -#' without colors use \code{highlight.color}. -#' @param gene.type Gene biotypes to retain when a \code{gene_type} column is -#' available, e.g. \code{"protein_coding"}. Use \code{NULL} to keep all -#' biotypes. Default value is \code{"protein_coding"}. -#' @param labels Logical value or character vector of gene names to label. -#' Default value is \code{FALSE} so the track stays clean. -#' @param label.fontsize Gene label font size. Default value is 5. -#' @param label.fontcolor Gene label color for non-highlighted genes. -#' Default value is \code{"black"}. -#' @param label.position Label position: \code{"above"} or \code{"center"}. -#' Default value is \code{"above"}. -#' @param label.overlap Logical value indicating whether labels should be -#' stacked into extra levels to avoid collisions. Default value is -#' \code{TRUE}. -#' @param show.strand Strand display: \code{"arrows"}, \code{"labels"}, or -#' \code{"none"}. Logical \code{TRUE}/\code{FALSE} are accepted for backward -#' compatibility. Default value is \code{"arrows"}. -#' @param strand.color Strand-label color. Default value is \code{"black"}. -#' @param arrow.spacing Spacing between strand chevrons in points. -#' Default value is 30. -#' @param body.lwd Gene-body line width in expanded mode. Default value is -#' 0.8. -#' @param exon.height Exon block height as a fraction of row height. -#' Default value is 0.7. -#' @param feature.min.px Minimum feature width in pixels at 72 dpi. -#' Default value is 3. -#' @param exon.min.px Minimum exon width in pixels at 72 dpi. -#' Default value is 1. -#' @param exon.min.width Deprecated point-based exon width override. When -#' supplied, it takes precedence over \code{exon.min.px}. -#' @param row.height Optional explicit row height in \code{default.units}. -#' @param auto.collapse.bp.per.inch Basepairs per inch above which -#' \code{displayMode = "auto"} collapses genes. Default value is 50000. -#' @param max.rows Maximum number of gene rows. Default value is 4. -#' @param params An optional \link[plotgardener]{pgParams} object. -#' @param ... Additional arguments passed to \code{plotText()}. -#' -#' @return Invisibly returns a list with the gene rows, grobs, display mode, -#' and displayed window. -#' @export -plotNeoGenes <- function(data = NULL, neo, x, y, width, height, - txdb = NULL, orgdb = NULL, - assembly = NULL, - gene.id.column = NULL, display.column = NULL, - just = c("left", "top"), - default.units = "inches", - displayMode = c("auto", "collapsed", "expanded", - "squished"), - chromstart = 0, chromend = NULL, - color = "black", highlight.color = "red", - geneHighlights = NULL, gene.type = "protein_coding", - geneOrder = NULL, labelClusters = FALSE, - labelClusterRot = 45, - geneBackground = "grey", - geneMode = c("expand", "focus", "compact"), - focus.alpha = 0.5, - labels = FALSE, label.fontsize = 5, - label.fontcolor = "black", - label.position = c("above", "center"), - label.overlap = TRUE, - show.strand = c("arrows", "labels", "none"), - strand.color = "black", - arrow.spacing = 30, - body.lwd = 0.8, exon.height = 0.7, - feature.min.px = 3, exon.min.px = 1, - exon.min.width = NULL, - row.height = NULL, - auto.collapse.bp.per.inch = 50e3, - max.rows = 4, - reader = c("auto", "readGFF", "import", "tabix"), - cache = NULL, - params = NULL, ...) { - if (!inherits(neo, "neoAssembly")) { - stop("`neo` must be a `neoAssembly` object.", call. = FALSE) - } - - ## Parse parameters ------------------------------------------------------ - geneInternal <- parseParams( - params = params, - defaultArgs = formals(eval(match.call()[[1]])), - declaredArgs = lapply(match.call()[-1], eval.parent, n = 2), - class = "neoGeneInternal" - ) - geneInternal$just <- justConversion(just = geneInternal$just) - if (is.null(geneInternal$assembly)) { - geneInternal$assembly <- neo$assembly - } - assembly <- geneInternal$assembly - - displayMode <- match.arg( - geneInternal$displayMode, - c("auto", "collapsed", "expanded", "squished") - ) - label.position <- match.arg(geneInternal$label.position, - c("above", "center")) - reader <- match.arg(geneInternal$reader, - c("auto", "readGFF", "import", "tabix")) - geneMode <- match.arg(geneInternal$geneMode, - c("expand", "focus", "compact")) - showStrand <- geneInternal$show.strand - if (is.logical(showStrand)) { - showStrand <- if (isTRUE(showStrand)) "labels" else "none" - } - showStrand <- match.arg(showStrand, c("arrows", "labels", "none")) - if (is.null(geneInternal$chromend)) { - geneInternal$chromend <- neo$total_length - } - - ## Resolve the annotation source ---------------------------------------- - ## A TxDb/EnsDb can be passed as `data`, via `txdb=`, or left to the - ## default assembly packages. A GTF/GFF path uses the fast reader. - if (methods::is(data, "TxDb") || inherits(data, "EnsDb")) { - if (is.null(txdb)) { - txdb <- data - } - data <- NULL - } - - featureTypes <- c("gene", "exon", "CDS", "UTR", - "five_prime_UTR", "three_prime_UTR") - featureTags <- c("gene_id", "gene_name", "gene_type", - "transcript_id", "transcript_type") - - if (is.null(data)) { - if (is.null(txdb)) { - stop("Either `data` or `txdb` must be supplied.", call. = FALSE) - } - df <- .readNeoGenesTxDb( - txdb = txdb, orgdb = orgdb, neo = neo, - assemblyName = geneInternal$assembly, - gene.id.column = gene.id.column, - display.column = display.column - ) - } else if (is.character(data) && length(data) == 1 && - file.exists(data)) { - df <- .readNeoGenesGFF( - file = data, neo = neo, - type = featureTypes, tags = featureTags, - reader = reader, cache = cache - ) - } else if (inherits(data, "GRanges")) { - df <- as.data.frame(data) - df$chrom <- as.character(df$seqnames) - df$seqnames <- NULL - if ("type" %in% colnames(df)) { - df$feature <- as.character(df$type) - } else if ("feature" %in% colnames(df)) { - df$feature <- as.character(df$feature) - } else { - df$feature <- "exon" - } - if (!"gene" %in% colnames(df)) { - df$gene <- if ("gene_name" %in% colnames(df)) { - as.character(df$gene_name) - } else if ("gene_id" %in% colnames(df)) { - as.character(df$gene_id) - } else { - paste0("gene", seq_len(nrow(df))) - } - } - if (!"transcript" %in% colnames(df)) { - df$transcript <- df$gene - } - } else { - df <- as.data.frame(data, stringsAsFactors = FALSE) - if (!all(c("chrom", "start", "end") %in% colnames(df))) { - stop("`data` must contain `chrom`, `start`, and `end` columns.", - call. = FALSE) - } - if (!"feature" %in% colnames(df)) { - if ("type" %in% colnames(df)) { - df$feature <- as.character(df$type) - } else { - df$feature <- "exon" - } - } - if (!"gene" %in% colnames(df)) { - df$gene <- if ("name" %in% colnames(df)) { - df$name - } else { - paste0("gene", seq_len(nrow(df))) - } - } - if (!"transcript" %in% colnames(df)) { - df$transcript <- df$gene - } - } - if (!"strand" %in% colnames(df)) { - df$strand <- "*" - } - if (!"gene_type" %in% colnames(df) && "gene_biotype" %in% colnames(df)) { - df$gene_type <- df$gene_biotype - } - df$gene <- as.character(df$gene) - df$feature <- as.character(df$feature) - df$strand <- as.character(df$strand) - - ## Restrict to requested gene biotypes (GENCODE `gene_type`). TxDb - ## annotations often have no biotype column; only filter when the column - ## actually carries values. - if (!is.null(geneInternal$gene.type) && - "gene_type" %in% colnames(df) && - any(!is.na(df$gene_type) & nzchar(as.character(df$gene_type)))) { - df <- df[as.character(df$gene_type) %in% geneInternal$gene.type, , - drop = FALSE] - } - if (nrow(df) == 0) { - return(invisible(list(genes = NULL, grobs = list(), - displayMode = displayMode, - chromstart = geneInternal$chromstart, - chromend = geneInternal$chromend))) - } - - feature <- toupper(df$feature) - exonRows <- df[feature == "EXON", , drop = FALSE] - cdsRows <- df[feature == "CDS", , drop = FALSE] - geneRows <- df[feature == "GENE", , drop = FALSE] - if (nrow(exonRows) == 0) { - exonRows <- geneRows - } - if (nrow(exonRows) == 0) { - exonRows <- df - } - - mapRows <- function(rows) { - if (nrow(rows) == 0) { - return(NULL) - } - mapped <- mapNeoFeatures(rows, neo) - if (nrow(mapped) == 0) { - return(NULL) - } - mapped$gene <- as.character(mapped$gene) - mapped$strand <- as.character(mapped$strand) - mapped$key <- paste(mapped$gene, mapped$fragment, mapped$strand, - sep = "|") - mapped - } - mappedExons <- mapRows(exonRows) - mappedCDS <- mapRows(cdsRows) - if (is.null(mappedExons)) { - return(invisible(list(genes = NULL, grobs = list(), - displayMode = displayMode, - chromstart = geneInternal$chromstart, - chromend = geneInternal$chromend))) - } - - exonSplit <- split(mappedExons, mappedExons$key) - cdsSplit <- if (!is.null(mappedCDS)) split(mappedCDS, mappedCDS$key) else list() - keys <- names(exonSplit) - genes <- lapply(keys, function(key) { - g <- exonSplit[[key]] - exons <- IRanges::reduce(IRanges::IRanges(g$start, g$end)) - cds <- NULL - if (!is.null(cdsSplit[[key]])) { - cg <- cdsSplit[[key]] - cds <- IRanges::reduce(IRanges::IRanges(cg$start, cg$end)) - } - data.frame( - gene = g$gene[1], - strand = g$strand[1], - fragment = g$fragment[1], - start = min(g$start), - end = max(g$end), - exonStart = I(list(IRanges::start(exons))), - exonEnd = I(list(IRanges::end(exons))), - cdsStart = I(list(if (is.null(cds)) numeric(0) else - IRanges::start(cds))), - cdsEnd = I(list(if (is.null(cds)) numeric(0) else - IRanges::end(cds))), - nExons = length(exons), - stringsAsFactors = FALSE - ) - }) - genes <- do.call(rbind, genes) - genes <- genes[order(genes$start), , drop = FALSE] - - ## Clip to the displayed neo-coordinate window. - chromstart <- max(0, geneInternal$chromstart) - chromend <- min(neo$total_length, geneInternal$chromend) - if (chromend <= chromstart) { - stop("`chromend` must be greater than `chromstart`.", call. = FALSE) - } - genes <- genes[genes$end >= chromstart & genes$start <= chromend, , - drop = FALSE] - if (nrow(genes) == 0) { - return(invisible(list(genes = genes, grobs = list(), - displayMode = displayMode, - chromstart = chromstart, - chromend = chromend))) - } - genes$start <- pmax(genes$start, chromstart) - genes$end <- pmin(genes$end, chromend) - - ## Greedy row packing with explicit overflow handling. - packGenes <- function(genes, maxRows, overflow = c("drop", "last")) { - overflow <- match.arg(overflow) - genes$row <- 0L - rowEnds <- numeric(0) - for (i in seq_len(nrow(genes))) { - placed <- FALSE - for (r in seq_along(rowEnds)) { - if (genes$start[i] >= rowEnds[r]) { - genes$row[i] <- r - rowEnds[r] <- genes$end[i] - placed <- TRUE - break - } - } - if (!placed) { - rowEnds <- c(rowEnds, genes$end[i]) - genes$row[i] <- length(rowEnds) - } - } - if (any(genes$row > maxRows)) { - if (overflow == "last") { - genes$row[genes$row > maxRows] <- maxRows - } else { - warning("Not enough rows for all genes; increase `max.rows`.", - call. = FALSE) - genes <- genes[genes$row <= maxRows, , drop = FALSE] - } - } - genes - } - if (geneMode == "compact") { - genes$row <- 1L - } else { - genes <- packGenes( - genes, geneInternal$max.rows, - overflow = if (geneMode == "focus") "last" else "drop" - ) - } - if (nrow(genes) == 0) { - return(invisible(list(genes = genes, grobs = list(), - displayMode = displayMode, - chromstart = chromstart, - chromend = chromend))) - } - - ## Placement in page units ---------------------------------------------- - page_units <- get("page_units", envir = pgEnv) - xNum <- convertX(misc_defaultUnits(geneInternal$x, "x", - geneInternal$default.units), - unitTo = page_units, valueOnly = TRUE) - yNum <- convertY(misc_defaultUnits(geneInternal$y, "y", - geneInternal$default.units), - unitTo = page_units, valueOnly = TRUE) - widthNum <- convertWidth(misc_defaultUnits(geneInternal$width, "width", - geneInternal$default.units), - unitTo = page_units, valueOnly = TRUE) - heightNum <- convertHeight(misc_defaultUnits(geneInternal$height, - "height", - geneInternal$default.units), - unitTo = page_units, valueOnly = TRUE) - just <- geneInternal$just - xLeft <- xNum - just[1] * widthNum - yTop <- yNum - (1 - just[2]) * heightNum - - ## Choose display mode from actual basepairs-per-inch. - widthIn <- convertWidth(unit(widthNum, page_units), unitTo = "inches", - valueOnly = TRUE) - if (widthIn <= 0) { - stop("`width` must be positive.", call. = FALSE) - } - bpPerInch <- (chromend - chromstart) / widthIn - if (displayMode == "auto") { - displayMode <- if (bpPerInch > geneInternal$auto.collapse.bp.per.inch) { - "collapsed" - } else { - "expanded" - } - } - - nRows <- max(genes$row) - if (!is.null(geneInternal$row.height)) { - rowHeight <- convertHeight( - misc_defaultUnits(geneInternal$row.height, "height", - geneInternal$default.units), - unitTo = page_units, valueOnly = TRUE - ) - } else { - rowHeight <- heightNum / nRows - } - if (displayMode == "squished") { - rowHeight <- rowHeight * 0.6 - } - if (rowHeight * nRows > heightNum) { - warning("`row.height` exceeds the track height; using equal rows.", - call. = FALSE) - rowHeight <- heightNum / nRows - } - yOffset <- (heightNum - rowHeight * nRows) / 2 - - toX <- function(pos) { - xLeft + (pos - chromstart) / (chromend - chromstart) * widthNum - } - featureMinWidth <- convertWidth(unit(geneInternal$feature.min.px, - "points"), - unitTo = page_units, valueOnly = TRUE) - if (!is.null(geneInternal$exon.min.width)) { - exonMinWidth <- convertWidth(unit(geneInternal$exon.min.width, - "points"), - unitTo = page_units, valueOnly = TRUE) - } else { - exonMinWidth <- convertWidth(unit(geneInternal$exon.min.px, - "points"), - unitTo = page_units, valueOnly = TRUE) - } - exonMinBp <- exonMinWidth / widthNum * (chromend - chromstart) - ## Gene colors ---------------------------------------------------------- - colorMap <- NULL - if (!is.null(geneInternal$geneHighlights)) { - geneHighlights <- geneInternal$geneHighlights - if (is.data.frame(geneHighlights)) { - colorMap <- stats::setNames( - as.character(geneHighlights$color), - as.character(geneHighlights$gene) - ) - } else if (!is.null(names(geneHighlights))) { - colorMap <- as.character(geneHighlights) - names(colorMap) <- names(geneHighlights) - } else { - colorMap <- stats::setNames( - rep_len(geneInternal$highlight.color, length(geneHighlights)), - as.character(geneHighlights) - ) - } - } - geneColor <- function(g) { - if (!is.null(colorMap) && g %in% names(colorMap)) { - return(unname(colorMap[g])) - } - if (!is.null(colorMap)) { - return(geneInternal$geneBackground) - } - if (length(geneInternal$color) > 1 && - !is.null(names(geneInternal$color)) && - g %in% names(geneInternal$color)) { - return(unname(geneInternal$color[g])) - } - if (length(geneInternal$color) == 1) { - geneInternal$color - } else { - geneInternal$color[1] - } - } - isHighlighted <- vapply(genes$gene, function(g) { - (!is.null(colorMap) && g %in% names(colorMap)) || - (length(geneInternal$color) > 1 && - !is.null(names(geneInternal$color)) && - g %in% names(geneInternal$color)) - }, logical(1)) - geneCols <- unname(vapply(genes$gene, geneColor, character(1))) - - ## Priority genes keep full exon detail in compact mode. - priorityNames <- character(0) - if (!is.null(colorMap)) { - priorityNames <- c(priorityNames, names(colorMap)) - } - if (is.character(geneInternal$labels)) { - priorityNames <- c(priorityNames, geneInternal$labels) - } - if (!is.null(geneInternal$geneOrder)) { - priorityNames <- c(priorityNames, geneInternal$geneOrder) - } - priorityNames <- unique(priorityNames) - priorityIndex <- genes$gene %in% priorityNames - if (geneMode == "focus" && !any(priorityIndex)) { - priorityIndex <- rep(TRUE, nrow(genes)) - } - - ## Label layout --------------------------------------------------------- - ## Priority: explicit `geneOrder`, then highlighted genes, then the rest. - labelPriority <- seq_len(nrow(genes)) - ord <- if (is.null(geneInternal$geneOrder)) { - rep(NA_integer_, nrow(genes)) - } else { - match(genes$gene, geneInternal$geneOrder) - } - labelPriority <- order(is.na(ord), ord, !isHighlighted, labelPriority) - labelPriority <- match(seq_len(nrow(genes)), labelPriority) - drawLabel <- if (isTRUE(geneInternal$labels)) { - rep(TRUE, nrow(genes)) - } else if (is.character(geneInternal$labels)) { - genes$gene %in% geneInternal$labels - } else { - rep(FALSE, nrow(genes)) - } - if (geneMode == "focus") { - drawLabel <- drawLabel & priorityIndex - } - labelLevel <- integer(nrow(genes)) - labelHeight <- convertHeight( - grobHeight(textGrob("Hg", gp = gpar( - fontsize = geneInternal$label.fontsize - ))), - unitTo = page_units, valueOnly = TRUE - ) - if (isTRUE(geneInternal$label.overlap) && - !isTRUE(geneInternal$labelClusters) && - any(drawLabel) && label.position == "above") { - labelIdx <- which(drawLabel) - labelCx <- vapply(labelIdx, function(i) { - toX((genes$start[i] + genes$end[i]) / 2) - }, numeric(1)) - labelW <- vapply(labelIdx, function(i) { - convertWidth( - grobWidth(textGrob( - genes$gene[i], - gp = gpar(fontsize = geneInternal$label.fontsize) - )), - unitTo = page_units, valueOnly = TRUE - ) - }, numeric(1)) - for (r in unique(genes$row[labelIdx])) { - sub <- which(genes$row[labelIdx] == r) - sub <- sub[order(labelPriority[labelIdx[sub]], labelCx[sub])] - placedCx <- list() - placedW <- list() - for (j in sub) { - lev <- 0L - repeat { - key <- as.character(lev) - ok <- TRUE - if (!is.null(placedCx[[key]])) { - ok <- all(abs(labelCx[j] - placedCx[[key]]) >= - (labelW[j] + placedW[[key]]) / 2 + 0.005) - } - if (ok) break - lev <- lev + 1L - } - placedCx[[as.character(lev)]] <- - c(placedCx[[as.character(lev)]], labelCx[j]) - placedW[[as.character(lev)]] <- - c(placedW[[as.character(lev)]], labelW[j]) - labelLevel[labelIdx[j]] <- lev - } - } - } - - ## Drawing helpers ------------------------------------------------------ - clipIntervals <- function(starts, ends) { - if (length(starts) == 0) { - return(list(start = numeric(0), end = numeric(0))) - } - keep <- ends >= chromstart & starts <= chromend - list( - start = pmax(starts[keep], chromstart), - end = pmin(ends[keep], chromend) - ) - } - mergeIntervals <- function(starts, ends, minGap) { - if (length(starts) == 0) { - return(list(start = numeric(0), end = numeric(0))) - } - ord <- order(starts) - starts <- starts[ord] - ends <- ends[ord] - ms <- starts[1] - me <- ends[1] - if (length(starts) > 1) { - for (e in 2:length(starts)) { - if (starts[e] - me[length(me)] < minGap) { - me[length(me)] <- max(me[length(me)], ends[e]) - } else { - ms <- c(ms, starts[e]) - me <- c(me, ends[e]) - } - } - } - list(start = ms, end = me) - } - - grobs <- list() - for (i in seq_len(nrow(genes))) { - g <- genes[i, ] - center <- yTop + yOffset + (g$row - 0.5) * rowHeight - col <- geneCols[i] - alpha <- if (geneMode == "focus" && !priorityIndex[i]) { - geneInternal$focus.alpha - } else { - 1 - } - x1 <- toX(g$start) - x2 <- toX(g$end) - labelTop <- center - - if (displayMode == "collapsed") { - blockHeight <- rowHeight * 0.45 - geneWidthPx <- x2 - x1 - blockWidth <- max(geneWidthPx, featureMinWidth) - blockX <- if (blockWidth > geneWidthPx) { - (x1 + x2) / 2 - blockWidth / 2 - } else { - x1 - } - grobs[[length(grobs) + 1]] <- plotRect( - x = blockX, y = center - blockHeight / 2, - width = blockWidth, height = blockHeight, - just = c("left", "top"), - fill = col, linecolor = col, lwd = 0.2, alpha = alpha, - default.units = page_units - ) - labelTop <- center - blockHeight / 2 - if (showStrand == "arrows" && blockWidth > blockHeight) { - tipSize <- min(blockHeight * 0.7, blockWidth * 0.35) - tipShift <- tipSize * 0.5 - if (g$strand == "-") { - tipX <- blockX - tipShift - arrowX <- c(tipX + tipSize, tipX, tipX + tipSize) - } else { - tipX <- blockX + blockWidth + tipShift - arrowX <- c(tipX - tipSize, tipX, tipX - tipSize) - } - grobs[[length(grobs) + 1]] <- plotPolygon( - x = arrowX, - y = c(center - blockHeight / 2, center, - center + blockHeight / 2), - fill = col, linecolor = col, lwd = 0.2, alpha = alpha, - default.units = page_units - ) - } - } else { - exons <- clipIntervals(g$exonStart[[1]], g$exonEnd[[1]]) - if (g$nExons <= 1) { - blockHeight <- rowHeight * geneInternal$exon.height - blockWidth <- max(x2 - x1, featureMinWidth) - blockX <- if (blockWidth > x2 - x1) { - (x1 + x2) / 2 - blockWidth / 2 - } else { - x1 - } - grobs[[length(grobs) + 1]] <- plotRect( - x = blockX, y = center - blockHeight / 2, - width = blockWidth, height = blockHeight, - just = c("left", "top"), - fill = col, linecolor = col, lwd = 0.2, alpha = alpha, - default.units = page_units - ) - labelTop <- center - blockHeight / 2 - if (showStrand == "arrows" && blockWidth > blockHeight) { - tipSize <- min(blockHeight * 0.7, blockWidth * 0.35) - tipShift <- tipSize * 0.5 - if (g$strand == "-") { - tipX <- blockX - tipShift - arrowX <- c(tipX + tipSize, tipX, tipX + tipSize) - } else { - tipX <- blockX + blockWidth + tipShift - arrowX <- c(tipX - tipSize, tipX, tipX - tipSize) - } - grobs[[length(grobs) + 1]] <- plotPolygon( - x = arrowX, - y = c(center - blockHeight / 2, center, - center + blockHeight / 2), - fill = col, linecolor = col, lwd = 0.2, alpha = alpha, - default.units = page_units - ) - } - } else { - grobs[[length(grobs) + 1]] <- plotSegments( - x0 = x1, y0 = center, x1 = x2, y1 = center, - linecolor = col, lwd = geneInternal$body.lwd, - alpha = alpha, default.units = page_units - ) - fullHalf <- rowHeight * geneInternal$exon.height / 2 - utrHalf <- fullHalf / 2 - exons <- mergeIntervals(exons$start, exons$end, exonMinBp) - cds <- clipIntervals(g$cdsStart[[1]], g$cdsEnd[[1]]) - cds <- mergeIntervals(cds$start, cds$end, exonMinBp) - hasCDS <- length(cds$start) > 0 - - exonHalf <- if (hasCDS) utrHalf else fullHalf - for (e in seq_along(exons$start)) { - exonWidth <- max(toX(exons$end[e]) - toX(exons$start[e]), - exonMinWidth) - grobs[[length(grobs) + 1]] <- plotRect( - x = toX(exons$start[e]), y = center - exonHalf, - width = exonWidth, height = exonHalf * 2, - just = c("left", "top"), - fill = col, linecolor = col, lwd = 0.2, alpha = alpha, - default.units = page_units - ) - } - if (hasCDS) { - for (e in seq_along(cds$start)) { - cdsWidth <- max(toX(cds$end[e]) - toX(cds$start[e]), - exonMinWidth) - grobs[[length(grobs) + 1]] <- plotRect( - x = toX(cds$start[e]), y = center - fullHalf, - width = cdsWidth, height = fullHalf * 2, - just = c("left", "top"), - fill = col, linecolor = col, lwd = 0.2, - alpha = alpha, default.units = page_units - ) - } - } - labelTop <- center - fullHalf - - if (showStrand == "arrows") { - step <- convertWidth(unit(geneInternal$arrow.spacing, - "points"), - unitTo = page_units, - valueOnly = TRUE) - if (step > 0 && (x2 - x1) > step) { - arrowHalf <- rowHeight * 0.12 - arrowSize <- min(step * 0.32, rowHeight * 0.24) - arrowXs <- seq(x1 + step / 2, x2 - step / 2, - by = step) - for (ax in arrowXs) { - if (g$strand == "-") { - ax0 <- ax + arrowSize / 2 - } else { - ax0 <- ax - arrowSize / 2 - } - grobs[[length(grobs) + 1]] <- plotSegments( - x0 = ax0, y0 = center - arrowHalf, - x1 = ax, y1 = center, - linecolor = col, lwd = 0.3, - alpha = alpha, default.units = page_units - ) - grobs[[length(grobs) + 1]] <- plotSegments( - x0 = ax, y0 = center, - x1 = ax0, y1 = center + arrowHalf, - linecolor = col, lwd = 0.3, - alpha = alpha, default.units = page_units - ) - } - } - } - } - } - - if (showStrand == "labels" && - !(geneMode == "focus" && !priorityIndex[i])) { - strandLabel <- if (g$strand == "-") { - "-" - } else if (g$strand == "+") { - "+" - } else { - "*" - } - grobs[[length(grobs) + 1]] <- plotText( - label = strandLabel, x = x1 - 0.02, y = center, - just = c("right", "center"), - fontsize = geneInternal$label.fontsize, - fontcolor = geneInternal$strand.color, - default.units = page_units, ... - ) - } - - if (drawLabel[i]) { - labelCx <- toX((g$start + g$end) / 2) - if (label.position == "center") { - labelY <- center - labelJust <- c("center", "center") - } else { - labelY <- labelTop - 0.015 - - labelLevel[i] * (labelHeight + 0.005) - labelJust <- c("center", "bottom") - if (labelLevel[i] > 0) { - grobs[[length(grobs) + 1]] <- plotSegments( - x0 = labelCx, y0 = labelTop, - x1 = labelCx, y1 = labelY, - linecolor = "grey60", lwd = 0.3, - default.units = page_units - ) - } - } - labelCol <- if (isHighlighted[i]) col else - geneInternal$label.fontcolor - grobs[[length(grobs) + 1]] <- plotText( - label = g$gene, x = labelCx, y = labelY, - just = labelJust, - fontsize = geneInternal$label.fontsize, - fontcolor = labelCol, - rot = if (isTRUE(geneInternal$labelClusters)) { - geneInternal$labelClusterRot - } else { - 0 - }, - check.overlap = FALSE, - default.units = page_units, ... - ) - } - } - - invisible(list( - genes = genes, grobs = grobs, displayMode = displayMode, - chromstart = chromstart, chromend = chromend, - bpPerInch = bpPerInch, geneMode = geneMode - )) -} diff --git a/R/readNeoGenes.R b/R/readNeoGenes.R deleted file mode 100644 index 246ba9ddd..000000000 --- a/R/readNeoGenes.R +++ /dev/null @@ -1,379 +0,0 @@ -## Internal gene-annotation readers for plotNeoGenes(). -## -## The GTF/GFF path is intentionally separate from the renderer so that the -## expensive parse can be cached and reused across plots/samples. - -.neoGeneSessionCache <- new.env(parent = emptyenv()) - -.neoGeneRegions <- function(neo) { - GenomicRanges::GRanges( - seqnames = neo$fragments$chrom, - ranges = IRanges::IRanges( - start = neo$fragments$start, - end = neo$fragments$end - ) - ) -} - -.neoGeneRegionFrame <- function(neo) { - data.frame( - chrom = as.character(neo$fragments$chrom), - chrom_raw = as.character(neo$fragments$chrom_raw), - start = as.numeric(neo$fragments$start), - end = as.numeric(neo$fragments$end), - stringsAsFactors = FALSE - ) -} - -.neoGeneCacheKey <- function(file, regions, type, tags) { - info <- file.info(file) - key <- paste( - normalizePath(file, mustWork = FALSE), - ifelse(is.na(info$size), "", info$size), - ifelse(is.na(info$mtime), "", as.numeric(info$mtime)), - paste(regions$chrom, regions$chrom_raw, regions$start, regions$end, - sep = ":", collapse = ";"), - paste(type, collapse = ","), - paste(tags, collapse = ","), - sep = "|" - ) - if (requireNamespace("digest", quietly = TRUE)) { - return(digest::digest(key, algo = "xxhash64")) - } - key <- gsub("[^A-Za-z0-9._-]+", "_", key) - substr(key, 1, 180) -} - -.neoGeneCacheGet <- function(cache, key) { - if (is.null(cache)) { - return(NULL) - } - if (isTRUE(cache)) { - dir <- tools::R_user_dir("plotgardener", which = "cache") - } else { - dir <- cache - } - if (!dir.exists(dir)) { - dir.create(dir, recursive = TRUE, showWarnings = FALSE) - } - path <- file.path(dir, paste0("neo_genes_", key, ".rds")) - if (file.exists(path)) { - return(readRDS(path)) - } - NULL -} - -.neoGeneCacheSet <- function(cache, key, value) { - if (is.null(cache)) { - return(invisible(NULL)) - } - if (isTRUE(cache)) { - dir <- tools::R_user_dir("plotgardener", which = "cache") - } else { - dir <- cache - } - if (!dir.exists(dir)) { - dir.create(dir, recursive = TRUE, showWarnings = FALSE) - } - path <- file.path(dir, paste0("neo_genes_", key, ".rds")) - saveRDS(value, path) - invisible(path) -} - -.neoGeneSubsetRegions <- function(df, regions) { - if (nrow(df) == 0) { - return(df) - } - keep <- rep(FALSE, nrow(df)) - for (i in seq_len(nrow(regions))) { - keep <- keep | ( - (df$chrom == regions$chrom[i] | - df$chrom == regions$chrom_raw[i]) & - df$start <= regions$end[i] & - df$end >= regions$start[i] - ) - } - df[keep, , drop = FALSE] -} - -.neoGeneNormalize <- function(df, regions = NULL) { - if (is.null(df) || nrow(df) == 0) { - return(data.frame( - chrom = character(0), start = numeric(0), end = numeric(0), - strand = character(0), gene = character(0), - transcript = character(0), feature = character(0), - gene_type = character(0), stringsAsFactors = FALSE - )) - } - df <- as.data.frame(df, stringsAsFactors = FALSE) - - chromCol <- intersect(c("chrom", "seqid", "seqnames"), colnames(df))[1] - featureCol <- intersect(c("feature", "type"), colnames(df))[1] - geneCol <- intersect(c("gene", "gene_name", "name"), colnames(df))[1] - idCol <- intersect(c("gene_id", "geneId", "GENEID"), colnames(df))[1] - txCol <- intersect(c("transcript", "transcript_id", "TXNAME", "TXID"), - colnames(df))[1] - typeCol <- intersect(c("gene_type", "gene_biotype", "TXTYPE"), - colnames(df))[1] - - chrom <- if (!is.na(chromCol)) as.character(df[[chromCol]]) else NA_character_ - gene <- if (!is.na(geneCol)) as.character(df[[geneCol]]) else NA_character_ - if (!is.na(idCol)) { - ids <- as.character(df[[idCol]]) - gene[is.na(gene) | !nzchar(gene)] <- ids[is.na(gene) | !nzchar(gene)] - } - gene[is.na(gene) | !nzchar(gene)] <- paste0("gene", seq_len(nrow(df)))[ - is.na(gene) | !nzchar(gene) - ] - transcript <- if (!is.na(txCol)) as.character(df[[txCol]]) else gene - transcript[is.na(transcript) | !nzchar(transcript)] <- - gene[is.na(transcript) | !nzchar(transcript)] - - out <- data.frame( - chrom = chrom, - start = as.numeric(df$start), - end = as.numeric(df$end), - strand = if ("strand" %in% colnames(df)) { - as.character(df$strand) - } else { - "*" - }, - gene = gene, - transcript = transcript, - feature = if (!is.na(featureCol)) { - as.character(df[[featureCol]]) - } else { - "exon" - }, - gene_type = if (!is.na(typeCol)) { - as.character(df[[typeCol]]) - } else { - NA_character_ - }, - stringsAsFactors = FALSE - ) - out$strand[is.na(out$strand) | !nzchar(out$strand)] <- "*" - out <- out[!is.na(out$chrom) & !is.na(out$start) & !is.na(out$end), , - drop = FALSE] - - ## GENCODE carries gene_type on every row, but some GTF/GFF files only - ## put it on the gene rows. Fill it down by gene_id/gene name. - hasType <- !is.na(out$gene_type) & nzchar(as.character(out$gene_type)) - if (any(hasType) && any(!hasType)) { - typeMap <- tapply( - as.character(out$gene_type[hasType]), - out$gene[hasType], - function(x) x[1] - ) - fillIdx <- !hasType & out$gene %in% names(typeMap) - out$gene_type[fillIdx] <- unname(typeMap[out$gene[fillIdx]]) - } - - ## Drop duplicate feature rows (common in TxDb joins). - key <- paste(out$chrom, out$start, out$end, out$strand, out$gene, - out$transcript, out$feature, sep = "|") - out <- out[!duplicated(key), , drop = FALSE] - - if (!is.null(regions)) { - out <- .neoGeneSubsetRegions(out, regions) - } - out -} - -.neoGeneReadGFF <- function(file, regions, type, tags, reader) { - regionsGR <- GenomicRanges::GRanges( - seqnames = regions$chrom, - ranges = IRanges::IRanges(regions$start, regions$end) - ) - if (reader == "readGFF") { - if (!requireNamespace("rtracklayer", quietly = TRUE)) { - stop("`rtracklayer` is required to read GTF/GFF files.", - call. = FALSE) - } - ## `readGFF` applies the seqid/type filters during the native scan and - ## only materializes the requested columns/tags. It is much lighter - ## than import(..., which = regions), which parses the whole file into - ## a GRanges first. - df <- suppressWarnings(rtracklayer::readGFF( - file, - filter = list( - seqid = unique(c(regions$chrom, regions$chrom_raw)), - type = type - ), - columns = c("seqid", "start", "end", "strand", "type"), - tags = tags - )) - return(.neoGeneNormalize(df, regions)) - } - - if (reader == "tabix") { - if (!requireNamespace("Rsamtools", quietly = TRUE) || - !requireNamespace("rtracklayer", quietly = TRUE)) { - stop("`Rsamtools` and `rtracklayer` are required for the tabix ", - "reader.", call. = FALSE) - } - if (!file.exists(paste0(file, ".tbi"))) { - stop("Tabix index not found: ", paste0(file, ".tbi"), - call. = FALSE) - } - format <- if (grepl("\\.gff3?(\\.gz)?$", file, ignore.case = TRUE)) { - "GFF3" - } else { - "GTF" - } - tbx <- Rsamtools::TabixFile(file) - present <- Rsamtools::seqnamesTabix(tbx) - queryGR <- regionsGR[ - as.character(GenomicRanges::seqnames(regionsGR)) %in% present - ] - if (length(queryGR) == 0) { - return(.neoGeneNormalize(NULL)) - } - gr <- suppressWarnings(rtracklayer::import( - tbx, format = format, which = queryGR, - feature.type = type - )) - return(.neoGeneNormalize(as.data.frame(gr), regions)) - } - - ## Fallback: the original full-file import. - if (!requireNamespace("rtracklayer", quietly = TRUE)) { - stop("`rtracklayer` is required to read GTF/GFF files.", - call. = FALSE) - } - gr <- suppressMessages(rtracklayer::import( - file, feature.type = type, which = regionsGR - )) - .neoGeneNormalize(as.data.frame(gr), regions) -} - -.readNeoGenesGFF <- function(file, neo, type, tags, - reader = c("auto", "readGFF", "import", - "tabix"), - cache = NULL) { - reader <- match.arg(reader) - regions <- .neoGeneRegionFrame(neo) - if (reader == "auto") { - if (file.exists(paste0(file, ".tbi")) && - requireNamespace("Rsamtools", quietly = TRUE)) { - reader <- "tabix" - } else if (requireNamespace("rtracklayer", quietly = TRUE)) { - reader <- "readGFF" - } else { - reader <- "import" - } - } - - key <- .neoGeneCacheKey(file, regions, type, tags) - cached <- .neoGeneCacheGet(cache, key) - if (!is.null(cached)) { - return(cached) - } - sessionKey <- paste(reader, key, sep = "|") - if (exists(sessionKey, envir = .neoGeneSessionCache, inherits = FALSE)) { - cached <- get(sessionKey, envir = .neoGeneSessionCache, - inherits = FALSE) - .neoGeneCacheSet(cache, key, cached) - return(cached) - } - - df <- .neoGeneReadGFF(file, regions, type, tags, reader) - assign(sessionKey, df, envir = .neoGeneSessionCache) - .neoGeneCacheSet(cache, key, df) - df -} - -.readNeoGenesTxDb <- function(txdb, orgdb, neo, assemblyName, - gene.id.column = NULL, - display.column = NULL) { - if (!requireNamespace("GenomicFeatures", quietly = TRUE) || - !requireNamespace("AnnotationDbi", quietly = TRUE)) { - stop("`GenomicFeatures` and `AnnotationDbi` are required for TxDb ", - "gene annotation.", call. = FALSE) - } - if (is.null(display.column)) { - display.column <- if (is.null(orgdb)) "GENEID" else "SYMBOL" - } - if (is.null(gene.id.column)) { - gene.id.column <- if (identical(display.column, "GENEID")) { - "GENEID" - } else { - "ENTREZID" - } - } - asm <- assembly( - Genome = assemblyName, - TxDb = txdb, - OrgDb = if (is.null(orgdb)) NA else orgdb, - gene.id.column = gene.id.column, - display.column = display.column - ) - regions <- .neoGeneRegionFrame(neo) - chroms <- unique(regions$chrom) - parts <- lapply(chroms, function(ch) { - rr <- regions[regions$chrom == ch, , drop = FALSE] - getExons( - assembly = asm, - chromosome = ch, - start = min(rr$start), - stop = max(rr$end) - ) - }) - parts <- Filter(function(x) !is.null(x) && nrow(x) > 0, parts) - if (length(parts) == 0) { - return(.neoGeneNormalize(NULL)) - } - d <- do.call(rbind, parts) - - displayCol <- if (display.column %in% colnames(d)) { - display.column - } else if ("SYMBOL" %in% colnames(d)) { - "SYMBOL" - } else { - "GENEID" - } - gene <- as.character(d[[displayCol]]) - gene[is.na(gene) | !nzchar(gene)] <- as.character(d$GENEID)[ - is.na(gene) | !nzchar(gene) - ] - transcript <- if ("TXNAME" %in% colnames(d)) { - as.character(d$TXNAME) - } else { - as.character(d$TXID) - } - transcript[is.na(transcript) | !nzchar(transcript)] <- - gene[is.na(transcript) | !nzchar(transcript)] - - exons <- data.frame( - chrom = as.character(d$TXCHROM), - start = as.numeric(d$EXONSTART), - end = as.numeric(d$EXONEND), - strand = as.character(d$TXSTRAND), - gene = gene, - transcript = transcript, - feature = "exon", - gene_type = if ("TXTYPE" %in% colnames(d)) { - as.character(d$TXTYPE) - } else { - NA_character_ - }, - stringsAsFactors = FALSE - ) - - if (all(c("CDSSTART", "CDSEND") %in% colnames(d))) { - cdsKeep <- !is.na(d$CDSSTART) & !is.na(d$CDSEND) - cds <- data.frame( - chrom = as.character(d$TXCHROM)[cdsKeep], - start = as.numeric(d$CDSSTART)[cdsKeep], - end = as.numeric(d$CDSEND)[cdsKeep], - strand = as.character(d$TXSTRAND)[cdsKeep], - gene = gene[cdsKeep], - transcript = transcript[cdsKeep], - feature = "CDS", - gene_type = exons$gene_type[cdsKeep], - stringsAsFactors = FALSE - ) - exons <- rbind(exons, cds) - } - .neoGeneNormalize(exons, regions) -} diff --git a/R/readNeoHic.R b/R/readNeoHic.R deleted file mode 100644 index dcde5b917..000000000 --- a/R/readNeoHic.R +++ /dev/null @@ -1,548 +0,0 @@ -#' @keywords internal -.neoFileType <- function(file) { - ext <- tolower(tools::file_ext(file)) - if (ext == "hic") { - "hic" - } else if (ext %in% c("cool", "mcool")) { - "cool" - } else { - stop("`data` must be a .hic, .cool, or .mcool file.", call. = FALSE) - } -} - -#' @keywords internal -.neoFileResolutions <- function(file, fileType) { - if (fileType == "hic") { - strawr::readHicBpResolutions(file) - } else { - readCoolBpResolutions(file) - } -} - -#' @keywords internal -.neoAutoResolution <- function(file, fileType, neo, targetBins = 1000) { - resolutions <- .neoFileResolutions(file, fileType) - target <- neo$total_length / targetBins - resolutions[which.min(abs(resolutions - target))] -} - -#' @keywords internal -.neoMapPosition <- function(position, fragments, resolution, chrom = NULL) { - candidates <- fragments - if (!is.null(chrom)) { - candidates <- candidates[candidates$chrom == chrom, , drop = FALSE] - } - if (nrow(candidates) == 0) { - return(list(neo = NA_real_, fragment = NA_integer_)) - } - - exact <- which(position >= candidates$start & position < candidates$end) - if (length(exact) == 0) { - return(list(neo = NA_real_, fragment = NA_integer_)) - } - exact <- exact[1] - - frag <- candidates[exact, ] - if (frag$flipped) { - neoPosition <- frag$offset + (frag$end - (position + resolution)) - } else { - neoPosition <- frag$offset + (position - frag$start) - } - - neoPosition <- max(frag$offset, - min(neoPosition, frag$offset + frag$length - resolution)) - list(neo = neoPosition, fragment = frag$id) -} - -#' @keywords internal -.neoReadPair <- function(data, fileType, fi, fj, resolution, norm, matrix, - assembly) { - if (fileType == "hic") { - start1 <- max(1, fi$start) - end1 <- max(start1 + 1, fi$end) - start2 <- max(1, fj$start) - end2 <- max(start2 + 1, fj$end) - - if (fi$id == fj$id) { - readHic( - file = data, chrom = fi$chrom, - chromstart = start1, chromend = end1, - resolution = resolution, norm = norm, matrix = matrix, - assembly = assembly, zrange = NULL, quiet = TRUE - ) - } else { - readHic( - file = data, chrom = fi$chrom, - chromstart = start1, chromend = end1, - altchrom = fj$chrom, - altchromstart = start2, altchromend = end2, - resolution = resolution, norm = norm, matrix = matrix, - assembly = assembly, zrange = NULL, quiet = TRUE - ) - } - } else { - start1 <- max(0, fi$start) - end1 <- max(start1 + 1, fi$end) - start2 <- max(0, fj$start) - end2 <- max(start2 + 1, fj$end) - - if (fi$id == fj$id) { - readCool( - file = data, chrom = fi$chrom, - chromstart = start1, chromend = end1, - resolution = resolution, norm = norm, - zrange = NULL, quiet = TRUE - ) - } else { - readCool( - file = data, chrom = fi$chrom, - chromstart = start1, chromend = end1, - altchrom = fj$chrom, - altchromstart = start2, altchromend = end2, - resolution = resolution, norm = norm, - zrange = NULL, quiet = TRUE - ) - } - } -} - -#' @keywords internal -.neoEstimateResolution <- function(data) { - starts <- sort(unique(c(data$start1, data$start2))) - diffs <- diff(starts) - diffs <- diffs[diffs > 0] - if (length(diffs) == 0) { - stop("Cannot estimate `resolution` from the data frame; supply a ", - "numeric resolution.", call. = FALSE) - } - as.numeric(min(diffs)) -} - -#' @keywords internal -.neoNormalizePairData <- function(data) { - data <- as.data.frame(data, stringsAsFactors = FALSE) - cn <- colnames(data) - - if (all(c("chrom1", "start1", "chrom2", "start2") %in% cn)) { - countCol <- if ("counts" %in% cn) { - "counts" - } else if ("count" %in% cn) { - "count" - } else { - stop("`data` must contain a `counts` or `count` column.", - call. = FALSE) - } - out <- data.frame( - chrom1 = as.character(data$chrom1), - start1 = as.numeric(data$start1), - chrom2 = as.character(data$chrom2), - start2 = as.numeric(data$start2), - counts = as.numeric(data[[countCol]]), - stringsAsFactors = FALSE - ) - } else if (all(c("chrom", "start1", "start2") %in% cn)) { - countCol <- if ("counts" %in% cn) { - "counts" - } else if ("count" %in% cn) { - "count" - } else { - stop("`data` must contain a `counts` or `count` column.", - call. = FALSE) - } - out <- data.frame( - chrom1 = as.character(data$chrom), - start1 = as.numeric(data$start1), - chrom2 = as.character(data$chrom), - start2 = as.numeric(data$start2), - counts = as.numeric(data[[countCol]]), - stringsAsFactors = FALSE - ) - } else if (ncol(data) >= 5 && - is.character(data[[1]]) && is.numeric(data[[2]]) && - is.character(data[[3]]) && is.numeric(data[[4]]) && - is.numeric(data[[5]])) { - ## Accept `readCool()`/`readHic()` interchromosomal-like output: - ## chrom1, start1, chrom2, start2, counts - out <- data.frame( - chrom1 = as.character(data[[1]]), - start1 = as.numeric(data[[2]]), - chrom2 = as.character(data[[3]]), - start2 = as.numeric(data[[4]]), - counts = as.numeric(data[[5]]), - stringsAsFactors = FALSE - ) - } else { - stop("`data` must be a data frame with columns ", - "`chrom1`, `start1`, `chrom2`, `start2`, `counts`, or ", - "`chrom`, `start1`, `start2`, `counts`.", call. = FALSE) - } - - out -} - -#' @keywords internal -.neoMakeHic <- function(matrixDf, neo, resolution, norm, matrix, file, - zrange, quiet, pairCounts = NULL) { - if (!is.null(zrange)) { - matrixDf <- scale_data(upper = matrixDf, zrange = zrange) - } - - neoHic <- structure( - list( - matrix = matrixDf, - neo = neo, - resolution = resolution, - norm = norm, - matrix_type = matrix, - file = file, - pair_counts = pairCounts - ), - class = c("neoHic", "list") - ) - - if (!quiet) { - message("neoHic[", nrow(matrixDf), " pixels at ", - resolution, " bp]") - } - - neoHic -} - - -#' Reconstruct an SV-impacted contact matrix in neo-chromosome coordinates -#' -#' @param data Path to a `.hic`, `.cool`, or `.mcool` file, or a data frame -#' of precomputed genomic contacts with columns \code{chrom1}, \code{start1}, -#' \code{chrom2}, \code{start2}, and \code{counts}. A data frame with -#' \code{chrom}, \code{start1}, \code{start2}, and \code{counts} is also -#' accepted for intrachromosomal data. -#' @param neo A `neoAssembly` object from \code{readNeoAssembly()}, or a path -#' to an assembly file. If a path is supplied, \code{id} is required. -#' @param id Assembly ID when \code{neo} is an assembly file path. -#' @param resolution Resolution in basepairs, or \code{"auto"} to choose -#' a resolution close to 1000 bins across the neo-chromosome. For data frame -#' input, \code{"auto"} estimates the smallest positive spacing between bins. -#' @param norm Normalization to pass to \code{readHic()} or \code{readCool()}. -#' Default value is \code{norm = "NONE"}. -#' @param matrix Matrix type for `.hic` files. Default value is -#' \code{matrix = "observed"}. -#' @param zrange Optional numeric vector of length 2 used to clip the final -#' reconstructed counts. Default value is \code{zrange = NULL}. -#' @param assembly Genome assembly for `.hic` files and for reading an -#' assembly file path. Default value is \code{assembly = "hg38"}. -#' @param extend Basepairs to extend the first and last fragments when -#' \code{neo} is a file path. Default value is \code{extend = 0}. -#' @param prefix Prefix for chromosome names when \code{neo} is a file path. -#' Default value is \code{prefix = "chr"}. -#' @param quiet A logical indicating whether to print progress messages. -#' -#' @return A `neoHic` object: a list with \code{matrix} (a data frame of -#' \code{x}, \code{y}, \code{counts} in neo coordinates), \code{neo}, -#' \code{resolution}, \code{norm}, and \code{matrix_type}. -#' -#' @details -#' For file input, the reconstruction reads each fragment pair from the source -#' file and maps genomic bin starts onto the concatenated neo-chromosome. -#' Contacts are assigned only to the fragment pair being read, so pixels from -#' adjacent fragments are not double-counted. For data frame input, each row's -#' genomic coordinates are mapped to neo coordinates using the same rules. -#' -#' @examples -#' \dontrun{ -#' neo <- readNeoAssembly("HM1_merged.assemblies.txt", "C1", extend = 200000) -#' neoHic <- readNeoHic("HM1_merged.mcool", neo, resolution = 5000) -#' plotNeoHic(neoHic, type = "triangle") -#' -#' ## Or pass the assembly path and ID directly -#' neoHic2 <- readNeoHic( -#' "HM1_merged.mcool", -#' "HM1_merged.assemblies.txt", id = "C1", -#' extend = 200000, resolution = 5000 -#' ) -#' } -#' @export -readNeoHic <- function(data, neo, id = NULL, resolution = "auto", - norm = "NONE", matrix = "observed", zrange = NULL, - assembly = "hg38", extend = 0, prefix = "chr", - quiet = FALSE) { - - if (missing(data) || is.null(data)) { - stop("argument \"data\" is missing, with no default.", call. = FALSE) - } - if (is.character(neo)) { - if (is.null(id)) { - stop("`id` must be supplied when `neo` is an assembly file path.", - call. = FALSE) - } - neo <- readNeoAssembly( - file = neo, id = id, assembly = assembly, - extend = extend, prefix = prefix, quiet = quiet - ) - } - if (!inherits(neo, "neoAssembly")) { - stop("`neo` must be a `neoAssembly` object or an assembly file path.", - call. = FALSE) - } - - if (is.data.frame(data)) { - pairData <- .neoNormalizePairData(data) - if (identical(resolution, "auto")) { - resolution <- .neoEstimateResolution(pairData) - } - if (!is.numeric(resolution) || length(resolution) != 1 || - resolution <= 0) { - stop("`resolution` must be a positive number or \"auto\".", - call. = FALSE) - } - resolution <- as.numeric(resolution) - - fragments <- neo$fragments - mx <- lapply(seq_len(nrow(pairData)), function(k) { - .neoMapPosition(pairData$start1[k], fragments, - resolution = resolution, - chrom = pairData$chrom1[k]) - }) - my <- lapply(seq_len(nrow(pairData)), function(k) { - .neoMapPosition(pairData$start2[k], fragments, - resolution = resolution, - chrom = pairData$chrom2[k]) - }) - keep <- vapply(seq_len(nrow(pairData)), function(k) { - !is.na(mx[[k]]$fragment) && !is.na(my[[k]]$fragment) - }, logical(1)) - - if (!any(keep)) { - matrixDf <- data.frame( - x = numeric(0), y = numeric(0), counts = numeric(0) - ) - } else { - nx <- vapply(mx[keep], `[[`, numeric(1), "neo") - ny <- vapply(my[keep], `[[`, numeric(1), "neo") - matrixDf <- data.frame( - x = pmin(nx, ny), - y = pmax(nx, ny), - counts = pairData$counts[keep], - stringsAsFactors = FALSE - ) - matrixDf <- aggregate(counts ~ x + y, data = matrixDf, FUN = sum) - } - - return(.neoMakeHic( - matrixDf = matrixDf, neo = neo, resolution = resolution, - norm = norm, matrix = matrix, file = NA_character_, - zrange = zrange, quiet = quiet - )) - } - - if (!is.character(data) || length(data) != 1) { - stop("`data` must be a file path or data frame.", call. = FALSE) - } - if (!file.exists(data)) { - stop("Data file does not exist: ", data, call. = FALSE) - } - - fileType <- .neoFileType(data) - if (identical(resolution, "auto")) { - resolution <- .neoAutoResolution( - file = data, fileType = fileType, neo = neo - ) - } - if (!is.numeric(resolution) || length(resolution) != 1 || - resolution <= 0) { - stop("`resolution` must be a positive number or \"auto\".", - call. = FALSE) - } - resolution <- as.numeric(resolution) - - fragments <- neo$fragments - nFragments <- nrow(fragments) - parts <- list() - pairStats <- list() - - for (i in seq_len(nFragments)) { - for (j in i:nFragments) { - fi <- fragments[i, ] - fj <- fragments[j, ] - if (!quiet) { - message("neo pair ", i, "-", j, ": ", - fi$chrom, ":", fi$start, "-", fi$end, " / ", - fj$chrom, ":", fj$start, "-", fj$end) - } - - pairData <- .neoReadPair( - data = data, fileType = fileType, fi = fi, fj = fj, - resolution = resolution, norm = norm, matrix = matrix, - assembly = assembly - ) - - if (nrow(pairData) == 0) { - pairStats[[length(pairStats) + 1]] <- data.frame( - fragment1 = i, fragment2 = j, - pixels = 0L, counts = 0, stringsAsFactors = FALSE - ) - next - } - - x <- as.numeric(pairData[[1]]) - y <- as.numeric(pairData[[2]]) - counts <- as.numeric(pairData[[3]]) - - mx <- lapply(x, .neoMapPosition, - fragments = fragments, resolution = resolution, - chrom = fi$chrom) - my <- lapply(y, .neoMapPosition, - fragments = fragments, resolution = resolution, - chrom = fj$chrom) - - keep <- vapply(seq_along(x), function(k) { - fx <- mx[[k]]$fragment - fy <- my[[k]]$fragment - if (is.na(fx) || is.na(fy)) { - FALSE - } else if (i == j) { - fx == i && fy == i - } else { - (fx == i && fy == j) || (fx == j && fy == i) - } - }, logical(1)) - - if (!any(keep)) { - pairStats[[length(pairStats) + 1]] <- data.frame( - fragment1 = i, fragment2 = j, - pixels = 0L, counts = 0, stringsAsFactors = FALSE - ) - next - } - - nx <- vapply(mx[keep], `[[`, numeric(1), "neo") - ny <- vapply(my[keep], `[[`, numeric(1), "neo") - - parts[[length(parts) + 1]] <- data.frame( - x = pmin(nx, ny), - y = pmax(nx, ny), - counts = counts[keep], - stringsAsFactors = FALSE - ) - pairStats[[length(pairStats) + 1]] <- data.frame( - fragment1 = i, fragment2 = j, - pixels = sum(keep), counts = sum(counts[keep]), - stringsAsFactors = FALSE - ) - } - } - - if (length(parts) == 0) { - matrixDf <- data.frame( - x = numeric(0), y = numeric(0), counts = numeric(0) - ) - } else { - matrixDf <- do.call(rbind, parts) - matrixDf <- aggregate(counts ~ x + y, data = matrixDf, FUN = sum) - } - - pairCounts <- if (length(pairStats) > 0) { - do.call(rbind, pairStats) - } else { - NULL - } - if (!quiet && !is.null(pairCounts)) { - emptyInter <- pairCounts$fragment1 != pairCounts$fragment2 & - pairCounts$pixels == 0 - if (any(emptyInter)) { - warning( - "No inter-fragment contacts found for fragment pairs: ", - paste0(pairCounts$fragment1[emptyInter], "-", - pairCounts$fragment2[emptyInter], collapse = ", "), - ". The source Hi-C file may have no contacts in those ", - "fragment intervals.", call. = FALSE - ) - } - } - - .neoMakeHic( - matrixDf = matrixDf, neo = neo, resolution = resolution, - norm = norm, matrix = matrix, - file = normalizePath(data, mustWork = TRUE), - zrange = zrange, quiet = quiet, - pairCounts = pairCounts - ) -} - -#' @export -print.neoHic <- function(x, ...) { - cat("neoHic\n") - cat(" matrix:", nrow(x$matrix), "pixels\n") - cat(" resolution:", x$resolution, "bp\n") - cat(" norm:", x$norm, "\n") - cat(" neo length:", x$neo$total_length, "bp\n") - if (!is.null(x$pair_counts)) { - cat(" fragment-pair pixels:\n") - print(x$pair_counts, row.names = FALSE) - } - invisible(x) -} - -#' Plot a reconstructed neo-chromosome contact matrix -#' -#' @param neoHic A `neoHic` object from \code{readNeoHic()}. -#' @param type Hi-C plot type: \code{"triangle"}, \code{"square"}, or -#' \code{"rectangle"}. Default value is \code{type = "triangle"}. -#' @param flip Orientation. \code{"none"} or \code{FALSE} leaves the plot -#' unchanged, \code{"horizontal"} mirrors the x-axis so the opposite -#' chromosome is on the left, and \code{TRUE} retains the legacy vertical -#' triangle flip. Default value is \code{flip = "none"}. -#' @param ... Additional arguments passed to the corresponding -#' \code{plotHic*} function. -#' -#' @return The plot object returned by \code{plotHicTriangle()}, -#' \code{plotHicSquare()}, or \code{plotHicRectangle()}. -#' -#' @examples -#' \dontrun{ -#' neoHic <- readNeoHic("HM1_merged.mcool", neo, resolution = 5000) -#' plotNeoHic(neoHic, type = "square", x = 1, y = 1, width = 2, height = 2) -#' } -#' @export -plotNeoHic <- function(neoHic, type = c("triangle", "square", "rectangle"), - flip = c("none", "horizontal"), ...) { - if (!inherits(neoHic, "neoHic")) { - stop("`neoHic` must be a `neoHic` object.", call. = FALSE) - } - type <- match.arg(type) - flip <- flip[1] - verticalFlip <- FALSE - if (is.logical(flip)) { - verticalFlip <- isTRUE(flip) - flip <- "none" - } else { - flip <- match.arg(flip, c("none", "horizontal")) - } - - args <- list( - data = neoHic$matrix, - chrom = "neo", - chromstart = 0, - chromend = neoHic$neo$total_length, - resolution = neoHic$resolution, - ... - ) - if (verticalFlip) { - args$flip <- TRUE - } - if (identical(flip, "horizontal")) { - if (type == "rectangle") { - warning("Horizontal flipping is currently supported for triangle ", - "and square neo-Hi-C plots.", call. = FALSE) - } else { - args$xaxisDir <- "decrease" - } - } - - fun <- switch(type, - triangle = plotHicTriangle, - square = plotHicSquare, - rectangle = plotHicRectangle - ) - - do.call(fun, args) -} diff --git a/man/annoNeoDomains.Rd b/man/annoNeoDomains.Rd deleted file mode 100644 index 1ccd3b0f8..000000000 --- a/man/annoNeoDomains.Rd +++ /dev/null @@ -1,67 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/plotNeo.R -\name{annoNeoDomains} -\alias{annoNeoDomains} -\title{This mirrors the visual convention used by the neo-triangle examples: -a solid domain outline around the full neo-chromosome and dotted domain -outlines at each internal fragment seam.} -\usage{ -annoNeoDomains( - plot, - neo, - outer = TRUE, - seams = TRUE, - linecolor = "black", - lwd = 0.5, - lty = 1, - seam.color = NULL, - seam.lwd = NULL, - seam.lty = 2, - ... -) -} -\arguments{ -\item{plot}{A Hi-C plot object from \code{plotHicSquare()}, -\code{plotHicTriangle()}, or \code{plotHicRectangle()}.} - -\item{neo}{A `neoAssembly` object.} - -\item{outer}{Logical value indicating whether to draw the outer -neo-chromosome domain outline. Default value is \code{outer = TRUE}.} - -\item{seams}{Logical value indicating whether to draw internal fragment -seams. Default value is \code{seams = TRUE}.} - -\item{linecolor}{Domain line color. Default value is -\code{linecolor = "black"}.} - -\item{lwd}{Domain line width. Default value is \code{lwd = 0.5}.} - -\item{lty}{Outer domain line type. Default value is \code{lty = 1}.} - -\item{seam.color}{Seam line color. Defaults to \code{linecolor}.} - -\item{seam.lwd}{Seam line width. Defaults to \code{lwd}.} - -\item{seam.lty}{Seam line type. Default value is \code{seam.lty = 2} -(dotted).} - -\item{...}{Additional arguments passed to \code{annoDomains()}.} -} -\value{ -Invisibly returns a list with \code{outer} and \code{seams} -\code{annoDomains} objects. -} -\description{ -This mirrors the visual convention used by the neo-triangle examples: -a solid domain outline around the full neo-chromosome and dotted domain -outlines at each internal fragment seam. -} -\examples{ -\dontrun{ -neoHic <- readNeoHic("HM1_merged.mcool", neo, resolution = 5000) -h <- plotNeoHic(neoHic, type = "triangle", x = 1, y = 1, - width = 2, height = 1) -annoNeoDomains(h, neo) -} -} diff --git a/man/annoNeoFragmentLabels.Rd b/man/annoNeoFragmentLabels.Rd deleted file mode 100644 index fb1e1bc47..000000000 --- a/man/annoNeoFragmentLabels.Rd +++ /dev/null @@ -1,120 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/plotNeo.R -\name{annoNeoFragmentLabels} -\alias{annoNeoFragmentLabels} -\title{Add flexible labels to an SV neo-chromosome assembly} -\usage{ -annoNeoFragmentLabels( - neo, - x, - y, - width, - height = 0, - just = c("left", "top"), - default.units = "inches", - labels = TRUE, - label.style = "chrom", - label.fontsize = 7, - label.fontcolor = "black", - label.colors = NULL, - label.fontfamily = "", - label.fontface = 1, - label.rot = 0, - label.position = "center", - label.offset = 0.1, - show.inversion = FALSE, - inversion.suffix = " (inv)", - inversion.color = "red", - params = NULL, - ... -) -} -\arguments{ -\item{neo}{A `neoAssembly` object.} - -\item{x}{A numeric or unit object specifying the label row x-location.} - -\item{y}{A numeric or unit object specifying the label row y-location.} - -\item{width}{A numeric or unit object specifying the label row width.} - -\item{height}{A numeric or unit object specifying the label row height. -Default value is \code{height = 0}.} - -\item{just}{Justification of the label row relative to (x, y). -Default value is \code{just = c("left", "top")}.} - -\item{default.units}{Default units for numeric \code{x}, \code{y}, -\code{width}, and \code{height}. Default value is -\code{default.units = "inches"}.} - -\item{labels}{Logical value or character vector of labels. -If \code{TRUE}, labels are generated from \code{label.style}. -Default value is \code{labels = TRUE}.} - -\item{label.style}{Label style when \code{labels = TRUE}: \code{"chrom"} -(chromosome name), \code{"coordinate"} (chromosome and Mb coordinates), or -\code{"fragment"} (fragment number). Default value is -\code{label.style = "chrom"}.} - -\item{label.fontsize}{Label font size. Default value is -\code{label.fontsize = 7}.} - -\item{label.fontcolor}{Label color. Can be a vector recycled across -fragments. Default value is \code{label.fontcolor = "black"}.} - -\item{label.colors}{Optional explicit per-fragment colors. Overrides -\code{label.fontcolor} and inversion coloring.} - -\item{label.fontfamily}{Label font family. Default value is -\code{label.fontfamily = ""}.} - -\item{label.fontface}{Label font face. Default value is -\code{label.fontface = 1}.} - -\item{label.rot}{Label rotation in degrees. Default value is -\code{label.rot = 0}.} - -\item{label.position}{Label position relative to the fragment row: -\code{"center"}, \code{"above"}, or \code{"below"}. -Default value is \code{label.position = "center"}.} - -\item{label.offset}{Vertical offset in page units for \code{"above"} or -\code{"below"} positions. Default value is \code{label.offset = 0.1}.} - -\item{show.inversion}{Logical value indicating whether flipped fragments -should be marked. Default value is \code{show.inversion = FALSE}.} - -\item{inversion.suffix}{Suffix appended to flipped-fragment labels. -Default value is \code{inversion.suffix = " (inv)"}.} - -\item{inversion.color}{Color for flipped-fragment labels. Default value is -\code{inversion.color = "red"}.} - -\item{params}{An optional \link[plotgardener]{pgParams} object.} - -\item{...}{Additional arguments passed to \code{plotText()}.} -} -\value{ -Invisibly returns a list of \code{plotText()} objects. -} -\description{ -This is a label-only companion to \code{plotNeoAssembly()}. It is useful -when fragment labels need custom y-offsets, gaps, fonts, rotation, or -inversion highlighting without adding more arguments to the backbone -function. -} -\examples{ -\dontrun{ -plotNeoAssembly(neo, x = 1, y = 3, width = 3, height = 0.15, - labels = FALSE) -annoNeoFragmentLabels( - neo, x = 1, y = 3.25, width = 3, - label.style = "coordinate", - label.position = "below", - label.offset = 0.05, - label.fontface = "italic", - show.inversion = TRUE -) -} -} diff --git a/man/getNeoSignal.Rd b/man/getNeoSignal.Rd deleted file mode 100644 index f60f981e6..000000000 --- a/man/getNeoSignal.Rd +++ /dev/null @@ -1,46 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/neoSignal.R -\name{getNeoSignal} -\alias{getNeoSignal} -\title{Map a signal track onto neo-chromosome coordinates} -\usage{ -getNeoSignal( - data, - neo, - binSize = 1000, - fun = c("mean", "median", "sum", "max", "min"), - value.col = NULL, - chromstart = NULL, - chromend = NULL, - ... -) -} -\arguments{ -\item{data}{A bigWig path, `GRanges` object, or data frame with -`chrom`, `start`, `end`, and a signal column.} - -\item{neo}{A `neoAssembly` object.} - -\item{binSize}{Bin size in basepairs for the neo-coordinate output. Use -`NULL` to keep the input intervals. Default value is `1000`.} - -\item{fun}{Aggregation function for binning: `"mean"`, `"median"`, -`"sum"`, `"max"`, or `"min"`. Default value is `"mean"`.} - -\item{value.col}{Name of the signal column. If `NULL`, the function looks -for `"score"`, `"balanced"`, `"value"`, or the last numeric column.} - -\item{chromstart, chromend}{Optional neo-coordinate window. Only intervals -overlapping this window are returned.} - -\item{...}{Additional arguments passed to `readBigwig()`.} -} -\value{ -A data frame with `chrom`, `start`, `end`, and `score`. -} -\description{ -Maps bigWig, `GRanges`, or data-frame signal data through the -neo-chromosome topology and optionally bins it in neo coordinates. This -handles RNA-seq, ChIP-seq, and other genome-wide signal tracks in the same -way, including fragments that are inverted. -} diff --git a/man/getNeoV4C.Rd b/man/getNeoV4C.Rd deleted file mode 100644 index 572e54411..000000000 --- a/man/getNeoV4C.Rd +++ /dev/null @@ -1,30 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/neoSignal.R -\name{getNeoV4C} -\alias{getNeoV4C} -\title{Map a virtual-4C table onto neo-chromosome coordinates} -\usage{ -getNeoV4C(file, neo, value.col = "balanced", binSize = NULL, fun = "mean", ...) -} -\arguments{ -\item{file}{Path to a virtual-4C TSV file.} - -\item{neo}{A `neoAssembly` object.} - -\item{value.col}{Signal column. Default value is `"balanced"`.} - -\item{binSize}{Optional bin size. Default value is `NULL`, which keeps the -table's own intervals.} - -\item{fun}{Aggregation function when `binSize` is supplied.} - -\item{...}{Additional arguments passed to `getNeoSignal()`.} -} -\value{ -A data frame with `chrom`, `start`, `end`, and `score`. -} -\description{ -Convenience wrapper around `getNeoSignal()` for cooltools virtual-4C TSV -files. The table is mapped through the neo topology and adjacent intervals -are clipped so they do not overlap. -} diff --git a/man/mapNeoFeatures.Rd b/man/mapNeoFeatures.Rd deleted file mode 100644 index 950fb9aaa..000000000 --- a/man/mapNeoFeatures.Rd +++ /dev/null @@ -1,33 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/neoAssembly.R -\name{mapNeoFeatures} -\alias{mapNeoFeatures} -\title{Map genomic features to neo-chromosome coordinates} -\usage{ -mapNeoFeatures(data, neo) -} -\arguments{ -\item{data}{A data frame with columns \code{chrom}, \code{start}, and -\code{end}, or a \link[GenomicRanges]{GRanges} object.} - -\item{neo}{A `neoAssembly` object from \code{readNeoAssembly()}.} -} -\value{ -A data frame with \code{chrom = "neo"}, neo-coordinate -\code{start}/\code{end}, and a \code{fragment} column. Features that span -multiple fragments are split across fragments. If a \code{strand} column is -present, it is flipped for reverse-complemented fragments. -} -\description{ -Map genomic features to neo-chromosome coordinates -} -\examples{ -\dontrun{ -neo <- readNeoAssembly("HM1_merged.assemblies.txt", "C1", extend = 200000) -features <- data.frame( - chrom = "chr12", start = 65822483, end = 65968291, - name = "HMGA2", strand = "+" -) -mapNeoFeatures(features, neo) -} -} diff --git a/man/plotNeoAssembly.Rd b/man/plotNeoAssembly.Rd deleted file mode 100644 index 7091b5e61..000000000 --- a/man/plotNeoAssembly.Rd +++ /dev/null @@ -1,104 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/plotNeo.R -\name{plotNeoAssembly} -\alias{plotNeoAssembly} -\title{Draw an SV neo-chromosome assembly backbone} -\usage{ -plotNeoAssembly( - neo, - x, - y, - width, - height, - just = c("left", "top"), - default.units = "inches", - fill = "#D4EEF9", - linecolor = "white", - lwd = 0.5, - fragment.height = 0.6, - arrow.size = NULL, - labels = TRUE, - label.fontsize = 7, - label.fontcolor = "black", - show.seams = TRUE, - seam.color = "grey40", - seam.lwd = 0.5, - seam.lty = 1, - params = NULL, - ... -) -} -\arguments{ -\item{neo}{A `neoAssembly` object from \code{readNeoAssembly()}.} - -\item{x}{A numeric or unit object specifying the backbone x-location.} - -\item{y}{A numeric, unit object, or character containing a "b" combined -with a numeric value specifying the backbone y-location.} - -\item{width}{A numeric or unit object specifying the backbone width.} - -\item{height}{A numeric or unit object specifying the backbone height.} - -\item{just}{Justification of the backbone relative to its (x, y) location. -Default value is \code{just = c("left", "top")}.} - -\item{default.units}{A string indicating the default units to use if -\code{x}, \code{y}, \code{width}, or \code{height} are only given as -numerics. Default value is \code{default.units = "inches"}.} - -\item{fill}{Fill color(s) for fragments. A single value, a vector of -length equal to the number of fragments, or a named vector keyed by -chromosome name. Default value is \code{fill = "#D4EEF9"}.} - -\item{linecolor}{Fragment outline color. Default value is -\code{linecolor = "white"}.} - -\item{lwd}{Fragment outline line width. Default value is \code{lwd = 0.5}.} - -\item{fragment.height}{Fraction of \code{height} used by the fragment -arrows. Default value is \code{fragment.height = 0.6}.} - -\item{arrow.size}{Arrow-tip size in page units. If \code{NULL}, the tip is -sized relative to each fragment.} - -\item{labels}{Logical value indicating whether to draw fragment labels, or -a character vector of labels. Default value is \code{labels = TRUE}.} - -\item{label.fontsize}{Fragment label font size. -Default value is \code{label.fontsize = 7}.} - -\item{label.fontcolor}{Fragment label color. -Default value is \code{label.fontcolor = "black"}.} - -\item{show.seams}{Logical value indicating whether to draw fragment -boundaries. Default value is \code{show.seams = TRUE}.} - -\item{seam.color}{Fragment boundary color. -Default value is \code{seam.color = "grey40"}.} - -\item{seam.lwd}{Fragment boundary line width. Default value is -\code{seam.lwd = 0.5}.} - -\item{seam.lty}{Fragment boundary line type. Default value is -\code{seam.lty = 1}.} - -\item{params}{An optional \link[plotgardener]{pgParams} object.} - -\item{...}{Additional grid graphical parameters. See \link[grid]{gpar}.} -} -\value{ -Invisibly returns a list containing the fragment polygons, labels, -and boundary segments. -} -\description{ -Draw a directional fragment backbone for a `neoAssembly` object. Each -fragment is drawn as an arrow pointing in its neo-chromosome orientation. -} -\examples{ -\dontrun{ -neo <- readNeoAssembly("HM1_merged.assemblies.txt", "C1", extend = 200000) -pageCreate(width = 6, height = 2, default.units = "inches") -plotNeoAssembly(neo, x = 0.5, y = 0.5, width = 3, height = 0.2) -} -} diff --git a/man/plotNeoGenes.Rd b/man/plotNeoGenes.Rd deleted file mode 100644 index 7bafb0722..000000000 --- a/man/plotNeoGenes.Rd +++ /dev/null @@ -1,190 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/plotNeo.R -\name{plotNeoGenes} -\alias{plotNeoGenes} -\title{Plot IGV-style gene models in neo-chromosome coordinates} -\usage{ -plotNeoGenes( - data = NULL, - neo, - x, - y, - width, - height, - txdb = NULL, - orgdb = NULL, - assembly = NULL, - gene.id.column = NULL, - display.column = NULL, - just = c("left", "top"), - default.units = "inches", - displayMode = c("auto", "collapsed", "expanded", "squished"), - chromstart = 0, - chromend = NULL, - color = "black", - highlight.color = "red", - geneHighlights = NULL, - gene.type = "protein_coding", - geneOrder = NULL, - labelClusters = FALSE, - labelClusterRot = 45, - geneBackground = "grey", - geneMode = c("expand", "focus", "compact"), - focus.alpha = 0.5, - labels = FALSE, - label.fontsize = 5, - label.fontcolor = "black", - label.position = c("above", "center"), - label.overlap = TRUE, - show.strand = c("arrows", "labels", "none"), - strand.color = "black", - arrow.spacing = 30, - body.lwd = 0.8, - exon.height = 0.7, - feature.min.px = 3, - exon.min.px = 1, - exon.min.width = NULL, - row.height = NULL, - auto.collapse.bp.per.inch = 50000, - max.rows = 4, - reader = c("auto", "readGFF", "import", "tabix"), - cache = NULL, - params = NULL, - ... -) -} -\arguments{ -\item{data}{A GTF/GFF path, `GRanges` object, data frame, or a -`TxDb`/`EnsDb` annotation object. Data frames need `chrom`, `start`, -`end`, and optionally `strand`, `gene`, `transcript`, and `feature` -columns.} - -\item{neo}{A `neoAssembly` object.} - -\item{x, y, width, height}{Placement parameters.} - -\item{txdb}{Optional `TxDb` or `EnsDb` annotation. If `data` is a -`TxDb`/`EnsDb`, it is used automatically.} - -\item{orgdb}{Optional `OrgDb` used to map gene IDs to symbols.} - -\item{assembly}{Assembly name or object used to resolve default -`TxDb`/`OrgDb` packages. Defaults to `neo$assembly`.} - -\item{gene.id.column, display.column}{Column names used when reading a -`TxDb` annotation.} - -\item{just}{Justification. Default value is \code{c("left", "top")}.} - -\item{default.units}{Default units. Default value is \code{"inches"}.} - -\item{displayMode}{Gene display mode. \code{"auto"} chooses -\code{"collapsed"} or \code{"expanded"} from basepairs per inch. -\code{"squished"} uses expanded detail with shorter rows. -Default value is \code{displayMode = "auto"}.} - -\item{chromstart, chromend}{Neo-coordinate window to display. Defaults to -the full neo-chromosome.} - -\item{color}{Gene color. Can be a single color or a named vector by gene. -Default value is \code{"black"}.} - -\item{highlight.color}{Color for highlighted genes. -Default value is \code{"red"}.} - -\item{geneHighlights}{Optional character vector of gene names, a named -color vector, or a data frame with `gene` and `color` columns. Genes named -without colors use \code{highlight.color}.} - -\item{gene.type}{Gene biotypes to retain when a \code{gene_type} column is -available, e.g. \code{"protein_coding"}. Use \code{NULL} to keep all -biotypes. Default value is \code{"protein_coding"}.} - -\item{geneOrder}{Optional character vector giving label priority order.} - -\item{labelClusters}{Logical value indicating whether labels should be -rotated to reduce overlap. Default value is `FALSE`.} - -\item{labelClusterRot}{Rotation in degrees for clustered labels. -Default value is 45.} - -\item{geneBackground}{Color for non-highlighted genes when -`geneHighlights` is supplied. Default value is `"grey"`.} - -\item{geneMode}{Gene layout mode. `"expand"` draws all genes at full -opacity in packed rows. `"focus"` draws priority genes (`geneHighlights`, -`geneOrder`, or named `labels`) at full opacity and all other genes at -`focus.alpha`. `"compact"` draws all genes on a single line. -Default value is `"expand"`.} - -\item{focus.alpha}{Alpha applied to non-priority genes in focus mode. -Default value is 0.5.} - -\item{labels}{Logical value or character vector of gene names to label. -Default value is \code{FALSE} so the track stays clean.} - -\item{label.fontsize}{Gene label font size. Default value is 5.} - -\item{label.fontcolor}{Gene label color for non-highlighted genes. -Default value is \code{"black"}.} - -\item{label.position}{Label position: \code{"above"} or \code{"center"}. -Default value is \code{"above"}.} - -\item{label.overlap}{Logical value indicating whether labels should be -stacked into extra levels to avoid collisions. Default value is -\code{TRUE}.} - -\item{show.strand}{Strand display: \code{"arrows"}, \code{"labels"}, or -\code{"none"}. Logical \code{TRUE}/\code{FALSE} are accepted for backward -compatibility. Default value is \code{"arrows"}.} - -\item{strand.color}{Strand-label color. Default value is \code{"black"}.} - -\item{arrow.spacing}{Spacing between strand chevrons in points. -Default value is 30.} - -\item{body.lwd}{Gene-body line width in expanded mode. Default value is -0.8.} - -\item{exon.height}{Exon block height as a fraction of row height. -Default value is 0.7.} - -\item{feature.min.px}{Minimum feature width in pixels at 72 dpi. -Default value is 3.} - -\item{exon.min.px}{Minimum exon width in pixels at 72 dpi. -Default value is 1.} - -\item{exon.min.width}{Deprecated point-based exon width override. When -supplied, it takes precedence over \code{exon.min.px}.} - -\item{row.height}{Optional explicit row height in \code{default.units}.} - -\item{auto.collapse.bp.per.inch}{Basepairs per inch above which -\code{displayMode = "auto"} collapses genes. Default value is 50000.} - -\item{max.rows}{Maximum number of gene rows. Default value is 4.} - -\item{reader}{GTF/GFF reader: `"auto"`, `"readGFF"`, `"import"`, or -`"tabix"`. Default value is `"auto"`.} - -\item{cache}{Optional cache directory for parsed annotations, or `TRUE` -for the plotgardener user cache. Default value is `NULL` (no cache).} - -\item{params}{An optional \link[plotgardener]{pgParams} object.} - -\item{...}{Additional arguments passed to \code{plotText()}.} -} -\value{ -Invisibly returns a list with the gene rows, grobs, display mode, -and displayed window. -} -\description{ -Draws gene models through the neo-chromosome topology, using IGV-style -display modes. At whole-chromosome scale genes collapse to solid blocks; -when zoomed in, gene bodies and exon blocks are shown. Input can be a -GTF/GFF file, a `GRanges` object, or a data frame. Using a GTF/GFF file -allows arbitrary GENCODE releases without requiring a matching TxDb -package. -} diff --git a/man/plotNeoHic.Rd b/man/plotNeoHic.Rd deleted file mode 100644 index 2c0294ebe..000000000 --- a/man/plotNeoHic.Rd +++ /dev/null @@ -1,40 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/readNeoHic.R -\name{plotNeoHic} -\alias{plotNeoHic} -\title{Plot a reconstructed neo-chromosome contact matrix} -\usage{ -plotNeoHic( - neoHic, - type = c("triangle", "square", "rectangle"), - flip = c("none", "horizontal"), - ... -) -} -\arguments{ -\item{neoHic}{A `neoHic` object from \code{readNeoHic()}.} - -\item{type}{Hi-C plot type: \code{"triangle"}, \code{"square"}, or -\code{"rectangle"}. Default value is \code{type = "triangle"}.} - -\item{flip}{Orientation. \code{"none"} or \code{FALSE} leaves the plot -unchanged, \code{"horizontal"} mirrors the x-axis so the opposite -chromosome is on the left, and \code{TRUE} retains the legacy vertical -triangle flip. Default value is \code{flip = "none"}.} - -\item{...}{Additional arguments passed to the corresponding -\code{plotHic*} function.} -} -\value{ -The plot object returned by \code{plotHicTriangle()}, -\code{plotHicSquare()}, or \code{plotHicRectangle()}. -} -\description{ -Plot a reconstructed neo-chromosome contact matrix -} -\examples{ -\dontrun{ -neoHic <- readNeoHic("HM1_merged.mcool", neo, resolution = 5000) -plotNeoHic(neoHic, type = "square", x = 1, y = 1, width = 2, height = 2) -} -} diff --git a/man/readNeoAssembly.Rd b/man/readNeoAssembly.Rd deleted file mode 100644 index 0f7e1d323..000000000 --- a/man/readNeoAssembly.Rd +++ /dev/null @@ -1,66 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/neoAssembly.R -\name{readNeoAssembly} -\alias{readNeoAssembly} -\title{Read an SV neo-chromosome assembly topology} -\usage{ -readNeoAssembly( - file, - id, - assembly = "hg38", - extend = 0, - prefix = "chr", - quiet = FALSE -) -} -\arguments{ -\item{file}{Path to an `.assemblies.txt` file.} - -\item{id}{Assembly ID to extract, for example `"C1"`.} - -\item{assembly}{Genome assembly name. Default value is -\code{assembly = "hg38"}.} - -\item{extend}{Number of basepairs to extend the first and last fragment. -Default value is \code{extend = 0}.} - -\item{prefix}{Prefix to add to chromosome names that do not already have -one. Default value is \code{prefix = "chr"}.} - -\item{quiet}{A logical indicating whether to print messages.} -} -\value{ -A `neoAssembly` object: a list with \code{id}, \code{fragments}, -\code{total_length}, and \code{assembly}. \code{fragments} is a data frame -with columns \code{id}, \code{chrom}, \code{chrom_raw}, \code{start}, -\code{end}, \code{flipped}, \code{offset}, and \code{length}. -} -\description{ -Parse an assembly file from a neoloop/SV workflow and build a -`neoAssembly` object describing the concatenated neo-chromosome. -} -\details{ -Assembly lines are usually produced by NeoLoopFinder's -\code{assemble-complexSVs}. Each line contains an assembly ID, zero or more -SV records (\code{type,chrA,b1,strandA,chrB,b2,strandB}), and two span -coordinates (\code{chr,position}). Consecutive node pairs define fragments; -a fragment is flipped when its entry position is greater than its exit -position. See \code{vignette("neo_reconstruction")} for a full description -and examples. -} -\examples{ -\dontrun{ -neo <- readNeoAssembly( - file = "HM1_merged.assemblies.txt", - id = "C1", - assembly = "hg38", - extend = 200000 -) -neo -} -} -\references{ -Wang X, Xu J, Zhang B, Hou Y, Song F, Lyu H, Yue F. Genome-wide detection of -enhancer-hijacking events from chromatin interaction data in rearranged -genomes. Nature Methods (2021). -} diff --git a/man/readNeoHic.Rd b/man/readNeoHic.Rd deleted file mode 100644 index 1ae3c4625..000000000 --- a/man/readNeoHic.Rd +++ /dev/null @@ -1,85 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/readNeoHic.R -\name{readNeoHic} -\alias{readNeoHic} -\title{Reconstruct an SV-impacted contact matrix in neo-chromosome coordinates} -\usage{ -readNeoHic( - data, - neo, - id = NULL, - resolution = "auto", - norm = "NONE", - matrix = "observed", - zrange = NULL, - assembly = "hg38", - extend = 0, - prefix = "chr", - quiet = FALSE -) -} -\arguments{ -\item{data}{Path to a `.hic`, `.cool`, or `.mcool` file, or a data frame -of precomputed genomic contacts with columns \code{chrom1}, \code{start1}, -\code{chrom2}, \code{start2}, and \code{counts}. A data frame with -\code{chrom}, \code{start1}, \code{start2}, and \code{counts} is also -accepted for intrachromosomal data.} - -\item{neo}{A `neoAssembly` object from \code{readNeoAssembly()}, or a path -to an assembly file. If a path is supplied, \code{id} is required.} - -\item{id}{Assembly ID when \code{neo} is an assembly file path.} - -\item{resolution}{Resolution in basepairs, or \code{"auto"} to choose -a resolution close to 1000 bins across the neo-chromosome. For data frame -input, \code{"auto"} estimates the smallest positive spacing between bins.} - -\item{norm}{Normalization to pass to \code{readHic()} or \code{readCool()}. -Default value is \code{norm = "NONE"}.} - -\item{matrix}{Matrix type for `.hic` files. Default value is -\code{matrix = "observed"}.} - -\item{zrange}{Optional numeric vector of length 2 used to clip the final -reconstructed counts. Default value is \code{zrange = NULL}.} - -\item{assembly}{Genome assembly for `.hic` files and for reading an -assembly file path. Default value is \code{assembly = "hg38"}.} - -\item{extend}{Basepairs to extend the first and last fragments when -\code{neo} is a file path. Default value is \code{extend = 0}.} - -\item{prefix}{Prefix for chromosome names when \code{neo} is a file path. -Default value is \code{prefix = "chr"}.} - -\item{quiet}{A logical indicating whether to print progress messages.} -} -\value{ -A `neoHic` object: a list with \code{matrix} (a data frame of -\code{x}, \code{y}, \code{counts} in neo coordinates), \code{neo}, -\code{resolution}, \code{norm}, and \code{matrix_type}. -} -\description{ -Reconstruct an SV-impacted contact matrix in neo-chromosome coordinates -} -\details{ -For file input, the reconstruction reads each fragment pair from the source -file and maps genomic bin starts onto the concatenated neo-chromosome. -Contacts are assigned only to the fragment pair being read, so pixels from -adjacent fragments are not double-counted. For data frame input, each row's -genomic coordinates are mapped to neo coordinates using the same rules. -} -\examples{ -\dontrun{ -neo <- readNeoAssembly("HM1_merged.assemblies.txt", "C1", extend = 200000) -neoHic <- readNeoHic("HM1_merged.mcool", neo, resolution = 5000) -plotNeoHic(neoHic, type = "triangle") - -## Or pass the assembly path and ID directly -neoHic2 <- readNeoHic( - "HM1_merged.mcool", - "HM1_merged.assemblies.txt", id = "C1", - extend = 200000, resolution = 5000 -) -} -} diff --git a/tests/testthat/test-neo.R b/tests/testthat/test-neo.R deleted file mode 100644 index 95e2a6948..000000000 --- a/tests/testthat/test-neo.R +++ /dev/null @@ -1,1049 +0,0 @@ -test_that("readNeoAssembly parses fragments, offsets, and flips", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", - assembly - ) - - neo <- readNeoAssembly(assembly, "C1", extend = 0, quiet = TRUE) - - expect_s3_class(neo, "neoAssembly") - expect_equal(neo$total_length, 800) - expect_equal(nrow(neo$fragments), 2) - expect_equal(neo$fragments$chrom, c("chr1", "chr2")) - expect_equal(neo$fragments$flipped, c(TRUE, FALSE)) - expect_equal(neo$fragments$offset, c(0, 400)) - expect_equal(neo$fragments$length, c(400, 400)) -}) - -test_that("readNeoAssembly extends only the first and last fragments", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", - assembly - ) - - neo <- readNeoAssembly(assembly, "C1", extend = 100, quiet = TRUE) - - expect_equal(neo$fragments$length, c(500, 500)) - expect_equal(neo$fragments$offset, c(0, 500)) - expect_equal(neo$total_length, 1000) -}) - -test_that("mapNeoFeatures flips coordinates and strand", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - - features <- data.frame( - chrom = c("chr1", "chr2"), - start = c(0, 0), - end = c(100, 100), - name = c("f1", "f2"), - strand = c("+", "+") - ) - mapped <- mapNeoFeatures(features, neo) - - expect_equal(mapped$chrom, c("neo", "neo")) - expect_equal(mapped$fragment, c(1L, 2L)) - expect_equal(mapped$start, c(300, 400)) - expect_equal(mapped$end, c(400, 500)) - expect_equal(mapped$strand, c("-", "+")) -}) - -test_that("readNeoHic reconstructs a mcool matrix in neo coordinates", { - mcool <- withr::local_tempfile(fileext = ".mcool") - fx <- make_test_mcool(mcool) - - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - - neoHic <- readNeoHic( - mcool, neo, resolution = 100, norm = "NONE", quiet = TRUE - ) - - expect_s3_class(neoHic, "neoHic") - expect_equal(neoHic$resolution, 100) - expect_equal(neoHic$neo$total_length, 800) - expect_equal(nrow(neoHic$pair_counts), 3) - expect_true(all(c("fragment1", "fragment2", "pixels", "counts") %in% - colnames(neoHic$pair_counts))) - expect_true(all(neoHic$matrix$x <= neoHic$matrix$y)) - expect_false(any(duplicated(neoHic$matrix[, c("x", "y")]))) - - expected <- fx$pixels[ - (fx$pixels$bin1_id %in% 0:3 & fx$pixels$bin2_id %in% 0:3) | - (fx$pixels$bin1_id %in% 0:3 & fx$pixels$bin2_id %in% 10:13) | - (fx$pixels$bin1_id %in% 10:13 & fx$pixels$bin2_id %in% 10:13), - ] - expect_equal(sum(neoHic$matrix$counts), sum(expected$count)) - - getCount <- function(x, y) { - neoHic$matrix$counts[neoHic$matrix$x == x & neoHic$matrix$y == y] - } - ## chr1 bin 0 (flipped to neo 300) vs chr2 bin 10 (neo 400) - expect_equal( - getCount(300, 400), - fx$pixels$count[fx$pixels$bin1_id == 0 & fx$pixels$bin2_id == 10] - ) - ## chr1 bin 1 (flipped to neo 200) vs chr2 bin 11 (neo 500) - expect_equal( - getCount(200, 500), - fx$pixels$count[fx$pixels$bin1_id == 1 & fx$pixels$bin2_id == 11] - ) -}) - -test_that("plotNeoHic creates a plot object", { - mcool <- withr::local_tempfile(fileext = ".mcool") - fx <- make_test_mcool(mcool) - - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - neoHic <- readNeoHic( - mcool, neo, resolution = 100, norm = "NONE", quiet = TRUE - ) - - pageCreate(width = 4, height = 3, default.units = "inches", - showGuides = FALSE) - plot <- plotNeoHic( - neoHic, type = "triangle", - x = 0.5, y = 0.5, width = 2, height = 1.5, - just = c("left", "top"), draw = FALSE - ) - expect_s3_class(plot, "hicTriangle") -}) - -test_that("readNeoHic accepts an assembly path and ID", { - mcool <- withr::local_tempfile(fileext = ".mcool") - fx <- make_test_mcool(mcool) - - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", - assembly - ) - - neoHic <- readNeoHic( - mcool, assembly, id = "C1", - resolution = 100, norm = "NONE", quiet = TRUE - ) - expect_s3_class(neoHic, "neoHic") - expect_equal(neoHic$neo$id, "C1") - expect_true(nrow(neoHic$matrix) > 0) -}) - -test_that("readNeoHic accepts precomputed genomic pair data", { - mcool <- withr::local_tempfile(fileext = ".mcool") - fx <- make_test_mcool(mcool) - - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - - binChrom <- ifelse(fx$pixels$bin1_id < fx$nBins1, "chr1", "chr2") - binChrom2 <- ifelse(fx$pixels$bin2_id < fx$nBins1, "chr1", "chr2") - pairData <- data.frame( - chrom1 = binChrom, - start1 = fx$starts[fx$pixels$bin1_id + 1], - chrom2 = binChrom2, - start2 = fx$starts[fx$pixels$bin2_id + 1], - counts = fx$pixels$count - ) - pairData <- pairData[ - (pairData$chrom1 == "chr1" & pairData$start1 < 400 & - pairData$chrom2 == "chr1" & pairData$start2 < 400) | - (pairData$chrom1 == "chr1" & pairData$start1 < 400 & - pairData$chrom2 == "chr2" & pairData$start2 < 400) | - (pairData$chrom1 == "chr2" & pairData$start1 < 400 & - pairData$chrom2 == "chr2" & pairData$start2 < 400), - ] - - fromFile <- readNeoHic( - mcool, neo, resolution = 100, norm = "NONE", quiet = TRUE - ) - fromDf <- readNeoHic( - pairData, neo, resolution = 100, quiet = TRUE - ) - - expect_equal(fromDf$matrix, fromFile$matrix) -}) - -test_that("annoNeoFragmentLabels supports coordinate and inversion labels", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - labels <- annoNeoFragmentLabels( - neo, - x = 0.5, y = 0.5, width = 3, - label.style = "coordinate", - label.position = "below", - label.offset = 0.05, - label.fontface = "italic", - show.inversion = TRUE - ) - expect_type(labels, "list") - expect_length(labels, 2) -}) - -test_that("plotNeoHic can flip the x-axis horizontally", { - mcool <- withr::local_tempfile(fileext = ".mcool") - fx <- make_test_mcool(mcool) - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines("C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", assembly) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - neoHic <- readNeoHic(mcool, neo, resolution = 100, - norm = "NONE", quiet = TRUE) - - pageCreate(width = 3, height = 3, default.units = "inches", - showGuides = FALSE) - hic <- plotNeoHic( - neoHic, type = "square", flip = "horizontal", - x = 0.5, y = 0.5, width = 2, height = 2, - draw = FALSE, zrange = c(0, 2) - ) - expect_equal(hic$xaxisRange, c(neo$total_length, 0)) - expect_equal(hic$xaxisDir, "decrease") - - tri <- plotNeoHic( - neoHic, type = "triangle", flip = "horizontal", - x = 0.5, y = 0.5, width = 2, height = 1, - draw = FALSE, zrange = c(0, 2) - ) - expect_equal(tri$xaxisRange, c(neo$total_length, 0)) - expect_equal(tri$xaxisDir, "decrease") -}) - -test_that("plotNeoGenes draws IGV-style gene bodies and exon blocks", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - - genes <- data.frame( - chrom = c("chr1", "chr1", "chr2", "chr2"), - start = c(100, 150, 100, 300), - end = c(120, 200, 180, 350), - strand = c("+", "+", "-", "-"), - gene = c("GENE1", "GENE1", "GENE2", "GENE3"), - feature = "exon", - gene_type = c("protein_coding", "protein_coding", - "protein_coding", "lncRNA") - ) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - res <- plotNeoGenes( - genes, neo, x = 0.5, y = 0.5, width = 3, height = 0.5, - labels = "GENE1", geneHighlights = "GENE1", - gene.type = "protein_coding", show.strand = TRUE, max.rows = 2 - ) - - ## lncRNA GENE3 is filtered out by gene.type - expect_setequal(unique(res$genes$gene), c("GENE1", "GENE2")) - ## Each gene is one row with a list of reduced exon intervals - expect_equal(nrow(res$genes), 2) - expect_equal(length(res$genes$exonStart[[1]]), 2) - ## IGV style: body segments plus exon rectangles - classes <- vapply(res$grobs, function(g) class(g)[1], character(1)) - expect_true("segments" %in% classes) - expect_true("rect" %in% classes) - ## Highlighted gene is red, non-highlighted gene stays black - expect_equal(res$grobs[[1]]$gp$col, "red") - grobCols <- vapply(res$grobs, function(g) { - if (is.null(g$gp$col)) NA_character_ else as.character(g$gp$col)[1] - }, character(1)) - expect_true("red" %in% grobCols) - expect_true("black" %in% grobCols) - - ## Exon blocks are centred on the gene body, not offset above it - body <- res$grobs[[1]] - exon <- res$grobs[[which(classes == "rect")[1]]] - expect_equal(as.numeric(exon$y), - as.numeric(body$y0) + as.numeric(exon$height) / 2) - expect_equal(exon$just, c(0, 1)) -}) - -test_that("plotNeoGenes can hide strand labels", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - genes <- data.frame( - chrom = "chr2", start = 100, end = 200, strand = "+", - gene = "GENE1", feature = "exon" - ) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - noStrand <- plotNeoGenes( - genes, neo, x = 0.5, y = 0.5, width = 3, height = 0.3, - labels = FALSE, show.strand = FALSE - ) - strand <- plotNeoGenes( - genes, neo, x = 0.5, y = 1, width = 3, height = 0.3, - labels = FALSE, show.strand = TRUE - ) - expect_false(any(vapply(noStrand$grobs, - function(g) identical(g$label, "+"), logical(1)))) - expect_true(any(vapply(strand$grobs, - function(g) identical(g$label, "+"), logical(1)))) -}) - -test_that("plotNeoAssembly and annoNeoDomains expose seam styling", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - - pageCreate(width = 4, height = 3, default.units = "inches", - showGuides = FALSE) - asm <- plotNeoAssembly( - neo, x = 0.5, y = 0.5, width = 3, height = 0.2, - labels = FALSE, seam.color = "purple", seam.lwd = 2, - seam.lty = 3 - ) - expect_equal(asm$seams[[1]]$gp$col, "purple") - expect_equal(asm$seams[[1]]$gp$lwd, 2) - expect_equal(asm$seams[[1]]$gp$lty, 3) - - domainPlot <- plotNeoHic( - readNeoHic( - { - mcool <- withr::local_tempfile(fileext = ".mcool") - make_test_mcool(mcool) - mcool - }, - neo, resolution = 100, norm = "NONE", quiet = TRUE - ), - type = "triangle", - x = 0.5, y = 1, width = 3, height = 1, - draw = FALSE, zrange = c(0, 2) - ) - domains <- annoNeoDomains( - domainPlot, neo, seam.color = "green", seam.lwd = 1.5, - seam.lty = 2 - ) - expect_equal(length(domains$seams), 1) - seamKids <- domains$seams[[1]]$grobs$children - expect_true(length(seamKids) > 0) - expect_equal(seamKids[[1]]$gp$col, "green") - expect_equal(seamKids[[1]]$gp$lwd, 1.5) - expect_equal(seamKids[[1]]$gp$lty, 2) -}) - -test_that("annoNeoFragmentLabels accepts explicit per-fragment colors", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - labels <- annoNeoFragmentLabels( - neo, x = 0.5, y = 0.5, width = 3, - labels = c("frag1", "frag2"), - label.colors = c("red", "green") - ) - expect_equal(labels[[1]]$gp$col, "red") - expect_equal(labels[[2]]$gp$col, "green") -}) - -test_that("plotNeoGenes reads arbitrary GTF files", { - skip_if_not_installed("rtracklayer") - gtf <- withr::local_tempfile(fileext = ".gtf") - writeLines(c( - 'chr1\tTEST\tgene\t100\t200\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', - 'chr1\tTEST\texon\t100\t120\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', - 'chr1\tTEST\texon\t180\t200\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', - 'chr1\tTEST\tgene\t300\t400\t.\t+\t.\tgene_id "G2"; gene_name "GENE2"; gene_type "lncRNA";', - 'chr1\tTEST\texon\t300\t400\t.\t+\t.\tgene_id "G2"; gene_name "GENE2"; gene_type "lncRNA";' - ), gtf) - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - res <- plotNeoGenes( - gtf, neo, x = 0.5, y = 0.5, width = 3, height = 0.3, - labels = "GENE1", gene.type = "protein_coding" - ) - expect_equal(unique(res$genes$gene), "GENE1") - expect_equal(length(res$genes$exonStart[[1]]), 2) -}) - -test_that("collapsed display mode draws solid gene blocks without exon ticks", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - genes <- data.frame( - chrom = "chr2", start = c(100, 300), end = c(200, 400), - strand = "+", gene = c("GENE1", "GENE2"), feature = "exon" - ) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - res <- plotNeoGenes( - genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.4, - displayMode = "collapsed", labels = FALSE, - show.strand = "none", max.rows = 2 - ) - - expect_equal(res$displayMode, "collapsed") - classes <- vapply(res$grobs, function(g) class(g)[1], character(1)) - expect_true(all(classes == "rect")) - minPx <- convertWidth(unit(3, "points"), unitTo = "inches", - valueOnly = TRUE) - widths <- vapply(res$grobs, function(g) as.numeric(g$width), numeric(1)) - expect_true(all(widths >= minPx - 1e-8)) -}) - -test_that("expanded display mode draws body lines and exon blocks", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - genes <- data.frame( - chrom = "chr2", start = c(100, 150), end = c(120, 220), - strand = "+", gene = "GENE1", feature = "exon" - ) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - res <- plotNeoGenes( - genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.4, - displayMode = "expanded", labels = FALSE, - show.strand = "none", max.rows = 1 - ) - - expect_equal(res$displayMode, "expanded") - classes <- vapply(res$grobs, function(g) class(g)[1], character(1)) - expect_true("segments" %in% classes) - expect_true("rect" %in% classes) - exon <- res$grobs[[which(classes == "rect")[1]]] - expect_equal(exon$just, c(0, 1)) - minPx <- convertWidth(unit(1, "points"), unitTo = "inches", - valueOnly = TRUE) - expect_gte(as.numeric(exon$width), minPx - 1e-8) -}) - -test_that("auto display mode switches on basepairs per inch", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - genes <- data.frame( - chrom = "chr2", start = 100, end = 200, strand = "+", - gene = "GENE1", feature = "exon" - ) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - collapsed <- plotNeoGenes( - genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, - displayMode = "auto", auto.collapse.bp.per.inch = 1, - labels = FALSE, show.strand = "none" - ) - expanded <- plotNeoGenes( - genes, neo, x = 0.5, y = 1, width = 2, height = 0.3, - displayMode = "auto", auto.collapse.bp.per.inch = 1e9, - labels = FALSE, show.strand = "none" - ) - expect_equal(collapsed$displayMode, "collapsed") - expect_equal(expanded$displayMode, "expanded") -}) - -test_that("chromstart and chromend clip and rescale the neo window", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - genes <- data.frame( - chrom = "chr2", start = c(100, 300), end = c(200, 400), - strand = "+", gene = c("GENE1", "GENE2"), feature = "exon" - ) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - res <- plotNeoGenes( - genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, - displayMode = "collapsed", chromstart = 620, chromend = 800, - labels = FALSE, show.strand = "none" - ) - expect_equal(res$genes$gene, "GENE2") - expect_equal(res$chromstart, 620) - expect_equal(res$chromend, 800) - ## chr2 fragment starts at neo 400, so 300 bp is neo 700. The window - ## starts at 620 and spans 180 bp. - expect_equal(as.numeric(res$grobs[[1]]$x), 0.5 + 80 / 180 * 2) -}) - -test_that("plotNeoGenes warns and drops genes when rows overflow", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - genes <- data.frame( - chrom = "chr2", start = c(100, 100, 100), end = c(300, 300, 300), - strand = "+", gene = c("G1", "G2", "G3"), feature = "exon" - ) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - expect_warning( - res <- plotNeoGenes( - genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, - displayMode = "collapsed", labels = FALSE, - show.strand = "none", max.rows = 1 - ), - "Not enough rows" - ) - expect_equal(nrow(res$genes), 1) -}) - -test_that("plotNeoGenes suppresses overlapping labels", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - genes <- data.frame( - chrom = "chr2", start = c(100, 150), end = c(140, 190), - strand = "+", gene = c("GENE1", "GENE2"), feature = "exon" - ) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - res <- plotNeoGenes( - genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, - displayMode = "collapsed", labels = c("GENE1", "GENE2"), - show.strand = "none", label.overlap = TRUE, max.rows = 1 - ) - texts <- Filter(function(g) class(g)[1] == "text", res$grobs) - labels <- vapply(texts, function(g) as.character(g$label), character(1)) - ys <- vapply(texts, function(g) as.numeric(g$y), numeric(1)) - expect_equal(sort(labels), c("GENE1", "GENE2")) - expect_false(isTRUE(all.equal(ys[1], ys[2]))) -}) - -test_that("single-exon genes are solid blocks in expanded mode", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - genes <- data.frame( - chrom = "chr2", start = 100, end = 200, strand = "+", - gene = "GENE1", feature = "exon" - ) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - res <- plotNeoGenes( - genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, - displayMode = "expanded", labels = FALSE, show.strand = "none" - ) - classes <- vapply(res$grobs, function(g) class(g)[1], character(1)) - expect_false("segments" %in% classes) - expect_true("rect" %in% classes) -}) - -test_that("UTR and CDS blocks use half and full heights", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - genes <- data.frame( - chrom = "chr2", - start = c(100, 160, 120, 160), - end = c(140, 220, 140, 200), - strand = "+", - gene = "GENE1", - feature = c("exon", "exon", "CDS", "CDS") - ) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - res <- plotNeoGenes( - genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, - displayMode = "expanded", labels = FALSE, show.strand = "none", - max.rows = 1 - ) - classes <- vapply(res$grobs, function(g) class(g)[1], character(1)) - heights <- vapply(res$grobs[classes == "rect"], - function(g) as.numeric(g$height), numeric(1)) - expect_equal(length(heights), 4) - expect_equal(heights[1] / heights[3], 0.5) - expect_equal(heights[2] / heights[4], 0.5) -}) - -test_that("strand arrows are emitted in collapsed mode", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - genes <- data.frame( - chrom = "chr2", start = 100, end = 300, strand = "+", - gene = "GENE1", feature = "exon" - ) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - res <- plotNeoGenes( - genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, - displayMode = "collapsed", labels = FALSE, - show.strand = "arrows" - ) - classes <- vapply(res$grobs, function(g) class(g)[1], character(1)) - expect_true("polygon" %in% classes) -}) - -test_that("plotNeoGenes reads CDS and UTR features from a GTF", { - skip_if_not_installed("rtracklayer") - gtf <- withr::local_tempfile(fileext = ".gtf") - writeLines(c( - 'chr2\tTEST\tgene\t100\t300\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', - 'chr2\tTEST\texon\t100\t140\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', - 'chr2\tTEST\texon\t200\t300\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', - 'chr2\tTEST\tCDS\t120\t140\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', - 'chr2\tTEST\tCDS\t200\t280\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', - 'chr2\tTEST\tUTR\t100\t120\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', - 'chr2\tTEST\tUTR\t280\t300\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";' - ), gtf) - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - res <- plotNeoGenes( - gtf, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, - displayMode = "expanded", labels = FALSE, show.strand = "none" - ) - expect_equal(nrow(res$genes), 1) - expect_equal(length(res$genes$cdsStart[[1]]), 2) - expect_equal(length(res$genes$exonStart[[1]]), 2) -}) - -test_that("plotNeoGenes accepts GRanges input", { - skip_if_not_installed("GenomicRanges") - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - gr <- GenomicRanges::GRanges( - "chr2", - IRanges::IRanges(100, 200), - strand = "+", - gene = "GENE1", - feature = "exon" - ) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - res <- plotNeoGenes( - gr, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, - displayMode = "expanded", labels = FALSE, show.strand = "none" - ) - expect_equal(nrow(res$genes), 1) - expect_equal(res$genes$gene, "GENE1") -}) - -test_that("squished display mode uses shorter rows than expanded", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - genes <- data.frame( - chrom = "chr2", start = 100, end = 200, strand = "+", - gene = "GENE1", feature = "exon" - ) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - expanded <- plotNeoGenes( - genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.4, - displayMode = "expanded", labels = FALSE, show.strand = "none" - ) - squished <- plotNeoGenes( - genes, neo, x = 0.5, y = 1, width = 2, height = 0.4, - displayMode = "squished", labels = FALSE, show.strand = "none" - ) - expect_equal(squished$displayMode, "squished") - expandedRect <- expanded$grobs[[which(vapply( - expanded$grobs, function(g) class(g)[1] == "rect", logical(1) - ))[1]]] - squishedRect <- squished$grobs[[which(vapply( - squished$grobs, function(g) class(g)[1] == "rect", logical(1) - ))[1]]] - expect_lt(as.numeric(squishedRect$height), as.numeric(expandedRect$height)) -}) - -test_that("geneBackground controls non-highlighted genes", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines( - "C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", - assembly - ) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - genes <- data.frame( - chrom = "chr2", start = c(100, 300), end = c(200, 400), - strand = "+", gene = c("GENE1", "GENE2"), feature = "exon" - ) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - res <- plotNeoGenes( - genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, - displayMode = "collapsed", labels = FALSE, show.strand = "none", - geneHighlights = "GENE1", geneBackground = "grey" - ) - cols <- vapply(res$grobs, function(g) { - if (is.null(g$gp$col)) NA_character_ else as.character(g$gp$col)[1] - }, character(1)) - expect_true("red" %in% cols) - expect_true("grey" %in% cols) -}) - -test_that("geneOrder prioritizes labels", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines("C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", assembly) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - genes <- data.frame( - chrom = "chr2", start = c(100, 150), end = c(140, 190), - strand = "+", gene = c("LONGNAME1", "LONGNAME2"), feature = "exon" - ) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - res <- plotNeoGenes( - genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, - displayMode = "collapsed", labels = c("LONGNAME1", "LONGNAME2"), - geneOrder = c("LONGNAME2", "LONGNAME1"), show.strand = "none", - label.overlap = TRUE, max.rows = 1 - ) - texts <- Filter(function(g) class(g)[1] == "text", res$grobs) - labels <- vapply(texts, function(g) as.character(g$label), character(1)) - ys <- vapply(texts, function(g) as.numeric(g$y), numeric(1)) - ## Priority label stays on the lower level; the other is stacked above. - ## plotText stores bottom-based y, so the priority label sits lower. - expect_lt(ys[match("LONGNAME2", labels)], - ys[match("LONGNAME1", labels)]) -}) - -test_that("labelClusters draws rotated labels without stacking", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines("C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", assembly) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - genes <- data.frame( - chrom = "chr2", start = c(100, 150), end = c(140, 190), - strand = "+", gene = c("LONGNAME1", "LONGNAME2"), feature = "exon" - ) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - res <- plotNeoGenes( - genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, - displayMode = "collapsed", labels = c("LONGNAME1", "LONGNAME2"), - labelClusters = TRUE, labelClusterRot = 45, - show.strand = "none", label.overlap = TRUE, max.rows = 1 - ) - texts <- Filter(function(g) class(g)[1] == "text", res$grobs) - expect_equal(length(texts), 2) - ys <- vapply(texts, function(g) as.numeric(g$y), numeric(1)) - rots <- vapply(texts, function(g) as.numeric(g$grobs$rot), numeric(1)) - expect_equal(length(unique(ys)), 1) - expect_true(all(rots == 45)) -}) - -test_that("plotNeoGenes supports TxDb and OrgDb annotation", { - skip_if_not_installed("TxDb.Hsapiens.UCSC.hg38.knownGene") - skip_if_not_installed("org.Hs.eg.db") - suppressPackageStartupMessages({ - library(TxDb.Hsapiens.UCSC.hg38.knownGene) - library(org.Hs.eg.db) - }) - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines("C1\t12,65820000\t12,65830000", assembly) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - res <- plotNeoGenes( - data = TxDb.Hsapiens.UCSC.hg38.knownGene, - orgdb = org.Hs.eg.db, - neo = neo, x = 0.5, y = 0.5, width = 3, height = 0.5, - displayMode = "expanded", labels = "HMGA2", show.strand = "none" - ) - expect_true(any(res$genes$gene == "HMGA2")) - - res2 <- plotNeoGenes( - txdb = TxDb.Hsapiens.UCSC.hg38.knownGene, - orgdb = org.Hs.eg.db, - neo = neo, x = 0.5, y = 1.1, width = 3, height = 0.5, - displayMode = "collapsed", labels = FALSE, show.strand = "none" - ) - expect_true(any(res2$genes$gene == "HMGA2")) -}) - -test_that("GTF readers agree and cache the parsed annotation", { - skip_if_not_installed("rtracklayer") - gtf <- withr::local_tempfile(fileext = ".gtf") - writeLines(c( - 'chr2\tTEST\tgene\t100\t300\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', - 'chr2\tTEST\texon\t100\t140\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', - 'chr2\tTEST\texon\t200\t300\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";' - ), gtf) - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines("C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", assembly) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - fast <- plotNeoGenes( - gtf, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, - displayMode = "expanded", labels = FALSE, show.strand = "none", - reader = "readGFF" - ) - fallback <- plotNeoGenes( - gtf, neo, x = 0.5, y = 1, width = 2, height = 0.3, - displayMode = "expanded", labels = FALSE, show.strand = "none", - reader = "import" - ) - expect_equal(fast$genes$gene, fallback$genes$gene) - expect_equal(fast$genes$start, fallback$genes$start) - expect_equal(fast$genes$end, fallback$genes$end) - - cache <- withr::local_tempdir() - plotNeoGenes( - gtf, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, - displayMode = "collapsed", labels = FALSE, show.strand = "none", - reader = "readGFF", cache = cache - ) - expect_equal(length(list.files(cache)), 1) -}) - -test_that("tabix reader returns the same annotation", { - skip_if_not_installed("rtracklayer") - skip_if_not_installed("Rsamtools") - gtf <- withr::local_tempfile(fileext = ".gtf") - writeLines(c( - 'chr2\tTEST\tgene\t100\t300\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', - 'chr2\tTEST\texon\t100\t140\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";', - 'chr2\tTEST\texon\t200\t300\t.\t+\t.\tgene_id "G1"; gene_name "GENE1"; gene_type "protein_coding";' - ), gtf) - ## Tabix requires position-sorted input. - lines <- readLines(gtf) - fields <- strsplit(lines, "\t", fixed = TRUE) - ord <- order( - vapply(fields, `[`, character(1), 1), - as.numeric(vapply(fields, `[`, character(1), 4)) - ) - sorted <- withr::local_tempfile(fileext = ".gtf") - writeLines(lines[ord], sorted) - gz <- paste0(sorted, ".gz") - withr::defer(unlink(c(gz, paste0(gz, ".tbi")))) - Rsamtools::bgzip(sorted, dest = gz, overwrite = TRUE) - Rsamtools::indexTabix(gz, format = "gff") - - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines("C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", assembly) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - res <- plotNeoGenes( - gz, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, - displayMode = "expanded", labels = FALSE, show.strand = "none", - reader = "tabix" - ) - expect_equal(res$genes$gene, "GENE1") - expect_equal(length(res$genes$exonStart[[1]]), 2) -}) - -test_that("focus mode fades non-priority genes but keeps their exons", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines("C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", assembly) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - genes <- data.frame( - chrom = "chr2", - start = c(100, 220, 320, 370), - end = c(140, 300, 360, 390), - strand = "+", - gene = c("GENE1", "GENE1", "GENE2", "GENE2"), - feature = "exon" - ) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - res <- plotNeoGenes( - genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, - displayMode = "expanded", geneMode = "focus", focus.alpha = 0.5, - geneHighlights = "GENE1", geneBackground = "grey", - labels = "GENE1", show.strand = "arrows", max.rows = 1 - ) - expect_equal(res$geneMode, "focus") - rects <- Filter(function(g) class(g)[1] == "rect", res$grobs) - cols <- vapply(rects, function(g) as.character(g$gp$col)[1], character(1)) - alphas <- vapply(rects, function(g) as.numeric(g$gp$alpha)[1], numeric(1)) - expect_true(any(cols == "red" & alphas == 1)) - expect_true(any(cols == "grey" & alphas == 0.5)) - segments <- Filter(function(g) class(g)[1] == "segments", res$grobs) - segCols <- vapply(segments, function(g) as.character(g$gp$col)[1], - character(1)) - segAlphas <- vapply(segments, function(g) as.numeric(g$gp$alpha)[1], - numeric(1)) - expect_true(any(segCols == "grey" & segAlphas == 0.5)) - texts <- Filter(function(g) class(g)[1] == "text", res$grobs) - expect_equal(length(texts), 1) - expect_equal(texts[[1]]$label, "GENE1") -}) - -test_that("compact mode draws all genes in a single row", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines("C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", assembly) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - genes <- data.frame( - chrom = "chr2", - start = c(100, 220, 320, 370), - end = c(140, 300, 360, 390), - strand = "+", - gene = c("GENE1", "GENE1", "GENE2", "GENE2"), - feature = "exon" - ) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - res <- plotNeoGenes( - genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, - displayMode = "expanded", geneMode = "compact", - geneHighlights = "GENE1", show.strand = "none", max.rows = 4 - ) - expect_equal(res$geneMode, "compact") - expect_true(all(res$genes$row == 1)) - rects <- Filter(function(g) class(g)[1] == "rect", res$grobs) - cols <- vapply(rects, function(g) as.character(g$gp$col)[1], character(1)) - expect_true("red" %in% cols) - expect_true("grey" %in% cols) -}) - -test_that("focus mode keeps overflowing background genes on the last row", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines("C1\ttranslocation,1,0,+,2,0,+\t1,400\t2,400", assembly) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - genes <- data.frame( - chrom = "chr2", start = c(100, 100, 100), end = c(300, 300, 300), - strand = "+", gene = c("GENE1", "GENE2", "GENE3"), feature = "exon" - ) - - pageCreate(width = 4, height = 2, default.units = "inches", - showGuides = FALSE) - res <- plotNeoGenes( - genes, neo, x = 0.5, y = 0.5, width = 2, height = 0.3, - displayMode = "expanded", geneMode = "focus", - geneHighlights = "GENE1", labels = FALSE, - show.strand = "none", max.rows = 1 - ) - expect_equal(nrow(res$genes), 3) - expect_true(all(res$genes$row == 1)) -}) - -test_that("getNeoSignal maps and bins bigWig-like signal", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines("C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", assembly) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - signal <- data.frame( - chrom = c("chr1", "chr2"), - start = c(100, 100), end = c(200, 200), - score = c(2, 4) - ) - res <- getNeoSignal(signal, neo, binSize = 100) - expect_equal(res$chrom, rep("neo", 2)) - expect_equal(res$start, c(200, 500)) - expect_equal(res$end, c(299, 599)) - expect_equal(res$score, c(2, 4)) - - gr <- GenomicRanges::GRanges( - c("chr1", "chr2"), - IRanges::IRanges(c(100, 100), c(200, 200)), - score = c(2, 4) - ) - grRes <- getNeoSignal(gr, neo, binSize = 100) - expect_equal(grRes$start, c(200, 500)) - - window <- getNeoSignal(signal, neo, binSize = 100, - chromstart = 450, chromend = 650) - expect_equal(window$start, 500) -}) - -test_that("getNeoV4C maps virtual-4C tables", { - assembly <- withr::local_tempfile(fileext = ".assemblies.txt") - writeLines("C1\ttranslocation,1,0,-,2,0,+\t1,400\t2,400", assembly) - neo <- readNeoAssembly(assembly, "C1", quiet = TRUE) - tsv <- withr::local_tempfile(fileext = ".tsv") - writeLines(c( - "chrom\tstart\tend\tbalanced", - "chr2\t100\t200\t1.5", - "chr2\t200\t300\t2.5" - ), tsv) - res <- getNeoV4C(tsv, neo) - expect_equal(res$chrom, rep("neo", 2)) - expect_equal(res$start, c(500, 600)) - expect_equal(res$score, c(1.5, 2.5)) - expect_true(all(res$end < c(600, 700))) -}) diff --git a/vignettes/neo_reconstruction.Rmd b/vignettes/neo_reconstruction.Rmd deleted file mode 100644 index 9206038dc..000000000 --- a/vignettes/neo_reconstruction.Rmd +++ /dev/null @@ -1,304 +0,0 @@ ---- -title: "Reconstructing SV-impacted Hi-C maps with plotgardener" -output: rmarkdown::html_vignette -vignette: > - %\VignetteIndexEntry{Reconstructing SV-impacted Hi-C maps with plotgardener} - %\VignetteEngine{knitr::rmarkdown} - %\VignetteEncoding{UTF-8} ---- - -```{r setup, include=FALSE} -knitr::opts_chunk$set( - collapse = TRUE, - comment = "#>", - eval = FALSE -) -``` - -This vignette describes how to go from structural variant (SV) assemblies to a -reconstructed neo-chromosome Hi-C map. The assembly file format is the one -produced by [NeoLoopFinder](https://github.com/XiaoTaoWang/NeoLoopFinder) -`assemble-complexSVs`. - -## 1. Get SV assemblies from NeoLoopFinder - -NeoLoopFinder expects a six-column SV list: - -```text -chr7 chr14 ++ 14000000 37500000 translocation -chr7 chr14 -- 7901149 37573191 translocation -``` - -The columns are: - -1. `chrA`: chromosome of the first breakpoint. -2. `chrB`: chromosome of the second breakpoint. -3. `orientation`: `++`, `+-`, `-+`, or `--`. -4. `b1`: first breakpoint position on `chrA`. -5. `b2`: second breakpoint position on `chrB`. -6. `type`: `deletion`, `inversion`, `duplication`, or `translocation`. - -Then run `assemble-complexSVs`, for example: - -```bash -assemble-complexSVs \ - -O SKNMC \ - -B SKNMC-EagleC.SV.txt \ - --balance-type CNV \ - --protocol insitu \ - --nproc 6 \ - -H SKNMC-MboI-allReps-filtered.mcool::resolutions/25000 \ - SKNMC-MboI-allReps-filtered.mcool::resolutions/10000 \ - SKNMC-MboI-allReps-filtered.mcool::resolutions/5000 -``` - -This produces `SKNMC.assemblies.txt`. A typical file looks like this: - -```text -A0 inversion,8,132915000,+,8,130825000,+ deletion,8,130800000,-,8,129520000,+ 8,132155000 8,129375000 -A1 inversion,11,84315000,-,11,83565000,- inversion,11,84315000,+,11,83565000,+ 11,85050000 11,82625000 -C0 translocation,1,10260000,+,X,21495000,- 1,9380000 X,22205000 -C1 translocation,1,10260000,-,X,21495000,+ 1,10630000 X,20080000 -``` - -## 2. Understand the assembly file format - -Each non-empty line is one assembly: - -```text - -``` - -The fields are tab-separated: - -- `assembly_id`: a unique ID such as `C1`, `A0`, or `C16`. -- `SV records`: zero or more SV records, each formatted as - `type,chrA,b1,strandA,chrB,b2,strandB`. -- `span1`: the first assembled span, formatted as `chr,position`. -- `span2`: the last assembled span, formatted as `chr,position`. - -The SV records and spans define the ordered nodes of the neo-chromosome: - -```text -span1 position - -> SV1 chrA position - -> SV1 chrB position - -> SV2 chrA position - -> SV2 chrB position - -> ... - -> span2 position -``` - -Consecutive node pairs become fragments. A fragment is marked as flipped when -its entry position is greater than its exit position. For example: - -```text -C1 translocation,12,65690000,-,14,68280000,+ 12,66455000 14,67645000 -``` - -This gives: - -| fragment | chromosome | interval | orientation | -|---|---|---|---| -| 1 | chr12 | 65690000-66455000 | flipped | -| 2 | chr14 | 67645000-68280000 | flipped | - -`readNeoAssembly()` reproduces this topology, applies optional end extension, -and assigns cumulative `offset` and `length` values in the concatenated -neo-chromosome. - -```{r read-assembly, eval=FALSE} -library(plotgardener) - -neo <- readNeoAssembly( - file = "HM1_merged.assemblies.txt", - id = "C1", - assembly = "hg38", - extend = 200000 -) -neo -neo$fragments -``` - -### Custom assembly files - -You can also create an assembly file yourself. It must contain at least one -tab-separated line with an ID, the SV record(s), and the two spans: - -```text -C1 translocation,1,0,-,2,0,+ 1,400 2,400 -``` - -Here `chr1:0-400` is reverse-complemented and `chr2:0-400` is forward, giving a -400 bp + 400 bp neo-chromosome. - -### Chromosome names and coordinates - -- `readNeoAssembly()` adds a `chr` prefix when it is missing. Set - `prefix = ""` if your data uses unprefixed names. -- Positions are used as supplied. `.hic` readers are 1-based and `.cool` - readers use 0-based bin starts; plotgardener handles the source-specific - bin starts when mapping. -- `extend` adds bases only to the first and last fragments, matching the - common NeoLoopFinder visualization convention. - -## 3. Reconstruct the neo-chromosome matrix - -`readNeoHic()` reads each fragment pair from a `.hic`, `.cool`, or `.mcool` -file and maps the contacts into neo-chromosome coordinates. - -Use the exact normalization column stored in the file. For NeoLoopFinder -workflows, this is often `sweight` (from `correct-cnv`) or `weight` (ICE): - -```{r read-neohic, eval=FALSE} -neo <- readNeoAssembly( - file = "HM1_merged.assemblies.txt", - id = "C1", - extend = 200000 -) - -neoHic <- readNeoHic( - data = "HM1_merged-Arima-R1-filtered.mcool", - neo = neo, - resolution = 5000, - norm = "sweight" -) - -neoHic -head(neoHic$matrix) -``` - -You can also pass the assembly file and ID directly: - -```{r read-neohic-path, eval=FALSE} -neoHic <- readNeoHic( - data = "HM1_merged-Arima-R1-filtered.mcool", - neo = "HM1_merged.assemblies.txt", id = "C1", - extend = 200000, resolution = 5000, norm = "sweight" -) -``` - -`readNeoHic()` also accepts a precomputed genomic pair data frame with -columns `chrom1`, `start1`, `chrom2`, `start2`, and `counts`: - -```{r read-neohic-df, eval=FALSE} -neoHic <- readNeoHic( - data = pairData, neo = neo, - resolution = 5000 -) -``` - -Check the available columns with: - -```{r norms, eval=FALSE} -readCoolNorms( - "HM1_merged-Arima-R1-filtered.mcool", - resolution = 5000 -) -``` - -The reconstruction keeps bins in the coordinate space but drops contacts whose -normalization weight is missing or non-finite, matching the usual NeoLoopFinder -visualization behavior. - -## 4. Plot the reconstruction - -```{r plot-neo, eval=FALSE} -pageCreate(width = 5.5, height = 6, default.units = "inches", - showGuides = FALSE) - -hicPlot <- plotNeoHic( - neoHic, - type = "triangle", - x = 1, y = 0.9, width = 3.4, height = 1.9, - just = c("left", "top"), - zrange = c(0, 0.005), - palette = colorRampPalette(c("white", "#FFDFDF", "#FF7575", - "#FF2626", "#F70000")) -) - -## Solid outer neo-chromosome domain + dotted internal seams -annoNeoDomains(hicPlot, neo) - -## Fragment backbone with directional arrows -plotNeoAssembly( - neo, - x = 1, y = 3.05, width = 3.4, height = 0.16, - just = c("left", "top"), - fill = "#D4EEF9", - labels = TRUE, - show.seams = TRUE -) -``` - -For more control over fragment labels, turn labels off in the backbone and use -`annoNeoFragmentLabels()`: - -```{r neo-labels, eval=FALSE} -plotNeoAssembly( - neo, - x = 1, y = 3.05, width = 3.4, height = 0.16, - just = c("left", "top"), - labels = FALSE -) -annoNeoFragmentLabels( - neo, - x = 1, y = 3.3, width = 3.4, - label.style = "coordinate", - label.position = "below", - label.offset = 0.05, - label.fontsize = 7, - label.fontface = "italic", - label.fontcolor = "black", - show.inversion = TRUE, - inversion.color = "red" -) -``` - -`annoNeoFragmentLabels()` supports chromosome, coordinate, or fragment-number -labels, custom fonts/colors/rotation, vertical offsets, and inversion marking. - -`annoNeoDomains()` is the functional equivalent of the dotted seam/domain -annotations in the NeoLoopFinder triangle examples: - -- outer domain outline: solid, controlled by `lty` -- internal fragment seams: dotted, controlled by `seam.lty` - -## 5. Map genes and other features - -`mapNeoFeatures()` maps BED-like data or a `GRanges` object into the -neo-chromosome coordinate system: - -```{r map-features, eval=FALSE} -genes <- data.frame( - chrom = "chr12", - start = 65822483, - end = 65968291, - name = "HMGA2", - strand = "+" -) - -mapNeoFeatures(genes, neo) -``` - -For features that span a fragment boundary, the feature is split across -fragments. Strand is inverted for reverse-complemented fragments. - -## 6. Practical notes - -- Use a resolution that gives a reasonable number of bins across the - neo-chromosome. `resolution = "auto"` targets roughly 1,000 bins. -- For NeoLoopFinder, run `correct-cnv` first if you want `sweight` - normalization. -- If your `.cool`/`.mcool` chromosome names lack `chr`, either add the prefix - as recommended by NeoLoopFinder or let `readNeoAssembly()` add it to the - assembly side and use `readCoolNorms()` to verify the file side. -- `readNeoHic()` uses the existing `readHic()`/`readCool()` readers, so the - raw contact extraction is the same as for ordinary plotgardener Hi-C plots. - -## References - -- Wang X, Xu J, Zhang B, Hou Y, Song F, Lyu H, Yue F. Genome-wide detection of - enhancer-hijacking events from chromatin interaction data in rearranged - genomes. *Nature Methods* (2021). -- NeoLoopFinder: