Repository for Petra's work at ampli Jan-Feb 2019

fftest.R 888B

1234567891011121314151617181920212223242526272829
  1. # Testing the reconstruction of arbitrary sequencies using fourier transforms
  2. library(ggplot2)
  3. library(scales)
  4. library(dplyr)
  5. theme_set(theme_bw())
  6. fextract <- function(x, y, keep = 1, top = TRUE) {
  7. sdy <- sd(y)
  8. my <- mean(y)
  9. stany <- (y - my) / sdy
  10. ftf <- fft(stany)
  11. if (top) {
  12. ftf[rank(-abs(ftf)) > keep] <- 0
  13. } else {
  14. ftf[(keep + 1):length(ftf)] <- 0
  15. }
  16. rfv <- Re(fft(ftf, inverse = TRUE))
  17. return(data.frame(x = x, y = y, f = (rfv - mean(rfv)) / sd(rfv) * sdy + my))
  18. }
  19. n <- 100
  20. k <- 1
  21. dat1 <- data.frame(x = 1:n, yo = 10 * sin(rescale(1:n, 2 * c(-pi, pi) + rnorm(2))))
  22. dat1$y <- dat1$yo + rnorm(n)
  23. fnew <- fextract(dat1$x, dat1$y, keep = k, top = TRUE)
  24. # ggplot(rdat1, aes(x, y)) + geom_line()
  25. ggplot(fnew, aes(x, y)) + geom_line() + geom_point() +
  26. geom_line(aes(x, f), color = "blue") + geom_point(aes(x, f), color = "blue")