
    M/Ph,                        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d6dZd7dZd Zd Zd Z d Z!d Z"d Z#d Z$d
dgZ%d
dgZ&d
dgZ'g d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           Z0 eeed!          Z1e-dd"         d#k    r e+e-         e          Z2n e+e-         ee          Z2 e/e0dd$                     e/e2dd$                     ee0e2d            ee1e2e2d         z  d           d8d&Z3d9d(Z4d:d*Z5d+ Z6d,ed,dfd-Z7 e3            Z8 ee8d                   Z9e9:                    d.          Z; e/e;d                     ee8d                   Z< ee8d         d/0          Z= e4e8d                   Z> e4e8d         e8d         ?                                z
            Z@ e/e<dd                     e/e=dd                     e/e>dd                     e/e@dd                     ed
dgd
gd1          Z e/ ee          dd2                     e/ e	jA        ed                      ejB        e            ejC                      e7eee            ejC                      e7eeed/3            ejC                      eee<dd2          ejD         eEe<dd2                             d,3            ejC                      ejF        d4          ZG eeGe<dd2         d,3            ejF        d5          ZG eeGe<dd2          ejD         eEe<dd2                             d/3           dS );ztrying 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皙? i  
   c                 ^    ||dk    rt          |           S |dk    rt          |           S d S )Nconstantlinear)detrend_meandetrend_linear)xkeys     d/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/sandbox/tsa/example_arma.pydetrendr   %   s9    
{c:ooA	ha    
    c                     t          j        |           } |rPt          d          g|z  }|                    t           j                   | |                     |          |         z
  S | |                     |          z
  S )z0Return x minus its mean along the specified axisN)npasarraysliceappendnewaxismean)r   axisinds      r   demeanr$   +   sl    

1A %T{{md"

2:166$<<$$$qvvd||r   c                 0    | |                                  z
  S )zReturn x minus the mean(x))r!   r   s    r   r   r   4   s    qvvxx<r   c                     | S )zReturn x: no detrending r&   s    r   detrend_noner)   8   s    Hr   c                    t          j        t          |           t           j                  }t          j        || d          }|d         |d         z  }|                                 ||                                z  z
  }| ||z  |z   z
  S )z2Return y minus best fit line; 'linear' detrending )dtype   )bias)r   r,   )r   r   )r   arangelenfloat_covr!   )yr   Cbas        r   r   r   <   sw     		#a&&	***A
q!!A	#qvA	1QVVXX:A!a=r   c                 b    t          | |          fdt          d          D             }|S )z6add correlation of MA representation explicitely

    c                 `    g | ]*}t          j        d |z
           |                   +S N)r   dot).0tirnobss     r   
<listcomp>z"acovf_explicit.<locals>.<listcomp>J   s9    DDDQ7DF7R$Z00DDDr   r   )r   range)armar=   	acovfexplr<   s     ` @r   acovf_explicitrC   E   s=     
r2	&	&BDDDDD%))DDDIr   c                 :   | d          }|d         }d|dz  z   d|z  |z  z   d|dz  z
  z  g}|                     d||z  z   ||z   z  d|dz  z
  z             t          d          D ]"}|d         }|                     ||z             #t          j        |          S )Nr,   r         )r   r?   r   array)r@   rA   r5   r4   rho_lasts          r   acovf_arma11rL   M   s    
 
AA
1A q!tGAaCEMBq!tG$
%CJJ!A#!}bAg&'''1XX  2w

