def DWT_synthesize(self, coefs, wavelet=None): if wavelet is None: wavelet = self.wavelet samples = np.empty((self.size, 2), dtype=np.int16) decomposition_0 = pywt.unravel_coeffs(coefs[:self.size], self.slices, self.shapes, output_format="wavedec") decomposition_1 = pywt.unravel_coeffs(coefs[self.size:], self.slices, self.shapes, output_format="wavedec") samples[:, 0] = np.rint(pywt.waverec(decomposition_0, wavelet=wavelet, mode="per")).astype(np.int16) samples[:, 1] = np.rint(pywt.waverec(decomposition_1, wavelet=wavelet, mode="per")).astype(np.int16) return samples
def reconstruct(self, coefs, *args): """ WaveletTransformer.reconstruct(self, coef, *args) Computes and returns the inverse wavelet transform of the ravelled vector of coefficients coefs using the wavelet specified by self.wname. Inputs ------ coef : 1d numpy array args: tuple Expecting, e.g., (slices, shapes) as returned by pywt.ravel_coeffs Returns ------- y : numpy array Example ------- >>> # not tested: >>> xHat = wt.reconstruct(coefs, *aux_data) >>> print(nnse(xHat, x0, 1)) """ return self._waverec( wt.unravel_coeffs(coefs, *args, output_format=self._of), self.wname)
def test_wavedecn_coeff_ravel(): # verify round trip is correct: # wavedecn - >ravel_coeffs-> unravel_coeffs -> waverecn # This is done for wavedec{1, 2, n} rng = np.random.RandomState(1234) params = {'wavedec': {'d': 1, 'dec': pywt.wavedec, 'rec': pywt.waverec}, 'wavedec2': {'d': 2, 'dec': pywt.wavedec2, 'rec': pywt.waverec2}, 'wavedecn': {'d': 3, 'dec': pywt.wavedecn, 'rec': pywt.waverecn}} N = 12 for f in params: x1 = rng.randn(*([N] * params[f]['d'])) for mode in pywt.Modes.modes: for wave in wavelist: w = pywt.Wavelet(wave) maxlevel = pywt.dwt_max_level(np.min(x1.shape), w.dec_len) if maxlevel == 0: continue coeffs = params[f]['dec'](x1, w, mode=mode) coeff_arr, slices, shapes = pywt.ravel_coeffs(coeffs) coeffs2 = pywt.unravel_coeffs(coeff_arr, slices, shapes, output_format=f) x1r = params[f]['rec'](coeffs2, w, mode=mode) assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4)
def test_wavedecn_coeff_ravel(): # verify round trip is correct: # wavedecn - >ravel_coeffs-> unravel_coeffs -> waverecn # This is done for wavedec{1, 2, n} rng = np.random.RandomState(1234) params = {'wavedec': {'d': 1, 'dec': pywt.wavedec, 'rec': pywt.waverec}, 'wavedec2': {'d': 2, 'dec': pywt.wavedec2, 'rec': pywt.waverec2}, 'wavedecn': {'d': 3, 'dec': pywt.wavedecn, 'rec': pywt.waverecn}} N = 12 for f in params: x1 = rng.randn(*([N] * params[f]['d'])) for mode in pywt.Modes.modes: for wave in wavelist: w = pywt.Wavelet(wave) maxlevel = pywt.dwt_max_level(np.min(x1.shape), w.dec_len) if maxlevel == 0: continue coeffs = params[f]['dec'](x1, w, mode=mode) coeff_arr, slices, shapes = pywt.ravel_coeffs(coeffs) coeffs2 = pywt.unravel_coeffs(coeff_arr, slices, shapes, output_format=f) x1r = params[f]['rec'](coeffs2, w, mode=mode) assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4)
def test_swt_ravel_and_unravel(): # When trim_approx=True, all swt functions can user pywt.ravel_coeffs for ndim, _swt, _iswt, ravel_type in [(1, pywt.swt, pywt.iswt, 'swt'), (2, pywt.swt2, pywt.iswt2, 'swt2'), (3, pywt.swtn, pywt.iswtn, 'swtn')]: x = np.ones((16, ) * ndim) c = _swt(x, 'sym2', level=3, trim_approx=True) arr, slices, shapes = pywt.ravel_coeffs(c) c = pywt.unravel_coeffs(arr, slices, shapes, output_format=ravel_type) r = _iswt(c, 'sym2') assert_allclose(x, r)
def adj_op(self, x): if (self.wav == 'dirac'): return np.reshape(x, self.shape) if (self.wav == 'fourier'): return np.fft.ifftn(np.reshape(x, self.shape)) if (self.wav == "dct"): return scipy.fft.idctn(np.reshape(x, self.shape), norm='ortho') coeffs_from_arr = pywt.unravel_coeffs(x, self.coeff_slices, self.coeff_shapes, output_format='wavedecn') return pywt.waverecn(coeffs_from_arr, wavelet=self.wav, mode='periodic', axes=self.axes)
def _dot_internal(alpha, bases, padding, iy, sy, sqrtP, nx, ny, real_type): nbasis, nband, _ = alpha.shape # reduction over basis done externally since chunked x = np.zeros((nbasis, nband, nx, ny), dtype=real_type) for b in range(nbasis): base = bases[b] for l in range(nband): a = alpha[b, l, padding[b]] alpha_rec = pywt.unravel_coeffs(a, iy[base], sy[base], output_format='wavedecn') wave = pywt.waverecn(alpha_rec, base, mode='zero') x[b, l] += wave / sqrtP return x
def test_ravel_wavedec2_with_lists(): x1 = np.ones((8, 8)) wav = pywt.Wavelet('haar') coeffs = pywt.wavedec2(x1, wav) # list [cHn, cVn, cDn] instead of tuple is okay coeffs[1:] = [list(c) for c in coeffs[1:]] coeff_arr, slices, shapes = pywt.ravel_coeffs(coeffs) coeffs2 = pywt.unravel_coeffs(coeff_arr, slices, shapes, output_format='wavedec2') x1r = pywt.waverec2(coeffs2, wav) assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4) # wrong length list will cause a ValueError coeffs[1:] = [list(c[:-1]) for c in coeffs[1:]] # truncate diag coeffs assert_raises(ValueError, pywt.ravel_coeffs, coeffs)
def test_ravel_wavedec2_with_lists(): x1 = np.ones((8, 8)) wav = pywt.Wavelet('haar') coeffs = pywt.wavedec2(x1, wav) # list [cHn, cVn, cDn] instead of tuple is okay coeffs[1:] = [list(c) for c in coeffs[1:]] coeff_arr, slices, shapes = pywt.ravel_coeffs(coeffs) coeffs2 = pywt.unravel_coeffs(coeff_arr, slices, shapes, output_format='wavedec2') x1r = pywt.waverec2(coeffs2, wav) assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4) # wrong length list will cause a ValueError coeffs[1:] = [list(c[:-1]) for c in coeffs[1:]] # truncate diag coeffs assert_raises(ValueError, pywt.ravel_coeffs, coeffs)
def test_waverecn_coeff_ravel_odd(): # verify round trip is correct: # wavedecn - >ravel_coeffs-> unravel_coeffs -> waverecn rng = np.random.RandomState(1234) x1 = rng.randn(35, 33) for mode in pywt.Modes.modes: for wave in ['haar', ]: w = pywt.Wavelet(wave) maxlevel = pywt.dwt_max_level(np.min(x1.shape), w.dec_len) if maxlevel == 0: continue coeffs = pywt.wavedecn(x1, w, mode=mode) coeff_arr, slices, shapes = pywt.ravel_coeffs(coeffs) coeffs2 = pywt.unravel_coeffs(coeff_arr, slices, shapes) x1r = pywt.waverecn(coeffs2, w, mode=mode) # truncate reconstructed values to original shape x1r = x1r[tuple([slice(s) for s in x1.shape])] assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4)
def test_waverecn_coeff_ravel_odd(): # verify round trip is correct: # wavedecn - >ravel_coeffs-> unravel_coeffs -> waverecn rng = np.random.RandomState(1234) x1 = rng.randn(35, 33) for mode in pywt.Modes.modes: for wave in ['haar', ]: w = pywt.Wavelet(wave) maxlevel = pywt.dwt_max_level(np.min(x1.shape), w.dec_len) if maxlevel == 0: continue coeffs = pywt.wavedecn(x1, w, mode=mode) coeff_arr, slices, shapes = pywt.ravel_coeffs(coeffs) coeffs2 = pywt.unravel_coeffs(coeff_arr, slices, shapes) x1r = pywt.waverecn(coeffs2, w, mode=mode) # truncate reconstructed values to original shape x1r = x1r[tuple([slice(s) for s in x1.shape])] assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4)
def test_wavedecn_coeff_ravel_zero_level(): # verify round trip is correct: # wavedecn - >ravel_coeffs-> unravel_coeffs -> waverecn # This is done for wavedec{1, 2, n} rng = np.random.RandomState(1234) params = {'wavedec': {'d': 1, 'dec': pywt.wavedec, 'rec': pywt.waverec}, 'wavedec2': {'d': 2, 'dec': pywt.wavedec2, 'rec': pywt.waverec2}, 'wavedecn': {'d': 3, 'dec': pywt.wavedecn, 'rec': pywt.waverecn}} N = 16 for f in params: x1 = rng.randn(*([N] * params[f]['d'])) for mode in pywt.Modes.modes: w = pywt.Wavelet('db2') coeffs = params[f]['dec'](x1, w, mode=mode, level=0) coeff_arr, slices, shapes = pywt.ravel_coeffs(coeffs) coeffs2 = pywt.unravel_coeffs(coeff_arr, slices, shapes, output_format=f) x1r = params[f]['rec'](coeffs2, w, mode=mode) assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4)
def test_wavedecn_coeff_ravel_zero_level(): # verify round trip is correct: # wavedecn - >ravel_coeffs-> unravel_coeffs -> waverecn # This is done for wavedec{1, 2, n} rng = np.random.RandomState(1234) params = {'wavedec': {'d': 1, 'dec': pywt.wavedec, 'rec': pywt.waverec}, 'wavedec2': {'d': 2, 'dec': pywt.wavedec2, 'rec': pywt.waverec2}, 'wavedecn': {'d': 3, 'dec': pywt.wavedecn, 'rec': pywt.waverecn}} N = 16 for f in params: x1 = rng.randn(*([N] * params[f]['d'])) for mode in pywt.Modes.modes: w = pywt.Wavelet('db2') coeffs = params[f]['dec'](x1, w, mode=mode, level=0) coeff_arr, slices, shapes = pywt.ravel_coeffs(coeffs) coeffs2 = pywt.unravel_coeffs(coeff_arr, slices, shapes, output_format=f) x1r = params[f]['rec'](coeffs2, w, mode=mode) assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4)
def _call(self, coeffs): """Return the inverse wavelet transform of ``coeffs``.""" if self.impl == 'pywt': coeffs = pywt.unravel_coeffs(coeffs, coeff_slices=self._coeff_slices, coeff_shapes=self._coeff_shapes, output_format='wavedecn') recon = pywt.waverecn(coeffs, wavelet=self.pywt_wavelet, mode=self.pywt_pad_mode, axes=self.axes) recon_shape = self.range.shape if recon.shape != recon_shape: # If the original shape was odd along any transformed axes it # will have been rounded up to the next even size after the # reconstruction. The extra sample should be discarded. # The underlying reason is decimation by two in reconstruction # must keep ceil(N/2) samples in each band for perfect # reconstruction. Reconstruction then upsamples by two. # When N is odd, (2 * np.ceil(N/2)) != N. recon_slc = [] for i, (n_recon, n_intended) in enumerate(zip(recon.shape, recon_shape)): if n_recon == n_intended + 1: # Upsampling added one entry too much in this axis, # drop last one recon_slc.append(slice(-1)) elif n_recon == n_intended: recon_slc.append(slice(None)) else: raise ValueError( 'in axis {}: expected size {} or {} in ' '`recon_shape`, got {}' ''.format(i, n_recon - 1, n_recon, n_intended)) recon = recon[tuple(recon_slc)] return recon else: raise RuntimeError("bad `impl` '{}'".format(self.impl))
def dot(self, alpha): """ Takes array of coefficients to image. alpha comes in as a raveled array of coefficients and has to be unraveled before passing to waverecn. """ x = np.zeros((self.nband, self.nx, self.ny), dtype=self.real_type) for b in range(self.nbasis): base = self.bases[b] for l in range(self.nband): # unpad a = alpha[b, l, self.padding[b]] if base == 'self': wave = a.reshape(self.nx, self.ny) else: # unravel and rec alpha_rec = pywt.unravel_coeffs(a, self.iy[base], self.sy[base]) wave = pywt.waverecn(alpha_rec, base, mode='zero') # accumulate x[l] += wave / self.sqrtP return x
def dot(self, coeffs): """ Takes array of coefficients to image. alpha comes in as a raveled array of coefficients and has to be unraveled before passing to waverecn. """ x = np.zeros((2, self.nband, self.nx, self.ny), dtype=self.real_type) x[0] = coeffs[0, :, self.dpadding].reshape(self.nband, self.nx, self.ny) # Dirac components alpha = coeffs[1::] # wavelet coefficients for b in range(self.nbasis): base = self.bases[b] for l in range(self.nband): # unpad a = alpha[b, l, self.padding[b]] # unravel and rec alpha_rec = pywt.unravel_coeffs(a, self.iy[base], self.sy[base]) wave = pywt.waverecn(alpha_rec, base, mode='zero') # accumulate x[1, l] += wave / self.sqrtP return x
+-------------------------------+-------------------------------+ """ cam = pywt.data.camera() coeffs = pywt.wavedecn(cam, wavelet="db2", level=3) # Concatenating all coefficients into a single n-d array arr, coeff_slices = pywt.coeffs_to_array(coeffs) # Splitting concatenated coefficient array back into its components coeffs_from_arr = pywt.array_to_coeffs(arr, coeff_slices) cam_recon = pywt.waverecn(coeffs_from_arr, wavelet='db2') # Raveling coefficients to a 1D array arr, coeff_slices, coeff_shapes = pywt.ravel_coeffs(coeffs) # Unraveling coefficients from a 1D array coeffs_from_arr = pywt.unravel_coeffs(arr, coeff_slices, coeff_shapes) cam_recon2 = pywt.waverecn(coeffs_from_arr, wavelet='db2') # Multilevel: n-d coefficient shapes shapes = pywt.wavedecn_shapes((64, 32), 'db2', mode='periodization') # Multilevel: Total size of all coefficients size = pywt.wavedecn_size(shapes) print(size) print()