U
    ^»{jêû  ã                   @   s"  d dl mZmZmZmZ d dlT d dlZd dlZd dl	Z	dd„ Z
dd„ Zd@d	d
„ZdAdd„Zdd„ ZdBdd„Zdd„ ZdCdd„ZdDdd„Zdde
dddfdd„ZdEd d!„Zd"d#„ ZdFd&d'„Zd(d)„ Zd*d+„ ZdGd,d-„ZdHd/d0„ZdId1d2„ZdJd7d8„ZdKd9d:„Zdeddddfd;d<„ZdLd>d?„ZdS )Mé    )Úabsolute_importÚdivisionÚprint_functionÚunicode_literals)Ú*Nc                 C   s   t jt  | | ¡dd�S )Né   ©Úaxis)ÚnpÚmaxÚabs©ÚxÚy© r   úM/var/www/html/bwave/python/venv/lib/python3.8/site-packages/nolds/measures.pyÚrowwise_chebyshev	   s    r   c                 C   s   t  t j| | d dd�¡S )Né   r   r   )r
   ÚsqrtÚsumr   r   r   r   Úrowwise_euclidean   s    r   ÚRANSACc           
   	   C   s:  |dkrjz<t  ¡ �* t  dt¡ dd lm} dd lm} W 5 Q R X W n$ tk
rh   t  	dt
¡ d}Y nX |dkr€t | ||¡S |dk�r(| |jdd�¡}t | ¡}t|jƒdkrÀ| d	d¡}| |¡ |¡}z"| ||¡ |jjd d d	… }	W n0 tk
�r"   t  	d
t
¡ t | ||¡}	Y nX |	S td |¡ƒ‚d S )Nr   Úignorer   zHfitting mode 'RANSAC' requires the package sklearn, using 'poly' insteadÚpolyF)Zfit_interceptr   éÿÿÿÿz5RANSAC did not reach consensus, using numpy's polyfitzinvalid fitting mode ({}))ÚwarningsÚcatch_warningsÚsimplefilterÚImportWarningZsklearn.linear_modelZlinear_modelZsklearn.preprocessingZpreprocessingÚImportErrorÚwarnÚRuntimeWarningr
   ZpolyfitZRANSACRegressorZLinearRegressionÚasarrayÚlenÚshapeÚreshapeZPolynomialFeaturesZfit_transformÚfitZ
estimator_Zcoef_Ú
ValueErrorÚformat)
r   r   Zdegreer&   ZsklinZskpreÚmodelZxdatZpolydatZcoefr   r   r   Úpoly_fit   s>    
ý


ýr*   r   c                 C   sŽ   t  | ¡} |d | d }t| ƒ|k rBd}t| t| ƒ|||¡ƒ‚t| ƒ| d }t jt  |¡| g|dd�}|t  |¡ |df¡7 }| | S )aÎ  
  Perform a time-delay embedding of a time series

  Args:
    data (array-like):
      the data that should be embedded
    emb_dim (int):
      the embedding dimension
  Kwargs:
    lag (int):
      the lag between elements in the embedded vectors

  Returns:
    emb_dim x m array:
      matrix of embedded vectors of the form
      [data[i], data[i+lag], data[i+2*lag], ... data[i+(emb_dim-1)*lag]]
      for i in 0 to m-1 (m = len(data)-(emb_dim-1)*lag)
  r   zdcannot embed data of length {} with embedding dimension {} and lag {}, minimum required length is {}r   r   )r
   r"   r#   r'   r(   ÚrepeatÚaranger%   )ÚdataÚemb_dimÚlagÚmin_lenÚmsgÚmÚindicesr   r   r   Údelay_embedding7   s    
r4   c                  K   s@   | d d | d  d }|| d d 7 }|| d d d 7 }|S )a  
  Helper function that calculates the minimum number of data points required
  to use lyap_r.

  Note that none of the required parameters may be set to None.

  Kwargs:
    kwargs(dict):
      arguments used for lyap_r (required: emb_dim, lag, trajectory_len and
      min_tsep)

  Returns:
    minimum number of data points required to call lyap_r with the given
    parameters
  r.   r   r/   Útrajectory_lenÚmin_tsepr   r   )Úkwargsr0   r   r   r   Ú
lyap_r_lenU   s    r8   é
   é   Fc           "   	      sX  t j| dd�} t| ƒ‰d}|dks*ˆdkr@t j | ˆd d ¡}ˆdkrÐt j ˆd d ¡t  |¡ }t  |dd… ¡t  t  |dd… ¡¡ }t	t  
