当前位置: 首页>>代码示例>>Python>>正文


Python signal.fftconvolve方法代码示例

本文整理汇总了Python中scipy.signal.fftconvolve方法的典型用法代码示例。如果您正苦于以下问题:Python signal.fftconvolve方法的具体用法?Python signal.fftconvolve怎么用?Python signal.fftconvolve使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在scipy.signal的用法示例。


在下文中一共展示了signal.fftconvolve方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: acovf_fft

# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import fftconvolve [as 别名]
def acovf_fft(x, demean=True):
    '''autocovariance function with call to fftconvolve, biased

    Parameters
    ----------
    x : array_like
        timeseries, signal
    demean : boolean
        If true, then demean time series

    Returns
    -------
    acovf : array
        autocovariance for data, same length as x

    might work for nd in parallel with time along axis 0

    '''
    from scipy import signal
    x = np.asarray(x)

    if demean:
        x = x - x.mean()

    signal.fftconvolve(x,x[::-1])[len(x)-1:len(x)+10]/x.shape[0] 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:27,代码来源:tsa.py

示例2: test_valid_mode

# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import fftconvolve [as 别名]
def test_valid_mode(self):
        # See gh-5897
        a = array([3, 2, 1])
        b = array([3, 3, 5, 6, 8, 7, 9, 0, 1])
        expected = array([24., 31., 41., 43., 49., 25., 12.])

        out = fftconvolve(a, b, 'valid')
        assert_array_almost_equal(out, expected)

        out = fftconvolve(b, a, 'valid')
        assert_array_almost_equal(out, expected)

        a = array([3 - 1j, 2 + 7j, 1 + 0j])
        b = array([3 + 2j, 3 - 3j, 5 + 0j, 6 - 1j, 8 + 0j])
        expected = array([45. + 12.j, 30. + 23.j, 48 + 32.j])

        out = fftconvolve(a, b, 'valid')
        assert_array_almost_equal(out, expected)

        out = fftconvolve(b, a, 'valid')
        assert_array_almost_equal(out, expected) 
开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:23,代码来源:test_signaltools.py

示例3: test_many_sizes

# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import fftconvolve [as 别名]
def test_many_sizes(self):
        np.random.seed(1234)

        def ns():
            for j in range(1, 100):
                yield j
            for j in range(1000, 1500):
                yield j
            for k in range(50):
                yield np.random.randint(1001, 10000)

        for n in ns():
            msg = 'n=%d' % (n,)
            a = np.random.rand(n) + 1j * np.random.rand(n)
            b = np.random.rand(n) + 1j * np.random.rand(n)
            c = fftconvolve(a, b, 'full')
            d = np.convolve(a, b, 'full')
            assert_allclose(c, d, atol=1e-10, err_msg=msg) 
开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:20,代码来源:test_signaltools.py

示例4: convolve

# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import fftconvolve [as 别名]
def convolve(self, impulse_segment, allow_resample=False):
        """Convolve this audio segment with the given impulse segment.

        Note that this is an in-place transformation.

        :param impulse_segment: Impulse response segments.
        :type impulse_segment: AudioSegment
        :param allow_resample: Indicates whether resampling is allowed when
                               the impulse_segment has a different sample 
                               rate from this signal.
        :type allow_resample: bool
        :raises ValueError: If the sample rate is not match between two
                            audio segments when resample is not allowed.
        """
        if allow_resample and self.sample_rate != impulse_segment.sample_rate:
            impulse_segment.resample(self.sample_rate)
        if self.sample_rate != impulse_segment.sample_rate:
            raise ValueError("Impulse segment's sample rate (%d Hz) is not "
                             "equal to base signal sample rate (%d Hz)." %
                             (impulse_segment.sample_rate, self.sample_rate))
        samples = signal.fftconvolve(self.samples, impulse_segment.samples,
                                     "full")
        self._samples = samples 
开发者ID:Pelhans,项目名称:ZASR_tensorflow,代码行数:25,代码来源:audio.py

示例5: simulate

# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import fftconvolve [as 别名]
def simulate(self, p, tmin=None, tmax=None, freq=None, dt=1.0):
        """Simulates the head contribution.

        Parameters
        ----------
        p: numpy.ndarray
           Parameters used for simulation.
        tmin: str, optional
        tmax: str, optional
        freq: str, optional
        dt: int, optional

        Returns
        -------
        pandas.Series
            The simulated head contribution.

        """
        self.update_stress(tmin=tmin, tmax=tmax, freq=freq)
        b = self.get_block(p, dt, tmin, tmax)
        stress = self.stress[0].series
        npoints = stress.index.size
        h = Series(data=fftconvolve(stress, b, 'full')[:npoints],
                   index=stress.index, name=self.name, fastpath=True)
        return h 
