python类convolve()的实例源码

test_filter.py 文件源码 项目:urh 作者: jopohl 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def test_fft_convolution(self):
        x = np.array([1, 2, 3])
        h = np.array([0, 1, 0.5])
        expected_result = np.array([1., 2.5, 4.])
        result_np = np.convolve(x, h, 'same')
        self.assertTrue(np.array_equal(result_np, expected_result))

        result_fft = Filter.fft_convolve_1d(x, h)
        self.assertTrue(np.array_equal(result_fft, expected_result))

        x = np.linspace(0, 1, num=10 ** 3).astype(np.complex64)
        h = Filter.design_windowed_sinc_bandpass(0.1, 0.4, 0.01)
        # fft convolve is faster if IR is round about 400 samples or windowed sinc has bandwidth of 0.01
        #print(len(h))

        t_np = time.time()
        result_np = np.convolve(x, h, mode="same")
        t_np = time.time() - t_np

        t_fft = time.time()
        result_fft = Filter.fft_convolve_1d(x, h)
        t_fft = time.time() - t_fft

        np.testing.assert_array_almost_equal(result_np, result_fft)
        #print("fft convolve time", t_fft, "np convolve time", t_np)
Filter.py 文件源码 项目:urh 作者: jopohl 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def apply_bandpass_filter(data, f_low, f_high, filter_bw=0.08):
        if f_low > f_high:
            f_low, f_high = f_high, f_low

        f_low = util.clip(f_low, -0.5, 0.5)
        f_high = util.clip(f_high, -0.5, 0.5)

        h = Filter.design_windowed_sinc_bandpass(f_low, f_high, filter_bw)

        # Choose normal or FFT convolution based on heuristic described in
        # https://softwareengineering.stackexchange.com/questions/171757/computational-complexity-of-correlation-in-time-vs-multiplication-in-frequency-s/
        if len(h) < 8 * math.log(math.sqrt(len(data))):
            logger.debug("Use normal convolve")
            return np.convolve(data, h, 'same')
        else:
            logger.debug("Use FFT convolve")
            return Filter.fft_convolve_1d(data, h)
technical_indicators.py 文件源码 项目:pytrader 作者: owocki 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def moving_average(x, n, type='simple'):
    """
    compute an n period moving average.

    type is 'simple' | 'exponential'

    """
    x = np.asarray(x)
    if type == 'simple':
        weights = np.ones(n)
    else:
        weights = np.exp(np.linspace(-1., 0., n))

    weights /= weights.sum()

    a = np.convolve(x, weights, mode='full')[:len(x)]
    a[:n] = a[n]
    return a
thinkdsp.py 文件源码 项目:ThinkX 作者: AllenDowney 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def convolve(self, other):
        """Convolves two Spectrums.

        other: Spectrum

        returns: Spectrum
        """
        assert all(self.fs == other.fs)
        if self.full:
            hs1 = np.fft.fftshift(self.hs)
            hs2 = np.fft.fftshift(other.hs)
            hs = np.convolve(hs1, hs2, mode='same')
            hs = np.fft.ifftshift(hs)
        else:
            # not sure this branch would mean very much
            hs = np.convolve(self.hs, other.hs, mode='same')

        return Spectrum(hs, self.fs, self.framerate, self.full)
thinkdsp.py 文件源码 项目:ThinkX 作者: AllenDowney 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def convolve(self, other):
        """Convolves two waves.

        Note: this operation ignores the timestamps; the result
        has the timestamps of self.

        other: Wave or NumPy array

        returns: Wave
        """
        if isinstance(other, Wave):
            assert self.framerate == other.framerate
            window = other.ys
        else:
            window = other

        ys = np.convolve(self.ys, window, mode='full')
        #ts = np.arange(len(ys)) / self.framerate
        return Wave(ys, framerate=self.framerate)
plot_learning.py 文件源码 项目:almond-nnparser 作者: Stanford-Mobisocial-IoT-Lab 项目源码 文件源码 阅读 44 收藏 0 点赞 0 评论 0
def movingaverage (values, window):
    weights = np.repeat(1.0, window)/window
    sma = np.convolve(values, weights, 'valid')
    return sma
gen_plots.py 文件源码 项目:almond-nnparser 作者: Stanford-Mobisocial-IoT-Lab 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def movingaverage (values, window):
    weights = np.repeat(1.0, window)/window
    sma = np.convolve(values, weights, 'valid')
    return sma
plot_utils.py 文件源码 项目:pybot 作者: spillai 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def moving_average(X, win_size=3): 
    return np.convolve(X, np.repeat(1.0, win_size) / win_size, 'valid')
common.py 文件源码 项目:ProtScan 作者: gianlucacorrado 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def smooth(votes, **params):
    """Compute the convolution with a Gaussian signal."""
    window = params.get('window', 50)
    std = params.get('std', 20)
    profiles = dict()
    window = gaussian(window, std=std)
    for k, vote in votes.iteritems():
        smoothed = convolve(vote, window, mode='same')
        profiles[k] = smoothed
    return profiles
read_weather.py 文件源码 项目:PEAS 作者: panoptes 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def movingaverage(interval, window_size):
    window = np.ones(int(window_size)) / float(window_size)
    return np.convolve(interval, window, 'same')


