
    >htn                     .   S r SSKrSSKJr  / SQrS rSSSS	S
SSSSSSS.r/ SQSS/SS/SS/SS/SS// SQ/ SQSS // S!QS"//r0 r	\ H"  r
\
S   \	\
S   '   \
S#S  H  r\
S   \	\'   M     M$         S*S$ jrS+S% jr    S,S& jr  S-S' jr " S( S)5      rg).zQMultiple Testing and P-Value Correction


Author: Josef Perktold
License: BSD-3

    N)RegressionFDR)fdrcorrectionfdrcorrection_twostage	local_fdrmultipletestsNullDistributionr   c                 d    [        U 5      n[        R                  " SUS-   5      [        U5      -  $ )z2no frills empirical cdf used in fdrcorrection
       )lennparangefloat)xnobss     nC:\Users\julio\OneDrive\Documentos\Trabajo\Ideas Frescas\venv\Lib\site-packages\statsmodels/stats/multitest.py_ecdfr      s+     q6D99QtAv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
   c           
         SSK n[        R                  " U 5      n UnU(       d,  [        R                  " U 5      n[        R                  " X5      n [        U 5      n	S[        R                  " SU-
  SU	-  5      -
  n
U[        U	5      -  nUR                  5       S;   a  X:*  nU [        U	5      -  nGOUR                  5       S;   a5  X
:*  n[        R                  " U	[        R                  " U * 5      -  5      * nGOUR                  5       S;   a  S[        R                  " SU-
  S[        R                  " U	SS5      -  5      -
  nX:  nA[        R                  " U5      S   nUR                  S:X  a  [        U 5      nO[        R                  " U5      nS	UUS& U) nA[        R                  " [        R                  " U	SS5      [        R                  " U * 5      -  5      * n[        R                  R!                  U5      nAGOUR                  5       S
;   a  X[        R                  " U	SS5      -  :  n[        R                  " U5      S   nUR                  S:X  a  [        U 5      nO[        R                  " U5      nS	UUS& U) nU [        R                  " U	SS5      -  n[        R                  R!                  U5      nAUR#                  5         GOUR                  5       S;   a  U[        R                  " U	SS5      -  nU U:*  n[        R                  " U5      nUS   R                  S:  a/  [        R$                  " [        R                  " U5      5      nS	USU& [        R                  " U	SS5      U -  n[        R&                  R!                  USSS2   5      SSS2   nAGOUR                  5       S;   a  U R)                  5       n[+        U	SS5       H  n[        R                  " UU U* S -  [        R                  " SUS-   5      -  5      n[        R                  " UU* S U5      UU* S& [        R                  " USU*  [        R&                  " UU SU*  -  U5      5      USU* & M     UnUU:*  nGO.UR                  5       S;   a  [-        XSS	S9u  pGOUR                  5       S;   a  [-        XSS	S9u  pOUR                  5       S;   a  [/        XSUS	S9SS u  pOUR                  5       S;   a  [/        XSUS	S9SS u  pOUR                  5       S;   a~  [        R                  " SU	S-   5      nU	S-   U-
  U-  U -  SU -
  -  n[        R                  R!                  U5      n[        R&                  R!                  USSS2   5      SSS2   nAX:*  nO[1        S5      eUb  SXS:  '   U(       d  U(       a  XX4$ [        R2                  " U5      nUUW'   A[        R2                  " U5      nUUU'   UUX4$ )a=  
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?   maxiterr@      )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?   rC   r@   returnsortedrF   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 JJuEF**U#'ZFbhhVbi88K%-'J||~44$%-/	>	)%88FRXXuf-=$=>>	/	/bhhV')"))FAr*B'BD D+	::i(+==Au:L66(+L#'	,- 
  "xx		&!R(@(*%(8)9  : :**//0CD	=	(RYYvq"%===	::i(+==Au:L66(+L#'	,- #bii2&>>**//0CD


	3	3299VQ33'!F#!9>>Arzz&12I!%F:I ii26>**//0CDbD0IJ4R4P	+	+JJLvq"%A&&UA23Z"))Aad*;;<CZZ1"#,AqbcFZZ#A2

1uSqbz>3(GHAcrF & f	G	G"/8?;?#A 
J	J"/8;;?#A 
E	E"8@EAHCG#I JL!#M 
3	3"8@DAHCG#I JL!#M
 
;	& YYq&1*%b[2r!E)R%Z8 jj33A6**//0CDbD0IJ4R4P ) 011"-.)*L??==9$3!--'!(+AAr   c           	         [         R                  " U 5      n U R                  S:X  d   S5       eU(       d-  [         R                  " U 5      n[         R                  " X5      nOU nUS;   a  [        U5      nOZUS;   aI  [         R                  " S[         R                  " S[        U5      S-   5      -  5      n[        U5      U-  nO[        S5      eXVU-  :*  nUR                  5       (       a'  [        [         R                  " U5      S   5      n	SUS	U	& XV-  n
[         R                  R                  U
S	S	S
2   5      S	S	S
2   nA
SXS:  '   U(       d8  [         R                  " U5      nXW'   A[         R                  " U5      nXU'   X4$ X4$ )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)rA   negcorrr:   z"only indep and negcorr implementedr   TNr;   )r   rG   ndimrH   rI   r   sumr   r   rX   anyrT   rN   rU   rR   rY   )rZ   r>   r?   r@   pvals_sortindpvals_sorted
ecdffactorcmra   rj   rg   rb   rp   rq   s                 r   r   r     so   f JJuE::?PPP?

5)wwu4//<(
	#	#VVBryyC$5a$7889<(2-

 =>>--Fzz||

6*1-.	!z	&3jj++,?",EFttLO)*OA%&==9*9'--'!'((&&r   c                    [         R                  " U 5      n Ub  SSKnSnUR                  U[        5        USL a  SnOUSL d  US;   a  [        U 5      nU(       d,  [         R                  " U 5      n[         R                  " X5      n [        U 5      n	US:X  a
  S	U-   n
X-  nOUS
:X  a  S	n
UnO[        S5      eU/n[        XSSS9u  pUR                  5       nUS:X  d  X:X  a	  UnX-  nUnOU=nnU	n[        U5       He  nS	U	-  U-
  nX-  U-  nUR                  U5        [        U USSS9u  pUR                  5       nUUS-
  :  d  UU:X  a    OUU:  a  [        S5      eUnMg     UUS	-  U	-  -  nUS:X  a  US	U-   -  nSXS:  '   U(       d@  [         R                  " U5      nUUW'   A[         R                  " U5      nUUU'   UUU	U-
  U4$ XU	U-
  U4$ )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;   NrB   r:   rE   z+only 'bky' and 'bh' are available as methodr<   r=   z oops - should not be here)r   rG   warningswarnFutureWarningr   rH   rI   rX   r   rx   rW   appendRuntimeErrorrY   )rZ   r>   r?   rC   iterr@   r   msgrz   r^   factalpha_primealpha_stagesrej	pvalscorrr1ra   riri_oldntests0it
alpha_star
pvalscorr_s                          r   r   r   r  s   ^ JJuEHc=)u}	J.e* 

5)-ZF5l	4FGG=L"5G-13NC	B
aR\	.BFlV+G$-7J
+*5
759;NCBgk!bFlf"#?@@F !" 	Ws]f,,	U?"u*%IIk]]9-
$-
=!s# #}z6B;<<v{L88r   c                    SSK Jn  SSK Jn  SSKJn  [        U 5      n	[        U 5      n
[        R                  " XU5      n[        R                  " X5      S   nUSS USS -   S-  n[        R                  " XS-   5      nUR                  S5      nUS	:  nUSS2U4==   UU   -  ss'   U" [        R                  " SU-   5      U5      R                  5       R                  nUS:  a%  U" XUR                  5       S
9R!                  SUUS9nO"U" XUR                  5       S
9R                  US9n[        R                  " XS-   5      nUSS2U4==   UU   -  ss'   UR#                  U5      [%        U 5      US   US   -
  -  -  nUcE  [        R&                  " SU S-  -  5      [        R(                  " S[        R*                  -  5      -  nOU" U 5      nUU-  U-  n[        R,                  " USS5      nU$ )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
   rD   g:0yE>)family)L1_wtr>   start_params)r         )+statsmodels.genmod.generalized_linear_modelr   r   #statsmodels.regression.linear_modelr   rP   rT   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sdrn   startmd	dmat_fullfzf0fdrs                          r   r   r     s   ` @D7 w<Dw<D;;t5)D LL'*E #2Yab!Q&E 99U!G$D 
!B	TBBK2b6Kq5y!4(,,.55E qyX%5%5%78HHqX]lqHrX%5%5%78<<%<P 		'7+Iae2 
I	#g,$q'DG2C"D	EB VVD7A:%&RUU);;g B

#C
''#q!
CJr   c                   ,    \ rS rSrSr  SS jrS rSrg)r   ip  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
c                 r  ^^^^^^^^^^ [         R                  " UT:  UT:*  -  5      n[        U5      S:X  a  [        S5      eX   m[        U5      [        T5      smmUUU4S jmSSKJm  UUUUUUU4S jnSSKJn	  U	" U[         R                  S   SS	9n
T" U
S
   5      u  pnXl	        Xl
        Xl        g )Nr   z,No Z-scores fall between null_lb and null_ubc                    > SnSnSnSnT(       a	  X   nUS-  nT(       a  [         R                  " X   5      nUS-  nT(       a  SS[         R                  " X   * 5      -   -  nXU4$ )N        r:   r   r
   )r   r   )r   meanr   probrn   estimate_meanestimate_null_proportionestimate_scales        r   xform(NullDistribution.__init__.<locals>.xform  so    DBDBzaVVFJ'a'A
{ 334T>!r   )normc                   > T" U 5      u  pnT
R                  TU-
  U-  5      T
R                  TU-
  U-  5      -
  nX4-  nT	[        R                  " U5      -  TT	-
  [        R                  " SU-
  5      -  -   nTU-
  U-  nU[        R                  " US-  * S-  5      T	[        R                  " U5      -  -
  -  nUT	[        R                  " U5      -  -  nU* $ )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
   rD   )cdfr   r   rx   )r   dr   rt   central_masscprvalzvn_zsn_zs0r   null_lbnull_ubr   zscores0s           r   fun&NullDistribution.__init__.<locals>.fun  s     FmGA! !HHgkQ%67 HHgkQ%678L !B 266":%B(GGD Q,!#BBFFBE6A:&):::DEBFF<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   rn   r   r   mzr   r   r   r   r   r   r   r   s     `````       @@@@@r   __init__NullDistribution.__init__  s     ^^W/Gw4FGHr7a<MNN; 'lCMe	"& 	3	 	D 	,c255?=Ar#w$	#r   c                    XR                   -
  U R                  -  n[        R                  " SUS-  -  [        R                  " U R                  5      -
  S[        R                  " S[        R
                  -  5      -  -
  5      $ )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   rD   g      ?)r   r   r   r   r   r   )r   r   zvals      r   pdfNullDistribution.pdf  s[      ))#tww.vvd47lRVVDGG_4s266!BEE'?7JJKKr   )r   r   r   N)r;   r
   TTF)__name__
__module____qualname____firstlineno____doc__r   r   __static_attributes__ r   r   r   r   p  s    .` FJ?DM$bLr   r   )皙?r   r
   FF)r   r<   F)r   rB   r
   NF)r:   N      r   )r   numpyr   statsmodels.stats._knockoffr   __all__r   multitest_methods_names_alias_listmultitest_aliasrl   rk   r   r   r   r   r   r   r   r   <module>r      s%    5A+ !- ' &!-!1!)%=%>'G(Q&N  +W~V}l#&'h;>J'9{ 	AaDOAaDqrUqT  

 -1!$VBrW't 6;#$ $%*V9r @AbJSL SLr   