tests/shiny-alignment.R

library(shiny)
library(iSTATS)

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

server_icoshift <- function(input, output, session) {
  source(app_file("functions.R"), local = TRUE)

  axis <- seq(0.1, -0.1, length.out = 64)
  peak <- exp(-((seq_len(64) - 32) / 4)^2)
  NMRData <- rbind(peak * 0.9, peak, peak * 1.1)
  NMRData_plot <- NMRData
  CS_values_real <- rbind(axis, axis)
  file_names <- c("duplicate", "reference", "duplicate")
  refresh_count <- 0L
  reference_update <- NULL
  refreshval <- function() refresh_count <<- refresh_count + 1L
  detected_text <- "-0.02, 0.02"
  updateTextAreaInput <- function(session, inputId, value) {
    stopifnot(identical(inputId, "icoshift_intervals"))
    detected_text <<- value
  }
  updateSelectInput <- function(session, inputId, choices, selected) {
    stopifnot(identical(inputId, "icoshift_reference"))
    reference_update <<- list(choices = choices, selected = selected)
  }

  icoshift_status <- reactiveVal("No alignment has been applied.")
  icoshift_detection <- reactiveVal(NULL)
  icoshift_editable_intervals <- reactiveVal(matrix(c(-0.02, 0.02), nrow = 1L))
  icoshift_interval_references <- reactiveVal(NULL)
  icoshift_applied_intervals <- reactiveVal(NULL)
  alignment_original <- reactiveVal(NMRData)
  alignment_aligned <- reactiveVal(NULL)
  alignment_original_cache <- reactiveVal(NULL)
  alignment_cache_dir <- reactiveVal(NULL)
  alignment_view_range <- reactiveVal(range(axis))
  alignment_view_y <- reactiveVal(NULL)
  alignment_highlight <- reactiveVal(NULL)
  alignment_data_version <- reactiveVal(0L)
  alignment_memory_point_limit <- 32L
  output$icoshift_status <- renderText(icoshift_status())

  expressions <- parse(app_file("Pretreatment_server.R"))
  assignment_for <- function(name) {
    matches <- Filter(function(expr) {
      is.call(expr) && identical(expr[[1L]], as.name("<-")) &&
        identical(as.character(expr[[2L]]), name)
    }, expressions)
    stopifnot(length(matches) == 1L)
    matches[[1L]]
  }
  for (name in c(".remove_alignment_cache", ".alignment_original_data",
                 ".reset_alignment_source", ".cache_large_alignment_source",
                 ".restore_alignment_source", ".alignment_full_range",
                 ".alignment_xlim", ".alignment_zoom", ".alignment_reset_view",
                 ".alignment_move_view", ".alignment_hit", ".alignment_pick",
                 ".alignment_hover_ui", ".publish_icoshift_intervals",
                 ".remove_icoshift_region_at", ".icoshift_text_is_valid",
                 ".commit_icoshift_alignment"))
    eval(assignment_for(name), envir = environment())
  observer_for <- function(input_id) {
    matches <- Filter(function(expr) {
    is.call(expr) && identical(expr[[1L]], as.name("observeEvent")) &&
      is.call(expr[[2L]]) &&
      identical(as.character(expr[[2L]][[3L]]), input_id)
    }, expressions)
    stopifnot(length(matches) == 1L)
    matches[[1L]]
  }
  eval(assignment_for("alignment_ylim"), envir = environment())
  for (input_id in c("alignment_unaligned_brush", "alignment_aligned_brush",
                     "alignment_unaligned_click", "alignment_aligned_click",
                     "alignment_unaligned_dblclick", "alignment_reset_view",
                     "alignment_zoom_out", "alignment_pan_left",
                     "alignment_pan_right", "alignment_region_drag",
                     "alignment_region_remove",
                     "icoshift_intervals", "icoshift_region_brush",
                     "icoshift_region_remove", "icoshift_detect",
                     "icoshift_auto_align", "icoshift_align"))
    eval(observer_for(input_id), envir = environment())
}

