Is this wavelet transform implementation correct?

user2464424 picture user2464424 · Nov 27, 2013 · Viewed 8.6k times · Source

I am searching for alternatives to the FFT to create a spectrogram analyser in python. I heard that the wavelet transform is faster and provides better time accuracy than the short time FFT. I went in this wikipedia article that features the Haar wavelet transform implementation in Java:

https://en.wikipedia.org/wiki/Discrete_wavelet_transform#Code_example

I brutally converted it to python but I have no idea if the values I'm getting are correct. Can someone confirm?

from math import *

N = 8
res = [sin(k) for k in xrange(N)]

for k in xrange(N):
    print res[k]

print

def discreteHaarWaveletTransform(x):
    N = len(x)
    output = [0.0]*N

    length = N >> 1
    while True:
        for i in xrange(0,length):
            summ = x[i * 2] + x[i * 2 + 1]
            difference = x[i * 2] - x[i * 2 + 1]
            output[i] = summ
            output[length + i] = difference

        if length == 1:
            return output

        #Swap arrays to do next iteration
        #System.arraycopy(output, 0, x, 0, length << 1)
        x = output[:length << 1]

        length >>= 1


res = discreteHaarWaveletTransform(res)

for k in xrange(N):
    print res[k]

Result:

0.0
0.841470984808
0.909297426826
0.14112000806
-0.756802495308
-0.958924274663
-0.279415498199
0.656986598719

0.553732750242
3.23004408914
-0.208946450078
-2.09329787049
-0.841470984808
0.768177418766
0.202121779355
-0.936402096918

Answer

lennon310 picture lennon310 · Nov 27, 2013

I don't find anything wrong. You can also check it by comparing your result to the result from Pywavelet package. There is also an example on the implementation of haar wavelet with Pywavelet.