inst/app/Pretreatment_server.R

## Module Pretreatment ###############################

# Variables
NMRData_Mean <- colMeans(NMRData[,])
ysup <- max(NMRData[,])
yinf <- ysup*-0.03
ysup <- ysup + ysup*0.03
p_value <- 0.05


# Data.frame
testy_norm <<- data.frame(Chemical_Shift=CS_values_real[1,],Spectrum=NMRData[1,])
CS_norm <<- reactiveValues(vranges = c(-13131313,-131313))
ranges <- reactiveValues(x = c(min(testy_norm$Chemical_Shift),(max(testy_norm$Chemical_Shift))), y = c(yinf,ysup))
ranges_sel <- reactiveValues(x = c(min(testy_norm$Chemical_Shift),(max(testy_norm$Chemical_Shift))), y = c(yinf,ysup))
spectrums <- reactiveValues(dat = data.frame(Chemical_Shift=CS_values_real[1,],Spectrum=NMRData[1,]))
spectrums_sel <- reactiveValues(dat = data.frame(Chemical_Shift=CS_values_real[1,],Spectrum=NMRData[1,]))
rr_n <<- reactiveValues(csranges = c(-13131313,-131313))
icoshift_status <- reactiveVal("No icoshift alignment has been applied in this session.")
icoshift_detection <- reactiveVal(NULL)
icoshift_editable_intervals <- reactiveVal(matrix(c(-0.1, 0.1), nrow = 1L))
icoshift_interval_references <- reactiveVal(NULL)
icoshift_applied_intervals <- reactiveVal(NULL)
alignment_original <- reactiveVal(NULL)
alignment_aligned <- reactiveVal(NULL)
alignment_original_cache <- reactiveVal(NULL)
alignment_cache_dir <- reactiveVal(NULL)
alignment_view_range <- reactiveVal(NULL)
alignment_view_y <- reactiveVal(NULL)
alignment_highlight <- reactiveVal(NULL)
alignment_data_version <- reactiveVal(0L)
alignment_previous_tab <- reactiveVal(NULL)
alignment_memory_point_limit <- 65536L
output$icoshift_status <- renderText(icoshift_status())
output$icoshift_detection_available <- reactive(!is.null(icoshift_detection()))
outputOptions(output, "icoshift_detection_available", suspendWhenHidden = FALSE)
output$alignment_original_available <- reactive(
  !is.null(alignment_original()) || !is.null(alignment_original_cache()))
output$alignment_result_available <- reactive(!is.null(alignment_aligned()))
outputOptions(output, "alignment_original_available", suspendWhenHidden = FALSE)
outputOptions(output, "alignment_result_available", suspendWhenHidden = FALSE)

.remove_alignment_cache <- function() {
  directory <- alignment_cache_dir()
  if (!is.null(directory) && dir.exists(directory))
    unlink(directory, recursive = TRUE, force = TRUE)
  alignment_original_cache(NULL)
  alignment_cache_dir(NULL)
}

.alignment_original_data <- function() {
  data <- alignment_original()
  if (!is.null(data)) return(data)
  path <- alignment_original_cache()
  if (is.null(path) || !file.exists(path)) return(NULL)
  readRDS(path)
}

# Called by every successful importer. It makes a new import the immutable
# source for detection/alignment and clears every result from the prior data.
.reset_alignment_source <- function(data) {
  stopifnot(is.matrix(data), is.numeric(data), nrow(data) > 0L, ncol(data) > 0L)
  .remove_alignment_cache()
  alignment_original(data)
  alignment_aligned(NULL)
  alignment_view_range(range(CS_values_real[1, ], finite = TRUE))
  alignment_view_y(NULL)
  alignment_highlight(NULL)
  alignment_data_version(isolate(alignment_data_version()) + 1L)
  icoshift_detection(NULL)
  icoshift_interval_references(NULL)
  icoshift_applied_intervals(NULL)
  updateSelectInput(
    session, "icoshift_reference",
    choices = .alignment_reference_choices(file_names, nrow(data)),
    selected = "average")
  icoshift_status("Imported spectra are ready. Alignment is optional.")
}

