# Testing the reconstruction of arbitrary sequencies using fourier transforms
library(ggplot2)
library(scales)
library(dplyr)
theme_set(theme_bw())

fextract <- function(x, y, keep = 1, top = TRUE) {
    sdy <- sd(y)
    my <- mean(y)
    stany <- (y - my) / sdy
    ftf <- fft(stany)
    if (top) {
        ftf[rank(-abs(ftf)) > keep] <- 0
    } else {
        ftf[(keep + 1):length(ftf)] <- 0
    }
    rfv <- Re(fft(ftf, inverse = TRUE))
    return(data.frame(x = x, y = y, f = (rfv - mean(rfv)) / sd(rfv) * sdy + my))
}

n <- 100
k <- 1
dat1 <- data.frame(x = 1:n, yo = 10 * sin(rescale(1:n, 2 * c(-pi, pi) + rnorm(2))))
dat1$y <- dat1$yo + rnorm(n)
fnew <- fextract(dat1$x, dat1$y, keep = k, top = TRUE)
# ggplot(rdat1, aes(x, y)) + geom_line()
ggplot(fnew, aes(x, y)) + geom_line() + geom_point() + 
    geom_line(aes(x, f), color = "blue") + geom_point(aes(x, f), color = "blue")

