Exemplo n.º 1
0
def descriptor(seq, median_len):
    ns = list(map(numMappingPP, seq))  # here we map the nucleotides to numbers

    ## we ensure that all the sequences have the same size
    I = median_len - len(
        ns
    )  # change "median_len" to other length stat for length normalization
    if I > 0:  # when the seq size is smaller than the median
        ns_temp = pywt.pad(ns, I, 'antisymmetric')  #wextend('1','asym',ns,I);
        ns_temp = np.array(ns_temp)
        #print(len(ns_temp), len(ns))
        ns_new = ns_temp[
            I:ns_temp.shape[0]]  #nsNew = nsTemp((I+1):length(nsTemp));
    elif I < 0:  # when the seq size is bigger than the median
        ns = np.array(ns)
        ns_new = ns[0:median_len]
    else:
        ns_new = np.array(ns)

    #print(ns_new.shape)
    #print("processing FFT...")
    fourier_transform = fft(ns_new)
    #print("getting  magnitude spectra...")
    magnitud_spectra = np.abs(fourier_transform)  # %magnitude spectra

    return ns_new, fourier_transform, magnitud_spectra
 def pad_to_mult(self, support, mult):
     if len(support) % mult == 0:
         return support
     else:
         self.swt_buffer_length = mult - (len(support) % mult)
         return pywt.pad(support, (0, self.swt_buffer_length),
                         mode='smooth')
Exemplo n.º 3
0
def test_pad_nd():
    for ndim in [2, 3]:
        x = np.arange(4**ndim).reshape((4, ) * ndim)
        if ndim == 2:
            pad_widths = [(2, 1), (2, 3)]
        else:
            pad_widths = [(2, 1), ] * ndim
        for mode in pywt.Modes.modes:
            xp = pywt.pad(x, pad_widths, mode)

            # expected result is the same as applying along axes separably
            xp_expected = x.copy()
            for ax in range(ndim):
                xp_expected = np.apply_along_axis(pywt.pad,
                                                  ax,
                                                  xp_expected,
                                                  pad_widths=[pad_widths[ax]],
                                                  mode=mode)
            assert_array_equal(xp, xp_expected)
Exemplo n.º 4
0
    def metric(self, field, cm, verify=False):
        """
        Compute metric(s) for a single field

        Parameters
        ----------
        field : numpy array of shape (npx,npx) - npx is number of pixels
            Cloud water path field.
        cm : numpy array of shape (npx,npx)
            Cloud mask field.

        Returns
        -------
        woi1 : float
           First wavelet organisation index (scale distribution).
        woi2 : float
            Second wavelet organisation index (total amount of stuff).
        woi3 : float
            Third wavelet organisation index (directional alignment).

        """

        # STATIONARY/UNDECIMATED Direct Wavelet Transform
        field = pywt.pad(field, self.pad, "periodic")
        scaleMax = int(np.log(field.shape[0]) / np.log(2))
        coeffs = pywt.swt2(field, "haar", scaleMax, norm=True, trim_approx=True)
        # Bug in pywt -> trim_approx=False does opposite of its intention
        # Structure of coeffs:
        # - coeffs    -> list with nScales indices. Each scale is a 2-power of
        #                the image resolution. For 512x512 images we have
        #                512 = 2^9 -> 10 scales
        # - coeffs[i] -> Contains three directions:
        #                   [0] - Horizontal
        #                   [1] - Vertical
        #                   [2] - Diagonal

        specs = np.zeros((len(coeffs), 3))  # Shape (nScales,3)
        k = np.arange(0, len(specs))
        for i in range(len(coeffs)):
            if i == 0:
                ec = coeffs[i] ** 2
                specs[i, 0] = np.mean(ec)
            else:
                for j in range(len(coeffs[i])):
                    ec = coeffs[i][j] ** 2  # Energy -> squared wavelet coeffs
                    specs[i, j] = np.mean(ec)  # Domain-averaging at each scale

        # Decompose into ''large scale'' energy and ''small scale'' energy
        # Large scales are defined as 0 < k < 5
        specs = specs[1:]
        specL = specs[:5, :]
        specS = specs[5:, :]

        Ebar = np.sum(np.mean(specs, axis=1))
        Elbar = np.sum(np.mean(specL, axis=1))
        Esbar = np.sum(np.mean(specS, axis=1))

        Eld = np.sum(specL, axis=0)
        Esd = np.sum(specS, axis=0)

        # Compute wavelet organisation index
        woi1 = Elbar / Ebar
        woi2 = (Elbar + Esbar) / np.sum(cm)
        woi3 = (
            1.0
            / 3
            * np.sqrt(
                np.sum(((Esd - Esbar) / Esbar) ** 2 + ((Eld - Elbar) / Elbar) ** 2)
            )
        )

        woi = np.log(woi1) + np.log(woi2) + np.log(woi3)

        if self.plot:
            labs = ["Horizontal", "Vertical", "Diagonal"]
            fig, axs = plt.subplots(ncols=2, figsize=(8, 4))
            axs[0].imshow(field, "gist_ncar")
            axs[0].set_xticks([])
            axs[0].set_yticks([])
            axs[0].set_title("CWP")
            for i in range(3):
                axs[1].plot(k[1:], specs[:, i], label=labs[i])
            axs[1].set_xscale("log")
            axs[1].set_xlabel(r"Scale number $k$")
            axs[1].set_ylabel("Energy")
            axs[1].set_title("Wavelet energy spectrum")
            axs[1].legend()
            plt.tight_layout()
            plt.show()

        if verify:
            return specs
        else:
            return woi1, woi2, woi3, woi
Exemplo n.º 5
0
def test_pad_1d():
    x = [1, 2, 3]
    assert_array_equal(pywt.pad(x, (4, 6), 'periodization'),
                       [1, 2, 3, 3, 1, 2, 3, 3, 1, 2, 3, 3, 1, 2])
    assert_array_equal(pywt.pad(x, (4, 6), 'periodic'),
                       [3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3])
    assert_array_equal(pywt.pad(x, (4, 6), 'constant'),
                       [1, 1, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3, 3])
    assert_array_equal(pywt.pad(x, (4, 6), 'zero'),
                       [0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0, 0, 0])
    assert_array_equal(pywt.pad(x, (4, 6), 'smooth'),
                       [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    assert_array_equal(pywt.pad(x, (4, 6), 'symmetric'),
                       [3, 3, 2, 1, 1, 2, 3, 3, 2, 1, 1, 2, 3])
    assert_array_equal(pywt.pad(x, (4, 6), 'antisymmetric'),
                       [3, -3, -2, -1, 1, 2, 3, -3, -2, -1, 1, 2, 3])
    assert_array_equal(pywt.pad(x, (4, 6), 'reflect'),
                       [1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3, 2, 1])
    assert_array_equal(pywt.pad(x, (4, 6), 'antireflect'),
                       [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

    # equivalence of various pad_width formats
    assert_array_equal(pywt.pad(x, 4, 'periodic'),
                       pywt.pad(x, (4, 4), 'periodic'))

    assert_array_equal(pywt.pad(x, (4, ), 'periodic'),
                       pywt.pad(x, (4, 4), 'periodic'))

    assert_array_equal(pywt.pad(x, [(4, 4)], 'periodic'),
                       pywt.pad(x, (4, 4), 'periodic'))
 def apply_pad_x(self):
     self.x = pywt.pad(self.x, self.PAD_WIDTH, 'antireflect')