U
    QvfB8                     @   sT   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gZ
dd	dZdddZdS )    N)f)options)_postprocess_dataframecronbach_alphaintraclass_corrpairwiseffffff?c                    s^  t  tjstd|dks ttdd |||fD rH j|||d  j\}}|dksbtd|dksrtdd	}t fd
d jD st|  	 	 r|dkr j
ddd  jdd}	||d  dt|	|	     }
d| }|d }||d  }dd|
 t|d ||  }dd|
 td|d  ||  }|
t||gdfS )aG  Cronbach's alpha reliability measure.

    Parameters
    ----------
    data : :py:class:`pandas.DataFrame`
        Wide or long-format dataframe.
    items : str
        Column in ``data`` with the items names (long-format only).
    scores : str
        Column in ``data`` with the scores (long-format only).
    subject : str
        Column in ``data`` with the subject identifier (long-format only).
    nan_policy : bool
        If `'listwise'`, remove the entire rows that contain missing values
        (= listwise deletion). If `'pairwise'` (default), only pairwise
        missing values are removed when computing the covariance matrix.
        For more details, please refer to the :py:meth:`pandas.DataFrame.cov`
        method.
    ci : float
        Confidence interval (.95 = 95%)

    Returns
    -------
    alpha : float
        Cronbach's alpha

    Notes
    -----
    This function works with both wide and long format dataframe. If you pass a
    long-format dataframe, you must also pass the ``items``, ``scores`` and
    ``subj`` columns (in which case the data will be converted into wide
    format using the :py:meth:`pandas.DataFrame.pivot` method).

    Internal consistency is usually measured with Cronbach's alpha [1]_,
    a statistic calculated from the pairwise correlations between items.
    Internal consistency ranges between negative infinity and one.
    Coefficient alpha will be negative whenever there is greater
    within-subject variability than between-subject variability.

    Cronbach's :math:`\alpha` is defined as

    .. math::

        \alpha ={k \over k-1}\left(1-{\sum_{{i=1}}^{k}\sigma_{{y_{i}}}^{2}
        \over\sigma_{x}^{2}}\right)

    where :math:`k` refers to the number of items, :math:`\sigma_{x}^{2}`
    is the variance of the observed total scores, and
    :math:`\sigma_{{y_{i}}}^{2}` the variance of component :math:`i` for
    the current sample of subjects.

    Another formula for Cronbach's :math:`\alpha` is

    .. math::

        \alpha = \frac{k \times \bar c}{\bar v + (k - 1) \times \bar c}

    where :math:`\bar c` refers to the average of all covariances between
    items and :math:`\bar v` to the average variance of each item.

    95% confidence intervals are calculated using Feldt's method [2]_:

    .. math::

        c_L = 1 - (1 - \alpha) \cdot F_{(0.025, n-1, (n-1)(k-1))}

        c_U = 1 - (1 - \alpha) \cdot F_{(0.975, n-1, (n-1)(k-1))}

    where :math:`n` is the number of subjects and :math:`k` the number of
    items.

    Results have been tested against the `psych
    <https://cran.r-project.org/web/packages/psych/psych.pdf>`_ R package.

    References
    ----------
    .. [1] http://www.real-statistics.com/reliability/cronbachs-alpha/

    .. [2] Feldt, Leonard S., Woodruff, David J., & Salih, Fathi A. (1987).
           Statistical inference for coefficient alpha. Applied Psychological
           Measurement, 11(1):93-103.

    Examples
    --------
    Binary wide-format dataframe (with missing values)

    >>> import pingouin as pg
    >>> data = pg.read_dataset('cronbach_wide_missing')
    >>> # In R: psych:alpha(data, use="pairwise")
    >>> pg.cronbach_alpha(data=data)
    (0.732660835214447, array([0.435, 0.909]))

    After listwise deletion of missing values (remove the entire rows)

    >>> # In R: psych:alpha(data, use="complete.obs")
    >>> pg.cronbach_alpha(data=data, nan_policy='listwise')
    (0.8016949152542373, array([0.581, 0.933]))

    After imputing the missing values with the median of each column

    >>> pg.cronbach_alpha(data=data.fillna(data.median()))
    (0.7380191693290734, array([0.447, 0.911]))

    Likert-type long-format dataframe

    >>> data = pg.read_dataset('cronbach_alpha')
    >>> pg.cronbach_alpha(data=data, items='Items', scores='Scores',
    ...                   subject='Subj')
    (0.5917188485995826, array([0.195, 0.84 ]))
    data must be a dataframe.)r   listwisec                 S   s   g | ]}|d k	qS N .0vr   r   8/tmp/pip-unpacked-wheel-2te3nxqf/pingouin/reliability.py
