R/fast_convolve.R

Defines functions fast_convolve

fast_convolve <- function(y, delay) {
  n <- length(y)
  assert_numeric(delay, lower = 0, any.missing = FALSE, len = n)
  if (n < 100) return(calc_delays(y, delay)) # this is exact, normalizes

  # Has potential errors due to fft / ifft
  convolved_seq <- stats::convolve(y, rev(delay), type = "open")
  convolved_seq <- convolved_seq[seq_along(y)]

  # now we find the support and 0 out the rest
  eps <- .Machine$double.eps
  if (any(delay < eps) || any(y < eps)) {
    idy <- as.double(y > eps)
    idd <- as.double(delay > eps)
    id0 <- stats::convolve(idy, rev(idd), type = "open")[seq_along(y)]
    convolved_seq[id0 < 0.5] <- 0
    convolved_seq[convolved_seq < eps] <- 0
  }
  # normalize
  cw <- cumsum(delay)
  wcs <- convolved_seq / cw
  wcs[cw < eps] <- 0
  wcs
}

Try the rtestim package in your browser

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

rtestim documentation built on Aug. 8, 2025, 6:21 p.m.