U
    g»{j¼O  ã                
   @   sæ  d Z ddlmZmZ ddlmZ ddlZddlZddl	m
Z
 ddl	mZ ddlmZ dd	d
dddgZdZdZedddgƒZedddgƒZedddgƒZd1ee eedœdd„Zee edœdd
„Zeddeddƒeddƒeddƒfee eeeeeeed œd!d	„Zeddeddƒeddƒfee eeeeeed"œd#d$„Zee ee dœd%d&„Zd2ee eee d(œd)d*„Zeddƒeddƒeddƒfee ee eeeed+œd,d-„Zee edœd.d„Z ee edœd/d„Z!ee edœd0d„Z"dS )3z~This script provides several methods to extract features from Normal to Normal Intervals
 for heart rate variability analysis.é    )ÚListÚTuple)Ú
namedtupleN)Úinterpolate)Úsignal)ÚLombScargleÚget_time_domain_featuresÚget_frequency_domain_featuresÚget_geometrical_featuresÚget_poincare_plot_featuresÚget_csi_cvi_featuresÚ
get_sampenÚwelchZlombZVlf_bandÚlowÚhighZLf_bandZHf_bandT)Únn_intervalsÚpnni_as_percentÚreturnc                 C   s  t  | ¡}|rt| ƒd nt| ƒ}t  | ¡}t  | ¡}t| ƒt| ƒ }t  |¡}t  t  |d ¡¡}t	t  
|¡dkƒ}	d|	 | }
t	t  
|¡dkƒ}d| | }|| }t j| dd�}|| }t  d| ¡}t  |¡}t|ƒ}t|ƒ}t  |¡}||||	|
|||||||||||dœ}|S )	a
  
    Returns a dictionary containing time domain features for HRV analysis.
    Mostly used on long term recordings (24h) but some studies use some of those features on
    short term recordings, from 1 to 5 minutes window.

    Parameters
    ----------
    nn_intervals : list
        list of Normal to Normal Interval
    pnni_as_percent: bool
        whether to remove bias or not to compute pnni features.

    Returns
    -------
    time_domain_features : dict
        dictionary containing time domain features for HRV analyses. There are details
        about each features below.

    Notes
    -----
    Here are some details about feature engineering...

    - **mean_nni**: The mean of RR-intervals.

    - **sdnn** : The standard deviation of the time interval between successive normal heart beats     (i.e. the RR-intervals).

    - **sdsd**: The standard deviation of differences between adjacent RR-intervals

    - **rmssd**: The square root of the mean of the sum of the squares of differences between     adjacent NN-intervals. Reflects high frequency (fast or parasympathetic) influences on hrV     (*i.e.*, those influencing larger changes from one beat to the next).

    - **median_nni**: Median Absolute values of the successive differences between the RR-intervals.

    - **nni_50**: Number of interval differences of successive RR-intervals greater than 50 ms.

    - **pnni_50**: The proportion derived by dividing nni_50 (The number of interval differences     of successive RR-intervals greater than 50 ms) by the total number of RR-intervals.

    - **nni_20**: Number of interval differences of successive RR-intervals greater than 20 ms.

    - **pnni_20**: The proportion derived by dividing nni_20 (The number of interval differences     of successive RR-intervals greater than 20 ms) by the total number of RR-intervals.

    - **range_nni**: difference between the maximum and minimum nn_interval.

    - **cvsd**: Coefficient of variation of successive differences equal to the rmssd divided by     mean_nni.

    - **cvnni**: Coefficient of variation equal to the ratio of sdnn divided by mean_nni.

    - **mean_hr**: The mean Heart Rate.

    - **max_hr**: Max heart rate.

    - **min_hr**: Min heart rate.

    - **std_hr**: Standard deviation of heart rate.

    References
    ----------
    .. [1] Heart rate variability - Standards of measurement, physiological interpretation, and     clinical use, Task Force of The European Society of Cardiology and The North American Society     of Pacing and Electrophysiology, 1996
    é   é   é2   éd   é   ©Zddofi`ê  )Úmean_nniÚsdnnÚsdsdÚnni_50Úpnni_50Únni_20Úpnni_20ÚrmssdÚ
median_nniÚ	range_nniÚcvsdÚcvnniÚmean_hrÚmax_hrÚmin_hrÚstd_hr)ÚnpÚdiffÚlenÚmeanZmedianÚmaxÚminÚstdÚsqrtÚsumÚabsÚdivide)r   r   Zdiff_nniZ
length_intr   r"   r#   r   r!   r   r   r   r    r$   r   r%   Zheart_rate_listr&   r(   r'   r)   Ztime_domain_features© r5   ú[/var/www/html/bwave/python/venv/lib/python3.8/site-packages/hrvanalysis/extract_features.pyr      sJ    D





ð)r   r   c                 C   s8   t | ƒttj| tdddƒd�d ƒ }d}||dœ}|S )aÆ  
    Returns a dictionary containing geometrical time domain features for HRV analyses.
    Known practise is to use this function on recordings from 20 minutes to 24 Hours window.

    Parameters
    ---------
    nn_intervals : list
        list of Normal to Normal Interval.

    Returns
    ---------
    geometrical_features : dict
        Dictionary containing geometrical time domain features for HRV analyses.
        There are details about each features below.

    Notes
    ----------
    Details about feature engineering...

    - **triangular_index**: The HRV triangular index measurement is the integral of the density     distribution (= the number of all NN-intervals) divided by the maximum of the density     distribution.

    - **tinn**: The triangular interpolation of NN-interval histogram (TINN) is the baseline width      of the distribution measured as a base of a triangle, approximating the NN-interval      distribution

    References
    ----------
    .. [1] Heart rate variability - Standards of measurement, physiological interpretation, and     clinical use, Task Force of The European Society of Cardiology and The North American Society     of Pacing and Electrophysiology, 1996

    i,  iÐ  é   )Zbinsr   N)Ztriangular_indexÚtinn)r,   r.   r*   Z	histogramÚrange)r   Z
triang_idxr8   Zgeometrical_featuresr5   r5   r6   r
   —   s    $&þé   Zlineargú~j¼t“h?g{®Gáz¤?g333333Ã?gš™™™™™Ù?)r   ÚmethodÚsampling_frequencyÚinterpolation_methodÚvlf_bandÚlf_bandÚhf_bandr   c           
      C   s6   t | ƒ} t| |||||d�\}}t|||||d�}	|	S )a,  
    Returns a dictionary containing frequency domain features for HRV analyses.
    To our knowledge, you might use this function on short term recordings, from 2 to 5 minutes      window.

    Parameters
    ---------
    nn_intervals : list
        list of Normal to Normal Interval
    method : str
        Method used to calculate the psd. Choice are Welch's FFT or Lomb method.
    sampling_frequency : int
        Frequency at which the signal is sampled. Common value range from 1 Hz to 10 Hz,
        by default set to 4 Hz. No need to specify if Lomb method is used.
    interpolation_method : str
        kind of interpolation as a string, by default "linear". No need to specify if Lomb
        method is used.
    vlf_band : tuple
        Very low frequency bands for features extraction from power spectral density.
    lf_band : tuple
        Low frequency bands for features extraction from power spectral density.
    hf_band : tuple
        High frequency bands for features extraction from power spectral density.

    Returns
    ---------
    frequency_domain_features : dict
        Dictionary containing frequency domain features for HRV analyses. There are details
        about each features below.

    Notes
    ---------
    Details about feature engineering...

    - **total_power** : Total power density spectral

    - **vlf** : variance ( = power ) in HRV in the Very low Frequency (.003 to .04 Hz by default).     Reflect an intrinsic rhythm produced by the heart which is modulated primarily by sympathetic     activity.

    - **lf** : variance ( = power ) in HRV in the low Frequency (.04 to .15 Hz). Reflects a     mixture of sympathetic and parasympathetic activity, but in long-term recordings, it reflects     sympathetic activity and can be reduced by the beta-adrenergic antagonist propanolol.

    - **hf**: variance ( = power ) in HRV in the High Frequency (.15 to .40 Hz by default).     Reflects fast changes in beat-to-beat variability due to parasympathetic (vagal) activity.     Sometimes called the respiratory band because it corresponds to HRV changes related to the     respiratory cycle and can be increased by slow, deep breathing (about 6 or 7 breaths per     minute) and decreased by anticholinergic drugs or vagal blockade.

    - **lf_hf_ratio** : lf/hf ratio is sometimes used by some investigators as a quantitative     mirror of the sympatho/vagal balance.

    - **lfnu** : normalized lf power.

    - **hfnu** : normalized hf power.

    References
    ----------
    .. [1] Heart rate variability - Standards of measurement, physiological interpretation, and     clinical use, Task Force of The European Society of Cardiology and The North American Society     of Pacing and Electrophysiology, 1996

    .. [2] Signal Processing Methods for Heart Rate Variability - Gari D. Clifford, 2002

    )r   r;   r<   r=   r>   r@   )ÚfreqÚpsdr>   r?   r@   )ÚlistÚ_get_freq_psd_from_nn_intervalsÚ_get_features_from_psd)
r   r;   r<   r=   r>   r?   r@   rA   rB   Zfrequency_domain_featuresr5   r5   r6   r	   Ê   s    J ý
ý)r   r;   r<   r=   r>   r@   r   c                 C   s–   t | ƒ}|tkrXtj|| |d�}t| |ƒ}||ƒ}	|	t |	¡ }
tj|
|ddd�\}}n6|t	kr†t
|| dd�j|d |d d	�\}}ntd
ƒ‚||fS )a¹  
    Returns the frequency and power of the signal.

    Parameters
    ---------
    nn_intervals : list
        list of Normal to Normal Interval
    method : str
        Method used to calculate the psd. Choice are Welch's FFT or Lomb method.
    sampling_frequency : int
        Frequency at which the signal is sampled. Common value range from 1 Hz to 10 Hz,
        by default set to 7 Hz. No need to specify if Lomb method is used.
    interpolation_method : str
        Kind of interpolation as a string, by default "linear". No need to specify if Lomb
        method is used.
    vlf_band : tuple
        Very low frequency bands for features extraction from power spectral density.
    hf_band : tuple
        High frequency bands for features extraction from power spectral density.

    Returns
    ---------
    freq : list
        Frequency of the corresponding psd points.
    psd : list
        Power Spectral Density of the signal.
    )ÚxÚyÚkindZhanni   )rF   ÚfsZwindowZnfftrB   )Znormalizationr   r   )Zminimum_frequencyZmaximum_frequencyz5Not a valid method. Choose between 'lomb' and 'welch')Ú_create_timestamp_listÚWELCH_METHODr   Zinterp1dÚ#_create_interpolated_timestamp_listr*   r-   r   r   ÚLOMB_METHODr   Z	autopowerÚ
ValueError)r   r;   r<   r=   r>   r@   Ztimestamp_listZfunctZtimestamps_interpolationZnni_interpolationZnni_normalizedrA   rB   r5   r5   r6   rD   %  s$    !

ÿÿþrD   c                 C   s   t  | ¡d }||d  S )a#  
    Creates corresponding time interval for all nn_intervals

    Parameters
    ---------
    nn_intervals : list
        List of Normal to Normal Interval.

    Returns
    ---------
    nni_tmstp : list
        list of time intervals between first NN-interval and final NN-interval.
    iè  r   )r*   Zcumsum)r   Z	nni_tmstpr5   r5   r6   rJ   `  s    rJ   é   )r   r<   r   c                 C   s&   t | ƒ}t d|d dt|ƒ ¡}|S )a_  
    Creates the interpolation time used for Fourier transform's method

    Parameters
    ---------
    nn_intervals : list
        List of Normal to Normal Interval.
    sampling_frequency : int
        Frequency at which the signal is sampled.

    Returns
    ---------
    nni_interpolation_tmstp : list
        Timestamp for interpolation.
    r   éÿÿÿÿr   )rJ   r*   ZarangeÚfloat)r   r<   Ztime_nniZnni_interpolation_tmstpr5   r5   r6   rL   u  s    rL   )rA   rB   r>   r?   r@   r   c                 C   sâ   t  | |d k| |d k ¡}t  | |d k| |d k ¡}t  | |d k| |d k ¡}t j|| | | d�}t j|| | | d�}	t j|| | | d�}