d| ¡ƒ‰ˆ|ˆ krÐt	|ˆ ƒ‰d}t | ˆ¡t¡ |dk�r¤t j |t  |¡ ¡}t  |ˆd ¡}|ˆd  ddt j   }d}‡ ‡‡‡‡fd	d
„}tdˆƒD ]f‰ˆ}|ˆd ˆ  |k �sp|ˆd ˆ  |k �rv �q¤|ˆƒ|k �r<d}t | |¡t¡  �q¤�q<tˆ |ˆˆd�}t| ƒ|k �ràd}t | ˆ |ˆˆ|¡t¡ t| ˆ |ƒ‰tˆƒ}t  ‡fdd„t|ƒD ƒ¡}t|ƒD ],‰tdƒ|ˆtdˆˆ ƒˆˆ d …f< �q|ˆ d }ˆd d }|dk�r€d}t| | d ¡ƒ‚||k �rÐt  t jt  |d|…d|…f ¡dd�¡�sºt‚d}t| |ˆ|¡ƒ‚t  t jt  |d|…d|…f ¡dd�¡�s t‚t j|d|…d|…f dd�}t j ˆtd�}tˆƒD ]j}t  !|¡| || f}|| }t  "|dk¡}t|d ƒdk�r„t j# ||< nt  t  $|| ¡¡||< �q4t  !ˆ¡}t  "t  |¡¡}|| }|| }t|ƒdk �ræt j# dg} n t%||d… ||d… d|d�} |�r0t&||d… ||d… | dd|
d� | d | }!|	�rP|!||| ffS |!S dS )u¥  
  Estimates the largest Lyapunov exponent using the algorithm of Rosenstein
  et al. [lr_1]_.

  Explanation of Lyapunov exponents:
    See lyap_e.

  Explanation of the algorithm:
    The algorithm of Rosenstein et al. is only able to recover the largest
    Lyapunov exponent, but behaves rather robust to parameter choices.

    The idea for the algorithm relates closely to the definition of Lyapunov
    exponents. First, the dynamics of the data are reconstructed using a delay
    embedding method with a lag, such that each value x_i of the data is mapped
    to the vector

    X_i = [x_i, x_(i+lag), x_(i+2*lag), ..., x_(i+(emb_dim-1) * lag)]

    For each such vector X_i, we find the closest neighbor X_j using the
    euclidean distance. We know that as we follow the trajectories from X_i and
    X_j in time in a chaotic system the distances between X_(i+k) and X_(j+k)
    denoted as d_i(k) will increase according to a power law
    d_i(k) = c * e^(lambda * k) where lambda is a good approximation of the
    highest Lyapunov exponent, because the exponential expansion along the axis
    associated with this exponent will quickly dominate the expansion or
    contraction along other axes.

    To calculate lambda, we look at the logarithm of the distance trajectory,
    because log(d_i(k)) = log(c) + lambda * k. This gives a set of lines
    (one for each index i) whose slope is an approximation of lambda. We
    therefore extract the mean log trajectory d'(k) by taking the mean of
    log(d_i(k)) over all orbit vectors X_i. We then fit a straight line to
    the plot of d'(k) versus k. The slope of the line gives the desired
    parameter lambda.

  Method for choosing min_tsep:
    Usually we want to find neighbors between points that are close in phase
    space but not too close in time, because we want to avoid spurious
    correlations between the obtained trajectories that originate from temporal
    dependencies rather than the dynamic properties of the system. Therefore it
    is critical to find a good value for min_tsep. One rather plausible
    estimate for this value is to set min_tsep to the mean period of the
    signal, which can be obtained by calculating the mean frequency using the
    fast fourier transform. This procedure is used by default if the user sets
    min_tsep = None.

  Method for choosing lag:
    Another parameter that can be hard to choose by instinct alone is the lag
    between individual values in a vector of the embedded orbit. Here,
    Rosenstein et al. suggest to set the lag to the distance where the
    autocorrelation function drops below 1 - 1/e times its original (maximal)
    value. This procedure is used by default if the user sets lag = None.

  References:
    .. [lr_1] M. T. Rosenstein, J. J. Collins, and C. J. De Luca,
       â€œA practical method for calculating largest Lyapunov exponents from
       small data sets,â€� Physica D: Nonlinear Phenomena, vol. 65, no. 1,
       pp. 117â€“134, 1993.

  Reference Code:
    .. [lr_a] mirwais, "Largest Lyapunov Exponent with Rosenstein's Algorithm",
       url: http://www.mathworks.com/matlabcentral/fileexchange/38424-largest-lyapunov-exponent-with-rosenstein-s-algorithm
    .. [lr_b] Shapour Mohammadi, "LYAPROSEN: MATLAB function to calculate
       Lyapunov exponent",
       url: https://ideas.repec.org/c/boc/bocode/t741502.html

  Args:
    data (iterable of float):
      (one-dimensional) time series
  Kwargs:
    emb_dim (int):
      embedding dimension for delay embedding
    lag (float):
      lag for delay embedding
    min_tsep (float):
      minimal temporal separation between two "neighbors" (default:
      find a suitable value by calculating the mean period of the data)
    tau (float):
      step size between data points in the time series in seconds
      (normalization scaling factor for exponents)
    min_neighbors (int):
      if lag=None, the search for a suitable lag will be stopped when the
      number of potential neighbors for a vector drops below min_neighbors
    trajectory_len (int):
      the time (in number of data points) to follow the distance
      trajectories between two neighboring points
    fit (str):
      the fitting method to use for the line fit, either 'poly' for normal
      least squares polynomial fitting or 'RANSAC' for RANSAC-fitting which
      is more robust to outliers
    debug_plot (boolean):
      if True, a simple plot of the final line-fitting step will
      be shown
    debug_data (boolean):
      if True, debugging data will be returned alongside the result
    plot_file (str):
      if debug_plot is True and plot_file is not None, the plot will be saved
      under the given file name instead of directly showing it through
      ``plt.show()``
    fit_offset (int):
      neglect the first fit_offset steps when fitting

  Returns:
    float:
      an estimate of the largest Lyapunov exponent (a positive exponent is
      a strong indicator for chaos)
    (1d-vector, 1d-vector, list):
      only present if debug_data is True: debug data of the form
      ``(ks, div_traj, poly)`` where ``ks`` are the x-values of the line fit, 
      ``div_traj`` are the y-values and ``poly`` are the line coefficients
      (``[slope, intercept]``).

  Úfloat32©Zdtypeç      Ð?Nr   r   ç      ð?z;signal has very low mean frequency, setting min_tsep = {:d}c                    s   t ˆ ˆˆˆd�}tdˆ| ƒS )N©r.   r/   r5   r6   r   )r8   r   )Z	lag_valuer0   )r.   Úir6   Únr5   r   r   Únb_neighborsþ   s      þzlyap_r.<locals>.nb_neighborszKautocorrelation declined too slowly to find suitable lag, setting lag to {}r?   zufor emb_dim = {}, lag = {}, min_tsep = {} and trajectory_len = {} you need at least {} datapoints in your time seriesc                    s   g | ]}t ˆ ˆ | ƒ‘qS r   )r   ©Ú.0r@   )Úorbitr   r   Ú
<listcomp>  s     zlyap_r.<locals>.<listcomp>Úinfr   zWNot enough data points. Need {} additional data points to follow a complete trajectory.r   z›Not enough data points. At least {} trajectories are required to find a valid neighbor for each orbit vector with min_tsep={} but only {} could be created.©r&   Úkz	log(d(k))©Úfname)'r
   r"   r#   ZfftZrfftZrfftfreqr   Úmeanr   ÚintÚceilr   r    r(   r!   ZirfftZconjZrollÚeÚranger8   r4   ÚarrayÚfloatr   r'   ÚanyÚallÚisinfÚAssertionErrorÚisfiniteZargminÚzerosr,   ÚwhererG   Úlogr*   Úplot_reg)"r-   r.   r/   r6   ÚtauZmin_neighborsr5   r&   Ú
debug_plotÚ
debug_dataÚ	plot_fileZ
fit_offsetZmax_tsep_factorÚfÚmfr1   ZacorrÚepsrB   r0   r2   ÚdistsZntrajZmin_trajZnb_idxZdiv_trajrI   r3   Z
div_traj_kÚnonzeroÚksZfiniter   Úler   )r.   r@   r6   rA   rE   r5   r   Úlyap_rm   s˜    u*
,
  þþ*

00
 $rg   c                  K   sH   | d d | d d  }| d }||7 }|| d d 7 }|| d 7 }|S )a~  
  Helper function that calculates the minimum number of data points required
  to use lyap_e.

  Note that none of the required parameters may be set to None.

  Kwargs:
    kwargs(dict):
      arguments used for lyap_e (required: emb_dim, matrix_dim, min_nb
      and min_tsep)

  Returns:
    minimum number of data points required to call lyap_e with the given
    parameters
  r.   r   Ú
matrix_dimr6   r   Úmin_nbr   )r7   r2   r0   r   r   r   Ú
lyap_e_lenY  s    rj   é   c	           "   
      s&  t  ˆ ¡‰ tˆ ƒ}	ˆd |d  dkr.tdƒ‚ˆd |d  ‰|dkrXtd| |d ƒ}tˆ|||d�}