.cache_large_alignment_source <- function() {
  data <- alignment_original()
  if (is.null(data) || ncol(data) <= alignment_memory_point_limit) return(FALSE)
  directory <- alignment_cache_dir()
  if (is.null(directory) || !dir.exists(directory)) {
    directory <- tempfile("istats-session-")
    if (!dir.create(directory, recursive = FALSE))
      stop("Could not create the session alignment cache.")
    alignment_cache_dir(directory)
  }
  path <- file.path(directory, "original.rds")
  saveRDS(data, path, compress = FALSE)
  alignment_original_cache(path)
  alignment_original(NULL)
  TRUE
}

.restore_alignment_source <- function(notify = TRUE) {
  if (!is.null(alignment_original())) return(FALSE)
  path <- alignment_original_cache()
  if (is.null(path) || !file.exists(path)) return(FALSE)
  if (notify)
    showNotification("Loading original data\u2026", type = "message", duration = 2)
  alignment_original(readRDS(path))
  TRUE
}

# onSessionEnded runs outside any reactive context; reactiveVal reads need isolate().
session$onSessionEnded(function() isolate(.remove_alignment_cache()))

observeEvent(input$main_bar, {
  current <- input$main_bar
  previous <- alignment_previous_tab()
  if (identical(current, "Alignment")) .restore_alignment_source()
  if (identical(previous, "Alignment") && !identical(current, "Alignment"))
    .cache_large_alignment_source()
  alignment_previous_tab(current)
}, ignoreInit = FALSE)

# Both comparison panels are PNGs drawn on the server from a per-pixel
# envelope of the full matrices. They share one x/y view, so brushing either
# panel zooms both without browser-side synchronization.
.alignment_full_range <- function() range(CS_values_real[1, ], finite = TRUE)

.alignment_xlim <- function() {
  visible <- alignment_view_range()
  if (is.null(visible)) .alignment_full_range() else visible
}

alignment_ylim <- reactive({
  limits <- alignment_view_y()
  if (!is.null(limits)) return(limits)
  .spectra_ylim(list(.alignment_original_data(), alignment_aligned()),
                CS_values_real[1, ], .alignment_xlim())
})

.alignment_render_panel <- function(data, output_id) {
  width <- session$clientData[[paste0("output_", output_id, "_width")]]
  ratio <- session$clientData$pixelratio
  if (is.null(width) || !is.finite(width)) width <- 1000
  if (is.null(ratio) || !is.finite(ratio)) ratio <- 1
  xlim <- .alignment_xlim()
  envelope <- .alignment_pixel_envelope(data, CS_values_real[1, ], xlim,
                                        width * ratio)
  visible_applied <- .icoshift_visible_applied_intervals(
    icoshift_editable_intervals(), icoshift_interval_references(),
    icoshift_applied_intervals())
  .spectra_draw_panel(envelope, xlim, alignment_ylim(),
                      editable = icoshift_editable_intervals(),
                      applied = visible_applied,
                      highlight = alignment_highlight())
}

.alignment_plot_cache_key <- function() list(
  alignment_data_version(), alignment_view_range(), alignment_view_y(),
  icoshift_editable_intervals(), icoshift_interval_references(),
  icoshift_applied_intervals(),
  alignment_highlight())

output$alignment_unaligned_plot <- bindCache(renderPlot({
  data <- .alignment_original_data()
  req(data)
  .alignment_render_panel(data, "alignment_unaligned_plot")
}, res = 96), .alignment_plot_cache_key(), !is.null(alignment_original()),
cache = "session")

output$alignment_aligned_plot <- bindCache(renderPlot({
  req(alignment_aligned())
  .alignment_render_panel(alignment_aligned(), "alignment_aligned_plot")
}, res = 96), .alignment_plot_cache_key(), !is.null(alignment_aligned()),
cache = "session")

.alignment_zoom <- function(brush) {
  if (is.null(brush)) return(FALSE)
  x <- sort(c(brush$xmin, brush$xmax))
  y <- sort(c(brush$ymin, brush$ymax))
  if (any(!is.finite(c(x, y))) || diff(x) <= 0) return(FALSE)
  alignment_view_range(x)
  if (diff(y) > 0) alignment_view_y(y)
  TRUE
}

.alignment_reset_view <- function(clear_highlight = FALSE) {
  alignment_view_range(.alignment_full_range())
  alignment_view_y(NULL)
  if (clear_highlight) alignment_highlight(NULL)
}

.alignment_move_view <- function(zoom = 1, shift = 0) {
  alignment_view_range(.spectra_shift_range(alignment_view_range(),
                                            .alignment_full_range(), zoom, shift))
  if (zoom != 1) alignment_view_y(NULL)
}

