R/alignment_regions.R

Defines functions .find_local_minima .peak_widths .peak_prominences .validate_peak_indices .find_local_peaks .alignment_peak_candidates .filter_peak_table .build_alignment_regions .apply_alignment_masks .normalize_alignment_masks .expand_region_bounds .group_peak_candidates .summarize_peak_groups .component_ids .validate_optional_frequency .distance_filter .ppm_window_points .validate_nonnegative_scalar .noise_from_differences .peak_table .signal_base_bounds .peak_noise .index_to_ppm .validate_ppm_axis .representative_spectrum .normalize_spectra .validate_spectral_matrix .validate_peak_signal

# Internal peak primitives used by the automatic alignment-region detector.
# Indices use R's one-based convention; interpolated positions use the same
# continuous coordinate system. The algorithms follow scipy.signal's peak
# definition, prominence search and width interpolation without requiring
# Python at run time.

.validate_peak_signal <- function(x) {
  if (!is.numeric(x) || !is.null(dim(x))) {
    stop("x deve ser um vetor numerico.", call. = FALSE)
  }
  as.numeric(x)
}

.validate_spectral_matrix <- function(spectra) {
  if (!is.matrix(spectra) || !is.numeric(spectra) || nrow(spectra) < 1L ||
      ncol(spectra) < 3L || any(is.infinite(spectra))) {
    stop("spectra deve ser uma matriz numerica sem valores infinitos.",
         call. = FALSE)
  }
  spectra
}

.normalize_spectra <- function(spectra) {
  spectra <- .validate_spectral_matrix(spectra)
  factors <- rowMeans(abs(spectra), na.rm = TRUE)
  if (any(!is.finite(factors) | factors <= 0)) {
    stop("cada espectro deve conter intensidade finita nao nula.",
         call. = FALSE)
  }
  normalized <- spectra / factors
  attr(normalized, "scale_factors") <- factors
  normalized
}

.representative_spectrum <- function(spectra,
                                     method = c("median", "trimmed_mean"),
                                     trim = 0.1) {
  method <- match.arg(method)
  if (length(trim) != 1L || is.na(trim) || !is.finite(trim) ||
      trim < 0 || trim >= 0.5) {
    stop("trim deve estar no intervalo [0, 0.5).", call. = FALSE)
  }
  normalized <- .normalize_spectra(spectra)
  aggregate <- if (method == "median") {
    function(z) stats::median(z, na.rm = TRUE)
  } else {
    function(z) mean(z, trim = trim, na.rm = TRUE)
  }
  profile <- apply(normalized, 2L, aggregate)
  profile[!is.finite(profile)] <- NA_real_
  as.numeric(profile)
}

.validate_ppm_axis <- function(ppm, n, uniform_tolerance = 0.5) {
  if (!is.numeric(ppm) || !is.null(dim(ppm)) || length(ppm) != n ||
      anyNA(ppm) || any(!is.finite(ppm))) {
    stop("ppm deve ser um vetor numerico finito do comprimento do perfil.",
         call. = FALSE)
  }
  if (length(uniform_tolerance) != 1L || is.na(uniform_tolerance) ||
      !is.finite(uniform_tolerance) || uniform_tolerance < 0) {
    stop("uniform_tolerance deve ser um numero finito nao negativo.",
         call. = FALSE)
  }
  direction <- diff(ppm)
  if (!all(direction > 0) && !all(direction < 0)) {
    stop("ppm deve ser estritamente monotono.", call. = FALSE)
  }
  steps <- abs(direction)
  typical_step <- stats::median(steps)
  # Eixos arredondados podem terminar num ponto ajustado para o limite (o
  # NMRData de exemplo termina em ...0,0004, 0,0001, 0). Por isso o primeiro e
  # o ultimo passo podem ser menores; maiores continuam sujeitos a tolerancia.
  interior <- if (length(steps) > 2L) steps[-c(1L, length(steps))] else steps
  ends <- steps[c(1L, length(steps))]
  relative_deviation <- max(abs(interior - typical_step)) / typical_step
  if (!is.finite(relative_deviation) || relative_deviation > uniform_tolerance ||
      any(ends > typical_step * (1 + uniform_tolerance))) {
    stop("ppm deve ser uniforme ou quase uniforme.", call. = FALSE)
  }
  ppm <- as.numeric(ppm)
  attr(ppm, "step_ppm") <- typical_step
  attr(ppm, "step_relative_deviation") <- relative_deviation
  ppm
}

.index_to_ppm <- function(index, ppm) {
  stats::approx(seq_along(ppm), ppm, xout = index, rule = 2)$y
}

.peak_noise <- function(x, left_base, right_base) {
  vapply(seq_along(left_base), function(k) {
    segment <- x[left_base[k]:right_base[k]]
    differences <- diff(segment)
    differences <- differences[is.finite(differences)]
    if (length(differences) < 2L) return(NA_real_)
    stats::mad(differences, center = stats::median(differences),
               constant = 1.4826) / sqrt(2)
  }, numeric(1L))
}

.signal_base_bounds <- function(x, peaks, height_fraction = 0.01,
                                noise_multiplier = 3,
                                sustain_points = 3L,
                                search_window_points = NULL) {
  x <- .validate_peak_signal(x)
  peaks <- .validate_peak_indices(peaks, length(x))
  height_fraction <- .validate_nonnegative_scalar(
    height_fraction, "height_fraction")
  noise_multiplier <- .validate_nonnegative_scalar(
    noise_multiplier, "noise_multiplier")
  if (height_fraction > 1) {
    stop("height_fraction deve estar no intervalo [0, 1].", call. = FALSE)
  }
  if (length(sustain_points) != 1L || is.na(sustain_points) ||
      !is.finite(sustain_points) || sustain_points != floor(sustain_points) ||
      sustain_points < 1L) {
    stop("sustain_points deve ser um inteiro positivo.", call. = FALSE)
  }
  sustain_points <- as.integer(sustain_points)
  if (!length(peaks)) {
    return(data.frame(signal_left_base = integer(),
                      signal_right_base = integer(),
                      signal_prominence = numeric(),
                      signal_base_height = numeric()))
  }

  # A mediana das primeiras diferencas remove uma linha de base linear sem
  # deixar que poucos sinais intensos determinem a inclinacao. A prominencia
  # local continua sendo calculada separadamente e permanece responsavel por
  # SNR, largura e agrupamento; esta serie serve apenas para procurar onde a
  # cauda fisica do sinal retorna a base.
  finite_differences <- diff(x)
  finite_differences <- finite_differences[is.finite(finite_differences)]
  baseline_step <- if (length(finite_differences)) {
    stats::median(finite_differences)
  } else {
    0
  }
  detrended <- x - baseline_step * (seq_along(x) - 1L)
  physical <- .peak_prominences(detrended, peaks,
                                wlen = search_window_points)
  noise <- .noise_from_differences(detrended)
  if (!is.finite(noise)) noise <- 0

  first_sustained <- function(indices, threshold, fallback) {
    below <- is.finite(detrended[indices]) & detrended[indices] <= threshold
    if (length(below) >= sustain_points) {
      run_end <- which(stats::filter(as.integer(below),
                                     rep(1, sustain_points),
                                     sides = 1) == sustain_points)[1L]
      if (!is.na(run_end)) {
        return(indices[run_end - sustain_points + 1L])
      }
    }
    fallback
  }

  left <- right <- peaks
  base_height <- rep(NA_real_, length(peaks))
  for (k in seq_along(peaks)) {
    peak <- peaks[k]
    left_floor <- detrended[physical$left_base[k]]
    right_floor <- detrended[physical$right_base[k]]
    prominence <- physical$prominence[k]
    tolerance <- max(height_fraction * prominence,
                     noise_multiplier * noise, na.rm = TRUE)
    left_threshold <- left_floor + tolerance
    right_threshold <- right_floor + tolerance
    left[k] <- first_sustained(
      seq.int(peak, physical$left_base[k]), left_threshold,
      physical$left_base[k])
    right[k] <- first_sustained(
      seq.int(peak, physical$right_base[k]), right_threshold,
      physical$right_base[k])
    base_height[k] <- max(left_threshold, right_threshold)
  }
  data.frame(signal_left_base = as.integer(left),
             signal_right_base = as.integer(right),
             signal_prominence = physical$prominence,
             signal_base_height = base_height)
}

