/usr/lib/python2.7/dist-packages/pywt/_multidim.py is in python-pywt 0.5.1-1.1ubuntu4.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | # Copyright (c) 2006-2012 Filip Wasilewski <http://en.ig.ma/>
# Copyright (c) 2012-2016 The PyWavelets Developers
# <https://github.com/PyWavelets/pywt>
# See COPYING for license details.
"""
2D and nD Discrete Wavelet Transforms and Inverse Discrete Wavelet Transforms.
"""
from __future__ import division, print_function, absolute_import
__all__ = ['dwt2', 'idwt2', 'dwtn', 'idwtn']
from itertools import product
import numpy as np
from ._extensions._pywt import Wavelet, Modes
from ._extensions._dwt import dwt_axis, idwt_axis
def dwt2(data, wavelet, mode='symmetric', axes=(-2, -1)):
"""
2D Discrete Wavelet Transform.
Parameters
----------
data : array_like
2D array with input data
wavelet : Wavelet object or name string
Wavelet to use
mode : str, optional
Signal extension mode, see Modes (default: 'symmetric')
axes : 2-tuple of ints, optional
Axes over which to compute the DWT. Repeated elements mean the DWT will
be performed multiple times along these axes.
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
--------
>>> import numpy as np
>>> import pywt
>>> data = np.ones((4,4), dtype=np.float64)
>>> coeffs = pywt.dwt2(data, 'haar')
>>> cA, (cH, cV, cD) = coeffs
>>> cA
array([[ 2., 2.],
[ 2., 2.]])
>>> cV
array([[ 0., 0.],
[ 0., 0.]])
"""
axes = tuple(axes)
data = np.asarray(data)
if len(axes) != 2:
raise ValueError("Expected 2 axes")
if data.ndim < len(np.unique(axes)):
raise ValueError("Input array has fewer dimensions than the specified "
"axes")
coefs = dwtn(data, wavelet, mode, axes)
return coefs['aa'], (coefs['da'], coefs['ad'], coefs['dd'])
def idwt2(coeffs, wavelet, mode='symmetric', axes=(-2, -1)):
"""
2-D Inverse Discrete Wavelet Transform.
Reconstructs data from coefficient arrays.
Parameters
----------
coeffs : tuple
(cA, (cH, cV, cD)) A tuple with approximation coefficients and three
details coefficients 2D arrays like from `dwt2()`
wavelet : Wavelet object or name string
Wavelet to use
mode : str, optional
Signal extension mode, see Modes (default: 'symmetric')
axes : 2-tuple of ints, optional
Axes over which to compute the IDWT. Repeated elements mean the IDWT
will be performed multiple times along these axes.
Examples
--------
>>> import numpy as np
>>> import pywt
>>> data = np.array([[1,2], [3,4]], dtype=np.float64)
>>> coeffs = pywt.dwt2(data, 'haar')
>>> pywt.idwt2(coeffs, 'haar')
array([[ 1., 2.],
[ 3., 4.]])
"""
# L -low-pass data, H - high-pass data
LL, (HL, LH, HH) = coeffs
axes = tuple(axes)
if len(axes) != 2:
raise ValueError("Expected 2 axes")
coeffs = {'aa': LL, 'da': HL, 'ad': LH, 'dd': HH}
# drop the keys corresponding to value = None
coeffs = dict((k, v) for k, v in coeffs.items() if v is not None)
return idwtn(coeffs, wavelet, mode, axes)
def dwtn(data, wavelet, mode='symmetric', axes=None):
"""
Single-level n-dimensional Discrete Wavelet Transform.
Parameters
----------
data : array_like
n-dimensional array with input data.
wavelet : Wavelet object or name string
Wavelet to use.
mode : str, optional
Signal extension mode, see `Modes`. Default is 'symmetric'.
axes : sequence of ints, optional
Axes over which to compute the DWT. Repeated elements mean the DWT will
be performed multiple times along these axes. A value of ``None`` (the
default) selects all axes.
Axes may be repeated, but information about the original size may be
lost if it is not divisible by ``2 ** nrepeats``. The reconstruction
will be larger, with additional values derived according to the
``mode`` parameter. ``pywt.wavedecn`` should be used for multilevel
decomposition.
Returns
-------
coeffs : dict
Results are arranged in a dictionary, where key specifies
the transform type on each dimension and value is a n-dimensional
coefficients array.
For example, for a 2D case the result will look something like this::
{'aa': <coeffs> # A(LL) - approx. on 1st dim, approx. on 2nd dim
'ad': <coeffs> # V(LH) - approx. on 1st dim, det. on 2nd dim
'da': <coeffs> # H(HL) - det. on 1st dim, approx. on 2nd dim
'dd': <coeffs> # D(HH) - det. on 1st dim, det. on 2nd dim
}
For user-specified ``axes``, the order of the characters in the
dictionary keys map to the specified ``axes``.
"""
data = np.asarray(data)
if np.iscomplexobj(data):
real = dwtn(data.real, wavelet, mode, axes)
imag = dwtn(data.imag, wavelet, mode, axes)
return dict((k, real[k] + 1j * imag[k]) for k in real.keys())
if data.dtype == np.dtype('object'):
raise TypeError("Input must be a numeric array-like")
if data.ndim < 1:
raise ValueError("Input data must be at least 1D")
if axes is None:
axes = range(data.ndim)
axes = (a + data.ndim if a < 0 else a for a in axes)
mode = Modes.from_object(mode)
if not isinstance(wavelet, Wavelet):
wavelet = Wavelet(wavelet)
coeffs = [('', data)]
for axis in axes:
new_coeffs = []
for subband, x in coeffs:
cA, cD = dwt_axis(x, wavelet, mode, axis)
new_coeffs.extend([(subband + 'a', cA),
(subband + 'd', cD)])
coeffs = new_coeffs
return dict(coeffs)
def _fix_coeffs(coeffs):
missing_keys = [k for k, v in coeffs.items() if
v is None]
if missing_keys:
raise ValueError(
"The following detail coefficients were set to None: "
"{}.".format(missing_keys))
invalid_keys = [k for k, v in coeffs.items() if
not set(k) <= set('ad')]
if invalid_keys:
raise ValueError(
"The following invalid keys were found in the detail "
"coefficient dictionary: {}.".format(invalid_keys))
key_lengths = [len(k) for k in coeffs.keys()]
if len(np.unique(key_lengths)) > 1:
raise ValueError(
"All detail coefficient names must have equal length.")
return dict((k, np.asarray(v)) for k, v in coeffs.items())
def idwtn(coeffs, wavelet, mode='symmetric', axes=None):
"""
Single-level n-dimensional Inverse Discrete Wavelet Transform.
Parameters
----------
coeffs: dict
Dictionary as in output of `dwtn`. Missing or None items
will be treated as zeroes.
wavelet : Wavelet object or name string
Wavelet to use
mode : str, optional
Signal extension mode used in the decomposition,
see Modes (default: 'symmetric').
axes : sequence of ints, optional
Axes over which to compute the IDWT. Repeated elements mean the IDWT
will be performed multiple times along these axes. A value of ``None``
(the default) selects all axes.
For the most accurate reconstruction, the axes should be provided in
the same order as they were provided to ``dwtn``.
Returns
-------
data: ndarray
Original signal reconstructed from input data.
"""
if not isinstance(wavelet, Wavelet):
wavelet = Wavelet(wavelet)
mode = Modes.from_object(mode)
# Raise error for invalid key combinations
coeffs = _fix_coeffs(coeffs)
if any(np.iscomplexobj(v) for v in coeffs.values()):
real_coeffs = dict((k, v.real) for k, v in coeffs.items())
imag_coeffs = dict((k, v.imag) for k, v in coeffs.items())
return (idwtn(real_coeffs, wavelet, mode, axes) +
1j * idwtn(imag_coeffs, wavelet, mode, axes))
# key length matches the number of axes transformed
ndim_transform = max(len(key) for key in coeffs.keys())
try:
coeff_shapes = (v.shape for k, v in coeffs.items()
if v is not None and len(k) == ndim_transform)
coeff_shape = next(coeff_shapes)
except StopIteration:
raise ValueError("`coeffs` must contain at least one non-null wavelet "
"band")
if any(s != coeff_shape for s in coeff_shapes):
raise ValueError("`coeffs` must all be of equal size (or None)")
if axes is None:
axes = range(ndim_transform)
ndim = ndim_transform
else:
ndim = len(coeff_shape)
axes = (a + ndim if a < 0 else a for a in axes)
for key_length, axis in reversed(list(enumerate(axes))):
if axis < 0 or axis >= ndim:
raise ValueError("Axis greater than data dimensions")
new_coeffs = {}
new_keys = [''.join(coef) for coef in product('ad', repeat=key_length)]
for key in new_keys:
L = coeffs.get(key + 'a', None)
H = coeffs.get(key + 'd', None)
new_coeffs[key] = idwt_axis(L, H, wavelet, mode, axis)
coeffs = new_coeffs
return coeffs['']
|