R/icoshift_core.R

Defines functions coshifta CC_FFTShift preprocessX msc MeanwNaN SumwNaN

# Porte literal do nucleo do icoshift v3.0 beta (MATLAB -> R).
# Sinais ficam em LINHAS na interface publica (igual ao MATLAB); internamente
# a FFT trabalha com sinais em COLUNAS para poder usar stats::mvfft.

# ---- private/SumwNaN.m , private/MeanwNaN.m -------------------------------
SumwNaN <- function(X, Dim = 1L) {
  X[is.na(X)] <- 0
  if (Dim == 1L) colSums(X) else rowSums(X)
}

MeanwNaN <- function(X, Dim = 1L) {
  if (is.null(dim(X))) X <- matrix(X, nrow = 1L)
  nas <- is.na(X)
  X[nas] <- 0
  c_ <- if (Dim == 1L) colSums(!nas) else rowSums(!nas)
  c_[c_ == 0] <- NA_real_
  s <- if (Dim == 1L) colSums(X) else rowSums(X)
  s / c_
}

# ---- private/msc.m --------------------------------------------------------
msc <- function(option, X) {
  # preprocessX chama msc(0, A). No original, option=0 ajusta um polinomio
  # constante contra o espectro medio, portanto apenas remove a media da linha.
  if (option != 0) stop("Only the msc option used by icoshift is implemented")
  X - rowMeans(X)
}

# ---- private/preprocessX.m -----------------------------------------------
# opt = c(show, alignPreprocessed)
preprocessX <- function(A, opt) {
  if (is.null(dim(A))) A <- matrix(A, nrow = 1L)
  mode <- opt[2L]
  if (mode == 0) return(A)
  if (mode == 3) {
    if (nrow(A) > 1L) A <- msc(0, A)
  } else if (mode == 2) {
    A <- A - apply(A, 1L, min, na.rm = TRUE)
  } else if (mode == 1) {
    # SNV como no MATLAB: centra na linha, depois MULTIPLICA por (n-1)/sqrt(SS)
    A <- A - MeanwNaN(A, 2L)
    A <- A * ((rowSums(!is.na(A)) - 1) / sqrt(SumwNaN(A^2, 2L)))
  } else {
    deg <- -mode
    Xd <- t(apply(A, 1L, diff, differences = deg))
    if (deg == 1L) Xd <- cbind(Xd[, 1L, drop = FALSE], Xd)
    else           Xd <- cbind(Xd[, 1L, drop = FALSE], Xd, Xd[, ncol(Xd), drop = FALSE])
    A <- Xd
  }
  A
}

# ---- CC_FFTShift (dentro de private/coshifta.m) ---------------------------
# Devolve apenas os deslocamentos: o Xwarp do MATLAB e descartado por coshifta.
CC_FFTShift <- function(T, X, Options) {
  if (is.null(dim(X))) X <- matrix(X, nrow = 1L)
  if (is.null(dim(T))) T <- matrix(T, nrow = 1L)
  o1 <- Options[1L]; o2 <- Options[2L]
  if (o1 > o2) stop("Lower bound for shift is larger than upper bound")

  Xnorm <- sqrt(SumwNaN(X^2, 2L)); Xnorm[Xnorm == 0] <- 1
  Xn <- X / Xnorm
  Tnorm <- sqrt(SumwNaN(T^2, 2L)); Tnorm[Tnorm == 0] <- 1
  Tn <- T / Tnorm

  nP <- ncol(X); nT <- ncol(T)
  pad <- max(abs(c(o1, o2)))
  miss_offset <- numeric(nrow(Xn))
  if (anyNA(Xn) || anyNA(Tn)) {
    compact_edges <- function(v, label) {
      good <- which(!is.na(v))
      if (!length(good) || anyNA(v[min(good):max(good)]))
        stop(sprintf("Missing values can be handled only if leading or trailing in %s", label))
      if (max(min(good) - 1L, length(v) - max(good)) > pad)
        stop("Missing values band larger than largest admitted shift")
      c(min(good), max(good))
    }
    target_edges <- compact_edges(as.vector(Tn), "the target")
    for (i in seq_len(nrow(Xn))) {
      edges <- compact_edges(Xn[i, ], "a sample")
      miss_offset[i] <- edges[1L] - target_edges[1L]
      values <- Xn[i, edges[1L]:edges[2L]]
      Xn[i, ] <- c(values, numeric(ncol(Xn) - length(values)))
    }
    values <- Tn[1L, target_edges[1L]:target_edges[2L]]
    Tn[1L, ] <- c(values, numeric(ncol(Tn) - length(values)))
  }

  len_fft <- max(nT, nP) + pad
  Shift <- o1:o2

  idx <- if (o1 < 0 && o2 > 0)       c((len_fft + o1 + 1):len_fft, 1:(o2 + 1))
         else if (o1 < 0 && o2 < 0)  (len_fft + o1 + 1):(len_fft + o2 + 1)
         else if (o1 < 0 && o2 == 0) c((len_fft + o1 + 1):(len_fft + o2), 1)
         else                        (o1 + 1):(o2 + 1)

  # sinais em colunas, zero-padding ate len_fft
  Xp <- matrix(0, nrow = len_fft, ncol = nrow(X))
  Xp[seq_len(nP), ] <- t(Xn)
  Tp <- numeric(len_fft); Tp[seq_len(nT)] <- as.vector(Tn)

  Xf <- stats::mvfft(Xp)
  Tf <- Conj(stats::fft(Tp))
  cc <- Re(stats::mvfft(Xf * Tf, inverse = TRUE) / len_fft)   # ifft real: produto e conj-simetrico
  cc <- cc[idx, , drop = FALSE]

  if (is.finite(Options[6L]) && Options[6L] > -1 && Options[6L] < 1 - 1e-2)
    cc <- pmax(cc, Options[6L])

  Shift[max.col(t(cc), ties.method = "first")] + miss_offset
}

