Esempio n. 1
0
 def test_matrix8(self):
     from numpy.lib.stride_tricks import as_strided
     x = self.xd1[:10].copy()
     y = as_strided(x, shape=(4,4,), strides=(2*x.itemsize, x.itemsize))
     f1 = mkl_fft.fft(y)
     f2 = mkl_fft.fft(y.copy())
     assert_allclose(f1, f2, atol=1e-15, rtol=1e-7)
Esempio n. 2
0
    def test_matrix7(self):
        x = self.ad2.copy()
        f1 = mkl_fft.fft(x)
        f2 = np.array([ mkl_fft.fft(x[i]) for i in range(x.shape[0])])
        assert_allclose(f1, f2)

        f1 = mkl_fft.fft(x, axis=0)
        f2 = np.array([ mkl_fft.fft(x[:, i]) for i in range(x.shape[1])]).T
        assert_allclose(f1, f2)
Esempio n. 3
0
    def test_vector1(self):
        """check that mkl_fft gives the same result of numpy.fft"""
        f1 = mkl_fft.fft(self.xz1)
        f2 = np_fft.fft(self.xz1)
        assert_allclose(f1,f2, rtol=1e-7, atol=2e-12)

        f1 = mkl_fft.fft(self.xc1)
        f2 = np_fft.fft(self.xc1)
        assert_allclose(f1,f2, rtol=2e-6, atol=2e-6)
Esempio n. 4
0
 def test_vector9(self):
     "works on subtypes of ndarray"
     mask = np.zeros(self.xd1.shape, dtype='int')
     mask[1] = 1
     mask[-2] = 1
     x = np.ma.masked_array(self.xd1, mask=mask)
     f1 = mkl_fft.fft(x)
     f2 = mkl_fft.fft(self.xd1)
     assert_allclose(f1, f2)
Esempio n. 5
0
 def test_cf_contig(self):
     """fft of F-contiguous array is the same as of C-contiguous with same data"""
     for ar in [self.ad, self.af, self.az, self.ac]:
         r_tol, a_tol = _get_rtol_atol(ar)
         d_ccont = ar.copy()
         d_fcont = np.asfortranarray(d_ccont)
         f1 = mkl_fft.fft(d_ccont)
         f2 = mkl_fft.fft(d_fcont)
         assert_allclose(f1, f2, rtol=r_tol, atol=a_tol)
Esempio n. 6
0
 def test_matrix1(self):
     """fftn equals repeated fft"""
     for ar in [self.md, self.mz, self.mf, self.mc]:
         r_tol, a_tol = _get_rtol_atol(ar)
         d = ar.copy()
         t1 = mkl_fft.fftn(d)
         t2 = mkl_fft.fft(mkl_fft.fft(d, axis=0), axis=1)
         t3 = mkl_fft.fft(mkl_fft.fft(d, axis=1), axis=0)
         assert_allclose(t1, t2, rtol=r_tol, atol=a_tol, err_msg = "failed test for dtype {}, max abs diff: {}".format(d.dtype, np.max(np.abs(t1-t2))))
         assert_allclose(t1, t3, rtol=r_tol, atol=a_tol, err_msg = "failed test for dtype {}, max abs diff: {}".format(d.dtype, np.max(np.abs(t1-t3))))
Esempio n. 7
0
 def test_array6(self):
     """Inputs with Fortran layout are handled correctly, issue 29"""
     z = self.az3
     z = z.astype(z.dtype, order='F')
     y1 = mkl_fft.fft(z, axis=0)
     y2 = mkl_fft.fft(self.az3, axis=0)
     assert_allclose(y1, y2, atol=2e-15)
     y1 = mkl_fft.fft(z, axis=-1)
     y2 = mkl_fft.fft(self.az3, axis=-1)
     assert_allclose(y1, y2, atol=2e-15)
Esempio n. 8
0
    def test_vector6(self):
        "fft in place"
        x = self.xz1.copy()
        f1 = mkl_fft.fft(x, overwrite_x=True)
        assert_(not _datacopied(f1, x))  # this is in-place

        x = self.xz1.copy()
        f1 = mkl_fft.fft(x[::-2], overwrite_x=True)
        assert_( not np.allclose(x, self.xz1) ) # this is also in-place
        assert_( np.allclose(x[-2::-2], self.xz1[-2::-2]) ) 
        assert_( np.allclose(x[-1::-2], f1) ) 