.alignment_hit <- function(event, data) {
  if (is.null(event) || is.null(data)) return(NULL)
  tolerance <- .plot_event_tolerance(event)
  .nearest_spectrum(data, CS_values_real[1, ], event$x, event$y,
                    tolerance[["x"]], tolerance[["y"]])
}

# A click on a curve highlights it; clicking it again or clicking empty space
# clears the highlight without changing the zoom.
.alignment_pick <- function(event, data) {
  hit <- .alignment_hit(event, data)
  if (is.null(hit) || identical(alignment_highlight(), hit$index))
    alignment_highlight(NULL)
  else
    alignment_highlight(hit$index)
  hit
}

.alignment_hover_ui <- function(event, data) {
  hit <- .alignment_hit(event, data)
  if (is.null(hit)) return(NULL)
  .spectra_hover_label(event, hit, .spectrum_label(hit$index, file_names))
}

output$alignment_unaligned_hover_label <- renderUI(
  .alignment_hover_ui(input$alignment_unaligned_hover,
                      .alignment_original_data()))
output$alignment_aligned_hover_label <- renderUI(
  .alignment_hover_ui(input$alignment_aligned_hover, alignment_aligned()))

output$alignment_highlight_text <- renderText({
  index <- alignment_highlight()
  # Short enough for the one-line status chip; the full rule lives in the
  # "?" popover of alignment_ui.R.
  if (is.null(index)) return("Hover a curve to identify its sample")
  paste0("Highlighted: ", .spectrum_label(index, file_names))
})

observeEvent(input$alignment_unaligned_brush,
             .alignment_zoom(input$alignment_unaligned_brush))
observeEvent(input$alignment_aligned_brush,
             .alignment_zoom(input$alignment_aligned_brush))
observeEvent(input$alignment_unaligned_click,
             .alignment_pick(input$alignment_unaligned_click,
                             .alignment_original_data()))
observeEvent(input$alignment_aligned_click,
             .alignment_pick(input$alignment_aligned_click, alignment_aligned()))
observeEvent(input$alignment_unaligned_dblclick, .alignment_reset_view(TRUE))
observeEvent(input$alignment_aligned_dblclick, .alignment_reset_view(TRUE))
observeEvent(input$alignment_reset_view, .alignment_reset_view(), ignoreInit = TRUE)
observeEvent(input$alignment_zoom_out, .alignment_move_view(zoom = 2), ignoreInit = TRUE)
observeEvent(input$alignment_pan_left, .alignment_move_view(shift = 0.5), ignoreInit = TRUE)
observeEvent(input$alignment_pan_right, .alignment_move_view(shift = -0.5), ignoreInit = TRUE)

icoshift_detection_audit <- reactive({
  req(icoshift_detection())
  audit <- .icoshift_detection_audit(icoshift_detection(), CS_values_real[1, ])
  intervals <- icoshift_editable_intervals()
  audit$regions <- data.frame(
    ppm_min = pmin(intervals[, 1L], intervals[, 2L]),
    ppm_max = pmax(intervals[, 1L], intervals[, 2L]),
    region_id = seq_len(nrow(intervals)))
  audit
})

output$icoshift_detection_plot <- renderPlot({
  .plot_icoshift_detection_audit(icoshift_detection_audit())
})

output$icoshift_detection_table <- renderTable({
  icoshift_detection_audit()$table
}, digits = 6, na = "-", striped = TRUE, bordered = TRUE,
   spacing = "xs", width = "100%")

output$icoshift_regions_table <- renderTable({
  .icoshift_interval_comparison_table(
    icoshift_editable_intervals(), icoshift_interval_references())
}, digits = 6, striped = TRUE, bordered = TRUE, spacing = "xs", width = "100%")

output$icoshift_applied_regions_table <- renderTable({
  intervals <- icoshift_applied_intervals()
  if (is.null(intervals)) return(NULL)
  .icoshift_interval_table(intervals)
}, digits = 6, striped = TRUE, bordered = TRUE, spacing = "xs", width = "100%")

# These two tables sit behind inactive tabs in alignment_ui.R; keeping them
# unsuspended means the tab is already filled when the user opens it.
outputOptions(output, "icoshift_detection_table", suspendWhenHidden = FALSE)
outputOptions(output, "icoshift_applied_regions_table", suspendWhenHidden = FALSE)