.peak_table <- function(x, ppm, wlen = NULL, rel_height = 0.5,
                        uniform_tolerance = 0.5,
                        base_height_fraction = 0.01,
                        base_noise_multiplier = 3,
                        base_sustain_points = 3L,
                        base_search_ppm = 0.5) {
  x <- .validate_peak_signal(x)
  ppm <- .validate_ppm_axis(ppm, length(x), uniform_tolerance)
  found <- .find_local_peaks(x)
  prominence <- .peak_prominences(x, found$peak, wlen = wlen)
  widths <- .peak_widths(x, found$peak, rel_height = rel_height,
                         prominence_data = prominence)
  signal_bases <- .signal_base_bounds(
    x, found$peak, height_fraction = base_height_fraction,
    noise_multiplier = base_noise_multiplier,
    sustain_points = base_sustain_points,
    search_window_points = .ppm_window_points(
      base_search_ppm, attr(ppm, "step_ppm")))
  if (!is.null(wlen) && nrow(found)) {
    window <- as.integer(ceiling(wlen))
    if (window %% 2L == 0L) window <- window + 1L
    half_window <- window %/% 2L
    left_limit <- pmax(1L, found$peak - half_window)
    right_limit <- pmin(length(x), found$peak + half_window)
    left_truncated <- prominence$left_base == left_limit & left_limit > 1L
    right_truncated <- prominence$right_base == right_limit &
      right_limit < length(x)
    signal_bases$signal_left_base[!left_truncated] <-
      prominence$left_base[!left_truncated]
    signal_bases$signal_right_base[!right_truncated] <-
      prominence$right_base[!right_truncated]
  }
  if (!nrow(found)) {
    return(data.frame(index = integer(), ppm = numeric(),
                      intensity = numeric(), prominence = numeric(),
                      left_base = integer(), right_base = integer(),
                      left_base_ppm = numeric(), right_base_ppm = numeric(),
                      signal_left_base = integer(),
                      signal_right_base = integer(),
                      signal_left_base_ppm = numeric(),
                      signal_right_base_ppm = numeric(),
                      signal_prominence = numeric(),
                      signal_base_height = numeric(),
                      width_points = numeric(), width_ppm = numeric(),
                      width_height = numeric(), left_ip = numeric(),
                      right_ip = numeric(), noise = numeric()))
  }
  data.frame(
    index = found$peak,
    ppm = ppm[found$peak],
    intensity = x[found$peak],
    prominence = prominence$prominence,
    left_base = prominence$left_base,
    right_base = prominence$right_base,
    left_base_ppm = ppm[prominence$left_base],
    right_base_ppm = ppm[prominence$right_base],
    signal_left_base = signal_bases$signal_left_base,
    signal_right_base = signal_bases$signal_right_base,
    signal_left_base_ppm = ppm[signal_bases$signal_left_base],
    signal_right_base_ppm = ppm[signal_bases$signal_right_base],
    signal_prominence = signal_bases$signal_prominence,
    signal_base_height = signal_bases$signal_base_height,
    width_points = widths$width,
    width_ppm = abs(.index_to_ppm(widths$right_ip, ppm) -
                    .index_to_ppm(widths$left_ip, ppm)),
    width_height = widths$width_height,
    left_ip = widths$left_ip,
    right_ip = widths$right_ip,
    noise = .peak_noise(x, prominence$left_base, prominence$right_base)
  )
}

.noise_from_differences <- function(x) {
  differences <- diff(x)
  differences <- differences[is.finite(differences)]
  if (length(differences) < 2L) return(NA_real_)
  noise <- stats::mad(differences, center = stats::median(differences),
                      constant = 1.4826) / sqrt(2)
  if (!is.finite(noise) || noise < 0) NA_real_ else noise
}

.validate_nonnegative_scalar <- function(x, name, positive = FALSE) {
  invalid <- length(x) != 1L || is.na(x) || !is.finite(x) ||
    if (positive) x <= 0 else x < 0
  if (invalid) {
    qualifier <- if (positive) "positivo" else "nao negativo"
    stop(sprintf("%s deve ser um numero finito %s.", name, qualifier),
         call. = FALSE)
  }
  as.numeric(x)
}

.ppm_window_points <- function(value_ppm, step_ppm) {
  points <- max(3L, as.integer(ceiling(value_ppm / step_ppm)))
  if (points %% 2L == 0L) points <- points + 1L
  points
}

.distance_filter <- function(peaks, min_distance_ppm) {
  if (nrow(peaks) < 2L || min_distance_ppm <= 0) return(peaks)
  # As in scipy.signal.find_peaks, distance conflicts retain the taller
  # property value. SNR has already acted as a threshold and is not reused as
  # priority because local slope can raise the robust noise around strong peaks.
  order_by_score <- order(peaks$prominence, decreasing = TRUE, na.last = TRUE)
  selected <- logical(nrow(peaks))
  for (candidate in order_by_score) {
    if (!any(selected) ||
        all(abs(peaks$ppm[candidate] - peaks$ppm[selected]) >=
            min_distance_ppm)) {
      selected[candidate] <- TRUE
    }
  }
  peaks[selected, , drop = FALSE]
}

.validate_optional_frequency <- function(frequency_mhz) {
  if (is.null(frequency_mhz)) return(NULL)
  .validate_nonnegative_scalar(frequency_mhz, "frequency_mhz",
                               positive = TRUE)
}