开发者ID:pastas,项目名称:pastas,代码行数:27,代码来源:stressmodels.py

示例6: convolve

# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import fftconvolve [as 别名]
def convolve(self, distribution):
        """
        Convolves distribution with alpha-stable kernel.

        Args:
            distribution(ndarray): Discrete probability distribution to convolve.

        Returns:
            ndarray: convolution
        """
        gs = np.array(self.study.gridSize)
        padded_distribution = np.zeros(3*np.array(gs))
        if len(gs) == 2:
            padded_distribution[gs[0]:2*gs[0], gs[1]:2*gs[1]] = distribution
        elif len(gs) == 1:
            padded_distribution[gs[0]:2*gs[0]] = distribution

        padded_convolution = fftconvolve(padded_distribution, self.kernel, mode='same')
        if len(gs) == 2:
            convolution = padded_convolution[gs[0]:2*gs[0], gs[1]:2*gs[1]]
        elif len(gs) == 1:
            convolution = padded_convolution[gs[0]:2*gs[0]]

        return convolution 
开发者ID:christophmark,项目名称:bayesloop,代码行数:26,代码来源:transitionModels.py

示例7: sincinterp

# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import fftconvolve [as 别名]
def sincinterp(x):
        """
        Sinc interpolation for computation of fractional transformations.
        As appears in :
        -https://github.com/audiolabs/frft/
        ----------
        Args:
            f       : (array) Complex valued input array
            a       : (float) Alpha factor
        Returns:
            ret     : (array) Real valued synthesised data
        """
        N = len(x)
        y = np.zeros(2 * N - 1, dtype=x.dtype)
        y[:2 * N:2] = x
        xint = fftconvolve( y[:2 * N], np.sinc(np.arange(-(2 * N - 3), (2 * N - 2)).T / 2),)
        return xint[2 * N - 3: -2 * N + 3] 
开发者ID:TUIlmenauAMS,项目名称:ASP,代码行数:19,代码来源:TFMethods.py

示例8: potential_from_kappa_grid_adaptive

# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import fftconvolve [as 别名]
def potential_from_kappa_grid_adaptive(kappa_high_res, grid_spacing, low_res_factor, high_res_kernel_size):
    """
    lensing potential on the convergence grid
    the computation is performed as a convolution of the Green's function with the convergence map using FFT

    :param kappa_high_res: 2d grid of convergence values
    :param grid_spacing: pixel size of grid
    :param low_res_factor: lower resolution factor of larger scale kernel.
    :param high_res_kernel_size: int, size of high resolution kernel in units of degraded pixels
    :return: lensing potential in a 2d grid at positions x_grid, y_grid
    """
    kappa_low_res = image_util.re_size(kappa_high_res, factor=low_res_factor)
    num_pix = len(kappa_high_res) * 2
    if num_pix % 2 == 0:
        num_pix += 1
    grid_spacing_low_res = grid_spacing * low_res_factor
    kernel = potential_kernel(num_pix, grid_spacing)
    kernel_low_res, kernel_high_res = kernel_util.split_kernel(kernel, high_res_kernel_size, low_res_factor, normalized=False)

    f_high_res = scp.fftconvolve(kappa_high_res, kernel_high_res, mode='same') / np.pi * grid_spacing ** 2
    f_high_res = image_util.re_size(f_high_res, low_res_factor)
    f_low_res = scp.fftconvolve(kappa_low_res, kernel_low_res, mode='same') / np.pi * grid_spacing_low_res ** 2
    return f_high_res + f_low_res 
开发者ID:sibirrer,项目名称:lenstronomy,代码行数:25,代码来源:convergence_integrals.py

示例9: deflection_from_kappa_grid

# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import fftconvolve [as 别名]
def deflection_from_kappa_grid(kappa, grid_spacing):
    """
    deflection angles on the convergence grid
    the computation is performed as a convolution of the Green's function with the convergence map using FFT

    :param kappa: convergence values for each pixel (2-d array)
    :param grid_spacing: pixel size of grid
    :return: numerical deflection angles in x- and y- direction
    """
    num_pix = len(kappa) * 2
    if num_pix % 2 == 0:
        num_pix += 1
    kernel_x, kernel_y = deflection_kernel(num_pix, grid_spacing)
    f_x = scp.fftconvolve(kappa, kernel_x, mode='same') / np.pi * grid_spacing ** 2
    f_y = scp.fftconvolve(kappa, kernel_y, mode='same') / np.pi * grid_spacing ** 2
    return f_x, f_y 
开发者ID:sibirrer,项目名称:lenstronomy,代码行数:18,代码来源:convergence_integrals.py

示例10: _project

# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import fftconvolve [as 别名]
def _project(reference_sources, C):
    """Project images using pre-computed filters C
    reference_sources are nsrc X nsampl X nchan
    C is nsrc X nchan X filters_len X nchan
    """
    # shapes: ensure that input is 3d (comprising the source index)
    if len(reference_sources.shape) == 2:
        reference_sources = reference_sources[None, ...]
        C = C[None, ...]

    (nsrc, nsampl, nchan) = reference_sources.shape
    filters_len = C.shape[-2]

    # zero pad
    reference_sources = _zeropad(reference_sources, filters_len - 1, axis=1)
    sproj = np.zeros((nchan, nsampl + filters_len - 1))

    for (j, cj, c) in itertools.product(
        list(range(nsrc)), list(range(nchan)), list(range(nchan))
    ):
        sproj[c] += fftconvolve(
            C[j, cj, :, c],
            reference_sources[j, :, cj]
        )[:nsampl + filters_len - 1]
    return sproj.T 
开发者ID:sigsep,项目名称:sigsep-mus-eval,代码行数:27,代码来源:metrics.py

示例11: get_gabor_filters

# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import fftconvolve [as 别名]
def get_gabor_filters(size=21, filter_scale=4., num_orients=16, weights=False):
    """Get Gabor filter bank. See Preproc for parameters and returns."""
    def _get_sparse_gaussian():
        """Sparse Gaussian."""
        size = 2 * np.ceil(np.sqrt(2.) * filter_scale) + 1
        alt = np.zeros((int(size), int(size)), np.float32)
        alt[int(size // 2), int(size // 2)] = 1
        gaussian = gaussian_filter(alt, filter_scale / np.sqrt(2.), mode='constant')
        gaussian[gaussian < 0.05 * gaussian.max()] = 0
        return gaussian

    gaussian = _get_sparse_gaussian()
    filts = []
    for angle in np.linspace(0., 2 * np.pi, num_orients, endpoint=False):
        acts = np.zeros((size, size), np.float32)
        x, y = np.cos(angle) * filter_scale, np.sin(angle) * filter_scale
        acts[int(size / 2 + y), int(size / 2 + x)] = 1.
        acts[int(size / 2 - y), int(size / 2 - x)] = -1.
        filt = fftconvolve(acts, gaussian, mode='same')
        filt /= np.abs(filt).sum()  # Normalize to ensure the maximum output is 1
        if weights:
            filt = np.abs(filt)
        filts.append(filt)
    return filts 
开发者ID:vicariousinc,项目名称:science_rcn,代码行数:26,代码来源:preproc.py

示例12: _execute

# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import fftconvolve [as 别名]
def _execute(self, x):
        is_2d = x.ndim==2
        output_shape, input_shape = self._output_shape, self._input_shape
        filters = self.filters
        nfilters = filters.shape[0]

        # XXX depends on convolution
        y = numx.empty((x.shape[0], nfilters,
                        output_shape[0], output_shape[1]), dtype=self.dtype)
        for n_im, im in enumerate(x):
            if is_2d:
                im = im.reshape(input_shape)
            for n_flt, flt in enumerate(filters):
                if self.approach == 'fft':
                    y[n_im,n_flt,:,:] = signal.fftconvolve(im, flt, mode=self.mode)
                elif self.approach == 'linear':
                    y[n_im,n_flt,:,:] = signal.convolve2d(im, flt,
                                                          mode=self.mode,
                                                          boundary=self.boundary,
                                                          fillvalue=self.fillvalue)

        # reshape if necessary
        if self.output_2d:
            y.resize((y.shape[0], self.output_dim))

        return y 
开发者ID:ME-ICA,项目名称:me-ica,代码行数:28,代码来源:convolution_nodes.py

示例13: __call__

# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import fftconvolve [as 别名]
def __call__(self, pkg):
        pkg = format_package(pkg)
        wav = pkg['chunk']
        # sample an ir_file
        ir_file = self.sample_IR()
        IR, p_max = self.load_IR(ir_file, self.ir_fmt)
        IR = IR.astype(np.float32)
        wav = wav.data.numpy().reshape(-1)
        Ex = np.dot(wav, wav)
        wav = wav.astype(np.float32).reshape(-1)
        # wav = wav / np.max(np.abs(wav))
        # rev = signal.fftconvolve(wav, IR, mode='full')
        rev = signal.convolve(wav, IR, mode='full').reshape(-1)
        Er = np.dot(rev, rev)
        # rev = rev / np.max(np.abs(rev))
        # IR delay compensation
        rev = self.shift(rev, -p_max)
        if Er > 0:
            Eratio = np.sqrt(Ex / Er) 
        else:
            Eratio = 1.0
            #rev = rev / np.max(np.abs(rev))

        # Trim rev signal to match clean length
        rev = rev[:wav.shape[0]]
        rev = Eratio * rev
        rev = torch.FloatTensor(rev)
        if self.report:
            if 'report' not in pkg:
                pkg['report'] = {}
            pkg['report']['ir_file'] = ir_file
        pkg['chunk'] = rev
        return pkg 
开发者ID:santi-pdp,项目名称:pase,代码行数:35,代码来源:transforms.py

示例14: _pad_nans

# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import fftconvolve [as 别名]
def _pad_nans(x, head=None, tail=None):
    if np.ndim(x) == 1:
        if head is None and tail is None:
            return x
        elif head and tail:
            return np.r_[[np.nan] * head, x, [np.nan] * tail]
        elif tail is None:
            return np.r_[[np.nan] * head, x]
        elif head is None:
            return np.r_[x, [np.nan] * tail]
    elif np.ndim(x) == 2:
        if head is None and tail is None:
            return x
        elif head and tail:
            return np.r_[[[np.nan] * x.shape[1]] * head, x,
                         [[np.nan] * x.shape[1]] * tail]
        elif tail is None:
            return np.r_[[[np.nan] * x.shape[1]] * head, x]
        elif head is None:
            return np.r_[x, [[np.nan] * x.shape[1]] * tail]
    else:
        raise ValueError("Nan-padding for ndim > 2 not implemented")

#original changes and examples in sandbox.tsa.try_var_convolve

# don't do these imports, here just for copied fftconvolve
#get rid of these imports
#from scipy.fftpack import fft, ifft, ifftshift, fft2, ifft2, fftn, \
#     ifftn, fftfreq
#from numpy import product,array 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:32,代码来源:filtertools.py

示例15: fftconvolve_old

# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import fftconvolve [as 别名]
def fftconvolve_old(in1, in2, in3=None, mode="full"):
    """Convolve two N-dimensional arrays using FFT. See convolve.

    copied from scipy.signal.signaltools, but here used to try out inverse filter
    doesn't work or I can't get it to work

     2010-10-23:
    looks ok to me for 1d,
    from results below with padded data array (fftp)
    but it doesn't work for multidimensional inverse filter (fftn)
    original signal.fftconvolve also uses fftn

    """
    s1 = array(in1.shape)
    s2 = array(in2.shape)
    complex_result = (np.issubdtype(in1.dtype, np.complex) or
                      np.issubdtype(in2.dtype, np.complex))
    size = s1+s2-1

    # Always use 2**n-sized FFT
    fsize = 2**np.ceil(np.log2(size))
    IN1 = fftn(in1,fsize)
    #IN1 *= fftn(in2,fsize) #JP: this looks like the only change I made
    IN1 /= fftn(in2,fsize)  # use inverse filter
    # note the inverse is elementwise not matrix inverse
    # is this correct, NO  doesn't seem to work for VARMA
    fslice = tuple([slice(0, int(sz)) for sz in size])
    ret = ifftn(IN1)[fslice].copy()
    del IN1
    if not complex_result:
        ret = ret.real
    if mode == "full":
        return ret
    elif mode == "same":
        if product(s1,axis=0) > product(s2,axis=0):
            osize = s1
        else:
            osize = s2
        return _centered(ret,osize)
    elif mode == "valid":
        return _centered(ret,abs(s2-s1)+1) 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:43,代码来源:try_var_convolve.py


注:本文中的scipy.signal.fftconvolve方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。