Py Wavelets
Py Wavelets
Py Wavelets
Release 1.1.0.dev0+399196a
1 Main features 3
2 Getting help 5
3 License 7
4 Citing 9
5 Contents 11
Bibliography 115
Index 117
i
ii
PyWavelets Documentation, Release 1.1.0.dev0+399196a
PyWavelets is open source wavelet transform software for Python. It combines a simple high level interface with low
level C and Cython performance.
PyWavelets is very easy to use and get started with. Just install the package, open the Python interactive shell and
type:
import numpy as np
import matplotlib.pyplot as plt
import pywt
import pywt.data
# Load image
original = pywt.data.camera()
fig.tight_layout()
plt.show()
Contents 1
PyWavelets Documentation, Release 1.1.0.dev0+399196a
2 Contents
CHAPTER 1
Main features
3
PyWavelets Documentation, Release 1.1.0.dev0+399196a
Getting help
Use GitHub Issues, StackOverflow, or the PyWavelets discussions group to post your comments or questions.
5
PyWavelets Documentation, Release 1.1.0.dev0+399196a
License
PyWavelets is a free Open Source software released under the MIT license.
7
PyWavelets Documentation, Release 1.1.0.dev0+399196a
8 Chapter 3. License
CHAPTER 4
Citing
If you use PyWavelets in a scientific publication, we would appreciate citations of the project via the following JOSS
publication:
Gregory R. Lee, Ralf Gommers, Filip Wasilewski, Kai Wohlfahrt, Aaron O’Leary (2019). PyWavelets: A
Python package for wavelet analysis. Journal of Open Source Software, 4(36), 1237, https://doi.org/10.
21105/joss.01237.
Specific releases can also be cited via Zenodo. The DOI below will correspond to the most recent release. DOIs for
past versions can be found by following the link in the badge below to Zenodo:
9
PyWavelets Documentation, Release 1.1.0.dev0+399196a
10 Chapter 4. Citing
CHAPTER 5
Contents
5.1 Installing
The latest release, including binary packages for Windows, macOS and Linux, is available for download from PyPI.
You can also find source releases at the Releases Page.
You can install PyWavelets with:
Users of the Anaconda Python distribution may wish to obtain pre-built Windows, Intel Linux or macOS / OSX
binaries from the main or conda-forge channel:
Several Linux distributions have their own packages for PyWavelets, but these tend to be moderately out of date.
Query your Linux package manager tool for python-pywavelets, python-wavelets, python-pywt or a
similar package name.
pip install .
11
PyWavelets Documentation, Release 1.1.0.dev0+399196a
• Cython >= 0.23.5 (if installing from git, not from a PyPI source release)
To run all the tests for PyWavelets, you will also need to install the Matplotlib package. If SciPy is available, FFT-based
continuous wavelet transforms will use the FFT implementation from SciPy instead of NumPy.
See also:
Development guide section contains more information on building and installing from source code.
5.2.1 Wavelets
Wavelet families()
pywt.families(short=True)
Returns a list of available built-in wavelet families.
Currently the built-in families are:
• Haar (haar)
• Daubechies (db)
• Symlets (sym)
• Coiflets (coif)
• Biorthogonal (bior)
• Reverse biorthogonal (rbio)
• “Discrete” FIR approximation of Meyer wavelet (dmey)
• Gaussian wavelets (gaus)
• Mexican hat wavelet (mexh)
• Morlet wavelet (morl)
• Complex Gaussian wavelets (cgau)
• Shannon wavelets (shan)
• Frequency B-Spline wavelets (fbsp)
• Complex Morlet wavelets (cmor)
Parameters
short [bool, optional] Use short names (default: True).
Returns
families [list] List of available wavelet families.
Examples
12 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
>>> pywt.families(short=False)
['Haar', 'Daubechies', 'Symlets', 'Coiflets', 'Biorthogonal', 'Reverse
˓→biorthogonal', 'Discrete Meyer (FIR Approximation)', 'Gaussian', 'Mexican hat
pywt.wavelist(family=None, kind=’all’)
Returns list of available wavelet names for the given family name.
Parameters
family [str, optional] Short family name. If the family name is None (default) then names of
all the built-in wavelets are returned. Otherwise the function returns names of wavelets that
belong to the given family. Valid names are:
kind [{‘all’, ‘continuous’, ‘discrete’}, optional] Whether to return only wavelet names of dis-
crete or continuous wavelets, or all wavelets. Default is 'all'. Ignored if family is
specified.
Returns
wavelist [list of str] List of available wavelet names.
Examples
Custom discrete wavelets are also supported through the Wavelet object constructor as described below.
Wavelet object
The filter bank object can be a list of four filters coefficients or an object with filter_bank attribute, which
returns a list of such filters in the following order:
Wavelet objects can also be used as a base filter banks. See section on using custom wavelets for more informa-
tion.
Example:
name
Wavelet name.
short_name
Short wavelet name.
dec_lo
Decomposition filter values.
dec_hi
Decomposition filter values.
rec_lo
Reconstruction filter values.
rec_hi
Reconstruction filter values.
dec_len
Decomposition filter length.
rec_len
Reconstruction filter length.
filter_bank
Returns filters list for the current wavelet in the following order:
inverse_filter_bank
Returns list of reverse wavelet filters coefficients. The mapping from the filter_coeffs list is as
follows:
short_family_name
Wavelet short family name
family_name
Wavelet family name
orthogonal
Set if wavelet is orthogonal
biorthogonal
Set if wavelet is biorthogonal
symmetry
asymmetric, near symmetric, symmetric
14 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
vanishing_moments_psi
Number of vanishing moments for the wavelet function
vanishing_moments_phi
Number of vanishing moments for the scaling function
Example:
Wavelet.wavefun(level)
Changed in version 0.2: The time (space) localisation of approximation function points was added.
The wavefun() method can be used to calculate approximations of scaling function (phi) and wavelet func-
tion (psi) at the given level of refinement.
For orthogonal wavelets returns approximations of scaling function and wavelet function with corresponding
x-grid coordinates:
Example:
For other (biorthogonal but not orthogonal) wavelets returns approximations of scaling and wavelet
function both for decomposition and reconstruction and corresponding x-grid coordinates:
Example:
See also:
You can find live examples of wavefun() usage and images of all the built-in wavelets on the Wavelet Proper-
ties Browser page. However, this website is no longer actively maintained and does not include every wavelet
present in PyWavelets. The precision of the wavelet coefficients at that site is also lower than those included in
PyWavelets.
PyWavelets comes with a long list of the most popular wavelets built-in and ready to use. If you need to use a
specific wavelet which is not included in the list it is very easy to do so. Just pass a list of four filters or an object with
a filter_bank attribute as a filter_bank argument to the Wavelet constructor.
The filters list, either in a form of a simple Python list or returned via the filter_bank attribute, must be in the
following order:
• lowpass decomposition filter
• highpass decomposition filter
• lowpass reconstruction filter
• highpass reconstruction filter
just as for the filter_bank attribute of the Wavelet class.
The Wavelet object created in this way is a standard Wavelet instance.
The following example illustrates the way of creating custom Wavelet objects from plain Python lists of filter coeffi-
cients and a filter bank-like object.
Example:
ContinuousWavelet object
class pywt.ContinuousWavelet(name)
Describes properties of a continuous wavelet identified by the specified wavelet name. In order to use a built-in
wavelet the name parameter must be a valid wavelet name from the pywt.wavelist() list.
Parameters name – Wavelet name
Example:
16 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
name
Continuous Wavelet name.
short_family_name
Wavelet short family name
family_name
Wavelet family name
orthogonal
Set if wavelet is orthogonal
biorthogonal
Set if wavelet is biorthogonal
complex_cwt
Returns if wavelet is complex
lower_bound
Set the lower bound of the effective support
upper_bound
Set the upper bound of the effective support
center_frequency
Set the center frequency for the shan, fbsp and cmor wavelets
bandwidth_frequency
Set the bandwidth frequency for the shan, fbsp and cmor wavelets
fbsp_order
Set the order for the fbsp wavelet
symmetry
asymmetric, near symmetric, symmetric, anti-symmetric
Example:
[psi, x] = wavelet.wavefun(level)
Example:
Because the most common and practical way of representing digital signals in computer science is with finite arrays
of values, some extrapolation of the input data has to be performed in order to extend the signal before computing the
Discrete Wavelet Transform using the cascading filter banks algorithm.
Depending on the extrapolation method, significant artifacts at the signal’s borders can be introduced during that
process, which in turn may lead to inaccurate computations of the DWT at the signal’s ends.
PyWavelets provides several methods of signal extrapolation that can be used to minimize this negative effect:
• zero - zero-padding - signal is extended by adding zero samples:
18 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
• reflect - reflect-padding - signal is extended by reflecting samples. This mode is also known as
whole-sample symmetric.:
• smooth - smooth-padding - signal is extended according to the first derivatives calculated on the
edges (straight line)
• antisymmetric - anti-symmetric padding - signal is extended by mirroring and negating sam-
ples. This mode is also known as half-sample anti-symmetric:
... (2*x1 - x3) (2*x1 - x2) | x1 x2 ... xn | (2*xn - xn-1) (2*xn - xn-2)
˓→...
DWT performed for these extension modes is slightly redundant, but ensures perfect reconstruction. To receive the
smallest possible number of coefficients, computations can be performed with the periodization mode:
• periodization - periodization - is like periodic-padding but gives the smallest possible number
of decomposition coefficients. IDWT must be performed with the same mode.
Example:
The following figure illustrates how a short signal (red) gets extended (black) outside of its original extent. Note that
periodization first extends the signal to an even length prior to using periodic boundary conditions.
2 2 2
0 10 20 30 40 0 10 20 30 40 0 10 20 30 40
antisymmetric antireflect periodization
5 10
5 4
0
0
2
5 5
0 10 20 30 40 0 10 20 30 40 0 20 40
smooth constant zero
0 4
4
10 2
2
20 0
0 10 20 30 40 0 10 20 30 40 0 10 20 30 40
Notice that you can use any of the following ways of passing wavelet and mode parameters:
Note: Extending data in context of PyWavelets does not mean reallocation of the data in the computer’s physical
20 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
memory and copying values, but rather computing the extra values only when they are needed. This feature saves
extra memory and CPU resources and helps to avoid page swapping when handling relatively big data arrays on
computers with low physical memory.
Naming Conventions
The correspondence between PyWavelets edge modes and the extension modes available in Matlab’s dwtmode and
numpy’s pad are tabulated here for reference.
Notes
The performance of padding in dimensions > 1 may be substantially slower for modes 'smooth' and
'antisymmetric' as these modes are not supported efficiently by the underlying numpy.pad() func-
tion.
Note that the behavior of the 'constant' mode here follows the PyWavelets convention which is different
from NumPy (it is equivalent to mode='edge' in numpy.pad()).
Pywavelets provides a function, pad(), that operate like numpy.pad(), but supporting the PyWavelets signal
extension modes discussed above. For efficiency, the DWT routines in PyWavelets do not expclitly create padded
signals using this function. It can be used to manually prepad signals to reduce boundary effects in functions such as
cwt() and swt() that do not currently support all of these signal extension modes.
Wavelet transform has recently become a very popular when it comes to analysis, de-noising and compression of sig-
nals and images. This section describes functions used to perform single- and multilevel Discrete Wavelet Transforms.
Notes
Length of coefficients arrays depends on the selected mode. For all modes except periodization:
len(cA) == len(cD) == floor((len(data) + wavelet.dec_len - 1) / 2)
For periodization mode (“per”):
len(cA) == len(cD) == ceil(len(data) / 2)
Examples
See the signal extension modes section for the list of available options and the dwt_coeff_len() function for
information on getting the expected result length.
The transform can be performed over one axis of multi-dimensional data. By default this is the last axis. For multi-
dimensional transforms see the 2D transforms section.
22 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
Examples
upcoef
pywt.dwt_max_level(data_len, filter_len)
Compute the maximum useful level of decomposition.
Parameters
data_len [int] Input data length.
filter_len [int, str or Wavelet] The wavelet filter length. Alternatively, the name of a discrete
wavelet or a Wavelet object can be specified.
Returns
max_level [int] Maximum level.
Notes
The rational for the choice of levels is the maximum level where at least one coefficient in the output is un-
corrupted by edge effects caused by signal extension. Put another way, decomposition stops when the signal
becomes shorter than the FIR filter length for a given wavelet. This corresponds to:
⌊︂ (︂ )︂⌋︂
data_len
max_level = log2
filter_len − 1
Examples
24 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
Returns
level [int] Maximum level.
Notes
Examples
Notes
Based on the given input data length (data_len), wavelet decomposition filter length (filter_len) and signal
extension mode, the dwt_coeff_len() function calculates the length of the resulting coefficients arrays that would
be created while performing dwt() transform.
filter_len can be either an int or Wavelet object for convenience.
cA [array_like or None] Approximation coefficients. If None, will be set to array of zeros with
same shape as cD.
cD [array_like or None] Detail coefficients. If None, will be set to array of zeros with same
shape as cA.
wavelet [Wavelet object or name] Wavelet to use
mode [str, optional (default: ‘symmetric’)] Signal extension mode, see Modes.
axis: int, optional Axis over which to compute the inverse DWT. If not given, the last axis is
used.
Returns
rec: array_like Single level reconstruction of signal from given coefficients.
Examples
One of the neat features of idwt is that one of the cA and cD arguments can be set to None. In that situation
the reconstruction will be performed using only the other one. Mathematically speaking, this is equivalent to
passing a zero-filled array as one of the arguments.
Notes
It may sometimes be desired to run waverec with some sets of coefficients omitted. This can best be done by
setting the corresponding arrays to zero arrays of matching shape and dtype. Explicitly removing list entries or
setting them to None is not supported.
Specifically, to ignore detail coefficients at level 2, one could do:
26 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
coeffs[-2] == np.zeros_like(coeffs[-2])
Examples
downcoef
Examples
There are a number of different ways a wavelet decomposition can be performed for multiresolution analysis of n-
dimensional data. Here we will review the three approaches currently implemented in PyWavelets. 2D cases are
illustrated, but each of the approaches extends to the n-dimensional case in a straightforward manner.
The most common approach to the multilevel discrete wavelet transform involves further decomposition of only the
approximation subband at each subsequent level. This is also sometimes referred to as the Mallat decomposition
[Mall89]. In 2D, the discrete wavelet transform produces four sets of coefficients corresponding to the four possible
compinations of the wavelet decomposition filters over the two separate axes. (In n-dimensions, there are 2**n sets
of coefficients). For subsequent levels of decomposition, only the approximation coefficients (the lowpass subband)
are further decomposed.
In PyWavelets, this decomposition is implemented for n-dimensional data by wavedecn() and the inverse by
waverecn(). 1D and 2D versions of these routines also exist. It is illustrated in the figure below. The top row
indicates the coefficient names as used by wavedec2() after each level of decomposition. The bottom row shows
wavelet coefficients for the camerman image (with each subband independently normalized for easier visualization).
import numpy as np
import pywt
from matplotlib import pyplot as plt
from pywt._doc_utils import wavedec2_keys, draw_2d_wp_basis
x = pywt.data.camera().astype(np.float32)
shape = x.shape
plt.tight_layout()
plt.show()
It can be seen that many of the coefficients are near zero (gray). This ability of the wavelet transform to sparsely
represent natural images is a key property that makes it desirable in applications such as image compression and
restoration.
28 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
v d v d v d
An alternative decomposition results in first fully decomposing one axis of the data prior to moving onto each ad-
ditional axis in turn. This is illustrated for the 2D case in the upper right panel of the figure below. This approach
has a factor of two higher computational cost as compared to the Mallat approach, but has advantages in compactly
representing anisotropic data. A demo of this is available).
This form of the DWT is also sometimes referred to as the tensor wavelet transform or the hyperbolic wavelet
transform. In PyWavelets it is implemented for n-dimensional data by fswavedecn() and the inverse by
fswaverecn().
Another possible choice is to apply additional levels of decomposition to all wavelet subbands from the first level as
opposed to only the approximation subband. This is known as the wavelet packet transform and is illustrated in 2D in
the lower left panel of the figure. It is also possible to only perform any subset of the decompositions, resulting in a
wide number of potential wavelet packet bases. An arbitrary example is shown in the lower right panel of the figure
below.
A further description is available in the wavelet packet documentation.
For the wavelet packets, the plots below use “natural” ordering for simplicity, but this does not directly match the
“frequency” ordering for these wavelet packets. It is possible to rearrange the coefficients into frequency ordering (see
the get_level method of WaveletPacket2D and [Wick94] for more details).
from itertools import product
import numpy as np
from matplotlib import pyplot as plt
from pywt._doc_utils import (wavedec_keys, wavedec2_keys, draw_2d_wp_basis,
draw_2d_fswavedecn_basis)
if False:
fig, axes = plt.subplots(1, 4, figsize=[16, 4])
axes = axes.ravel()
else:
fig, axes = plt.subplots(2, 2, figsize=[8, 8])
axes = axes.ravel()
plt.tight_layout()
plt.show()
References
30 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
ah
h
av ad ('ad', 'ad') ('d', 'ad')
ah
h
ad
vh
d
vv vd
Returns
(cA, (cH, cV, cD)) [tuple] Approximation, horizontal detail, vertical detail and diagonal detail
coefficients respectively. Horizontal refers to array axis 0 (or axes[0] for user-specified
axes).
Examples
The relation to the other common data layout where all the approximation and details coefficients are stored in one big
2D array is as follows:
-------------------
| | |
| cA(LL) | cH(LH) |
| | |
(cA, (cH, cV, cD)) <---> -------------------
| | |
| cV(HL) | cD(HH) |
| | |
-------------------
PyWavelets does not follow this pattern because of pure practical reasons of simple access to particular type of the
output coefficients.
32 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
Examples
Examples
Returns
2D array of reconstructed data.
Notes
It may sometimes be desired to run waverec2 with some sets of coefficients omitted. This can best be done
by setting the corresponding arrays to zero arrays of matching shape and dtype. Explicitly removing list or tuple
entries or setting them to None is not supported.
Specifically, to ignore all detail coefficients at level 2, one could do:
coeffs[-2] == tuple([np.zeros_like(v) for v in coeffs[-2]])
Examples
2D coordinate conventions
The labels for “horizontal” and “vertical” used by dwt2 and idwt2 follow the common mathematical convention
that coordinate axis 0 is horizontal while axis 1 is vertical:
dwt2, idwt2 convention
----------------------
axis 1 ^
|
|
|
(continues on next page)
34 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
Note that this is different from another common convention used in computer graphics and image processing (e.g. by
matplotlib’s imshow and functions in scikit-image). In those packages axis 0 is a vertical axis and axis 1 is
horizontal as follows:
imshow convention
-------------------
axis 1
|--------->
|
|
|
axis 0 v
For user-specified axes, the order of the characters in the dictionary keys map to the spec-
ified axes.
36 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
where the order of the characters in each key map to the specified axes.
Examples
Returns
nD array of reconstructed data.
Notes
It may sometimes be desired to run waverecn with some sets of coefficients omitted. This can best be done
by setting the corresponding arrays to zero arrays of matching shape and dtype. Explicitly removing list or
Examples
38 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
Returns
fswavedecn_result [FswavedecnResult object] Contains the wavelet coefficients, slice objects
to allow obtaining the coefficients per detail or approximation level, and more. See
FswavedecnResult for details.
See also:
Notes
This transformation has been variously referred to as the (fully) separable wavelet transform (e.g. refs [1],
[3]), the tensor-product wavelet ([2]) or the hyperbolic wavelet transform ([4]). It is well suited to data with
anisotropic smoothness.
In [2] it was demonstrated that fully separable transform performs at least as well as the DWT for image com-
pression. Computation time is a factor 2 larger than that for the DWT.
References
Examples
pywt.fswaverecn(fswavedecn_result)
Fully Separable Inverse Wavelet Reconstruction.
Parameters
fswavedecn_result [FswavedecnResult object] FswavedecnResult object from fswavedecn.
Returns
reconstructed [ndarray] Array of reconstructed data.
See also:
Notes
This transformation has been variously referred to as the (fully) separable wavelet transform (e.g. refs [1],
[3]), the tensor-product wavelet ([2]) or the hyperbolic wavelet transform ([4]). It is well suited to data with
anisotropic smoothness.
In [2] it was demonstrated that the fully separable transform performs at least as well as the DWT for image
compression. Computation time is a factor 2 larger than that for the DWT.
References
Methods
Convenience routines are available for converting the outputs of the multilevel dwt functions (wavedec, wavedec2
and wavedecn) to and from a single, concatenated coefficient array.
40 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
Notes
+---------------+---------------+-------------------------------+
| | | |
| c[0] | c[1]['da'] | |
| | | |
+---------------+---------------+ c[2]['da'] |
| | | |
| c[1]['ad'] | c[1]['dd'] | |
| | | |
+---------------+---------------+ ------------------------------+
| | |
| | |
| | |
| c[2]['ad'] | c[2]['dd'] |
| | |
| | |
| | |
+-------------------------------+-------------------------------+
Examples
Notes
A single large array containing all coefficients will have subsets stored, into a waverecn list, c, as indicated
below:
+---------------+---------------+-------------------------------+
| | | |
| c[0] | c[1]['da'] | |
| | | |
+---------------+---------------+ c[2]['da'] |
| | | |
| c[1]['ad'] | c[1]['dd'] | |
| | | |
+---------------+---------------+ ------------------------------+
| | |
| | |
| | |
| c[2]['ad'] | c[2]['dd'] |
| | |
| | |
| | |
+-------------------------------+-------------------------------+
Examples
42 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
pywt.ravel_coeffs(coeffs, axes=None)
Ravel a set of multilevel wavelet coefficients into a single 1D array.
Parameters
coeffs [array-like] A list of multilevel wavelet coefficients as returned by wavedec,
wavedec2 or wavedecn. This function is also compatible with the output of swt, swt2
and swtn if those functions were called with trim_approx=True.
axes [sequence of ints, optional] Axes over which the DWT that created coeffs was per-
formed. The default value of None corresponds to all axes.
Returns
coeff_arr [array-like] Wavelet transform coefficient array. All coefficients have been concate-
nated into a single array.
coeff_slices [list] List of slices corresponding to each coefficient. As a 2D example,
coeff_arr[coeff_slices[1]['dd']] would extract the first level detail coeffi-
cients from coeff_arr.
coeff_shapes [list] List of shapes corresponding to each coefficient. For example, in 2D,
coeff_shapes[1]['dd'] would contain the original shape of the first level detail co-
efficients array.
See also:
Examples
Examples
pywt.wavedecn_size(shapes)
Compute the total number of wavedecn coefficients.
Parameters
shapes [list of coefficient shapes] A set of coefficient shapes as returned by
wavedecn_shapes. Alternatively, the user can specify a set of coefficients as
returned by wavedecn.
Returns
size [int] The total number of coefficients.
Examples
44 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
Examples
Stationary Wavelet Transform (SWT), also known as Undecimated wavelet transform or Algorithme à trous is a
translation-invariance modification of the Discrete Wavelet Transform that does not decimate coefficients at every
transformation level.
Multilevel 1D swt
trim_approx [bool, optional] If True, approximation coefficients at the final level are retained.
norm [bool, optional] If True, transform is normalized so that the energy of the coefficients will
be equal to the energy of data. In other words, np.linalg.norm(data.ravel())
will equal the norm of the concatenated transform coefficients when trim_approx is
True.
Returns
coeffs [list] List of approximation and details coefficients pairs in order similar to wavedec
function:
Notes
The implementation here follows the “algorithm a-trous” and requires that the signal length along the trans-
formed axis be a multiple of 2**level. If this is not the case, the user should pad up to an appropriate size
using a function such as numpy.pad.
A primary benefit of this transform in comparison to its decimated counterpart (pywt.wavedecn), is that it
is shift-invariant. This comes at cost of redundancy in the transform (the size of the output coefficients is larger
than the input).
When the following three conditions are true:
1. The wavelet is orthogonal
2. swt is called with norm=True
3. swt is called with trim_approx=True
the transform has the following additional properties that may be desirable in applications:
1. energy is conserved
2. variance is partitioned across scales
When used with norm=True, this transform is closely related to the multiple-overlap DWT (MODWT) as
popularized for time-series analysis, although the underlying implementation is slightly different from the one
published in [1]. Specifically, the implementation used here requires a signal that is a multiple of 2**level
in length.
References
[1]
46 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
Multilevel 2D swt2
[
(cA_m+level,
(cH_m+level, cV_m+level, cD_m+level)
),
...,
(cA_m+1,
(cH_m+1, cV_m+1, cD_m+1)
),
(cA_m,
(cH_m, cV_m, cD_m)
)
]
[
cA_m+level,
(cH_m+level, cV_m+level, cD_m+level),
...,
(cH_m+1, cV_m+1, cD_m+1),
(cH_m, cV_m, cD_m),
]
Notes
The implementation here follows the “algorithm a-trous” and requires that the signal length along the trans-
formed axes be a multiple of 2**level. If this is not the case, the user should pad up to an appropriate size
using a function such as numpy.pad.
A primary benefit of this transform in comparison to its decimated counterpart (pywt.wavedecn), is that it
is shift-invariant. This comes at cost of redundancy in the transform (the size of the output coefficients is larger
than the input).
When the following three conditions are true:
1. The wavelet is orthogonal
2. swt2 is called with norm=True
3. swt2 is called with trim_approx=True
the transform has the following additional properties that may be desirable in applications:
1. energy is conserved
2. variance is partitioned across scales
48 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
For user-specified axes, the order of the characters in the dictionary keys map to the spec-
ified axes.
If trim_approx is True, the first element of the list contains the array of approximation
coefficients from the final level of decomposition, while the remaining coefficient dictionar-
ies contain only detail coefficients. This matches the behavior of pywt.wavedecn.
Notes
The implementation here follows the “algorithm a-trous” and requires that the signal length along the trans-
formed axes be a multiple of 2**level. If this is not the case, the user should pad up to an appropriate size
using a function such as numpy.pad.
A primary benefit of this transform in comparison to its decimated counterpart (pywt.wavedecn), is that it
is shift-invariant. This comes at cost of redundancy in the transform (the size of the output coefficients is larger
than the input).
When the following three conditions are true:
1. The wavelet is orthogonal
2. swtn is called with norm=True
3. swtn is called with trim_approx=True
the transform has the following additional properties that may be desirable in applications:
1. energy is conserved
2. variance is partitioned across scales
pywt.swt_max_level(input_len)
Calculates the maximum level of Stationary Wavelet Transform for data of given length.
Parameters
input_len [int] Input data length.
Returns
max_level [int] Maximum level of Stationary Wavelet Transform for data of given length.
Notes
For the current implementation of the stationary wavelet transform, this corresponds to the number of times
input_len is evenly divisible by two. In other words, for an n-level transform, the signal length must be a
multiple of 2**n. numpy.pad can be used to pad a signal up to an appropriate length as needed.
Multilevel 1D iswt
Examples
Multilevel 2D iswt2
[
(cA_n,
(cH_n, cV_n, cD_n)
),
...,
(cA_2,
(cH_2, cV_2, cD_2)
),
(cA_1,
(cH_1, cV_1, cD_1)
)
]
50 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
wavelet [Wavelet object or name string, or 2-tuple of wavelets] Wavelet to use. This can also
be a 2-tuple of wavelets to apply per axis.
norm [bool, optional] Controls the normalization used by the inverse transform. This must be
set equal to the value that was used by pywt.swt2 to preserve the energy of a round-trip
transform.
Returns
2D array of reconstructed data.
Examples
Examples
class pywt.BaseNode
class pywt.Node(BaseNode)
class pywt.WaveletPacket(Node)
class pywt.Node2D(BaseNode)
class pywt.WaveletPacket2D(Node2D)
Note: The BaseNode is a base class for Node and Node2D. It should not be used directly unless creating a
new transformation type. It is included here to document the common interface of 1D and 2D node an wavelet
packet transform classes.
52 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
parent
Parent node. Used in tree navigation. None for root node.
wavelet
Wavelet used for decomposition and reconstruction. Inherited from parent node.
mode
Signal extension mode for the dwt() (dwt2()) and idwt() (idwt2()) decomposition and recon-
struction functions. Inherited from parent node.
level
Decomposition level of the current node. 0 for root (original data), 1 for the first decomposition level, etc.
path
Path string defining position of the node in the decomposition tree.
node_name
Node name describing data coefficients type of the current subnode.
See Node.node_name and Node2D.node_name.
maxlevel
Maximum allowed level of decomposition. Evaluated from parent or child nodes.
is_empty
Checks if data attribute is None.
has_any_subnode
Checks if node has any subnodes (is not a leaf node).
decompose()
Performs Discrete Wavelet Transform on the data and returns transform coefficients.
reconstruct([update=False ])
Performs Inverse Discrete Wavelet Transform on subnodes coefficients and returns reconstructed data for
the current level.
Parameters update – If set, the data attribute will be updated with the reconstructed value.
get_subnode(part[, decompose=True ])
Returns subnode or None (see decomposition flag description).
Parameters
• part – Subnode name
• decompose – If True and subnode does not exist, it will be created using coefficients
from the DWT decomposition of the current node.
__getitem__(path)
Used to access nodes in the decomposition tree by string path.
Parameters path – Path string composed from valid node names. See Node.node_name
and Node2D.node_name for node naming convention.
Similar to get_subnode() method with decompose=True, but can access nodes on any level in the
decomposition tree.
If node does not exist yet, it will be created by decomposition of its parent node.
__setitem__(path, data)
Used to set node or node’s data in the decomposition tree. Nodes are identified by string path.
Parameters
• path – Path string composed from valid node names. See Node.node_name and
Node2D.node_name for node naming convention.
• data – numeric array or BaseNode subclass.
__delitem__(path)
Used to delete node from the decomposition tree.
Parameters path – Path string composed from valid node names. See Node.node_name
and Node2D.node_name for node naming convention.
get_leaf_nodes([decompose=False ])
Traverses through the decomposition tree and collects leaf nodes (nodes without any subnodes).
Parameters decompose – If decompose is True, the method will try to decompose the tree
up to the maximum level.
walk(self, func[, args=()[, kwargs={}[, decompose=True ]]])
Traverses the decomposition tree and calls func(node, *args, **kwargs) on every node. If func
returns True, descending to subnodes will continue.
Parameters
• func – callable accepting BaseNode as the first param and optional positional and key-
word arguments:
• decompose – If decompose is True (default), the method will also try to decompose
the tree up to the maximum level.
Args arguments to pass to the func
Kwargs keyword arguments to pass to the func
walk_depth(self, func[, args=()[, kwargs={}[, decompose=False ]]])
Similar to walk() but traverses the tree in depth-first order.
Parameters
• func – callable accepting BaseNode as the first param and optional positional and key-
word arguments:
• decompose – If decompose is True, the method will also try to decompose the tree
up to the maximum level.
Args arguments to pass to the func
Kwargs keyword arguments to pass to the func
class pywt.Node(BaseNode)
class pywt.WaveletPacket(Node)
54 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
node_name
Node name describing data coefficients type of the current subnode.
For WaveletPacket case it is just as in dwt():
• a - approximation coefficients
• d - details coefficients
decompose()
See also:
class pywt.WaveletPacket(Node)
class pywt.Node2D(BaseNode)
class pywt.WaveletPacket2D(Node2D)
node_name
For WaveletPacket2D case it is just as in dwt2():
• a - approximation coefficients (LL)
• h - horizontal detail coefficients (LH)
• v - vertical detail coefficients (HL)
See also:
dwt2() for 2D Discrete Wavelet Transform output coefficients.
expand_2d_path(self, path):
class pywt.WaveletPacket2D(Node2D)
This section describes functions used to perform single continuous wavelet transforms.
56 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
sampling_period [float] Sampling period for the frequencies output (optional). The values
computed for coefs are independent of the choice of sampling_period (i.e. scales
is not scaled by the sampling period).
method [{‘conv’, ‘fft’}, optional]
The method used to compute the CWT. Can be any of:
• conv uses numpy.convolve.
• fft uses frequency domain convolution.
• auto uses automatic selection based on an estimate of the computational complexity
at each scale.
The conv method complexity is O(len(scale) * len(data)). The fft method
is O(N * log2(N)) with N = len(scale) + len(data) - 1. It is well suited
for large size signals but slightly slower than conv on small ones.
axis: int, optional Axis over which to compute the CWT. If not given, the last axis is used.
Returns
coefs [array_like] Continuous wavelet transform of the input signal for the given scales and
wavelet. The first axis of coefs corresponds to the scales. The remaining axes match the
shape of data.
frequencies [array_like] If the unit of sampling period are seconds and given, than frequencies
are in hertz. Otherwise, a sampling period of 1 is assumed.
Notes
Size of coefficients arrays depends on the length of the input array and the length of given scales.
Examples
A variety of continuous wavelets have been implemented. A list of the available wavelet names compatible with cwt
can be obtained by:
wavlist = pywt.wavelist(kind='continuous')
where the constant out front is a normalization factor so that the wavelet has unit energy.
Morlet Wavelet
The complex Morlet wavelet ("cmorB-C" with floating point values B, C) is given by:
1 𝑡2
𝜓(𝑡) = √ exp− 𝐵 expj2𝜋𝐶𝑡
𝜋𝐵
where 𝐵 is the bandwidth and 𝐶 is the center frequency.
The Gaussian wavelets ("gausP" where P is an integer between 1 and and 8) correspond to the Pth order derivatives
of the function:
2
𝜓(𝑡) = 𝐶 exp−𝑡
The complex Gaussian wavelets ("cgauP" where P is an integer between 1 and 8) correspond to the Pth order
derivatives of the function:
2
𝜓(𝑡) = 𝐶 exp−j𝑡 exp−𝑡
58 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
Shannon Wavelets
The Shannon wavelets ("shanB-C" with floating point values B and C) correspond to the following wavelets:
√ sin(𝜋𝐵𝑡)
𝜓(𝑡) = 𝐵 expj2𝜋𝐶𝑡
𝜋𝐵𝑡
where 𝐵 is the bandwidth and 𝐶 is the center frequency.
The frequency B-spline wavelets ("fpspM-B-C" with integer M and floating point B, C) correspond to the following
wavelets:
]︂𝑀
√ sin(𝜋𝐵 𝑀𝑡 )
[︂
𝜓(𝑡) = 𝐵 exp2j𝜋𝐶𝑡
𝜋𝐵 𝑀𝑡
where 𝑀 is the spline order, 𝐵 is the bandwidth and 𝐶 is the center frequency.
For each of the wavelets described below, the implementation in PyWavelets evaluates the wavelet function for 𝑡
over the range [wavelet.lower_bound, wavelet.upper_bound] (with default range [−8, 8]). scale
= 1 corresponds to the case where the extent of the wavelet is (wavelet.upper_bound - wavelet.
lower_bound + 1) samples of the digital signal being analyzed. Larger scales correspond to stretching of the
wavelet. For example, at scale=10 the wavelet is stretched by a factor of 10, making it sensitive to lower frequen-
cies in the signal.
To relate a given scale to a specific signal frequency, the sampling period of the signal must be known. pywt.
scale2frequency() can be used to convert a list of scales to their corresponding frequencies. The proper choice
of scales depends on the chosen wavelet, so pywt.scale2frequency() should be used to get an idea of an
appropriate range for the signal of interest.
For the cmor, fbsp and shan wavelets, the user can specify a specific a normalized center frequency. A value of
1.0 corresponds to 1/dt where dt is the sampling period. In other words, when analyzing a signal sampled at 100 Hz,
a center frequency of 1.0 corresponds to ~100 Hz at scale = 1. This is above the Nyquist rate of 50 Hz, so for this
particular wavelet, one would analyze a signal using scales >= 2.
The CWT in PyWavelets is applied to discrete data by convolution with samples of the integral of the wavelet. If
scale is too low, this will result in a discrete filter that is inadequately sampled leading to aliasing as shown in the
example below. Here the wavelet is 'cmor1.5-1.0'. The left column of the figure shows the discrete filters used
in the convolution at various scales. The right column are the corresponding Fourier power spectra of each filter.. For
scales 1 and 2 it can be seen that aliasing due to violation of the Nyquist limit occurs.
import numpy as np
import pywt
import matplotlib.pyplot as plt
(continues on next page)
wav = pywt.ContinuousWavelet('cmor1.5-1.0')
max_len = int(np.max(scales)*width + 1)
t = np.arange(max_len)
fig, axes = plt.subplots(len(scales), 2, figsize=(12, 6))
for n, scale in enumerate(scales):
# The CWT consists of convolution of filt with the signal at this scale
# Here we plot this discrete convolution kernel at each scale.
nt = len(filt)
t = np.linspace(-nt//2, nt//2, nt)
axes[n, 0].plot(t, filt.real, t, filt.imag)
axes[n, 0].set_xlim([-max_len//2, max_len//2])
axes[n, 0].set_ylim([-1, 1])
axes[n, 0].text(50, 0.35, 'scale = {}'.format(scale))
60 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
filter |FFT(filter)|2
1 1.0
real scale = 1 Power
0 imaginary 0.5 scale = 1
1 0.0
1 100 50 0 50 100 1.0 0
scale = 2
0 0.5 scale = 2
1 0.0
1 100 50 0 50 100 1.0 0
scale = 3
0 0.5 scale = 3
1 0.0
1 100 50 0 50 100 1.0 0
scale = 4
0 0.5 scale = 4
1 0.0
1 100 50 0 50 100 1.0 0
scale = 10
0 0.5 scale = 10
1 0.0
1 100 50 0 50 100 1.0 0
scale = 15
0 0.5 scale = 15
1 0.0
100 50 0 50 100 0
time (samples) frequency (radians)
The thresholding helper module implements the most popular signal thresholding functions.
Thresholding
threshold_firm
References
Examples
threshold
62 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
Notes
firm is a continuous function (like soft thresholding), but is unbiased for large values (like hard thresholding).
If value_high == value_low this function becomes hard-thresholding. If value_high is infinity, this
function becomes soft-thresholding.
References
[1], [2]
The left panel of the figure below illustrates that non-negative Garotte thresholding is intermediate between soft and
hard thresholding. Firm thresholding transitions between soft and hard thresholding behavior. It requires a pair of
threshold values that define the width of the transition region.
import numpy as np
import matplotlib.pyplot as plt
import pywt
s = np.linspace(-4, 4, 1000)
ax[1].plot(s, s_soft)
ax[1].plot(s, s_hard)
ax[1].plot(s, s_firm1)
ax[1].plot(s, s_firm2)
ax[1].plot(s, s_firm3)
ax[1].legend(['soft (0.5)', 'hard (0.5)', 'firm(0.5, 1)', 'firm(0.5, 2)',
'firm(0.5, 4)'])
ax[1].set_xlabel('input value')
ax[1].set_ylabel('thresholded value')
plt.show()
thresholded value
1 1
0 0
1 1
2 2
3 3
4 4
4 2 0 2 4 4 2 0 2 4
input value input value
pywt.integrate_wavelet(wavelet, precision=8)
Integrate psi wavelet function from -Inf to x using the rectangle integration method.
Parameters
wavelet [Wavelet instance or str] Wavelet to integrate. If a string, should be the name of a
wavelet.
precision [int, optional] Precision that will be used for wavelet function approximation com-
puted with the wavefun(level=precision) Wavelet’s method (default: 8).
Returns
[int_psi, x] : for orthogonal wavelets
[int_psi_d, int_psi_r, x] : for other wavelets
Examples
• for other wavelets - integrals of decomposition and reconstruction wavelet functions and a corresponding x-grid:
64 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
pywt.central_frequency(wavelet, precision=8)
Computes the central frequency of the psi wavelet function.
Parameters
wavelet [Wavelet instance, str or tuple] Wavelet to integrate. If a string, should be the name of
a wavelet.
precision [int, optional] Precision that will be used for wavelet function approximation com-
puted with the wavefun(level=precision) Wavelet’s method (default: 8).
Returns
scalar
pywt.scale2frequency(wavelet, scale, precision=8)
Parameters
wavelet [Wavelet instance or str] Wavelet to integrate. If a string, should be the name of a
wavelet.
scale [scalar]
precision [int, optional] Precision that will be used for wavelet function approximation com-
puted with wavelet.wavefun(level=precision). Default is 8.
Returns
freq [scalar]
pywt.qmf(filt)
Returns the Quadrature Mirror Filter(QMF).
The magnitude response of QMF is mirror image about pi/2 of that of the input filter.
Parameters
filt [array_like] Input filter for which QMF needs to be computed.
Returns
qm_filter [ndarray] Quadrature mirror of the input filter.
pywt.orthogonal_filter_bank(scaling_filter)
Returns the orthogonal filter bank.
The orthogonal filter bank consists of the HPFs and LPFs at decomposition and reconstruction stage for the
input scaling filter.
Parameters
scaling_filter [array_like] Input scaling filter (father wavelet).
Returns
orth_filt_bank [tuple of 4 ndarrays] The orthogonal filter bank of the input scaling filter in the
order : 1] Decomposition LPF 2] Decomposition HPF 3] Reconstruction LPF 4] Recon-
struction HPF
Example Datasets
name description
ecg ECG waveform (1024 samples)
aero grayscale image (512x512)
ascent grayscale image (512x512)
camera grayscale image (512x512)
nino sea surface temperature (264 samples)
demo_signal various synthetic 1d test signals
Notes
This function is a partial reimplementation of the MakeSignal function from the [Wavelab](https://statweb.
stanford.edu/~wavelab/) toolbox. These test signals are provided with permission of Dr. Donoho to encour-
age reproducible research.
References
[1], [2]
Example:
66 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
The following examples are used as doctest regression tests written using reST markup. They are included in the
documentation since they contain various useful examples illustrating how to use and how not to use PyWavelets.
For more usage examples see the demo directory in the source package.
Wavelet objects are really a handy carriers of a bunch of DWT-specific data like quadrature mirror filters and some
general properties associated with them.
At first let’s go through the methods of creating a Wavelet object. The easiest and the most convenient way is to use
builtin named Wavelets.
These wavelets are organized into groups called wavelet families. The most commonly used families are:
The wavelist() function with family name passed as an argument is used to obtain the list of wavelet names in
each family.
˓→db29, db30, db31, db32, db33, db34, db35, db36, db37, db38
sym family: sym2, sym3, sym4, sym5, sym6, sym7, sym8, sym9, sym10, sym11, sym12,
˓→sym13, sym14, sym15, sym16, sym17, sym18, sym19, sym20
coif family: coif1, coif2, coif3, coif4, coif5, coif6, coif7, coif8, coif9, coif10,
˓→coif11, coif12, coif13, coif14, coif15, coif16, coif17
bior family: bior1.1, bior1.3, bior1.5, bior2.2, bior2.4, bior2.6, bior2.8, bior3.1,
˓→bior3.3, bior3.5, bior3.7, bior3.9, bior4.4, bior5.5, bior6.8
rbio family: rbio1.1, rbio1.3, rbio1.5, rbio2.2, rbio2.4, rbio2.6, rbio2.8, rbio3.1,
˓→rbio3.3, rbio3.5, rbio3.7, rbio3.9, rbio4.4, rbio5.5, rbio6.8
To get the full list of builtin wavelets’ names just use the wavelist() with no argument.
Now when we know all the names let’s finally create a Wavelet object:
>>> w = pywt.Wavelet('db3')
Wavelet properties
But what can we do with Wavelet objects? Well, they carry some interesting information.
First, let’s try printing a Wavelet object. This shows a brief information about its name, its family name and some
properties like orthogonality and symmetry.
>>> print(w)
Wavelet db3
Family name: Daubechies
Short name: db
Filters length: 6
Orthogonal: True
Biorthogonal: True
Symmetry: asymmetric
DWT: True
CWT: False
But the most important information are the wavelet filters coefficients, which are used in Discrete Wavelet Transform.
These coefficients can be obtained via the dec_lo, Wavelet.dec_hi, rec_lo and rec_hi attributes, which
corresponds to lowpass and highpass decomposition filters and lowpass and highpass reconstruction filters respec-
tively:
Another way to get the filters data is to use the filter_bank attribute, which returns all four filters in a tuple:
>>> print(w.name)
db3
>>> print(w.short_family_name)
db
>>> print(w.family_name)
Daubechies
>>> int(w.dec_len) # int() is for normalizing longs and ints for doctest
6
>>> int(w.rec_len)
6
68 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
>>> w.orthogonal
True
>>> w.biorthogonal
True
• Symmetry (symmetry):
>>> print(w.symmetry)
asymmetric
• Number of vanishing moments for the scaling function phi (vanishing_moments_phi) and
the wavelet function psi (vanishing_moments_psi) associated with the filters:
>>> w.vanishing_moments_phi
0
>>> w.vanishing_moments_psi
3
Now when we know a bit about the builtin Wavelets, let’s see how to create custom Wavelets objects. These can be
done in two ways:
1) Passing the filter bank object that implements the filter_bank attribute. The attribute must return four filters
coefficients.
Note that such custom wavelets will not have all the properties set to correct values:
>>> print(my_wavelet)
Wavelet My Haar Wavelet
Family name:
Short name:
Filters length: 2
Orthogonal: False
Biorthogonal: False
Symmetry: unknown
DWT: True
CWT: False
>>> print(my_wavelet)
Wavelet My Haar Wavelet
Family name:
Short name:
Filters length: 2
Orthogonal: True
Biorthogonal: True
Symmetry: unknown
DWT: True
CWT: False
We all know that the fun with wavelets is in wavelet functions. Now what would be this package without a tool to
compute wavelet and scaling functions approximations?
This is the purpose of the wavefun() method, which is used to approximate scaling function (phi) and wavelet
function (psi) at the given level of refinement, based on the filters coefficients.
The number of returned values varies depending on the wavelet’s orthogonality property. For orthogonal wavelets the
result is tuple with scaling function, wavelet function and xgrid coordinates.
>>> w = pywt.Wavelet('sym3')
>>> w.orthogonal
True
>>> (phi, psi, x) = w.wavefun(level=5)
For biorthogonal (non-orthogonal) wavelets different scaling and wavelet functions are used for decomposition and
reconstruction, and thus five elements are returned: decomposition scaling and wavelet functions approximations,
reconstruction scaling and wavelet functions approximations, and the xgrid.
>>> w = pywt.Wavelet('bior1.3')
>>> w.orthogonal
False
>>> (phi_d, psi_d, phi_r, psi_r, x) = w.wavefun(level=5)
See also:
You can find live examples of wavefun() usage and images of all the built-in wavelets on the Wavelet Properties
Browser page. However, this website is no longer actively maintained and does not include every wavelet present
in PyWavelets. The precision of the wavelet coefficients at that site is also lower than those included in PyWavelets.
70 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
>>> print(pywt.Modes.modes)
['zero', 'constant', 'symmetric', 'periodic', 'smooth', 'periodization', 'reflect',
˓→'antisymmetric', 'antireflect']
Let’s do a Discrete Wavelet Transform of a sample data x using the db2 wavelet. It’s simple..
>>> import pywt
>>> x = [3, 7, 1, 1, -2, 5, 4, 6]
>>> cA, cD = pywt.dwt(x, 'db2')
More Examples
Now let’s experiment with the dwt() some more. For example let’s pass a Wavelet object instead of the wavelet
name and specify signal extension mode (the default is symmetric) for the border effect handling:
>>> w = pywt.Wavelet('sym3')
>>> cA, cD = pywt.dwt(x, wavelet=w, mode='constant')
>>> print(cA)
[ 4.38354585 3.80302657 7.31813271 -0.58565539 4.09727044 7.81994027]
>>> print(cD)
[-1.33068221 -2.78795192 -3.16825651 -0.67715519 -0.09722957 -0.07045258]
Note that the output coefficients arrays length depends not only on the input data length but also on the :class:Wavelet
type (particularly on its filters length that are used in the transformation).
To find out what will be the output data size use the dwt_coeff_len() function:
>>> # int() is for normalizing Python integers and long integers for documentation
˓→tests
Looks fine. (And if you expected that the output length would be a half of the input data length, well, that’s the
trade-off that allows for the perfect reconstruction. . . ).
The third argument of the dwt_coeff_len() is the already mentioned signal extension mode (please refer to the
PyWavelets’ documentation for the modes description). Currently there are six extension modes available:
>>> pywt.Modes.modes
['zero', 'constant', 'symmetric', 'periodic', 'smooth', 'periodization', 'reflect',
˓→'antisymmetric', 'antireflect']
As you see in the above example, the periodization (periodization) mode is slightly different from the others. It’s aim
when doing the DWT transform is to output coefficients arrays that are half of the length of the input data.
Knowing that, you should never mix the periodization mode with other modes when doing DWT and IDWT. Otherwise,
it will produce invalid results:
72 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
>>> x
[3, 7, 1, 1, -2, 5, 4, 6]
>>> cA, cD = pywt.dwt(x, wavelet=w, mode='periodization')
>>> print(pywt.idwt(cA, cD, 'sym3', 'symmetric')) # invalid mode
[ 1. 1. -2. 5.]
>>> print(pywt.idwt(cA, cD, 'sym3', 'periodization'))
[ 3. 7. 1. 1. -2. 5. 4. 6.]
Now some tips & tricks. Passing None as one of the coefficient arrays parameters is similar to passing a zero-filled
array. The results are simply the same:
When doing the IDWT transform, usually the coefficient arrays must have the same size.
Not every coefficient array can be used in IDWT. In the following example the idwt() will fail because the input
arrays are invalid - they couldn’t be created as a result of DWT, because the minimal output length for dwt using db4
wavelet and the symmetric mode is 4, not 3:
74 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
Import pywt
>>> x = [1, 2, 3, 4, 5, 6, 7, 8]
>>> wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
The input data and decomposition coefficients are stored in the WaveletPacket.data attribute:
>>> print(wp.data)
[1, 2, 3, 4, 5, 6, 7, 8]
Nodes are identified by paths. For the root node the path is '' and the decomposition level is 0.
>>> print(repr(wp.path))
''
>>> print(wp.level)
0
>>> print(wp['ad'].maxlevel)
3
Traversing WP tree:
Accessing subnodes:
>>> x = [1, 2, 3, 4, 5, 6, 7, 8]
>>> wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
>>> print(wp.maxlevel)
3
>>> print(wp['a'].data)
[ 2.12132034 4.94974747 7.77817459 10.60660172]
>>> print(wp['a'].path)
a
• 2nd level:
>>> print(wp['aa'].data)
[ 5. 13.]
>>> print(wp['aa'].path)
aa
• 3rd level:
>>> print(wp['aaa'].data)
[ 12.72792206]
>>> print(wp['aaa'].path)
aaa
Ups, we have reached the maximum level of decomposition and got an IndexError:
>>> print(wp['aaaa'].data)
Traceback (most recent call last):
...
IndexError: Path length is out of range.
>>> print(wp['ac'])
Traceback (most recent call last):
...
ValueError: Subnode name must be in ['a', 'd'], not 'c'.
WaveletPacket object is a tree data structure, which evaluates to a set of Node objects. WaveletPacket is just
a special subclass of the Node class (which in turn inherits from the BaseNode).
Tree nodes can be accessed using the obj[x] (Node.__getitem__()) operator. Each tree node has a set of
attributes: data, path, node_name, parent, level, maxlevel and mode.
>>> x = [1, 2, 3, 4, 5, 6, 7, 8]
>>> wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
>>> print(wp['ad'].data)
[-2. -2.]
76 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
>>> print(wp['ad'].path)
ad
>>> print(wp['ad'].node_name)
d
>>> print(wp['ad'].parent.path)
a
>>> print(wp['ad'].level)
2
>>> print(wp['ad'].maxlevel)
3
>>> print(wp['ad'].mode)
symmetric
Collecting nodes
>>> x = [1, 2, 3, 4, 5, 6, 7, 8]
>>> wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
We can get all nodes on the particular level either in natural order:
Note that WaveletPacket.get_level() also performs automatic decomposition until it reaches the specified
level.
>>> x = [1, 2, 3, 4, 5, 6, 7, 8]
>>> wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
Now create a new Wavelet Packet and set its nodes with some data.
For convenience, Node.data gets automatically extracted from the Node object:
>>> print(new_wp.reconstruct(update=False))
[ 1. 2. 3. 4. 5. 6. 7. 8.]
If the update param in the reconstruct method is set to False, the node’s data will not be updated.
>>> print(new_wp.data)
None
>>> print(new_wp.reconstruct(update=True))
[ 1. 2. 3. 4. 5. 6. 7. 8.]
>>> print(new_wp.data)
[ 1. 2. 3. 4. 5. 6. 7. 8.]
>>> x = [1, 2, 3, 4, 5, 6, 7, 8]
>>> wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
First, start with a tree decomposition at level 2. Leaf nodes in the tree are:
To remove a node from the WP tree, use Python’s del obj[x] (Node.__delitem__):
78 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
>>> print(wp.reconstruct())
[ 2. 3. 2. 3. 6. 7. 6. 7.]
Printing leaf nodes and tree reconstruction confirms the original state of the tree:
>>> print(wp.reconstruct())
[ 1. 2. 3. 4. 5. 6. 7. 8.]
Lazy evaluation:
Note: This section is for demonstration of pywt internals purposes only. Do not rely on the attribute access to nodes
as presented in this example.
>>> x = [1, 2, 3, 4, 5, 6, 7, 8]
>>> wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
>>> print(wp.a)
None
>>> print(wp['a'])
a: [ 2.12132034 4.94974747 7.77817459 10.60660172]
>>> print(wp.a)
a: [ 2.12132034 4.94974747 7.77817459 10.60660172]
And so is wp.d:
>>> print(wp.d)
d: [-0.70710678 -0.70710678 -0.70710678 -0.70710678]
Import pywt
The input data and decomposition coefficients are stored in the WaveletPacket2D.data attribute:
>>> print(wp.data)
[[ 1. 2. 3. 4. 5. 6. 7. 8.]
[ 1. 2. 3. 4. 5. 6. 7. 8.]
[ 1. 2. 3. 4. 5. 6. 7. 8.]
[ 1. 2. 3. 4. 5. 6. 7. 8.]
[ 1. 2. 3. 4. 5. 6. 7. 8.]
[ 1. 2. 3. 4. 5. 6. 7. 8.]
[ 1. 2. 3. 4. 5. 6. 7. 8.]
[ 1. 2. 3. 4. 5. 6. 7. 8.]]
Nodes are identified by paths. For the root node the path is '' and the decomposition level is 0.
>>> print(repr(wp.path))
''
>>> print(wp.level)
0
The WaveletPacket2D.maxlevel, if not given in the constructor, is automatically computed based on the data
size:
>>> print(wp.maxlevel)
3
80 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
Traversing WP tree:
Wavelet Packet nodes are arranged in a tree. Each node in a WP tree is uniquely identified and addressed by a path
string.
In the 1D WaveletPacket case nodes were accessed using 'a' (approximation) and 'd' (details) path names
(each node has two 1D children).
Because now we deal with a bit more complex structure (each node has four children), we have four basic path names
based on the dwt 2D output convention to address the WP2D structure:
• a - LL, low-low coefficients
• h - LH, low-high coefficients
• v - HL, high-low coefficients
• d - HH, high-high coefficients
In other words, subnode naming corresponds to the dwt2() function output naming convention (as wavelet packet
transform is based on the dwt2 transform):
-------------------
| | |
| cA(LL) | cH(LH) |
| | |
(cA, (cH, cV, cD)) <---> -------------------
| | |
| cV(HL) | cD(HH) |
| | |
-------------------
Knowing what the nodes names are, we can now access them using the indexing operator obj[x]
(WaveletPacket2D.__getitem__()):
>>> print(wp['a'].data)
[[ 3. 7. 11. 15.]
[ 3. 7. 11. 15.]
[ 3. 7. 11. 15.]
[ 3. 7. 11. 15.]]
>>> print(wp['h'].data)
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
>>> print(wp['v'].data)
[[-1. -1. -1. -1.]
[-1. -1. -1. -1.]
[-1. -1. -1. -1.]
[-1. -1. -1. -1.]]
>>> print(wp['d'].data)
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
>>> print(wp['aa'].data)
[[ 10. 26.]
[ 10. 26.]]
Indexing base WaveletPacket2D (as well as 1D WaveletPacket) using compound path is just the same as
indexing WP subnode:
>>> print(wp['aaa'].data)
[[ 36.]]
>>> print(wp['aaaa'].data)
Traceback (most recent call last):
...
IndexError: Path length is out of range.
Ups, we have reached the maximum level of decomposition for the 'aaaa' path, which btw. was:
>>> print(wp.maxlevel)
3
>>> print(wp['f'])
Traceback (most recent call last):
...
ValueError: Subnode name must be in ['a', 'h', 'v', 'd'], not 'f'.
WaveletPacket2D is a tree data structure, which evaluates to a set of Node2D objects. WaveletPacket2D
is just a special subclass of the Node2D class (which in turn inherits from a BaseNode, just like with Node and
WaveletPacket for the 1D case.).
>>> print(wp['av'].data)
[[-4. -4.]
[-4. -4.]]
>>> print(wp['av'].path)
av
>>> print(wp['av'].node_name)
v
>>> print(wp['av'].parent.path)
a
82 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
>>> print(wp['av'].parent.data)
[[ 3. 7. 11. 15.]
[ 3. 7. 11. 15.]
[ 3. 7. 11. 15.]
[ 3. 7. 11. 15.]]
>>> print(wp['av'].level)
2
>>> print(wp['av'].maxlevel)
3
>>> print(wp['av'].mode)
symmetric
Collecting nodes
We can get all nodes on the particular level using the WaveletPacket2D.get_level() method:
• 0 level - the root wp node:
>>> len(wp.get_level(0))
1
>>> print([node.path for node in wp.get_level(0)])
['']
>>> len(wp.get_level(1))
4
>>> print([node.path for node in wp.get_level(1)])
['a', 'h', 'v', 'd']
>>> len(wp.get_level(2))
16
>>> paths = [node.path for node in wp.get_level(2)]
>>> for i, path in enumerate(paths):
... if (i+1) % 4 == 0:
... print(path)
... else:
... print(path, end=' ')
aa ah av ad
ha hh hv hd
va vh vv vd
da dh dv dd
>>> print(len(wp.get_level(3)))
64
>>> paths = [node.path for node in wp.get_level(3)]
>>> for i, path in enumerate(paths):
(continues on next page)
Note that WaveletPacket2D.get_level() performs automatic decomposition until it reaches the given level.
Let’s create a new empty 2D Wavelet Packet structure and set its nodes values with known data from the previous
examples:
>>> new_wp = pywt.WaveletPacket2D(data=None, wavelet='db1', mode='symmetric')
>>> new_wp['a'] = [[3.0, 7.0, 11.0, 15.0], [3.0, 7.0, 11.0, 15.0],
... [3.0, 7.0, 11.0, 15.0], [3.0, 7.0, 11.0, 15.0]]
>>> new_wp['d'] = [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0],
... [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]
For convenience, Node2D.data gets automatically extracted from the base Node2D object:
>>> new_wp['h'] = wp['h'] # all zeros
Note: just remember to not assign to the node.data parameter directly (todo).
And reconstruct the data from the a, d, vh, vv, vd and h packets (Note that va node was not set and the WP tree is
“not complete” - the va branch will be treated as zero-array):
>>> print(new_wp.reconstruct(update=False))
[[ 1.5 1.5 3.5 3.5 5.5 5.5 7.5 7.5]
[ 1.5 1.5 3.5 3.5 5.5 5.5 7.5 7.5]
[ 1.5 1.5 3.5 3.5 5.5 5.5 7.5 7.5]
[ 1.5 1.5 3.5 3.5 5.5 5.5 7.5 7.5]
[ 1.5 1.5 3.5 3.5 5.5 5.5 7.5 7.5]
[ 1.5 1.5 3.5 3.5 5.5 5.5 7.5 7.5]
[ 1.5 1.5 3.5 3.5 5.5 5.5 7.5 7.5]
[ 1.5 1.5 3.5 3.5 5.5 5.5 7.5 7.5]]
Now set the va node with the known values and do the reconstruction again:
>>> new_wp['va'] = wp['va'].data # [[-2.0, -2.0], [-2.0, -2.0]]
>>> print(new_wp.reconstruct(update=False))
[[ 1. 2. 3. 4. 5. 6. 7. 8.]
(continues on next page)
84 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
If the update param in the WaveletPacket2D.reconstruct() method is set to False, the node’s Node2D.
data attribute will not be updated.
>>> print(new_wp.data)
None
>>> print(new_wp.reconstruct(update=True))
[[ 1. 2. 3. 4. 5. 6. 7. 8.]
[ 1. 2. 3. 4. 5. 6. 7. 8.]
[ 1. 2. 3. 4. 5. 6. 7. 8.]
[ 1. 2. 3. 4. 5. 6. 7. 8.]
[ 1. 2. 3. 4. 5. 6. 7. 8.]
[ 1. 2. 3. 4. 5. 6. 7. 8.]
[ 1. 2. 3. 4. 5. 6. 7. 8.]
[ 1. 2. 3. 4. 5. 6. 7. 8.]]
>>> print(new_wp.data)
[[ 1. 2. 3. 4. 5. 6. 7. 8.]
[ 1. 2. 3. 4. 5. 6. 7. 8.]
[ 1. 2. 3. 4. 5. 6. 7. 8.]
[ 1. 2. 3. 4. 5. 6. 7. 8.]
[ 1. 2. 3. 4. 5. 6. 7. 8.]
[ 1. 2. 3. 4. 5. 6. 7. 8.]
[ 1. 2. 3. 4. 5. 6. 7. 8.]
[ 1. 2. 3. 4. 5. 6. 7. 8.]]
Since we have an interesting WP structure built, it is a good occasion to present the WaveletPacket2D.
get_leaf_nodes() method, which collects non-zero leaf nodes from the WP tree:
Passing the decompose = True parameter to the method will force the WP object to do a full decomposition up
to the maximum level of decomposition:
>>> paths = [n.path for n in new_wp.get_leaf_nodes(decompose=True)]
>>> len(paths)
64
>>> for i, path in enumerate(paths):
... if (i+1) % 8 == 0:
... print(path)
... else:
... try:
... print(path, end=' ')
... except:
... print(path, end=' ')
aaa aah aav aad aha ahh ahv ahd
ava avh avv avd ada adh adv add
haa hah hav had hha hhh hhv hhd
hva hvh hvv hvd hda hdh hdv hdd
vaa vah vav vad vha vhh vhv vhd
vva vvh vvv vvd vda vdh vdv vdd
daa dah dav dad dha dhh dhv dhd
dva dvh dvv dvd dda ddh ddv ddd
Lazy evaluation:
Note: This section is for demonstration of pywt internals purposes only. Do not rely on the attribute access to nodes
as presented in this example.
86 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
And so is wp.d:
>>> print(wp.d)
d: [[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
5.3.7 Gotchas
PyWavelets utilizes NumPy under the hood. That’s why handling the data containing None values can be surprising.
None values are converted to ‘not a number’ (numpy.NaN) values:
5.4 Contributing
All contributions including bug reports, bug fixes, new feature implementations and documentation improvements are
welcome. Moreover, developers with an interest in PyWavelets are very welcome to join the development team! Please
see our guidelines for pull requests for more information.
Contributors are expected to behave in a productive and respectful manner in accordance with our community guide-
lines.
5.4.1 History
PyWavelets started in 2006 as an academic project for a masters thesis on Analysis and Classification of Medical
Signals using Wavelet Transforms and was maintained until 2012 by its original developer. In 2013 maintenance was
taken over in a new repo) by a larger development team - a move supported by the original developer. The repo move
doesn’t mean that this is a fork - the package continues to be developed under the name “PyWavelets”, and released
on PyPI and Github (see this issue for the discussion where that was decided).
5.4. Contributing 87
PyWavelets Documentation, Release 1.1.0.dev0+399196a
This section contains information on building and installing PyWavelets from source code as well as instructions for
preparing the build environment on Windows and Linux.
To start developing PyWavelets code on Windows you will have to install a C compiler and prepare the build environ-
ment.
Depending on your Python version, a different version of the Microsoft Visual C++ compiler will be required to build
extensions. The same compiler that was used to build Python itself should be used.
For Python 3.5, 3.6 and 3.7 it will be MSVC 2015.
The MSVC version should be printed when starting a Python REPL, and can be checked against the note below:
Python 3.5.5 (default, Feb 13 2018, 06:15:35) [MSC v.1900 64 bit (AMD64)] on win32
To get started first download, extract and install Microsoft Windows SDK for Windows 7 and
.NET Framework 3.5 SP1 from http://www.microsoft.com/downloads/en/details.aspx?familyid=
71DEB800-C591-4F97-A900-BEA146E4FAE1&displaylang=en.
There are several ISO images on the site, so just grab the one that is suitable for your platform:
• GRMSDK_EN_DVD.iso for 32-bit x86 platform
• GRMSDKX_EN_DVD.iso for 64-bit AMD64 platform (AMD64 is the codename for 64-bit CPU architecture,
not the processor manufacturer)
After installing the SDK and before compiling the extension you have to configure some environment variables.
For 32-bit build execute the util/setenv_build32.bat script in the cmd window:
88 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
You can also take a look at Cython’s “Installing MinGW on Windows” page at http://wiki.cython.org/
InstallingOnWindows for more info.
Note: Python 2.7/3.2 distutils package is incompatible with the current version (4.7+) of MinGW (MinGW dropped
the -mno-cygwin flag, which is still passed by distutils).
To use MinGW to compile Python extensions you have to patch the distutils/cygwinccompiler.py library
module and remove every occurrence of -mno-cygwin.
See http://bugs.python.org/issue12641 bug report for more information on the issue.
Next steps
There is a good chance that you already have a working build environment. Just skip steps that you don’t need to
execute.
Note that the example below uses aptitude package manager, which is specific to Debian and Ubuntu Linux
distributions. Use your favourite package manager to install these packages on your OS.
aptitude install build-essential gcc python-dev git-core
Next steps
A good practice is to create a separate Python virtual environment for each project. If you don’t have virtualenv yet,
install and activate it using:
curl -O https://raw.github.com/pypa/virtualenv/master/virtualenv.py
python virtualenv.py <name_of_the_venv>
. <name_of_the_venv>/bin/activate
Installing Cython
Installing numpy
Numpy can also be obtained via scientific python distributions such as:
• Anaconda
• Enthought Canopy
• Python(x,y)
Installing Sphinx
Sphinx is a documentation tool that converts reStructuredText files into nicely looking html documentation. Install it
with:
Go to https://github.com/PyWavelets/pywt GitHub project page, fork and clone the repository or use the upstream
repository to get the source code:
90 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
Activate your Python virtual environment, go to the cloned source directory and type the following commands to build
and install the package:
To build docs:
cd doc
make html
or:
5.5.5 Testing
The project is using Travis-CI service for continuous integration and testing.
Current build status is:
If you are submitting a patch or pull request please make sure it does not break the build.
There’s also a config file for running tests with Tox (pip install tox). To for example run tests for Python 3.5
and 3.6 use:
tox -e py35,py36
The following are guidelines for preparing a release of PyWavelets. The notation vX.X.X in the commands below
would be replaced by the actual release number.
Prior to the release, make sure the release notes are up to date. The author lists can be generated via:
92 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
Push a commit with the new tag and updates of dependency versions where needed to https://github.com/MacPython/
pywavelets-wheels. The wheels will be produced automatically and uploaded to http://wheels.scipy.org/. From there
they can be uploaded to PyPI automatically with wheel-uploader.
See the README on https://github.com/MacPython/pywavelets-wheels for more details.
Remove untracked files and directories with git clean. Warning: this will delete files & directories that are not
under version control so you may want to do a dry run first by adding -n, so you can see what will be removed:
git clean -xfdn
The binary Windows wheels downloaded from Appveyor (see above) should also be placed into the /dist subfolder
along with the sdist archives.
The wheels and source distributions created above can all be securely uploaded to pypi.python.org using twine:
twine upload -s dist/*
Note that the documentation on ReadTheDocs (http://pywavelets.readthedocs.org) will have been automatically gen-
erated, so no actions need to be taken for documentation.
Update conda-forge
Send a PR with the new version number and sha256 hash of the source release to https://github.com/conda-forge/
pywavelets-feedstock.
On the project’s GitHub page, click the releases tab and then press the “Draft a new release” button to create a release
from the appropriate tag.
If these instructions are not clear or you need help setting up your development environment, go ahead and ask on the
PyWavelets discussion group at http://groups.google.com/group/pywavelets or open a ticket on GitHub.
Contents
* Test suite
* n-D Inverse Discrete Wavelet Transform
* Thresholding
– Backwards incompatible changes
– Other changes
– Authors
PyWavelets 0.3.0 is the first release of the package in 3 years. It is the result of a significant effort of a growing
development team to modernize the package, to provide Python 3.x support and to make a start with providing new
features as well as improved performance. A 0.4.0 release will follow shortly, and will contain more significant new
features as well as changes/deprecations to streamline the API.
This release requires Python 2.6, 2.7 or 3.3-3.5 and NumPy 1.6.2 or greater.
Highlights of this release include:
• Support for Python 3.x (>=3.3)
• Added a test suite (based on nose, coverage up to 61% so far)
• Maintenance work: C style complying to the Numpy style guide, improved templating system, more complete
docstrings, pep8/pyflakes compliance, and more.
94 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
New features
Test suite
The function pywt.idwtn, which provides n-dimensional inverse DWT, has been added. It complements idwt,
idwt2 and dwtn.
Thresholding
The function pywt.threshold has been added. It unifies the four thresholding functions that are still provided in the
pywt.thresholding namespace.
Other changes
Development has moved to a new repo. Everyone with an interest in wavelets is welcome to contribute!
Building wheels, building with python setup.py develop and many other standard ways to build and install
PyWavelets are supported now.
Authors
• Ankit Agrawal +
• François Boulogne +
• Ralf Gommers +
• David Menéndez Hurtado +
• Gregory R. Lee +
• David McInnis +
• Helder Oliveira +
• Filip Wasilewski
• Kai Wohlfahrt +
A total of 9 people contributed to this release. People with a “+” by their names contributed a patch for the first time.
This list of names is automatically generated, and may not be fully complete.
96 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
Contents
PyWavelets 0.4.0 is the culmination of 6 months of work. In addition to several new features, some changes and
deprecations have been made to streamline the API.
This release requires Python 2.6, 2.7 or 3.3-3.5 and NumPy 1.6.2 or greater.
Highlights of this release include:
New features
1D (iswt) and 2D (iswt2) inverse stationary wavelet transforms were added. These currently only support even
length inputs.
The multidimensional DWT and IDWT code was refactored and is now an order of magnitude faster than in previous
releases. The following functions benefit: dwt2, idwt2, dwtn, idwtn.
64 and 128-bit complex data types are now supported by all wavelet transforms.
All wavelet transform functions now support explicit specification of the axis or axes upon which to perform the
transform.
Example Datasets
Two additional 2D grayscale images were added (camera, ascent). The previously existing 1D ECG data (ecg) and the
2D aerial image (aero) used in the demos can also now be imported via functions defined in pywt.data (e.g. camera
= pywt.data.camera())
Deprecated features
A number of functions have been renamed, the old names are deprecated and will be removed in a future release:
• intwave, renamed to integrate_wavelet
• centrfrq, renamed to central_frequency
• scal2frq, renamed to scale2frequency
• orthfilt, renamed to orthogonal_filter_bank
98 Chapter 5. Contents
PyWavelets Documentation, Release 1.1.0.dev0+399196a
idwt no longer takes a correct_size parameter. As a consequence, idwt2 inputs must match exactly in length.
For multilevel transforms, where arrays differing in size by one element may be produced, use the waverec functions
from the multilevel module instead.
Bugs Fixed
float32 inputs were not always respected. All transforms now return float32 outputs when called using float32 inputs.
Incorrect detail coefficients were returned by downcoef when level > 1.
Other changes
Much of the API documentation is now autogenerated from the corresponding function docstrings. The numpydoc
sphinx extension is now needed to build the documentation.
Authors
• Thomas Arildsen +
• François Boulogne
• Ralf Gommers
• Gregory R. Lee
• Michael Marino +
• Aaron O’Leary +
• Daniele Tricoli +
• Kai Wohlfahrt
A total of 8 people contributed to this release. People with a “+” by their names contributed a patch for the first time.
This list of names is automatically generated, and may not be fully complete.
Contents
PyWavelets is a Python toolbox implementing both discrete and continuous wavelet transforms (mathematical time-
frequency transforms) with a wide range of built-in wavelets. C/Cython are used for the low-level routines, enabling
high performance. Key Features of PyWavelets are:
• 1D, 2D and nD Forward and Inverse Discrete Wavelet Transform (DWT and IDWT)
• 1D, 2D and nD Multilevel DWT and IDWT
• 1D and 2D Forward and Inverse Stationary Wavelet Transform
• 1D and 2D Wavelet Packet decomposition and reconstruction
• 1D Continuous Wavelet Transform
• When multiple valid implementations are available, we have chosen to maintain consistency with MATLAB™’s
Wavelet Toolbox.
PyWavelets 0.5.0 is the culmination of 1 year of work. In addition to several new features, substantial refactoring of
the underlying C and Cython code have been made.
This release requires Python 2.6, 2.7 or 3.3-3.5 and NumPy 1.9.1 or greater. This will be the final release supporting
Python 2.6 and 3.3.
Highlights of this release include:
• 1D continuous wavelet transforms
New features
A wide range of continous wavelets are now available. These include the following:
• Gaussian wavelets (gaus1. . . ‘‘gaus8‘‘)
• Mexican hat wavelet (mexh)
• Morlet wavelet (morl)
• Complex Gaussian wavelets (cgau1. . . ‘‘cgau8‘‘)
• Shannon wavelet (shan)
• Frequency B-Spline wavelet (fbsp)
• Complex Morlet wavelet (cmor)
Also, see the new CWT-related demo: demo/cwt_analysis.py
Additional Debauchies wavelets (db20. . . ‘‘db38‘‘) and Coiflets (coif6. . . ‘‘coif17‘‘) have been added.
Discrete wavelet transforms support a new extension mode, reflect. This mode pads an array symmetrically, but
without repeating the edge value. As an example:
This differs from symmetric, which repeats the values at the boundaries:
New routines to convert the coefficients returned by multilevel DWT routines to and from a single n-dimensional array
have been added. pywt.coeffs_to_array concatenates the output of wavedec, wavedec2 or wavedecn
into a single numpy array. pywt.array_to_coeffs can be used to transform back from a single coefficient array
to a format appropriate for waverec, waverec2 or waverecn.
Cython code calling the wavelet filtering routines (DWT and SWT) now releases the global interpreter lock (GIL)
where possible. A potential use case is in speeding up the batch computation of several large DWTs using multi-
threading (e.g. via concurrent.futures).
The axis specific transform support introduced in the prior release was extended to the multilevel DWT transforms.
All wavedec* and waverec* routines have a new axis (1D) or axes (2D, nD) keyword argument. If unspecified
the default behaviour is to transform all axes of the input.
Stationary wavelet transforms are now faster when the number of levels is greater than one. The improvement can be
very large (multiple orders of magnitude) for transforms with a large number of levels.
Deprecated features
A FutureWarning was added to swt2 and iswt2 to warn about a pending backwards incompatible change to the
order of the coefficients in the list returned by these routines. The actual change will not occur until the next release.
Transform coefficients will be returned in descending rather than ascending order. This change is being made for
consistency with all other existing multi-level transforms in PyWavelets.
Bugs Fixed
Other changes
A substantial overhaul of the C extension code has been performed. Custom templating is no longer used. The
intention is to make this code easier to maintain and expand in the future.
The Cython code has been split out into a multiple files to hopefully make relevant portions of the wrappers easier to
find for future developers.
setup.py now relies on setuptools in all cases (rather than distutils).
Authors
• Jonathan Dan +
• Ralf Gommers
• David Menéndez Hurtado
• Gregory R. Lee
• Holger Nahrstaedt +
• Daniel M. Pelt +
• Alexandre Saint +
• Scott Sievert +
• Kai Wohlfahrt
• Frank Yu +
A total of 10 people contributed to this release. People with a “+” by their names contributed a patch for the first time.
This list of names is automatically generated, and may not be fully complete.
• #148: Reorganize C v2
• #161: Remove numpy distutils
• #162: fix: iswt/idwt performance regression
• #164: Improved coefficients for db and coif
• #167: Add coverage (codecov.io)
• #168: convert transform coefficients to and from a single n-dimensional array
• #169: Remove templating
• #170: :Always install new pip on Appveyor
• #172: Adding of missing wavelets from the matlab list
• #178: use Index_t instead of index_t
• #179: add axis/axes support to multilevel discrete wavelet transforms
• #181: Fix memory leak
• #182: improve test coverage for _multidim.py and _multilevel.py
• #183: improve coverage for _dwt.py
• #184: fix corner case in coeffs_to_array
• #188: Drop GIL in c_wt calls
• #190: bump minimum numpy to 1.9
• #192: Upgrade to Pillow>=3 api
• #193: ENH: add ‘reflect’ extension mode
• #197: BLD: fix “python setup.py develop”. Closes gh-196
• #198: Choose clz* based on SIZE_MAX
• #201: speedup multi-level swt
• #205: fix dwtn/idwtn with axes != None and complex data
• #206: DOC: correct typo in iswt docstring
• #207: minor documentation updates
• #208: document coeff_to_array and array_to_coeff
• #214: FIX: update several doctests to reflect the new wavelets added
• #218: FIX: initialize all properties of a blank discrete wavelet
• #219: document coordinate conventions for 2D DWT routines.
• #220: Run doctests on TravisCI
• #221: Documentation for cwt and ContinuousWavelet
• #222: consistent use of double backticks in docs
Contents
We are very pleased to announce the release of PyWavelets 1.0. We view this version number as a milestone in the
project’s now more than a decade long history. It reflects that PyWavelets has stabilized over the past few years, and
is now a mature package which a lot of other important packages depend on. A listing of those package won’t be
complete, but some we are aware of are:
New features
Many common synthetic 1D test signals have been implemented in the new function pywt.data.
demo_signals to encourage reproducible research. To get a list of the available signals, call pywt.data.
demo_signals('list'). These signals have been validated to match the test signals of the same name from
the Wavelab toolbox (with the kind permission of Dr. David Donoho).
The Cython modules and underlying C library can now be built with C99 complex support when supported by the
compiler. Doing so improves performance when running wavelet transforms on complex-valued data. On POSIX
systems (Linux, Mac OS X), C99 complex support is enabled by default at build time. The user can set the environment
variable USE_C99_COMPLEX to 0 or 1 to manually disable or enable C99 support at compile time.
complex-valued CWT
The continuous wavelet transform, cwt, now also accepts complex-valued data.
The continous wavelets "cmor", "shan" and "fbsp" now let the user specify attributes such as their center fre-
quency and bandwidth that were previously fixed. See more on this in the section on deprecated features.
A new variant of the multilevel n-dimensional DWT has been implemented. It is known as the fully separable wavelet
transform (FSWT). The functions fswavedecn fswaverecn correspond to the forward and inverse transforms,
respectively. This differs from the existing wavedecn and waverecn in dimensions >= 2 in that all levels of
decomposition are performed along a single axis prior to moving on to the next.
pywt.threshold now supports non-negative Garotte thresholding (mode='garotte'). There is also a new
function pywt.threshold_firm that implements firm (semi-soft) thresholding. Both of the these new threshold-
ing methods are intermediate between soft and hard thresholding.
Two new boundary handling modes for the discrete wavelet transforms have been implemented. These correspond to
whole-sample and half-sample anti-symmetric boundary conditions (antisymmetric and antireflect).
The function ravel_coeffs can be used to ravel all coefficients from wavedec, wavedec2 or wavedecn
into a single 1D array. Unraveling back into a list of individual n-dimensional coefficients can be performed by
unravel_coeffs.
The new function wavedecn_size outputs the total number of coefficients that will be produced by a wavedecn
decomposition. The function wavedecn_shapes returns full shape information for all coefficient arrays produced
by wavedecn. These functions provide the size/shape information without having to explicitly compute a transform.
Deprecated features
The continous wavelets with names "cmor", "shan" and "fbsp" should now be modified to include formerly
hard-coded attributes such as their center frequency and bandwidth. Use of the bare names “cmor”. “shan” and
“fbsp” is now deprecated. For “cmor” (and “shan”), the form of the wavelet name is now “cmorB-C” (“shanB-C”)
where B and C are floats representing the bandwidth frequency and center frequency. For “fbsp” the form should now
incorporate three floats as in “fbspM-B-C” where M is the spline order and B and C are the bandwidth and center
frequencies.
Bugs Fixed
Assigning new data to the Node or Node2D no longer forces a cast to float64 when the data is one of the other
dtypes supported by the dwt (float32, complex64, complex128).
Calling pywt.threshold with mode='soft' now works properly for complex-valued inputs.
A segfault when running multiple swt2 or swtn transforms concurrently has been fixed.
Several instances of deprecated numpy multi-indexing that caused warnings in numpy >=1.15 have been resolved.
The 2d inverse stationary wavelet transform, iswt2, now supports non-square inputs (an unnecessary check for square
inputs was removed).
Wavelet packets no longer convert float32 to float64 upon assignment to nodes.
Doctests have been updated to also work with NumPy >= 1.14,
Indexing conventions have been updated to avoid FutureWarnings in NumPy 1.15.
Other changes
Authors
• 0-tree +
• Jacopo Antonello +
• Matthew Brett +
• Saket Choudhary +
• Michael V. DePalatis +
• Daniel Goertzen +
• Ralf Gommers
• Mark Harfouche +
• John Kirkham +
• Dawid Laszuk +
• Gregory R. Lee
• Michel Pelletier +
• Balint Reczey +
• SylvainLan +
• Daniele Tricoli
• Kai Wohlfahrt
A total of 16 people contributed to this release. People with a “+” by their names contributed a patch for the first time.
This list of names is automatically generated, and may not be fully complete.
• #380: BLD: fix doc build on ReadTheDocs, need matplotlib for plots. . .
• #381: Fix corner case for small scales in CWT
• #382: avoid FutureWarnings related to multiindexing in Numpy1.15
• #383: adding Community guidelines
• #384: swap swt2 coefficient order (and remove FutureWarnings)
• #387: improve CWT docs
• #390: MAINT: update Python version support. Closes gh-385.
• #391: fix broken link in documentation
• #392: do not force float64 dtype on assignment to Node, Node2D
• #398: MAINT: update .gitignore for files generated during build.
• #401: Fix failing numpy 1.9.3 build on Travis CI
• #403: Change ValueError to UserWarning when level is > dwt_max_level
• #404: BLD: fix ReadTheDocs build. Outdated NumPy gave a conflict with MPL.
• #410: DOC: rewrite docs front page
• #413: add wavelets.pybytes.com disclaimer
Contents
New features
Deprecated features
Bugs Fixed
Other changes
Authors
[Mall89] Mallat, S.G. “A Theory for Multiresolution Signal Decomposition: The Wavelet Representation”
IEEE Transactions on Pattern Analysis and Machine Intelligence, vol. 2, no. 7. July 1989. DOI:
10.1109/34.192463
[Wick94] Wickerhauser, M.V. “Adapted Wavelet Analysis from Theory to Software” Wellesley. Massachusetts: A K
Peters. 1994.
[1] PH Westerink. Subband Coding of Images. Ph.D. dissertation, Dept. Elect. Eng., Inf. Theory Group,
Delft Univ. Technol., Delft, The Netherlands, 1989. (see Section 2.3) http://resolver.tudelft.nl/uuid:
a4d195c3-1f89-4d66-913d-db9af0969509
[2] CP Rosiene and TQ Nguyen. Tensor-product wavelet vs. Mallat decomposition: A comparative analysis, in
Proc. IEEE Int. Symp. Circuits and Systems, Orlando, FL, Jun. 1999, pp. 431-434.
[3] V Velisavljevic, B Beferull-Lozano, M Vetterli and PL Dragotti. Directionlets: Anisotropic Multidirectional
Representation With Separable Filtering. IEEE Transactions on Image Processing, Vol. 15, No. 7, July 2006.
[4] RA DeVore, SV Konyagin and VN Temlyakov. “Hyperbolic wavelet approximation,” Constr. Approx. 14
(1998), 1-26.
[1] PH Westerink. Subband Coding of Images. Ph.D. dissertation, Dept. Elect. Eng., Inf. Theory Group,
Delft Univ. Technol., Delft, The Netherlands, 1989. (see Section 2.3) http://resolver.tudelft.nl/uuid:
a4d195c3-1f89-4d66-913d-db9af0969509
[2] CP Rosiene and TQ Nguyen. Tensor-product wavelet vs. Mallat decomposition: A comparative analysis, in
Proc. IEEE Int. Symp. Circuits and Systems, Orlando, FL, Jun. 1999, pp. 431-434.
[3] V Velisavljevic, B Beferull-Lozano, M Vetterli and PL Dragotti. Directionlets: Anisotropic Multidirectional
Representation With Separable Filtering. IEEE Transactions on Image Processing, Vol. 15, No. 7, July 2006.
[4] RA DeVore, SV Konyagin and VN Temlyakov. “Hyperbolic wavelet approximation,” Constr. Approx. 14
(1998), 1-26.
[1] DB Percival and AT Walden. Wavelet Methods for Time Series Analysis. Cambridge University Press, 2000.
[1] D.L. Donoho and I.M. Johnstone. Ideal Spatial Adaptation via Wavelet Shrinkage. Biometrika. Vol. 81, No.
3, pp.425-455, 1994. DOI:10.1093/biomet/81.3.425
[2] L. Breiman. Better Subset Regression Using the Nonnegative Garrote. Technometrics, Vol. 37, pp. 373-384,
1995. DOI:10.2307/1269730
115
PyWavelets Documentation, Release 1.1.0.dev0+399196a
[3] H-Y. Gao. Wavelet Shrinkage Denoising Using the Non-Negative Garrote. Journal of Computational and
Graphical Statistics Vol. 7, No. 4, pp.469-488. 1998. DOI:10.1080/10618600.1998.10474789
[1] H.-Y. Gao and A.G. Bruce. Waveshrink with firm shrinkage. Statistica Sinica, Vol. 7, pp. 855-874, 1997.
[2] A. Bruce and H-Y. Gao. WaveShrink: Shrinkage Functions and Thresholds. Proc. SPIE 2569, Wavelet
Applications in Signal and Image Processing III, 1995. DOI:10.1117/12.217582
[1] D.L. Donoho and I.M. Johnstone. Ideal spatial adaptation by wavelet shrinkage. Biometrika, vol. 81, pp.
425–455, 1994.
[2] S. Mallat. A Wavelet Tour of Signal Processing: The Sparse Way. Academic Press. 2009.
116 Bibliography
Index
117
PyWavelets Documentation, Release 1.1.0.dev0+399196a
S
scale2frequency() (in module pywt), 65
short_family_name (pywt.ContinuousWavelet at-
tribute), 17
short_family_name (pywt.Wavelet attribute), 14
short_name (pywt.Wavelet attribute), 14
swt() (in module pywt), 45
swt2() (in module pywt), 47
swt_max_level() (in module pywt), 49
swtn() (in module pywt), 48
symmetry (pywt.ContinuousWavelet attribute), 17
symmetry (pywt.Wavelet attribute), 14
T
threshold() (in module pywt), 61
threshold_firm() (in module pywt), 62
U
unravel_coeffs() (in module pywt), 43
118 Index