U
    Ãmœdé  ã                   @   sT   d Z ddlZddlmZ ddlmZ ddd„Zdd	„ Zd
d„ Z	dd„ Z
ddd„ZdS )a	  
BDS test for IID time series

References
----------

Broock, W. A., J. A. Scheinkman, W. D. Dechert, and B. LeBaron. 1996.
"A Test for Independence Based on the Correlation Dimension."
Econometric Reviews 15 (3): 197-235.

Kanzler, Ludwig. 1999.
"Very Fast and Correctly Sized Estimation of the BDS Statistic".
SSRN Scholarly Paper ID 151669. Rochester, NY: Social Science Research Network.

LeBaron, Blake. 1997.
"A Fast Algorithm for the BDS Statistic."
Studies in Nonlinear Dynamics & Econometrics 2 (2) (January 1).
é    N)Ústats)Ú
array_likeç      ø?c                 C   sp   t | dƒ} |dk	r&|dkr&td| ƒ‚|dkr:td| ƒ‚|dkrR|| jdd� }t | dd…df |  ¡|k S )a•  
    Calculate all pairwise threshold distance indicators for a time series

    Parameters
    ----------
    x : 1d array
        observations of time series for which heaviside distance indicators
        are calculated
    epsilon : scalar, optional
        the threshold distance to use in calculating the heaviside indicators
    distance : scalar, optional
        if epsilon is omitted, specifies the distance multiplier to use when
        computing it

    Returns
    -------
    indicators : 2d array
        matrix of distance threshold indicators

    Notes
    -----
    Since this can be a very large matrix, use np.int8 to save some space.
    ÚxNr   zCThreshold distance must be positive if specified. Got epsilon of %fz?Threshold distance must be positive. Got distance multiplier %fé   )Zddof)r   Ú
ValueErrorZstdÚnpÚabs)r   ÚepsilonÚdistance© r   úM/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/statsmodels/tsa/_bds.pyÚdistance_indicators   s    
ÿÿr   c                 C   sœ   | j dkstdƒ‚| jd | jd ks.tdƒ‚|dkr<| }n:t| |d ƒ\}} | dd…dd…f | dd…dd…f  }t|ƒ}t |t |d¡ ¡}||fS )a‰  
    Calculate a correlation sum

    Useful as an estimator of a correlation integral

    Parameters
    ----------
    indicators : ndarray
        2d array of distance threshold indicators
    embedding_dim : int
        embedding dimension

    Returns
    -------
    corrsum : float
        Correlation sum
    indicators_joint
        matrix of joint-distance-threshold indicators
    é   zIndicators must be a matrixr   r   z+Indicator matrix must be symmetric (square)Néÿÿÿÿ)Úndimr   ÚshapeÚcorrelation_sumÚlenr   ZmeanZtriu_indices)Ú
indicatorsÚembedding_dimZindicators_jointZcorrsumÚnobsr   r   r   r   D   s    
(r   c                 C   sJ   t  d|f¡}t| dƒ\|d< } td|ƒD ]}t| dƒ\|d|f< } q*|S )a3  
    Calculate all correlation sums for embedding dimensions 1:max_dim

    Parameters
    ----------
    indicators : 2d array
        matrix of distance threshold indicators
    max_dim : int
        maximum embedding dimension

    Returns
    -------
    corrsums : ndarray
        Correlation sums
    r   )r   r   r   r   )r   Úzerosr   Úrange)r   Úmax_dimZcorrsumsÚir   r   r   Úcorrelation_sumsh   s
    r   c           
      C   s  t | ƒ}t| dƒ\}}|  d¡d  ¡ d|  ¡   d|  ||d  |d   }t d|d f¡}td|d ƒD ]ˆ}d}td|ƒD ] }	||||	  |d|	   7 }q‚d|| d|  |d d |d|    |d | |d| d     |d|d f< qp||fS )a  
    Calculate the variance of a BDS effect

    Parameters
    ----------
    indicators : ndarray
        2d array of distance threshold indicators
    max_dim : int
        maximum embedding dimension

    Returns
    -------
    variances : float
        Variance of BDS effect
    r   r   é   r   é   )r   r   Úsumr   r   r   )
r   r   r   Úcorrsum_1dimÚ_ÚkÚ	variancesr   ÚtmpÚjr   r   r   Ú_var‚   s,    ÿÿÿþýÿr&   r   c              
   C   sV  t | ddd�} t| ƒ}|dk s&||kr2td| ƒ‚t| ||ƒ}t||ƒ}t||ƒ\}}t |¡}	t d|d f¡}
t d|d f¡}t	d|d ƒD ]®}|d }|| }t
||d…|d…f dƒ\}}|d|d f }|||  }|	d|d f }t |¡| | |
d|d f< dtj t |
d|d f ¡¡ }||d|d f< q’t |
¡t |¡fS )a”  
    BDS Test Statistic for Independence of a Time Series

    Parameters
    ----------
    x : ndarray
        Observations of time series for which bds statistics is calculated.
    max_dim : int
        The maximum embedding dimension.
    epsilon : {float, None}, optional
        The threshold distance to use in calculating the correlation sum.
    distance : float, optional
        Specifies the distance multiplier to use when computing the test
        statistic if epsilon is omitted.

    Returns
    -------
    bds_stat : float
        The BDS statistic.
    pvalue : float
        The p-values associated with the BDS statistic.

    Notes
    -----
    The null hypothesis of the test statistic is for an independent and
    identically distributed (i.i.d.) time series, and an unspecified
    alternative hypothesis.

    This test is often used as a residual diagnostic.

    The calculation involves matrices of size (nobs, nobs), so this test
    will not work with very long datasets.

    Implementation conditions on the first m-1 initial values, which are
    required to calculate the m-histories:
    x_t^m = (x_t, x_{t-1}, ... x_{t-(m-1)})
    r   r   )r   r   zFMaximum embedding dimension must be in the range [2,len(x)-1]. Got %d.Nr   )r   r   r   r   r   r&   r   Úsqrtr   r   r   r   ZnormZsfr	   Zsqueeze)r   r   r
   r   Z	nobs_fullr   Zcorrsum_mdimsr#   r"   ZstddevsZ	bds_statsZpvaluesr   Zninitialr   r    r!   Zcorrsum_mdimZeffectÚsdZpvaluer   r   r   Úbds¦   s.    &ÿ

"r)   )Nr   )r   Nr   )Ú__doc__Únumpyr   Zscipyr   Zstatsmodels.tools.validationr   r   r   r   r&   r)   r   r   r   r   Ú<module>   s   
*$$