Example #1
0
    def setUp(self):
        m, n = randint(20, 101), randint(4, 5)
        ms = randint(2, 11)
        fs = int(2 ** nextpow2(randint(1, m / ms)))

        self.x = rand(m, n)
        self.window = int(np.floor(ms / 1e3 * fs))

        if not self.window:
            self.window += 1
Example #2
0
def test_get_fft_funcs():
    m, n = [int(2 ** nextpow2(randint(5, 10))) for _ in xrange(2)]
    x = randn(m, n)
    xc = x + 1j

    ifft, fft = get_fft_funcs(xc, xc)
    assert fft is np.fft.fft, 'fft is not np.fft.fft'
    assert ifft is np.fft.ifft, 'ifft is not np.fft.ifft'
    ravelxc = xc.ravel()
    assert_allclose(ifft(fft(ravelxc)), ravelxc)

    ifft, fft = get_fft_funcs(x, x)
    assert fft is np.fft.rfft
    assert ifft is np.fft.irfft
    ravelx = x.ravel()
    assert_allclose(ifft(fft(ravelx)), ravelx)
Example #3
0
def test_mult_mat_xcorr():
    x = randn(randint(2, 4), randint(4, 5))
    m, n = x.shape
    ifft, fft = get_fft_funcs(x)
    nfft = int(2 ** nextpow2(m))
    X = fft(x.T, nfft)
    Xc = X.conj()
    mx, nx = X.shape

    c = np.empty((mx ** 2, nx), dtype=X.dtype)
    oc = c.copy()

    mult_mat_xcorr(X, Xc, oc, n, nx)

    for i in xrange(n):
        c[i * n:(i + 1) * n] = X[i] * Xc

    assert_allclose(c, oc)

    cc, occ = map(lambda x: ifft(x, nfft).T, (c, oc))

    assert_allclose(cc, occ)
Example #4
0
def xcorr(x, y=None, maxlags=None, detrend=detrend_mean,
          scale_type='normalize'):
    """Compute the cross correlation of `x` and `y`.

    This function computes the cross correlation of `x` and `y`. It uses the
    equivalence of the cross correlation with the negative convolution computed
    using a FFT to achieve must faster cross correlation than is possible with
    the signal processing definition.

    By default it computes the normalized cross correlation.

    Parameters
    ----------
    x : array_like
        The array to correlate.

    y : array_like, optional
        If y is None or equal to `x` or x and y reference the same object,
        the autocorrelation is computed.

    maxlags : int, optional
        The maximum lag at which to compute the cross correlation. Must be less
        than or equal to the max(x.size, y.size) if not None.

    detrend : callable, optional
        A callable to detrend the data. It must take a single parameter and
        return an array

    scale_type : {None, 'none', 'unbiased', 'biased', 'normalize'}, optional
        * The type of scaling to perform on the data
        * The default of 'normalize' returns the cross correlation scaled by
          the lag 0 cross correlation i.e., the cross correlation scaled by the
          product of the standard deviations of the arrays at lag 0.

    Raises
    ------
    AssertionError
        * If `y` is not None and `x` is a matrix
        * If `x` is not a vector when `y` is None or `y` is `x` or
          ``all(x == y)``.
        * If `detrend` is not callable
        * If `scale_type` is not a string or ``None``
        * If `scale_type` is not in ``(None, 'none', 'unbiased', 'biased',
          'normalize')``
        * If `maxlags` ``>`` `lsize`, see source for details.

    Returns
    -------
    c : Series or DataFrame or array_like
        Autocorrelation of `x` if `y` is ``None``, cross-correlation of `x` if
        `x` is a matrix and `y` is ``None``, or the cross-correlation of `x`
        and `y` if both `x` and `y` are vectors.
    """
    assert x.ndim in (1, 2), 'x must be a 1D or 2D array'
    assert callable(detrend), 'detrend must be a callable object'
    assert isinstance(scale_type, basestring) or scale_type is None, \
        '"scale_type" must be a string or None'
    assert scale_type in _SCALE_KEYS, ('"scale_type" must be one of '
                                       '{0}'.format(_SCALE_KEYS))

    x = detrend(x)

    if x.ndim == 2 and np.greater(x.shape, 1).all():
        assert y is None, 'y argument not allowed when x is a 2D array'
        lsize = x.shape[0]
        inputs = x,
        corrfunc = matrixcorr
    elif y is None or y is x or np.array_equal(x, y):
        assert isvector(x), 'x must be 1D'
        lsize = max(x.shape)
        inputs = x,
        corrfunc = autocorr
    else:
        x, y, lsize = pad_larger(x, detrend(y))
        inputs = x, y
        corrfunc = crosscorr

    nfft = 2 ** nextpow2(2 * lsize - 1)
    ctmp = corrfunc(*inputs, nfft=nfft)

    if maxlags is None:
        maxlags = lsize

    assert maxlags <= lsize, ('max lags must be less than or equal to %i'
                              % lsize)

    lags = np.r_[1 - maxlags:maxlags]

    if isinstance(x, Series):
        return_type = lambda x, index: Series(x, index=index)
    elif isinstance(x, DataFrame):
        return_type = lambda x, index: DataFrame(x, index=index)
    elif isinstance(x, np.ndarray):
        return_type = lambda x, index: np.asanyarray(x)

    sc_func = _SCALE_FUNCTIONS[scale_type]
    return sc_func(return_type(ctmp[lags], index=lags), x, y, lags, lsize)