testServer(server_icoshift, {
  eval(quote({
  original_data <- NMRData
  original_axis <- CS_values_real
  original_names <- file_names
  session$setInputs(icoshift_reference = "average")
  # Brushing either panel sets one shared x/y view; buttons move and widen it
  # inside the data range, and reset/double-click restore the full view.
  full_range <- range(original_axis[1, ])
  session$setInputs(alignment_unaligned_brush = list(
    xmin = -0.04, xmax = 0.05, ymin = 0.1, ymax = 0.8))
  stopifnot(isTRUE(all.equal(alignment_view_range(), c(-0.04, 0.05))),
            isTRUE(all.equal(alignment_ylim(), c(0.1, 0.8))))
  session$setInputs(alignment_pan_left = 1)
  stopifnot(isTRUE(all.equal(alignment_view_range(), c(0.005, 0.095))))
  session$setInputs(alignment_pan_left = 2)
  stopifnot(isTRUE(all.equal(alignment_view_range(), c(0.01, 0.1))))
  session$setInputs(alignment_pan_right = 1, alignment_zoom_out = 1)
  stopifnot(isTRUE(all.equal(alignment_view_range(), c(-0.08, 0.1))),
            is.null(alignment_view_y()),
            alignment_ylim()[2L] > max(original_data))
  session$setInputs(alignment_aligned_brush = list(
    xmin = 0.02, xmax = -0.01, ymin = 0, ymax = 1))
  stopifnot(isTRUE(all.equal(alignment_view_range(), c(-0.01, 0.02))))
  session$setInputs(alignment_reset_view = 1)
  stopifnot(isTRUE(all.equal(alignment_view_range(), full_range)),
            is.null(alignment_view_y()))

  # Pointer events identify the sample on the full matrix: a click on the
  # tallest curve highlights it, a second click or empty space clears it
  # without touching the zoom, and a double-click clears highlight and zoom.
  # Browser clicks are events; a counter keeps repeated clicks distinct.
  clicks <- 0L
  event_at <- function(x, y) list(
    x = x, y = y, nonce = (clicks <<- clicks + 1L),
    coords_css = list(x = 100, y = 50),
    domain = list(left = 0.1, right = -0.1, bottom = -0.1, top = 1.2),
    range = list(left = 0, right = 640, bottom = 400, top = 0),
    img_css_ratio = list(x = 1, y = 1))
  peak_ppm <- original_axis[1L, 32L]
  session$setInputs(alignment_unaligned_click = event_at(peak_ppm, 1.1))
  stopifnot(identical(alignment_highlight(), 3L))
  label <- as.character(.alignment_hover_ui(event_at(peak_ppm, 0.9),
                                            original_data))
  stopifnot(grepl("left", label, fixed = TRUE),
            grepl(sprintf("%.4f ppm", peak_ppm), label, fixed = TRUE),
            is.null(.alignment_hover_ui(event_at(peak_ppm, 0.5),
                                        original_data)))
  session$setInputs(alignment_unaligned_brush = list(
    xmin = -0.04, xmax = 0.05, ymin = 0.1, ymax = 0.8))
  session$setInputs(alignment_unaligned_click = event_at(peak_ppm, 1.1))
  stopifnot(is.null(alignment_highlight()),
            isTRUE(all.equal(alignment_view_range(), c(-0.04, 0.05))))
  session$setInputs(alignment_unaligned_click = event_at(peak_ppm, 1.1))
  stopifnot(identical(alignment_highlight(), 3L))
  session$setInputs(alignment_unaligned_click = event_at(peak_ppm, 0.5))
  stopifnot(is.null(alignment_highlight()),
            isTRUE(all.equal(alignment_view_range(), c(-0.04, 0.05))))
  session$setInputs(alignment_unaligned_click = event_at(peak_ppm, 1.1))
  stopifnot(identical(alignment_highlight(), 3L))
  session$setInputs(alignment_unaligned_brush = list(
    xmin = -0.04, xmax = 0.05, ymin = 0.1, ymax = 0.8))
  session$setInputs(alignment_unaligned_dblclick = list(x = 0, y = 0))
  stopifnot(is.null(alignment_highlight()),
            isTRUE(all.equal(alignment_view_range(), full_range)))

  # "Edit regions" mode: drags from the browser resize, move and add regions
  # and rewrite the text box; a double-click removes one. A half-typed text is
  # never overwritten.
  session$setInputs(icoshift_intervals = "-0.02, 0.02")
  detected_text <- "-0.02, 0.02"
  session$setInputs(alignment_region_drag = list(from = 0.0201, to = 0.03,
                                                 tolerance = 0.001))
  stopifnot(identical(unname(icoshift_editable_intervals()), matrix(c(-0.02, 0.03), 1L)),
            identical(detected_text, "-0.02, 0.03"),
            startsWith(icoshift_status(), "Resized region 1"))
  session$setInputs(alignment_region_drag = list(from = 0, to = -0.01,
                                                 tolerance = 0.001))
  stopifnot(identical(detected_text, "-0.03, 0.02"),
            startsWith(icoshift_status(), "Moved region 1"))
  session$setInputs(alignment_region_drag = list(from = 0.05, to = 0.08,
                                                 tolerance = 0.001))
  stopifnot(identical(detected_text, "-0.03, 0.02\n0.05, 0.08"),
            nrow(icoshift_editable_intervals()) == 2L,
            startsWith(icoshift_status(), "Added region 2"))
  session$setInputs(alignment_region_remove = list(x = 0.06))
  stopifnot(identical(detected_text, "-0.03, 0.02"),
            startsWith(icoshift_status(), "Removed region 2"))
  session$setInputs(alignment_region_remove = list(x = 0))
  stopifnot(identical(detected_text, "-0.03, 0.02"),
            startsWith(icoshift_status(), "At least one region"))
  session$setInputs(icoshift_intervals = "-0.03, ")
  session$setInputs(alignment_region_drag = list(from = 0, to = 0.01,
                                                 tolerance = 0.001))
  stopifnot(identical(detected_text, "-0.03, 0.02"),
            startsWith(icoshift_status(), "Fix the interval text"))
  session$setInputs(icoshift_intervals = "-0.02, 0.02")
  detected_text <- "-0.02, 0.02"

  session$setInputs(icoshift_intervals = detected_text,
                    icoshift_detection_sensitivity = 5,
                    icoshift_frequency_mhz = "400.1318813",
                    icoshift_use_j = TRUE,
                    icoshift_detect = 1)
  detected <- icoshift_detection()
  if (is.null(detected))
    stop(icoshift_status())
  audit <- .icoshift_detection_audit(detected, original_axis[1, ])
  audit_fixture <- detected
  audit_fixture$grouping$multiplet_candidates <- data.frame(
    first_peak = 1L, last_peak = 1L, polarity = "positive", J_Hz = 4,
    confidence = 0.67, confidence_label = "moderate", j_supported = TRUE)
  audit_fixture$regions$congested[1L] <- TRUE
  audit_with_j <- .icoshift_detection_audit(audit_fixture,
                                             original_axis[1, ])
  audit_plot <- .plot_icoshift_detection_audit(audit_with_j)
  audit_plot_built <- ggplot2::ggplot_build(audit_plot)
  stopifnot(is.list(detected), nrow(detected$regions) >= 1L,
            nrow(audit$maxima) == nrow(detected$grouping$peaks),
            nrow(audit$minima) >= 1L,
            nrow(audit$regions) == nrow(detected$regions),
            identical(names(audit$table),
                      c("Type", "ppm", "Prominence", "Width_ppm", "J_Hz",
                        "Confidence", "Alerts")),
            audit_with_j$table$J_Hz[1L] == 4,
            identical(audit_with_j$table$Confidence[1L], "moderate (0.67)"),
            grepl("congested region", audit_with_j$table$Alerts[1L],
                  fixed = TRUE),
            inherits(audit_plot, "ggplot"),
            length(audit_plot_built$data) == 6L,
            identical(NMRData, original_data),
            identical(NMRData_plot, original_data),
            identical(CS_values_real, original_axis),
            identical(file_names, original_names),
            refresh_count == 0L,
            grepl("editable ppm region", icoshift_status(), fixed = TRUE),
            isTRUE(all.equal(
              unname(.parse_icoshift_intervals(detected_text, original_axis[1, ])),
              unname(as.matrix(detected$regions[, c("start_ppm", "end_ppm")])),
              tolerance = 1e-9)))

  detected_intervals <- icoshift_editable_intervals()
  session$setInputs(icoshift_region_brush = list(xmin = -0.09, xmax = -0.075))
  stopifnot(nrow(icoshift_editable_intervals()) == nrow(detected_intervals) + 1L,
            nrow(.icoshift_interval_table(icoshift_editable_intervals())) ==
              nrow(detected_intervals) + 1L,
            grepl("Added region", icoshift_status(), fixed = TRUE))
  session$setInputs(icoshift_region_remove = list(x = -0.0825))
  stopifnot(isTRUE(all.equal(icoshift_editable_intervals(), detected_intervals,
                            check.attributes = FALSE)),
            grepl("Removed region", icoshift_status(), fixed = TRUE))

  last_valid_text <- detected_text
  last_detection <- detected
  session$setInputs(icoshift_frequency_mhz = "invalid", icoshift_detect = 2)
  stopifnot(identical(detected_text, last_valid_text),
            identical(icoshift_detection(), last_detection),
            identical(NMRData, original_data),
            identical(NMRData_plot, original_data),
            identical(CS_values_real, original_axis),
            identical(file_names, original_names),
            refresh_count == 0L,
            startsWith(icoshift_status(), "Detection error:"))

  intervals <- .parse_icoshift_intervals("-0.06, 0.06", original_axis[1, ])
  expected <- suppressMessages(.run_icoshift_alignment(
    original_data, original_axis[1, ], intervals))
  stopifnot(is.function(getFromNamespace("icoshift", "iSTATS")))

  session$setInputs(icoshift_intervals = "-0.06, 0.06", icoshift_align = 1)
  stopifnot(identical(NMRData, expected$xCS),
            identical(NMRData_plot, expected$xCS),
            identical(alignment_original(), original_data),
            identical(alignment_aligned(), expected$xCS),
            identical(CS_values_real, original_axis),
            identical(file_names, original_names),
            identical(icoshift_intervals_used, intervals),
            identical(icoshift_indexes, expected$ind),
            identical(icoshift_applied_intervals(), intervals),
            alignment_data_version() == 1L,
            refresh_count == 1L,
            grepl("Aligned 3 spectra", icoshift_status(), fixed = TRUE))

  # Text and mouse edit one pending proposal without recomputing the matrix.
  # The proposed endpoint stays outside parentheses; each later edit replaces
  # the prior proposal. A new alignment atomically promotes it and clears the
  # parenthetical notation.
  first_aligned_data <- NMRData
  session$setInputs(icoshift_intervals = "-0.05, 0.06")
  stopifnot(identical(detected_text, "-0.05 (-0.06), 0.06"),
            identical(unname(icoshift_editable_intervals()),
                      matrix(c(-0.05, 0.06), 1L)),
            identical(icoshift_applied_intervals(), intervals),
            identical(NMRData, first_aligned_data), refresh_count == 1L)
  session$setInputs(alignment_region_drag = list(from = -0.05, to = -0.04,
                                                 tolerance = 0.001))
  stopifnot(identical(detected_text, "-0.04 (-0.06), 0.06"),
            !grepl("-0.05", detected_text, fixed = TRUE),
            identical(NMRData, first_aligned_data), refresh_count == 1L)
  session$setInputs(alignment_region_drag = list(from = 0.08, to = 0.09,
                                                 tolerance = 0.001))
  stopifnot(identical(detected_text,
                      "-0.04 (-0.06), 0.06\n0.08, 0.09"),
            all(is.na(icoshift_interval_references()[2L, ])),
            identical(icoshift_applied_intervals(), intervals))
  session$setInputs(alignment_region_remove = list(x = 0.085))
  stopifnot(identical(detected_text, "-0.04 (-0.06), 0.06"),
            nrow(icoshift_editable_intervals()) == 1L,
            identical(icoshift_applied_intervals(), intervals))
  detected_text <- "-0.03 (-0.06), 0.06"
  session$setInputs(icoshift_intervals = detected_text)
  pending_intervals <- matrix(c(-0.03, 0.06), 1L)
  session$setInputs(icoshift_reference = "1")
  pending_expected <- suppressMessages(.run_icoshift_alignment(
    original_data, original_axis[1, ], pending_intervals,
    target = original_data[1L, ]))
  stopifnot(identical(icoshift_editable_intervals(), pending_intervals),
            identical(detected_text, "-0.03 (-0.06), 0.06"),
            identical(NMRData, first_aligned_data), refresh_count == 1L)
  session$setInputs(icoshift_align = 2)
  stopifnot(identical(NMRData, pending_expected$xCS),
            identical(icoshift_applied_intervals(), pending_intervals),
            identical(icoshift_interval_references(), pending_intervals),
            identical(detected_text, "-0.03, 0.06"),
            alignment_data_version() == 2L, refresh_count == 2L)

  # An invalid reference is rejected before any state is committed.
  before_bad_reference <- NMRData
  session$setInputs(icoshift_reference = "99", icoshift_align = 3)
  stopifnot(identical(NMRData, before_bad_reference), refresh_count == 2L,
            startsWith(icoshift_status(), "Alignment error:"))

  aligned_data <- NMRData
  session$setInputs(icoshift_reference = "average",
                    icoshift_intervals = "not an interval", icoshift_align = 4)
  stopifnot(identical(NMRData, aligned_data),
            identical(NMRData_plot, aligned_data),
            identical(CS_values_real, original_axis),
            identical(file_names, original_names),
            refresh_count == 2L,
            startsWith(icoshift_status(), "Alignment error:"))

  # An automatic input error is atomic: neither the prior audit nor aligned
  # data/applied intervals are changed. A valid action then detects and aligns.
  before_auto_data <- NMRData
  before_auto_detection <- icoshift_detection()
  before_auto_applied <- icoshift_applied_intervals()
  before_auto_text <- detected_text
  session$setInputs(icoshift_frequency_mhz = "invalid", icoshift_auto_align = 1)
  stopifnot(identical(NMRData, before_auto_data),
            identical(icoshift_detection(), before_auto_detection),
            identical(icoshift_applied_intervals(), before_auto_applied),
            identical(detected_text, before_auto_text),
            refresh_count == 2L,
            startsWith(icoshift_status(), "Automatic alignment error:"))

  session$setInputs(icoshift_frequency_mhz = "400.1318813",
                    icoshift_reference = "3",
                    icoshift_auto_align = 2)
  expected_last <- suppressMessages(.run_icoshift_alignment(
    original_data, original_axis[1, ], intervals,
    target = original_data[3L, ]))
  stopifnot(refresh_count == 3L,
            identical(NMRData, expected_last$xCS),
            identical(NMRData_plot, NMRData),
            identical(alignment_original(), original_data),
            identical(alignment_aligned(), NMRData),
            identical(CS_values_real, original_axis),
            identical(file_names, original_names),
            is.list(icoshift_detection()),
            identical(icoshift_applied_intervals(),
                      icoshift_editable_intervals()),
            identical(icoshift_intervals_used, icoshift_applied_intervals()),
            grepl("Automatically detected and applied", icoshift_status(),
                  fixed = TRUE),
            grepl("duplicate (sample 3)", icoshift_status(), fixed = TRUE))

  # Large sources are cached and restored by the session, while a new import
  # discards both the previous result and cache. Alignment always starts from
  # the immutable source, so repeating it above did not accumulate shifts.
  stopifnot(.cache_large_alignment_source(), is.null(alignment_original()),
            file.exists(alignment_original_cache()),
            dir.exists(alignment_cache_dir()),
            identical(.alignment_original_data(), original_data))
  cached_path <- alignment_original_cache()
  cached_directory <- alignment_cache_dir()
  cached_expected <- suppressMessages(.run_icoshift_alignment(
    original_data, original_axis[1, ], intervals,
    target = original_data[2L, ]))
  session$setInputs(icoshift_reference = "2",
                    icoshift_intervals = "-0.06, 0.06", icoshift_align = 5)
  stopifnot(is.null(alignment_original()),
            identical(NMRData, cached_expected$xCS), refresh_count == 4L,
            grepl("reference (sample 2)", icoshift_status(), fixed = TRUE))
  stopifnot(.restore_alignment_source(notify = FALSE),
            identical(alignment_original(), original_data))
  replacement <- original_data * 2
  NMRData <- replacement
  NMRData_plot <- replacement
  .reset_alignment_source(replacement)
  stopifnot(identical(alignment_original(), replacement),
            is.null(alignment_aligned()), is.null(alignment_original_cache()),
            is.null(alignment_cache_dir()), !file.exists(cached_path),
            !dir.exists(cached_directory), is.null(icoshift_detection()),
            is.null(icoshift_applied_intervals()),
            is.null(icoshift_interval_references()),
            alignment_data_version() == 5L,
            identical(reference_update$selected, "average"),
            identical(unname(reference_update$choices),
                      c("average", "1", "2", "3")),
            identical(names(reference_update$choices),
                      c("Average spectrum", "duplicate", "reference", "duplicate")))

  # Importers display the data as read and analyse it shifted by a constant;
  # aligning must keep that constant out of the displayed matrix.
  NMRData_plot <- replacement - 7
  offset_expected <- suppressMessages(.run_icoshift_alignment(
    replacement, original_axis[1, ], intervals))
  session$setInputs(icoshift_reference = "average",
                    icoshift_intervals = "-0.06, 0.06", icoshift_align = 6)
  stopifnot(identical(NMRData, offset_expected$xCS),
            isTRUE(all.equal(NMRData_plot, offset_expected$xCS - 7)))
  }), envir = environment(.run_icoshift_alignment))
})