# Keep valid textual edits, the graphical overlay and the current-region table
# synchronized. During an incomplete edit, the last valid preview is retained.
observeEvent(input$icoshift_intervals, {
  tryCatch({
    parsed <- .parse_icoshift_interval_text(input$icoshift_intervals,
                                            CS_values_real[1, ])
    old_intervals <- isolate(icoshift_editable_intervals())
    references <- .reconcile_icoshift_interval_references(
      old_intervals, isolate(icoshift_interval_references()), parsed$intervals)
    icoshift_editable_intervals(parsed$intervals)
    icoshift_interval_references(references)
    normalized <- .format_icoshift_pending_intervals(parsed$intervals, references)
    if (!identical(input$icoshift_intervals, normalized))
      updateTextAreaInput(session, "icoshift_intervals", value = normalized)
  }, error = function(e) NULL)
}, ignoreInit = TRUE)

observeEvent(input$icoshift_region_brush, {
  req(icoshift_detection(), input$icoshift_region_brush)
  brush <- input$icoshift_region_brush
  candidate <- c(brush$xmin, brush$xmax)
  tryCatch({
    intervals <- rbind(icoshift_editable_intervals(), candidate)
    references <- .reconcile_icoshift_interval_references(
      icoshift_editable_intervals(), icoshift_interval_references(), intervals)
    text <- .format_icoshift_pending_intervals(intervals, references)
    intervals <- .parse_icoshift_intervals(text, CS_values_real[1, ])
    icoshift_editable_intervals(intervals)
    icoshift_interval_references(references)
    updateTextAreaInput(session, "icoshift_intervals", value = text)
    icoshift_status(sprintf("Added region %.6g to %.6g ppm; confirm alignment when ready.",
                            candidate[1L], candidate[2L]))
  }, error = function(e) {
    icoshift_status(paste("Region edit error:", conditionMessage(e)))
  })
})

# Publishes an edited region matrix to the overlay, the table and the text box.
.publish_icoshift_intervals <- function(intervals, message) {
  references <- .reconcile_icoshift_interval_references(
    icoshift_editable_intervals(), icoshift_interval_references(), intervals)
  text <- .format_icoshift_pending_intervals(intervals, references)
  intervals <- .parse_icoshift_intervals(text, CS_values_real[1, ])
  icoshift_editable_intervals(intervals)
  icoshift_interval_references(references)
  updateTextAreaInput(session, "icoshift_intervals", value = text)
  icoshift_status(message)
}

.remove_icoshift_region_at <- function(ppm) {
  tryCatch({
    removed <- .remove_icoshift_interval(icoshift_editable_intervals(), ppm)
    if (!is.null(removed))
      .publish_icoshift_intervals(removed$intervals, sprintf(
        "Removed region %d; confirm alignment when ready.", removed$region))
  }, error = function(e) icoshift_status(conditionMessage(e)))
}

observeEvent(input$icoshift_region_remove, {
  req(icoshift_detection(), input$icoshift_region_remove)
  .remove_icoshift_region_at(input$icoshift_region_remove$x)
})

# Region editing directly on the comparison panels ("Edit regions" mode). The
# browser sends the drag in ppm; a half-typed interval text is never replaced.
.icoshift_text_is_valid <- function() {
  text <- input$icoshift_intervals
  is.null(text) || !inherits(tryCatch(
    .parse_icoshift_intervals(text, CS_values_real[1, ]),
    error = function(e) e), "error")
}

observeEvent(input$alignment_region_drag, {
  drag <- input$alignment_region_drag
  if (!.icoshift_text_is_valid()) {
    icoshift_status("Fix the interval text before editing regions on the plot.")
    return()
  }
  tryCatch({
    edited <- .drag_icoshift_interval(icoshift_editable_intervals(),
                                      as.numeric(drag$from), as.numeric(drag$to),
                                      as.numeric(drag$tolerance),
                                      range(CS_values_real[1, ]))
    limits <- edited$intervals[edited$region, ]
    .publish_icoshift_intervals(edited$intervals, sprintf(
      "%s region %d: %.4f to %.4f ppm; confirm alignment when ready.",
      edited$action, edited$region, limits[1L], limits[2L]))
  }, error = function(e) icoshift_status(paste("Region edit:", conditionMessage(e))))
})

observeEvent(input$alignment_region_remove, {
  if (!.icoshift_text_is_valid()) {
    icoshift_status("Fix the interval text before editing regions on the plot.")
    return()
  }
  .remove_icoshift_region_at(as.numeric(input$alignment_region_remove$x))
})

