U
    g»{jH4  ã                   @   sF  d Z ddlmZ ddlmZ ddlZddlZdZdZ	dZ
dZd	Zd
dddgZd)ee eeeedœdd
„Zd*ee eeeedœdd„Zd+eeeeedœdd„Zd,ee eeeef dœdd„Zd-ee eeef dœdd„Zd.eeeeed!œd"d„Zdddd de
dfee eeeeeeeee d#œ	d$d„Zd/ee eeed&œd'd(„ZdS )0zPThis script provides several methods to clean abnormal and ectopic RR-intervals.é    )ÚTuple)ÚListNÚmalikZkarlssonZkamathZacarZcustomÚremove_outliersÚremove_ectopic_beatsÚinterpolate_nan_valuesÚget_nn_intervalsTé,  éÐ  )Úrr_intervalsÚverboseÚlow_rriÚhigh_rriÚreturnc                    s�   ‡ ‡fdd„| D ƒ}|rŒg }| D ](}ˆ |  kr8ˆkr>qH nq |  |¡ q tt |¡ƒ}|dkrptd |¡ƒ ntd |¡ƒ td |¡ƒ |S )a'  
    Function that replace RR-interval outlier by nan.

    Parameters
    ---------
    rr_intervals : list
        raw signal extracted.
    low_rri : int
        lowest RrInterval to be considered plausible.
    high_rri : int
        highest RrInterval to be considered plausible.
    verbose : bool
        Print information about deleted outliers.

    Returns
    ---------
    rr_intervals_cleaned : list
        list of RR-intervals without outliers

    References
    ----------
    .. [1] O. Inbar, A. Oten, M. Scheinowitz, A. Rotstein, R. Dlin, R.Casaburi. Normal     cardiopulmonary responses during incremental exercise in 20-70-yr-old men.

    .. [2] W. C. Miller, J. P. Wallace, K. E. Eggert. Predicting max HR and the HR-VO2 relationship    for exercise prescription in obesity.

    .. [3] H. Tanaka, K. D. Monahan, D. R. Seals. Age-predictedmaximal heart rate revisited.

    .. [4] M. Gulati, L. J. Shaw, R. A. Thisted, H. R. Black, C. N. B.Merz, M. F. Arnsdorf. Heart     rate response to exercise stress testing in asymptomatic women.
    c                    s.   g | ]&}ˆ |  krˆkr$n n|nt j‘qS © )ÚnpÚnan)Ú.0Úrri©r   r   r   úX/var/www/html/bwave/python/venv/lib/python3.8/site-packages/hrvanalysis/preprocessing.pyÚ
<listcomp><   s     z#remove_outliers.<locals>.<listcomp>r   z {} outlier(s) have been deleted.z The outlier(s) value(s) are : {})ÚappendÚsumr   ÚisnanÚprintÚformat)r   r   r   r   Úrr_intervals_cleanedZoutliers_listr   Z	nan_countr   r   r   r      s    %çš™™™™™É?)r   ÚmethodÚcustom_removing_ruler   r   c           	      C   sð   |t ttttfkrtdƒ‚|tkr4t| |d�\}}n¤|tkrLt| d�\}}nŒd}d}| d g}t| dd… ƒD ]h\}}|r’| 	| |d  ¡ d}qnt
|| |d  ||d	�r¾| 	| |d  ¡ qn| 	tj¡ |d7 }d
}qn|rìtd ||¡ƒ |S )aN  
    RR-intervals differing by more than the removing_rule from the one proceeding it are removed.

    Parameters
    ---------
    rr_intervals : list
        list of RR-intervals
    method : str
        method to use to clean outlier. malik, kamath, karlsson, acar or custom.
    custom_removing_rule : int
        Percentage criteria of difference with previous RR-interval at which we consider
        that it is abnormal. If method is set to Karlsson, it is the percentage of difference
        between the absolute mean of previous and next RR-interval at which  to consider the beat
        as abnormal.
    verbose : bool
        Print information about ectopic beats.

    Returns
    ---------
    nn_intervals : list
        list of NN Interval
    outlier_count : int
        Count of outlier detected in RR-interval list

    References
    ----------
    .. [5] Kamath M.V., Fallen E.L.: Correction of the Heart Rate Variability Signal for Ectopics     and Miss- ing Beats, In: Malik M., Camm A.J.

    .. [6] Geometric Methods for Heart Rate Variability Assessment - Malik M et al
    zšNot a valid method. Please choose between malik, kamath, karlsson, acar.         You can also choose your own removing critera with custom_rule parameter.)r   Úremoving_rule)r   r   FNéÿÿÿÿé   )r   Úcustom_ruleTz2{} ectopic beat(s) have been deleted with {} rule.)Ú
