tests/spectra-plot.R

library(shiny)

app_file <- function(name) {
  path <- system.file("app", name, package = "iSTATS")
  stopifnot(nzchar(path))
  path
}

helpers <- new.env()
sys.source(app_file("functions.R"), envir = helpers)
with(helpers, {
  # Envelope: extremes per pixel are exact, edges are included and the output
  # keeps the axis order (ppm decreasing) with one x per min/max pair.
  axis <- seq(10, -1, length.out = 43845L)
  set.seed(1)
  data <- matrix(rnorm(3L * length(axis)), 3L)
  data[2L, 20000L] <- 50
  data[3L, 30000L] <- -40
  envelope <- .alignment_pixel_envelope(data, axis, c(-1, 10), 1000)
  stopifnot(isTRUE(envelope$envelope),
            ncol(envelope$y) <= 2L * 1000L,
            length(envelope$x) == ncol(envelope$y),
            identical(range(envelope$columns), c(1L, length(axis))),
            all(diff(envelope$x) <= 0),
            max(envelope$y[2L, ]) == 50, min(envelope$y[3L, ]) == -40,
            all.equal(apply(envelope$y, 1L, max), apply(data, 1L, max)),
            all.equal(apply(envelope$y, 1L, min), apply(data, 1L, min)))

  # A zoomed range keeps one neighbour on each side and, with fewer points
  # than pixels, returns the raw columns. Limits may be given in any order.
  zoom <- .alignment_pixel_envelope(data, axis, c(5.0005, 4.9995), 800)
  inside <- which(axis >= 4.9995 & axis <= 5.0005)
  stopifnot(!isTRUE(zoom$envelope),
            identical(zoom$columns, seq(min(inside) - 1L, max(inside) + 1L)),
            identical(zoom$y, data[, zoom$columns, drop = FALSE]),
            identical(zoom$x, axis[zoom$columns]))

  # Increasing axes and ranges outside the data are handled as well.
  rising <- .alignment_pixel_envelope(data[, rev(seq_along(axis))], rev(axis),
                                      NULL, 500)
  stopifnot(all(diff(rising$x) >= 0), max(rising$y[2L, ]) == 50)
  outside <- .alignment_pixel_envelope(data, axis, c(20, 30), 500)
  stopifnot(length(outside$columns) >= 1L, 1L %in% outside$columns)

  # Projection limits ignore isolated lower artefacts, retain the real upper
  # peak and place the robust row baseline 10% above the lower panel edge.
  projection <- matrix(100 + rnorm(3L * length(axis)), 3L)
  projection[2L, 20000L] <- 250
  projection[3L, 30000L] <- -1000
  ylim <- .spectra_ylim(list(projection, NULL), axis, c(-1, 10))
  sampled_columns <- unique(as.integer(round(seq.int(
    1L, ncol(projection), length.out = 4096L))))
  robust_min <- unname(stats::quantile(
    as.numeric(projection[, sampled_columns]), 0.001,
    names = FALSE, type = 8))
  stopifnot(ylim[1L] > -1000, ylim[2L] > 250,
            isTRUE(all.equal((robust_min - ylim[1L]) / diff(ylim), 0.10,
                             tolerance = 1e-12)),
            isTRUE(all.equal((ylim[2L] - 250) / diff(ylim), 0.03,
                             tolerance = 1e-12)))
  vector_ylim <- .spectra_projection_ylim(projection[1L, ])
  vector_baseline <- unname(stats::quantile(
    projection[1L, sampled_columns], 0.001, names = FALSE, type = 8))
  stopifnot(isTRUE(all.equal((vector_baseline - vector_ylim[1L]) /
                             diff(vector_ylim), 0.10, tolerance = 1e-12)))

  # Nearest spectrum: the vertical distance chooses the curve, a tolerance
  # rejects empty space and the reported value comes from the full matrix.
  small_axis <- seq(1, 0, length.out = 11L)
  curves <- rbind(rep(0, 11L), rep(5, 11L), c(rep(1, 5L), 20, rep(1, 5L)))
  hit <- .nearest_spectrum(curves, small_axis, 0.52, 4.6, 0.001, 1)
  stopifnot(hit$index == 2L, hit$intensity == 5)
  peak <- .nearest_spectrum(curves, small_axis, 0.52, 18, 0.05, 1)
  stopifnot(peak$index == 3L, peak$column == 6L, peak$ppm == 0.5,
            peak$intensity == 20)
  stopifnot(is.null(.nearest_spectrum(curves, small_axis, 0.5, 12, 0, 1)),
            is.null(.nearest_spectrum(curves, small_axis, NA, 1)))

  event <- list(domain = list(left = 10, right = -1, bottom = -2, top = 2),
                range = list(left = 0, right = 1100, bottom = 400, top = 0),
                img_css_ratio = list(x = 2, y = 2))
  tolerance <- .plot_event_tolerance(event, pixels = 5)
  stopifnot(isTRUE(all.equal(unname(tolerance), c(0.1, 0.1))))
  stopifnot(.spectrum_label(2L, c("a", "b")) == "b",
            .spectrum_label(3L, c("a", "b")) == "Spectrum 3")

  # Region drags: limit, inside, new region, clamping, rounding and errors.
  regions <- rbind(c(8.5, 8.4), c(1.0, 1.5))
  limits <- c(-1, 10)
  resized <- .drag_icoshift_interval(regions, 8.4003, 8.3, 0.001, limits)
  stopifnot(resized$action == "Resized", resized$region == 1L,
            identical(resized$intervals[1L, ], c(8.5, 8.3)))
  moved <- .drag_icoshift_interval(regions, 1.2, 1.26789, 0.001, limits)
  stopifnot(moved$action == "Moved",
            isTRUE(all.equal(moved$intervals[2L, ], c(1.0679, 1.5679))))
  edge <- .drag_icoshift_interval(regions, 1.3, 20, 0.001, limits)
  stopifnot(identical(edge$intervals[2L, ], c(9.5, 10)))
  added <- .drag_icoshift_interval(regions, 3.2, 3.1, 0.001, limits)
  stopifnot(added$action == "Added", added$region == 3L,
            identical(added$intervals[3L, ], c(3.1, 3.2)))
  first <- .drag_icoshift_interval(NULL, 3.2, -5, 0.001, limits)
  stopifnot(identical(first$intervals, matrix(c(-1, 3.2), 1L)))
  stopifnot(inherits(try(.drag_icoshift_interval(regions, 3.2, 3.2005, 0.001, limits),
                         silent = TRUE), "try-error"),
            inherits(try(.drag_icoshift_interval(regions, 8.4, 8.5, 0.001, limits),
                         silent = TRUE), "try-error"))
  removed <- .remove_icoshift_interval(regions, 1.2)
  stopifnot(removed$region == 2L, identical(removed$intervals, regions[1L, , drop = FALSE]),
            is.null(.remove_icoshift_interval(regions, 5)),
            inherits(try(.remove_icoshift_interval(regions[1L, , drop = FALSE], 8.45),
                         silent = TRUE), "try-error"))

  # STOCSY layers: per pixel, each class keeps the extremes of the segments
  # that start at its points (point i to i + 1, as the legacy ggplot coloured
  # them); pixels without the class are NA and the last point starts nothing.
  trace <- data[1L, ]
  classes <- rep("B", length(axis))
  classes[c(1L, 2L, 20000L, 20001L, length(axis))] <- "A"
  classes[30000L] <- "C"
  trace[20001L] <- 70
  stocsy <- .stocsy_pixel_layers(trace, axis, classes, c(-1, 10), 1000)
  size <- ceiling(length(axis) / 1000)
  bin_of <- function(i) as.integer((i - 1L) %/% size + 1L)
  layer_bins <- function(layer) which(!is.na(layer$y[c(TRUE, FALSE)]))
  segment_low <- function(i) pmin(trace[i], trace[i + 1L])
  segment_high <- function(i) pmax(trace[i], trace[i + 1L])
  a <- stocsy$layers$A
  stopifnot(isTRUE(stocsy$envelope),
            identical(stocsy$base$y, .alignment_pixel_envelope(
              matrix(trace, 1L), axis, c(-1, 10), 1000)$y),
            identical(a$x, stocsy$base$x),
            identical(layer_bins(a), sort(unique(bin_of(c(1L, 2L, 20000L, 20001L))))),
            identical(layer_bins(stocsy$layers$C), bin_of(30000L)),
            max(a$y, na.rm = TRUE) == 70,
            min(a$y, na.rm = TRUE) == min(segment_low(c(1L, 2L, 20000L, 20001L))),
            all(a$y[c(FALSE, TRUE)] >= a$y[c(TRUE, FALSE)], na.rm = TRUE))
  b <- bin_of(30000L)
  stopifnot(stocsy$layers$C$y[2L * b - 1L] == segment_low(30000L),
            stocsy$layers$C$y[2L * b] == segment_high(30000L))

  # Zoomed in, the class segments are the real ones; a short legacy class
  # vector leaves the remaining points uncoloured.
  zoomed <- .stocsy_pixel_layers(trace, axis, classes[1:20000],
                                 c(axis[20003L], axis[19990L]), 800)
  stopifnot(!isTRUE(zoomed$envelope),
            identical(zoomed$layers$A$x0, axis[20000L]),
            identical(zoomed$layers$A$y1, trace[20001L]),
            !length(zoomed$layers$C$x0))
  none <- .stocsy_pixel_layers(trace, axis, NULL, NULL, 1000)
  stopifnot(all(is.na(none$layers$A$y)), all(is.na(none$layers$C$y)))

  # Drawing succeeds for data, highlight, marker and the empty state.
  png_file <- tempfile(fileext = ".png")
  grDevices::png(png_file, width = 800, height = 400)
  .spectra_draw_panel(envelope, c(-1, 10), ylim,
                      editable = matrix(c(1, 2), 1L),
                      applied = matrix(c(3, 4), 1L), highlight = 2L,
                      marker = list(x = 5, y = 1))
  .spectra_draw_panel(NULL, NULL, NULL)
  .stocsy_draw(trace, classes, c(-1, 10), ylim, 800, axis = axis)
  .stocsy_draw(trace, classes, c(axis[20003L], axis[19990L]), ylim, 800,
               axis = axis)
  grDevices::dev.off()
  for (type in c("png", "pdf", "jpeg", "tiff")) {
    saved <- tempfile(fileext = paste0(".", type))
    .stocsy_save(saved, type, 100, function(width_px)
      .stocsy_draw(trace, classes, NULL, ylim, width_px, axis = axis))
    stopifnot(file.size(saved) > 0)
    unlink(saved)
  }
  stopifnot(file.size(png_file) > 0)
  unlink(png_file)
})