.component_ids <- function(n, edges) {
  if (!n) return(integer())
  parent <- seq_len(n)
  root <- function(i) {
    while (parent[i] != i) i <- parent[i]
    i
  }
  if (length(edges)) {
    for (edge in edges) {
      left <- root(edge[1L])
      right <- root(edge[2L])
      if (left != right) parent[right] <- left
    }
  }
  roots <- vapply(seq_len(n), root, integer(1L))
  match(roots, unique(roots))
}

.summarize_peak_groups <- function(peaks, group_id) {
  empty <- data.frame(
    group_id = integer(), polarity = character(), components = integer(),
    first_peak = integer(), last_peak = integer(), ppm_min = numeric(),
    ppm_max = numeric(), stringsAsFactors = FALSE)
  if (!nrow(peaks)) return(empty)
  rows <- split(seq_len(nrow(peaks)), group_id)
  result <- lapply(seq_along(rows), function(k) {
    selected <- rows[[k]]
    data.frame(
      group_id = k,
      polarity = paste(unique(peaks$polarity[selected]), collapse = ","),
      components = length(selected), first_peak = min(peaks$index[selected]),
      last_peak = max(peaks$index[selected]),
      ppm_min = min(peaks$ppm[selected]), ppm_max = max(peaks$ppm[selected]),
      stringsAsFactors = FALSE)
  })
  do.call(rbind, result)
}

# Group filtered peaks without making a chemical assignment. Overlapping peak
# bases provide the conservative grouping available without J. A repeated,
# digitally resolved spacing may join those base groups only when observation
# frequency is known and at least two consecutive spacings support the run.
.group_peak_candidates <- function(peaks, ppm, frequency_mhz = NULL,
                                   use_j = TRUE,
                                   spacing_tolerance_points = 2,
                                   min_repeated_spacings = 2L,
                                   uniform_tolerance = 0.5) {
  required <- c("index", "ppm", "left_base", "right_base")
  if (!is.data.frame(peaks) || !all(required %in% names(peaks))) {
    stop("peaks deve ser uma tabela auditavel de picos.", call. = FALSE)
  }
  ppm <- .validate_ppm_axis(ppm, length(ppm), uniform_tolerance)
  frequency_mhz <- .validate_optional_frequency(frequency_mhz)
  spacing_tolerance_points <- .validate_nonnegative_scalar(
    spacing_tolerance_points, "spacing_tolerance_points", positive = TRUE)
  min_repeated_spacings <- .validate_nonnegative_scalar(
    min_repeated_spacings, "min_repeated_spacings", positive = TRUE)
  if (min_repeated_spacings != floor(min_repeated_spacings)) {
    stop("min_repeated_spacings deve ser inteiro.", call. = FALSE)
  }
  min_repeated_spacings <- as.integer(min_repeated_spacings)
  if (min_repeated_spacings < 2L) {
    stop("min_repeated_spacings deve ser pelo menos 2.", call. = FALSE)
  }
  if (length(use_j) != 1L || is.na(use_j) || !is.logical(use_j)) {
    stop("use_j deve ser TRUE ou FALSE.", call. = FALSE)
  }
  if (nrow(peaks) && (anyNA(peaks[, required]) ||
      any(!is.finite(as.matrix(peaks[, required]))) ||
      any(peaks$index != floor(peaks$index)) ||
      any(peaks$index < 1L | peaks$index > length(ppm)) ||
      any(peaks$left_base != floor(peaks$left_base)) ||
      any(peaks$right_base != floor(peaks$right_base)) ||
      any(peaks$left_base < 1L | peaks$left_base > length(ppm)) ||
      any(peaks$right_base < 1L | peaks$right_base > length(ppm)) ||
      any(peaks$ppm != ppm[peaks$index]))) {
    stop("peaks contem indices, ppm ou bases invalidos.", call. = FALSE)
  }
  if (!"polarity" %in% names(peaks)) peaks$polarity <- "positive"
  if (anyNA(peaks$polarity) || any(!nzchar(as.character(peaks$polarity)))) {
    stop("peaks contem polaridade invalida.", call. = FALSE)
  }
  peaks <- peaks[order(peaks$index, peaks$polarity), , drop = FALSE]
  rownames(peaks) <- NULL
  step_ppm <- attr(ppm, "step_ppm")
  tolerance_ppm <- spacing_tolerance_points * step_ppm
  digital_resolution_hz <- if (is.null(frequency_mhz)) NA_real_ else
    step_ppm * frequency_mhz

  empty_spacings <- data.frame(
    spacing_id = integer(), left_peak = integer(), right_peak = integer(),
    left_index = integer(), right_index = integer(), polarity = character(),
    delta_ppm = numeric(), J_Hz = numeric(), stringsAsFactors = FALSE)
  empty_multiplets <- data.frame(
    candidate_id = integer(), polarity = character(), components = integer(),
    first_peak = integer(), last_peak = integer(), spacings = integer(),
    first_index = integer(), last_index = integer(), ppm_min = numeric(),
    ppm_max = numeric(),
    delta_ppm = numeric(), J_Hz = numeric(), dispersion_ppm = numeric(),
    dispersion_Hz = numeric(), tolerance_ppm = numeric(),
    confidence = numeric(), confidence_label = character(),
    j_supported = logical(), stringsAsFactors = FALSE)

  if (!nrow(peaks)) {
    peaks$group_without_j <- integer()
    peaks$group_with_j <- integer()
    return(list(
      peaks = peaks, spacings = empty_spacings,
      multiplet_candidates = empty_multiplets,
      groups_without_j = .summarize_peak_groups(peaks, integer()),
      groups_with_j = .summarize_peak_groups(peaks, integer()),
      parameters = list(frequency_mhz = frequency_mhz,
        digital_resolution_ppm = step_ppm,
        digital_resolution_hz = digital_resolution_hz,
        spacing_tolerance_points = spacing_tolerance_points,
        spacing_tolerance_ppm = tolerance_ppm,
        min_repeated_spacings = min_repeated_spacings, use_j = use_j)))
  }

  base_edges <- list()
  spacing_rows <- list()
  polarity_rows <- split(seq_len(nrow(peaks)), peaks$polarity)
  for (selected in polarity_rows) {
    if (length(selected) < 2L) next
    for (k in seq_len(length(selected) - 1L)) {
      left <- selected[k]
      right <- selected[k + 1L]
      left_interval <- sort(c(peaks$left_base[left], peaks$right_base[left]))
      right_interval <- sort(c(peaks$left_base[right], peaks$right_base[right]))
      if (max(left_interval[1L], right_interval[1L]) <=
          min(left_interval[2L], right_interval[2L])) {
        base_edges[[length(base_edges) + 1L]] <- c(left, right)
      }
      spacing_rows[[length(spacing_rows) + 1L]] <- data.frame(
        left_peak = left, right_peak = right,
        left_index = peaks$index[left], right_index = peaks$index[right],
        polarity = peaks$polarity[left],
        delta_ppm = abs(peaks$ppm[right] - peaks$ppm[left]),
        stringsAsFactors = FALSE)
    }
  }
  spacings <- if (length(spacing_rows)) do.call(rbind, spacing_rows) else
    empty_spacings[, -1L, drop = FALSE]
  if (nrow(spacings)) {
    spacings$spacing_id <- seq_len(nrow(spacings))
    spacings$J_Hz <- if (is.null(frequency_mhz)) NA_real_ else
      spacings$delta_ppm * frequency_mhz
    spacings <- spacings[, names(empty_spacings), drop = FALSE]
  } else {
    spacings <- empty_spacings
  }

  candidates <- list()
  j_edges <- list()
  if (nrow(spacings) >= min_repeated_spacings) {
    spacing_sets <- split(seq_len(nrow(spacings)), spacings$polarity)
    for (selected in spacing_sets) {
      start <- 1L
      while (start <= length(selected)) {
        finish <- start
        while (finish < length(selected) &&
               spacings$left_peak[selected[finish + 1L]] ==
                 spacings$right_peak[selected[finish]]) {
          proposed <- selected[start:(finish + 1L)]
          center <- stats::median(spacings$delta_ppm[proposed])
          if (max(abs(spacings$delta_ppm[proposed] - center)) >
              tolerance_ppm) break
          finish <- finish + 1L
        }
        run <- selected[start:finish]
        if (length(run) >= min_repeated_spacings) {
          values <- spacings$delta_ppm[run]
          center <- stats::median(values)
          dispersion <- max(abs(values - center))
          confidence <- max(0, 1 - dispersion / tolerance_ppm) *
            min(1, length(run) / 3)
          label <- if (confidence >= 0.8) "high" else if (confidence >= 0.5)
            "moderate" else "low"
          resolved <- center > tolerance_ppm
          supported <- !is.null(frequency_mhz) && resolved &&
            confidence >= 0.5
          first <- spacings$left_peak[run[1L]]
          last <- spacings$right_peak[run[length(run)]]
          members <- c(spacings$left_peak[run], last)
          candidates[[length(candidates) + 1L]] <- data.frame(
            candidate_id = length(candidates) + 1L,
            polarity = spacings$polarity[run[1L]],
            components = length(run) + 1L,
            first_peak = first, last_peak = last, spacings = length(run),
            first_index = peaks$index[first], last_index = peaks$index[last],
            ppm_min = min(peaks$ppm[members]),
            ppm_max = max(peaks$ppm[members]),
            delta_ppm = center,
            J_Hz = if (is.null(frequency_mhz)) NA_real_ else
              center * frequency_mhz,
            dispersion_ppm = dispersion,
            dispersion_Hz = if (is.null(frequency_mhz)) NA_real_ else
              dispersion * frequency_mhz,
            tolerance_ppm = tolerance_ppm, confidence = confidence,
            confidence_label = label, j_supported = supported,
            stringsAsFactors = FALSE)
          if (use_j && supported) {
            for (k in seq_len(length(members) - 1L)) {
              j_edges[[length(j_edges) + 1L]] <- members[c(k, k + 1L)]
            }
          }
          start <- finish + 1L
        } else {
          start <- start + 1L
        }
      }
    }
  }
  multiplets <- if (length(candidates)) do.call(rbind, candidates) else
    empty_multiplets
  without_j <- .component_ids(nrow(peaks), base_edges)
  with_j <- .component_ids(nrow(peaks), c(base_edges, j_edges))
  peaks$group_without_j <- without_j
  peaks$group_with_j <- with_j
  list(
    peaks = peaks, spacings = spacings, multiplet_candidates = multiplets,
    groups_without_j = .summarize_peak_groups(peaks, without_j),
    groups_with_j = .summarize_peak_groups(peaks, with_j),
    parameters = list(frequency_mhz = frequency_mhz,
      digital_resolution_ppm = step_ppm,
      digital_resolution_hz = digital_resolution_hz,
      spacing_tolerance_points = spacing_tolerance_points,
      spacing_tolerance_ppm = tolerance_ppm,
      min_repeated_spacings = min_repeated_spacings, use_j = use_j))
}