1T68C==r   c                     | d          }| d          }t          j        d          }d|dz  z   |dz  z   |d<   | ||z  z   |d<   | |d<   |S )Nr,   rE   r   r   r   zeros)rA   b1b2rI   s       r   	acovf_ma2rR   `   sd     Q%B
Q%B
(2,,C"a%i"a%CFcBrEkCFSCFJr   c                 b    | d          }t          j        d          }d|dz  z   |d<   | |d<   |S )Nr,   r   rE   r   rN   )rA   r4   rI   s      r   	acovf_ma1rT   o   s=     
AA
(2,,C!Q$hCFRCFJr   gg        )r   r   g333333?ma1ma2arma11ar1)r=   )lagsrE   rA         c                    t          j        g d          }t           j                            | |dz            }t          j        |           }t          |          }t          |          D ]<}||         t          j        |d |         d d d         |d |                   z   ||<   =t          ||           D ]7}||         t          j        |||z
  |         d d d         |          z   ||<   8|||fS )N)g@gQ|g|?5^:@g oŏg      ?)sizescalerG   )r   rH   randomnormalrO   r/   r?   r9   )NsigmatapsvuPls          r   ar_generatorrh      s    
 866677D
	aucz22A
AD		A1XX 4 4tbfQrrU44R4[$rr(333!1QZZ 3 3tbfQqs1uXddd^T222!a:r   rG   c                     | j         |         }t          j                            | d|z  dz
  |          }t          j                            ||                                z  |          j        d|         }||z  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.
rE   r,   )nr"   )r"   N)shaper   fftifft	conjugatereal)sr"   ra   Ssxxs        r   autocorrrs      sh     	
A


1!AD
))A
&++aoD+
1
1
6rr
:Cq5Lr   validc                     t          j        | ||          t          j        |           t          j        |          z  | j        d         z  z  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-correlationrG   )r   	correlatestdrk   )r   r2   modes      r   	norm_corrry      sB    
 \!Ad##fQiiq		!172;/1 3r   c                       | j         ||fi |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
    )xcorr)selfr   kwargss      r   pltacorrr~      s!    x 4:a%%f%%%r   Tc                 n   t          |          }|t          |          k    rt          d           |t          j        |                    } |t          j        |                    }t          j        ||d          }	|r@|	t          j        t          j        ||          t          j        ||          z            z  }	||dz
  }||k    s|dk     rt          d|z            t          j        | |dz             }
|	|dz
  |z
  ||z            }	|rZ | j        |
dg|	fi |} | j	        di |}|
                    dd	           |
                    d
d            | j        |
|	fi |}n?|
                    dd	           |
                    d
d            | j        |
|	fi |\  }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 lengthrE   )rx   Nr,   z.maxlags must be None or strictly positive < %dr   markero	linestyleNoner(   )r/   
ValueErrorr   r   rv   sqrtr9   r.   vlinesaxhline
setdefaultplot)r|   r   r2   normedr   	usevlinesmaxlagsr}   NxcrY   r5   r4   ds                 r   pltxcorrr     s    p 
QB	3q66zz7888
1A
1A
Q"""A 2	RWRVAq\\BF1aLL0111q&"}}! )+-. / / 	/ 9gXgai((D	"Q$w,r'z
!"A  DKqc1////DL""6""(C(((+v...DIdA(((( 	(C(((+v...TYtQ))&))Aq=r   )   r   r   F)unbiasedi     )r         r8   )r   )r[   r   )rG   )rt   )H__doc__numpyr   numpy.testingr   matplotlib.pyplotpyplotpltstatsmodelsr   statsmodels.tsa.arima_processr   r   r   r   statsmodels.tsa.arima.modelr	   statsmodels.tsa.stattoolsr
   r   statsmodels.graphics.tsaplotsr   r@   rA   modr   x_acfx_irr   r$   r   r)   r   rC   rL   rR   rT   rX   ar0rU   rV   ma0dict	comparefncasesr   argsprintmyacovfmyacfothacovfrh   rs   ry   r~   r   arrvsarmafitresacf1acovf1bacf2r!   acf2myule_walkerr   figurer.   r/   subplotaxr(   r   r   <module>r      sT        3 3 3 3 3 3       " " " " " " U U U U U U U U > > > > > > > > - - - - - - 0 0 0 0 0 0 0 0 2 2 2 2 2 2$Z#Y 	R&&AssR$$! ! ! !             &	 	 	   
4j	2h	3inn	2hD
				< 		   	 #s		c
	C:	c
	
  > >GAtFB	E"III	E!RjRb)))GHR"%%%E!ud{{9Q<##9Q<B''	E'"1"+	E(2A2, gx333eXhqk%9"====   &   3 3 3 3<& <& <&| !%l"[ [ [ [D 	 uU1X
hhx c!f
s58}}
%a5
)
)
)xaq%(--//)** d3B3i    gcrcl    d3B3i    eCRCj    #tseS11 cc!ffSbSk    jQ## $ $ $ 	 
 Qq    

 QqE " " " " 

 d3B3i33tCRCy>>22d C C C C 

S[ T#2#Y$ ' ' ' 'S[ T#2#Y		##d3B3i..11U C C C C C Cr   