cat("PASS server-rendered spectra: pixel envelope, STOCSY layers, shared limits, nearest spectrum, drawing and saving\n")

# Plot Spectra module: server-side zoom, moves, scaling, identification,
# marker, show-all and PNG download on the currently selected spectrum.
server_plot_spectra <- function(input, output, session) {
  source(app_file("functions.R"), local = TRUE)
  axis <- seq(10, 0, length.out = 2001L)
  NMRData_plot <- rbind(exp(-((axis - 3) / 0.05)^2) * 100,
                        exp(-((axis - 7) / 0.05)^2) * 50)
  CS_values_real <- rbind(axis, axis)
  file_names <- c("sample A", "sample B")
  alignment_data_version <- reactiveVal(0L)
  source(app_file("plot_interativo_server.R"), local = TRUE)
}

testServer(server_plot_spectra, {
  # Before any selection (e.g. right after an import) the first row is used.
  session$flushReact()
  alignment_data_version(1L)
  session$flushReact()
  stopifnot(identical(.plot_multi_index(), 1L),
            isTRUE(all.equal(ranges_multi$y, c(-3, 103))))
  session$setInputs(spectrum_list_multi = "sample B")
  stopifnot(identical(.plot_multi_index(), 2L),
            isTRUE(all.equal(ranges_multi$y, c(-1.5, 51.5))))
  png_file <- tempfile(fileext = ".png")
  grDevices::png(png_file, width = 800, height = 400)
  .plot_multi_draw(800)
  grDevices::dev.off()
  stopifnot(file.size(png_file) > 0)

  session$setInputs(plot_multi_brush = list(xmin = 6, xmax = 8, ymin = 0, ymax = 60))
  stopifnot(identical(ranges_multi$x, c(6, 8)), identical(ranges_multi$y, c(0, 60)),
            isTRUE(all.equal(peran_multi, 0.4)))
  session$setInputs(s_left_multi = 1)
  stopifnot(isTRUE(all.equal(ranges_multi$x, c(5.6, 7.6))))
  session$setInputs(s_right_f_multi = 1)
  stopifnot(isTRUE(all.equal(ranges_multi$x, c(8, 10))))
  session$setInputs(s_left_f_multi = 1)
  stopifnot(isTRUE(all.equal(ranges_multi$x, c(0, 2))))

  session$setInputs(x2_multi = 1)
  stopifnot(plot_multi_scale() == 2)
  event <- list(x = 7.001, y = 100.2, coords_css = list(x = 10, y = 10),
                domain = list(left = 10, right = 0, bottom = 0, top = 110),
                range = list(left = 0, right = 1000, bottom = 500, top = 0),
                img_css_ratio = list(x = 1, y = 1))
  hit <- .plot_multi_hit(event)
  stopifnot(isTRUE(all.equal(hit$ppm, 7)), isTRUE(all.equal(hit$intensity, 100)))
  session$setInputs(plot_multi_hover = event, plot_multi_click = event)
  stopifnot(grepl("sample B", output$plot_multi_hover_label$html, fixed = TRUE),
            isTRUE(all.equal(plot_multi_marker()$ppm, 7)),
            grepl("Pinned: sample B, 7.0000 ppm", output$plot_multi_marker_text,
                  fixed = TRUE))
  download <- output$download_plot_multi
  stopifnot(file.exists(download), file.size(download) > 0)

  # Clicking the pinned point again, or empty space, removes the pin.
  # (Browser clicks are events; `nonce` keeps repeated test clicks distinct.)
  session$setInputs(plot_multi_click = c(event, nonce = 1))
  stopifnot(is.null(plot_multi_marker()))
  session$setInputs(plot_multi_click = c(event, nonce = 2))
  stopifnot(!is.null(plot_multi_marker()))
  empty <- event
  empty$y <- 150
  session$setInputs(plot_multi_click = empty)
  stopifnot(is.null(plot_multi_marker()))
  session$setInputs(plot_multi_click = c(event, nonce = 3))
  session$setInputs(plot_dblclick_multi = list(x = 5, y = 5))
  stopifnot(identical(ranges_multi$x, c(0, 10)), plot_multi_scale() == 1,
            is.null(plot_multi_marker()), idb_multi == 0)
  session$setInputs(q8_multi = 1, all_multi = 1, x8_multi = 1)
  stopifnot(plot_multi_scale() == 8)
  alignment_data_version(2L)
  session$flushReact()
  stopifnot(plot_multi_scale() == 1)
})

cat("PASS Plot Spectra: server-rendered zoom, moves, scaling, hover, pinned point and download\n")

Try the iSTATS package in your browser

Any scripts or data that you put into this service are public.

iSTATS documentation built on Nov. 6, 2026, 1:07 a.m.