.expand_region_bounds <- function(left, right, margin, minimum_points, n) {
  start <- max(1L, as.integer(left) - margin)
  end <- min(n, as.integer(right) + margin)
  missing <- minimum_points - (end - start + 1L)
  if (missing > 0L) {
    add_left <- min(start - 1L, missing %/% 2L)
    start <- start - add_left
    missing <- minimum_points - (end - start + 1L)
    add_right <- min(n - end, missing)
    end <- end + add_right
    missing <- minimum_points - (end - start + 1L)
    if (missing > 0L) start <- max(1L, start - missing)
  }
  c(start, end)
}

.normalize_alignment_masks <- function(masks, ppm) {
  empty <- data.frame(
    mask_id = integer(), mask_type = character(), ppm_min = numeric(),
    ppm_max = numeric(), start_index = integer(), end_index = integer(),
    stringsAsFactors = FALSE)
  if (is.null(masks)) return(empty)
  if (is.numeric(masks) && is.null(dim(masks))) {
    if (!length(masks) || length(masks) %% 2L) {
      stop("masks deve conter pares de limites em ppm.", call. = FALSE)
    }
    masks <- matrix(masks, ncol = 2L, byrow = TRUE)
  }
  if (!is.matrix(masks) && !is.data.frame(masks)) {
    stop("masks deve ser vetor, matriz ou data.frame de intervalos.",
         call. = FALSE)
  }
  if (ncol(masks) < 2L || !nrow(masks)) {
    if (!nrow(masks)) return(empty)
    stop("masks deve ter duas colunas de limites em ppm.", call. = FALSE)
  }
  mask_names <- names(masks)
  endpoint_columns <- if (!is.null(mask_names) &&
                          all(c("start_ppm", "end_ppm") %in% mask_names)) {
    c("start_ppm", "end_ppm")
  } else {
    seq_len(2L)
  }
  endpoints <- suppressWarnings(matrix(
    as.numeric(as.matrix(masks[, endpoint_columns, drop = FALSE])), ncol = 2L))
  if (anyNA(endpoints) || any(!is.finite(endpoints)) ||
      any(endpoints[, 1L] == endpoints[, 2L])) {
    stop("cada mascara deve ter dois limites ppm finitos e diferentes.",
         call. = FALSE)
  }
  ppm_range <- range(ppm)
  if (any(endpoints < ppm_range[1L] | endpoints > ppm_range[2L])) {
    stop("os limites de masks devem estar dentro do eixo ppm.", call. = FALSE)
  }
  type_column <- if (!is.null(mask_names)) {
    intersect(c("mask_type", "type", "label"), mask_names)[1L]
  } else {
    NA_character_
  }
  types <- if (!is.na(type_column)) as.character(masks[[type_column]]) else
    rep("excluded", nrow(endpoints))
  if (anyNA(types) || any(!nzchar(trimws(types)))) {
    stop("o rotulo de cada mascara deve ser texto nao vazio.", call. = FALSE)
  }
  types <- trimws(types)
  nearest_index <- function(value) which.min(abs(ppm - value))
  index_pairs <- t(vapply(seq_len(nrow(endpoints)), function(k) {
    sort(c(nearest_index(endpoints[k, 1L]),
           nearest_index(endpoints[k, 2L])))
  }, integer(2L)))
  raw <- data.frame(
    mask_type = types,
    ppm_min = apply(endpoints, 1L, min), ppm_max = apply(endpoints, 1L, max),
    start_index = index_pairs[, 1L], end_index = index_pairs[, 2L],
    stringsAsFactors = FALSE)
  raw <- raw[order(raw$start_index, raw$end_index, raw$mask_type), , drop = FALSE]

  merged <- list()
  current <- raw[1L, , drop = FALSE]
  if (nrow(raw) > 1L) {
    for (k in 2:nrow(raw)) {
      next_mask <- raw[k, , drop = FALSE]
      if (next_mask$start_index <= current$end_index + 1L) {
        current$end_index <- max(current$end_index, next_mask$end_index)
        current$ppm_min <- min(current$ppm_min, next_mask$ppm_min)
        current$ppm_max <- max(current$ppm_max, next_mask$ppm_max)
        current$mask_type <- paste(sort(unique(c(
          strsplit(current$mask_type, ",", fixed = TRUE)[[1L]],
          next_mask$mask_type))), collapse = ",")
      } else {
        merged[[length(merged) + 1L]] <- current
        current <- next_mask
      }
    }
  }
  merged[[length(merged) + 1L]] <- current
  result <- do.call(rbind, merged)
  result$mask_id <- seq_len(nrow(result))
  result <- result[, names(empty), drop = FALSE]
  rownames(result) <- NULL
  result
}