|
| |	 }||	 }|||	  d }|	||	  d }||	|||||
dœ}|S )aâ  
    Computes frequency domain features from the power spectral decomposition.

    Parameters
    ---------
    freq : array
        Array of sample frequencies.
    psd : list
        Power spectral density or power spectrum.
    vlf_band : tuple
        Very low frequency bands for features extraction from power spectral density.
    lf_band : tuple
        Low frequency bands for features extraction from power spectral density.
    hf_band : tuple
        High frequency bands for features extraction from power spectral density.

    Returns
    ---------
    freqency_domain_features : dict
        Dictionary containing frequency domain features for HRV analyses. There are details
        about each features given below.
    r   r   )rG   rF   r   )ÚlfÚhfÚlf_hf_ratioÚlfnuÚhfnuÚtotal_powerÚvlf)r*   Úlogical_andZtrapz)rA   rB   r>   r?   r@   Zvlf_indexesZ
lf_indexesZ
hf_indexesrR   rS   rX   rW   rT   rU   rV   Zfreqency_domain_featuresr5   r5   r6   rE   ‹  s&    ù
rE   c                 C   sR   t | ƒ}d|d  }d|d  }|| }t || ¡}|d | }|||dœ}|S )aˆ  
    Returns a dictionary containing 3 features from non linear domain for HRV analyses.
    Known practise is to use this function on short term recordings, on 30 , 50, 100 RR-intervals (or
    seconds) window.

    Parameters
    ---------
    nn_intervals : list
        Normal to Normal Intervals.

    Returns
    ---------
    csi_cvi_features : dict
        Dictionary containing non linear domain features for hrV analyses. There are  details about
        each features are given below.

    Notes
    ---------
    - **csi** : Cardiac Sympathetic Index.

    - **cvi** : Cadiac Vagal Index.

    - **Modified_csi** : Modified CSI is an alternative measure in research of seizure detection.

    References
    ----------
    .. [3] Using Lorenz plot and Cardiac Sympathetic Index of heart rate variability for detecting     seizures for patients with epilepsy, Jesper Jeppesen et al, 2014

    r:   Úsd1Úsd2r   )ÚcsiÚcviZModified_csi)r   r*   Úlog10)r   Úpoincare_plot_featuresÚTÚLr\   r]   Zmodified_csiZcsi_cvi_featuresr5   r5   r6   r   Æ  s    !ýc                 C   sp   t  | ¡}t  t j|dd�d d ¡}t  dt j| dd�d  dt j|dd�d   ¡}|| }|||dœ}|S )u  
    Function returning a dictionary containing 3 features from non linear domain
    for HRV analyses.
    Known practise is to use this function on short term recordings, from 5 minutes window.

    Parameters
    ---------
    nn_intervals : list
        Normal to Normal Interval

    Returns
    ---------
    poincare_plot_features : dict
        Dictionary containing non linear domain features for hrV analyses. There
        are details about each features are given below.

    Notes
    ---------
    - **sd1** : The standard deviation of projection of the PoincareÌ� plot on the line     perpendicular to the line of identity.

    - **sd2** : SD2 is defined as the standard deviation of the projection of the PoincareÌ�     plot on the line of identity (y=x).

    - **ratio_sd2_sd1** : Ratio between SD2 and SD1.

    References
    ----------
    .. [4] Pre-ictal heart rate variability assessment of epileptic seizures by means of linear     and non- linear analyses, Soroor Behbahani, Nader Jafarnia Dabanloo et al - 2013

    r   r   r   g      à?)rZ   r[   Úratio_sd2_sd1)r*   r+   r1   r0   )r   Zdiff_nn_intervalsrZ   r[   rb   r_   r5   r5   r6   r   ø  s    !
2ýc                 C   s   t j| dd�}d|iS )aè  
    Function computing the sample entropy of the given data.
    Must use this function on short term recordings, from 1 minute window.

    Parameters
    ---------
    nn_intervals : list
        Normal to Normal Interval

    Returns
    ---------
    sampen : float
        The sample entropy of the data

    References
    ----------
    .. [5] Physiological time-series analysis using approximate entropy and sample entropy,     JOSHUA S. RICHMAN1, J. RANDALL MOORMAN - 2000

    r   )Zemb_dimÚsampen)Únoldsrc   )r   rc   r5   r5   r6   r   )  s    )T)rO   )#Ú__doc__Útypingr   r   Úcollectionsr   Únumpyr*   rd   Zscipyr   r   Zastropy.statsr   Ú__all__rK   rM   ZVlfBandZLfBandZHfBandrQ   ÚboolÚdictr   r
   ÚstrÚintr	   rD   rJ   rL   rE   r   r   r   r5   r5   r5   r6   Ú<module>   sv     þx3 ü
  ü[ü
 ü;þ þ;21