Python numpy.correlate() Examples

The following are 30 code examples for showing how to use numpy.correlate(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: tedana   Author: ME-ICA   File: ma_pca.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def _autocorr(data):
    """
    Calculates the auto correlation of a given array.

    Parameters
    ----------
    data : array-like
        The array to calculate the autocorrelation of

    Returns
    -------
    u : ndarray
        The array of autocorrelations
    """
    u = np.correlate(data, data, mode='full')
    # Take upper half of correlation matrix
    return u[u.size // 2:] 
Example 2
Project: vnpy_crypto   Author: birforce   File: ar_model.py    License: MIT License 6 votes vote down vote up
def _presample_varcov(self, params):
        """
        Returns the inverse of the presample variance-covariance.

        Notes
        -----
        See Hamilton p. 125
        """
        k = self.k_trend
        p = self.k_ar
        p1 = p+1

        # get inv(Vp) Hamilton 5.3.7
        params0 = np.r_[-1, params[k:]]

        Vpinv = np.zeros((p, p), dtype=params.dtype)
        for i in range(1, p1):
            Vpinv[i-1, i-1:] = np.correlate(params0, params0[:i],)[:-1]
            Vpinv[i-1, i-1:] -= np.correlate(params0[-i:], params0,)[:-1]

        Vpinv = Vpinv + Vpinv.T - np.diag(Vpinv.diagonal())
        return Vpinv 
Example 3
Project: vnpy_crypto   Author: birforce   File: example_arma.py    License: MIT License 6 votes vote down vote up
def ar_generator(N=512, sigma=1.):
    # this generates a signal u(n) = a1*u(n-1) + a2*u(n-2) + ... + v(n)
    # where v(n) is a stationary stochastic process with zero mean
    # and variance = sigma
    # this sequence is shown to be estimated well by an order 8 AR system
    taps = np.array([2.7607, -3.8106, 2.6535, -0.9238])
    v = np.random.normal(size=N, scale=sigma**0.5)
    u = np.zeros(N)
    P = len(taps)
    for l in range(P):
        u[l] = v[l] + np.dot(u[:l][::-1], taps[:l])
    for l in range(P,N):
        u[l] = v[l] + np.dot(u[l-P:l][::-1], taps)
    return u, v, taps

#JP: small differences to using np.correlate, because assumes mean(s)=0
#    denominator is N, not N-k, biased estimator
#    misnomer: (biased) autocovariance not autocorrelation
#from nitime.utils 
Example 4
Project: VideoDigitalWatermarking   Author: piraaa   File: watermarking.py    License: MIT License 6 votes vote down vote up
def extractMseq(cover, stego, secret_length, m, tau=1):
	u"""Extract secret informations by spread spectrum using m-sequence.
	@param  cover         : cover data (2 dimensional np.ndarray)
	@param  stego         : stego data (2 dimension np.ndarray)
	@param  secret_length : length of secret information
	@param  m             : M-Sequence
	@param  tau           : embed shift interval
	@return secret        : extracted secret information
	"""

	cover = _image2vrctor(cover)
	stego = _image2vrctor(stego)

	m_length = len(m)

	data = stego - cover
	data = data[:m_length:tau]

	secret_data = correlate(m, data, cycle=CYCLE)
	center = ((m_length-1)*2+1)//2
	secret_data = secret_data[center:center+secret_length]
	secret_data = list(map(_checkData, secret_data))

	return secret_data 
Example 5
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_signaltools.py    License: MIT License 6 votes vote down vote up
def test_rank0(self, dt):
        a = np.array(np.random.randn()).astype(dt)
        a += 1j * np.array(np.random.randn()).astype(dt)
        b = np.array(np.random.randn()).astype(dt)
        b += 1j * np.array(np.random.randn()).astype(dt)

        y_r = (correlate(a.real, b.real)
               + correlate(a.imag, b.imag)).astype(dt)
        y_r += 1j * (-correlate(a.real, b.imag) + correlate(a.imag, b.real))

        y = correlate(a, b, 'full')
        assert_array_almost_equal(y, y_r, decimal=self.decimal(dt) - 1)
        assert_equal(y.dtype, dt)

        assert_equal(correlate([1], [2j]), correlate(1, 2j))
        assert_equal(correlate([2j], [3j]), correlate(2j, 3j))
        assert_equal(correlate([3j], [4]), correlate(3j, 4)) 
Example 6
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_signaltools.py    License: MIT License 6 votes vote down vote up
def test_consistency_correlate_funcs(self):
        # Compare np.correlate, signal.correlate, signal.correlate2d
        a = np.arange(5)
        b = np.array([3.2, 1.4, 3])
        for mode in ['full', 'valid', 'same']:
            assert_almost_equal(np.correlate(a, b, mode=mode),
                                signal.correlate(a, b, mode=mode))
            assert_almost_equal(np.squeeze(signal.correlate2d([a], [b],
                                                              mode=mode)),
                                signal.correlate(a, b, mode=mode))

            # See gh-5897
            if mode == 'valid':
                assert_almost_equal(np.correlate(b, a, mode=mode),
                                    signal.correlate(b, a, mode=mode))
                assert_almost_equal(np.squeeze(signal.correlate2d([b], [a],
                                                                  mode=mode)),
                                    signal.correlate(b, a, mode=mode)) 
Example 7
Project: recruit   Author: Frank-qlu   File: test_numeric.py    License: Apache License 2.0 5 votes vote down vote up
def test_float(self):
        self._setup(float)
        z = np.correlate(self.x, self.y, 'full')
        assert_array_almost_equal(z, self.z1)
        z = np.correlate(self.x, self.y[:-1], 'full')
        assert_array_almost_equal(z, self.z1_4)
        z = np.correlate(self.y, self.x, 'full')
        assert_array_almost_equal(z, self.z2)
        z = np.correlate(self.x[::-1], self.y, 'full')
        assert_array_almost_equal(z, self.z1r)
        z = np.correlate(self.y, self.x[::-1], 'full')
        assert_array_almost_equal(z, self.z2r)
        z = np.correlate(self.xs, self.y, 'full')
        assert_array_almost_equal(z, self.zs) 
Example 8
Project: recruit   Author: Frank-qlu   File: test_numeric.py    License: Apache License 2.0 5 votes vote down vote up
def test_object(self):
        self._setup(Decimal)
        z = np.correlate(self.x, self.y, 'full')
        assert_array_almost_equal(z, self.z1)
        z = np.correlate(self.y, self.x, 'full')
        assert_array_almost_equal(z, self.z2) 
Example 9
Project: recruit   Author: Frank-qlu   File: test_numeric.py    License: Apache License 2.0 5 votes vote down vote up
def test_no_overwrite(self):
        d = np.ones(100)
        k = np.ones(3)
        np.correlate(d, k)
        assert_array_equal(d, np.ones(100))
        assert_array_equal(k, np.ones(3)) 
Example 10
Project: recruit   Author: Frank-qlu   File: test_numeric.py    License: Apache License 2.0 5 votes vote down vote up
def test_complex(self):
        x = np.array([1, 2, 3, 4+1j], dtype=complex)
        y = np.array([-1, -2j, 3+1j], dtype=complex)
        r_z = np.array([3-1j, 6, 8+1j, 11+5j, -5+8j, -4-1j], dtype=complex)
        r_z = r_z[::-1].conjugate()
        z = np.correlate(y, x, mode='full')
        assert_array_almost_equal(z, r_z) 
Example 11
Project: ibllib   Author: int-brain-lab   File: xcorr_numpy.py    License: MIT License 5 votes vote down vote up
def xcorr(x, y, maxlags=None):
    """Cross-correlation between two 1D signals of the same length."""
    ns = len(x)
    if len(y) != ns:
        raise ValueError("x and y should have the same length.")
    maxlags = maxlags or ns - 1
    return np.correlate(x, y, mode='full')[ns - 1 - maxlags:ns + maxlags] 
Example 12
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_numeric.py    License: MIT License 5 votes vote down vote up
def test_float(self):
        self._setup(np.float)
        z = np.correlate(self.x, self.y, 'full')
        assert_array_almost_equal(z, self.z1)
        z = np.correlate(self.x, self.y[:-1], 'full')
        assert_array_almost_equal(z, self.z1_4)
        z = np.correlate(self.y, self.x, 'full')
        assert_array_almost_equal(z, self.z2)
        z = np.correlate(self.x[::-1], self.y, 'full')
        assert_array_almost_equal(z, self.z1r)
        z = np.correlate(self.y, self.x[::-1], 'full')
        assert_array_almost_equal(z, self.z2r)
        z = np.correlate(self.xs, self.y, 'full')
        assert_array_almost_equal(z, self.zs) 
Example 13
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_numeric.py    License: MIT License 5 votes vote down vote up
def test_object(self):
        self._setup(Decimal)
        z = np.correlate(self.x, self.y, 'full')
        assert_array_almost_equal(z, self.z1)
        z = np.correlate(self.y, self.x, 'full')
        assert_array_almost_equal(z, self.z2) 
Example 14
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_numeric.py    License: MIT License 5 votes vote down vote up
def test_no_overwrite(self):
        d = np.ones(100)
        k = np.ones(3)
        np.correlate(d, k)
        assert_array_equal(d, np.ones(100))
        assert_array_equal(k, np.ones(3)) 
Example 15
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_numeric.py    License: MIT License 5 votes vote down vote up
def test_complex(self):
        x = np.array([1, 2, 3, 4+1j], dtype=np.complex)
        y = np.array([-1, -2j, 3+1j], dtype=np.complex)
        r_z = np.array([3-1j, 6, 8+1j, 11+5j, -5+8j, -4-1j], dtype=np.complex)
        r_z = r_z[::-1].conjugate()
        z = np.correlate(y, x, mode='full')
        assert_array_almost_equal(z, r_z) 
Example 16
Project: vnpy_crypto   Author: birforce   File: test_numeric.py    License: MIT License 5 votes vote down vote up
def test_float(self):
        self._setup(float)
        z = np.correlate(self.x, self.y, 'full')
        assert_array_almost_equal(z, self.z1)
        z = np.correlate(self.x, self.y[:-1], 'full')
        assert_array_almost_equal(z, self.z1_4)
        z = np.correlate(self.y, self.x, 'full')
        assert_array_almost_equal(z, self.z2)
        z = np.correlate(self.x[::-1], self.y, 'full')
        assert_array_almost_equal(z, self.z1r)
        z = np.correlate(self.y, self.x[::-1], 'full')
        assert_array_almost_equal(z, self.z2r)
        z = np.correlate(self.xs, self.y, 'full')
        assert_array_almost_equal(z, self.zs) 
Example 17
Project: vnpy_crypto   Author: birforce   File: test_numeric.py    License: MIT License 5 votes vote down vote up
def test_object(self):
        self._setup(Decimal)
        z = np.correlate(self.x, self.y, 'full')
        assert_array_almost_equal(z, self.z1)
        z = np.correlate(self.y, self.x, 'full')
        assert_array_almost_equal(z, self.z2) 
Example 18
Project: vnpy_crypto   Author: birforce   File: test_numeric.py    License: MIT License 5 votes vote down vote up
def test_no_overwrite(self):
        d = np.ones(100)
        k = np.ones(3)
        np.correlate(d, k)
        assert_array_equal(d, np.ones(100))
        assert_array_equal(k, np.ones(3)) 
Example 19
Project: vnpy_crypto   Author: birforce   File: test_numeric.py    License: MIT License 5 votes vote down vote up
def test_complex(self):
        x = np.array([1, 2, 3, 4+1j], dtype=complex)
        y = np.array([-1, -2j, 3+1j], dtype=complex)
        r_z = np.array([3-1j, 6, 8+1j, 11+5j, -5+8j, -4-1j], dtype=complex)
        r_z = r_z[::-1].conjugate()
        z = np.correlate(y, x, mode='full')
        assert_array_almost_equal(z, r_z) 
Example 20
Project: vnpy_crypto   Author: birforce   File: stattools.py    License: MIT License 5 votes vote down vote up
def ccf(x, y, unbiased=True):
    '''cross-correlation function for 1d

    Parameters
    ----------
    x, y : arrays
       time series data
    unbiased : boolean
       if True, then denominators for autocovariance is n-k, otherwise n

    Returns
    -------
    ccf : array
        cross-correlation function of x and y

    Notes
    -----
    This is based np.correlate which does full convolution. For very long time
    series it is recommended to use fft convolution instead.

    If unbiased is true, the denominator for the autocovariance is adjusted
    but the autocorrelation is not an unbiased estimtor.

    '''
    cvf = ccovf(x, y, unbiased=unbiased, demean=True)
    return cvf / (np.std(x) * np.std(y)) 
Example 21
Project: vnpy_crypto   Author: birforce   File: example_arma.py    License: MIT License 5 votes vote down vote up
def norm_corr(x,y,mode = 'valid'):
    """Returns the correlation between two ndarrays, by calling np.correlate in
'same' mode and normalizing the result by the std of the arrays and by
their lengths. This results in a correlation = 1 for an auto-correlation"""

    return ( np.correlate(x,y,mode) /
             (np.std(x)*np.std(y)*(x.shape[-1])) )



# from matplotlib axes.py
# note: self is axis 
Example 22
Project: dirty_cat   Author: dirty-cat   File: fast_hash.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def ngram_min_hash(string, ngram_range=(2, 4), seed=0, return_minmax=False):
    """ Compute the min/max hash of the ngrams of the string.

    Parameters
    ----------
    string : str
        String to encode.
    ngram_range : tuple (min_n, max_n), default=(2, 4)
        The lower and upper boundary of the range of n-values 
        for different n-grams to be extracted.
    seed : int, default=0
        Integer used to seed the hashing function.
    return_minmax : bool, default=False
        If True, returns both the minhash and maxhash of the string.
        Else, only returns the minhash. 
    Returns
    -------
    int or tuple 
        The min_hash or (min_hash, max_hash) of the n-grams of the string.

    """
    # Create a numerical 1D array from the string
    array = np.frombuffer(string.encode(), dtype='int8', count=len(string))

    max_hash = MININT32
    min_hash = MAXINT32
    for atom_len in range(ngram_range[0], ngram_range[1]):
        atom = gen_atom(atom_len, seed=seed)
        # np.correlate is faster than np.convolve
        # the convolution gives a hash for each ngram
        hashes = np.correlate(array, atom)
        min_hash = min(min_hash, hashes.min())
        if return_minmax:
            max_hash = max(max_hash, hashes.max())

    # We should check that longer windows do not have different
    # statistics from shorter ones
    if return_minmax:
        return min_hash, max_hash
    return min_hash 
Example 23
Project: Computable   Author: ktraunmueller   File: test_numeric.py    License: MIT License 5 votes vote down vote up
def test_float(self):
        self._setup(np.float)
        z = np.correlate(self.x, self.y, 'full', old_behavior=self.old_behavior)
        assert_array_almost_equal(z, self.z1)
        z = np.correlate(self.y, self.x, 'full', old_behavior=self.old_behavior)
        assert_array_almost_equal(z, self.z2) 
Example 24
Project: Computable   Author: ktraunmueller   File: test_numeric.py    License: MIT License 5 votes vote down vote up
def test_object(self):
        self._setup(Decimal)
        z = np.correlate(self.x, self.y, 'full', old_behavior=self.old_behavior)
        assert_array_almost_equal(z, self.z1)
        z = np.correlate(self.y, self.x, 'full', old_behavior=self.old_behavior)
        assert_array_almost_equal(z, self.z2) 
Example 25
Project: Computable   Author: ktraunmueller   File: test_numeric.py    License: MIT License 5 votes vote down vote up
def _setup(self, dt):
        # correlate uses an unconventional definition so that correlate(a, b)
        # == correlate(b, a), so force the corresponding outputs to be the same
        # as well
        _TestCorrelate._setup(self, dt)
        self.z2 = self.z1 
Example 26
Project: Computable   Author: ktraunmueller   File: test_numeric.py    License: MIT License 5 votes vote down vote up
def test_complex(self):
        x = np.array([1, 2, 3, 4+1j], dtype=np.complex)
        y = np.array([-1, -2j, 3+1j], dtype=np.complex)
        r_z = np.array([3+1j, 6, 8-1j, 9+1j, -1-8j, -4-1j], dtype=np.complex)
        z = np.correlate(x, y, 'full', old_behavior=self.old_behavior)
        assert_array_almost_equal(z, r_z) 
Example 27
Project: Computable   Author: ktraunmueller   File: test_numeric.py    License: MIT License 5 votes vote down vote up
def test_complex(self):
        x = np.array([1, 2, 3, 4+1j], dtype=np.complex)
        y = np.array([-1, -2j, 3+1j], dtype=np.complex)
        r_z = np.array([3-1j, 6, 8+1j, 11+5j, -5+8j, -4-1j], dtype=np.complex)
        #z = np.acorrelate(x, y, 'full')
        #assert_array_almost_equal(z, r_z)

        r_z = r_z[::-1].conjugate()
        z = np.correlate(y, x, 'full', old_behavior=self.old_behavior)
        assert_array_almost_equal(z, r_z) 
Example 28
Project: Computable   Author: ktraunmueller   File: test_signaltools.py    License: MIT License 5 votes vote down vote up
def test_rank1_same(self):
        a, b, y_r = self._setup_rank1()
        y = correlate(a, b, 'same')
        assert_array_almost_equal(y, y_r[:-1])
        self.assertTrue(y.dtype == self.dt) 
Example 29
Project: Computable   Author: ktraunmueller   File: test_signaltools.py    License: MIT License 5 votes vote down vote up
def test_rank1_full(self):
        a, b, y_r = self._setup_rank1()
        y = correlate(a, b, 'full')
        assert_array_almost_equal(y, y_r)
        self.assertTrue(y.dtype == self.dt) 
Example 30
Project: Computable   Author: ktraunmueller   File: test_signaltools.py    License: MIT License 5 votes vote down vote up
def test_rank3_valid(self):
        a, b, y_r = self._setup_rank3()
        y = correlate(a, b, "valid")
        assert_array_almost_equal(y, y_r[1:2,2:4,3:5])
        self.assertTrue(y.dtype == self.dt)