.apply_alignment_masks <- function(regions, masks, ppm,
                                   minimum_region_points) {
  masks <- .normalize_alignment_masks(masks, ppm)
  regions$mask_status <- rep("unmasked", nrow(regions))
  regions$mask_labels <- rep("", nrow(regions))
  removed <- regions[FALSE, , drop = FALSE]
  if (!nrow(regions) || !nrow(masks)) {
    attr(regions, "masked_regions") <- removed
    attr(regions, "masks") <- masks
    return(regions)
  }

  kept <- list()
  discarded <- list()
  for (k in seq_len(nrow(regions))) {
    region <- regions[k, , drop = FALSE]
    hits <- which(masks$start_index <= region$end_index &
                  masks$end_index >= region$start_index)
    if (!length(hits)) {
      kept[[length(kept) + 1L]] <- region
      next
    }
    region$mask_labels <- paste(sort(unique(unlist(strsplit(
      masks$mask_type[hits], ",", fixed = TRUE)))), collapse = ",")
    blocked <- rep(FALSE, length(ppm))
    for (hit in hits) {
      blocked[masks$start_index[hit]:masks$end_index[hit]] <- TRUE
    }
    if (any(blocked[region$core_start:region$core_end])) {
      region$mask_status <- "removed_core"
      discarded[[length(discarded) + 1L]] <- region
      next
    }
    available <- (!blocked) & seq_along(ppm) >= region$start_index &
      seq_along(ppm) <= region$end_index
    run_id <- cumsum(c(TRUE, diff(available) != 0L))
    core_run <- unique(run_id[region$core_start:region$core_end])
    candidate <- which(available & run_id == core_run)
    if (length(candidate) < minimum_region_points) {
      region$mask_status <- "removed_too_short"
      discarded[[length(discarded) + 1L]] <- region
      next
    }
    region$start_index <- min(candidate)
    region$end_index <- max(candidate)
    region$start_ppm <- ppm[region$start_index]
    region$end_ppm <- ppm[region$end_index]
    region$ppm_min <- min(region$start_ppm, region$end_ppm)
    region$ppm_max <- max(region$start_ppm, region$end_ppm)
    region$points <- region$end_index - region$start_index + 1L
    region$mask_status <- "trimmed"
    kept[[length(kept) + 1L]] <- region
  }
  result <- if (length(kept)) do.call(rbind, kept) else
    regions[FALSE, , drop = FALSE]
  removed <- if (length(discarded)) do.call(rbind, discarded) else removed
  result$region_id <- seq_len(nrow(result))
  rownames(result) <- NULL
  rownames(removed) <- NULL
  attr(result, "masked_regions") <- removed
  attr(result, "masks") <- masks
  result
}