# -----------------------------------------------------------------------------
# AAG Cloud Sensor Class
# -----------------------------------------------------------------------------
dgrad.py 文件源码 项目:pyrsss 作者: butala 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def __init__(self, n, axis, order=3, mode='valid'):
        """
        Construct a second-order gradient operator for signal of dimension
        *n* for dimension *axis*. Use a filter kernel of length
        *order* (must be odd). Use convolution type *mode*.
        """
        # assert that the filter length is odd
        assert(order % 2 == 1)
        self.n = n
        self.ndim = len(self.n)
        self.axis = axis
        if axis < 0 or axis >= self.ndim:
            raise ValueError('0 <= axis (= {0}) < ndim = {1}'.format(axis, self.ndim))

        self.d = differentiator(int(order/2) + 1)
        self.d2 = NP.convolve(self.d, self.d)

        self.mode = mode

        h_list = []
        m = []
        for i in reversed(range(self.ndim)):
            if i == axis:
                h_list.append(self.d2)
            else:
                h_list.append(NP.array([1]))
            m.append(len(h_list[-1]))
        self.m = m

        if mode == 'circ':
            n_prime = array(n) - m + 1
            super(Gradient2Filter, self).__init__(n_prime, h_list, mode=mode)
        else:
            super(Gradient2Filter, self).__init__(n, h_list, mode=mode)
graph.py 文件源码 项目:ml-forex 作者: ADM91 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def plot_ema(self, n, p, linestyle):
        temp = []
        for i in range(n):
            temp.append(i**p)
        mask = list(reversed([float(x)/sum(temp) for x in temp]))

        self.ema = np.convolve(self.signal[:,1], mask, mode='valid')
        print len(self.ema)
        print len(self.tstamps)
        self.plt.plot(self.tstamps[n-1:], self.ema, linestyle, linewidth=1.7)
test_regression.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 41 收藏 0 点赞 0 评论 0
def test_convolve_empty(self, level=rlevel):
        # Convolve should raise an error for empty input array.
        self.assertRaises(ValueError, np.convolve, [], [1])
        self.assertRaises(ValueError, np.convolve, [1], [])
test_numeric.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_object(self):
        d = [1.] * 100
        k = [1.] * 3
        assert_array_almost_equal(np.convolve(d, k)[2:-2], np.full(98, 3))
test_numeric.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def test_no_overwrite(self):
        d = np.ones(100)
        k = np.ones(3)
        np.convolve(d, k)
        assert_array_equal(d, np.ones(100))
        assert_array_equal(k, np.ones(3))
polynomial.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def polymul(c1, c2):
    """
    Multiply one polynomial by another.

    Returns the product of two polynomials `c1` * `c2`.  The arguments are
    sequences of coefficients, from lowest order term to highest, e.g.,
    [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2.``

    Parameters
    ----------
    c1, c2 : array_like
        1-D arrays of coefficients representing a polynomial, relative to the
        "standard" basis, and ordered from lowest order term to highest.

    Returns
    -------
    out : ndarray
        Of the coefficients of their product.

    See Also
    --------
    polyadd, polysub, polydiv, polypow

    Examples
    --------
    >>> from numpy.polynomial import polynomial as P
    >>> c1 = (1,2,3)
    >>> c2 = (3,2,1)
    >>> P.polymul(c1,c2)
    array([  3.,   8.,  14.,   8.,   3.])

    """
    # c1, c2 are trimmed copies
    [c1, c2] = pu.as_series([c1, c2])
    ret = np.convolve(c1, c2)
    return pu.trimseq(ret)
runner.py 文件源码 项目:reinforcement_learning 作者: andreweskeclarke 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def runningMean(self, x, N):
        return np.convolve(x, np.ones((N,))/N)[(N-1):]
visualize.py 文件源码 项目:pytorch-a2c-ppo-acktr 作者: ikostrikov 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def smooth_reward_curve(x, y):
    # Halfwidth of our smoothing convolution
    halfwidth = min(31, int(np.ceil(len(x) / 30)))
    k = halfwidth
    xsmoo = x[k:-k]
    ysmoo = np.convolve(y, np.ones(2 * k + 1), mode='valid') / \
        np.convolve(np.ones_like(y), np.ones(2 * k + 1), mode='valid')
    downsample = max(int(np.floor(len(xsmoo) / 1e3)), 1)
    return xsmoo[::downsample], ysmoo[::downsample]
util.py 文件源码 项目:srcnn-from-scratch 作者: kenji0x02 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def smooth_curve(x):
    """?????????????????????

    ???http://glowingpython.blogspot.jp/2012/02/convolution-with-numpy.html
    """
    window_len = 11
    s = np.r_[x[window_len - 1:0:-1], x, x[-1:-window_len:-1]]
    w = np.kaiser(window_len, 2)
    y = np.convolve(w / w.sum(), s, mode='valid')
    return y[5:len(y) - 5]
plot.py 文件源码 项目:vnet.pytorch 作者: mattmacy 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def rolling(N, i, loss, err):
    i_ = i[N-1:]
    K = np.full(N, 1./N)
    loss_ = np.convolve(loss, K, 'valid')
    err_ = np.convolve(err, K, 'valid')
    return i_, loss_, err_


问题


面经


文章

微信
公众号

扫码关注公众号