Exemplo n.º 1
0
def test_wavedecn_shapes_and_size():
    wav = pywt.Wavelet('db2')
    for data_shape in [(33, ), (64, 32), (1, 15, 30)]:
        for axes in [None, 0, -1]:
            for mode in pywt.Modes.modes:
                coeffs = pywt.wavedecn(np.ones(data_shape),
                                       wav,
                                       mode=mode,
                                       axes=axes)

                # verify that the shapes match the coefficient shapes
                shapes = pywt.wavedecn_shapes(data_shape,
                                              wav,
                                              mode=mode,
                                              axes=axes)

                assert_equal(coeffs[0].shape, shapes[0])
                expected_size = coeffs[0].size
                for level in range(1, len(coeffs)):
                    for k, v in coeffs[level].items():
                        expected_size += v.size
                        assert_equal(shapes[level][k], v.shape)

                # size can be determined from either the shapes or coeffs
                size = pywt.wavedecn_size(shapes)
                assert_equal(size, expected_size)

                size = pywt.wavedecn_size(coeffs)
                assert_equal(size, expected_size)
Exemplo n.º 2
0
    def scales(self):
        """Get the scales of each coefficient.

        Returns
        -------
        scales : ``range`` element
            The scale of each coefficient, given by an integer. 0 for the
            lowest resolution and self.nlevels for the highest.
        """
        if self.impl == 'pywt':
            if self.__variant == 'forward':
                discr_space = self.domain
                wavelet_space = self.range
            else:
                discr_space = self.range
                wavelet_space = self.domain

            shapes = pywt.wavedecn_shapes(discr_space.shape,
                                          self.pywt_wavelet,
                                          mode=self.pywt_pad_mode,
                                          level=self.nlevels,
                                          axes=self.axes)
            coeff_list = [np.full(shapes[0], 0)]
            for i in range(1, 1 + len(shapes[1:])):
                coeff_list.append(
                    {k: np.full(shapes[i][k], i)
                     for k in shapes[i].keys()})
            coeffs = pywt.ravel_coeffs(coeff_list, axes=self.axes)[0]
            return wavelet_space.element(coeffs)
        else:
            raise RuntimeError("bad `impl` '{}'".format(self.impl))