# Build non-overlapping candidate intervals from conservative peak groups.
# The 11-point minimum is imposed because the exhaustive n="b" search starts
# with a maximum shift of 10 points. Overlapping margins are separated only at
# a sufficiently deep minimum outside both groups' external bases; otherwise
# the groups are retained together and explicitly marked as congested.
.build_alignment_regions <- function(profile, peaks, ppm,
                                     expected_shift_ppm = 0.005,
                                     width_margin_factor = 0.5,
                                     minimum_region_points = 11L,
                                     deep_minimum_fraction = 0.5,
                                     group_column = "group_with_j",
                                     masks = NULL,
                                     uniform_tolerance = 0.5) {
  profile <- .validate_peak_signal(profile)
  ppm <- .validate_ppm_axis(ppm, length(profile), uniform_tolerance)
  expected_shift_ppm <- .validate_nonnegative_scalar(
    expected_shift_ppm, "expected_shift_ppm")
  width_margin_factor <- .validate_nonnegative_scalar(
    width_margin_factor, "width_margin_factor")
  deep_minimum_fraction <- .validate_nonnegative_scalar(
    deep_minimum_fraction, "deep_minimum_fraction")
  if (length(minimum_region_points) != 1L || is.na(minimum_region_points) ||
      !is.finite(minimum_region_points) ||
      minimum_region_points != floor(minimum_region_points) ||
      minimum_region_points < 11L) {
    stop("minimum_region_points deve ser inteiro e pelo menos 11.",
         call. = FALSE)
  }
  minimum_region_points <- as.integer(minimum_region_points)
  required <- c("index", "ppm", "left_base", "right_base", "left_ip",
                "right_ip", "width_points", "prominence", "polarity",
                group_column)
  if (!is.data.frame(peaks) || !all(required %in% names(peaks))) {
    stop("peaks nao contem os campos necessarios para construir regioes.",
         call. = FALSE)
  }
  # Tabelas produzidas pelo detector novo trazem bases fisicas independentes
  # da janela local. Aceitar tabelas internas antigas preserva a API do helper
  # para extensoes que constroem candidatos manualmente.
  if (!"signal_left_base" %in% names(peaks)) {
    peaks$signal_left_base <- peaks$left_base
  }
  if (!"signal_right_base" %in% names(peaks)) {
    peaks$signal_right_base <- peaks$right_base
  }
  required <- c(required, "signal_left_base", "signal_right_base")
  empty <- data.frame(
    region_id = integer(), group_ids = character(), polarity = character(),
    components = integer(), start_index = integer(), end_index = integer(),
    start_ppm = numeric(), end_ppm = numeric(), ppm_min = numeric(),
    ppm_max = numeric(), points = integer(), core_start = integer(),
    core_end = integer(), margin_points = integer(), congested = logical(),
    resolution = character(), split_minima = character(),
    mask_status = character(), mask_labels = character(),
    stringsAsFactors = FALSE)
  if (minimum_region_points > length(profile) || !nrow(peaks)) {
    return(.apply_alignment_masks(empty, masks, ppm, minimum_region_points))
  }
  numeric_required <- setdiff(required, c("polarity", group_column))
  if (anyNA(peaks[, required]) ||
      any(!is.finite(as.matrix(peaks[, numeric_required]))) ||
      any(!peaks$polarity %in% c("positive", "negative")) ||
      any(peaks$index != floor(peaks$index)) ||
      any(peaks$index < 1L | peaks$index > length(profile)) ||
      any(peaks$ppm != ppm[peaks$index])) {
    stop("peaks contem valores invalidos para construir regioes.",
         call. = FALSE)
  }

  peaks <- peaks[order(peaks$index, peaks$polarity), , drop = FALSE]
  rownames(peaks) <- NULL
  groups <- split(seq_len(nrow(peaks)), peaks[[group_column]])
  step_ppm <- attr(ppm, "step_ppm")
  regions <- lapply(names(groups), function(id) {
    members <- groups[[id]]
    core_start <- min(peaks$signal_left_base[members],
                      floor(peaks$left_ip[members]))
    core_end <- max(peaks$signal_right_base[members],
                    ceiling(peaks$right_ip[members]))
    margin <- as.integer(ceiling(expected_shift_ppm / step_ppm +
                                 width_margin_factor *
                                   max(peaks$width_points[members])))
    bounds <- .expand_region_bounds(core_start, core_end, margin,
                                    minimum_region_points, length(profile))
    list(group_ids = id, members = members, start = bounds[1L], end = bounds[2L],
         core_start = core_start, core_end = core_end, margin = margin,
         congested = FALSE, resolution = "independent",
         split_minima = integer())
  })
  # Bases fisicas largas podem fazer um grupo posterior comecar antes de um
  # nucleo anterior. A varredura que elimina sobreposicoes precisa seguir a
  # geometria efetiva dos intervalos, usando o nucleo apenas como desempate.
  regions <- regions[order(
    vapply(regions, `[[`, numeric(1L), "start"),
    vapply(regions, `[[`, numeric(1L), "core_start"))]

  resolved <- list()
  current <- regions[[1L]]
  if (length(regions) > 1L) {
    for (region_index in seq.int(2L, length(regions))) {
      next_region <- regions[[region_index]]
      if (current$end < next_region$start) {
        resolved[[length(resolved) + 1L]] <- current
        current <- next_region
        next
      }
      left_peak <- current$members[which.max(peaks$index[current$members])]
      right_peak <- next_region$members[
        which.min(peaks$index[next_region$members])]
      same_polarity <- peaks$polarity[left_peak] == peaks$polarity[right_peak]
      split <- NA_integer_
      later_crosses_gap <- FALSE
      if (region_index < length(regions)) {
        later_starts <- vapply(regions[seq.int(region_index + 1L,
                                               length(regions))],
                               `[[`, numeric(1L), "start")
        later_crosses_gap <- any(later_starts <= next_region$core_start)
      }
      if (same_polarity && current$core_end < next_region$core_start &&
          !later_crosses_gap) {
        candidates <- current$core_end:(next_region$core_start - 1L)
        sign <- if (peaks$polarity[left_peak] == "negative") -1 else 1
        transformed <- sign * profile[candidates]
        if (any(is.finite(transformed))) {
          split <- candidates[which.min(replace(transformed,
                                                 !is.finite(transformed), Inf))]
          valley <- sign * profile[split]
          peak_floor <- min(sign * profile[peaks$index[c(left_peak,
                                                         right_peak)]])
          prominence_floor <- min(peaks$prominence[c(left_peak, right_peak)])
          depth <- (peak_floor - valley) / prominence_floor
          leaves_valid_intervals <-
            split - current$start + 1L >= minimum_region_points &&
            next_region$end - split >= minimum_region_points
          if (!is.finite(depth) || depth < deep_minimum_fraction ||
              !leaves_valid_intervals) split <- NA_integer_
        }
      }
      if (!is.na(split)) {
        current$end <- split
        current$resolution <- "deep_minimum"
        current$split_minima <- unique(c(current$split_minima, split))
        next_region$start <- split + 1L
        next_region$resolution <- "deep_minimum"
        next_region$split_minima <- unique(c(next_region$split_minima, split))
        resolved[[length(resolved) + 1L]] <- current
        current <- next_region
      } else {
        current$group_ids <- c(current$group_ids, next_region$group_ids)
        current$members <- unique(c(current$members, next_region$members))
        current$start <- min(current$start, next_region$start)
        current$end <- max(current$end, next_region$end)
        current$core_start <- min(current$core_start, next_region$core_start)
        current$core_end <- max(current$core_end, next_region$core_end)
        current$margin <- max(current$margin, next_region$margin)
        current$congested <- TRUE
        current$resolution <- "merged_congested"
        current$split_minima <- unique(c(current$split_minima,
                                          next_region$split_minima))
      }
    }
  }
  resolved[[length(resolved) + 1L]] <- current

  rows <- lapply(seq_along(resolved), function(k) {
    region <- resolved[[k]]
    polarities <- unique(peaks$polarity[region$members])
    split_text <- if (length(region$split_minima))
      paste(region$split_minima, collapse = ",") else ""
    data.frame(
      region_id = k, group_ids = paste(region$group_ids, collapse = ","),
      polarity = paste(polarities, collapse = ","),
      components = length(region$members), start_index = region$start,
      end_index = region$end, start_ppm = ppm[region$start],
      end_ppm = ppm[region$end],
      ppm_min = min(ppm[c(region$start, region$end)]),
      ppm_max = max(ppm[c(region$start, region$end)]),
      points = region$end - region$start + 1L,
      core_start = region$core_start, core_end = region$core_end,
      margin_points = region$margin, congested = region$congested,
      resolution = region$resolution, split_minima = split_text,
      stringsAsFactors = FALSE)
  })
  result <- do.call(rbind, rows)
  result <- .apply_alignment_masks(result, masks, ppm, minimum_region_points)
  stopifnot(all(result$points >= minimum_region_points),
            all(result$start_index >= 1L),
            all(result$end_index <= length(ppm)),
            all(result$start_index < result$end_index))
  overlap <- which(head(result$end_index, -1L) >=
                     tail(result$start_index, -1L))
  if (length(overlap)) {
    stop(sprintf("regioes resolvidas ainda se sobrepoem nas linhas %s.",
                 paste(overlap, collapse = ", ")), call. = FALSE)
  }
  result
}

