PyWavelets-0.5.1/ 0000755 >SK[ >P00000000000 13017376011 015555 5 ustar lee8rx domain^users 0000000 0000000 PyWavelets-0.5.1/CHANGES.txt 0000755 >SK[ >P00000004144 13017375740 017404 0 ustar lee8rx domain^users 0000000 0000000 Changelog
unreleased:
changes:
- most operations now drop the Python GIL to allow efficient threading
0.4.0
changes:
- idwt no longer takes a 'correct_size' parameter.
- Sizes of the arrays passed to all idwt functions must match exactly.
- use 'multilevel.wavecrec' for multilevel transforms
0.3.0
A major refactoring, providing support for Python 3.x while maintaining
full backwards compatiblity.
Development has moved to https://github.com/PyWavelets/pywt
0.2.2
maintenance release:
- resolved setup and build issues
- support for compilation using MSVC compiler
- updated documentation
- moved main repository to GitHub (https://github.com/nigma/pywt)
0.2.0
changes:
- 2D Wavelet Packet and Inverse Wavelet Packet Transforms
- 2D Stationary Wavelet Transform
- Single and double precision computations
- DWT and IDWT optimizations
- refactored Wavelet Packet code
0.1.6
changes:
- argument order changed for wavedec to be more consistent with other
functions. Now is (data, wavelet, *mode*, *level*).
- added 2D DWT and IDWT (dwt2, idwt2)
- added 2D multilevel transform - wavedec2 and waverec2
- added support for Python 2.5 (requires modified Pyrex, see the documentation)
- using Python memory management functions instead of C stdlib ones
fixes:
- rbior wavelets filters corrected
0.1.4
changes:
- Wavelet class can be subclassed
- requires NumPy, edit numerix.py to use with other numeric modules,
array.array is no more directly supported
- code cleanup & comments
- wavedec and waverec Pyrex code moved to pure Python multilevel.py
module
- doctesting doc examples
fixes:
- fixed swt for too high level value
- fixed bug in upcoef wrapper code for some take values
0.1.2
changes:
- support for custom filter banks
- now compiles without numpy installed
fixes:
- fixed handling of non-contiguous arrays
0.1.0
initial release
PyWavelets-0.5.1/demo/ 0000755 >SK[ >P00000000000 13017376010 016500 5 ustar lee8rx domain^users 0000000 0000000 PyWavelets-0.5.1/demo/batch_processing.py 0000755 >SK[ >P00000006577 13017375740 022422 0 ustar lee8rx domain^users 0000000 0000000 """
Demo: Parallel processing accross images
Multithreading can be used to run transforms on a set of images in parallel.
This will give a net performance benefit if the images to be transformed are
sufficiently large.
This demo runs a multilevel wavelet decomposition on a list of 32 images,
each of size (512, 512). Computations are repeated sequentially and in
parallel and the runtimes compared.
In general, multithreading will be more beneficial for larger images and for
wavelets with a larger filter size.
One can also change ``ndim`` to 3 in the code below to use a set of 3D volumes
instead.
"""
import time
from functools import partial
from multiprocessing import cpu_count
try:
from concurrent import futures
except ImportError:
raise ImportError(
"This demo requires concurrent.futures. It can be installed for "
"for python 2.x via: pip install futures")
import numpy as np
from numpy.testing import assert_array_equal
import pywt
# the test image
cam = pywt.data.camera().astype(float)
ndim = 2 # dimension of images to transform (2 or 3)
num_images = 32 # number of images to transform
max_workers = cpu_count() # max number of available threads
nrepeat = 5 # averages used in the benchmark
# create a list of num_images images
if ndim == 2:
imgs = [cam, ] * num_images
wavelet = 'db8'
elif ndim == 3:
# stack image along 3rd dimension to create a [512 x 512 x 16] 3D volume
im3 = np.concatenate([cam[:, :, np.newaxis], ]*16, axis=-1)
# create multiple copies of the volume
imgs = [im3, ] * num_images
wavelet = 'db1'
else:
ValueError("Only 2D and 3D test cases implemented")
# define a function to apply to each image
wavedecn_func = partial(pywt.wavedecn, wavelet=wavelet, mode='periodization',
level=3)
def concurrent_transforms(func, imgs, max_workers=None):
"""Call func on each img in imgs using a ThreadPoolExecutor."""
executor = futures.ThreadPoolExecutor
if max_workers is None:
# default to as many workers as available cpus
max_workers = cpu_count()
results = []
with executor(max_workers=max_workers) as execute:
for result in execute.map(func, imgs):
results.append(result)
return results
print("Processing {} images of shape {}".format(len(imgs), imgs[0].shape))
# Sequential computation via a list comprehension
tstart = time.time()
for n in range(nrepeat):
results = [wavedecn_func(img) for img in imgs]
t = (time.time()-tstart)/nrepeat
print("\nSequential Case")
print("\tElapsed time: {:0.2f} ms".format(1000*t))
# Concurrent computation via concurrent.futures
tstart = time.time()
for n in range(nrepeat):
results_concurrent = concurrent_transforms(wavedecn_func, imgs,
max_workers=max_workers)
t2 = (time.time()-tstart)/nrepeat
print("\nMultithreaded Case")
print("\tNumber of concurrent workers: {}".format(max_workers))
print("\tElapsed time: {:0.2f} ms".format(1000*t2))
print("\nRelative speedup with concurrent = {}".format(t/t2))
# check a couple of the coefficient arrays to verify matching results for
# sequential and multithreaded computation
assert_array_equal(results[-1][0],
results_concurrent[-1][0])
assert_array_equal(results[-1][1]['d' + 'a'*(ndim-1)],
results_concurrent[-1][1]['d' + 'a'*(ndim-1)])
PyWavelets-0.5.1/demo/benchmark.py 0000755 >SK[ >P00000003570 13017375740 021025 0 ustar lee8rx domain^users 0000000 0000000 #!/usr/bin/env python
# -*- coding: utf-8 -*-
import gc
import sys
import time
import numpy as np
import matplotlib.pyplot as plt
import pywt
if sys.platform == 'win32':
clock = time.clock
else:
clock = time.time
sizes = [20, 50, 100, 120, 150, 200, 250, 300, 400, 500, 600, 750,
1000, 2000, 3000, 4000, 5000, 6000, 7500,
10000, 15000, 20000, 25000, 30000, 40000, 50000, 75000,
100000, 150000, 200000, 250000, 300000, 400000, 500000,
600000, 750000, 1000000, 2000000, 5000000][:-4]
wavelet_names = ['db1', 'db2', 'db3', 'db4', 'db5', 'db6', 'db7',
'db8', 'db9', 'db10', 'sym10', 'coif1', 'coif2',
'coif3', 'coif4', 'coif5']
wavelets = [pywt.Wavelet(n) for n in wavelet_names]
mode = pywt.Modes.zero
times_dwt = [[] for i in range(len(wavelets))]
times_idwt = [[] for i in range(len(wavelets))]
for j, size in enumerate(sizes):
data = np.ones((size,), dtype=np.float64)
print((("%d/%d" % (j + 1, len(sizes))).rjust(6), str(size).rjust(9)))
for i, w in enumerate(wavelets):
min_t1, min_t2 = 9999., 9999.
for _ in range(5):
# Repeat timing 5 times to reduce run-to-run variation
t1 = clock()
(a, d) = pywt.dwt(data, w, mode)
t1 = clock() - t1
min_t1 = min(t1, min_t1)
t2 = clock()
a0 = pywt.idwt(a, d, w, mode)
t2 = clock() - t2
min_t2 = min(t2, min_t2)
times_dwt[i].append(min_t1)
times_idwt[i].append(min_t2)
gc.collect()
for j, (times, name) in enumerate([(times_dwt, 'dwt'), (times_idwt, 'idwt')]):
fig = plt.figure(j)
ax = fig.add_subplot(111)
ax.set_title(name)
for i, n in enumerate(wavelet_names):
ax.loglog(sizes, times[i], label=n)
ax.legend(loc='best')
ax.set_xlabel('len(x)')
ax.set_ylabel('time [s]')
plt.show()
PyWavelets-0.5.1/demo/cwt_analysis.py 0000755 >SK[ >P00000001646 13017375740 021575 0 ustar lee8rx domain^users 0000000 0000000 #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import pywt
time, sst = pywt.data.nino()
dt = time[1]-time[0]
# Taken from http://nicolasfauchereau.github.io/climatecode/posts/wavelet-analysis-in-python/
wavelet = 'cmor'
scales = np.arange(1,128)
[cfs,frequencies] = pywt.cwt(sst,scales,wavelet,dt)
power = (abs(cfs)) ** 2
period = 1. / frequencies
levels = [0.0625, 0.125, 0.25, 0.5, 1, 2, 4, 8]
f, ax = plt.subplots(figsize=(15,10))
ax.contourf(time, np.log2(period), np.log2(power), np.log2(levels),
extend='both')
ax.set_title('%s Wavelet Power Spectrum (%s)' % ('Nino1+2', wavelet))
ax.set_ylabel('Period (years)')
Yticks = 2 ** np.arange(np.ceil(np.log2(period.min())),
np.ceil(np.log2(period.max())))
ax.set_yticks(np.log2(Yticks))
ax.set_yticklabels(Yticks)
ax.invert_yaxis()
ylim = ax.get_ylim()
ax.set_ylim(ylim[0], -1)
plt.show()
PyWavelets-0.5.1/demo/dwt2_dwtn_image.py 0000755 >SK[ >P00000003304 13017375740 022144 0 ustar lee8rx domain^users 0000000 0000000 #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import pywt
import pywt.data
# Load image
original = pywt.data.aero()
# Wavelet transform of image, and plot approximation and details
titles = ['Approximation', ' Horizontal detail',
'Vertical detail', 'Diagonal detail']
coeffs2 = pywt.dwt2(original, 'bior1.3')
LL, (LH, HL, HH) = coeffs2
fig = plt.figure()
for i, a in enumerate([LL, LH, HL, HH]):
ax = fig.add_subplot(2, 2, i + 1)
ax.imshow(a, origin='image', interpolation="nearest", cmap=plt.cm.gray)
ax.set_title(titles[i], fontsize=12)
fig.suptitle("dwt2 coefficients", fontsize=14)
# Now reconstruct and plot the original image
reconstructed = pywt.idwt2(coeffs2, 'bior1.3')
fig = plt.figure()
plt.imshow(reconstructed, interpolation="nearest", cmap=plt.cm.gray)
# Check that reconstructed image is close to the original
np.testing.assert_allclose(original, reconstructed, atol=1e-13, rtol=1e-13)
# Now do the same with dwtn/idwtn, to show the difference in their signatures
coeffsn = pywt.dwtn(original, 'bior1.3')
fig = plt.figure()
for i, key in enumerate(['aa', 'ad', 'da', 'dd']):
ax = fig.add_subplot(2, 2, i + 1)
ax.imshow(coeffsn[key], origin='image', interpolation="nearest",
cmap=plt.cm.gray)
ax.set_title(titles[i], fontsize=12)
fig.suptitle("dwtn coefficients", fontsize=14)
# Now reconstruct and plot the original image
reconstructed = pywt.idwtn(coeffsn, 'bior1.3')
fig = plt.figure()
plt.imshow(reconstructed, interpolation="nearest", cmap=plt.cm.gray)
# Check that reconstructed image is close to the original
np.testing.assert_allclose(original, reconstructed, atol=1e-13, rtol=1e-13)
plt.show()
PyWavelets-0.5.1/demo/dwt_signal_decomposition.py 0000755 >SK[ >P00000003400 13017375740 024152 0 ustar lee8rx domain^users 0000000 0000000 #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import pywt
import pywt.data
ecg = pywt.data.ecg()
data1 = np.concatenate((np.arange(1, 400),
np.arange(398, 600),
np.arange(601, 1024)))
x = np.linspace(0.082, 2.128, num=1024)[::-1]
data2 = np.sin(40 * np.log(x)) * np.sign((np.log(x)))
mode = pywt.Modes.smooth
def plot_signal_decomp(data, w, title):
"""Decompose and plot a signal S.
S = An + Dn + Dn-1 + ... + D1
"""
w = pywt.Wavelet(w)
a = data
ca = []
cd = []
for i in range(5):
(a, d) = pywt.dwt(a, w, mode)
ca.append(a)
cd.append(d)
rec_a = []
rec_d = []
for i, coeff in enumerate(ca):
coeff_list = [coeff, None] + [None] * i
rec_a.append(pywt.waverec(coeff_list, w))
for i, coeff in enumerate(cd):
coeff_list = [None, coeff] + [None] * i
rec_d.append(pywt.waverec(coeff_list, w))
fig = plt.figure()
ax_main = fig.add_subplot(len(rec_a) + 1, 1, 1)
ax_main.set_title(title)
ax_main.plot(data)
ax_main.set_xlim(0, len(data) - 1)
for i, y in enumerate(rec_a):
ax = fig.add_subplot(len(rec_a) + 1, 2, 3 + i * 2)
ax.plot(y, 'r')
ax.set_xlim(0, len(y) - 1)
ax.set_ylabel("A%d" % (i + 1))
for i, y in enumerate(rec_d):
ax = fig.add_subplot(len(rec_d) + 1, 2, 4 + i * 2)
ax.plot(y, 'g')
ax.set_xlim(0, len(y) - 1)
ax.set_ylabel("D%d" % (i + 1))
plot_signal_decomp(data1, 'coif5', "DWT: Signal irregularity")
plot_signal_decomp(data2, 'sym5',
"DWT: Frequency and phase change - Symmlets5")
plot_signal_decomp(ecg, 'sym5', "DWT: Ecg sample - Symmlets5")
plt.show()
PyWavelets-0.5.1/demo/dwt_swt_show_coeffs.py 0000755 >SK[ >P00000004645 13017375740 023157 0 ustar lee8rx domain^users 0000000 0000000 #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import pywt
import pywt.data
ecg = pywt.data.ecg()
data1 = np.concatenate((np.arange(1, 400),
np.arange(398, 600),
np.arange(601, 1024)))
x = np.linspace(0.082, 2.128, num=1024)[::-1]
data2 = np.sin(40 * np.log(x)) * np.sign((np.log(x)))
mode = pywt.Modes.sp1DWT = 1
def plot_coeffs(data, w, title, use_dwt=True):
"""Show dwt or swt coefficients for given data and wavelet."""
w = pywt.Wavelet(w)
a = data
ca = []
cd = []
if use_dwt:
for i in range(5):
(a, d) = pywt.dwt(a, w, mode)
ca.append(a)
cd.append(d)
else:
coeffs = pywt.swt(data, w, 5) # [(cA5, cD5), ..., (cA1, cD1)]
for a, d in reversed(coeffs):
ca.append(a)
cd.append(d)
fig = plt.figure()
ax_main = fig.add_subplot(len(ca) + 1, 1, 1)
ax_main.set_title(title)
ax_main.plot(data)
ax_main.set_xlim(0, len(data) - 1)
for i, x in enumerate(ca):
ax = fig.add_subplot(len(ca) + 1, 2, 3 + i * 2)
ax.plot(x, 'r')
ax.set_ylabel("A%d" % (i + 1))
if use_dwt:
ax.set_xlim(0, len(x) - 1)
else:
ax.set_xlim(w.dec_len * i, len(x) - 1 - w.dec_len * i)
for i, x in enumerate(cd):
ax = fig.add_subplot(len(cd) + 1, 2, 4 + i * 2)
ax.plot(x, 'g')
ax.set_ylabel("D%d" % (i + 1))
# Scale axes
ax.set_xlim(0, len(x) - 1)
if use_dwt:
ax.set_ylim(min(0, 1.4 * min(x)), max(0, 1.4 * max(x)))
else:
vals = x[w.dec_len * (1 + i):len(x) - w.dec_len * (1 + i)]
ax.set_ylim(min(0, 2 * min(vals)), max(0, 2 * max(vals)))
# Show DWT coefficients
use_dwt = True
plot_coeffs(data1, 'db1',
"DWT: Signal irregularity shown in D1 - Haar wavelet",
use_dwt)
plot_coeffs(data2, 'sym5', "DWT: Frequency and phase change - Symmlets5",
use_dwt)
plot_coeffs(ecg, 'sym5', "DWT: Ecg sample - Symmlets5", use_dwt)
# Show DWT coefficients
use_dwt = False
plot_coeffs(data1, 'db1', "SWT: Signal irregularity detection - Haar wavelet",
use_dwt)
plot_coeffs(data2, 'sym5', "SWT: Frequency and phase change - Symmlets5",
use_dwt)
plot_coeffs(ecg, 'sym5', "SWT: Ecg sample - simple QRS detection - Symmlets5",
use_dwt)
plt.show()
PyWavelets-0.5.1/demo/image_blender.py 0000755 >SK[ >P00000015535 13017375740 021654 0 ustar lee8rx domain^users 0000000 0000000 #!/usr/bin/env python
# Copyright (c) 2006-2012 Filip Wasilewski
# Copyright (c) 2012-2016 The PyWavelets Developers
#
# See COPYING for license details.
"""
Wavelet Image Blender.
Blend image A with texture extracted from image B by selecting
detail coefficients:
----------------- -----------------
| | | |
| | | |
| | | |
| A | | B |
| | | |
| | | |
| | | |
----------------- -----------------
| |
2D DWT | 2D DWT |
V V
----------------- --------- -----------------
| | | | | | |
| A(LL) | H(LH) | | H(LH) | | |
| | | | | IDWT | |
----------------- + ----------------- -----> | C |
| | | | | | | |
| V(HL) | D(HH) | | V(HL) | D(HH) | | |
| | | | | | | |
----------------- ----------------- -----------------
(details only)
"""
import optparse
import os
import sys
if os.name == 'nt':
from time import clock # noqa
else:
from time import time as clock # noqa
from PIL import Image # PIL
import numpy # http://www.scipy.org
import pywt
def image2array(image):
"""PIL Image to NumPy array"""
assert image.mode in ('L', 'RGB', 'CMYK')
arr = numpy.fromstring(image.tobytes(), numpy.uint8)
arr.shape = (image.size[1], image.size[0], len(image.getbands()))
return arr.swapaxes(0, 2).swapaxes(1, 2).astype(numpy.float32)
def array2image(arr, mode):
"""NumPy array to PIL Image"""
arr = arr.swapaxes(1, 2).swapaxes(0, 2)
arr[arr < 0] = 0
arr[arr > 255] = 255
arr = numpy.fix(arr).astype(numpy.uint8)
return Image.frombytes(mode, arr.shape[1::-1], arr.tobytes())
def load_image(path, mode=None, size=None):
"""Load image"""
im = Image.open(path)
if im.mode not in ('L', 'P', 'RGB', 'CMYK'):
raise TypeError("Image mode must be 'L', 'P', 'RGB' or 'CMYK'")
if mode is not None:
if mode == 'P':
raise ValueError("Mode must be 'L', 'RGB' or 'CMYK'")
im = im.convert(mode)
elif im.mode == 'P':
im = im.convert('RGB')
if size is not None and im.size != size:
im = im.resize(size, Image.ANTIALIAS)
return im
def blend_images(base, texture, wavelet, level, mode='smooth', base_gain=None,
texture_gain=None):
"""Blend loaded images at `level` of granularity using `wavelet`"""
base_data = image2array(base)
texture_data = image2array(texture)
output_data = []
# process color bands
for base_band, texture_band in zip(base_data, texture_data):
# multilevel dwt
base_band_coeffs = pywt.wavedec2(base_band, wavelet, mode, level)
texture_band_coeffs = pywt.wavedec2(texture_band, wavelet, mode, level)
# average coefficients of base image
output_band_coeffs = [base_band_coeffs[0]] # cA
del base_band_coeffs[0], texture_band_coeffs[0]
# blend details coefficients
for n, (base_band_details, texture_band_details) in enumerate(
zip(base_band_coeffs, texture_band_coeffs)):
blended_details = []
for (base_detail, texture_detail) in zip(base_band_details,
texture_band_details):
if base_gain is not None:
base_detail *= base_gain
if texture_gain is not None:
texture_detail *= texture_gain
# select coeffs with greater energy
blended = numpy.where(abs(base_detail) > abs(texture_detail),
base_detail, texture_detail)
blended_details.append(blended)
base_band_coeffs[n] = texture_band_coeffs[n] = None
output_band_coeffs.append(blended_details)
# multilevel idwt
new_band = pywt.waverec2(output_band_coeffs, wavelet, mode)
output_data.append(new_band)
del new_band, base_band_coeffs, texture_band_coeffs
del base_data, texture_data
output_data = numpy.array(output_data)
return array2image(output_data, base.mode)
def main():
usage = "usage: %prog -b BASE -t TEXTURE -o OUTPUT "\
"[-w WAVELET] [-l LEVEL] [-m MODE]"
parser = optparse.OptionParser(usage=usage)
parser.add_option("-b", "--base", dest="base", metavar="BASE",
help="base image name")
parser.add_option("-t", "--texture", dest="texture", metavar="TEXTURE",
help="texture image name")
parser.add_option("-o", "--output", dest="output", metavar="OUTPUT",
help="output image name")
parser.add_option("-w", "--wavelet", dest="wavelet", metavar="WAVELET",
default='db2', help="wavelet name [default: %default]")
parser.add_option("-l", "--level", dest="level", metavar="LEVEL",
type="int", default=4,
help="decomposition level [default: %default]")
parser.add_option("-m", "--mode", dest="mode", metavar="MODE",
default='symmetric',
help="decomposition mode. Adjust this if"
" getting edge artifacts [default: %default]")
parser.add_option("-x", "--base_gain", dest="base_gain", metavar="BG",
type="float", default=None,
help="Base image gain [default: %default]")
parser.add_option("-y", "--texture_gain", dest="texture_gain",
metavar="TG", type="float", default=None,
help="Texture image gain [default: %default]")
parser.add_option("--timeit", dest="timeit", action="store_true",
default=False, help="time blending operations")
(options, args) = parser.parse_args()
if None in (options.base, options.texture, options.output):
parser.print_help()
sys.exit(-1)
base = load_image(options.base)
texture = load_image(options.texture, base.mode, base.size)
if options.timeit:
t = clock()
im = blend_images(base, texture, options.wavelet, options.level,
options.mode, options.base_gain, options.texture_gain)
if options.timeit:
print("%.3fs" % (clock() - t))
im.save(options.output)
if __name__ == '__main__':
main()
PyWavelets-0.5.1/demo/plot_wavelets.py 0000755 >SK[ >P00000005140 13017375740 021756 0 ustar lee8rx domain^users 0000000 0000000 #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Plot scaling and wavelet functions for db, sym, coif, bior and rbio families
import itertools
import matplotlib.pyplot as plt
import pywt
plot_data = [('db', (4, 3)),
('sym', (4, 3)),
('coif', (3, 2))]
for family, (rows, cols) in plot_data:
fig = plt.figure()
fig.subplots_adjust(hspace=0.2, wspace=0.2, bottom=.02, left=.06,
right=.97, top=.94)
colors = itertools.cycle('bgrcmyk')
wnames = pywt.wavelist(family)
i = iter(wnames)
for col in range(cols):
for row in range(rows):
try:
wavelet = pywt.Wavelet(next(i))
except StopIteration:
break
phi, psi, x = wavelet.wavefun(level=5)
color = next(colors)
ax = fig.add_subplot(rows, 2 * cols, 1 + 2 * (col + row * cols))
ax.set_title(wavelet.name + " phi")
ax.plot(x, phi, color)
ax.set_xlim(min(x), max(x))
ax = fig.add_subplot(rows, 2*cols, 1 + 2*(col + row*cols) + 1)
ax.set_title(wavelet.name + " psi")
ax.plot(x, psi, color)
ax.set_xlim(min(x), max(x))
for family, (rows, cols) in [('bior', (4, 3)), ('rbio', (4, 3))]:
fig = plt.figure()
fig.subplots_adjust(hspace=0.5, wspace=0.2, bottom=.02, left=.06,
right=.97, top=.94)
colors = itertools.cycle('bgrcmyk')
wnames = pywt.wavelist(family)
i = iter(wnames)
for col in range(cols):
for row in range(rows):
try:
wavelet = pywt.Wavelet(next(i))
except StopIteration:
break
phi, psi, phi_r, psi_r, x = wavelet.wavefun(level=5)
row *= 2
color = next(colors)
ax = fig.add_subplot(2*rows, 2*cols, 1 + 2*(col + row*cols))
ax.set_title(wavelet.name + " phi")
ax.plot(x, phi, color)
ax.set_xlim(min(x), max(x))
ax = fig.add_subplot(2*rows, 2*cols, 2*(1 + col + row*cols))
ax.set_title(wavelet.name + " psi")
ax.plot(x, psi, color)
ax.set_xlim(min(x), max(x))
row += 1
ax = fig.add_subplot(2*rows, 2*cols, 1 + 2*(col + row*cols))
ax.set_title(wavelet.name + " phi_r")
ax.plot(x, phi_r, color)
ax.set_xlim(min(x), max(x))
ax = fig.add_subplot(2*rows, 2*cols, 1 + 2*(col + row*cols) + 1)
ax.set_title(wavelet.name + " psi_r")
ax.plot(x, psi_r, color)
ax.set_xlim(min(x), max(x))
plt.show()
PyWavelets-0.5.1/demo/swt2.py 0000755 >SK[ >P00000001306 13017375740 017765 0 ustar lee8rx domain^users 0000000 0000000 #!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import pywt
import pywt.data
arr = pywt.data.aero()
plt.imshow(arr, interpolation="nearest", cmap=plt.cm.gray)
level = 0
titles = ['Approximation', ' Horizontal detail',
'Vertical detail', 'Diagonal detail']
for LL, (LH, HL, HH) in pywt.swt2(arr, 'bior1.3', level=3, start_level=0):
fig = plt.figure()
for i, a in enumerate([LL, LH, HL, HH]):
ax = fig.add_subplot(2, 2, i + 1)
ax.imshow(a, origin='image', interpolation="nearest", cmap=plt.cm.gray)
ax.set_title(titles[i], fontsize=12)
fig.suptitle("SWT2 coefficients, level %s" % level, fontsize=14)
level += 1
plt.show()
PyWavelets-0.5.1/demo/waveinfo.py 0000755 >SK[ >P00000003645 13017375740 020714 0 ustar lee8rx domain^users 0000000 0000000 #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import matplotlib.pyplot as plt
import numpy as np
import pywt
usage = """
Usage:
python waveinfo.py waveletname
Example: python waveinfo.py 'sym5'
"""
try:
wavelet = pywt.Wavelet(sys.argv[1])
try:
level = int(sys.argv[2])
except IndexError as e:
level = 10
except ValueError as e:
print("Unknown wavelet")
raise SystemExit
except IndexError as e:
print(usage)
raise SystemExit
data = wavelet.wavefun(level)
if len(data) == 2:
x = data[1]
psi = data[0]
fig = plt.figure()
if wavelet.complex_cwt:
plt.subplot(211)
plt.title(wavelet.name+' real part')
mi, ma = np.real(psi).min(), np.real(psi).max()
margin = (ma - mi) * 0.05
plt.plot(x,np.real(psi))
plt.ylim(mi - margin, ma + margin)
plt.xlim(x[0], x[-1])
plt.subplot(212)
plt.title(wavelet.name+' imag part')
mi, ma = np.imag(psi).min(), np.imag(psi).max()
margin = (ma - mi) * 0.05
plt.plot(x,np.imag(psi))
plt.ylim(mi - margin, ma + margin)
plt.xlim(x[0], x[-1])
else:
mi, ma = psi.min(), psi.max()
margin = (ma - mi) * 0.05
plt.plot(x,psi)
plt.title(wavelet.name)
plt.ylim(mi - margin, ma + margin)
plt.xlim(x[0], x[-1])
else:
funcs, x = data[:-1], data[-1]
labels = ["scaling function (phi)", "wavelet function (psi)",
"r. scaling function (phi)", "r. wavelet function (psi)"]
colors = ("r", "g", "r", "g")
fig = plt.figure()
for i, (d, label, color) in enumerate(zip(funcs, labels, colors)):
mi, ma = d.min(), d.max()
margin = (ma - mi) * 0.05
ax = fig.add_subplot((len(data) - 1) // 2, 2, 1 + i)
ax.plot(x, d, color)
ax.set_title(label)
ax.set_ylim(mi - margin, ma + margin)
ax.set_xlim(x[0], x[-1])
plt.show()
PyWavelets-0.5.1/demo/wp_2d.py 0000755 >SK[ >P00000002436 13017375740 020106 0 ustar lee8rx domain^users 0000000 0000000 #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from pywt import WaveletPacket2D
import pywt.data
arr = pywt.data.aero()
wp2 = WaveletPacket2D(arr, 'db2', 'symmetric', maxlevel=2)
# Show original figure
plt.imshow(arr, interpolation="nearest", cmap=plt.cm.gray)
path = ['d', 'v', 'h', 'a']
# Show level 1 nodes
fig = plt.figure()
for i, p2 in enumerate(path):
ax = fig.add_subplot(2, 2, i + 1)
ax.imshow(np.sqrt(np.abs(wp2[p2].data)), origin='image',
interpolation="nearest", cmap=plt.cm.gray)
ax.set_title(p2)
# Show level 2 nodes
for p1 in path:
fig = plt.figure()
for i, p2 in enumerate(path):
ax = fig.add_subplot(2, 2, i + 1)
p1p2 = p1 + p2
ax.imshow(np.sqrt(np.abs(wp2[p1p2].data)), origin='image',
interpolation="nearest", cmap=plt.cm.gray)
ax.set_title(p1p2)
fig = plt.figure()
i = 1
for row in wp2.get_level(2, 'freq'):
for node in row:
ax = fig.add_subplot(len(row), len(row), i)
ax.set_title("%s=(%s row, %s col)" % (
(node.path,) + wp2.expand_2d_path(node.path)))
ax.imshow(np.sqrt(np.abs(node.data)), origin='image',
interpolation="nearest", cmap=plt.cm.gray)
i += 1
plt.show()
PyWavelets-0.5.1/demo/wp_scalogram.py 0000755 >SK[ >P00000002627 13017375740 021553 0 ustar lee8rx domain^users 0000000 0000000 #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import pywt
x = np.linspace(0, 1, num=512)
data = np.sin(250 * np.pi * x**2)
wavelet = 'db2'
level = 4
order = "freq" # other option is "normal"
interpolation = 'nearest'
cmap = plt.cm.cool
# Construct wavelet packet
wp = pywt.WaveletPacket(data, wavelet, 'symmetric', maxlevel=level)
nodes = wp.get_level(level, order=order)
labels = [n.path for n in nodes]
values = np.array([n.data for n in nodes], 'd')
values = abs(values)
# Show signal and wavelet packet coefficients
fig = plt.figure()
fig.subplots_adjust(hspace=0.2, bottom=.03, left=.07, right=.97, top=.92)
ax = fig.add_subplot(2, 1, 1)
ax.set_title("linchirp signal")
ax.plot(x, data, 'b')
ax.set_xlim(0, x[-1])
ax = fig.add_subplot(2, 1, 2)
ax.set_title("Wavelet packet coefficients at level %d" % level)
ax.imshow(values, interpolation=interpolation, cmap=cmap, aspect="auto",
origin="lower", extent=[0, 1, 0, len(values)])
ax.set_yticks(np.arange(0.5, len(labels) + 0.5), labels)
# Show spectrogram and wavelet packet coefficients
fig2 = plt.figure()
ax2 = fig2.add_subplot(211)
ax2.specgram(data, NFFT=64, noverlap=32, cmap=cmap)
ax2.set_title("Spectrogram of signal")
ax3 = fig2.add_subplot(212)
ax3.imshow(values, origin='upper', extent=[-1, 1, -1, 1],
interpolation='nearest')
ax3.set_title("Wavelet packet coefficients")
plt.show()
PyWavelets-0.5.1/demo/wp_visualize_coeffs_distribution.py 0000755 >SK[ >P00000001510 13017375740 025730 0 ustar lee8rx domain^users 0000000 0000000 #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import numpy as np
import matplotlib.pyplot as plt
from pywt import WaveletPacket
import pywt.data
ecg = pywt.data.ecg()
wp = WaveletPacket(ecg, 'sym5', maxlevel=4)
fig = plt.figure()
plt.set_cmap('bone')
ax = fig.add_subplot(wp.maxlevel + 1, 1, 1)
ax.plot(ecg, 'k')
ax.set_xlim(0, len(ecg) - 1)
ax.set_title("Wavelet packet coefficients")
for level in range(1, wp.maxlevel + 1):
ax = fig.add_subplot(wp.maxlevel + 1, 1, level + 1)
nodes = wp.get_level(level, "freq")
nodes.reverse()
labels = [n.path for n in nodes]
values = -abs(np.array([n.data for n in nodes]))
ax.imshow(values, interpolation='nearest', aspect='auto')
ax.set_yticks(np.arange(len(labels) - 0.5, -0.5, -1), labels)
plt.setp(ax.get_xticklabels(), visible=False)
plt.show()
PyWavelets-0.5.1/demo/_dwt_decompose.c 0000755 >SK[ >P00000002342 13017375740 021654 0 ustar lee8rx domain^users 0000000 0000000 /*
* Note: this currently doesn't get installed. There's also no way to query
* the location of wt.h. Conclusion: there is no C API.
*/
#include
#include "wt.h"
int main(){
// Using C API to decompose 1D signal.
// Results equivalent to pywt.dwt([1,2,3,4,5,6,7,8], 'db2', 'zpd').
// Compile: gcc -I../src dwt_decompose.c ../src/wt.c ../src/wavelets.c ../src/common.c ../src/convolution.c
Wavelet *w = wavelet('d', 2);
MODE mode = MODE_ZEROPAD;
int i;
float input[] = {1,2,3,4,5,6,7,8,9};
float *cA, *cD;
pywt_index_t input_len, output_len;
input_len = sizeof input / sizeof input[0];
output_len = dwt_buffer_length(input_len, w->dec_len, mode);
cA = wtcalloc(output_len, sizeof(float));
cD = wtcalloc(output_len, sizeof(float));
printf("Wavelet: %s %d\n\n", w->family_name, w->vanishing_moments_psi);
float_dec_a(input, input_len, w, cA, output_len, mode);
float_dec_d(input, input_len, w, cD, output_len, mode);
for(i=0; i