# Shiny runs onSessionEnded callbacks outside any reactive context. Evaluate
# the app's own callback that way and require it to remove the session cache.
local({
  expressions <- parse(app_file("Pretreatment_server.R"))
  ended <- Filter(function(expr) {
    is.call(expr) && identical(expr[[1L]], quote(session$onSessionEnded))
  }, expressions)
  stopifnot(length(ended) == 1L)
  cleanup_env <- new.env()
  cache_dir <- tempfile("istats-session-")
  dir.create(cache_dir)
  cache_path <- file.path(cache_dir, "original.rds")
  saveRDS(1, cache_path)
  cleanup_env$alignment_cache_dir <- reactiveVal(cache_dir)
  cleanup_env$alignment_original_cache <- reactiveVal(cache_path)
  eval(Filter(function(expr) {
    is.call(expr) && identical(expr[[1L]], as.name("<-")) &&
      identical(as.character(expr[[2L]]), ".remove_alignment_cache")
  }, expressions)[[1L]], envir = cleanup_env)
  callback <- eval(ended[[1L]][[2L]], envir = cleanup_env)
  callback()
  stopifnot(!dir.exists(cache_dir),
            is.null(isolate(cleanup_env$alignment_cache_dir())),
            is.null(isolate(cleanup_env$alignment_original_cache())))
})

cat(paste0("PASS Shiny icoshift workflows: assisted detection, graphical ",
           "add/remove, explicit manual confirmation, atomic automatic ",
           "detect-and-align, indexed references, immutable source, session ",
           "cache, and applied-region audit\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.