.filter_peak_table <- function(peaks, ppm, profile,
                               min_prominence_snr = 5,
                               min_distance_ppm = 0.002,
                               min_width_ppm = 0.001,
                               edge_margin_ppm = 0.005) {
  min_prominence_snr <- .validate_nonnegative_scalar(
    min_prominence_snr, "min_prominence_snr")
  min_distance_ppm <- .validate_nonnegative_scalar(
    min_distance_ppm, "min_distance_ppm")
  min_width_ppm <- .validate_nonnegative_scalar(
    min_width_ppm, "min_width_ppm")
  edge_margin_ppm <- .validate_nonnegative_scalar(
    edge_margin_ppm, "edge_margin_ppm")

  global_noise <- .noise_from_differences(profile)
  if (!nrow(peaks)) {
    peaks$global_noise <- numeric()
    peaks$effective_noise <- numeric()
    peaks$prominence_snr <- numeric()
    return(peaks)
  }
  local_noise <- peaks$noise
  usable_local <- is.finite(local_noise) & local_noise >= 0
  effective_noise <- rep(global_noise, nrow(peaks))
  effective_noise[usable_local] <- pmax(local_noise[usable_local], global_noise,
                                        na.rm = TRUE)
  effective_noise[!is.finite(effective_noise)] <- NA_real_
  snr <- peaks$prominence / effective_noise
  snr[effective_noise == 0 & peaks$prominence > 0] <- Inf
  edge_distance <- pmin(abs(peaks$ppm - ppm[1L]),
                        abs(peaks$ppm - ppm[length(ppm)]))
  keep <- is.finite(peaks$prominence) & peaks$prominence > 0 &
    !is.na(snr) & snr >= min_prominence_snr &
    is.finite(peaks$width_ppm) & peaks$width_ppm >= min_width_ppm &
    edge_distance >= edge_margin_ppm
  peaks$global_noise <- global_noise
  peaks$effective_noise <- effective_noise
  peaks$prominence_snr <- snr
  peaks <- peaks[keep, , drop = FALSE]
  peaks <- .distance_filter(peaks, min_distance_ppm)
  peaks[order(peaks$index, peaks$polarity), , drop = FALSE]
}

.alignment_peak_candidates <- function(spectra, ppm,
                                       method = c("median", "trimmed_mean"),
                                       trim = 0.1,
                                       min_prominence_snr = 5,
                                       min_distance_ppm = 0.002,
                                       min_width_ppm = 0.001,
                                       window_ppm = 0.05,
                                       edge_margin_ppm = 0.005,
                                       base_height_fraction = 0.01,
                                       base_noise_multiplier = 3,
                                       base_sustain_points = 3L,
                                       base_search_ppm = 0.5,
                                       include_negative = FALSE,
                                       rel_height = 0.5,
                                       uniform_tolerance = 0.5,
                                       frequency_mhz = NULL,
                                       use_j = TRUE,
                                       spacing_tolerance_points = 2,
                                       min_repeated_spacings = 2L,
                                       expected_shift_ppm = 0.005,
                                       width_margin_factor = 0.5,
                                       minimum_region_points = 11L,
                                       deep_minimum_fraction = 0.5,
                                       masks = NULL) {
  method <- match.arg(method)
  profile <- .representative_spectrum(spectra, method = method, trim = trim)
  ppm <- .validate_ppm_axis(ppm, length(profile), uniform_tolerance)
  window_ppm <- .validate_nonnegative_scalar(window_ppm, "window_ppm",
                                              positive = TRUE)
  base_search_ppm <- .validate_nonnegative_scalar(
    base_search_ppm, "base_search_ppm", positive = TRUE)
  if (base_search_ppm < window_ppm) {
    stop("base_search_ppm deve ser pelo menos window_ppm.", call. = FALSE)
  }
  if (length(include_negative) != 1L || is.na(include_negative) ||
      !is.logical(include_negative)) {
    stop("include_negative deve ser TRUE ou FALSE.", call. = FALSE)
  }
  wlen <- .ppm_window_points(window_ppm, attr(ppm, "step_ppm"))
  positive <- .peak_table(profile, ppm, wlen = wlen,
                          rel_height = rel_height,
                          uniform_tolerance = uniform_tolerance,
                          base_height_fraction = base_height_fraction,
                          base_noise_multiplier = base_noise_multiplier,
                          base_sustain_points = base_sustain_points,
                          base_search_ppm = base_search_ppm)
  positive$polarity <- rep("positive", nrow(positive))
  raw_peaks <- positive
  if (include_negative) {
    negative <- .peak_table(-profile, ppm, wlen = wlen,
                            rel_height = rel_height,
                            uniform_tolerance = uniform_tolerance,
                            base_height_fraction = base_height_fraction,
                            base_noise_multiplier = base_noise_multiplier,
                            base_sustain_points = base_sustain_points,
                            base_search_ppm = base_search_ppm)
    negative$intensity <- profile[negative$index]
    negative$width_height <- -negative$width_height
    negative$polarity <- rep("negative", nrow(negative))
    raw_peaks <- rbind(positive, negative)
    raw_peaks <- raw_peaks[order(raw_peaks$index, raw_peaks$polarity), ,
                           drop = FALSE]
  }
  peaks <- .filter_peak_table(
    raw_peaks, ppm, profile,
    min_prominence_snr = min_prominence_snr,
    min_distance_ppm = min_distance_ppm,
    min_width_ppm = min_width_ppm,
    edge_margin_ppm = edge_margin_ppm)
  grouping <- .group_peak_candidates(
    peaks, ppm, frequency_mhz = frequency_mhz, use_j = use_j,
    spacing_tolerance_points = spacing_tolerance_points,
    min_repeated_spacings = min_repeated_spacings,
    uniform_tolerance = uniform_tolerance)
  regions <- .build_alignment_regions(
    profile, grouping$peaks, ppm,
    expected_shift_ppm = expected_shift_ppm,
    width_margin_factor = width_margin_factor,
    minimum_region_points = minimum_region_points,
    deep_minimum_fraction = deep_minimum_fraction,
    group_column = if (use_j) "group_with_j" else "group_without_j",
    masks = masks,
    uniform_tolerance = uniform_tolerance)
  masked_regions <- attr(regions, "masked_regions")
  normalized_masks <- attr(regions, "masks")
  list(profile = profile, raw_peaks = raw_peaks, peaks = peaks,
       grouping = grouping, regions = regions, masked_regions = masked_regions,
       method = method,
       parameters = list(
         min_prominence_snr = min_prominence_snr,
         min_distance_ppm = min_distance_ppm,
         min_width_ppm = min_width_ppm,
         window_ppm = window_ppm,
         window_points = wlen,
         edge_margin_ppm = edge_margin_ppm,
         base_height_fraction = base_height_fraction,
         base_noise_multiplier = base_noise_multiplier,
         base_sustain_points = base_sustain_points,
         base_search_ppm = base_search_ppm,
         include_negative = include_negative,
         rel_height = rel_height,
         uniform_tolerance = uniform_tolerance,
         frequency_mhz = frequency_mhz,
         use_j = use_j,
         spacing_tolerance_points = spacing_tolerance_points,
         min_repeated_spacings = min_repeated_spacings,
         expected_shift_ppm = expected_shift_ppm,
         width_margin_factor = width_margin_factor,
         minimum_region_points = minimum_region_points,
         deep_minimum_fraction = deep_minimum_fraction,
         masks = normalized_masks,
         step_ppm = attr(ppm, "step_ppm"),
         step_relative_deviation = attr(ppm, "step_relative_deviation")))
}