.commit_icoshift_alignment <- function(result, intervals) {
  # Importers keep NMRData_plot as read and add one constant to NMRData so it
  # is positive. The alignment runs on NMRData; take that constant back out so
  # the displayed intensities do not jump after aligning.
  offset <- NMRData[1L, 1L] - NMRData_plot[1L, 1L]
  NMRData_plot <<- if (isTRUE(offset != 0)) result$xCS - offset else result$xCS
  NMRData <<- result$xCS
  alignment_aligned(result$xCS)
  alignment_data_version(isolate(alignment_data_version()) + 1L)
  icoshift_intervals_used <<- intervals
  icoshift_indexes <<- result$ind
  icoshift_editable_intervals(intervals)
  icoshift_interval_references(intervals)
  icoshift_applied_intervals(intervals)
  updateTextAreaInput(session, "icoshift_intervals",
                      value = .format_icoshift_pending_intervals(intervals, intervals))
  refreshval()
}



# Detect against the current, unaligned matrix. Only the editable suggestion and
# its audit result are published after complete validation.
observeEvent(input$icoshift_detect, {
  old_file_names <- file_names
  old_axis <- CS_values_real
  tryCatch({
    original <- .alignment_original_data()
    if (is.null(original)) stop("Import spectra before detecting regions.")
    if (length(file_names) != nrow(original))
      stop("Sample names do not match the rows of NMRData.")
    frequency_mhz <- .parse_optional_frequency_mhz(input$icoshift_frequency_mhz)
    suggestion <- withProgress(message = "Detecting alignment regions...", value = 0, {
      detected <- .run_alignment_region_detection(
        original, CS_values_real[1, ],
        sensitivity = input$icoshift_detection_sensitivity,
        frequency_mhz = frequency_mhz,
        use_j = isTRUE(input$icoshift_use_j))
      incProgress(1)
      detected
    })

    if (!identical(file_names, old_file_names) || !identical(CS_values_real, old_axis))
      stop("Sample names or chemical-shift axis changed unexpectedly; suggestions were not applied.")

    updateTextAreaInput(session, "icoshift_intervals", value = suggestion$text)
    icoshift_editable_intervals(suggestion$intervals)
    icoshift_interval_references(NULL)
    icoshift_detection(suggestion$result)
    icoshift_status(sprintf("Detected %d editable ppm region(s); spectra were not aligned.",
                            nrow(suggestion$intervals)))
    showNotification("Alignment regions detected; review them before aligning.",
                     type = "message")
  }, error = function(e) {
    message <- paste("Detection error:", conditionMessage(e))
    icoshift_status(message)
    showModal(modalDialog(title = "Alignment-region detection", message,
                          easyClose = TRUE, footer = modalButton("Close")))
  })
})

# Complete automatic workflow. Detection and alignment are computed locally;
# no suggestion or data is published unless both results pass validation.
observeEvent(input$icoshift_auto_align, {
  old_file_names <- file_names
  old_axis <- CS_values_real
  tryCatch({
    original <- .alignment_original_data()
    if (is.null(original)) stop("Import spectra before aligning.")
    if (length(file_names) != nrow(original))
      stop("Sample names do not match the rows of NMRData.")
    reference <- .resolve_icoshift_target(
      original, input$icoshift_reference, file_names)
    frequency_mhz <- .parse_optional_frequency_mhz(input$icoshift_frequency_mhz)
    automatic <- withProgress(message = "Detecting and aligning spectra...", value = 0, {
      suggestion <- .run_alignment_region_detection(
        original, CS_values_real[1, ],
        sensitivity = input$icoshift_detection_sensitivity,
        frequency_mhz = frequency_mhz,
        use_j = isTRUE(input$icoshift_use_j))
      incProgress(0.5)
      aligned <- .run_icoshift_alignment(
        original, CS_values_real[1, ], suggestion$intervals,
        target = reference$target)
      incProgress(0.5)
      list(suggestion = suggestion, aligned = aligned)
    })
    if (!identical(file_names, old_file_names) || !identical(CS_values_real, old_axis))
      stop("Sample names or chemical-shift axis changed unexpectedly; automatic alignment was not applied.")

    updateTextAreaInput(session, "icoshift_intervals",
                        value = automatic$suggestion$text)
    icoshift_detection(automatic$suggestion$result)
    icoshift_editable_intervals(automatic$suggestion$intervals)
    icoshift_interval_references(NULL)
    .commit_icoshift_alignment(automatic$aligned,
                               automatic$suggestion$intervals)
    icoshift_status(sprintf(
      paste0("Automatically detected and applied %d ppm region(s) to %d ",
             "spectra using %s as the alignment reference."),
      nrow(automatic$suggestion$intervals), nrow(NMRData), reference$label))
    showNotification("Automatic icoshift alignment completed.", type = "message")
  }, error = function(e) {
    message <- paste("Automatic alignment error:", conditionMessage(e))
    icoshift_status(message)
    showModal(modalDialog(title = "Automatic icoshift alignment", message,
                          easyClose = TRUE, footer = modalButton("Close")))
  })
})