MALIK_RULEÚKAMATH_RULEÚKARLSSON_RULEÚ	ACAR_RULEÚCUSTOM_RULEÚ
ValueErrorÚ_remove_outlier_karlssonÚ_remove_outlier_acarÚ	enumerater   Ú
is_outlierr   r   r   r   )	r   r   r    r   Únn_intervalsÚoutlier_countZprevious_outlierÚiÚrr_intervalr   r   r   r   O   s4    !ÿ
ÿ)r2   Únext_rr_intervalr   r$   r   c                 C   s€   |t krt| | ƒd|  k}n^|tkrhd||    ko@d|  kn  pdd| |   ko`d|  kn  }nt| | ƒ||  k}|S )aþ  
    Test if the rr_interval is an outlier

    Parameters
    ----------
    rr_interval : int
        RrInterval
    next_rr_interval : int
        consecutive RrInterval
    method : str
        method to use to clean outlier. malik, kamath, karlsson, acar or custom
    custom_rule : int
        percentage criteria of difference with previous RR-interval at which we consider
        that it is abnormal

    Returns
    ----------
    outlier : bool
        True if RrInterval is valid, False if not
    r   r   gÍÌÌÌÌÌÔ?g\�Âõ(\Ï?)r%   Úabsr&   )r2   r3   r   r$   Zoutlierr   r   r   r.   •   s    "ÿÿr.   )r   r!   r   c                 C   sª   | d g}d}t t| ƒƒD ]†}|t| ƒd krD| | |d  ¡  q¢| | | |d   d }t|| |d   ƒ|| k rŒ| | |d  ¡ q| tj¡ |d7 }q||fS )uÊ  
    RR-intervals differing by more than the 20 % of the mean of previous and next RR-interval
    are removed.

    Parameters
    ---------
    rr_intervals : list
        list of RR-intervals
    removing_rule : float
        Percentage of difference between the absolute mean of previous and next RR-interval at which     to consider the beat as abnormal.

    Returns
    ---------
    nn_intervals : list
        list of NN Interval

    References
    ----------
    .. [7]  Automatic filtering of outliers in RR-intervals before analysis of heart rate     variability in Holter recordings: a comparison with carefully edited data - Marcus Karlsson,     Rolf HÃ¶rnsten, Annika Rydberg and Urban Wiklund
    r   é   r#   )ÚrangeÚlenr   r4   r   r   )r   r!   r/   r0   r1   Zmean_prev_next_rrir   r   r   r+   µ   s    

r+   )r   r   c                 C   s|   g }d}t | ƒD ]b\}}|dk r,| |¡ qt |dd… ¡}t|| ƒ|| k r^| |¡ q| tj¡ |d7 }q||fS )aq  
    RR-intervals differing by more than the 20 % of the mean of last 9 RrIntervals
    are removed.

    Parameters
    ---------
    rr_intervals : list
        list of RR-intervals
    custom_rule : int
        percentage criteria of difference with mean of  9 previous RR-intervals at
        which we consider that RR-interval is abnormal. By default, set to 20 %

    Returns
    ---------
    nn_intervals : list
        list of NN Interval

    References
    ----------
    .. [8] Automatic ectopic beat elimination in short-term heart rate variability measurements     Acar B., Irina S., Hemingway H., Malik M.
    r   é	   i÷ÿÿÿNr#   )r-   r   r   Znanmeanr4   r   )r   r$   r/   r0   r1   r2   Zacar_rule_eltr   r   r   r,   ß   s    

r,   ÚlinearÚforward)r   Úinterpolation_methodÚ
limit_areaÚlimit_directionr   c                 C   s&   t  | ¡}|j||||d�}|j ¡ S )a`  
    Function that interpolate Nan values with linear interpolation

    Parameters
    ---------
    rr_intervals : list
        RrIntervals list.
    interpolation_method : str
        Method used to interpolate Nan values of series.
    limit_area: str
        If limit is specified, consecutive NaNs will be filled with this restriction.
    limit_direction: str
        If limit is specified, consecutive NaNs will be filled in this direction.
    limit: int
        TODO
    Returns
    ---------
    interpolated_rr_intervals : list
        new list with outliers replaced by interpolated values.
    )r   Úlimitr<   r=   )ÚpdZSeriesZinterpolateÚvaluesÚtolist)r   r;   r<   r=   r>   Zseries_rr_intervals_cleanedÚinterpolated_rr_intervalsr   r   r   r     s    
