
    M/Phqk                     :   d Z ddlZddlmZ g dZd Zdddd	d
dddddddZg dddgddgddgddgddgg dg ddd gg d!d"ggZi Z	eD ]+Z
e
d         e	e
d         <   e
d#d         D ]Ze
d         e	e<   ,	 	 	 	 d1d&Zd2d(Z	 	 	 	 d3d*Z	 	 d4d.Z G d/ d0          ZdS )5zQMultiple Testing and P-Value Correction


Author: Josef Perktold
License: BSD-3

    N)RegressionFDR)fdrcorrectionfdrcorrection_twostage	local_fdrmultipletestsNullDistributionr   c                 p    t          |           }t          j        d|dz             t          |          z  S )z2no frills empirical cdf used in fdrcorrection
       )lennparangefloat)xnobss     [/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/stats/multitest.py_ecdfr      s0     q66D9QtAvuT{{**    
BonferroniSidakHolmz
Holm-SidakzSimes-HochbergHommelzFDR Benjamini-HochbergzFDR Benjamini-YekutielizFDR 2-stage Benjamini-Hochbergz'FDR 2-stage Benjamini-Krieger-Yekutieliz&FDR adaptive Gavrilov-Benjamini-Sarkar)bshhsshhofdr_bhfdr_byfdr_tsbh	fdr_tsbkyfdr_gbsr   bonf
bonferronir   sidakr   holmr   
holm-sidakr   simes-hochbergr   hommelr   fdr_ifdr_pfdrifdrpr   fdr_nfdr_cfdrnfdrcorrr    fdr_2sbhr!   	fdr_2sbkyfdr_twostager"   r
   皙?Fc           
         ddl }t          j        |           } |}|s)t          j        |           }t          j        | |          } t          |           }	dt          j        d|z
  d|	z            z
  }
|t          |	          z  }|                                dv r| |k    }| t          |	          z  }nO|                                dv r3| |
k    }t          j	        |	t          j
        |            z             }n|                                dv rdt          j        d|z
  dt          j        |	dd          z            z
  }| |k    }~t          j        |          d         }|j        dk    rt          |           }nt          j        |          }d	||d<   | }~t          j	        t          j        |	dd          t          j
        |            z             }t          j                            |          }~n|                                d
v r| |t          j        |	dd          z  k    }t          j        |          d         }|j        dk    rt          |           }nt          j        |          }d	||d<   | }| t          j        |	dd          z  }t          j                            |          }~|                                 n-|                                dv r|t          j        |	dd          z  }| |k    }t          j        |          }|d         j        dk    r-t          j        t          j        |                    }d	|d|<   t          j        |	dd          | z  }t          j                            |ddd                   ddd         }~nY|                                dv r|                                 }t+          |	dd          D ]}t          j        || | d         z  t          j        d|dz             z            }t          j        || d         |          || d<   t          j        |d|          t          j        || d|          z  |                    |d| <   |}||k    }nq|                                dv rt-          | |dd	          \  }}nC|                                dv rt-          | |dd	          \  }}n|                                dv r t/          | |d|d	          dd         \  }}n|                                dv r t/          | |d|d	          dd         \  }}n|                                dv rt          j        d|	dz             }|	dz   |z
  |z  | z  d| z
  z  }t          j                            |          }t          j                            |ddd                   ddd         }~||k    }nt1          d          |	d||dk    <   |s|r|||
|fS t          j        |          }|||<   ~t          j        |          }|||<   |||
|fS )aI  
    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 : str
        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)

    maxiter : int or bool
        Maximum number of iterations for two-stage fdr, `fdr_tsbh` and
        `fdr_tsbky`. It is ignored by all other methods.
        maxiter=1 (default) corresponds to the two stage method.
        maxiter=-1 corresponds to full iterations which is maxiter=len(pvals).
        maxiter=0 uses only a single stage fdr correction using a 'bh' or 'bky'
        prior fraction of assumed true hypotheses.
    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 : ndarray, boolean
        true for hypothesis that can be rejected for given alpha
    pvals_corrected : ndarray
        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.
    r   Nr
         ?r#   )r   r&   )r   r(   T)r   r'   )r   r)   )r   r*   r+   indepalphamethod	is_sortedr0   nr6   bky)r?   r@   maxiterrA      )r    r5   bh)r"   zmethod not recognized)gcr   asarrayargsorttaker   powerr   lowerexpm1log1pr   nonzerosizeminmaximum
