
    !g                     J    d Z ddlZddlmZ ddlmZ d
dZd Zd Z	d Z
dd	Zy)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_likec                     t        | d      } ||dk  rt        d|z        |dk  rt        d|z        ||| j                  d      z  }t        j                  | dddf   | z
        |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   )ddof)r   
ValueErrorstdnpabs)r   epsilondistances      Q/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/statsmodels/tsa/_bds.pydistance_indicatorsr      s    0 	1cAw!| .078 9 	91} 79AB C 	C QUUU]*66!AtG*q.!G++    c                 b   | j                   dk(  st        d      | j                  d   | j                  d   k(  st        d      |dk(  r| }n)t        | |dz
        \  }} | ddddf   | ddddf   z  }t	        |      }t        j                  |t        j                  |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   meantriu_indices)
indicatorsembedding_dimindicators_jointcorrsumnobss        r   r   r   D   s    ( ??a677A*"2"21"55FGG%-j-!:KL%ab!"f-j"crc.BB Dgg&rtQ'?@AG$$$r   c                     t        j                  d|f      }t        | d      \  |d<   } t        d|      D ]  }t        | d      \  |d|f<   }  |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_dimcorrsumsis       r   correlation_sumsr&   h   sc    " xxG%H!0Q!?HTNJ1g D%4Z%C"A
D Or   c                    t        |       }t        | d      \  }}| j                  d      dz  j                         d| j                         z  z
  d|z  z   ||dz
  z  |dz
  z  z  }t        j                  d|dz
  f      }t        d|dz         D ]f  }d}t        d|      D ]  }	||||	z
  z  |d|	z  z  z  z  } d||z  d|z  z   |dz
  dz  |d|z  z  z  z   |dz  |z  |d|z  dz
  z  z  z
  z  |d|dz
  f<   h ||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js
             r   _varr1      sh     z?D%j!4OL!
..
Q
	#	#	%*..*:(:	:	
4
D1H%2	4A !Wq[)*Iq'A+. Nq-( 	DAA)*\AE-BCCC	D()}Ga!#q=7H(IJK A"lQ5F5J&KLM)N	!]1_$%	N a<r   c           
         t        | dd      } t        |       }|dk  s||k\  rt        d|z        t        | ||      }t	        ||      }t        ||      \  }}t        j                  |      }	t        j                  d|dz
  f      }
t        j                  d|dz
  f      }t        d|dz         D ]  }|dz
  }||z
  }t        ||d|df   d      \  }}|d|dz
  f   }|||z  z
  }|	d|dz
  f   }t        j                  |      |z  |z  |
d|dz
  f<   dt        j                  j                  t        j                  |
d|dz
  f               z  }||d|dz
  f<    t        j                  |
      t        j                  |      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&   r1   r   sqrtr!   r"   r   r   normsfr   squeeze)r   r#   r   r   	nobs_fullr   corrsum_mdimsr.   r-   stddevs	bds_statspvaluesr   ninitialr   r+   r,   corrsum_mdimeffectsdpvalues                        r   bdsrA      s   L 	1c"AAI{g* 24;< = 	= %Q:J %Z9M 
G,LIqggi G!Wq[)*Ihh7Q;'(Gq'!), /!A%8# **XY	5I*JANa$Q(9%9: }!<=Q))* +-''$-&*@2*E	!]Q&&' 5::==	!]Q5F2F(G!HII(.=1$$%%/( ::i "**W"555r   )N      ?)r   NrB   )__doc__numpyr   scipyr   statsmodels.tools.validationr   r   r   r&   r1   rA    r   r   <module>rH      s2   &   3',T!%H4!HM6r   