<listcomp>   s     z"cronbach_alpha.<locals>.<listcomp>)indexvaluescolumns   z At least two items are required.z*At least two raters/subjects are required.zAll columns must be numeric.c                    s   g | ]} | j jd kqS )bfiu)dtypekind)r   cdatar   r   r      s     r
   r   anyZaxishowT)Znumeric_only      )
isinstancepd	DataFrameAssertionErrorallZpivotshaper   isnar   dropnaZcovnptracesumr   Zisfround)r   itemsZscoressubject
nan_policycinkerrCZcronbachalphadf1df2lowerupperr   r   r   r      s&    r
 &"raisec           /         s>  ddl m} t tjs tdtdd |||fD s<tt fdd|||fD s\t|dksht j|||dd	   	 	 }|r|d
kr j
ddd ntd  j||d  | jjdkstd |  } |  }tjdd4 t }	dtd< | |||gdd}
t|	 W 5 Q R X |
jd }|
jd |
jd  |
jd |
jd   }|
jd }|
jd }|| ||d |   }|| ||d |  |||  |   }|| ||d |   }|| | }|| ||| |   }|| | }|| }|d }||d  }t|||}||  }}|d |d  }t|||}dd d!d"d#d$gd%d&d'd(d)d*g||||||g||||||g|d ||||||g||||||gd+}t|}d,}|td|d  || }|td|d  || } |d ||d   }!| d | |d   }"|td|d  || }#|td|d  || }$|#d |#|d   }%|$d |$|d   }&|| }'||| |' |d|d |    ||  d  }(||d  |d  |'d  |d|d |   ||  d  })|(|) }*td|d  |d |*}+td|d  |*|d },|||+|   |+|| || | | |   ||   }-||,| |  || || | | |  ||, |   }.t|!|"gt|-|.gt|%|&gtdd|  dd|   gt|-| d|-|d    |.| d|.|d    gtdd|#  dd|$  gg|d-< t|S ).a  Intraclass correlation.

    Parameters
    ----------
    data : :py:class:`pandas.DataFrame`
        Long-format dataframe. Data must be fully balanced.
    targets : string
        Name of column in ``data`` containing the targets.
    raters : string
        Name of column in ``data`` containing the raters.
    ratings : string
        Name of column in ``data`` containing the ratings.
    nan_policy : str
        Defines how to handle when input contains missing values (nan).
        `'raise'` (default) throws an error, `'omit'` performs the calculations
        after deleting target(s) with one or more missing values (= listwise
        deletion).

        .. versionadded:: 0.3.0

    Returns
    -------
    stats : :py:class:`pandas.DataFrame`
        Output dataframe:

        * ``'Type'``: ICC type
        * ``'Description'``: description of the ICC
        * ``'ICC'``: intraclass correlation
        * ``'F'``: F statistic
        * ``'df1'``: numerator degree of freedom
        * ``'df2'``: denominator degree of freedom
        * ``'pval'``: p-value
        * ``'CI95%'``: 95% confidence intervals around the ICC

    Notes
    -----
    The intraclass correlation (ICC, [1]_) assesses the reliability of ratings
    by comparing the variability of different ratings of the same subject to
    the total variation across all ratings and all subjects.

    Shrout and Fleiss (1979) [2]_ describe six cases of reliability of ratings
    done by :math:`k` raters on :math:`n` targets. Pingouin returns all six
    cases with corresponding F and p-values, as well as 95% confidence
    intervals.

    From the documentation of the ICC function in the `psych
    <https://cran.r-project.org/web/packages/psych/psych.pdf>`_ R package:

    - **ICC1**: Each target is rated by a different rater and the raters are
      selected at random. This is a one-way ANOVA fixed effects model.

    - **ICC2**: A random sample of :math:`k` raters rate each target. The
      measure is one of absolute agreement in the ratings. ICC1 is sensitive
      to differences in means between raters and is a measure of absolute
      agreement.

    - **ICC3**: A fixed set of :math:`k` raters rate each target. There is no
      generalization to a larger population of raters. ICC2 and ICC3 remove
      mean differences between raters, but are sensitive to interactions.
      The difference between ICC2 and ICC3 is whether raters are seen as fixed
      or random effects.

    Then, for each of these cases, the reliability can either be estimated for
    a single rating or for the average of :math:`k` ratings. The 1 rating case
    is equivalent to the average intercorrelation, while the :math:`k` rating
    case is equivalent to the Spearman Brown adjusted reliability.
    **ICC1k**, **ICC2k**, **ICC3K** reflect the means of :math:`k` raters.

    This function has been tested against the ICC function of the R psych
    package. Note however that contrarily to the R implementation, the
    current implementation does not use linear mixed effect but regular ANOVA,
    which means that it only works with complete-case data (no missing values).

    References
    ----------
    .. [1] http://www.real-statistics.com/reliability/intraclass-correlation/

    .. [2] Shrout, P. E., & Fleiss, J. L. (1979). Intraclass correlations:
           uses in assessing rater reliability. Psychological bulletin, 86(2),
           420.

    Examples
    --------
    ICCs of wine quality assessed by 4 judges.

    >>> import pingouin as pg
    >>> data = pg.read_dataset('icc')
    >>> icc = pg.intraclass_corr(data=data, targets='Wine', raters='Judge',
    ...                          ratings='Scores').round(3)
    >>> icc.set_index("Type")
                       Description    ICC       F  df1  df2  pval         CI95%
    Type
    ICC1    Single raters absolute  0.728  11.680    7   24   0.0  [0.43, 0.93]
    ICC2      Single random raters  0.728  11.787    7   21   0.0  [0.43, 0.93]
    ICC3       Single fixed raters  0.729  11.787    7   21   0.0  [0.43, 0.93]
    ICC1k  Average raters absolute  0.914  11.680    7   24   0.0  [0.75, 0.98]
    ICC2k    Average random raters  0.914  11.787    7   21   0.0  [0.75, 0.98]
    ICC3k     Average fixed raters  0.915  11.787    7   21   0.0  [0.75, 0.98]
    r   )anovar	   c                 S   s   g | ]}|d k	qS r   r   r   r   r   r   r     s     z#intraclass_corr.<locals>.<listcomp>c                    s   g | ]}| j kqS r   )r   r   r   r   r   r     s     )omitr:   T)r   r   r   Zobservedr<   r   r   zwEither missing values are present in data or data are unbalanced. Please remove them manually or use nan_policy='omit'.)Zid_varsZ
