ó
áp7]c           @   sî  d  Z  d d l m Z d d l m Z d d l Z d d l m Z d d d d	 d
 d g Z	 d „  Z
 i d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d  6d! d" 6Z d d# d$ g d d% g d d& g d d' g d d( g d d) g d d* d+ d, d- g d d. d/ d0 d1 g d d2 g d  d3 d4 g d" g g Z e ƒ  Z xC e D]; Z e d5 e e d5 <x  e d6 D] Z e d5 e e <qgWqDWd7 d e e d8 „ Z d7 d9 e d: „ Z d7 d; e e d< „ Z d= d d> d? d@ „ Z d
 e f dA „  ƒ  YZ d S(B   sQ   Multiple Testing and P-Value Correction


Author: Josef Perktold
License: BSD-3

iÿÿÿÿ(   t   range(   t   OrderedDictN(   t   RegressionFDRt   fdrcorrectiont   fdrcorrection_twostaget	   local_fdrt   multipletestst   NullDistributionR   c         C   s*   t  |  ƒ } t j d | d ƒ t | ƒ S(   s2   no frills empirical cdf used in fdrcorrection
    i   (   t   lent   npt   aranget   float(   t   xt   nobs(    (    s:   lib/python2.7/site-packages/statsmodels/stats/multitest.pyt   _ecdf   s    t
   Bonferronit   bt   Sidakt   st   Holmt   hs
   Holm-Sidakt   hss   Simes-Hochbergt   sht   Hommelt   hos   FDR Benjamini-Hochbergt   fdr_bhs   FDR Benjamini-Yekutielit   fdr_bys   FDR 2-stage Benjamini-Hochbergt   fdr_tsbhs'   FDR 2-stage Benjamini-Krieger-Yekutielit	   fdr_tsbkys&   FDR adaptive Gavrilov-Benjamini-Sarkart   fdr_gbst   bonft
   bonferronit   sidakt   holms
   holm-sidaks   simes-hochbergt   hommelt   fdr_it   fdr_pt   fdrit   fdrpt   fdr_nt   fdr_ct   fdrnt   fdrcorrt   fdr_2sbht	   fdr_2sbkyt   fdr_twostagei    i   gš™™™™™©?c         C   s5  d d l  } t j |  ƒ }  | } | sK t j |  ƒ } t j |  | ƒ }  n  t |  ƒ } d t j d | d | ƒ }	 | t | ƒ }
 | j ƒ  d, k r¶ |  |
 k } |  t | ƒ } nû| j ƒ  d- k rñ |  |	 k } d t j d |  | ƒ } nÀ| j ƒ  d. k rÔd t j d | d t j	 | d d ƒ ƒ } |  | k } ~ t j
 | ƒ d } | j d k rpt |  ƒ } n t j | ƒ } t | | )| } ~ d t j d |  t j	 | d d ƒ ƒ } t j j | ƒ } ~ nÝ| j ƒ  d/ k r‘|  | t j	 | d d ƒ k } t j
 | ƒ d } | j d k r6t |  ƒ } n t j | ƒ } t | | )| } |  t j	 | d d ƒ } t j j | ƒ } ~ | j ƒ  n | j ƒ  d0 k rZ| t j	 | d d ƒ } |  | k } t j
 | ƒ } | d j d k rt j t j
 | ƒ ƒ } t | | *n  t j	 | d d ƒ |  } t j j | d d d … ƒ d d d … } ~ nW| j ƒ  d1 k r#|  j ƒ  } x“ t | d d ƒ D] } t j | |  | t j	 d | d ƒ ƒ } t j | | | ƒ | | )t j | |  t j | |  |  | ƒ ƒ | | *q‹W| } | | k } nŽ| j ƒ  d2 k r\t |  d | d d d t ƒ\ } } nU| j ƒ  d3 k r•t |  d | d d! d t ƒ\ } } n| j ƒ  d4 k rÒt |  d | d d% d t ƒd&  \ } } nß | j ƒ  d5 k rt |  d | d d) d t ƒd&  \ } } n¢ | j ƒ  d6 k r¥t j	 d | d ƒ } | d | | |  d |  } t j j | ƒ } t j j | d d d … ƒ d d d … } ~ | | k } n t d+ ƒ ‚ | d k	 rÐd | | d k <n  | sÜ| rì| | |	 |
 f St j | ƒ } | | | <~ t j | ƒ } | | | <| | |	 |
 f Sd S(7   s™  
    Test results and p-value correction for multiple tests

    Parameters
    ----------
    pvals : array_like, 1-d
        uncorrected p-values.   Must be 1-dimensional.
    alpha : float
        FWER, family-wise error rate, e.g. 0.1
    method : string
        Method used for testing and adjustment of pvalues. Can be either the
        full name or initial letters. Available methods are:

        - `bonferroni` : one-step correction
        - `sidak` : one-step correction
        - `holm-sidak` : step down method using Sidak adjustments
        - `holm` : step-down method using Bonferroni adjustments
        - `simes-hochberg` : step-up method  (independent)
        - `hommel` : closed method based on Simes tests (non-negative)
        - `fdr_bh` : Benjamini/Hochberg  (non-negative)
        - `fdr_by` : Benjamini/Yekutieli (negative)
        - `fdr_tsbh` : two stage fdr correction (non-negative)
        - `fdr_tsbky` : two stage fdr correction (non-negative)

    is_sorted : bool
        If False (default), the p_values will be sorted, but the corrected
        pvalues are in the original order. If True, then it assumed that the
        pvalues are already sorted in ascending order.
    returnsorted : bool
         not tested, return sorted p-values instead of original sequence

    Returns
    -------
    reject : array, boolean
        true for hypothesis that can be rejected for given alpha
    pvals_corrected : array
        p-values corrected for multiple tests
    alphacSidak: float
        corrected alpha for Sidak method
    alphacBonf: float
        corrected alpha for Bonferroni method

    Notes
    -----
    There may be API changes for this function in the future.

    Except for 'fdr_twostage', the p-value correction is independent of the
    alpha specified as argument. In these cases the corrected p-values
    can also be compared with a different alpha. In the case of 'fdr_twostage',
    the corrected p-values are specific to the given alpha, see
    ``fdrcorrection_twostage``.

    The 'fdr_gbs' procedure is not verified against another package, p-values
    are derived from scratch and are not derived in the reference. In Monte
    Carlo experiments the method worked correctly and maintained the false
    discovery rate.

    All procedures that are included, control FWER or FDR in the independent
    case, and most are robust in the positively correlated case.

    `fdr_gbs`: high power, fdr control for independent case and only small
    violation in positively correlated case

    **Timing**:

    Most of the time with large arrays is spent in `argsort`. When
    we want to calculate the p-value for several methods, then it is more
    efficient to presort the pvalues, and put the results back into the
    original order outside of the function.

    Method='hommel' is very slow for large arrays, since it requires the
    evaluation of n partitions, where n is the number of p-values.
    iÿÿÿÿNi   g      ð?R   R   R   R   R    R   s
   holm-sidaki    R   R!   R   s   simes-hochbergR   R"   R   R#   R$   R%   R&   t   alphat   methodt   indept	   is_sortedR   R'   R(   R)   R*   t   nR   R,   R-   t   bkyi   R   R+   t   bhR   s   method not recognized(   R   R   R   (   R   R    (   R   s
   holm-sidak(   R   R!   (   R   s   simes-hochberg(   R   R"   (   R   R#   R$   R%   R&   (   R   R'   R(   R)   R*   (   R   R,   R-   (   R   R+   (   R   (   t   gcR	   t   asarrayt   argsortt   takeR   t   powerR   t   lowerR
   t   nonzerot   sizet   mint   Truet   maximumt
   accumulatet   collectt   maxt   minimumt   copyR    R   R   t
   ValueErrort   Nonet
   empty_like(   t   pvalsR.   R/   R1   t   returnsortedR5   t   alphaft   sortindt   ntestst   alphacSidakt
   alphacBonft   rejectt   pvals_correctedt   alphacSidak_allt	   notrejectt   nr_indext   notrejectmint   pvals_corrected_rawt   alphasht   rejindt	   rejectmaxt   at   mt   cimt   iit   qt   pvals_corrected_t   reject_(    (    s:   lib/python2.7/site-packages/statsmodels/stats/multitest.pyR   B   s¾    K

,,5,

R0   c         C   sŒ  t  j |  ƒ }  | s9 t  j |  ƒ } t  j |  | ƒ } n |  } | d k rZ t | ƒ } nT | d k r¢ t  j d t  j d t | ƒ d ƒ ƒ } t | ƒ | } n t d	 ƒ ‚ | | | k } | j	 ƒ  rð t
 t  j | ƒ d
 ƒ }	 t | |	 *n  | | }
 t  j j |
 d d d … ƒ d d d … } ~
 d | | d k <| s~t  j | ƒ } | | | <~ t  j | ƒ } | | | <| | f S| | f Sd S(   s§  pvalue correction for false discovery rate

    This covers Benjamini/Hochberg for independent or positively correlated and
    Benjamini/Yekutieli for general or negatively correlated tests. Both are
    available in the function multipletests, as method=`fdr_bh`, resp. `fdr_by`.

    Parameters
    ----------
    pvals : array_like
        set of p-values of the individual tests.
    alpha : float
        error rate
    method : {'indep', 'negcorr')

    Returns
    -------
    rejected : array, bool
        True if a hypothesis is rejected, False if not
    pvalue-corrected : array
        pvalues adjusted for multiple hypothesis testing to limit FDR

    Notes
    -----

    If there is prior information on the fraction of true hypothesis, then alpha
    should be set to alpha * m/m_0 where m is the number of tests,
    given by the p-values, and m_0 is an estimate of the true hypothesis.
    (see Benjamini, Krieger and Yekuteli)

    The two-step method of Benjamini, Krieger and Yekutiel that estimates the number
    of false hypotheses will be available (soon).

    Method names can be abbreviated to first letter, 'i' or 'p' for fdr_bh and 'n' for
    fdr_by.



    t   iR0   t   pt   poscorrR2   t   negcorrg      ð?i   s"   only indep and negcorr implementedi    Niÿÿÿÿ(   R`   R0   Ra   Rb   (   R2   Rc   (   R	   R6   R7   R8   R   t   sumR
   R   RE   t   anyRB   R;   R>   RC   R@   RG   (   RH   R.   R/   R1   t   pvals_sortindt   pvals_sortedt
   ecdffactort   cmRO   RX   RU   RP   R^   R_   (    (    s:   lib/python2.7/site-packages/statsmodels/stats/multitest.pyR     s6    ')
,


R3   c         C   s2  t  j |  ƒ }  | s9 t  j |  ƒ } t  j |  | ƒ }  n  t |  ƒ } | d k rh d | } | | } n' | d k rƒ d } | } n t d ƒ ‚ | g }	 t |  d | d d d t ƒ\ }
 } |
 j ƒ  } | d	 k sà | | k rø |
 | | | | |	 f S| } x› t r›d | | } | | | } |	 j	 | ƒ t |  d | d d d t ƒ\ }
 } |
 j ƒ  } | ss| | k rwPn | | k  r’t
 d
 ƒ ‚ n  | } qW| | d | 9} | d k rË| d | 9} n  | st  j | ƒ } | | | <~ t  j |
 ƒ } |
 | | <| | | | |	 f S|
 | | | |	 f Sd S(   sÞ  (iterated) two stage linear step-up procedure with estimation of number of true
    hypotheses

    Benjamini, Krieger and Yekuteli, procedure in Definition 6

    Parameters
    ----------
    pvals : array_like
        set of p-values of the individual tests.
    alpha : float
        error rate
    method : {'bky', 'bh')
        see Notes for details

        * 'bky' - implements the procedure in Definition 6 of Benjamini, Krieger
           and Yekuteli 2006
        * 'bh' - the two stage method of Benjamini and Hochberg

    iter : bool

    Returns
    -------
    rejected : array, bool
        True if a hypothesis is rejected, False if not
    pvalue-corrected : array
        pvalues adjusted for multiple hypotheses testing to limit FDR
    m0 : int
        ntest - rej, estimated number of true hypotheses
    alpha_stages : list of floats
        A list of alphas that have been used at each stage

    Notes
    -----
    The returned corrected p-values are specific to the given alpha, they
    cannot be used for a different alpha.

    The returned corrected p-values are from the last stage of the fdr_bh
    linear step-up procedure (fdrcorrection0 with method='indep') corrected
    for the estimated fraction of true hypotheses.
    This means that the rejection decision can be obtained with
    ``pval_corrected <= alpha``, where ``alpha`` is the origianal significance
    level.
    (Note: This has changed from earlier versions (<0.5.0) of statsmodels.)

    BKY described several other multi-stage methods, which would be easy to implement.
    However, in their simulation the simple two-stage method (with iter=False) was the
    most robust to the presence of positive correlation

    TODO: What should be returned?

    R3   g      ð?R4   s+   only 'bky' and 'bh' are available as methodR.   R/   R0   R1   i    s    oops - shouldn't be hereN(   R	   R6   R7   R8   R   RE   R   R>   Rd   t   appendt   RuntimeErrorRG   (   RH   R.   R/   t   iterR1   Rf   RL   t   factt   alpha_primet   alpha_stagest   rejt	   pvalscorrt   r1t   ri_oldt   ntests0t
   alpha_start   rit
   pvalscorr_RO   (    (    s:   lib/python2.7/site-packages/statsmodels/stats/multitest.pyR   Z  sT    5
			


g      ð?i   i   c         C   s—  d d l  m } d d l  m } d d l m } t |  ƒ } t |  ƒ }	 t j | |	 | ƒ }
 t j	 |  |
 ƒ d } |
 d  |
 d d } t j
 | | d ƒ } | t j d | ƒ | ƒ j ƒ  } | | | d | j ƒ  ƒj d	 | j ƒ } t j
 |  | d ƒ } | j | ƒ t |  ƒ |
 d |
 d } | d k rdt j d
 |  d ƒ t j d t j ƒ } n | |  ƒ } | | | } t j | d d ƒ } | S(   s±  
    Calculate local FDR values for a list of Z-scores.

    Parameters
    ----------
    zscores : array-like
        A vector of Z-scores
    null_proportion : float
        The assumed proportion of true null hypotheses
    null_pdf : function mapping reals to positive reals
        The density of null Z-scores; if None, use standard normal
    deg : integer
        The maximum exponent in the polynomial expansion of the
        density of non-null Z-scores
    nbins : integer
        The number of bins for estimating the marginal density
        of Z-scores.

    Returns
    -------
    fdr : array-like
        A vector of FDR values

    References
    ----------
    B Efron (2008).  Microarrays, Empirical Bayes, and the Two-Groups
    Model.  Statistical Science 23:1, 1-22.

    Examples
    --------
    Basic use (the null Z-scores are taken to be standard normal):

    >>> from statsmodels.stats.multitest import local_fdr
    >>> import numpy as np
    >>> zscores = np.random.randn(30)
    >>> fdr = local_fdr(zscores)

    Use a Gaussian null distribution estimated from the data:

    >>> null = EmpiricalNull(zscores)
    >>> fdr = local_fdr(zscores, null_pdf=null.pdf)
    iÿÿÿÿ(   t   GLM(   t   families(   t   OLSi    i   i   t   familyt   start_paramsg      à¿N(   t+   statsmodels.genmod.generalized_linear_modelRx   Ry   t#   statsmodels.regression.linear_modelRz   R=   RB   R	   t   linspacet	   histogramt   vandert   logt   fitt   Poissont   paramst   predictR   RF   t   expt   sqrtt   pit   clip(   t   zscorest   null_proportiont   null_pdft   degt   nbinsRx   Ry   Rz   t   minzt   maxzt   binst   zhistt   zbinst   dmatt   mdt	   dmat_fullt   fzt   f0t   fdr(    (    s:   lib/python2.7/site-packages/statsmodels/stats/multitest.pyR   Ç  s&    -"*).c           B   s/   e  Z d  Z d d e e e d „ Z d „  Z RS(   s)  
    Estimate a Gaussian distribution for the null Z-scores.

    The observed Z-scores consist of both null and non-null values.
    The fitted distribution of null Z-scores is Gaussian, but may have
    non-zero mean and/or non-unit scale.

    Parameters
    ----------
    zscores : array-like
        The observed Z-scores.
    null_lb : float
        Z-scores between `null_lb` and `null_ub` are all considered to be
        true null hypotheses.
    null_ub : float
        See `null_lb`.
    estimate_mean : bool
        If True, estimate the mean of the distribution.  If False, the
        mean is fixed at zero.
    estimate_scale : bool
        If True, estimate the scale of the distribution.  If False, the
        scale parameter is fixed at 1.
    estimate_null_proportion : bool
        If True, estimate the proportion of true null hypotheses (i.e.
        the proportion of z-scores with expected value zero).  If False,
        this parameter is fixed at 1.

    Attributes
    ----------
    mean : float
        The estimated mean of the empirical null distribution
    sd : float
        The estimated standard deviation of the empirical null distribution
    null_proportion : float
        The estimated proportion of true null hypotheses among all hypotheses

    References
    ----------
    B Efron (2008).  Microarrays, Empirical Bayes, and the Two-Groups
    Model.  Statistical Science 23:1, 1-22.

    Notes
    -----
    See also:

    http://nipy.org/nipy/labs/enn.html#nipy.algorithms.statistics.empirical_pvalue.NormalEmpiricalNull.fdr
    iÿÿÿÿi   c            s  t  j | ˆ k | ˆ k @ƒ } t | ƒ d k r@ t d ƒ ‚ n  | | ‰	 t | ƒ t ˆ	 ƒ ‰ ‰ ‡  ‡ ‡ f d †  ‰ d d l m ‰ ‡ ‡ ‡ ‡ ‡ ‡ ‡	 f d †  } d d l m }	 |	 | t  j d d
 d ƒ}
 ˆ |
 d ƒ \ } } } | |  _	 | |  _
 | |  _ d  S(   Ni    s,   No Z-scores fall between null_lb and null_ubc            s   d } d } d } d } ˆ  r5 |  | } | d 7} n  ˆ r[ t  j |  | ƒ } | d 7} n  ˆ r€ d d t  j |  | ƒ } n  | | | f S(   Ng        g      ð?i    i   (   R	   R‡   (   R…   t   meant   sdt   probR\   (   t   estimate_meant   estimate_null_proportiont   estimate_scale(    s:   lib/python2.7/site-packages/statsmodels/stats/multitest.pyt   xform`  s    
iÿÿÿÿ(   t   normc            sÎ   ˆ |  ƒ \ } } } ˆ j  ˆ | | ƒ ˆ j  ˆ | | ƒ } | | } ˆ t j | ƒ ˆ  ˆ t j d | ƒ } ˆ | | } | t j | d d ƒ ˆ t j | ƒ 7} | ˆ t j | ƒ 8} | S(   s]  
            Negative log-likelihood of z-scores.

            The function has three arguments, packed into a vector:

            mean : location parameter
            logscale : log of the scale parameter
            logitprop : logit of the proportion of true nulls

            The implementation follows section 4 from Efron 2008.
            i   i   (   t   cdfR	   R‚   Rd   (   R…   t   dR   Ra   t   central_masst   cpt   rvalt   zv(   t   n_zst   n_zs0R¢   t   null_lbt   null_ubR¡   t   zscores0(    s:   lib/python2.7/site-packages/statsmodels/stats/multitest.pyt   funv  s    
,-(   t   minimizeg        i   R/   s   Nelder-MeadR   (   g        i    i   (   R	   t   flatnonzeroR   Rk   t   scipy.stats.distributionsR¢   t   scipy.optimizeR¯   t   r_R›   Rœ   RŒ   (   t   selfR‹   R«   R¬   Rž   R    RŸ   R\   R®   R¯   t   mzR›   Rœ   R   (    (
   Rž   RŸ   R    R©   Rª   R¢   R«   R¬   R¡   R­   s:   lib/python2.7/site-packages/statsmodels/stats/multitest.pyt   __init__R  s    
!"		c         C   sQ   | |  j  |  j } t j d | d t j |  j ƒ d t j d t j ƒ ƒ S(   s[  
        Evaluates the fitted emirical null Z-score density.

        Parameters
        ----------
        zscores : scalar or array-like
            The point or points at which the density is to be
            evaluated.

        Returns
        -------
        The empirical null Z-score density evaluated at the given
        points.
        g      à¿i   g      à?(   R›   Rœ   R	   R‡   R‚   R‰   (   R´   R‹   t   zval(    (    s:   lib/python2.7/site-packages/statsmodels/stats/multitest.pyt   pdf£  s    (   t   __name__t
   __module__t   __doc__R>   t   FalseR¶   R¸   (    (    (    s:   lib/python2.7/site-packages/statsmodels/stats/multitest.pyR   !  s   /	P(   R»   t   statsmodels.compat.pythonR    t   collectionsR   t   numpyR	   t   statsmodels.stats._knockoffR   t   __all__R   t   multitest_methods_namest   _alias_listt   multitest_aliasRZ   RY   R¼   R   R   R   RF   R   t   objectR   (    (    (    s:   lib/python2.7/site-packages/statsmodels/stats/multitest.pyt   <module>   sT   			

								ÊM	l	Y