Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd function used for signal processing?

Ηello! I hope this is an acceptable sort of question.

Going through some code used for signal processing I came upon an odd function:

let kInd = (k1, pow) => {

  let k2 = 0;
  let k3 = 0;

  for (let i = 0; i < pow; i++) {
    k3 = k1 >> 1;
    k2 = 2 * (k2 - k3) + k1;
    k1 = k3;
  }

  return k2;

};

This function is called towards the end of a fourier transform calculation to swap indexes in the real+imaginary pair of arrays:

let fft = samples => {

  let pow = Math.log2(samples.length); // `samples.length` is expected to be 2^int

  // ... a bunch of code to generate `rBuff` and `iBuff` arrays representing 
  // real and imaginary components of fourier values

  // Now make use of `kInd`; conditionally swap some indexes in `rBuff` and `iBuff`:
  for (let i = 0; i < rBuff.length; i++) {
    let k = kInd(i, pow);
    if (k >= i) continue;
    [ rBuff[i], rBuff[k] ] = [ rBuff[k], rBuff[i] ];
    [ iBuff[i], iBuff[k] ] = [ iBuff[k], iBuff[i] ];
  }

  // ... A bit of code to convert to power spectrum and return result

};

My question is: what the heck is kInd doing? I've run it to output some example values; it looks like it outputs sums of powers of 2 in a nearly random order as its k1 parameter increments. Small changes to kInd lead to completely wrong results from fft.

Thanks!

(Note: let me know if more code would help. Trying to keep this as brief as possible for the reader's sake!)

like image 395
Gershom Maes Avatar asked Sep 18 '18 06:09

Gershom Maes


1 Answers

This implements the butterfly operation of the FFT algorithm.

For example, running...

console.log([0,1,2,3,4,5,6,7].map(i => kInd(i, 3)))

...prints...

[ 0, 4, 2, 6, 1, 5, 3, 7 ]

... which is the mapping in the diagram here:

http://www.alwayslearn.com/DFT%20and%20FFT%20Tutorial/DFTandFFT_FFT_Butterfly_8_Input.html

like image 86
Martin Stone Avatar answered Oct 21 '22 14:10

Martin Stone