# Align the complete matrix while keeping sample names and the ppm axis intact.
# State is only replaced after icoshift completes and its result is validated.
observeEvent(input$icoshift_align, {
  old_file_names <- file_names
  old_axis <- CS_values_real
  tryCatch({
    original <- .alignment_original_data()
    if (is.null(original)) stop("Import spectra before aligning.")
    if (length(file_names) != nrow(original))
      stop("Sample names do not match the rows of NMRData.")
    reference <- .resolve_icoshift_target(
      original, input$icoshift_reference, file_names)
    intervals <- .parse_icoshift_intervals(input$icoshift_intervals,
                                           CS_values_real[1, ])
    result <- withProgress(message = "Aligning spectra with icoshift...", value = 0, {
      aligned <- .run_icoshift_alignment(
        original, CS_values_real[1, ], intervals, target = reference$target)
      incProgress(1)
      aligned
    })

    if (!identical(file_names, old_file_names) || !identical(CS_values_real, old_axis))
      stop("Sample names or chemical-shift axis changed unexpectedly; alignment was not applied.")

    .commit_icoshift_alignment(result, intervals)
    icoshift_status(sprintf(
      "Aligned %d spectra in %d ppm interval(s) using %s as the alignment reference.",
      nrow(NMRData), nrow(intervals), reference$label))
    showNotification("icoshift alignment completed.", type = "message")
  }, error = function(e) {
    message <- paste("Alignment error:", conditionMessage(e))
    icoshift_status(message)
    showModal(modalDialog(title = "icoshift alignment", message,
                          easyClose = TRUE, footer = modalButton("Close")))
  })
})


# Plot Normalization

# Plot spectra average
output$plot_norm <- renderPlot({
  ggplot2::ggplot(spectrums$dat,ggplot2::aes(Chemical_Shift,Spectrum)) + ggplot2::geom_line(color='blue') + ggplot2::scale_x_reverse() +
    ggplot2::coord_cartesian(xlim = c(ranges$x[2],ranges$x[1]), ylim = ranges$y, expand = FALSE) +
    ggplot2::theme(axis.text.x = ggplot2::element_text(size = 12, color = "#000000"),
                    axis.text.y = ggplot2::element_text(size = 12, color = "#000000"),
                    title = ggplot2::element_text(face = "bold", color = "#000000", size = 17),
                    axis.title = ggplot2::element_text(face = "bold", color = "#000000", size = 15)
    ) +
    ggplot2::labs(x = "Chemical Shift", y = "Intensity") +
    ggplot2::geom_vline(xintercept=rr_nn$csranges, color = "green", size = 0.1, alpha=0.3) +
    ggplot2::geom_vline(xintercept=rr_n$csranges, color = "red", size = 0.1, alpha=0.3)
})



# Brush
observeEvent(input$plot_brush_norm,{
  brush <- input$plot_brush_norm

  if (!is.null(brush)) {
    ranges$x <- c(brush$xmin, brush$xmax)
    ranges$y <- c(brush$ymin, brush$ymax)
    spectrums$dat$Spectrum <- testy$Spectrum*chkzoom
    peran <<- (ranges$x[2] - ranges$x[1])*0.2
  }

  else {
    ranges$x <- c(min(testy$Chemical_Shift),(max(testy$Chemical_Shift)))
  }
})


# Mean centering
observeEvent(input$mean_norm,{
  # s_stoc <<- 0


  .mean_centering()

  choose_norm <<- 7

})


