Thursday, August 27, 2020

Filtering Complex Data with R

Filtering

Base R has a function filter that can perform moving average (MA) or filters (AR). But it cannot do both at the same time; it cannot do an autoregresive ARMA filter. It also only works on real data. The filter function in the signal package can perform ARMA filters, but is is built on the filter function in the base package. So, it also cannot filter complex data. Below is an example of filtering some data with the filter from the signal package. We are using a 6 sample MA filter as specified by the b=rep(1/6,6).

N <- 64
x <- rnorm(N)
b <- rep(1/6,6)
a <- 1
y <- signal::filter(b,a,x)

The figure below has two plots. The blue circles are the Gaussian samples. The green circles are the filtered Gaussian samples. The filtered data has less variance.

Complex Data

In engineering the most common kind of complex data is the circularly symmetric gaussian noise. The circularly symmetric part means that the real and complex part are independent and identically distributed. I described the makeCG function in another post, but as you can see the real part and the imaginary part are made using separate calls to the rnorm function.

makeCG <- function(N,v=1) {(sqrt(v/2))*rnorm(N) + (sqrt(v/2))*1i*rnorm(N)}

The function filterComplex filters real or complex data. The function inputs the MA parameters b and the AR parameters a, and the data x. If the data is complex, it makes two filter calls: one with the real part and one with the imaginary part. If the data is real it make one call.

filterComplex <- function(b, a, x) {
  if (is.complex(x)) {
    y <- signal::filter(b,a,Re(x)) + 1i*signal::filter(b,a,Im(x))
  } else y <- signal::filter(b,a,x)
  return(y)
}

Here we simulate complex Gaussian data and use the function filterComplex to filter it.

N <- 64
x <- makeCG(N)
b <- rep(1/6,6)
a <- 1
y <- filterComplex(b,a,x)

The figure below has two plots. The blue circles are the real part of the complex Gaussian samples. The green circles are the real part of filtered complex Gaussian samples. As expected, the filtered data has less variance.

Now the imaginary part. The blue circles are the imaginary part of the complex Gaussian samples. The green circles are the imaginary part of filtered complex Gaussian samples.

November Fog