|	|
k r�d}t | |	ˆ||||
¡t	¡ t
ˆ dˆ … ˆdd	�}t|ƒ|k ràtˆ ƒ|
k sÄt‚d
}t| |t|ƒ |¡ƒ‚t  |¡}t j|dd�}t  |j¡}g }tt|ƒƒD �]–}t||| ƒ}tdƒ||< td|| ƒ}tt|ƒ|| d ƒ}t j|||…< t  |¡}||d  }|| }t  |¡�rºtˆ ƒ|
k �s¢t‚d}t| ||||
¡ƒ‚t  ||k¡d }t  ‡ ‡‡fdd„|D ƒ¡}|ˆ ||ˆ ˆ… 8 }tt  |¡|ƒ|ˆ  tˆ ƒk�rLtˆ ƒ|
k �s2t‚d}t| ||ˆ |
¡ƒ‚ˆ ||ˆ   ˆ ||ˆ    }t jj||dd�\}}}}t  ||f¡}t  |d ¡|dd…dd…f< ||d< t j t  ||¡¡\}}t  t  |¡¡}d|t  |dk¡< t  |¡}t  ||¡}t  ||¡}|}t  |¡} t  | dk¡}t j| jdd�}!t  | | ¡|!|< t j|!t  | dk¡< |�st|�r†| |!| ˆ ¡ ||  |!| 7  < ||  d7  < �q|�rÈt t  |¡d|d� t  |dk¡}||  ||   < t j|t  |dk¡< || }|ˆ }|�r"|t  |¡fS |S )u  
  Estimates the Lyapunov exponents for the given data using the algorithm of
  Eckmann et al. [le_1]_.

  Recommendations for parameter settings by Eckmann et al.:
    * long recording time improves accuracy, small tau does not
    * use large values for emb_dim
    * matrix_dim should be 'somewhat larger than the expected number of
      positive Lyapunov exponents'
    * min_nb = min(2 * matrix_dim, matrix_dim + 4)

  Explanation of Lyapunov exponents:
    The Lyapunov exponent describes the rate of separation of two
    infinitesimally close trajectories of a dynamical system in phase space.
    In a chaotic system, these trajectories diverge exponentially following
    the equation:

    \|X(t, X_0) - X(t, X_0 + eps)| = e^(lambda * t) * \|eps|

    In this equation X(t, X_0) is the trajectory of the system X starting at
    the point X_0 in phase space at time t. eps is the (infinitesimal)
    difference vector and lambda is called the Lyapunov exponent. If the
    system has more than one free variable, the phase space is
    multidimensional and each dimension has its own Lyapunov exponent. The
    existence of at least one positive Lyapunov exponent is generally seen as
    a strong indicator for chaos.

  Explanation of the Algorithm:
    To calculate the Lyapunov exponents analytically, the Jacobian of the
    system is required. The algorithm of Eckmann et al. therefore tries to
    estimate this Jacobian by reconstructing the dynamics of the system from
    which the time series was obtained. For this, several steps are required:

    * Embed the time series [x_1, x_2, ..., x_(N-1)] in an orbit of emb_dim
      dimensions (map each point x_i of the time series to a vector
      [x_i, x_(i+1), x_(i+2), ... x_(i+emb_dim-1)]).
    * For each vector X_i in this orbit find a radius r_i so that at least
      min_nb other vectors lie within (chebyshev-)distance r_i around X_i.
      These vectors will be called "neighbors" of X_i.
    * Find the Matrix T_i that sends points from the neighborhood of X_i to
      the neighborhood of X_(i+1). To avoid undetermined values in T_i, we
      construct T_i not with size (emb_dim x emb_dim) but with size
      (matrix_dim x matrix_dim), so that we have a larger "step size" m in the
      X_i, which are now defined as X'_i = [x_i, x_(i+m), x_(i+2m),
      ... x_(i+(matrix_dim-1)*m)]. This means that emb_dim-1 must be divisible
      by matrix_dim-1. The T_i are then found by a linear least squares fit,
      assuring that T_i (X_j - X_i) ~= X_(j+m) - X_(i+m) for any X_j in the
      neighborhood of X_i.
    * Starting with i = 1 and Q_0 = identity successively decompose the matrix
      T_i * Q_(i-1) into the matrices Q_i and R_i by a QR-decomposition.
    * Calculate the Lyapunov exponents from the mean of the logarithm of the
      diagonal elements of the matrices R_i. To normalize the Lyapunov
      exponents, they have to be divided by m and by the step size tau of the
      original time series.

  References:
    .. [le_1] J. P. Eckmann, S. O. Kamphorst, D. Ruelle, and S. Ciliberto,
       â€œLiapunov exponents from time series,â€� Physical Review A,
       vol. 34, no. 6, pp. 4971â€“4979, 1986.

  Reference code:
    .. [le_a] Manfred FÃ¼llsack, "Lyapunov exponent",
       url: http://systems-sciences.uni-graz.at/etextbook/sw2/lyapunov.html
    .. [le_b] Steve SIU, Lyapunov Exponents Toolbox (LET),
       url: http://www.mathworks.com/matlabcentral/fileexchange/233-let/content/LET/findlyap.m
    .. [le_c] Rainer Hegger, Holger Kantz, and Thomas Schreiber, TISEAN,
       url: http://www.mpipks-dresden.mpg.de/~tisean/Tisean_3.0.1/index.html

  Args:
    data (array-like of float):
      (scalar) data points

  Kwargs:
    emb_dim (int):
      embedding dimension
    matrix_dim (int):
      matrix dimension (emb_dim - 1 must be divisible by matrix_dim - 1)
    min_nb (int):
      minimal number of neighbors
      (default: min(2 * matrix_dim, matrix_dim + 4))
    min_tsep (int):
      minimal temporal separation between two "neighbors"
    tau (float):
      step size of the data in seconds
      (normalization scaling factor for exponents)
    debug_plot (boolean):
      if True, a histogram matrix of the individual estimates will be shown
    debug_data (boolean):
      if True, debugging data will be returned alongside the result
    plot_file (str):
      if debug_plot is True and plot_file is not None, the plot will be saved
      under the given file name instead of directly showing it through
      ``plt.show()``

  Returns:
    float array:
      array of matrix_dim Lyapunov exponents (positive exponents are indicators
      for chaos)
    2d-array of floats:
      only present if debug_data is True: all estimates for the matrix_dim
      Lyapunov exponents from the x iterations of R_i. The shape of this debug
      data is (x, matrix_dim).
  r   r   z0emb_dim - 1 must be divisible by matrix_dim - 1!Nr   rk   )r.   rh   ri   r6   z”{} data points are not enough! For emb_dim = {}, matrix_dim = {}, min_tsep = {} and min_nb = {} you need at least {} data points in your time series©r/   zgNot enough data points. Need at least {} additional data points to have min_nb = {} neighbor candidatesr;   r<   rG   z¦Not enough data points. Orbit vector {} has less than min_nb = {} valid neighbors that are at least min_tsep = {} time steps away. Input must have at least length {}.c                    s   g | ]}ˆ ||ˆ ˆ… ‘qS r   r   )rD   Új©r-   r.   r2   r   r   rF   <  s     zlyap_e.<locals>.<listcomp>z}Not enough data points. Cannot follow orbit vector {} for {} (matrix_dim * m) time steps. Input must have at least length {}.r   )ZrcondZlayp_erJ   )!r
   r"   r#   r'   Úminrj   r   r    r(   r!   r4   rV   ÚidentityrX   r$   rP   r   rR   r   rG   ZargsortrU   rY   rQ   ZlinalgZlstsqZqrÚdotÚsignZdiagrZ   ÚappendÚplot_histogram_matrix)"r-   r.   rh   ri   r6   r\   r]   r^   r_   rA   r0   r1   rE   Zold_QZlexpZlexp_countsZdebug_valuesr@   ZdiffsZ	mask_fromZmask_tor3   ÚidxÚrZmat_XZvec_betaÚaÚ_Zmat_TZmat_QZmat_RZ	sign_diagZdiag_RZlexp_ir   rn   r   Úlyap_et  sž    i
   ÿþ