# Scaling
observeEvent(input$scaling_norm,{
  if (!(sel_ind == 0)) {

  rr_n$csranges <<- c()
  col_sel_norm <<- c()

  .autoscaling()

  f <- 0
  output$norm_cond <- renderText(paste("After normalize: ", dif,"%"))

  for (j in 1:length(norm_var)) {

    if (norm_var[j] == "NO") {
      f <- f + 1
      col_sel_norm[f] <<- col_select[j]
    }
    else{

    }
  }
  rr_n$csranges <- CS_values_real[1,col_sel_norm]
  choose_norm <<- 6
  }

  else{
    showModal(modalDialog(
      title = "Warning!!!",
      "No region was selected. You must first select the desired region(s) before to start Normalize section!",
      easyClose = TRUE,
      footer = modalButton("Close"),
      size = "l"
    ))
  }

})


# Pareto
observeEvent(input$pareto_norm,{

  if (!(sel_ind == 0)) {

  rr_n$csranges <<- c()
  .pareto()
  col_sel_norm <<- c()
  f <- 0


  output$norm_cond <- renderText(paste("Affter normalize: ", dif,"%"))

  for (j in 1:length(norm_var)) {

    if (norm_var[j] == "NO") {
      f <- f + 1
      col_sel_norm[f] <<- col_select[j]
    }
    else{

    }
  }
  rr_n$csranges <- CS_values_real[1,col_sel_norm]
  choose_norm <<- 5
  }
  else{
    showModal(modalDialog(
      title = "Warning!!!",
      "No region was selected. You must first select the desired region(s) before to start Normalize section!",
      easyClose = TRUE,
      footer = modalButton("Close"),
      size = "l"
    ))
  }

})

# Square Root
observeEvent(input$sqr_norm,{
  if (!(sel_ind == 0)) {

  rr_n$csranges <<- c()
  .sqr_norm()
  col_sel_norm <<- c()
  f <- 0

  output$norm_cond <- renderText(paste("Affter normalize: ", dif,"%"))

  for (j in 1:length(norm_var)) {

    if (norm_var[j] == "NO") {
      f <- f + 1
      col_sel_norm[f] <<- col_select[j]
    }
    else{

    }
  }

  rr_n$csranges <- CS_values_real[1,col_sel_norm]
  choose_norm <<- 4
  }

  else{
    showModal(modalDialog(
      title = "Warning!!!",
      "No region was selected. You must first select the desired region(s) before to start Normalize section!",
      easyClose = TRUE,
      footer = modalButton("Close"),
      size = "l"
    ))
  }

})


# Inverse Square Root
observeEvent(input$i_sqr_norm,{
  if (!(sel_ind == 0)) {

  rr_n$csranges <<- c()
  .isqr_norm()
  col_sel_norm <<- c()
  f <- 0

  output$norm_cond <- renderText(paste("Affter normalize: ", dif,"%"))

  for (j in 1:length(norm_var)) {

    if (norm_var[j] == "NO") {
      f <- f + 1
      col_sel_norm[f] <<- col_select[j]
    }
    else{

    }
  }

  rr_n$csranges <- CS_values_real[1,col_sel_norm]
  choose_norm <<- 3
  }

  else{
    showModal(modalDialog(
      title = "Warning!!!",
      "No region was selected. You must first select the desired region(s) before to start Normalize section!",
      easyClose = TRUE,
      footer = modalButton("Close"),
      size = "l"
    ))
  }

})


# Log
observeEvent(input$log_norm,{

  if (!(sel_ind == 0)) {

  rr_n$csranges <<- c()
  .log_norm()
  col_sel_norm <<- c()
  f <- 0

  output$norm_cond <- renderText(paste("Affter normalize: ", dif,"%"))

  for (j in 1:length(norm_var)) {

    if (norm_var[j] == "NO") {
      f <- f + 1
      col_sel_norm[f] <<- col_select[j]
    }
    else{

    }
  }

  rr_n$csranges <- CS_values_real[1,col_sel_norm]
  choose_norm <<- 2
  }

  else{
    showModal(modalDialog(
      title = "Warning!!!",
      "No region was selected. You must first select the desired region(s) before to start Normalize section!",
      easyClose = TRUE,
      footer = modalButton("Close"),
      size = "l"
    ))
  }

})