.find_local_peaks <- function(x) {
  x <- .validate_peak_signal(x)
  n <- length(x)
  empty <- data.frame(peak = integer(), left_edge = integer(),
                      right_edge = integer(), plateau_size = integer())
  if (n < 3L) {
    return(empty)
  }

  # No vetor mais alternante possivel ha no maximo floor((n - 1) / 2)
  # picos internos. Pre-alocar evita crescimento quadratico por c() repetido.
  capacity <- (n - 1L) %/% 2L
  peaks <- left_edges <- right_edges <- integer(capacity)
  count <- 0L
  i <- 2L
  while (i < n) {
    if (!is.na(x[i - 1L]) && !is.na(x[i]) && x[i - 1L] < x[i]) {
      right <- i
      while (right < n && !is.na(x[right + 1L]) &&
             x[right + 1L] == x[i]) {
        right <- right + 1L
      }
      if (right < n && !is.na(x[right + 1L]) && x[right + 1L] < x[i]) {
        count <- count + 1L
        left_edges[count] <- i
        right_edges[count] <- right
        peaks[count] <- floor((i + right) / 2)
      }
      i <- right + 1L
    } else {
      i <- i + 1L
    }
  }

  if (!count) {
    return(empty)
  }
  keep <- seq_len(count)
  peaks <- peaks[keep]
  left_edges <- left_edges[keep]
  right_edges <- right_edges[keep]
  data.frame(peak = as.integer(peaks), left_edge = left_edges,
             right_edge = right_edges,
             plateau_size = right_edges - left_edges + 1L)
}

.validate_peak_indices <- function(peaks, n) {
  if (!is.numeric(peaks) || anyNA(peaks) ||
      any(!is.finite(peaks)) || any(peaks != floor(peaks)) ||
      any(peaks < 1L | peaks > n)) {
    stop("peaks deve conter indices inteiros validos de x.", call. = FALSE)
  }
  as.integer(peaks)
}

.peak_prominences <- function(x, peaks = .find_local_peaks(x)$peak,
                              wlen = NULL) {
  x <- .validate_peak_signal(x)
  peaks <- .validate_peak_indices(peaks, length(x))
  if (!length(peaks)) {
    return(data.frame(prominence = numeric(), left_base = integer(),
                      right_base = integer()))
  }

  if (is.null(wlen)) {
    half_window <- Inf
  } else {
    if (length(wlen) != 1L || is.na(wlen) || !is.finite(wlen) || wlen <= 1) {
      stop("wlen deve ser um numero finito maior que 1.", call. = FALSE)
    }
    window <- as.integer(ceiling(wlen))
    if (window %% 2L == 0L) {
      window <- window + 1L
    }
    half_window <- window %/% 2L
  }

  prominence <- rep(NA_real_, length(peaks))
  left_base <- right_base <- peaks
  for (k in seq_along(peaks)) {
    peak <- peaks[k]
    if (is.na(x[peak])) {
      next
    }
    left_limit <- if (is.infinite(half_window)) 1L else
      max(1L, peak - half_window)
    right_limit <- if (is.infinite(half_window)) length(x) else
      min(length(x), peak + half_window)

    left_min <- right_min <- x[peak]
    i <- peak
    while (i > left_limit) {
      i <- i - 1L
      if (is.na(x[i]) || x[i] > x[peak]) break
      if (x[i] < left_min) {
        left_min <- x[i]
        left_base[k] <- i
      }
    }

    i <- peak
    while (i < right_limit) {
      i <- i + 1L
      if (is.na(x[i]) || x[i] > x[peak]) break
      if (x[i] < right_min) {
        right_min <- x[i]
        right_base[k] <- i
      }
    }
    prominence[k] <- x[peak] - max(left_min, right_min)
  }

  data.frame(prominence = prominence, left_base = left_base,
             right_base = right_base)
}

.peak_widths <- function(x, peaks = .find_local_peaks(x)$peak,
                         rel_height = 0.5, prominence_data = NULL) {
  x <- .validate_peak_signal(x)
  peaks <- .validate_peak_indices(peaks, length(x))
  if (length(rel_height) != 1L || is.na(rel_height) ||
      !is.finite(rel_height) || rel_height < 0) {
    stop("rel_height deve ser um numero finito nao negativo.", call. = FALSE)
  }
  if (!length(peaks)) {
    return(data.frame(width = numeric(), width_height = numeric(),
                      left_ip = numeric(), right_ip = numeric()))
  }

  if (is.null(prominence_data)) {
    prominence_data <- .peak_prominences(x, peaks)
  }
  required <- c("prominence", "left_base", "right_base")
  if (!is.data.frame(prominence_data) ||
      !all(required %in% names(prominence_data)) ||
      nrow(prominence_data) != length(peaks)) {
    stop("prominence_data e incompativel com peaks.", call. = FALSE)
  }

  widths <- heights <- left_ips <- right_ips <- rep(NA_real_, length(peaks))
  for (k in seq_along(peaks)) {
    peak <- peaks[k]
    left <- as.integer(prominence_data$left_base[k])
    right <- as.integer(prominence_data$right_base[k])
    prom <- prominence_data$prominence[k]
    if (anyNA(c(x[peak], left, right, prom)) || left > peak || right < peak ||
        left < 1L || right > length(x)) {
      next
    }

    height <- x[peak] - prom * rel_height
    i <- peak
    while (i > left && height < x[i]) i <- i - 1L
    left_ip <- as.numeric(i)
    if (x[i] < height) {
      left_ip <- left_ip + (height - x[i]) / (x[i + 1L] - x[i])
    }

    i <- peak
    while (i < right && height < x[i]) i <- i + 1L
    right_ip <- as.numeric(i)
    if (x[i] < height) {
      right_ip <- right_ip - (height - x[i]) / (x[i - 1L] - x[i])
    }

    heights[k] <- height
    left_ips[k] <- left_ip
    right_ips[k] <- right_ip
    widths[k] <- right_ip - left_ip
  }

  data.frame(width = widths, width_height = heights,
             left_ip = left_ips, right_ip = right_ips)
}

.find_local_minima <- function(x) {
  x <- .validate_peak_signal(x)
  result <- .find_local_peaks(-x)
  names(result)[names(result) == "peak"] <- "minimum"
  result
}

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.