# ---- private/coshifta.m ---------------------------------------------------
# options = c(show, fill, NA, BLOCKSIZE, -Inf, alignPreprocessed)
coshifta <- function(xT, xP, refW, n, options) {
  if (length(refW) == 0L) refW <- 0
  if (!is.null(dim(refW)) && nrow(refW) != 1L)
    stop('Reference windows "refW" must be either a single vector or 0')
  refW <- as.vector(refW)
  rw <- if (all(refW >= 0)) length(refW) else 1L
  Filling <- if (options[2L] == 1) -Inf else if (options[2L] == 0) NA_real_ else stop("options(2) must be 0 or 1")

  if (is.character(xT) && tolower(xT) == "average") xT <- matrix(MeanwNaN(xP, 1L), nrow = 1L)
  if (is.null(dim(xT))) xT <- matrix(xT, nrow = 1L)
  dimP <- dim(xP)
  if (ncol(xT) != dimP[2L]) stop('Target "xT" and sample "xP" must be of compatible size')
  if ((rw > 1L && min(refW) < 1L) || max(refW) > ncol(xT))
    stop('Reference window "refW" must be a subset of xP')
  if (nrow(xT) != 1L) stop('Target "xT" must be a single row spectrum/chromatogram')

  auto <- is.character(n) && tolower(n) %in% c("b", "f")
  if (auto) {
    locDim <- if (rw != 1L) length(refW) else dimP[2L]
    try_last <- tolower(n) == "f"
    if (try_last) { n <- locDim - 1L;                     src_step <- round(locDim / 2) - 1L }
    else          { n <- max(trunc(0.05 * locDim), 10L);  src_step <- trunc(locDim / 20) }
  }
  if (rw == 1L) refW <- seq_len(dimP[2L])
  W <- length(refW)

  Tpp <- preprocessX(xT[1L, refW, drop = FALSE], c(0, options[6L]))
  B   <- preprocessX(xP[, refW, drop = FALSE],   c(options[1L], options[6L]))

  opt <- c(-n, n, 2, options[3L], Filling, options[5L])
  conv <- FALSE
  ind <- integer(dimP[1L])
  while (!conv) {
    ind <- CC_FFTShift(Tpp, B, opt)
    if (auto) {
      tmp  <- max(abs(ind))
      nTmp <- opt[2L] + src_step
      if (tmp == opt[2L] && !try_last) {
        try_last <- nTmp >= W
      } else if (tmp < opt[2L] && nTmp < W && !try_last) {
        try_last <- TRUE
      } else {
        conv <- TRUE; n <- opt[2L]; next
      }
      opt[2L] <- nTmp; opt[1L] <- -opt[2L]
    } else conv <- TRUE
  }

  # aplica os deslocamentos ao sinal ORIGINAL (nao ao preprocessado)
  if (identical(Filling, -Inf)) {
    leadSection <- xP[, 1L]; trailSection <- xP[, dimP[2L]]
  } else {
    leadSection <- rep(NA_real_, dimP[1L]); trailSection <- leadSection
  }
  for (iSam in which(ind != 0)) {
    s <- 1L; e <- dimP[2L]; cN <- abs(ind[iSam])
    if (ind[iSam] < 0) { iLead <- rep(leadSection[iSam], cN); iTrail <- numeric(0); e <- e + ind[iSam] }
    else               { iTrail <- rep(trailSection[iSam], cN); iLead <- numeric(0); s <- ind[iSam] + 1L }
    xP[iSam, ] <- c(iLead, xP[iSam, s:e], iTrail)
  }
  list(xP = xP, ind = ind, n = n)
}

Try the iSTATS package in your browser

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

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