# Start STOCSY-I
observeEvent(input$s_stocsy_i_norm, {
  if (choose_norm == 1) {
    .s_stocsy(matr_cor)
  }

  if (choose_norm == 2) {
    .s_stocsy(NMR_log)
  }
  if (choose_norm == 3) {
    .s_stocsy(NMR_i_sqr)
  }
  if (choose_norm == 4) {
    .s_stocsy(NMR_sqr)
  }
  if (choose_norm == 5) {
    .s_stocsy(NMR_Pareto)
  }
  if (choose_norm == 6) {
    .s_stocsy(NMR_ASC)
  }
  if (choose_norm == 7) {
    .s_stocsy(NMR_MC)
  }

})


# R critical by P-value
observeEvent(input$pv_n, {
  p_value_n <- as.numeric(input$pv_n)
  p_value <- p_value_n
  r_critical(p_value_n)
  output$r_critical <- renderText(paste("R critical = +/-",abs(R_CRITICAL[1])))
})





# Download point selected
output$downloadpoints2 <- downloadHandler(
  filename = function() {
    paste("Selected_Regions", ".csv", sep = "")
  },
  content = function(file) {
    if (choose_norm == 1) {
      col_select <<- col_select[order(col_select)]
      CS_sel_real <<- CS_values_real[1, col_select]
      matr_cor <<- NMRData[, col_select, drop = FALSE]
      colnames(matr_cor) <<- CS_sel_real
      write.table(.selected_points_export(NMRData, col_select,
                                          CS_values_real[1, ], file_names),
                  file,sep = ",",col.names = TRUE,row.names = FALSE)
    }
    if (choose_norm == 2) {
      col_select <<- col_select[order(col_select)]
      CS_sel_real <<- CS_values_real[1, col_select]
      colnames(NMR_log) <<- CS_sel_real
      write.table(.spectral_export_table(NMR_log, file_names, CS_sel_real), file,sep = ",",col.names = TRUE,row.names = FALSE)
    }
    if (choose_norm == 3) {
      col_select <<- col_select[order(col_select)]
      CS_sel_real <<- CS_values_real[1, col_select]
      colnames(NMR_i_sqr) <<- CS_sel_real
      write.table(.spectral_export_table(NMR_i_sqr, file_names, CS_sel_real), file,sep = ",",col.names = TRUE,row.names = FALSE)
    }
    if (choose_norm == 4) {
      col_select <<- col_select[order(col_select)]
      CS_sel_real <<- CS_values_real[1, col_select]
      colnames(NMR_sqr) <<- CS_sel_real
      write.table(.spectral_export_table(NMR_sqr, file_names, CS_sel_real), file,sep = ",",col.names = TRUE,row.names = FALSE)
    }
    if (choose_norm == 5) {
      col_select <<- col_select[order(col_select)]
      CS_sel_real <<- CS_values_real[1, col_select]
      colnames(NMR_Pareto) <<- CS_sel_real
      write.table(.spectral_export_table(NMR_Pareto, file_names, CS_sel_real), file,sep = ",",col.names = TRUE,row.names = FALSE)
    }
    if (choose_norm == 6) {
      col_select <<- col_select[order(col_select)]
      CS_sel_real <<- CS_values_real[1, col_select]
      colnames(NMR_ASC) <<- CS_sel_real
      write.table(.spectral_export_table(NMR_ASC, file_names, CS_sel_real), file,sep = ",",col.names = TRUE,row.names = FALSE)
    }
    if (choose_norm == 7) {
      col_select <<- col_select[order(col_select)]
      CS_sel_real <<- CS_values_real[1, col_select]
      colnames(NMR_MC) <<- CS_sel_real
      write.table(.spectral_export_table(NMR_MC, file_names, CS_sel_real), file,sep = ",",col.names = TRUE,row.names = FALSE)
    }
  }
)

# Download bucket selected
output$downloadareas2 <- downloadHandler(
  filename = function() {
    paste("Normalize_Regions", ".csv", sep = "")},
  content = function(file) {

    if (choose_norm %in% 1:7) {

      if (.has_selected_regions()) {
        write.table(.bucket_export(matr_selec, reg_selec, file_names), file,sep = ",",col.names = TRUE,row.names = FALSE)
      }

      else {
        showModal(modalDialog(
          title = "Warning!!!",
          "Please select at least one region to download this area",
          easyClose = TRUE,
          footer = modalButton("Close"),
          size = "l"
        ))
      }
    }
  }
)

# Plot_PDF I-STOCSY
observeEvent(input$norm_print_PDF, {
  ggplot2::ggsave("normal_regions.pdf",path = choose.dir(),width=195, height=105, units="mm", dpi = 300)
})

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.