U
    Kvf,                  	   @   s  d Z ddlZddlmZ ddlmZ ddlm	Z	 ddl
mZmZ ddl
mZmZ ddlmZ ddlmZmZ dd	lmZ d
dgZd
dgZdZeeedZeedd ZeeeZdDddZdEddZdd Zdd Zdd Z dd Z!dd Z"dd Z#d d! Z$d
d"gZ%d
d#gZ&d
dgZ'd
dd$gZ(d
d#gZ)e*d%e$fd&e#fd'e"fd(e"fgZ+d%e&e'ffd&e&e(ffd'e%e'ffd(e%e)ffgZ,e,D ]\Z-Z.e.\ZZe/d e/e-ee eeedd)Z0eeedd*Z1e-dd+ d,kre+e- eZ2ne+e- eeZ2e/e0dd-  e/e2dd-  ee0e2d ee1e2e2d  d qxdFd/d0Z3dGd2d3Z4dHd5d6Z5d7d8 Z6d9ed9dfd:d;Z7e3 Z8ee8d Z9e9:d<Z;e/e;d  ee8d Z<ee8d d=d>Z=e4e8d Z>e4e8d e8d ?  Z@e/e<dd  e/e=dd  e/e>dd  e/e@dd  ed
d"gd
gd?Ze/eedd@  e/e	Aed eBe eC  e7eee eC  e7eeed=dA eC  eee<dd@ eDeEe<dd@ d9dA eC  eFdBZGeeGe<dd@ d9dA eFdCZGeeGe<dd@ eDeEe<dd@ d=dA dS )Iztrying to verify theoretical acf of arma

explicit functions for autocovariance functions of ARIMA(1,1), MA(1), MA(2)
plus 3 functions from nitime.utils

    N)assert_array_almost_equal)
regression)arma_generate_samplearma_impulse_response)
arma_acovfarma_acf)ARIMA)acfacovf)plot_acf      ?g333333g? i  
   c                 C   s,   |d ks|dkrt | S |dkr(t| S d S )NZconstantZlinear)detrend_meandetrend_linear)xkey r   H/tmp/pip-unpacked-wheel-2v6byqio/statsmodels/sandbox/tsa/example_arma.pydetrend%   s    r   c                 C   sH   t | } |r:tdg| }|t j | | ||  S | | | S )z0Return x minus its mean along the specified axisN)npasarraysliceappendZnewaxismean)r   axisindr   r   r   demean+   s    
r   c                 C   s   | |    S )zReturn x minus the mean(x))r   r   r   r   r   r   4   s    r   c                 C   s   | S )zReturn x: no detrendingr   r   r   r   r   detrend_none8   s    r   c                 C   sX   t jt| t jd}t j|| dd}|d |d  }|  ||   }| || |  S )z2Return y minus best fit line; 'linear' detrending )Zdtype   )Zbias)r   r    )r   r   )r   arangelenZfloat_Zcovr   )yr   Cbar   r   r   r   <   s
    r   c                    s&   t | |  fddtdD }|S )z6add correlation of MA representation explicitely

    c                    s,   g | ]$}t  d |   | qS )N)r   dot).0tZirnobsr   r   