Exemplo n.º 3
0
    def send_bitplane(self, indata, bitplane_number):
        bitplane = (indata[:, bitplane_number%self.number_of_channels] >> bitplane_number//self.number_of_channels) & 1
        if np.any(bitplane): 
            bitplane = bitplane.astype(np.uint8)
            bitplane = np.packbits(bitplane)
            message = struct.pack(self.packet_format, self.recorded_chunk_number, bitplane_number, self.received_bitplanes_per_chunk[(self.played_chunk_number+1) % self.cells_in_buffer]+1, *bitplane)
            self.sending_sock.sendto(message, (self.destination_IP_addr, self.destination_port))
        else:
            self.skipped_bitplanes[self.recorded_chunk_number % self.cells_in_buffer] += 1
        # Get the number of wavelet coefficients to get the number of samples
        shapes = wt.wavedecn_shapes((bitplane,), wavelet)

        #Devuelve valores espaciados uniformemente dentro de un intervalo dado.
        #Los valores se generan dentro del intervalo medio abierto (en otras palabras, el intervalo que incluye inicio pero excluye detención ). 
        #Para argumentos enteros, la función es equivalente a la función de rango incorporada de Python , pero devuelve un ndarray en lugar de una lista.
        #[start, stop)
                      #(inicio,parada, paso)
        sample = np.arange(0, bitplane, 1)

        #Agregar una subtrama a la figura actual.
        #Contenedor Figure.add_subplotcon una diferencia de comportamiento explicado en la sección de notas.
        fig, axs = plt.subplots(bitplane//skipped_bitplanes,1, sharex=True)

        for i in range(0, bitplane,skipped_bitplanes):
            axs[i//skipped_bitplanes].set_ylim(-bitplane, bitplane)
            axs[i//skipped_bitplanes].grid(True)
            #Dibujamos en el eje de las cordenadas las muestras y la amplitud.
        axs[bitplane//skipped_bitplanes-1].set_xlabel('sample')
        axs[bitplane//skipped_bitplanes-2].set_ylable('Amplitud')
        
        print("Coefficient\t   Energy")
Exemplo n.º 4
0
def test_wavedecn_shapes_and_size():
    wav = pywt.Wavelet('db2')
    for data_shape in [(33, ), (64, 32), (1, 15, 30)]:
        for axes in [None, 0, -1]:
            for mode in pywt.Modes.modes:
                coeffs = pywt.wavedecn(np.ones(data_shape), wav,
                                       mode=mode, axes=axes)

                # verify that the shapes match the coefficient shapes
                shapes = pywt.wavedecn_shapes(data_shape, wav,
                                              mode=mode, axes=axes)

                assert_equal(coeffs[0].shape, shapes[0])
                expected_size = coeffs[0].size
                for level in range(1, len(coeffs)):
                    for k, v in coeffs[level].items():
                        expected_size += v.size
                        assert_equal(shapes[level][k], v.shape)

                # size can be determined from either the shapes or coeffs
                size = pywt.wavedecn_size(shapes)
                assert_equal(size, expected_size)

                size = pywt.wavedecn_size(coeffs)
                assert_equal(size, expected_size)
Exemplo n.º 5
0
    def __init__(self,
                 x_shape,
                 wavelet,
                 level,
                 axes=None,
                 pad_on_demand="constant"):
        """Decimated wavelet Transform operator.

        :param x_shape: Shape of the data to be wavelet transformed.
        :type x_shape: `numpy.array_like`
        :param wavelet: Wavelet type
        :type wavelet: string
        :param level: Numer of wavelet decomposition levels
        :type level: int
        :param axes: Axes along which to do the transform, defaults to None
        :type axes: int or tuple of int, optional
        :param pad_on_demand: Padding type to fit the `2 ** level` shape requirements, defaults to 'constant'
        :type pad_on_demand: string, optional. Options are all the `numpy.pad` padding modes.

        :raises ValueError: In case the pywavelets package is not available or its version is not adequate.
        """
        if not has_pywt:
            raise ValueError(
                "Cannot use Wavelet transform because pywavelets is not installed."
            )

        self.wavelet = wavelet
        self.level = level

        if axes is None:
            axes = np.arange(-len(x_shape), 0, dtype=np.intp)
        self.axes = axes

        self.pad_on_demand = pad_on_demand

        num_axes = len(self.axes)

        self.dir_shape = np.array(x_shape)

        self.sub_band_shapes = pywt.wavedecn_shapes(self.dir_shape,
                                                    self.wavelet,
                                                    mode=self.pad_on_demand,
                                                    level=self.level,
                                                    axes=self.axes)
        self.adj_shape = self.dir_shape.copy()
        for ax in self.axes:
            self.adj_shape[ax] = self.sub_band_shapes[0][ax] + np.sum([
                self.sub_band_shapes[x]["d" * num_axes][ax]
                for x in range(1, self.level + 1)
            ])
        self.slicing_info = None

        super().__init__()
Exemplo n.º 6
0
    def __init__(self,
                 space,
                 wavelet,
                 nlevels,
                 variant,
                 pad_mode='constant',
                 pad_const=0,
                 impl='pywt',
                 axes=None):
        """Initialize a new instance.

        Parameters
        ----------
        space : `DiscreteLp`
            Domain of the forward wavelet transform (the "image domain").
            In the case of ``variant in ('inverse', 'adjoint')``, this
            space is the range of the operator.
        wavelet : string or `pywt.Wavelet`
            Specification of the wavelet to be used in the transform.
            If a string is given, it is converted to a `pywt.Wavelet`.
            Use `pywt.wavelist` to get a list of available wavelets.

            Possible wavelet families are:

            ``'haar'``: Haar

            ``'db'``: Daubechies

            ``'sym'``: Symlets

            ``'coif'``: Coiflets

            ``'bior'``: Biorthogonal

            ``'rbio'``: Reverse biorthogonal

            ``'dmey'``: Discrete FIR approximation of the Meyer wavelet

        variant : {'forward', 'inverse', 'adjoint'}
            Wavelet transform variant to be created.
        nlevels : positive int, optional
            Number of scaling levels to be used in the decomposition. The
            maximum number of levels can be calculated with
            `pywt.dwtn_max_level`.
            Default: Use maximum number of levels.
        pad_mode : string, optional
            Method to be used to extend the signal.

            ``'constant'``: Fill with ``pad_const``.

            ``'symmetric'``: Reflect at the boundaries, not repeating the
            outmost values.

            ``'periodic'``: Fill in values from the other side, keeping
            the order.

            ``'order0'``: Extend constantly with the outmost values
            (ensures continuity).

            ``'order1'``: Extend with constant slope (ensures continuity of
            the first derivative). This requires at least 2 values along
            each axis where padding is applied.

            ``'pywt_per'``:  like ``'periodic'``-padding but gives the smallest
            possible number of decomposition coefficients.
            Only available with ``impl='pywt'``, See ``pywt.Modes.modes``.

            ``'reflect'``: Reflect at the boundary, without repeating the
            outmost values.

            ``'antisymmetric'``: Anti-symmetric variant of ``symmetric``.

            ``'antireflect'``: Anti-symmetric variant of ``reflect``.

            For reference, the following table compares the naming conventions
            for the modes in ODL vs. PyWavelets::

                ======================= ==================
                          ODL               PyWavelets
                ======================= ==================
                symmetric               symmetric
                reflect                 reflect
                order1                  smooth
                order0                  constant
                constant, pad_const=0   zero
                periodic                periodic
                pywt_per                periodization
                antisymmetric           antisymmetric
                antireflect             antireflect
                ======================= ==================

            See `signal extension modes`_ for an illustration of the modes
            (under the PyWavelets naming conventions).
        pad_const : float, optional
            Constant value to use if ``pad_mode == 'constant'``. Ignored
            otherwise. Constants other than 0 are not supported by the
            ``pywt`` back-end.
        impl : {'pywt'}, optional
            Back-end for the wavelet transform.
        axes : sequence of ints, optional
            Axes over which the DWT that created ``coeffs`` was performed.  The
            default value of ``None`` corresponds to all axes. When not all
            axes are included this is analagous to a batch transform in
            ``len(axes)`` dimensions looped over the non-transformed axes. In
            orther words, filtering and decimation does not occur along any
            axes not in ``axes``.

        References
        ----------
        .. _signal extension modes:
           https://pywavelets.readthedocs.io/en/latest/ref/signal-extension-modes.html
        """
        if not isinstance(space, DiscreteLp):
            raise TypeError('`space` {!r} is not a `DiscreteLp` instance.'
                            ''.format(space))

        self.__impl, impl_in = str(impl).lower(), impl
        if self.impl not in _SUPPORTED_WAVELET_IMPLS:
            raise ValueError("`impl` '{}' not supported".format(impl_in))

        if axes is None:
            axes = tuple(range(space.ndim))
        elif np.isscalar(axes):
            axes = (axes, )
        elif len(axes) > space.ndim:
            raise ValueError("Too many axes.")
        self.axes = tuple(axes)

        if nlevels is None:
            nlevels = pywt.dwtn_max_level(space.shape, wavelet, self.axes)
        self.__nlevels, nlevels_in = int(nlevels), nlevels
        if self.nlevels != nlevels_in:
            raise ValueError('`nlevels` must be integer, got {}'
                             ''.format(nlevels_in))

        self.__impl, impl_in = str(impl).lower(), impl
        if self.impl not in _SUPPORTED_WAVELET_IMPLS:
            raise ValueError("`impl` '{}' not supported".format(impl_in))

        self.__wavelet = getattr(wavelet, 'name', str(wavelet).lower())
        self.__pad_mode = str(pad_mode).lower()
        self.__pad_const = space.field.element(pad_const)

        if self.impl == 'pywt':
            self.pywt_pad_mode = pywt_pad_mode(pad_mode, pad_const)
            self.pywt_wavelet = pywt_wavelet(self.wavelet)
            # determine coefficient shapes (without running wavedecn)
            self._coeff_shapes = pywt.wavedecn_shapes(space.shape,
                                                      wavelet,
                                                      mode=self.pywt_pad_mode,
                                                      level=self.nlevels,
                                                      axes=self.axes)
            # precompute slices into the (raveled) coeffs
            self._coeff_slices = precompute_raveled_slices(self._coeff_shapes)
            coeff_size = pywt.wavedecn_size(self._coeff_shapes)
            coeff_space = space.tspace_type(coeff_size, dtype=space.dtype)
        else:
            raise RuntimeError("bad `impl` '{}'".format(self.impl))

        variant, variant_in = str(variant).lower(), variant
        if variant not in ('forward', 'inverse', 'adjoint'):
            raise ValueError("`variant` '{}' not understood"
                             "".format(variant_in))
        self.__variant = variant

        if variant == 'forward':
            super(WaveletTransformBase, self).__init__(domain=space,
                                                       range=coeff_space,
                                                       linear=True)
        else:
            super(WaveletTransformBase, self).__init__(domain=coeff_space,
                                                       range=space,
                                                       linear=True)
Exemplo n.º 7
0
# least distance of an valid R peak to two ends of ECG signals
PreprocCfg.rpeaks_skip_dist = int(0.5 * PreprocCfg.fs)  # 0.5s


# FeatureCfg only for ML models, deprecated
FeatureCfg = ED()
FeatureCfg.fs = BaseCfg.fs
FeatureCfg.features = ['wavelet', 'rr', 'morph',]

FeatureCfg.wt_family = 'db1'
FeatureCfg.wt_level = 3
FeatureCfg.beat_winL = BaseCfg.beat_winL
FeatureCfg.beat_winR = BaseCfg.beat_winR
FeatureCfg.wt_feature_len = pywt.wavedecn_shapes(
    shape=(1+FeatureCfg.beat_winL+FeatureCfg.beat_winR,), 
    wavelet=FeatureCfg.wt_family,
    level=FeatureCfg.wt_level
)[0][0]

FeatureCfg.rr_local_range = 10  # 10 r peaks
FeatureCfg.rr_global_range = 5 * 60 * FeatureCfg.fs  # 5min, units in number of points
FeatureCfg.rr_normalize_radius = 30  # number of beats (rpeaks)

FeatureCfg.morph_intervals = [[0,45], [85,95], [110,120], [170,200]]



ModelCfg = ED()
ModelCfg.fs = BaseCfg.fs
ModelCfg.n_leads = 1
ModelCfg.torch_dtype = BaseCfg.torch_dtype
+-------------------------------+-------------------------------+
"""

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()