PyWavelets / pywt

PyWavelets - Wavelet Transforms in Python
http://pywavelets.readthedocs.org
MIT License
2.06k stars 479 forks source link

pywt.swt yields unexpected results #767

Open M3rano opened 2 months ago

M3rano commented 2 months ago

When I use the pywt.swt function for a level 1 transform I get different results than when doing a manual convolution with the low pass and high pass filters using wavelet.dec_lo and wavelet.dec_hi. I do not understand why. Here is an example:

import numpy as np
from scipy.signal import convolve

# Example signal
signal = np.array([1, 2, 3, 4, 5, 6, 7, 8])

# Perform Stationary Wavelet Transform (SWT)
wavelet = pywt.Wavelet('db2')
coeffs = pywt.swt(signal, wavelet, level=1)

# Print the coefficients for each level
for i, (cA, cD) in enumerate(coeffs, 1):
    print(f"Level {i}:")
    print(f"  Approximation coefficients: {cA}")
    print(f"  Detail coefficients: {cD}")

# Obtain the decomposition filters
Lo_D = wavelet.dec_lo  # Low-pass filter
Hi_D = wavelet.dec_hi  # High-pass filter

# Convolve with level 1 filters
approx_level1 = convolve(signal, Lo_D, mode='same')
detail_level1 = convolve(signal, Hi_D, mode='same')

print("Level 1 Approximation:", approx_level1)
print("Level 1 Detail:", detail_level1)

Results:

Level 1:
  Approximation coefficients: [ 4.76027878  2.31078903  3.7250026   5.13921616  6.55342972  7.96764328
 10.41713303 10.03819564]
  Detail coefficients: [-1.03527618e+00  1.66533454e-16  1.11022302e-16  3.33066907e-16
  4.44089210e-16  2.22044605e-16  3.86370331e+00 -2.82842712e+00]
Level 1 Approximation: [-0.03467518  0.89657547  2.31078903  3.7250026   5.13921616  6.55342972
  7.96764328 10.54654255]
Level 1 Detail: [-1.29409523e-01  0.00000000e+00  2.22044605e-16  0.00000000e+00
  4.44089210e-16  4.44089210e-16  4.44089210e-16  4.34666622e+00]

I appreciate any help. Thank you.

M3rano commented 1 month ago

With the approximation coefficients it just seems to be a problem at the edges which I could fix by padding the array but I do not understand what happens with the detail coefficients.