value_namer   zRatings must be numeric.ignore)invalidNr,   r   )r   ZdvZbetweenZss_type)r   MS)r   SS)r   r@   )r   DF)r   rA   )r   r?   )r   r?   r   ZICC1ZICC2ZICC3ZICC1kZICC2kZICC3kzSingle raters absolutezSingle random raterszSingle fixed raterszAverage raters absolutezAverage random raterszAverage fixed raters)TypeDescriptionZICCFr6   r7   Zpvalg?zCI95%)Zpingouinr;   r!   r"   r#   r$   r%   Zpivot_tabler'   r   r(   
ValueErrorZreset_indexZmeltr   r   Znuniquer)   Zerrstater   copyupdateatr   ZsfZppfarrayr   )/r   targetsZratersZratingsr/   r;   Znan_presentr2   r1   Zold_optionsZaovZmsbZmswZmsjZmseZicc1Zicc2Zicc3Zicc1kZicc2kZicc3kZf1kr6   Zdf1kdZp1kZf2kZf3kZdf2kdZp2kstatsr5   Zf1lZf1ul1u1Zf3lZf3ul3u3fjZvnZvdr   Zf2uZf2ll2u2r   r   r   r      s    d 
(

(
0<884	)NNNNr   r   )NNNNr:   )Znumpyr)   Zpandasr"   Zscipy.statsr   Zpingouin.configr   Zpingouin.utilsr   __all__r   r   r   r   r   r   <module>   s              
 