
    M/Ph                     L    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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                    t          | d          } ||dk    rt          d|z            |dk    rt          d|z            |||                     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      T/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/tsa/_bds.pydistance_indicatorsr      s    0 	1cAw!|| .078 9 9 	91}} 79AB C C 	C QUUU]]*6!AAAtG*q.!!G++    c                    | j         dk    st          d          | j        d         | j        d         k    st          d          |dk    r| }n3t          | |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7A*"21"555FGGG%-j-!:KLL%abb!""f-j"crc.BB  Dg&rtQ'?'?@A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   sm    " xG%%H!0Q!?!?HTNJ1g D D%4Z%C%C"A

Or   c                 &   t          |           }t          | d          \  }}|                     d          dz                                  d|                                 z  z
  d|z  z   ||dz
  z  |dz
  z  z  }t          j        d|dz
  f          }t          d|dz             D ]h}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<   i||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   _varr2      s     z??D%j!44OL!
..

Q
	#	#	%	%*..*:*:(:	:	
4
D1H%2	4A !Wq[)**Iq'A+.. N Nq-(( 	D 	DAA)*\AE-BCCCC()}Ga!#q=7H(IJK A"lQ5F5J&KLM)N	!]1_$%% a<r   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                            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'   r2   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   bdsrB      s   L 	1c"""AAI{{g** 24;< = = 	= %Q::J %Z99M 
G,,LIqgi  G!Wq[)**Ih7Q;'((Gq'!),, / /!A%8# **XYY		5I*JANNa$Q(9%9: }!<=Q))* +-'$--&*@2*E	!]Q&&' 5:==	!]Q5F2F(G!H!HIII(.=1$$%%:i  "*W"5"555r   )Nr   )r   Nr   )__doc__numpyr   scipyr   statsmodels.tools.validationr   r   r   r'   r2   rB    r   r   <module>rH      s    &           3 3 3 3 3 3', ', ', ',T!% !% !%H  4! ! !HM6 M6 M6 M6 M6 M6r   