U
    ÃmœdÝ,  ã                	   @   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�rØe+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 )Izštrying 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ç      ð?g333333ã¿gš™™™™™Ù?Ú 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   ú]/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/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/   Úb1Ú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>   gš™™™™™é¿g        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      à?)ÚsizeÚscaler3   )r   r4   ÚrandomÚnormalr:   r"   r-   r'   )ÚNÚsigmaZtapsÚvÚuÚPÚlr   r   r   Úar_generator£   s    
40rO   r3   c                 C   sN   | j | }tjj| d| d |d�}tjj|| ¡  |d�jd|… }|| S )zŒReturns 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   rI   ÚSZsxxr   r   r   Úautocorr¶   s    
"rV   Úvalidc                 C   s,   t  | ||¡t  | ¡t  |¡ | jd   S )zØ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-correlationr3   )r   Ú	correlateZstdrQ   )r   r#   Úmoder   r   r   Ú	norm_corrÄ   s    ÿrZ   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    <r]   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 ršt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   )rY   Nr    z.maxlags must be None or strictly positive < %dr   ÚmarkerÚoZ	linestyleÚNone)r"   Ú
ValueErrorr   r   rX   Úsqrtr'   r!   ZvlinesZaxhlineÚ
setdefaultÚplot)r[   r   r#   Únormedr   Ú	usevlinesZmaxlagsr\   ZNxÚcrB   r&   r%   Údr   r   r   Úpltxcorr  s6    8"ÿri   )é   r   r   F)Zunbiasediô  é   )rf   éÓ   éÔ   )N)r   )rD   r   )r3   )rW   )HÚ__doc__Ú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>   rA   Zar0r?   r@   Zma0ÚdictZ	comparefnZcasesrg   ÚargsÚprintZmyacovfZmyacfZothacovfrO   rV   rZ   r]   ri   ZarrvsZarmaÚfitÚresZacf1Zacovf1bZacf2r   Zacf2mZyule_walkerrd   Zfigurer!   r"   ZsubplotZaxr   r   r   r   Ú<module>   s²   


		
ýÿ



ý


> ÿ
b

*