ý)	r   r   r   r<   r=   r;   Úectopic_beats_removal_methodr   r   c                 C   sB   t | |||d�}t||||d�}	t|	||d�}
t|
|||d�}|S )au  
    Function that computes NN Intervals from RR-intervals.

    Parameters
    ---------
    rr_intervals : list
        RrIntervals list.
    interpolation_method : str
        Method used to interpolate Nan values of series.
    ectopic_beats_removal_method : str
        method to use to clean outlier. malik, kamath, karlsson, acar or custom.
    low_rri : int
        lowest RrInterval to be considered plausible.
    high_rri : int
        highest RrInterval to be considered plausible.
    limit_area: str
        If limit is specified, consecutive NaNs will be filled with this restriction.
    limit_direction: str
        If limit is specified, consecutive NaNs will be filled in this direction.
    verbose : bool
        Print information about deleted outliers.

    Returns
    ---------
    interpolated_nn_intervals : list
        list of NN Interval interpolated
    )r   r   r   )r<   r=   )r   r   )r   r   r   )r   r   r   r<   r=   r;   rC   r   r   rB   r/   Zinterpolated_nn_intervalsr   r   r   r   '  s     ÿ ÿþ ÿç{®Gáz¤?)r/   r0   r!   r   c                 C   s<   d}|t | ƒ |kr tdƒ d}t | ƒdk r8tdƒ d}|S )a·  
    Test if the sample meet the condition to be used for analysis

    Parameters
    ----------
    nn_intervals : list
        list of Normal to Normal Interval
    outlier_count : int
        count of outliers or ectopic beats removed from the interval
    removing_rule : str
        rule to follow to determine whether the sample is valid or not

    Returns
    ----------
    bool
        True if sample is valid, False if not
    Tz>Too much outlier for analyses ! You should descard the sample.Féð   z-Not enough Heart beat for Nyquist criteria ! )r7   r   )r/   r0   r!   Úresultr   r   r   Úis_valid_sampleR  s    rG   )Tr	   r
   )r   r   T)r   r   )r   )r   )r9   Nr:   N)rD   )Ú__doc__Útypingr   r   Zpandasr?   Únumpyr   r%   r'   r&   r(   r)   Ú__all__ÚfloatÚboolÚintÚlistr   Ústrr   r.   r+   r,   r   r   rG   r   r   r   r   Ú<module>   sr     ÿ ÿ8    ÿ
  ÿF  ÿ ÿ  *'    üü"  ý   ý+