<listcomp>J   s     z"acovf_explicit.<locals>.<listcomp>r   )r   range)armar+   Z	acovfexplr   r*   r   acovf_explicitE   s    
r0   c                 C   s   | d  }|d }d|d  d| |  d|d   g}| d||  ||  d|d    tdD ]}|d }| ||  qft|S )Nr    r         )r   r-   r   array)r.   r/   r&   r%   rho_lastr   r   r   acovf_arma11M   s    
&&r8   c                 C   sV   | d  }| d  }t d}d|d  |d  |d< | ||  |d< | |d< |S )Nr    r1   r   r   r   zeros)r/   Zb1Zb2r5   r   r   r   	acovf_ma2`   s    



r;   c                 C   s2   | d  }t d}d|d  |d< | |d< |S )Nr    r   r1   r   r9   )r/   r%   r5   r   r   r   	acovf_ma1o   s
    


r<   gg        g333333?ma1ma2Zarma11ar1)r+   )lagsr1   r/         c                 C   s   t ddddg}t jj| |d d}t | }t|}t|D ]6}|| t |d | d d d |d |  ||< q@t|| D ]2}|| t ||| | d d d | ||< q|||fS )Ng@gQ|g|?5^:@g oŏg      ?)sizeZscaler3   )r   r4   randomnormalr:   r"   r-   r'   )NsigmaZtapsvuPlr   r   r   ar_generator   s    
40rL   r3   c                 C   sN   | j | }tjj| d| d |d}tjj||  |djd| }|| S )zReturns the autocorrelation of signal s at all lags. Adheres to the
definition r(k) = E{s(n)s*(n-k)} where E{} is the expectation operator.
r1   r    )nr   )r   N)shaper   ZfftZifft	conjugatereal)sr   rF   SZsxxr   r   r   autocorr   s    
"rS   validc                 C   s,   t | ||t | t | | jd   S )zReturns 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-correlationr3   )r   	correlateZstdrN   )r   r#   moder   r   r   	norm_corr   s    rW   c                 K   s   | j ||f|S )a9  
    call signature::

        acorr(x, normed=True, detrend=detrend_none, usevlines=True,
              maxlags=10, **kwargs)

    Plot the autocorrelation of *x*.  If *normed* = *True*,
    normalize the data by the autocorrelation at 0-th lag.  *x* is
    detrended by the *detrend* callable (default no normalization).

    Data are plotted as ``plot(lags, c, **kwargs)``

    Return value is a tuple (*lags*, *c*, *line*) where:

      - *lags* are a length 2*maxlags+1 lag vector

      - *c* is the 2*maxlags+1 auto correlation vector

      - *line* is a :class:`~matplotlib.lines.Line2D` instance
        returned by :meth:`plot`

    The default *linestyle* is None and the default *marker* is
    ``'o'``, though these can be overridden with keyword args.
    The cross correlation is performed with
    :func:`numpy.correlate` with *mode* = 2.

    If *usevlines* is *True*, :meth:`~matplotlib.axes.Axes.vlines`
    rather than :meth:`~matplotlib.axes.Axes.plot` is used to draw
    vertical lines from the origin to the acorr.  Otherwise, the
    plot style is determined by the kwargs, which are
    :class:`~matplotlib.lines.Line2D` properties.

    *maxlags* is a positive integer detailing the number of lags
    to show.  The default value of *None* will return all
    :math:`2 \mathrm{len}(x) - 1` lags.

    The return value is a tuple (*lags*, *c*, *linecol*, *b*)
    where

    - *linecol* is the
      :class:`~matplotlib.collections.LineCollection`

    - *b* is the *x*-axis.

    .. seealso::

        :meth:`~matplotlib.axes.Axes.plot` or
        :meth:`~matplotlib.axes.Axes.vlines`
           For documentation on valid kwargs.

    **Example:**

    :func:`~matplotlib.pyplot.xcorr` above, and
    :func:`~matplotlib.pyplot.acorr` below.

    **Example:**

    .. plot:: mpl_examples/pylab_examples/xcorr_demo.py
    )Zxcorr)selfr   kwargsr   r   r   pltacorr   s    <rZ   Tc                 K   sN  t |}|t |krtd|t|}|t|}tj||dd}	|rn|	tt||t||  }	|dkr~|d }||ks|dk rtd| t| |d }
|	|d | ||  }	|r| j|
dg|	f|}| j	f |}|
dd	 |
d
d | j|
|	f|}n.|
dd	 |
d
d | j|
|	f|\}d}|
|	||fS )a  
    call signature::

        def xcorr(self, x, y, normed=True, detrend=detrend_none,
          usevlines=True, maxlags=10, **kwargs):

    Plot the cross correlation between *x* and *y*.  If *normed* =
    *True*, normalize the data by the cross correlation at 0-th
    lag.  *x* and y are detrended by the *detrend* callable
    (default no normalization).  *x* and *y* must be equal length.

    Data are plotted as ``plot(lags, c, **kwargs)``

    Return value is a tuple (*lags*, *c*, *line*) where:

      - *lags* are a length ``2*maxlags+1`` lag vector

      - *c* is the ``2*maxlags+1`` auto correlation vector

      - *line* is a :class:`~matplotlib.lines.Line2D` instance
         returned by :func:`~matplotlib.pyplot.plot`.

    The default *linestyle* is *None* and the default *marker* is
    'o', though these can be overridden with keyword args.  The
    cross correlation is performed with :func:`numpy.correlate`
    with *mode* = 2.

    If *usevlines* is *True*:

       :func:`~matplotlib.pyplot.vlines`
       rather than :func:`~matplotlib.pyplot.plot` is used to draw
       vertical lines from the origin to the xcorr.  Otherwise the
       plotstyle is determined by the kwargs, which are
       :class:`~matplotlib.lines.Line2D` properties.

       The return value is a tuple (*lags*, *c*, *linecol*, *b*)
       where *linecol* is the
       :class:`matplotlib.collections.LineCollection` instance and
       *b* is the *x*-axis.

    *maxlags* is a positive integer detailing the number of lags to show.
    The default value of *None* will return all ``(2*len(x)-1)`` lags.

    **Example:**

    :func:`~matplotlib.pyplot.xcorr` above, and
    :func:`~matplotlib.pyplot.acorr` below.

    **Example:**

    .. plot:: mpl_examples/pylab_examples/xcorr_demo.py
    zx and y must be equal lengthr1   )rV   Nr    z.maxlags must be None or strictly positive < %dr   markeroZ	linestyleNone)r"   
ValueErrorr   r   rU   sqrtr'   r!   ZvlinesZaxhline
setdefaultplot)rX   r   r#   normedr   	usevlinesZmaxlagsrY   ZNxcr@   r&   r%   dr   r   r   pltxcorr  s6    8"rf   )   r   r   F)Zunbiasedi     )rc         )N)r   )rB   r   )r3   )rT   )H__doc__Znumpyr   Znumpy.testingr   Zmatplotlib.pyplotZpyplotZpltZstatsmodelsr   Zstatsmodels.tsa.arima_processr   r   r   r   Zstatsmodels.tsa.arima.modelr   Zstatsmodels.tsa.stattoolsr	   r
   Zstatsmodels.graphics.tsaplotsr   r.   r/   modr   Zx_acfZx_irr   r   r   r   r   r0   r8   r;   r<   r?   Zar0r=   r>   Zma0dictZ	comparefnZcasesrd   argsprintZmyacovfZmyacfZothacovfrL   rS   rW   rZ   rf   ZarrvsZarmaZfitresZacf1Zacovf1bZacf2r   Zacf2mZyule_walkerra   figurer!   r"   ZsubplotZaxr   r   r   r   <module>   s   


		







> 
b

*