!" 

ry   c              	      s4  dd l m} d}d‰ t | ¡}t|ƒd }t |¡}	t |¡}
d|	|
|  f‰d}ddg}‡ ‡fdd„| D ƒD ]L\}}|d	 |d  }|j|d d
… ||d || ¡|| dd� |d	7 }qn|j	|dd� |j
dd� | d¡ | d¡ | d|¡ |d k	�r
| |¡ |d k�r| ¡  n
| |¡ | ¡  d S )Nr   é   é2   gš™™™™™©?ÚgreenÚbluec                    s   g | ]}t  |ˆ ˆ¡‘qS r   )r
   Ú	histogram)rD   Zdat©ÚnbinsÚrngr   r   rF   ‹  s     zplot_dists.<locals>.<listcomp>r   r   zm={:d}ç      à?)ÚlabelÚcolorÚalphaÚred©r„   Úbest©ÚlocZdistanceÚcount)Úmatplotlib.pyplotÚpyplotr
   Zconcatenater#   rL   ÚstdÚbarr(   ÚaxvlineÚlegendÚxlabelÚylabelÚylimÚtitleÚshowÚsavefigÚclose)rc   Ú	tolerancer2   r•   rK   ÚpltZnstdZ
dists_fullZymaxrL   rŽ   r@   ÚcolorsÚhÚbinsÚbwr   r   r   Ú
plot_dists  s8    


 ÿ







rŸ   r   c              	   C   sJ  t  | ¡} |dkr dt  | ¡ }t| ƒ}tt  | ¡|d dd�}g }	g }
||d fD ]�}|
 d¡ |	 g ¡ |d|| d …d|…f }tt|ƒd ƒD ]J}|||d d… || ƒ}|rÈ|	d  |¡ |
d  t  ||k ¡7  < q˜qT|
d dkrút j	}nt  
d|
d  |
d  ¡ }|�r4t|	||d |¡|d	� |�rB||	fS |S dS )
uY
  
  Computes the sample entropy of the given data.

  Explanation of the sample entropy:
    The sample entropy of a time series is defined as the negative natural
    logarithm of the conditional probability that two sequences similar for
    emb_dim points remain similar at the next point, excluding self-matches.

    A lower value for the sample entropy therefore corresponds to a higher
    probability indicating more self-similarity.

  Explanation of the algorithm:
    The algorithm constructs all subsequences of length emb_dim
    [s_1, s_2, s_3, ...] and then counts each pair (s_i, s_j) with i != j
    where dist(s_i, s_j) < tolerance. The same process is repeated for all
    subsequences of length emb_dim + 1. The sum of similar sequence pairs
    with length emb_dim + 1 is divided by the sum of similar sequence pairs
    with length emb_dim. The result of the algorithm is the negative logarithm
    of this ratio/probability.

  References:
    .. [se_1] J. S. Richman and J. R. Moorman, â€œPhysiological time-series
       analysis using approximate entropy and sample entropy,â€�
       American Journal of Physiology-Heart and Circulatory Physiology,
       vol. 278, no. 6, pp. H2039â€“H2049, 2000.

  Reference code:
    .. [se_a] "sample_entropy" function in R-package "pracma",
        url: https://cran.r-project.org/web/packages/pracma/pracma.pdf

  Args:
    data (array-like of float):
      input data

  Kwargs:
    emb_dim (int):
      the embedding dimension (length of vectors to compare)
    tolerance (float):
      distance threshold for two template vectors to be considered equal
      (default: 0.2 * std(data))
    dist (function (2d-array, 1d-array) -> 1d-array):
      distance function used to calculate the distance between template
      vectors. Sampen is defined using ``rowwise_chebyshev``. You should only use
      something else, if you are sure that you need it.
    debug_plot (boolean):
      if True, a histogram of the individual distances for m and m+1
    debug_data (boolean):
      if True, debugging data will be returned alongside the result
    plot_file (str):
      if debug_plot is True and plot_file is not None, the plot will be saved
      under the given file name instead of directly showing it through
      ``plt.show()``

  Returns:
    float:
      the sample entropy of the data (negative logarithm of ratio between
      similar template vectors of length emb_dim + 1 and emb_dim)
    [float list, float list]:
      Lists of lists of the form ``[dists_m, dists_m1]`` containing the distances
      between template vectors for m (dists_m) and for m + 1 (dists_m1).
  Ngš™™™™™É?r   rl   r   r   r>   zsampEn = {:.3f})r•   rK   )r
   r"   rŽ   r#   r4   rs   rP   Úextendr   rG   rZ   rŸ   r(   )r-   r.   r™   Údistr]   r^   r_   rA   ZtVecsZ	plot_dataÚcountsr2   ZtVecsMr@   ZdstsZsaenr   r   r   Úsampenž  s4    ?


ÿr£   r{   c                    s<   t  dˆ  | ¡}tt  |¡ƒ}‡ fdd„td|d ƒD ƒS )a}  
  Creates a list of values by successively halving the total length total_N
  until the resulting value is less than min_n.

  Non-integer results are rounded down.

  Args:
    total_N (int):
      total length
  Kwargs:
    min_n (int):
      minimal length after division

  Returns:
    list of integers:
      total_N/2, total_N/4, total_N/8, ... until total_N/2^i < min_n
  r>   c                    s&   g | ]}t t d ˆ  d|  ¡ƒ‘qS )r>   r   )rM   r
   ÚfloorrC   ©Útotal_Nr   r   rF   #  s     zbinary_n.<locals>.<listcomp>r   )r
   Úlog2rM   r¤   rP   )r¦   Úmin_nÚmax_expr   r¥   r   Úbinary_n  s    rª   c                 C   s†   || kst ‚|dkst ‚tt t d| |  ¡t |¡ ¡ƒ}| g}t|d ƒD ]0}tt | ||  ¡ƒ}||d krP| |¡ qP|S )aû  
  Creates a list of values by successively multiplying a minimum value min_n by
  a factor > 1 until a maximum value max_n is reached.

  Non-integer results are rounded down.

  Args:
    min_n (float):
      minimum value (must be < max_n)
    max_n (float):
      maximum value (must be > min_n)
    factor (float):
      factor used to increase min_n (must be > 1)

  Returns:
    list of integers:
      min_n, min_n * factor, min_n * factor^2, ... min_n * factor^i < max_n
      without duplicates
  r   r>   r   )rV   rM   r
   r¤   rZ   rP   rs   )r¨   Úmax_nÚfactorÚmax_iÚnsr@   rA   r   r   r   Úlogarithmic_n&  s    &r¯   r=   é   c                 C   s\   t  | ¡}|| }|d|  d }|dt  |¡ | |  }t  t  |¡¡ d¡}t  |¡S )a  
  Creates an array of integers that lie evenly spaced in the "middle" of the
  logarithmic scale from 0 to log(max_n).

  If max_n is very small and/or nsteps is very large, this may lead to
  duplicate values which will be removed from the output.

  This function has benefits in hurst_rs, because it cuts away both very small
  and very large n, which both can cause problems, and still produces a
  logarithmically spaced sequence.

  Args:
    max_n (int):
      largest possible output value (should be the sequence length when used in
      hurst_rs)

  Kwargs:
    ratio (float):
      width of the "middle" of the logarithmic interval relative to log(max_n).
      For example, for ratio=1/2.0 the logarithm of the resulting values will
      lie between 0.25 * log(max_n) and 0.75 * log(max_n).
    nsteps (float):
      (maximum) number of values to take from the specified range

  Returns:
    array of int:
      a logarithmically spaced sequence of at most nsteps values (may be less,
      because only unique values are returned)
  r   r‚   r>   Zint32)r
   rZ   r,   ÚroundÚexpÚastypeÚunique)r«   ÚratioÚnstepsÚlÚspanÚstartZmidrangeÚnvalsr   r   r   Úlogmid_nG  s    