Esempio n. 9
0
 def IFFT_t_2(self, A):
     if MKL_AVAILABLE:
         if global_variables.PRE_FFTSHIFT:
             return mkl_fft.fft(A)
         else:
             return ifftshift(mkl_fft.fft(fftshift(A)))
     else:
         if global_variables.PRE_FFTSHIFT:
             return scipy.fftpack.fft(A)
         else:
             return ifftshift(scipy.fftpack.fft(fftshift(A)))
Esempio n. 10
0
    def test_vector4(self):
        "fft of strided is same as fft of contiguous copy"
        x = self.xz1[::2]
        f1 = mkl_fft.fft(x)
        f2 = mkl_fft.fft(x.copy())
        assert_(np.allclose(f1,f2))

        x = self.xz1[::-1]
        f1 = mkl_fft.fft(x)
        f2 = mkl_fft.fft(x.copy())
        assert_(np.allclose(f1,f2))
Esempio n. 11
0
    def test_vector10(self):
        "check n for real arrays"
        x = self.xd1[:8].copy()
        f1 = mkl_fft.fft(x, n = 7)
        f2 = mkl_fft.fft(self.xd1[:7])
        assert_allclose(f1, f2)

        f1 = mkl_fft.fft(x, n = 9)
        y = self.xd1[:9].copy()
        y[-1] = 0.0
        f2 = mkl_fft.fft(y)
        assert_allclose(f1, f2)
Esempio n. 12
0
    def test_vector11(self):
        "check n for complex arrays"
        x = self.xz1[:8].copy()
        f1 = mkl_fft.fft(x, n = 7)
        f2 = mkl_fft.fft(self.xz1[:7])
        assert_allclose(f1, f2)

        f1 = mkl_fft.fft(x, n = 9)
        y = self.xz1[:9].copy()
        y[-1] = 0.0 + 0.0j
        f2 = mkl_fft.fft(y)
        assert_allclose(f1, f2)
Esempio n. 13
0
    def test_scale_1d_vector(self):
        X = np.ones(128, dtype='d')
        f1 = mkl_fft.fft(X, forward_scale=0.25)
        f2 = mkl_fft.fft(X)
        r_tol, a_tol = _get_rtol_atol(X)
        assert_allclose(4*f1, f2, rtol=r_tol, atol=a_tol)

        X1 = mkl_fft.ifft(f1, forward_scale=0.25)
        assert_allclose(X, X1, rtol=r_tol, atol=a_tol)

        f3 = mkl_fft.rfft(X, forward_scale=0.5)
        X2 = mkl_fft.irfft(f3, forward_scale=0.5)
        assert_allclose(X, X2, rtol=r_tol, atol=a_tol)
Esempio n. 14
0
    def test_scale_1d_array(self):
        X = np.ones((8, 4, 4,), dtype='d')
        f1 = mkl_fft.fft(X, axis=1, forward_scale=0.25)
        f2 = mkl_fft.fft(X, axis=1)
        r_tol, a_tol = _get_rtol_atol(X)
        assert_allclose(4*f1, f2, rtol=r_tol, atol=a_tol)

        X1 = mkl_fft.ifft(f1, axis=1, forward_scale=0.25)
        assert_allclose(X, X1, rtol=r_tol, atol=a_tol)

        f3 = mkl_fft.rfft(X, axis=0, forward_scale=0.5)
        X2 = mkl_fft.irfft(f3, axis=0, forward_scale=0.5)
        assert_allclose(X, X2, rtol=r_tol, atol=a_tol)
