Skip to content

Instantly share code, notes, and snippets.

@arturaugusto
Last active August 29, 2015 14:00
Show Gist options
  • Select an option

  • Save arturaugusto/11378956 to your computer and use it in GitHub Desktop.

Select an option

Save arturaugusto/11378956 to your computer and use it in GitHub Desktop.
waveProc <- function(y, samples, sample_size, freq){
options(digits=10)
require("signal")
meas <- matrix(nrow = 50, ncol = 0)
dimnames(meas) = list(c(seq(1,50)), c() )
mag_list = c()
samples <- NROW(y)
n <- NROW(y)-1
T <- as.numeric(sample_size)*as.numeric(samples)
dt <- T / n
t <- seq(0,T,by=dt)
#FOURIER WORK
Y <- fft(y)
im <- Im(Y)
re <- Re(Y)
mag <- abs(Y)
mag <- mag/(max(mag))
mag_list <- c(mag_list, mag)
mag_matrix <- matrix(mag_list, nrow=NROW(y), ncol=1)
mag <- apply(mag_matrix,1,mean)
#FREQ ARRAY
samp_freq <- 1/as.numeric(sample_size)
nyq_freq <- (samp_freq/2)
bin_resolution <- nyq_freq / (length(Y)/2)
f <- seq(0,samp_freq,bin_resolution)
#detecta fundamental
limite <- ifelse(mag > 0.7,mag,0)
limite_diff <- diff(limite)
ff_id <- which(limite_diff < 0)[1]
f_fundamental <- f[ff_id]
bins <- seq(f_fundamental,f_fundamental*50,by=f_fundamental)
meas_series <- sapply(bins,
function(b){
b_id <- which( round(b) == round(f) )
mag[b_id]
})
meas <- cbind(meas, meas_series)
X <- matrix(1, NROW(y), 2)
X[,1] <- cos(2*pi*bins[1]*t);
X[,2] <- sin(2*pi*bins[1]*t);
beta <- lm(y ~ X)
phase_ini <- (atan2(beta$coefficients[[2]],beta$coefficients[[3]])*180)/pi
get_phase <- function (freq, offset){
X = matrix(1, NROW(y), 2)
X[,1] <- cos(2*pi*freq*t+offset);
X[,2] <- sin(2*pi*freq*t+offset);
beta <- lm(y ~ X)
ampt <- sqrt(beta$coefficients[[2]]^2+beta$coefficients[[3]]^2)
phase <- ((atan2(beta$coefficients[[2]],beta$coefficients[[3]])*180)/pi)
return(phase)
}
offset_angle <- get_phase(freq, 0)
offset_correction <- (offset_angle*pi)/180
out_ampt <- meas_series[1:40]
out_phase <- sapply(seq(1,40),
function(n){
get_phase(freq*n, offset_correction*n)
})
return(list(amplitude=out_ampt, phase=out_phase))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment