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 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
|
from functools import partial, reduce
import numpy as np
from ._multilevel import (_prep_axes_wavedecn, wavedec, wavedec2, wavedecn,
waverec, waverec2, waverecn)
from ._swt import iswt, iswt2, iswtn, swt, swt2, swt_max_level, swtn
from ._utils import _modes_per_axis, _wavelets_per_axis
__all__ = ["mra", "mra2", "mran", "imra", "imra2", "imran"]
def mra(data, wavelet, level=None, axis=-1, transform='swt',
mode='periodization'):
"""Forward 1D multiresolution analysis.
It is a projection onto the wavelet subspaces.
Parameters
----------
data: array_like
Input data
wavelet : Wavelet object or name string
Wavelet to use
level : int, optional
Decomposition level (must be >= 0). If level is None (default) then it
will be calculated using the `dwt_max_level` function.
axis: int, optional
Axis over which to compute the DWT. If not given, the last axis is
used. Currently only available when ``transform='dwt'``.
transform : {'dwt', 'swt'}
Whether to use the DWT or SWT for the transforms.
mode : str, optional
Signal extension mode, see `Modes` (default: 'symmetric'). This option
is only used when transform='dwt'.
Returns
-------
[cAn, {details_level_n}, ... {details_level_1}] : list
For more information, see the detailed description in `wavedec`
See Also
--------
imra, swt
Notes
-----
This is sometimes referred to as an additive decomposition because the
inverse transform (``imra``) is just the sum of the coefficient arrays
[1]_. The decomposition using ``transform='dwt'`` corresponds to section
2.2 while that using an undecimated transform (``transform='swt'``) is
described in section 3.2 and appendix A.
This transform does not share the variance partition property of ``swt``
with `norm=True`. It does however, result in coefficients that are
temporally aligned regardless of the symmetry of the wavelet used.
The redundancy of this transform is ``(level + 1)``.
References
----------
.. [1] Donald B. Percival and Harold O. Mofjeld. Analysis of Subtidal
Coastal Sea Level Fluctuations Using Wavelets. Journal of the American
Statistical Association Vol. 92, No. 439 (Sep., 1997), pp. 868-880.
https://doi.org/10.2307/2965551
"""
if transform == 'swt':
if mode != 'periodization':
raise ValueError(
"transform swt only supports mode='periodization'")
kwargs = dict(wavelet=wavelet, axis=axis, norm=True)
forward = partial(swt, level=level, trim_approx=True, **kwargs)
inverse = partial(iswt, **kwargs)
is_swt = True
elif transform == 'dwt':
kwargs = dict(wavelet=wavelet, mode=mode, axis=axis)
forward = partial(wavedec, level=level, **kwargs)
inverse = partial(waverec, **kwargs)
is_swt = False
else:
raise ValueError("unrecognized transform: {}".format(transform))
wav_coeffs = forward(data)
mra_coeffs = []
nc = len(wav_coeffs)
if is_swt:
# replicate same zeros array to save memory
z = np.zeros_like(wav_coeffs[0])
tmp = [z, ] * nc
else:
# zero arrays have variable size in DWT case
tmp = [np.zeros_like(c) for c in wav_coeffs]
for j in range(nc):
# tmp has arrays of zeros except for the jth entry
tmp[j] = wav_coeffs[j]
# reconstruct
rec = inverse(tmp)
if rec.shape != data.shape:
# trim any excess coefficients
rec = rec[tuple([slice(sz) for sz in data.shape])]
mra_coeffs.append(rec)
# restore zeros
if is_swt:
tmp[j] = z
else:
tmp[j] = np.zeros_like(tmp[j])
return mra_coeffs
def imra(mra_coeffs):
"""Inverse 1D multiresolution analysis via summation.
Parameters
----------
mra_coeffs : list of ndarray
Multiresolution analysis coefficients as returned by `mra`.
Returns
-------
rec : ndarray
The reconstructed signal.
See Also
--------
mra
References
----------
.. [1] Donald B. Percival and Harold O. Mofjeld. Analysis of Subtidal
Coastal Sea Level Fluctuations Using Wavelets. Journal of the American
Statistical Association Vol. 92, No. 439 (Sep., 1997), pp. 868-880.
https://doi.org/10.2307/2965551
"""
return reduce(lambda x, y: x + y, mra_coeffs)
def mra2(data, wavelet, level=None, axes=(-2, -1), transform='swt2',
mode='periodization'):
"""Forward 2D multiresolution analysis.
It is a projection onto wavelet subspaces.
Parameters
----------
data: array_like
Input data
wavelet : Wavelet object or name string, or 2-tuple of wavelets
Wavelet to use. This can also be a tuple containing a wavelet to
apply along each axis in `axes`.
level : int, optional
Decomposition level (must be >= 0). If level is None (default) then it
will be calculated using the `dwt_max_level` function.
axes : 2-tuple of ints, optional
Axes over which to compute the DWT. Repeated elements are not allowed.
Currently only available when ``transform='dwt2'``.
transform : {'dwt2', 'swt2'}
Whether to use the DWT or SWT for the transforms.
mode : str or 2-tuple of str, optional
Signal extension mode, see `Modes` (default: 'symmetric'). This option
is only used when transform='dwt2'.
Returns
-------
coeffs : list
For more information, see the detailed description in `wavedec2`
Notes
-----
This is sometimes referred to as an additive decomposition because the
inverse transform (``imra2``) is just the sum of the coefficient arrays
[1]_. The decomposition using ``transform='dwt'`` corresponds to section
2.2 while that using an undecimated transform (``transform='swt'``) is
described in section 3.2 and appendix A.
This transform does not share the variance partition property of ``swt2``
with `norm=True`. It does however, result in coefficients that are
temporally aligned regardless of the symmetry of the wavelet used.
The redundancy of this transform is ``3 * level + 1``.
See Also
--------
imra2, swt2
References
----------
.. [1] Donald B. Percival and Harold O. Mofjeld. Analysis of Subtidal
Coastal Sea Level Fluctuations Using Wavelets. Journal of the American
Statistical Association Vol. 92, No. 439 (Sep., 1997), pp. 868-880.
https://doi.org/10.2307/2965551
"""
if transform == 'swt2':
if mode != 'periodization':
raise ValueError(
"transform swt only supports mode='periodization'")
if level is None:
level = min(swt_max_level(s) for s in data.shape)
kwargs = dict(wavelet=wavelet, axes=axes, norm=True)
forward = partial(swt2, level=level, trim_approx=True, **kwargs)
inverse = partial(iswt2, **kwargs)
elif transform == 'dwt2':
kwargs = dict(wavelet=wavelet, mode=mode, axes=axes)
forward = partial(wavedec2, level=level, **kwargs)
inverse = partial(waverec2, **kwargs)
else:
raise ValueError("unrecognized transform: {}".format(transform))
wav_coeffs = forward(data)
mra_coeffs = []
nc = len(wav_coeffs)
z = np.zeros_like(wav_coeffs[0])
tmp = [z]
for j in range(1, nc):
tmp.append([np.zeros_like(c) for c in wav_coeffs[j]])
# tmp has arrays of zeros except for the jth entry
tmp[0] = wav_coeffs[0]
# reconstruct
rec = inverse(tmp)
if rec.shape != data.shape:
# trim any excess coefficients
rec = rec[tuple([slice(sz) for sz in data.shape])]
mra_coeffs.append(rec)
# restore zeros
tmp[0] = z
for j in range(1, nc):
dcoeffs = []
for n in range(3):
# tmp has arrays of zeros except for the jth entry
z = tmp[j][n]
tmp[j][n] = wav_coeffs[j][n]
# reconstruct
rec = inverse(tmp)
if rec.shape != data.shape:
# trim any excess coefficients
rec = rec[tuple([slice(sz) for sz in data.shape])]
dcoeffs.append(rec)
# restore zeros
tmp[j][n] = z
mra_coeffs.append(tuple(dcoeffs))
return mra_coeffs
def imra2(mra_coeffs):
"""Inverse 2D multiresolution analysis via summation.
Parameters
----------
mra_coeffs : list
Multiresolution analysis coefficients as returned by `mra2`.
Returns
-------
rec : ndarray
The reconstructed signal.
See Also
--------
mra2
References
----------
.. [1] Donald B. Percival and Harold O. Mofjeld. Analysis of Subtidal
Coastal Sea Level Fluctuations Using Wavelets. Journal of the American
Statistical Association Vol. 92, No. 439 (Sep., 1997), pp. 868-880.
https://doi.org/10.2307/2965551
"""
rec = mra_coeffs[0]
for j in range(1, len(mra_coeffs)):
for n in range(3):
rec += mra_coeffs[j][n]
return rec
def mran(data, wavelet, level=None, axes=None, transform='swtn',
mode='periodization'):
"""Forward nD multiresolution analysis.
It is a projection onto the wavelet subspaces.
Parameters
----------
data: array_like
Input data
wavelet : Wavelet object or name string, or tuple of wavelets
Wavelet to use. This can also be a tuple containing a wavelet to
apply along each axis in `axes`.
level : int, optional
Decomposition level (must be >= 0). If level is None (default) then it
will be calculated using the `dwt_max_level` function.
axes : tuple of ints, optional
Axes over which to compute the DWT. Repeated elements are not allowed.
transform : {'dwtn', 'swtn'}
Whether to use the DWT or SWT for the transforms.
mode : str or tuple of str, optional
Signal extension mode, see `Modes` (default: 'symmetric'). This option
is only used when transform='dwtn'.
Returns
-------
coeffs : list
For more information, see the detailed description in `wavedecn`.
See Also
--------
imran, swtn
Notes
-----
This is sometimes referred to as an additive decomposition because the
inverse transform (``imran``) is just the sum of the coefficient arrays
[1]_. The decomposition using ``transform='dwt'`` corresponds to section
2.2 while that using an undecimated transform (``transform='swt'``) is
described in section 3.2 and appendix A.
This transform does not share the variance partition property of ``swtn``
with `norm=True`. It does however, result in coefficients that are
temporally aligned regardless of the symmetry of the wavelet used.
The redundancy of this transform is ``(2**n - 1) * level + 1`` where ``n``
corresponds to the number of axes transformed.
References
----------
.. [1] Donald B. Percival and Harold O. Mofjeld. Analysis of Subtidal
Coastal Sea Level Fluctuations Using Wavelets. Journal of the American
Statistical Association Vol. 92, No. 439 (Sep., 1997), pp. 868-880.
https://doi.org/10.2307/2965551
"""
axes, axes_shapes, ndim_transform = _prep_axes_wavedecn(data.shape, axes)
wavelets = _wavelets_per_axis(wavelet, axes)
if transform == 'swtn':
if mode != 'periodization':
raise ValueError(
"transform swt only supports mode='periodization'")
if level is None:
level = min(swt_max_level(s) for s in data.shape)
kwargs = dict(wavelet=wavelets, axes=axes, norm=True)
forward = partial(swtn, level=level, trim_approx=True, **kwargs)
inverse = partial(iswtn, **kwargs)
elif transform == 'dwtn':
modes = _modes_per_axis(mode, axes)
kwargs = dict(wavelet=wavelets, mode=modes, axes=axes)
forward = partial(wavedecn, level=level, **kwargs)
inverse = partial(waverecn, **kwargs)
else:
raise ValueError("unrecognized transform: {}".format(transform))
wav_coeffs = forward(data)
mra_coeffs = []
nc = len(wav_coeffs)
z = np.zeros_like(wav_coeffs[0])
tmp = [z]
for j in range(1, nc):
tmp.append({k: np.zeros_like(v) for k, v in wav_coeffs[j].items()})
# tmp has arrays of zeros except for the jth entry
tmp[0] = wav_coeffs[0]
# reconstruct
rec = inverse(tmp)
if rec.shape != data.shape:
# trim any excess coefficients
rec = rec[tuple([slice(sz) for sz in data.shape])]
mra_coeffs.append(rec)
# restore zeros
tmp[0] = z
for j in range(1, nc):
dcoeffs = {}
dkeys = list(wav_coeffs[j].keys())
for k in dkeys:
# tmp has arrays of zeros except for the jth entry
z = tmp[j][k]
tmp[j][k] = wav_coeffs[j][k]
# tmp[j]['a' * len(k)] = z
# reconstruct
rec = inverse(tmp)
if rec.shape != data.shape:
# trim any excess coefficients
rec = rec[tuple([slice(sz) for sz in data.shape])]
dcoeffs[k] = rec
# restore zeros
tmp[j][k] = z
# tmp[j].pop('a' * len(k))
mra_coeffs.append(dcoeffs)
return mra_coeffs
def imran(mra_coeffs):
"""Inverse nD multiresolution analysis via summation.
Parameters
----------
mra_coeffs : list
Multiresolution analysis coefficients as returned by `mra2`.
Returns
-------
rec : ndarray
The reconstructed signal.
See Also
--------
mran
References
----------
.. [1] Donald B. Percival and Harold O. Mofjeld. Analysis of Subtidal
Coastal Sea Level Fluctuations Using Wavelets. Journal of the American
Statistical Association Vol. 92, No. 439 (Sep., 1997), pp. 868-880.
https://doi.org/10.2307/2965551
"""
rec = mra_coeffs[0]
for j in range(1, len(mra_coeffs)):
for k, v in mra_coeffs[j].items():
rec += v
return rec
|