Esempio n. 15
0
def fft(a, overwrite_x = False):
    """Computes  fft on a matrix of shape (..., n).
    
    This is identical to np.fft2(a)
    
    Parameters
    ----------
    a : array_like
        Input array (must be complex).
    overwrite_x : bool
        Specifies whether original array can be destroyed (for inplace transform)
       
    Returns
    -------
    out : complex ndarray
        Result of the transformation along the (-4,-3) axes.    
    """
    a = np.asarray(a, dtype = CDTYPE)      
    libname = DTMMConfig["fftlib"]    
    if libname == "mkl_fft":
        return mkl_fft.fft(a, overwrite_x = overwrite_x)
    elif libname == "scipy":
        return spfft.fft(a,  overwrite_x = overwrite_x)
    elif libname == "numpy":
        return npfft.fft(a)
    elif libname == "pyfftw":
        return pyfftw.interfaces.scipy_fft.fft(a, overwrite_x = overwrite_x)
    else: #default implementation is numpy
        return npfft.fft(a)
Esempio n. 16
0
def mkl_fft1d(a):
    
    n,m = a.shape
    b = np.zeros((n,m),dtype=np.complex128)
    for i in xrange(m):
        b[:,i] = mkl_fft.fft(a[:,i]+0j)
    return b
Esempio n. 17
0
def mkl_fft1d(a):
    
    n,m = a.shape
    b = np.zeros((n,m),dtype=np.complex128)
    for i in xrange(m):
        b[:,i] = mkl_fft.fft(a[:,i]+0j)
    return b
Esempio n. 18
0
    def test_vector3(self):
        "fft(ifft(x)) is identity"
        f1 = mkl_fft.ifft(self.xz1)
        f2 = mkl_fft.fft(f1)
        assert_(np.allclose(self.xz1,f2))

        f1 = mkl_fft.ifft(self.xc1)
        f2 = mkl_fft.fft(f1)
        assert_( np.allclose(self.xc1,f2))

        f1 = mkl_fft.ifft(self.xd1)
        f2 = mkl_fft.fft(f1)
        assert_( np.allclose(self.xd1,f2))

        f1 = mkl_fft.ifft(self.xf1)
        f2 = mkl_fft.fft(f1)
        assert_( np.allclose(self.xf1, f2, atol = 2.0e-7))
Esempio n. 19
0
def mfft(f):
    M = f.shape[0]
    N = f.shape[1]
    NS = N - 1
    N2 = int(N / 2)
    fh = fft(f)
    temp = np.empty((M, NS), dtype=complex)
    temp[:, :N2] = fh[:, :N2]
    temp[:, N2:] = fh[:, N2 + 1:]
    return temp
Esempio n. 20
0
 def plot_wavenum_evol(self, label):
     cutoff = int(self.size / 2)
     amplitudes = np.absolute(fft(self.phi)[0:cutoff])
     wavenumbers = np.argmax(amplitudes, axis=-1)
     plt.plot(wavenumbers)
     plt.xlabel(r'$t$')
     plt.ylabel(r'$n$')
     plt.tight_layout()
     plt.savefig('{}_wavenum.pdf'.format(label))
     plt.close()
Esempio n. 21
0
File: fft.py Progetto: inwwin/cddm
def _fft(a, overwrite_x=False):
    libname = CDDMConfig["fftlib"]
    if libname == "mkl_fft":
        return mkl_fft.fft(a, overwrite_x=overwrite_x)
    elif libname == "scipy":
        return spfft.fft(a, overwrite_x=overwrite_x)
    elif libname == "numpy":
        return np.fft.fft(a)
    elif libname == "pyfftw":
        return fftw.scipy_fftpack.fft(a, overwrite_x=overwrite_x)
Esempio n. 22
0
    def test_fft(self):

        n_tests = 1000
        n_max = 2
        d_max = 100

        norm = 'ortho'
        inplace = True
        scrambled = True

        passed = True

        for i in range(n_tests):
            ndim = np.random.randint(1, high=n_max + 1)
            axis = np.random.randint(0, high=ndim)
            dims = np.random.randint(1, high=d_max + 1, size=(ndim))

            x = np.random.normal(size=dims) + 1j * np.random.normal(size=dims)

            if inplace:
                X = x.copy()
                fft(X, axis=axis, norm=norm, out=X, scrambled=scrambled)
            else:
                X = fft(x, axis=axis, norm=norm, scrambled=scrambled)

            Y = np.fft.fft(x, axis=axis, norm=norm)

            x_ = ifft(X, axis=axis, norm=norm)

            if not np.allclose(X, Y) and not scrambled:
                print(
                    '  Failed forward with ndim=%d axis=%d dims=' %
                    (ndim, axis), dims)
                passed = False

            if not np.allclose(x, x_):
                print(
                    '  Failed backward with ndim=%d axis=%d dims=' %
                    (ndim, axis), dims)
                passed = False

        self.assertTrue(passed)