accumulatecollectmaxminimumcopyranger   r   
ValueError
empty_like)pvalsr?   r@   rD   rA   returnsortedrG   alphafsortindntestsalphacSidak
alphacBonfrejectpvals_correctedalphacSidak_all	notrejectnr_indexnotrejectminpvals_corrected_rawalphashrejind	rejectmaxamcimiiqpvals_corrected_reject_s                                r   r   r   ?   s   h IIIJuEF (*U##w''ZZFbhVbi888K%--'J||~~444*$%--/	>	)	)+%8FRXuf-=-=$=>>>	/	/	/bhV')")FAr*B*B'BD D DO+	:i((+=Au::LL6(++L#'	,-- 
  "x	&!R(@(@(*%(8(8)9  :  : :*//0CDD	=	(	(FRYvq"%=%===	:i((+=Au::LL6(++L#'	,-- #bi2&>&>>*//0CDD


	3	3	329VQ333'!F##!9>Arz&1122I!%F:I: i266>*//0CDDbD0IJJ44R4P	+	+	+JJLLvq"%% 	I 	IA&UA233Z")Aad*;*;;<<CZ1"##,,AqbccFZ#A2#
1uSqbSz>3(G(GHHAcrcFFf	G	G	G"/U8?;?#A #A #A 
J	J	J"/U8;;?#A #A #A 
E	E	E"8e@EAHCG#I #I #I JL!#M 
3	3	3"8e@DAHCG#I #I #I JL!#M
 
;	&	& Yq&1*%%b[2r!E)R%Z8 j33A66*//0CDDbD0IJJ44R4P E) 0111"-.)* BL BZ??=99$3!-''!(+zAAr   r=   c           	      (   t          j        |           } | j        dk    s
J d            |s*t          j        |           }t          j        | |          }n| }|dv rt          |          }n`|dv rMt          j        dt          j        dt          |          dz             z            }t          |          |z  }nt          d          |||z  k    }|
                                r.t          t          j        |          d                   }	d|d	|	<   ||z  }
t           j                            |
d	d	d
                   d	d	d
         }~
d||dk    <   |s7t          j        |          }|||<   ~t          j        |          }|||<   ||fS ||fS )a  
    pvalue correction for false discovery rate.

    This covers Benjamini/Hochberg for independent or positively correlated and
    Benjamini/Yekutieli for general or negatively correlated tests.

    Parameters
    ----------
    pvals : array_like, 1d
        Set of p-values of the individual tests.
    alpha : float, optional
        Family-wise error rate. Defaults to ``0.05``.
    method : {'i', 'indep', 'p', 'poscorr', 'n', 'negcorr'}, optional
        Which method to use for FDR correction.
        ``{'i', 'indep', 'p', 'poscorr'}`` all refer to ``fdr_bh``
        (Benjamini/Hochberg for independent or positively
        correlated tests). ``{'n', 'negcorr'}`` both refer to ``fdr_by``
        (Benjamini/Yekutieli for general or negatively correlated tests).
        Defaults to ``'indep'``.
    is_sorted : bool, optional
        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.

    Returns
    -------
    rejected : ndarray, bool
        True if a hypothesis is rejected, False if not
    pvalue-corrected : ndarray
        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).

    Both methods exposed via this function (Benjamini/Hochberg, Benjamini/Yekutieli)
    are also available in the function ``multipletests``, as ``method="fdr_bh"`` and
    ``method="fdr_by"``, respectively.

    See also
    --------
    multipletests

    r
   z2pvals must be 1-dimensional, that is of shape (n,))ir=   pposcorr)rB   negcorrr;   z"only indep and negcorr implementedr   TNr<   )r   rH   ndimrI   rJ   r   sumr   r   rY   anyrU   rO   rV   rS   rZ   )r[   r?   r@   rA   pvals_sortindpvals_sorted
ecdffactorcmrb   rk   rh   rc   rq   rr   s                 r   r   r     s   f JuE:???P??? 
5))wum44///<((

	#	#	#VBryC$5$5a$788899<((2-


 =>>>Z--Fzz|| "
6**1-..	!z	z&3j++,?",EFFtttLO)*OOA%& '=99*9'-''!'(((&&r   rC   c                    t          j        |           } |!ddl}d}|                    |t                     |du rd}n|du s|dv rt          |           }|s)t          j        |           }t          j        | |          } t          |           }	|dk    rd	|z   }
||
z  }n|d
k    rd	}
|}nt          d          |g}t          | |dd          \  }}|
                                }|dk    s||	k    r
|}||
z  }|}n|x}}|	}t          |          D ]y}d	|	z  |z
  }||	z  |z  }|                    |           t          | |dd          \  }}|
                                }||dz
  k    s||k    r n||k     rt          d          |}z||d	z  |	z  z  }|dk    r|d	|z   z  }d||dk    <   |s<t          j        |          }|||<   ~t          j        |          }|||<   |||	|z
  |fS |||	|z
  |fS )a  (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

    maxiter : int or bool
        Maximum number of iterations.
        maxiter=1 (default) corresponds to the two stage method.
        maxiter=-1 corresponds to full iterations which is maxiter=len(pvals).
        maxiter=0 uses only a single stage fdr correction using a 'bh' or 'bky'
        prior fraction of assumed true hypotheses.
        Boolean maxiter is allowed for backwards compatibility with the
        deprecated ``iter`` keyword.
        maxiter=False is two-stage fdr (maxiter=1)
        maxiter=True is full iteration (maxiter=-1 or maxiter=len(pvals))

        .. versionadded:: 0.14

            Replacement for ``iter`` with additional features.

    iter : bool
        ``iter`` is deprecated use ``maxiter`` instead.
        If iter is True, then only one iteration step is used, this is the
        two-step method.
        If iter is False, then iterations are stopped at convergence which
        occurs in a finite number of steps (at most len(pvals) steps).

        .. deprecated:: 0.14

            Use ``maxiter`` instead of ``iter``.

    Returns
    -------
    rejected : ndarray, bool
        True if a hypothesis is rejected, False if not
    pvalue-corrected : ndarray
        pvalues adjusted for multiple hypotheses testing to limit FDR
    m0 : int
        ntest - rej, estimated number of true (not rejected) 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 original 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?

    Nr   z8iter keyword is deprecated, use maxiter keyword instead.Fr
   T)r<   NrC   r;   rF   z+only 'bky' and 'bh' are available as methodr=   r>   z oops - should not be here)r   rH   warningswarnFutureWarningr   rI   rJ   rY   r   ry   rX   appendRuntimeErrorrZ   )r[   r?   r@   rD   iterrA   r   msgr{   r_   factalpha_primealpha_stagesrej	pvalscorrr1rb   riri_oldntests0it
alpha_star
pvalscorr_s                          r   r   r   r  s   ^ JuEHc=)))u}}	J..e**  .
5))}--ZZF5dl	4FGGG=L"5G-13 3 3NC	B
aR6\\T	.. 	 	BFlV+G$v-7J
+++*5
759; ; ;NCBgk!!bFllf"#?@@@FF 	Ws]f,,	U??"u*%IIik 9]9--
$-
=!s## #}z6B;<<Iv{L88r   r;         c                    ddl m} ddl m} ddlm} t          |           }	t          |           }
t          j        |	|
|          }t          j	        | |          d         }|dd         |dd         z   dz  }t          j
        ||dz             }|                    d          }|d	k    }|dd|fxx         ||         z  cc<    |t          j        d|z             |                                          j        }|dk    r7 ||||                                
                              d||          }n4 ||||                                
                              |          }t          j
        | |dz             }|dd|fxx         ||         z  cc<   |                    |          t%          |           |d         |d         z
  z  z  }|=t          j        d| dz  z            t          j        dt          j        z            z  }n ||           }||z  |z  }t          j        |dd          }|S )a+  
    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 : int
        The maximum exponent in the polynomial expansion of the
        density of non-null Z-scores
    nbins : int
        The number of bins for estimating the marginal density
        of Z-scores.
    alpha : float
        Use Poisson ridge regression with parameter alpha to estimate
        the density of non-null 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)
    r   )GLM)families)OLSNr<   r
   rE   g:0yE>)family)L1_wtr?   start_params)r         )+statsmodels.genmod.generalized_linear_modelr   r   #statsmodels.regression.linear_modelr   rQ   rU   r   linspace	histogramvanderstdlogfitparamsPoissonfit_regularizedpredictr   expsqrtpiclip)zscoresnull_proportionnull_pdfdegnbinsr?   r   r   r   minzmaxzbinszhistzbinsdmatsdro   startmd	dmat_fullfzf0fdrs                          r   r   r     sx   ` @?????DDDDDD777777 w<<Dw<<D;tT5))D L$''*E #2#Yabb!Q&E 9UC!G$$D 
