diff --git a/.Rbuildignore b/.Rbuildignore index 272c50b1..7b8df319 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 e43efbdf..61da1983 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 68017d51..e520132f 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,6 +65,7 @@ Suggests: BSgenome, BSgenome.Hsapiens.UCSC.hg19, ComplexHeatmap, + ensembldb, GenomicFeatures, ggplot2, InteractionSet, diff --git a/NAMESPACE b/NAMESPACE index 0fb72532..80217962 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -18,6 +18,7 @@ export(defaultPackages) export(genomes) export(mapColors) export(pageCreate) +export(pageExport) export(pageGuideHide) export(pageGuideHorizontal) export(pageGuideShow) @@ -26,6 +27,7 @@ export(pageLayoutCol) export(pageLayoutRow) export(pagePlotPlace) export(pagePlotRemove) +export(pageRedraw) export(pgParams) export(plotCircle) export(plotGG) @@ -76,6 +78,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,6 +93,7 @@ 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) diff --git a/NEWS.md b/NEWS.md index 34ab53bb..1be6f65f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,61 @@ +# 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`). +* 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. +* `plotTranscripts()` adds `labelPriority` and centers labels on the + in-bounds transcript portion. +* `plotGenes()` adds `labelClusters`/`labelClusterRot` for dense gene + clusters. +* `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 3c6cf5b8..794b03c6 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 b3acdf72..058c003e 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 d15a70f0..6de1a242 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 79388b27..195d3566 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 225e93b8..b12facb7 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 00000000..9aa1f72f --- /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 7e05a70b..a727f246 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/pageCreate.R b/R/pageCreate.R index 5a1cc5e7..50c749c3 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 00000000..aa36a01d --- /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 b1cb0685..3e84c87e 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 183c9a18..b0620d71 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 00000000..6e773128 --- /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 53059a9d..cbd0749b 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 1f49b0fb..732e68f8 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 e2c78785..2b86aeda 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 0da76416..4c5cd0af 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 a01de2c4..ac53a46c 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 80321e4f..eaaee9b1 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/plotSignal.R b/R/plotSignal.R index 1e9cadd7..e2531689 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 2337dbcf..c3c43d55 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 948c3aef..1e6af027 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 f73350fe..c572d7b9 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/readingFunctions.R b/R/readingFunctions.R index 3dcf006a..afd5e053 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/annoXaxis.Rd b/man/annoXaxis.Rd index 129ddfc2..e083edb0 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 d6d84b4d..29f68512 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 bbefd46d..b543862b 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 227c146a..c28a836f 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 00000000..76e798d7 --- /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 ac9d4fa4..cab38edf 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 00000000..0b3efb5b --- /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 e4a0efb0..3b100170 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 530812d3..13436032 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/pageExport.Rd b/man/pageExport.Rd new file mode 100644 index 00000000..a5aaa9d9 --- /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 dec93729..084205af 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 4cb2af77..8d68382d 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 00000000..25c5cdb1 --- /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 40ceb4bb..b83c0394 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 94402a1c..6d7360c7 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 498c5f17..2b80e87a 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 b2183aa0..38ec6a5a 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 2a697b15..4f1a3af7 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 d636f6d0..8b93ac62 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/plotSignal.Rd b/man/plotSignal.Rd index abd7f7ff..7d05bb86 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 d56f297f..d25deafe 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 76973c51..3f633d44 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 336f44ba..bd33638b 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/tests/testthat/helper-mcool.R b/tests/testthat/helper-mcool.R new file mode 100644 index 00000000..1116318f --- /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 00000000..3de26f6a --- /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 00000000..53c6ad6f --- /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 00000000..4421b716 --- /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 00000000..a044391b --- /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-pageExport.R b/tests/testthat/test-pageExport.R new file mode 100644 index 00000000..55917a64 --- /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 00000000..56113074 --- /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 00000000..df16271c --- /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 dc53c42c..6621781c 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 00000000..49e18ce4 --- /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)) +})