Esempio n. 23
0
    def test_fft(self):

        n_tests = 1000
        n_max = 2
        d_max = 100

        norm = 'ortho'
        inplace = True
        scrambled = True

        passed = True

        for i in range(n_tests):
            ndim = np.random.randint(1,high=n_max+1)
            axis = np.random.randint(0,high=ndim)
            dims = np.random.randint(1,high=d_max+1,size=(ndim))

            x = np.random.normal(size=dims) + 1j*np.random.normal(size=dims)

            if inplace:
                X = x.copy()
                fft(X, axis=axis, norm=norm, out=X, scrambled=scrambled)
            else:
                X = fft(x, axis=axis, norm=norm, scrambled=scrambled)

            Y = np.fft.fft(x, axis=axis, norm=norm)

            x_ = ifft(X, axis=axis, norm=norm)

            if not np.allclose(X,Y) and not scrambled:
                print('  Failed forward with ndim=%d axis=%d dims=' % (ndim, axis), dims)
                passed = False

            if not np.allclose(x, x_):
                print('  Failed backward with ndim=%d axis=%d dims=' % (ndim, axis), dims)
                passed = False

        self.assertTrue(passed)
Esempio n. 24
0
def hilbert(signal: np.ndarray) -> np.ndarray:
    """
    hilbert(signal)

    calculate the analytic signal using the `Hilbert transform` (same with scipy.signal.hilbert)

    .. math::
        S_a = S + iS_H

        where S_H is the hilbert transform of the signal

    Parameters
    ----------
        signal : np.ndarray
            signal

    Returns
    -------
        np.ndarray
           :math:'s + s_{H} i'
    """
    @njit
    def _modifyfft(x: np.ndarray) -> np.ndarray:
        """used by the function hilbert

        Parameters
        ----------
            x : np.ndarray
                [description]

        Returns
        -------
            np.ndarray
                [description]
        """
        N = x.size
        if N % 2 == 0:
            x[1:N // 2] = x[1:N // 2] * 2
            x[N // 2 + 1:] = 0
        else:
            x[1:(N + 1) // 2] = x[1:(N + 1) // 2] * 2
            x[(N + 1) // 2:] = 0
        return x

    Xf = fft(signal)
    Xf = _modifyfft(Xf)
    x = ifft(Xf)
    return x
Esempio n. 25
0
 def test_array5(self):
     """Inputs with zero strides are handled correctly"""
     z = self.az3
     z1 = z[np.newaxis]
     f1 = mkl_fft.fft(z1, axis=-1)
     f2 = mkl_fft.fft(z1.reshape(z1.shape), axis=-1)
     assert_allclose(f1, f2, atol=2e-15)
     z1 = z[:, np.newaxis]
     f1 = mkl_fft.fft(z1, axis=-1)
     f2 = mkl_fft.fft(z1.reshape(z1.shape), axis=-1)
     assert_allclose(f1, f2, atol=2e-15)
     z1 = z[:, :, np.newaxis]
     f1 = mkl_fft.fft(z1, axis=-1)
     f2 = mkl_fft.fft(z1.reshape(z1.shape), axis=-1)
     assert_allclose(f1, f2, atol=2e-15)
     z1 = z[:, :, :, np.newaxis]
     f1 = mkl_fft.fft(z1, axis=-1)
     f2 = mkl_fft.fft(z1.reshape(z1.shape), axis=-1)
     assert_allclose(f1, f2, atol=2e-15)
Esempio n. 26
0
def test_conv_sub_1d(ds=1):
    
    N = 2**12
    
    # signal - 2-d array N x K, where K - number of signals
    signal = np.random.normal(size = (N, 5))
    signal_fft = mkl_fft.fft(signal.T).T
    
    f = gabor(N, 1, 1)
    
    signal_filtered_ds = conv_sub_1d(signal_fft, f, ds = ds)
    
    _, ax = plt.subplots(1, 2, figsize = (10, 4))
    ax[0].plot(signal[:,0])
    ax[0].set_title('Initial signal: {}'.format(signal.shape))
    
    ax[1].plot(signal_filtered_ds[:,0])
    ax[1].set_title('Filtered downsampled signal: {}'.format(
        signal_filtered_ds.shape))
    plt.show() 
Esempio n. 27
0
    def test_fft_truncation(self):

        n_tests = 1000
        n_max = 2
        d_max = 100

        norm = None
        inplace = False
        scrambled = False

        passed = True

        for i in range(n_tests):
            ndim = np.random.randint(1, high=n_max + 1)
            axis = np.random.randint(0, high=ndim)
            dims = np.random.randint(2, high=d_max + 1, size=(ndim))

            x = np.random.normal(size=dims) + 1j * np.random.normal(size=dims)
            x_trunc = np.swapaxes(x, axis, -1)[..., :dims[axis] // 2]
            x_trunc = np.swapaxes(x_trunc, -1, axis)

            X = fft(x, axis=axis, n=dims[axis] // 2)

            Y = np.fft.fft(x, axis=axis, n=dims[axis] // 2)

            x_ = ifft(X, axis=axis, norm=norm)

            if not np.allclose(X, Y) and not scrambled:
                print(
                    '  Failed forward with ndim=%d axis=%d dims=' %
                    (ndim, axis), dims)
                passed = False

            if not np.allclose(x_trunc, x_):
                print(
                    '  Failed backward with ndim=%d axis=%d dims=' %
                    (ndim, axis), dims)
                passed = False

        self.assertTrue(passed)
Esempio n. 28
0
File: misc.py Progetto: caot/tomopy
 def fft(x, n=None, axis=-1, overwrite_input=False, extra_info=None):
     return mkl_fft.fft(x, n=n, axis=axis, overwrite_x=overwrite_input)
Esempio n. 29
0
 def fft(x, n=None, axis=-1, overwrite_input=False, extra_info=None):
     return mkl_fft.fft(x, n=n, axis=axis, overwrite_x=overwrite_input)
Esempio n. 30
0
 def test_matrix4(self):
     x = self.az2.copy()
     f1 = mkl_fft.fft(x[::3,::-1])
     f2 = mkl_fft.fft(x[::3,::-1], overwrite_x=True)
     assert_allclose(f1, f2)
Esempio n. 31
0
 def test_matrix6(self):
     x = self.ad2;
     f1 = mkl_fft.ifft(x)
     f2 = mkl_fft.fft(f1)
     assert_allclose(x, f2, atol=1e-10)
Esempio n. 32
0
shape = (len(epsilons), len(us))
means = np.empty(shape, dtype='float64')
error_bars = np.zeros(shape, dtype='float64')

for (i, epsilon) in enumerate(epsilons):
    for (k, u) in enumerate(us):
        label = 'u_{}_epsilon_{}{}'.format(u, epsilon, indices[k])
        print(label)
        solver = StoEvolution1D()
        solver.load(label)
        # solver.plot_evolution(label, t_size=200, x_size=400)
        # solver.plot_wavenum_evol(label)
        phi = solver.phi[-average_over:]

        cutoff = int(length / 2)
        amplitudes = np.absolute(fft(phi)[0:cutoff])
        wavenumbers = 2 * np.argmax(amplitudes, axis=-1)
        means[i, k] = np.mean(wavenumbers)
        error_bars[i, k] = np.std(wavenumbers)

plt.rc('text', usetex=True)
plt.rc('font', family='serif', size=18)
qc = np.sqrt(solver.a / (2 * solver.k))
x = np.log(us)
colors = ['tab:blue', 'tab:orange']
for (i, epsilon) in enumerate(epsilons):
    y = np.log(length) - np.log(means[i])
    poly = np.poly1d(np.polyfit(x, y, 1))
    plt.errorbar(x,
                 y,
                 yerr=error_bars[i] / means[i],
Esempio n. 33
0
 def test_array4(self):
     x = self.ad3
     for ax in range(x.ndim):
         f1 = mkl_fft.ifft(x, axis = ax)
         f2 = mkl_fft.fft(f1, axis = ax)
         assert_allclose(f2, x, atol=2e-15)