!B	TBBKKK2b6KKKCq5y!!4((,,..5E qyySX%5%5%7%7888HHqX]lqHrrSX%5%5%7%7888<<%<PP 	'37++Iaaae2 
I		#g,,$q'DG2C"D	EB VD7A:%&&RU););;Xg B

#C
'#q!

CJr   c                   $    e Zd ZdZ	 	 d	dZd ZdS )
r   a)  
    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
    r<   r
   TFc                    t          j        |k    |k    z            }t          |          dk    rt          d          ||         t          |          t                    cfdddlm fd}ddlm}	  |	|t           j        d         d	          }
 |
d
                   \  }}}|| _	        || _
        || _        d S )Nr   z,No Z-scores fall between null_lb and null_ubc                     d}d}d}d}r| |         }|dz  }rt          j        | |                   }|dz  }r!ddt          j        | |                    z   z  }|||fS )N        r;   r   r
   )r   r   )r   meanr   probro   estimate_meanestimate_null_proportionestimate_scales        r   xformz(NullDistribution.__init__.<locals>.xform  s    DBDB bza VF2J''a' 5Ar
{ 3 334T>!r   )normc                     |           \  }}}
                     |z
  |z            
                     |z
  |z            z
  }||z  }	t          j        |          z  	z
  t          j        d|z
            z  z   }|z
  |z  }|t          j        |dz   dz            	t          j        |          z  z
  z  }|	t          j        |          z  z  }| S )a]  
            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.
            r
   rE   )cdfr   r   ry   )r   dr   ru   central_masscprvalzvn_zsn_zs0r   null_lbnull_ubr   zscores0s           r   funz&NullDistribution.__init__.<locals>.fun  s     eFmmGAq! !HHgkQ%677 HHgkQ%6778L \!B 26"::%B(GGD Q,!#BBFBE6A:&&):::DEBF<0000D5Lr   )minimize)r   r      zNelder-Mead)r@   r   )r   flatnonzeror   r   scipy.stats.distributionsr   scipy.optimizer   r_r   r   r   )selfr   r   r   r   r   r   ro   r   r   mzr   r   r   r   r   r   r   r   s     `````       @@@@@r   __init__zNullDistribution.__init__  s>    ^W/Gw4FGHHr77a<<MNNN2; 'llCMMe	" 	" 	" 	" 	" 	" 	"& 	322222	 	 	 	 	 	 	 	 	 	 	D 	,+++++Xc25?=AAAr#wb$	#r   c                     || j         z
  | j        z  }t          j        d|dz  z  t          j        | j                  z
  dt          j        dt          j        z            z  z
            S )a\  
        Evaluates the fitted empirical 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.
        r   rE   g      ?)r   r   r   r   r   r   )r   r   zvals      r   pdfzNullDistribution.pdf  sV      $)#tw.vd47lRVDG__4s26!BE'??7JJKKKr   N)r<   r
   TTF)__name__
__module____qualname____doc__r   r    r   r   r   r   p  sV        . .` FJ?DM$ M$ M$ M$bL L L L Lr   r   )r9   r   r
   FF)r9   r=   F)r9   rC   r
   NF)r;   Nr   r   r   )r   numpyr   statsmodels.stats._knockoffr   __all__r   multitest_methods_names_alias_listmultitest_aliasrm   rl   r   r   r   r   r   r   r   r   <module>r      s        5 5 5 5 5 5A A A+ + + !- ' &!-!1!)%=%>'G(Q&N   +**W~V}l#&'h;;;>>>J'999{ 	 " "AaDOAaDqrrU " "qT" -1!$VB VB VB VBrW' W' W' W't 6;#$ $%*V9 V9 V9 V9r @Ab b b bJSL SL SL SL SL SL SL SL SL SLr   