r»   c                    sZ   |ˆkst ‚ˆ dkst ‚tt t d| ˆ ¡t ˆ ¡ ¡ƒ}‡ ‡fdd„t|d ƒD ƒS )a·  
  Creates a list of values by successively multiplying a minimum value min_n by
  a factor > 1 until a maximum value max_n is reached.

  Args:
    min_n (float):
      minimum value (must be < max_n)
    max_n (float):
      maximum value (must be > min_n)
    factor (float):
      factor used to increase min_n (must be > 1)

  Returns:
    list of floats:
      min_n, min_n * factor, min_n * factor^2, ... min_n * factor^i < max_n
  r   r>   c                    s   g | ]}ˆˆ |  ‘qS r   r   rC   ©r¬   r¨   r   r   rF   €  s     z!logarithmic_r.<locals>.<listcomp>)rV   rM   r
   r¤   rZ   rP   )r¨   r«   r¬   r­   r   r¼   r   Úlogarithmic_rl  s    &r½   c                 C   sŠ   | d |  }t  d| ¡}t  t  | | | ¡¡}| dkrft | d d ¡t tj¡ t | d ¡ }ndt | tj d ¡ }|| | S )a[  
  Calculates the expected (R/S)_n for white noise for a given n.

  This is used as a correction factor in the function hurst_rs. It uses the
  formula of Anis-Lloyd-Peters (see [h_3]_).

  Args:
    n (int):
      the value of n for which the expected (R/S)_n should be calculated

  Returns:
    float:
      expected (R/S)_n for white noise
  r‚   r   iT  r>   )r
   r,   r   r   ÚmathÚgammaÚpi)rA   Úfrontr@   ÚbackÚmiddler   r   r   Úexpected_rsƒ  s    .rÄ   c                 C   s2   dd„ | D ƒ}t t | ¡t |¡d|d�}|d S )aó  
  Uses expected_rs to calculate the expected value for the Hurst exponent h
  based on the values of n used for the calculation.

  Args:
    nvals (iterable of int):
      the values of n used to calculate the individual (R/S)_n

  KWargs:
    fit (str):
      the fitting method to use for the line fit, either 'poly' for normal
      least squares polynomial fitting or 'RANSAC' for RANSAC-fitting which
      is more robust to outliers

  Returns:
    float:
      expected h for white noise
  c                 S   s   g | ]}t |ƒ‘qS r   ©rÄ   ©rD   rA   r   r   r   rF   ®  s     zexpected_h.<locals>.<listcomp>r   rH   r   )r*   r
   rZ   )rº   r&   Úrsvalsr   r   r   r   Ú
expected_h›  s    rÈ   Tc                 C   sâ   t  | ¡} t| ƒ}|| }| d|||  … } t  | ||f¡}t j|dd�}|| |df¡ }t j|dd�}t j|dd�t j|dd� }t j|d|r˜dndd�}	t  	|dk¡}
||
 }|	|
 }	t|ƒdkrÐt j
S t  ||	 ¡S dS )a¦  
  Calculates an individual R/S value in the rescaled range approach for
  a given n.

  Note: This is just a helper function for hurst_rs and should not be called
  directly.

  Args:
    data (array-like of float):
      time series
    n (float):
      size of the subseries in which data should be split

  Kwargs:
    unbiased (boolean):
      if True, the standard deviation based on the unbiased variance
      (1/(N-1) instead of 1/N) will be used. This should be the default choice,
      since the true mean of the sequences is not known. This parameter should
      only be changed to recreate results of other implementations.

  Returns:
    float:
      (R/S)_n
  Nr   r   r   )r	   Zddof)r
   r"   r#   r%   rL   Úcumsumr   ro   rŽ   rY   Únan)r-   rA   Úunbiasedr¦   r2   ZseqsZmeansr   rv   Úsru   r   r   r   Úrs³  s     
rÍ   c              	   C   sj  dd l m} t| d ƒ}d}d}tt t |¡¡ƒ}|j|d |d fd� t|ƒD ]ê}| 	|||d ¡ t
tt 
| d d …|f ¡ƒtt | d d …|f ¡ƒƒ}	|	 |	f}
t | d d …|f ||
¡\}}|d |d  }| d¡t |¡ }| |d d… ||¡ |jt | d d …|f ¡d	d
� | |¡ | d ||¡¡ qT|d k�rT| ¡  n
| |¡ | ¡  d S )Nr   é   )r   r‚   rk   )Zfigsizer   r;   r   r†   r‡   z
{:s}[{:d}])rŒ   r�   r#   rM   r
   rN   r   ZfigurerP   Zsubplotr   r   ro   r~   r³   r   r�   r�   rL   r”   r•   r(   r–   r—   r˜   )r-   ÚnamerK   rš   Znhistsr€   r”   Znrowsr@   Zabsmaxr�   rœ   r�   Z	bin_widthr   r   r   rt   ê  s*    6
 



rt   r   r   r-   úregression linec           	      C   sˆ   ddl m} |j| |d|d� |dk	r@|j| t || ¡d|d� | |¡ | |¡ |jdd� |dkrr| ¡  n
| 	|¡ | 
¡  dS )aØ  
  Helper function to plot trend lines for line-fitting approaches. This
  function will show a plot through ``plt.show()`` and close it after the window
  has been closed by the user.

  Args:
    xvals (list/array of float):
      list of x-values
    yvals (list/array of float):
      list of y-values
    poly (list/array of float):
      polynomial parameters as accepted by ``np.polyval``
  Kwargs:
    x_label (str):
      label of the x-axis
    y_label (str):
      label of the y-axis
    data_label (str):
      label of the data
    reg_label(str):
      label of the regression line
    fname (str):
      file name (if not None, the plot will be saved to disc instead of
      showing it though ``plt.show()``)
  r   NZbo)rƒ   zr-rˆ   r‰   )rŒ   r�   Zplotr
   Úpolyvalr’   r“   r‘   r–   r—   r˜   )	ÚxvalsÚyvalsr   Zx_labelZy_labelZ
data_labelZ	reg_labelrK   rš   r   r   r   r[     s    



r[   c                    s(  t  ˆ ¡‰ tˆ ƒ}|dkr(t|ddd�}t  ‡ ‡fdd„|D ƒ¡}	t  t  |	¡¡}
|	|
 }	t  |¡|
 }t|	ƒdkr�t jt jg}|rèt 	d¡ nXt  
|¡}t  
|	¡}|rÀ|t  
d	d„ |D ƒ¡8 }t||d
|d�}|rèt|||dd|d� |rø|d d n|d }|�r |t  
|¡t  
|	¡|ffS |S dS )uu  
  Calculates the Hurst exponent by a standard rescaled range (R/S) approach.

  Explanation of Hurst exponent:
    The Hurst exponent is a measure for the "long-term memory" of a
    time series, meaning the long statistical dependencies in the data that do
    not originate from cycles.

    It originates from H.E. Hursts observations of the problem of long-term
    storage in water reservoirs. If x_i is the discharge of a river in year i
    and we observe this discharge for N years, we can calculate the storage
    capacity that would be required to keep the discharge steady at its mean
    value.

    To do so, we first substract the mean over all x_i from the individual
    x_i to obtain the departures x'_i from the mean for each year i. As the
    excess or deficit in discharge always carrys over from year i to year i+1,
    we need to examine the cumulative sum of x'_i, denoted by y_i. This
    cumulative sum represents the filling of our hypothetical storage. If the
    sum is above 0, we are storing excess discharge from the river, if it is
    below zero we have compensated a deficit in discharge by releasing
    water from the storage. The range (maximum - minimum) R of y_i therefore
    represents the total capacity required for the storage.

    Hurst showed that this value follows a steady trend for varying N if it
    is normalized by the standard deviation sigma over the x_i. Namely he
    obtained the following formula:

    R/sigma = (N/2)^K

    In this equation, K is called the Hurst exponent. Its value is 0.5 for
    white noise, but becomes greater for time series that exhibit some positive
    dependency on previous values. For negative dependencies it becomes less
    than 0.5.

  Explanation of the algorithm:
    The rescaled range (R/S) approach is directly derived from Hurst's
    definition. The time series of length N is split into non-overlapping
    subseries of length n. Then, R and S (S = sigma) are calculated for each
    subseries and the mean is taken over all subseries yielding (R/S)_n. This
    process is repeated for several lengths n. Finally, the exponent K is
    obtained by fitting a straight line to the plot of log((R/S)_n) vs log(n).

    There seems to be no consensus how to chose the subseries lenghts n.
    This function therefore leaves the choice to the user. The module provides
    some utility functions for "typical" values:

      * binary_n: N/2, N/4, N/8, ...
      * logarithmic_n: min_n, min_n * f, min_n * f^2, ...

  References:
    .. [h_1] H. E. Hurst, â€œThe problem of long-term storage in reservoirs,â€�
       International Association of Scientific Hydrology. Bulletin, vol. 1,
       no. 3, pp. 13â€“27, 1956.
    .. [h_2] H. E. Hurst, â€œA suggested statistical model of some time series
       which occur in nature,â€� Nature, vol. 180, p. 494, 1957.
    .. [h_3] R. Weron, â€œEstimating long-range dependence: finite sample
       properties and confidence intervals,â€� Physica A: Statistical Mechanics
       and its Applications, vol. 312, no. 1, pp. 285â€“299, 2002.

  Reference Code:
    .. [h_a] "hurst" function in R-package "pracma",
             url: https://cran.r-project.org/web/packages/pracma/pracma.pdf

             Note: Pracma yields several estimates of the Hurst exponent, which
             are listed below. Unless otherwise stated they use the divisors
             of the length of the sequence as n. The length is reduced by at
             most 1% to find the value that has the most divisors.

             * The "Simple R/S" estimate is just log((R/S)_n) / log(n) for 
               n = N.
             * The "theoretical Hurst exponent" is the value that would be
               expected of an uncorrected rescaled range approach for random
               noise of the size of the input data.
             * The "empirical Hurst exponent" is the uncorrected Hurst exponent
               obtained by the rescaled range approach.
             * The "corrected empirical Hurst exponent" is the Anis-Lloyd-Peters
               corrected Hurst exponent, but with sqrt(1/2 * pi * n) added to
               the (R/S)_n before the log.
             * The "corrected R over S Hurst exponent" uses the R-function "lm"
               instead of pracmas own "polyfit" and uses n = N/2, N/4, N/8, ...
               by successively halving the subsequences (which means that some
               subsequences may be one element longer than others). In contrast
               to its name it does not use the Anis-Lloyd-Peters correction
               factor.

             If you want to compare the output of pracma to the output of
             nolds, the "empirical hurst exponent" is the only measure that
             exactly corresponds to the Hurst measure implemented in nolds
             (by choosing corrected=False, fit="poly" and employing the same
             strategy for choosing n as the divisors of the (reduced)
             sequence length).
    .. [h_b] Rafael Weron, "HURST: MATLAB function to compute the Hurst
             exponent using R/S Analysis",
             url: https://ideas.repec.org/c/wuu/hscode/m11003.html

             Note: When the same values for nvals are used and fit is set to
             "poly", nolds yields exactly the same results as this
             implementation.
    .. [h_c] Bill Davidson, "Hurst exponent",
             url: http://www.mathworks.com/matlabcentral/fileexchange/9842-hurst-exponent
    .. [h_d] Tomaso Aste, "Generalized Hurst exponent",
             url: http://de.mathworks.com/matlabcentral/fileexchange/30076-generalized-hurst-exponent

  Args:
    data (array-like of float):
      time series
  Kwargs:
    nvals (iterable of int):
      sizes of subseries to use
      (default: logmid_n(total_N, ratio=1/4.0, nsteps=15) , that is 15
      logarithmically spaced values in the medium 25% of the logarithmic range)

      Generally, the choice for n is a trade-off between the length and the
      number of the subsequences that are used for the calculation of the
      (R/S)_n. Very low values of n lead to high variance in the ``r`` and ``s``
      while very high values may leave too few subsequences that the mean along
      them is still meaningful. Logarithmic spacing makes sense, because it 
      translates to even spacing in the log-log-plot.
    fit (str):
      the fitting method to use for the line fit, either 'poly' for normal
      least squares polynomial fitting or 'RANSAC' for RANSAC-fitting which
      is more robust to outliers
    debug_plot (boolean):
      if True, a simple plot of the final line-fitting step will be shown
    debug_data (boolean):
      if True, debugging data will be returned alongside the result
    plot_file (str):
      if debug_plot is True and plot_file is not None, the plot will be saved
      under the given file name instead of directly showing it through
      ``plt.show()``
    corrected (boolean):
      if True, the Anis-Lloyd-Peters correction factor will be applied to the
      output according to the expected value for the individual (R/S)_n
      (see [h_3]_)
    unbiased (boolean):
      if True, the standard deviation based on the unbiased variance
      (1/(N-1) instead of 1/N) will be used. This should be the default choice,
      since the true mean of the sequences is not known. This parameter should
      only be changed to recreate results of other implementations.

  Returns:
    float:
      estimated Hurst exponent K using a rescaled range approach (if K = 0.5
      there are no long-range correlations in the data, if K < 0.5 there are
      negative long-range correlations, if K > 0.5 there are positive
      long-range correlations)
    (1d-vector, 1d-vector, list):
      only present if debug_data is True: debug data of the form
      ``(nvals, rsvals, poly)`` where ``nvals`` are the values used for log(n), 
      ``rsvals`` are the corresponding log((R/S)_n) and ``poly`` are the line 
      coefficients (``[slope, intercept]``)
  Nr=   r°   )rµ   r¶   c                    s   g | ]}t ˆ |ˆd �‘qS ))rË   )rÍ   rÆ   ©r-   rË   r   r   rF   Ñ  s     zhurst_rs.<locals>.<listcomp>r   z.Cannot display debug plot, all (R/S)_n are NaNc                 S   s   g | ]}t |ƒ‘qS r   rÅ   rÆ   r   r   r   rF   á  s     r   rH   úlog(n)zlog((R/S)_n)rJ   r‚   )r
   r"   r#   r»   rQ   Zlogical_notÚisnanrÊ   r   r    rZ   r*   r[   )r-   rº   r&   r]   r^   r_   Z	correctedrË   r¦   rÇ   Znot_nanr   rÒ   rÓ   rœ   r   rÔ   r   Úhurst_rs.  s4     


