inst/app/select_signals_server.R

# PAREI NA PARTE DE COLOCAR NOVAS SELECÕES ONDE JA TEM AS SELECIONADAS

 # Variables
  NMRData_Mean <- colMeans(NMRData_plot[,])
  col_select <<- c()
  alr_click <<- 0
  sel_ind <<- 0
  exran <<- c()
  exp_click <<- 0
  col_select_old <- c()
  selection_ylim <- .spectra_projection_ylim(NMRData_Mean)
  cor_cutoff_p <- 0.9
  cor_cutoff_n <- -0.9
  chkzoom <<- 1
  idb <<- 0
  p_value <- 0.05
  s_stoc <<- 0

  # Data.frame
  testy <<- data.frame(Chemical_Shift=CS_values_real[1,],Spectrum=NMRData_plot[1,])
  CS_selection <<- reactiveValues(vranges = c(-13131313,-131313))
  selection_ranges <- reactiveValues(x = c(min(testy$Chemical_Shift),(max(testy$Chemical_Shift))), y = selection_ylim)
  selection_detail_ranges <- reactiveValues(x = c(min(testy$Chemical_Shift),(max(testy$Chemical_Shift))), y = selection_ylim)
  spectrums <- reactiveValues(dat = data.frame(Chemical_Shift=CS_values_real[1,],Spectrum=NMRData_Mean[]))
  spectrums_sel <- reactiveValues(dat = data.frame(Chemical_Shift=CS_values_real[1,],Spectrum= NMRData_Mean[]))

  # Radio button plot type
  observeEvent(input$radio_s, {
    value <<- (input$radio_s)
    drawn_values <- if (as.character(value) == "2") NMRData_plot else NMRData_Mean
    selection_ylim <- .spectra_projection_ylim(drawn_values)
    selection_ranges$y <- selection_ylim
    selection_detail_ranges$y <- selection_ylim
    chkzoom <<- 1
    idb <<- 0
    if (as.character(value) == "1") {
      spectrums$dat$Spectrum <- NMRData_Mean
      spectrums_sel$dat$Spectrum <- NMRData_Mean
    }
  })

  # Both panels are drawn in base graphics from a per-pixel envelope, like the
  # Alignment panels: the average or, in Overlap mode, every sample, both
  # scaled by the intensity buttons (`chkzoom`). Selected points are shaded red
  # and region suggestions outlined in blue.
  .selection_draw <- function(drawn, ranges, output_id) {
    axis <- CS_values_real[1, ]
    envelope <- .alignment_pixel_envelope(drawn, axis, ranges$x,
                                          .plot_output_pixels(output_id))
    .spectra_draw_panel(envelope, ranges$x, ranges$y, colors = "blue",
                        editable = selection_suggested(),
                        selected = .selected_column_runs(axis, CS_selection$vranges))
  }

  .selection_overlap <- function() identical(as.character(input$radio_s), "2")
  .selection_overlap_data <- function()
    if (chkzoom == 1) NMRData_plot else NMRData_plot*chkzoom

  output$plot1 <- renderPlot({
    average <- spectrums$dat$Spectrum
    .selection_draw(if (.selection_overlap()) .selection_overlap_data() else matrix(average, 1L),
                    selection_ranges, "plot1")
  }, res = 96)

  output$plot2 <- renderPlot({
    average <- spectrums_sel$dat$Spectrum
    .selection_draw(if (.selection_overlap()) .selection_overlap_data() else matrix(average, 1L),
                    selection_detail_ranges, "plot2")
  }, res = 96)

  # Automatic regions: the Alignment detector proposes signal regions on the
  # current matrix; the user edits them as text and loads them on request.
  selection_suggested <- reactiveVal(NULL)
  output$select_suggestions_available <- reactive(!is.null(selection_suggested()))
  outputOptions(output, "select_suggestions_available", suspendWhenHidden = FALSE)
  select_suggest_status <- reactiveVal("")
  output$select_suggest_status <- renderText(select_suggest_status())

  .discard_selection_suggestions <- function() {
    selection_suggested(NULL)
    select_suggest_status("")
    updateTextAreaInput(session, "select_suggested_regions", value = "")
  }

  observeEvent(input$select_suggest, {
    tryCatch({
      frequency_mhz <- .parse_optional_frequency_mhz(input$icoshift_frequency_mhz)
      sensitivity <- input$icoshift_detection_sensitivity
      if (is.null(sensitivity)) sensitivity <- 5
      suggestion <- withProgress(message = "Detecting signal regions...", value = 0, {
        detected <- .run_alignment_region_detection(
          NMRData, CS_values_real[1, ], sensitivity = sensitivity,
          frequency_mhz = frequency_mhz, use_j = isTRUE(input$icoshift_use_j))
        incProgress(1)
        detected
      })
      selection_suggested(suggestion$intervals)
      select_suggest_status(sprintf(
        "%d region(s) suggested. Edit the list if needed, then load them.",
        nrow(suggestion$intervals)))
      updateTextAreaInput(session, "select_suggested_regions", value = suggestion$text)
    }, error = function(e) {
      showModal(modalDialog(title = "Region suggestion",
                            paste("Detection error:", conditionMessage(e)),
                            easyClose = TRUE, footer = modalButton("Close")))
    })
  })

  observeEvent(input$select_suggested_regions, {
    if (is.null(selection_suggested())) return()
    tryCatch({
      selection_suggested(.parse_icoshift_intervals(input$select_suggested_regions,
                                                    CS_values_real[1, ]))
      select_suggest_status(sprintf("%d region(s) ready to load.",
                                    nrow(selection_suggested())))
    }, error = function(e) select_suggest_status(conditionMessage(e)))
  }, ignoreInit = TRUE)

  observeEvent(input$select_suggest_discard, .discard_selection_suggestions())

  observeEvent(input$select_suggest_load, {
    regions <- selection_suggested()
    req(regions)
    loaded <- .load_selection_regions(regions)
    .discard_selection_suggestions()
    message <- sprintf("Loaded %d region(s).", loaded$added)
    if (loaded$skipped)
      message <- paste(message, sprintf(
        "%d overlapped regions already loaded (or each other) and were skipped.",
        loaded$skipped))
    showNotification(message, type = "message")
  })

  # Adds ppm regions to the selection exactly as "Save selected region" does
  # for a brushed range, skipping any that touch a region already loaded.
  .load_selection_regions <- function(regions) {
    .clear_stocsy()
    axis <- CS_values_real[1, ]
    added <- skipped <- 0L
    for (i in seq_len(nrow(regions))) {
      limits <- sort(regions[i, ])
      loaded <- if (sel_ind > 0) matrix(as.numeric(reg_selec), ncol = 2L) else
        matrix(numeric(), 0L, 2L)
      if (any(pmin(loaded[, 1L], loaded[, 2L]) <= limits[2L] &
              pmax(loaded[, 1L], loaded[, 2L]) >= limits[1L])) {
        skipped <- skipped + 1L
        next
      }
      region_cols <- .region_columns(axis, limits[1L], limits[2L])
      if (sel_ind == 0) {
        col_select <<- c(region_cols, col_select_old)
        matr_selec <<- .region_bucket(NMRData, region_cols)
        reg_selec <<- matrix(limits, 1L, 2L)
      } else {
        col_select <<- c(col_select, region_cols)
        matr_selec <<- cbind(matr_selec, .region_bucket(NMRData, region_cols))
        reg_selec <<- rbind(reg_selec, limits, deparse.level = 0)
      }
      sel_ind <<- sel_ind + 1
      added <- added + 1L
    }
    if (added) CS_selection$vranges <<- CS_values_real[1, col_select]
    list(added = added, skipped = skipped)
  }

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

    if (!is.null(brush)) {
      selection_detail_ranges$x <- sort(c(brush$xmin, brush$xmax))
      selection_detail_ranges$y <- sort(c(brush$ymin, brush$ymax))
      selected_values <- if (as.character(input$radio_s) == "2")
        testy$Spectrum else NMRData_Mean
      spectrums_sel$dat$Spectrum <- selected_values*chkzoom
      peran_sel <<- (selection_detail_ranges$x[2] - selection_detail_ranges$x[1])*0.2
    }

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

  # Brush select signal
  observeEvent(input$sel_brush,{

  })

  # x2
  observeEvent(input$x2_sel1, {
    chkzoom <<- chkzoom*2
    spectrums$dat$Spectrum <- spectrums$dat$Spectrum*2
    })

  # x8
  observeEvent(input$x8_sel1, {
    chkzoom <<- chkzoom*8
    spectrums$dat$Spectrum <- spectrums$dat$Spectrum*8
  })

  # /2
  observeEvent(input$q2_sel1, {
    chkzoom <<- chkzoom/2
    spectrums$dat$Spectrum <- spectrums$dat$Spectrum/2
  })

  # /8
  observeEvent(input$q8_sel1, {
    chkzoom <<- chkzoom/8
    spectrums$dat$Spectrum <- spectrums$dat$Spectrum/8
  })
  
  # Download point selected to save coluns select
  output$downloadpoints_save <- downloadHandler(
    filename = function() {
      paste("Selected_Regions_saved", ".csv", sep = "")
    },
    content = function(file) {
      write.table(reg_selec,file, sep = ",",col.names = FALSE,row.names = FALSE)
    }
  )
  
  

  # Download point selected
  output$downloadpoints <- downloadHandler(
    filename = function() {
        paste("Selected_Regions", ".csv", sep = "")
      },
      content = function(file) {
        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
        export <- .selected_points_export(NMRData, col_select,
                                          CS_values_real[1, ], file_names)
        write.table(export, file, sep = ",", col.names = TRUE, row.names = FALSE)
      }
  )


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

          if (.has_selected_regions()) {
          export <- .bucket_export(matr_selec, reg_selec, file_names)
          write.table(export, 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"
            ))
          }
        }
  )

  observeEvent(input$rsh_sel1, {
    xsup <- max(CS_values_real[1,])
    xinf <- min(CS_values_real[1,])
    selection_ranges$x <- c(xinf,xsup)
    idb <<- 0
    })


  # Show all
  observeEvent(input$all_h, {
    drawn_values <- if (as.character(input$radio_s) == "2") NMRData_plot else NMRData_Mean
    selection_ranges$y <- .spectra_projection_ylim(drawn_values)
    spectrums$dat$Spectrum <- spectrums$dat$Spectrum/chkzoom
    chkzoom <<- 1
    idb <<- 0
  })

  # Button sel
  observeEvent(input$exp_sel1, {
    exp_click <<- exp_click + 1
    exran[exp_click] <<- abs(selection_ranges$x[2] - selection_ranges$x[1])*0.2
    selection_ranges$x <<- c((selection_ranges$x[1] + exran[exp_click] ), (selection_ranges$x[2] - exran[exp_click]))
  })

  # Paint selected region (red)
  observeEvent(input$cont_sel1, {

    if ((selection_ranges$x[1] <= min(testy$Chemical_Shift)) || (selection_ranges$x[2] >= max(testy$Chemical_Shift))) {}

    else {

      if ((exp_click - 1) <= 0) {
        selection_ranges$x <- c(min(testy$Chemical_Shift),(max(testy$Chemical_Shift)))
      }

      else {
      exp_click <<- exp_click - 1
      selection_ranges$x <<- c((selection_ranges$x[1] - exran[exp_click]), (selection_ranges$x[2] + exran[exp_click]))
      }
    }

  })


  # Move left
  observeEvent(input$s_left_sel1, {

    if (!(selection_ranges$x[1] <= min(testy$Chemical_Shift))) {
      selection_ranges$x[1] <<- (selection_ranges$x[1] - exran[exp_click] )
      selection_ranges$x[2] <<- (selection_ranges$x[2] - exran[exp_click] )
    }
  })


  # Move right
  observeEvent(input$s_right_sel1, {

    if (!(selection_ranges$x[2] >= max(testy$Chemical_Shift))) {
      selection_ranges$x[1] <<- (selection_ranges$x[1] + exran[exp_click] )
      selection_ranges$x[2] <<- (selection_ranges$x[2] + exran[exp_click] )
    }
  })


  # Move full left
  observeEvent(input$s_left_f_sel1, {

    if (exp_click > 0 && selection_ranges$x[1] > min(testy$Chemical_Shift)) {
      das <<- abs(selection_ranges$x[1] - selection_ranges$x[2])
      selection_ranges$x[1] <- min(testy$Chemical_Shift)
      selection_ranges$x[2] <- (selection_ranges$x[1] + das)
    }

    else {

    }
  })


  # Move full right
  observeEvent(input$s_right_f_sel1, {

    if (exp_click > 0 && selection_ranges$x[2] < max(testy$Chemical_Shift)) {
      das <<- abs(selection_ranges$x[1] - selection_ranges$x[2])
      selection_ranges$x[2] = max(testy$Chemical_Shift)
      selection_ranges$x[1] <- (selection_ranges$x[2] - das)
    }

    else {

    }
  })

  # Start STOCSY-I
  observeEvent(input$s_stocsy, {


      if (!(sel_ind == 0)) {
        col_select <<- col_select[order(col_select)]
        CS_sel_real <<- CS_selection$vranges[order(CS_selection$vranges,decreasing = TRUE)]
        matr_cor <<- matrix(data = NMRData[,col_select],dim(NMRData)[1], length(col_select))
        .start_stocsy(matr_cor)
        rr <<- vector(mode="character")

        norm_test(p_value,matr_cor)
        r_critical(p_value)

        updateSliderInput(session, "cutoff_stocsy_i", min = -1,
                          max = 1, value = c(-0.9,0.9) , step= 0.01)

        rr <<- .stocsy_classes(rr, ncol(NMRData), col_select, cor_pearson,
                              cor_cutoff_p, cor_cutoff_n)
        facts$fac_stocsy_i <<- rr[]
        facts_is$fac_stocsy_is <<- rr[]
        facts_rt$fac_stocsy_rt <<- rr[]
        .stocsy_show_all_views()
        updateTabsetPanel(session, "main_bar", "STOCSY-I")
      }

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

    stop_menssager <- 1
  })
  
  # plot regions selected
  observeEvent(input$region_selected,{
    
    
  })
  

  # Select regions
  observeEvent(input$sel_cor, {
      .clear_stocsy()
      brush <- input$sel_brush
      if (!is.null(brush)) {

        if (sel_ind == 0) {
          sel_ind <<- 1
          region_cols <- .region_columns(CS_values_real[1,], brush$xmin, brush$xmax)
          col_select <<- c(region_cols, col_select_old)
          CS_selection$vranges <<- CS_values_real[1,col_select]
          matr_selec <<- .region_bucket(NMRData, region_cols)
          reg_selec <<- matrix(data = c(brush$xmin,brush$xmax), 1, 2)
        }

        else {
          sel_ind <<- sel_ind + 1
          s_ind <<- 0
          
          if (sel_ind == 2) {

            if (((brush$xmin >= reg_selec[1,1]) && (brush$xmin <= reg_selec[1,2])) || ((brush$xmax >= reg_selec[1,1]) && (brush$xmax <= reg_selec[1,2])) || ((reg_selec[1,1] >= brush$xmin) && (reg_selec[1,1] <= brush$xmax)) || ((reg_selec[1,2] >= brush$xmin) && (reg_selec[1,2] <= brush$xmax))  ) {
            s_ind <<- 1
            sel_ind <<- sel_ind - 1
            }
          }

          else if (sel_ind > 2) {
            ind_gol <- 0
            
            for (i in 1:dim(reg_selec)[1]) {
              if (((brush$xmin >= reg_selec[i,1]) && (brush$xmin <= reg_selec[i,2])) || ((brush$xmax >= reg_selec[i,1]) && (brush$xmax <= reg_selec[i,2])) || ((reg_selec[i,1] >= brush$xmin) && (reg_selec[i,1] <= brush$xmax)) || ((reg_selec[i,2] >= brush$xmin) && (reg_selec[i,2] <= brush$xmax))  ) {
                ind_gol <- 1
              }
            }

            if (ind_gol == 1) {
              s_ind <<- 1
              sel_ind <<- sel_ind - 1
            }
          }
          
          if (s_ind == 0) {
            col_select_2 <<- .region_columns(CS_values_real[1,], brush$xmin, brush$xmax)
            col_select <<- c(col_select, col_select_2)
            reg_selec <<- rbind(reg_selec, c(brush$xmin,brush$xmax))
            CS_selection$vranges <<- CS_values_real[1,col_select]
            matr_selec <<- cbind(matr_selec, .region_bucket(NMRData, col_select_2))
          }

          else {
            showModal(modalDialog(
              title = "Warning!!!",
              "Part of the region you want to load was already loaded. Please, check the loaded regions and select a non superimposed one!!!",
              easyClose = TRUE,
              footer = modalButton("Close"),
              size = "l"
            ))
          }

        }
      }

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

  # click to delete regions selected
  observeEvent(input$sel_click, {
    if (alr_click == 1 && .has_selected_regions()) {
      exc_val <- input$sel_click$x
      regions <- matrix(as.numeric(reg_selec), ncol = 2L)
      hits <- which(exc_val >= regions[, 1] & exc_val <= regions[, 2])

      if (length(hits)) {
        .clear_stocsy()
        row_reg <<- hits[1]
        kept <- .remove_selected_region(reg_selec, matr_selec, col_select,
                                        CS_values_real[1, ], row_reg)
        sel_ind <<- nrow(kept$regions)

        if (sel_ind == 0) {
          reg_selec <<- matrix(0, 1, 2)
          col_select <<- c()
          CS_selection$vranges <<- c(-13131313,-131313)
        }

        else {
          reg_selec <<- kept$regions
          matr_selec <<- kept$buckets
          col_select <<- kept$selected
          CS_selection$vranges <<- CS_values_real[1,col_select]
        }
      }
      alr_click <<- 0
    }
  })

  # Delete region
  observeEvent(input$exc_reg, {
    if (!(sel_ind == 0)) {
      alr_click <<- 1
    }

    else {
      showModal(modalDialog(
        title = "Warning!!!",
        "No region was loaded, so exclusion it is not possible!",
        easyClose = TRUE,
        footer = modalButton("Close"),
        size = "l"
      ))
    }
  })

  observeEvent(input$plot_dblclick, {
    selection_detail_ranges$x <- c(min(testy$Chemical_Shift),(max(testy$Chemical_Shift)))
    selection_ranges$x <- c(min(testy$Chemical_Shift),(max(testy$Chemical_Shift)))
    drawn_values <- if (as.character(input$radio_s) == "2") NMRData_plot else NMRData_Mean
    selection_ylim <- .spectra_projection_ylim(drawn_values)
    selection_ranges$y <- selection_ylim
    selection_detail_ranges$y <- selection_ylim
    if (as.character(input$radio_s) == "1") {
      spectrums$dat$Spectrum <- NMRData_Mean
      spectrums_sel$dat$Spectrum <- NMRData_Mean
    }
    chkzoom <<- 1
    idb <<- 0
    peran <<- 0
    })

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.