ÿr×   c                    sX  t  | ¡} |dkr0t  | ¡}td| d| dƒ}t| ƒ}	t| |dd�‰t  ‡ ‡fdd„ttˆƒƒD ƒ¡}
g }|D ],}d	|	|	d   t  |
|k ¡ }| 	|¡ qpt  |¡}t  
|d
k¡}t  |¡| }|| }t|ƒd
kræt jt jg}ntt  |¡t  |¡d|d�}|�r(tt  |¡t  |¡|dd|d� |�rL|d
 t  |¡t  |¡|ffS |d
 S dS )u
  
  Calculates the correlation dimension with the Grassberger-Procaccia algorithm

  Explanation of correlation dimension:
    The correlation dimension is a characteristic measure that can be used
    to describe the geometry of chaotic attractors. It is defined using the
    correlation sum C(r) which is the fraction of pairs of points X_i in the
    phase space whose distance is smaller than r.

    If the relation between C(r) and r can be described by the power law

    C(r) ~ r^D

    then D is called the correlation dimension of the system.

    In a d-dimensional system, the maximum value for D is d. This value is
    obtained for systems that expand uniformly in each dimension with time.
    The lowest possible value is 0 for a system with constant C(r) (i.e. a
    system that visits just one point in the phase space). Generally if D is
    lower than d and the system has an attractor, this attractor is called
    "strange" and D is a measure of this "strangeness".

  Explanation of the algorithm:
    The Grassberger-Procaccia algorithm calculates C(r) for a range of
    different r and then fits a straight line into the plot of log(C(r))
    versus log(r).

    This version of the algorithm is created for one-dimensional (scalar) time
    series. Therefore, before calculating C(r), a delay embedding of the time
    series is performed to yield emb_dim dimensional vectors
    Y_i = [X_i, X_(i+1), X_(i+2), ... X_(i+embd_dim-1)]. Choosing a higher
    value for emb_dim allows to reconstruct higher dimensional dynamics and
    avoids "systematic errors due to corrections to scaling".

  References:
    .. [cd_1] P. Grassberger and I. Procaccia, â€œCharacterization of strange
              attractors,â€� Physical review letters, vol. 50, no. 5, p. 346,
              1983.
    .. [cd_2] P. Grassberger and I. Procaccia, â€œMeasuring the strangeness of
              strange attractors,â€� Physica D: Nonlinear Phenomena, vol. 9,
              no. 1, pp. 189â€“208, 1983.
    .. [cd_3] P. Grassberger, â€œGrassberger-Procaccia algorithm,â€�
              Scholarpedia, vol. 2, no. 5, p. 3043.
              urL: http://www.scholarpedia.org/article/Grassberger-Procaccia_algorithm

  Reference Code:
    .. [cd_a] "corrDim" function in R package "fractal",
              url: https://cran.r-project.org/web/packages/fractal/fractal.pdf
    .. [cd_b] Peng Yuehua, "Correlation dimension",
              url: http://de.mathworks.com/matlabcentral/fileexchange/24089-correlation-dimension

  Args:
    data (array-like of float):
      time series of data points
    emb_dim (int):
      embedding dimension
  Kwargs:
    rvals (iterable of float):
      list of values for to use for r
      (default: logarithmic_r(0.1 * std, 0.5 * std, 1.03))
    dist (function (2d-array, 1d-array) -> 1d-array):
      row-wise difference function
    fit (str):
      the fitting method to use for the line fit, either 'poly' for normal
      least squares polynomial fitting or 'RANSAC' for RANSAC-fitting which
      is more robust to outliers
    debug_plot (boolean):
      if True, a simple plot of the final line-fitting step will be shown
    debug_data (boolean):
      if True, debugging data will be returned alongside the result
    plot_file (str):
      if debug_plot is True and plot_file is not None, the plot will be saved
      under the given file name instead of directly showing it through
      ``plt.show()``

  Returns:
    float:
      correlation dimension as slope of the line fitted to log(r) vs log(C(r))
    (1d-vector, 1d-vector, list):
      only present if debug_data is True: debug data of the form
      ``(rvals, csums, poly)`` where ``rvals`` are the values used for log(r), 
      ``csums`` are the corresponding log(C(r)) and ``poly`` are the line 
      coefficients (``[slope, intercept]``)
  Nçš™™™™™¹?r‚   g{®Gázð?r   rl   c                    s   g | ]}ˆ ˆˆ| ƒ‘qS r   r   rC   ©r¡   rE   r   r   rF   O  s     zcorr_dim.<locals>.<listcomp>r>   r   rH   zlog(r)z	log(C(r))rJ   )r
   r"   rŽ   r½   r#   r4   rQ   rP   r   rs   rY   rÊ   r*   rZ   r[   )r-   r.   Zrvalsr¡   r&   r]   r^   r_   ÚsdrA   rc   Zcsumsrv   rÌ   rd   r   r   rÙ   r   Úcorr_dimð  s2    V

"
ÿrÛ   r   c	              	      sŒ  t  | ¡} t| ƒ}	|dkrt|	dkr4tdd|	 dƒ}n@|	dkrNdddd	d
dg}n&|	d |	d g}d}
t |
 |¡t¡ t|ƒdk rˆtdƒ‚t  	|¡dk ržtdƒ‚t  
|¡|	kr´tdƒ‚t  | t  | ¡ ¡‰g }|D ]þ‰ˆdksàt‚|�rt  ‡‡fdd„tdtˆƒˆ ˆd ƒD ƒ¡‰ n&ˆd|	|	ˆ  … ‰ ˆ  |	ˆ ˆf¡‰ t  ˆ¡‰‡ ‡‡‡fdd„ttˆ ƒƒD ƒ‰t  ˆ¡‰t  ‡‡fdd„ttˆ ƒƒD ƒ¡}t  t jˆ | d dd�ˆ ¡}t  |¡t|ƒ }| |¡ qÐt  |¡}t  |dk¡}t  |¡| }|| }t|ƒdk�rt jt jg}ntt  |¡t  |¡d|d�}|�r\tt  |¡t  |¡|dd|d� |�r€|d t  |¡t  |¡|ffS |d S dS )uÀ  
  Performs a detrended fluctuation analysis (DFA) on the given data

  Recommendations for parameter settings by Hardstone et al.:
    * nvals should be equally spaced on a logarithmic scale so that each window
      scale hase the same weight
    * min(nvals) < 4 does not make much sense as fitting a polynomial (even if
      it is only of order 1) to 3 or less data points is very prone.
    * max(nvals) > len(data) / 10 does not make much sense as we will then have
      less than 10 windows to calculate the average fluctuation
    * use overlap=True to obtain more windows and therefore better statistics
      (at an increased computational cost)

  Explanation of DFA:
    Detrended fluctuation analysis, much like the Hurst exponent, is used to
    find long-term statistical dependencies in time series.

    The idea behind DFA originates from the definition of self-affine
    processes. A process X is said to be self-affine if the standard deviation
    of the values within a window of length n changes with the window length
    factor L in a power law:

    std(X,L * n) = L^H * std(X, n)

    where std(X, k) is the standard deviation of the process X calculated over
    windows of size k. In this equation, H is called the Hurst parameter, which
    behaves indeed very similar to the Hurst exponent.

    Like the Hurst exponent, H can be obtained from a time series by
    calculating std(X,n) for different n and fitting a straight line to the
    plot of log(std(X,n)) versus log(n).

    To calculate a single std(X,n), the time series is split into windows of
    equal length n, so that the ith window of this size has the form

    W_(n,i) = [x_i, x_(i+1), x_(i+2), ... x_(i+n-1)]

    The value std(X,n) is then obtained by calculating std(W_(n,i)) for each i
    and averaging the obtained values over i.

    The aforementioned definition of self-affinity, however, assumes that the
    process is  non-stationary (i.e. that the standard deviation changes over
    time) and it is highly influenced by local and global trends of the time
    series.

    To overcome these problems, an estimate alpha of H is calculated by using a
    "walk" or "signal profile" instead of the raw time series. This walk is
    obtained by substracting the mean and then taking the cumulative sum of the
    original time series. The local trends are removed for each window
    separately by fitting a polynomial p_(n,i) to the window W_(n,i) and then
    calculating W'_(n,i) = W_(n,i) - p_(n,i) (element-wise substraction).

    We then calculate std(X,n) as before only using the "detrended" window
    W'_(n,i) instead of W_(n,i). Instead of H we obtain the parameter alpha
    from the line fitting.

    For alpha < 1 the underlying process is stationary and can be modelled as
    fractional Gaussian noise with H = alpha. This means for alpha = 0.5 we
    have no correlation or "memory", for 0.5 < alpha < 1 we have a memory with
    positive correlation and for alpha < 0.5 the correlation is negative.

    For alpha > 1 the underlying process is non-stationary and can be modeled
    as fractional Brownian motion with H = alpha - 1.

  References:
    .. [dfa_1] C.-K. Peng, S. V. Buldyrev, S. Havlin, M. Simons,
               H. E. Stanley, and A. L. Goldberger, â€œMosaic organization of
               DNA nucleotides,â€� Physical Review E, vol. 49, no. 2, 1994.
    .. [dfa_2] R. Hardstone, S.-S. Poil, G. Schiavone, R. Jansen,
               V. V. Nikulin, H. D. Mansvelder, and K. Linkenkaer-Hansen,
               â€œDetrended fluctuation analysis: A scale-free view on neuronal
               oscillations,â€� Frontiers in Physiology, vol. 30, 2012.

  Reference code:
    .. [dfa_a] Peter Jurica, "Introduction to MDFA in Python",
       url: http://bsp.brain.riken.jp/~juricap/mdfa/mdfaintro.html
    .. [dfa_b] JE Mietus, "dfa",
       url: https://www.physionet.org/physiotools/dfa/dfa-1.htm
    .. [dfa_c] "DFA" function in R package "fractal"

  Args:
    data (array-like of float):
      time series
  Kwargs:
    nvals (iterable of int):
      subseries sizes at which to calculate fluctuation
      (default: logarithmic_n(4, 0.1*len(data), 1.2))
    overlap (boolean):
      if True, the windows W_(n,i) will have a 50% overlap,
      otherwise non-overlapping windows will be used
    order (int):
      (polynomial) order of trend to remove
    fit_trend (str):
      the fitting method to use for fitting the trends, either 'poly'
      for normal least squares polynomial fitting or 'RANSAC' for
      RANSAC-fitting which is more robust to outliers but also tends to
      lead to unstable results
    fit_exp (str):
      the fitting method to use for the line fit, either 'poly' for normal
      least squares polynomial fitting or 'RANSAC' for RANSAC-fitting which
      is more robust to outliers
    debug_plot (boolean):
      if True, a simple plot of the final line-fitting step will be shown
    debug_data (boolean):
      if True, debugging data will be returned alongside the result
    plot_file (str):
      if debug_plot is True and plot_file is not None, the plot will be saved
      under the given file name instead of directly showing it through
      ``plt.show()``
  Returns:
    float:
      the estimate alpha for the Hurst parameter (alpha < 1: stationary
      process similar to fractional Gaussian noise with H = alpha,
      alpha > 1: non-stationary process similar to fractional Brownian
      motion with H = alpha - 1)
    (1d-vector, 1d-vector, list):
      only present if debug_data is True: debug data of the form
      ``(nvals, fluctuations, poly)`` where ``nvals`` are the values used for
      log(n), ``fluctuations`` are the corresponding log(std(X,n)) and ``poly``
      are the line coefficients (``[slope, intercept]``)
  NéF   rk   rØ   g333333ó?r9   é   é   é   é   é	   r   r   zPchoosing nvals = {} , DFA with less than ten data points is extremely unreliablezat least two nvals are neededznvals must be at least twoz*nvals cannot be larger than the input sizec                    s   g | ]}ˆ||ˆ  … ‘qS r   r   rC   )rA   Úwalkr   r   rF   ü  s     zdfa.<locals>.<listcomp>r   c                    s    g | ]}t ˆˆ | ˆˆd �‘qS )rH   )r*   rC   )ÚdÚ	fit_trendÚorderr   r   r   rF     s   ÿc                    s   g | ]}t  ˆ | ˆ¡‘qS r   )r
   rÑ   rC   )Útpolyr   r   r   rF     s     r   rH   rÕ   zstd(X,n)rJ   )r
   r"   r#   r¯   r   r    r(   r!   r'   ro   r   rÉ   rL   rV   rQ   rP   r%   r,   r   r   rs   rY   rÊ   r*   rZ   r[   )r-   rº   Zoverlaprå   rä   Zfit_expr]   r^   r_   r¦   r1   ZfluctuationsZtrendZflucsZf_nrd   r   r   )rã   rä   rA   rå   ræ   râ   r   r   Údfaf  sb    {
0

ÿ
" 
ÿÿrç   )r   )r   )r9   NNr   r:   r:   r   FFNr   )r9   rk   Nr   r   FFN)NN)r{   )r=   r°   )r   )T)N)r   r   r-   rÐ   N)Nr   FFNTT)NTr   r   r   FFN) Ú
__future__r   r   r   r   ÚbuiltinsÚnumpyr
   r   r¾   r   r   r*   r4   r8   rg   rj   ry   rŸ   r£   rª   r¯   r»   r½   rÄ   rÈ   rÍ   rt   r[   r×   rÛ   rç   r   r   r   r   Ú<module>   s~   
(
           þ
 m      ÿ
  
  ÿ
q
!
%

7
    ÿ
*        ÿ
 C   ÿ
v        ÿ