
    >h[7                       S r SSKrSSKrSSKJrJr  SSKJr  SSK	J
r
  SSKJr  \R                  r/ SQ/ SQS	.r  S$S
 jrS%S jr   S&S jr   S'S jr  S(S jr    S)S jr/ SQ/ SQS./ SQ/ SQS.S	.r    S*S jrS+S jr    S,S jr S-S jr S-S jr  S.S jr        S/S jr    S0S jr    S1S jr    S1S jr     S2S jr      S3S  jr!  S4S! jr"        S5S" jr#    S6S# jr$g)7zj
Test for ratio of Poisson intensities in two independent samples

Author: Josef Perktold
License: BSD-3

    N)statsoptimize)HolderTuple)_zstat_generic2)_mover_confint)waldscoreexact-cmidp-cwaldccvsqrt-asqrt-vsqrt)r   r	   r
   r   jeffr   r   r   r   	sqrt-centsqrt-centcc)testconfintc           
      V   UnX-  nUc  Sn[        U5      eUS:w  a  US;  a  Sn[        U5      eSn	US:X  a$  [        R                  " XW-  U-  5      n
Xr-
  U
-  nGOUS:X  a*  [        R                  " XWSU-  -   -  U-  5      n
Xr-
  U
-  nGOcUS	:X  aC  [        R                  " XR-  U-  5      n
Xr-
  U
-  n[        R                  R                  U5      nGOUR                  S
5      (       d  UR                  S5      (       a  [        R                  R                  XU-  5      n[        R                  R                  U S-
  Xb-  5      nUR                  S5      (       aP  US[        R                  R                  XU-  5      -  -
  nUS[        R                  R                  XU-  5      -  -
  nUS:X  a  S[        R                  " X5      -  nOUS:X  a  UnOUS:X  a  UnOSn[        U5      e[        R                  nSn	OUS:X  a5  Sn
[        R                  " U 5      [        R                  " Xb-  5      -
  U
-  nOUS:X  a;  Sn
[        R                  " U S-   5      [        R                  " Xb-  S-   5      -
  U
-  nOsUS:X  a_  Sn
[        R                  R                  S5      n[        R                  " XS-  S-   S-  -   5      [        R                  " Xb-  5      -
  U
-  nO[        SU-  5      eU	S:X  a  [        USU5      u  p[        U[        R                  " WSS5      U	UUUUS9nU$ )aQ  Test for one sample poisson mean or rate

Parameters
----------
count : array_like
    Observed count, number of events.
nobs : arrat_like
    Currently this is total exposure time of the count variable.
    This will likely change.
value : float, array_like
    This is the value of poisson rate under the null hypothesis.
method : str
    Method to use for confidence interval.
    This is required, there is currently no default method.
    See Notes for available methods.
alternative : {'two-sided', 'smaller', 'larger'}
    alternative hypothesis, which can be two-sided or either one of the
    one-sided tests.
dispersion : float
    Dispersion scale coefficient for Poisson QMLE. Default is that the
    data follows a Poisson distribution. Dispersion different from 1
    correspond to excess-dispersion in Poisson quasi-likelihood (GLM).
    Dispersion coeffficient different from one is currently only used in
    wald and score method.

Returns
-------
HolderTuple instance with test statistic, pvalue and other attributes.

Notes
-----
The implementatio of the hypothesis test is mainly based on the references
for the confidence interval, see confint_poisson.

Available methods are:

- "score" : based on score test, uses variance under null value
- "wald" : based on wald test, uses variance base on estimated rate.
- "waldccv" : based on wald test with 0.5 count added to variance
  computation. This does not use continuity correction for the center of
  the confidence interval.
- "exact-c" central confidence interval based on gamma distribution
- "midp-c" : based on midp correction of central exact confidence interval.
  this uses numerical inversion of the test function. not vectorized.
- "sqrt" : based on square root transformed counts
- "sqrt-a" based on Anscombe square root transformation of counts + 3/8.

See Also
--------
confint_poisson

9method needs to be specified, currently no default method   )r   waldccr	   z:excess dispersion only supported in wald and score methodsnormalr   r         ?r	   r
   r   	two-sided   largersmallerz8alternative should be "two-sided", "larger" or "smaller"Poissonr   r         ?r   g?   unknown method %sr   )	statisticpvaluedistributionmethodalternativeratenobs)
ValueErrornpr   r   normsf
startswithpoissoncdfpmfminimumnanisfr   r   clip)countr)   valuer&   r'   
dispersionnr(   msgdiststdr#   r$   pv1pv2critress                    jC:\Users\julio\OneDrive\Documentos\Trabajo\Ideas Frescas\venv\Lib\site-packages\statsmodels/stats/rates.pytest_poissonrB   1   s   n 	A9D~IoQ44NCS/!Dggj'!+,\S(		9	
 ggj37N3a78\S(		7	ggj(1,-\S(	y)			9	%	%):):8)D)Dmm5y1mmuqy!)4X&&emm//5yAAACemm//5yAAAC+%C--FH$FI%FLCS/!FF		6	WWU^bggai&88C?		8	WWUU]+bggai%6G.HHCO		8	zz~~e$WWUAgkR%778WWQY'(+./	
 ,v566x+Iq+F	
wwvq!$
C J    c                 Z	   UnX-  nUS-  nUc  Sn[        U5      eUS:X  aB  [        R                  R                  U5      [        R
                  " XT-  5      -  nXW-
  XW-   4nGO(US:X  aI  [        R                  R                  U5      [        R
                  " USU-  -   U-  5      -  nXW-
  XW-   4nGOUS:X  aZ  [        R                  R                  U5      n	X	S-  S-  -   n
U	[        R
                  " X	S-  S-  -   5      -  nX-
  U-  X-   U-  4nGOyUS:X  a  [        XSU-  SS	S
9nGObUS:X  aQ  [        R                  R                  U5      n	XYS-  SU-  -  -   n
U	[        R
                  " XT-  5      -  nX-
  X-   4nGOUS:X  aU  [        R                  R                  U5      n	X	S-  S-  -   n
U	[        R
                  " U S-   5      -  nX-
  U-  X-   U-  4nGOUS:X  a  [        R                  R                  U5      n	[        R
                  " [        R                  " U S-   S-
  S5      5      n[        R
                  " U S-   S-   5      nU	S-  n[        R                  " X-
  S5      S-  S-
  U-  X-   S-  S-
  U-  4nGOUS:X  an  [        R                  R                  U5      n	[        R
                  " U S-   5      n
U	S-  n[        R                  " X-
  S5      S-  S-
  U-  X-   S-  S-
  U-  4nGOUS:X  ap  [        R                  R                  U5      n	[        R
                  " X	S-  S-   S-  -   5      n
U	S-  n[        R                  " X-
  S5      S-  U-  X-   S-  U-  4nGOUS;   a  [        R                  R                  X05      U-  n[        R                  R                  X0S-   5      U-  n[        R                  " U5      R                  5       (       a6  [        R                  " U5      S:X  a  SnOSU[        R                  " U5      '   X4nOnUR                  S5      (       aJ  U S-   n[        R                  R                  X?5      U-  [        R                  R                  X?5      U-  4nO[        SU-  5      e[        R                  " US   S5      US   4nU$ )uP  Confidence interval for a Poisson mean or rate

The function is vectorized for all methods except "midp-c", which uses
an iterative method to invert the hypothesis test function.

All current methods are central, that is the probability of each tail is
smaller or equal to alpha / 2. The one-sided interval limits can be
obtained by doubling alpha.

Parameters
----------
count : array_like
    Observed count, number of events.
exposure : arrat_like
    Currently this is total exposure time of the count variable.
    This will likely change.
method : str
    Method to use for confidence interval
    This is required, there is currently no default method
alpha : float in (0, 1)
    Significance level, nominal coverage of the confidence interval is
    1 - alpha.

Returns
-------
tuple (low, upp) : confidence limits.

Notes
-----
Methods are mainly based on Barker (2002) [1]_ and Swift (2009) [3]_.

Available methods are:

- "exact-c" central confidence interval based on gamma distribution
- "score" : based on score test, uses variance under null value
- "wald" : based on wald test, uses variance base on estimated rate.
- "waldccv" : based on wald test with 0.5 count added to variance
  computation. This does not use continuity correction for the center of
  the confidence interval.
- "midp-c" : based on midp correction of central exact confidence interval.
  this uses numerical inversion of the test function. not vectorized.
- "jeffreys" : based on Jeffreys' prior. computed using gamma distribution
- "sqrt" : based on square root transformed counts
- "sqrt-a" based on Anscombe square root transformation of counts + 3/8.
- "sqrt-centcc" will likely be dropped. anscombe with continuity corrected
  center.
  (Similar to R survival cipoisson, but without the 3/8 right shift of
  the confidence interval).

sqrt-cent is the same as sqrt-a, using a different computation, will be
deleted.

sqrt-v is a corrected square root method attributed to vandenbrouke, which
might also be deleted.

Todo:

- missing dispersion,
- maybe split nobs and exposure (? needed in NB). Exposure could be used
  to standardize rate.
- modified wald, switch method if count=0.

See Also
--------
test_poisson

References
----------
.. [1] Barker, Lawrence. 2002. “A Comparison of Nine Confidence Intervals
   for a Poisson Parameter When the Expected Number of Events Is ≤ 5.”
   The American Statistician 56 (2): 85–89.
   https://doi.org/10.1198/000313002317572736.
.. [2] Patil, VV, and HV Kulkarni. 2012. “Comparison of Confidence
   Intervals for the Poisson Mean: Some New Aspects.”
   REVSTAT–Statistical Journal 10(2): 211–27.
.. [3] Swift, Michael Bruce. 2009. “Comparison of Confidence Intervals for
   a Poisson Mean – Further Considerations.” Communications in Statistics -
   Theory and Methods 38 (5): 748–59.
   https://doi.org/10.1080/03610920802255856.

r   r   r   r   r   r	      r   r
   )alphar&   method_startr   r   r    r   r   r   r   r!   )gammar
   r   g        r   r"   )r*   r   r,   r4   r+   r   _invert_test_confintmaximumrH   ppfisnananysizer.   )r6   exposurer&   rF   r9   r(   r:   whalfcir?   center
center_low
center_upplowuppcountcs                   rA   confint_poissonrX      sQ   d 	ADAIE~Io

u%(99lDL)	9	 

u%a10D(EElDL)	7	zz~~e$q1$rwwuQw{233~"V^q$89	8	!%!e)H/8: 
6	zz~~e$a1q5))rwwtx((nfn-	;	zz~~e$q1$rwwuu}--~"V^q$89	=	 zz~~e$WWRZZ(;Q?@
WWUU]S01
q

:-q1A5=B"Q&.!35 
8	zz~~e$'q

6>1-1E9Q>"U*a/1 
8	zz~~e$'A+!334qjj+a/!3fnq5H15LL	'	'kkooe+h6kkooe1W-888C=wws|q %(BHHSM"Z			6	"	"kkooe,x7kkooe,x79 ,v566
**RUA
1	&BIrC   c                    SU-
  nUnUS:w  a  US-  n[        XXHS9u  pUS:w  a  X-  n	X-  n
US:X  aJ  [        R                  R                  US-  U	5      n[        R                  R                  SUS-  -
  U
5      nOaUS:X  a&  Sn[        R                  R                  SU-
  U
5      nO5US:X  a/  [        R                  R                  Xy5      n[        R
                  n[        R                  " WS5      nUW4$ )u  tolerance interval for a poisson observation

Parameters
----------
count : array_like
    Observed count, number of events.
exposure : arrat_like
    Currently this is total exposure time of the count variable.
prob : float in (0, 1)
    Probability of poisson interval, often called "content".
    With known parameters, each tail would have at most probability
    ``1 - prob / 2`` in the two-sided interval.
exposure_new : float
    Exposure of the new or predicted observation.
method : str
    Method to used for confidence interval of the estimate of the
    poisson rate, used in `confint_poisson`.
    This is required, there is currently no default method.
alpha : float in (0, 1)
    Significance level for the confidence interval of the estimate of the
    Poisson rate. Nominal coverage of the confidence interval is
    1 - alpha.
alternative : {"two-sider", "larger", "smaller")
    The tolerance interval can be two-sided or one-sided.
    Alternative "larger" provides the upper bound of the confidence
    interval, larger counts are outside the interval.

Returns
-------
tuple (low, upp) of limits of tolerance interval.
    The tolerance interval is a closed interval, that is both ``low`` and
    ``upp`` are in the interval.

Notes
-----
verified against R package tolerance `poistol.int`

See Also
--------
confint_poisson
confint_quantile_poisson

References
----------
.. [1] Hahn, Gerald J., and William Q. Meeker. 1991. Statistical Intervals:
   A Guide for Practitioners. 1st ed. Wiley Series in Probability and
   Statistics. Wiley. https://doi.org/10.1002/9780470316771.
.. [2] Hahn, Gerald J., and Ramesh Chandra. 1981. “Tolerance Intervals for
   Poisson and Binomial Variables.” Journal of Quality Technology 13 (2):
   100–110. https://doi.org/10.1080/00224065.1981.11980998.

r   r   r   r&   rF   r   r   r   rX   r   r/   rK   r+   infrJ   )r6   rO   probexposure_newr&   rF   r'   	prob_tailalpha_rU   rV   low_predupp_preds                rA   tolerance_int_poissonrc   t  s    n DIFk!uvLHCqk!==$$Y]C8==$$QQ%6<		 ==$$Q]C8			!==$$Y466 zz(A&HXrC   c                    UnUS:w  a  US-  n[        XXGS9u  pUS:w  a  X-  nX-  n	US:X  a?  [        R                  R                  X(5      n
[        R                  R                  X)5      nO]US:X  a"  Sn
[        R                  R                  X)5      nO5US:X  a/  [        R                  R                  X(5      n
[        R
                  n[        R                  " W
S5      n
U
W4$ )au  confidence interval for quantile of poisson random variable

Parameters
----------
count : array_like
    Observed count, number of events.
exposure : arrat_like
    Currently this is total exposure time of the count variable.
prob : float in (0, 1)
    Probability for the quantile, e.g. 0.95 to get the upper 95% quantile.
    With known mean mu, the quantile would be poisson.ppf(prob, mu).
exposure_new : float
    Exposure of the new or predicted observation.
method : str
    Method to used for confidence interval of the estimate of the
    poisson rate, used in `confint_poisson`.
    This is required, there is currently no default method.
alpha : float in (0, 1)
    Significance level for the confidence interval of the estimate of the
    Poisson rate. Nominal coverage of the confidence interval is
    1 - alpha.
alternative : {"two-sider", "larger", "smaller")
    The tolerance interval can be two-sided or one-sided.
    Alternative "larger" provides the upper bound of the confidence
    interval, larger counts are outside the interval.

Returns
-------
tuple (low, upp) of limits of tolerance interval.
The confidence interval is a closed interval, that is both ``low`` and
``upp`` are in the interval.

See Also
--------
confint_poisson
tolerance_int_poisson

References
----------
Hahn, Gerald J, and William Q Meeker. 2010. Statistical Intervals: A Guide
for Practitioners.
r   r   rZ   r   r   r   r   r[   )r6   rO   r]   r^   r&   rF   r'   r`   rU   rV   ra   rb   s               rA   confint_quantile_poissonre     s    Z Fk!uvLHCqk!==$$T/==$$T/		 ==$$T/			!==$$T/66 zz(A&HXrC   c                    ^ ^^^ UU UU4S jn[        T TUS9n[        R                  " XVS   SSS9n[        R                  " XVS   SSS9n[        R                  " U5      S:X  d   eUS   US   4$ )z6invert hypothesis test to get confidence interval
    c                 2   > [        TTU TS9S   T-
  S-  nU$ )N)r7   r&   r   r   )rB   )rvrF   r6   r&   r)   s     rA   func"_invert_test_confint.<locals>.func  s-    %Qv>qArC   )r&   r   :0yE>Fxtoldispr   )rX   r   fminr+   rN   )	r6   r)   rF   r&   rG   rj   rQ   rU   rV   s	   ````     rA   rI   rI   
  sq    
 
 
\	:B
--e$U
;C
--e$U
;C773<1q63q6>rC   c           	         ^ ^^^^^^ UUU UUUU4S jn[        T TTTUTS9n	[        R                  " XS   SSS9n
[        R                  " XS   SSS9n[        R                  " U
5      S:X  d   eU
S   US   4$ )zAinvert hypothesis test to get confidence interval for 2indep
    c           
      8   > [        TTTTU TTS9S   T-
  S-  nU$ )N)r7   r&   comparer   r   )test_poisson_2indep)	rh   ri   rF   rs   count1count2	exposure1	exposure2r&   s	     rA   rj   )_invert_test_confint_2indep.<locals>.func%  sB     Y	VW    rC   )r&   rs   r   rl   Frm   r   )confint_poisson_2indepr   rp   r+   rN   )ru   rw   rv   rx   rF   r&   rs   rG   rj   rQ   rU   rV   s   ```````     rA   _invert_test_confint_2indepr{     s{      
 	69'3W
FB
--e$U
;C
--e$U
;C773<1q63q6>rC   )	r   r	   	score-logwald-log
exact-cond	cond-midpr   etest-score
etest-wald)r   r	   r   r   r   )ratiodiff)r   r	   r|   r}   sqrtccmover)r   r	   r   r   c
                    [        [        R                  XX#/5      u  ppX-  nX-  X-  nnSnUS:X  Gau  Uc  SnUb  [        R                  " S[
        5        UnUc  Uc  S=pEOUnUnUU-  nUS;   a'  XU-  -
  [        R                  " X-   U-  5      -  nSnGOvUS;   a*  XU-  -
  [        R                  " XUS	-  -  -   5      -  nSnGOFUS
;   aZ  [        R                  " X-  5      [        R                  " U5      -
  nU[        R                  " S	SU-  -   U-   X-   -  5      -  nSnGOUS;   aS  [        R                  " X-  5      [        R                  " U5      -
  [        R                  " SU
-  SU-  -   5      -  nSnGOUS;   aY  S	[        R                  " U
S-   5      [        R                  " US-   U-  5      -
  -  nU[        R                  " SU-   5      -  nSnGO.US;   ae  SSKJ	n  USU-   -  nX-   n[        R                  nUR                  U
UUUS9nUS;   a'  US[        R                  R                  U
UU5      -  -
  nSnGOUR                  S5      (       a8  UR!                  S5      (       a  SnOSnU	c  0 n	[#        XX#4UUUS.U	D6u  nnSnGOu[%        SU S35      eUS:X  GaT  Uc  SnUS;   a+  UU-
  U-
  [        R                  " X-  UU-  -   5      -  nSnGO)US;   a9  UU-
  U-
  nU[        R                  " U S-   US	-  -  US-   US	-  -  -   5      -  nSnOUS;   aq  X-   nUX-   -  nUU-
  nSU[        R                  " US	-  SU-  U-  X-   -  -   5      -   -  nUU-   nUU-
  U-
  [        R                  " UU-  UU-  -   5      -  nUU4nSnOsUR                  S5      (       aC  UR!                  S5      (       a  SnOSnUS:X  a  US-   nU	c  0 n	[#        XX#4UUSUS.U	D6u  nnSnO[%        SU S35      e['        S 5      eUS:X  a  [)        USU5      u  nnUU4n UU-  n!UU-
  n"[+        UWUUUUU U!U"UUUS!9n#U#$ )"u  Test for comparing two sample Poisson intensity rates.

Rates are defined as expected count divided by exposure.

The Null and alternative hypothesis for the rates, rate1 and rate2, of two
independent Poisson samples are

for compare = 'diff'

- H0: rate1 - rate2 - value = 0
- H1: rate1 - rate2 - value != 0  if alternative = 'two-sided'
- H1: rate1 - rate2 - value > 0   if alternative = 'larger'
- H1: rate1 - rate2 - value < 0   if alternative = 'smaller'

for compare = 'ratio'

- H0: rate1 / rate2 - value = 0
- H1: rate1 / rate2 - value != 0  if alternative = 'two-sided'
- H1: rate1 / rate2 - value > 0   if alternative = 'larger'
- H1: rate1 / rate2 - value < 0   if alternative = 'smaller'

Parameters
----------
count1 : int
    Number of events in first sample, treatment group.
exposure1 : float
    Total exposure (time * subjects) in first sample.
count2 : int
    Number of events in second sample, control group.
exposure2 : float
    Total exposure (time * subjects) in second sample.
ratio_null: float
    Ratio of the two Poisson rates under the Null hypothesis. Default is 1.
    Deprecated, use ``value`` instead.

    .. deprecated:: 0.14.0

        Use ``value`` instead.

value : float
    Value of the ratio or difference of 2 independent rates under the null
    hypothesis. Default is equal rates, i.e. 1 for ratio and 0 for diff.

    .. versionadded:: 0.14.0

        Replacement for ``ratio_null``.

method : string
    Method for the test statistic and the p-value. Defaults to `'score'`.
    see Notes.

    ratio:

    - 'wald': method W1A, wald test, variance based on observed rates
    - 'score': method W2A, score test, variance based on estimate under
      the Null hypothesis
    - 'wald-log': W3A, uses log-ratio, variance based on observed rates
    - 'score-log' W4A, uses log-ratio, variance based on estimate under
      the Null hypothesis
    - 'sqrt': W5A, based on variance stabilizing square root transformation
    - 'exact-cond': exact conditional test based on binomial distribution
       This uses ``binom_test`` which is minlike in the two-sided case.
    - 'cond-midp': midpoint-pvalue of exact conditional test
    - 'etest' or 'etest-score: etest with score test statistic
    - 'etest-wald': etest with wald test statistic

    diff:

    - 'wald',
    - 'waldccv'
    - 'score'
    - 'etest-score' or 'etest: etest with score test statistic
    - 'etest-wald': etest with wald test statistic

compare : {'diff', 'ratio'}
    Default is "ratio".
    If compare is `ratio`, then the hypothesis test is for the
    rate ratio defined by ratio = rate1 / rate2.
    If compare is `diff`, then the hypothesis test is for
    diff = rate1 - rate2.
alternative : {"two-sided" (default), "larger", smaller}
    The alternative hypothesis, H1, has to be one of the following

    - 'two-sided': H1: ratio, or diff, of rates is not equal to value
    - 'larger' :   H1: ratio, or diff, of rates is larger than value
    - 'smaller' :  H1: ratio, or diff, of rates is smaller than value
etest_kwds: dictionary
    Additional optional parameters to be passed to the etest_poisson_2indep
    function, namely y_grid.

Returns
-------
results : instance of HolderTuple class
    The two main attributes are test statistic `statistic` and p-value
    `pvalue`.

See Also
--------
tost_poisson_2indep
etest_poisson_2indep

Notes
-----
The hypothesis tests for compare="ratio" are based on Gu et al 2018.
The e-tests are also based on ...

- 'wald': method W1A, wald test, variance based on separate estimates
- 'score': method W2A, score test, variance based on estimate under Null
- 'wald-log': W3A, wald test for log transformed ratio
- 'score-log' W4A, score test for log transformed ratio
- 'sqrt': W5A, based on variance stabilizing square root transformation
- 'exact-cond': exact conditional test based on binomial distribution
- 'cond-midp': midpoint-pvalue of exact conditional test
- 'etest': etest with score test statistic
- 'etest-wald': etest with wald test statistic

The hypothesis test for compare="diff" are mainly based on Ng et al 2007
and ...

- wald
- score
- etest-score
- etest-wald

Note the etests use the constraint maximum likelihood estimate (cmle) as
parameters for the underlying Poisson probabilities. The constraint cmle
parameters are the same as in the score test.
The E-test in Krishnamoorty and Thomson uses a moment estimator instead of
the score estimator.

References
----------
.. [1] Gu, Ng, Tang, Schucany 2008: Testing the Ratio of Two Poisson Rates,
   Biometrical Journal 50 (2008) 2, 2008

.. [2] Ng, H. K. T., K. Gu, and M. L. Tang. 2007. “A Comparative Study of
   Tests for the Difference of Two Poisson Means.”
   Computational Statistics & Data Analysis 51 (6): 3085–99.
   https://doi.org/10.1016/j.csda.2006.02.004.

Nr   r	   /'ratio_null' is deprecated, use 'value' keywordr   r	   r   r   r   )r|   )r}   )r   r    )r~   r   r   )
proportion)propr'   )r   r   binomialetestr   )r7   r&   r'   r/   method "" not recognizedr   r   rE   z-scorer7   r&   rs   r'   #"compare" needs to be ratio or diff)r#   r$   r%   rs   r&   r'   ratesr   r   r7   
rates_cmle
ratio_null)mapr+   asarraywarningswarnFutureWarningr   logstatsmodels.statsr   r3   
binom_testr   binomr1   r.   endswithetest_poisson_2indepr*   NotImplementedErrorr   r   )$ru   rw   rv   rx   r7   r   r&   rs   r'   
etest_kwdsy1n1y2n2drate1rate2r   rh   r_dstatr;   r   bpy_totalr$   method_etestcount_pooledrate_pooleddtr2_cmler1_cmler   r   r   r@   s$                                       rA   rt   rt   \  s   f f%KLNBB
A7BG5EJ'>F!MMK')E%-!""EJ J!eYcMRWWbg_%==DDxcMRWWRsAv+-=%>>DD}$FF27ObffSk1DBGGQS[3.27;<<DD|#FF27ObffSk1RWWQVa"f_5MMDDxV,rwwVs7J/KKLDBGGAG$$DD224CBgG66D**2wR7B + DF&#GR(H"HHDw''v&&%&!
/6L<A#L@JLLD& Dxx/?@AA	F	=EXEME)RWWUZ%"*5L-MMDD{"EME)DBGGVc\RU2fslb!e5KKLLDDy 7L&"'2Ku$BR"''"a%!e)b.BG2L*L"MMNGoGU]U*GGGbL7R<789D!7+JDw''v&&%&W$#h.F!
/67<A#V'7 ,67LD&
 Dxx/?@AA!"GHHx&tQ<fENEEME5=D
##'%#"-!!!!+!+C JrC   c                     X-   nX-  X#-  pXaU-   -  n	X-
  n
SU
[         R                  " U
S-  SU-  U-  X-   -  -   5      -   -  nX-   nSnX-  X-  -   nXx-
  U-
  [         R                  " X-   5      -  nU(       a  XU4$ U$ )zGscore test and cmle for difference of 2 independent poisson rates

    r   r   rE   #B;r+   r   )r   r   r   r   r7   return_cmler   r   r   r   r   r   r   epsri   r   s                   rA   _score_diffr   x  s     7L7BG5r'*K		BR"''"a%!e)b.BG*D"DEEFGoG
Cw|#AME!RWWQW%55Dg%%rC   c           	        ^^^ ^!^" [        [        R                  XX#/5      u  nm nm!T!T -  nSmUS:X  ag  Uc  Tc  SmO Ub  [        R                  " S[
        5        UmTnX-  m"X-   T!-  ST"-   -  nX-  nUS;   a  UU"4S jnObUS;   a  UU"4S	 jnOT[        S
5      eUS:X  aC  Tc  Sm[        UT UT!TSS9nUu  nnnUS;   a	  U U!U4S jnOUS;   a
  UU U!U4S jnO[        S
5      eWnWnT U-  nT!U-  nW" X5      nU	b  [        R                  " S[
        5        U
b  U
OU	n
U
cP  [        R                  R                  S[        UU5      5      n[        US5      n[        R                  " US-   5      n
O1[        R                  " U
5      n
U
R                  S:w  a  [        S5      e[        R                  R                  U
U5      n[        R                  R                  U
U5      nU" U
SS2S4   U
SSS24   5      nSmUS;   a1  [        R                  " U5      [        R                  " U5      T-
  :  nO)US;   a	  UUT-
  :  nOUS;   a	  UUT-   :*  nO[        S5      eUSS2S4   USSS24   -  U   R!                  5       nUU4$ )u
  
E-test for ratio of two sample Poisson rates.

Rates are defined as expected count divided by exposure. The Null and
alternative hypothesis for the rates, rate1 and rate2, of two independent
Poisson samples are:

for compare = 'diff'

- H0: rate1 - rate2 - value = 0
- H1: rate1 - rate2 - value != 0  if alternative = 'two-sided'
- H1: rate1 - rate2 - value > 0   if alternative = 'larger'
- H1: rate1 - rate2 - value < 0   if alternative = 'smaller'

for compare = 'ratio'

- H0: rate1 / rate2 - value = 0
- H1: rate1 / rate2 - value != 0  if alternative = 'two-sided'
- H1: rate1 / rate2 - value > 0   if alternative = 'larger'
- H1: rate1 / rate2 - value < 0   if alternative = 'smaller'

Parameters
----------
count1 : int
    Number of events in first sample
exposure1 : float
    Total exposure (time * subjects) in first sample
count2 : int
    Number of events in first sample
exposure2 : float
    Total exposure (time * subjects) in first sample
ratio_null: float
    Ratio of the two Poisson rates under the Null hypothesis. Default is 1.
    Deprecated, use ``value`` instead.

    .. deprecated:: 0.14.0

        Use ``value`` instead.

value : float
    Value of the ratio or diff of 2 independent rates under the null
    hypothesis. Default is equal rates, i.e. 1 for ratio and 0 for diff.

    .. versionadded:: 0.14.0

        Replacement for ``ratio_null``.

method : {"score", "wald"}
    Method for the test statistic that defines the rejection region.
alternative : string
    The alternative hypothesis, H1, has to be one of the following

    - 'two-sided': H1: ratio of rates is not equal to ratio_null (default)
    - 'larger' :   H1: ratio of rates is larger than ratio_null
    - 'smaller' :  H1: ratio of rates is smaller than ratio_null

y_grid : None or 1-D ndarray
    Grid values for counts of the Poisson distribution used for computing
    the pvalue. By default truncation is based on an upper tail Poisson
    quantiles.

ygrid : None or 1-D ndarray
    Same as y_grid. Deprecated. If both y_grid and ygrid are provided,
    ygrid will be ignored.

    .. deprecated:: 0.14.0

        Use ``y_grid`` instead.

Returns
-------
stat_sample : float
    test statistic for the sample
pvalue : float

References
----------
Gu, Ng, Tang, Schucany 2008: Testing the Ratio of Two Poisson Rates,
Biometrical Journal 50 (2008) 2, 2008
Ng, H. K. T., K. Gu, and M. L. Tang. 2007. “A Comparative Study of Tests
for the Difference of Two Poisson Means.” Computational Statistics & Data
Analysis 51 (6): 3085–99. https://doi.org/10.1016/j.csda.2006.02.004.

r   r   Nr   r   r   c                 P   > XT-  -
  [         R                  " X-   T-  T-   5      -  $ Nr   x1x2r   r   s     rA   	stat_func'etest_poisson_2indep.<locals>.stat_func  s(    #X"'S31F)GGGrC   r   c                 V   > XT-  -
  [         R                  " XTS-  -  -   T-   5      -  $ )Nr   r   r   s     rA   r   r      s-    #X36k1AC1G)HHHrC   zmethod not recognizedr   r   Tr7   r   c                    > [        U TUTTS9$ )N)r7   )r   )r   r   r   r   r7   s     rA   r   r     s    "2r2r??rC   c                 r   > U T-  UT-  p2X#-
  T-
  nU[         R                  " UT-  UT-  -   T-   5      -  nU$ r   r   )	r   r   r   r   r   r   r   r   r7   s	        rA   r   r     sH    !BwRu-
URZ 7# =>>rC   zygrid is deprecated, use y_gridgvIh%<=d   z.y_grid needs to be None or 1-dimensional arraygV瞯<)r   z2-sided2s)r   l)r   szinvalid alternative)r   r+   r   r   r   r   r*   r   r   r/   r4   maxarangendimr1   abssum)#ru   rw   rv   rx   r   r7   r&   rs   r'   ygridy_gridr   r   r   rh   
rate2_cmle
rate1_cmler   tmp_r   r   mean1mean2stat_sample	thresholdpdf1pdf2
stat_spacemaskr$   r   r   r   r   s#        `                         @@@@rA   r   r     s   p f%KLNBB
RA
C'%-E#MMK')Eeg^q3w/
^
YH xI 455	F	=E"b"b4H$'!:zY@ @ x  455 EEJEJEB#K7G)VuF ~MM%%eS->?		3'	9q=)F#;;!MNN==VU+D==VU+D6!T'?F47O<J
C44vvj!bff[&9C&?@		'kC/0	(	(kC/0.//AtG}tD!G},d388:FrC   c                 p   [        XX#XFUSS9n[        XX#XVUSS9n	[        R                  " UR                  U	R                  :  [        5      n
[        R
                  " XR                  U	R                  /5      n[        R
                  " XR                  U	R                  /5      n[        UUUUXE4UU	SS9nU$ )a  Equivalence test based on two one-sided `test_proportions_2indep`

This assumes that we have two independent poisson samples.

The Null and alternative hypothesis for equivalence testing are

for compare = 'ratio'

- H0: rate1 / rate2 <= low or upp <= rate1 / rate2
- H1: low < rate1 / rate2 < upp

for compare = 'diff'

- H0: rate1 - rate2 <= low or upp <= rate1 - rate2
- H1: low < rate - rate < upp

Parameters
----------
count1 : int
    Number of events in first sample
exposure1 : float
    Total exposure (time * subjects) in first sample
count2 : int
    Number of events in second sample
exposure2 : float
    Total exposure (time * subjects) in second sample
low, upp :
    equivalence margin for the ratio or difference of Poisson rates
method: string
    TOST uses ``test_poisson_2indep`` and has the same methods.

    ratio:

    - 'wald': method W1A, wald test, variance based on observed rates
    - 'score': method W2A, score test, variance based on estimate under
      the Null hypothesis
    - 'wald-log': W3A, uses log-ratio, variance based on observed rates
    - 'score-log' W4A, uses log-ratio, variance based on estimate under
      the Null hypothesis
    - 'sqrt': W5A, based on variance stabilizing square root transformation
    - 'exact-cond': exact conditional test based on binomial distribution
       This uses ``binom_test`` which is minlike in the two-sided case.
    - 'cond-midp': midpoint-pvalue of exact conditional test
    - 'etest' or 'etest-score: etest with score test statistic
    - 'etest-wald': etest with wald test statistic

    diff:

    - 'wald',
    - 'waldccv'
    - 'score'
    - 'etest-score' or 'etest: etest with score test statistic
    - 'etest-wald': etest with wald test statistic

Returns
-------
results : instance of HolderTuple class
    The two main attributes are test statistic `statistic` and p-value
    `pvalue`.

References
----------
Gu, Ng, Tang, Schucany 2008: Testing the Ratio of Two Poisson Rates,
Biometrical Journal 50 (2008) 2, 2008

See Also
--------
test_poisson_2indep
confint_poisson_2indep
r   r   r   0Equivalence test for 2 independent Poisson rates)r#   r$   r&   rs   equiv_limitsresults_largerresults_smallertitle)rt   r+   r   r$   intchooser#   r   )ru   rw   rv   rx   rU   rV   r&   rs   tt1tt2idx_maxr#   r$   r@   s                 rA   tost_poisson_2indepr   L  s    R f$'&-*24C f$'&-*35C jjcjj0#6G		'MM3==#ABIYYwSZZ 89F
	##%$':%(&)NC JrC   c                 n   [        XX#XFUSS9n[        XX#XVUSS9n	[        R                  " UR                  U	R                  :  [        5      n
S[        R
                  " UR                  U	R                  5      -  n[        R                  " XR                  U	R                  /5      n[        UUUUU	SS9nU$ )u  Test for non-equivalence, minimum effect for poisson.

This reverses null and alternative hypothesis compared to equivalence
testing. The null hypothesis is that the effect, ratio (or diff), is in
an interval that specifies a range of irrelevant or unimportant
differences between the two samples.

The Null and alternative hypothesis comparing the ratio of rates are

for compare = 'ratio':

- H0: low < rate1 / rate2 < upp
- H1: rate1 / rate2 <= low or upp <= rate1 / rate2

for compare = 'diff':

- H0: rate1 - rate2 <= low or upp <= rate1 - rate2
- H1: low < rate - rate < upp


Notes
-----
This is implemented as two one-sided tests at the minimum effect boundaries
(low, upp) with (nominal) size alpha / 2 each.
The size of the test is the sum of the two one-tailed tests, which
corresponds to an equal-tailed two-sided test.
If low and upp are equal, then the result is the same as the standard
two-sided test.

The p-value is computed as `2 * min(pvalue_low, pvalue_upp)` in analogy to
two-sided equal-tail tests.

In large samples the nominal size of the test will be below alpha.

References
----------
.. [1] Hodges, J. L., Jr., and E. L. Lehmann. 1954. Testing the Approximate
   Validity of Statistical Hypotheses. Journal of the Royal Statistical
   Society, Series B (Methodological) 16: 261–68.

.. [2] Kim, Jae H., and Andrew P. Robinson. 2019. “Interval-Based
   Hypothesis Testing and Its Applications to Economics and Finance.”
   Econometrics 7 (2): 21. https://doi.org/10.3390/econometrics7020021.

r   r   r   r   r   )r#   r$   r&   r   r   r   )	rt   r+   r   r$   r   r2   r   r#   r   )ru   rw   rv   rx   rU   rV   r&   rs   r   r   idx_minr$   r#   r@   s                 rA   nonequivalence_poisson_2indepr     s    ^ f$'*35C f$'*24C
 jjcjj0#6GCJJ

33F		'MM3==#ABI
	##%(&)NC JrC   c                    [        [        R                  XX#/5      u  ppX-  X-  pUS-  nUS:X  Gae  US:X  a  [        XX#US-  SSSS9u  pX4nGO&US:X  a  [        R
                  R                  U5      nSnU U-   UU-   -  U-  U	-  n[        R                  " SU U-   -  SUU-   -  -   5      nU[        R                  " U* U-  5      -  U[        R                  " UU-  5      -  4nGOUS	:X  a  [        XX#US-  S	SSS9u  pX4nGOpUS:X  a  [        R
                  R                  U5      nU S
-   US
-   -  U-  U	-  n[        R                  " SU S
-   -  SUS
-   -  -   5      nU[        R                  " U* U-  5      -  U[        R                  " UU-  5      -  4nOUS:X  a  [        R
                  R                  U5      n[        R                  " U S
-   US
-   -  5      nS
[        R                  " U S
-   U-   S
-   SU-  -
  5      -  nUS
-   SUS-  -  -
  nUUU-  -
  U-  nUUU-  -   U-  nUS-  US-  4nO@US:X  a+  Un[        XUSU-  S9n[        XUSU-  S9n[        XUUSS9nO[        SU S35      e[        R                  " US   S5      US   4nU$ US:X  Ga  US;   aO  [        R
                  R                  U5      nX-
  nU[        R                  " X-  X-  -   5      -  nUU-
  UU-   4nU$ US;   a_  [        R
                  R                  U5      nX-
  n[        R                  " U S
-   U	S-  -  US
-   US-  -  -   5      nUU-  nUU-
  UU-   4nU$ US:X  a  [        XX#US-  SSSS9u  pX4nU$ US:X  a,  Un[        XUSU-  S9n[        XUSU-  S9n[        XUUSS9nU$ [        SU S35      e[        S5      e)a  Confidence interval for ratio or difference of 2 indep poisson rates.

Parameters
----------
count1 : int
    Number of events in first sample.
exposure1 : float
    Total exposure (time * subjects) in first sample.
count2 : int
    Number of events in second sample.
exposure2 : float
    Total exposure (time * subjects) in second sample.
method : string
    Method for the test statistic and the p-value. Defaults to `'score'`.
    see Notes.

    ratio:

    - 'wald': NOT YET, method W1A, wald test, variance based on observed
      rates
    - 'waldcc' :
    - 'score': method W2A, score test, variance based on estimate under
      the Null hypothesis
    - 'wald-log': W3A, uses log-ratio, variance based on observed rates
    - 'score-log' W4A, uses log-ratio, variance based on estimate under
      the Null hypothesis
    - 'sqrt': W5A, based on variance stabilizing square root transformation
    - 'sqrtcc' :
    - 'exact-cond': NOT YET, exact conditional test based on binomial
      distribution
      This uses ``binom_test`` which is minlike in the two-sided case.
    - 'cond-midp': NOT YET, midpoint-pvalue of exact conditional test
    - 'mover' :

    diff:

    - 'wald',
    - 'waldccv'
    - 'score'
    - 'mover'

compare : {'diff', 'ratio'}
    Default is "ratio".
    If compare is `diff`, then the hypothesis test is for
    diff = rate1 - rate2.
    If compare is `ratio`, then the hypothesis test is for the
    rate ratio defined by ratio = rate1 / rate2.
alternative : string
    The alternative hypothesis, H1, has to be one of the following

    - 'two-sided': H1: ratio of rates is not equal to ratio_null (default)
    - 'larger' :   H1: ratio of rates is larger than ratio_null
    - 'smaller' :  H1: ratio of rates is smaller than ratio_null

alpha : float in (0, 1)
    Significance level, nominal coverage of the confidence interval is
    1 - alpha.

Returns
-------
tuple (low, upp) : confidence limits.

r   r   r	   r   )rF   r&   rs   rG   r}   r   r   r|   r   r   g      ?r   rZ   )contrastr   r   r   r   r   r   r   )r   r+   r   r{   r   r,   r4   r   exprX   r   r*   rJ   r   )ru   rw   rv   rx   r&   rs   rF   method_moverr   r   r   r   r   r   rU   rV   rQ   r?   crR   r<   denomlow_sqrtupp_sqrtmethod_pci1ci2halfs                               rA   rz   rz     s^   J f%KLNBB7BG5AIE'W26ai%HC Bz!::>>%(DAqjVaZ025:F''!vz*Q&1*-==>C266D&3,//"&&:L1LMB{"26ai"%HC Bx::>>%(Dslv|4r9B>F''!v|,qFSL/AABC266D&3,//"&&:L1LMBx::>>%(DWWfslv|<=Fv 5 ;dTk IJJCc\D47N2E+u4H+u4HA+x{+Bw#H!"5IC!"5ICc3IB xx/?@AAjjA"BqE*L II 
F	X::>>%(D]F"''%*uz"9::D$-B< I9 {"::>>%(D]F''6C<2q50FSLBE3IIJC#:D$-B. I+ w26ai&HC B I w#H!"5IC!"5ICc3HB I	 xx/?@AA!"GHHrC   c                    SSK Jn  [        [        R                  XU/5      u  pnX2-  nXt-  SU -  SX1-  -  -   -  nU	S:X  a  UnO4U	S:X  a  Xt-  SXS-  -   S-  -  nXU-  XU-  -   -  -  nO[        SU	 S35      e[        R                  " U5      n[        R                  " U5      n[        R                  " X-  5      [        R                  " U5      -
  nU" UX&UUUS	9nS
nU
(       a  [        UUUUUUUUSS9	nU$ U$ )u  Power of test of ratio of 2 independent poisson rates.

This is based on Zhu and Zhu and Lakkis. It does not directly correspond
to `test_poisson_2indep`.

Parameters
----------
rate1 : float
    Poisson rate for the first sample, treatment group, under the
    alternative hypothesis.
rate2 : float
    Poisson rate for the second sample, reference group, under the
    alternative hypothesis.
nobs1 : float or int
    Number of observations in sample 1.
nobs_ratio : float
    Sample size ratio, nobs2 = nobs_ratio * nobs1.
exposure : float
    Exposure for each observation. Total exposure is nobs1 * exposure
    and nobs2 * exposure.
alpha : float in interval (0,1)
    Significance level, e.g. 0.05, is the probability of a type I
    error, that is wrong rejections if the Null Hypothesis is true.
value : float
    Rate ratio, rate1 / rate2, under the null hypothesis.
dispersion : float
    Dispersion coefficient for quasi-Poisson. Dispersion different from
    one can capture over or under dispersion relative to Poisson
    distribution.
method_var : {"score", "alt"}
    The variance of the test statistic for the null hypothesis given the
    rates under the alternative can be either equal to the rates under the
    alternative ``method_var="alt"``, or estimated under the constrained
    of the null hypothesis, ``method_var="score"``.
alternative : string, 'two-sided' (default), 'larger', 'smaller'
    Alternative hypothesis whether the power is calculated for a
    two-sided (default) or one sided test. The one-sided test can be
    either 'larger', 'smaller'.
return_results : bool
    If true, then a results instance with extra information is returned,
    otherwise only the computed power is returned.

Returns
-------
results : results instance or float
    If return_results is False, then only the power is returned.
    If return_results is True, then a results instance with the
    information in attributes is returned.

    power : float
        Power of the test, e.g. 0.8, is one minus the probability of a
        type II error. Power is the probability that the test correctly
        rejects the Null Hypothesis if the Alternative Hypothesis is true.

    Other attributes in results instance include :

    std_null
        standard error of difference under the null hypothesis (without
        sqrt(nobs1))
    std_alt
        standard error of difference under the alternative hypothesis
        (without sqrt(nobs1))

References
----------
.. [1] Zhu, Haiyuan. 2017. “Sample Size Calculation for Comparing Two
   Poisson or Negative Binomial Rates in Noninferiority or Equivalence
   Trials.” Statistics in Biopharmaceutical Research, March.
   https://doi.org/10.1080/19466315.2016.1225594
.. [2] Zhu, Haiyuan, and Hassan Lakkis. 2014. “Sample Size Calculation for
   Comparing Two Negative Binomial Rates.” Statistics in Medicine 33 (3):
   376–87. https://doi.org/10.1002/sim.5947.
.. [3] PASS documentation
r   normal_power_hetr   altr	   r   method_var  not recognizedstd_nullstd_alternativer'   Npower)	r  p_pooledr   std_altnobs1nobs2
nobs_ratiorF   tuple_)	statsmodels.stats.powerr   r   r+   r   r   r   r   r   )r   r   r  r  rO   r7   rF   r8   r'   
method_varreturn_resultsr   r  v1v0r   r  espow_r  r@   s                        rA   power_poisson_ratio_2indepr    s-   l 9bjj5*?@E%E		!e)a:3E.F"F	GBU	w	"a%*<&<q%@@
j E%-?$@AA!K
|?"KLLwwr{HggbkG			.BBx,3(35D H!
 
KrC   c                    [        [        R                  XU/5      u  pnXR-  nX-  SU -  SXQ-  -  -   -  nU	S:X  a  U=pORU	S:X  a=  X-  SX5-  -   S-  -  nXU-  XU-  -   -  -  nX-  SXE-  -   S-  -  nXU-  XU-  -   -  -  nO[        SU	 S35      e[        R                  " X-  5      [        R                  " U5      -
  n[        R                  " X-  5      [        R                  " U5      -
  n[        R
                  " U5      n[        R
                  " U5      n[        R
                  " U5      n[        UUXUUUS9nU
(       a  [        US   [        SS	 UUUUUUUS
S9
nU$ US   $ )u0  Power of equivalence test of ratio of 2 independent poisson rates.

Parameters
----------
rate1 : float
    Poisson rate for the first sample, treatment group, under the
    alternative hypothesis.
rate2 : float
    Poisson rate for the second sample, reference group, under the
    alternative hypothesis.
nobs1 : float or int
    Number of observations in sample 1.
low : float
    Lower equivalence margin for the rate ratio, rate1 / rate2.
upp : float
    Upper equivalence margin for the rate ratio, rate1 / rate2.
nobs_ratio : float
    Sample size ratio, nobs2 = nobs_ratio * nobs1.
exposure : float
    Exposure for each observation. Total exposure is nobs1 * exposure
    and nobs2 * exposure.
alpha : float in interval (0,1)
    Significance level, e.g. 0.05, is the probability of a type I
    error, that is wrong rejections if the Null Hypothesis is true.
value : float
    Difference between rates 1 and 2 under the null hypothesis.
method_var : {"score", "alt"}
    The variance of the test statistic for the null hypothesis given the
    rates uder the alternative, can be either equal to the rates under the
    alternative ``method_var="alt"``, or estimated under the constrained
    of the null hypothesis, ``method_var="score"``.
alternative : string, 'two-sided' (default), 'larger', 'smaller'
    Alternative hypothesis whether the power is calculated for a
    two-sided (default) or one sided test. The one-sided test can be
    either 'larger', 'smaller'.
return_results : bool
    If true, then a results instance with extra information is returned,
    otherwise only the computed power is returned.

Returns
-------
results : results instance or float
    If return_results is False, then only the power is returned.
    If return_results is True, then a results instance with the
    information in attributes is returned.

    power : float
        Power of the test, e.g. 0.8, is one minus the probability of a
        type II error. Power is the probability that the test correctly
        rejects the Null Hypothesis if the Alternative Hypothesis is true.

    Other attributes in results instance include :

    std_null
        standard error of difference under the null hypothesis (without
        sqrt(nobs1))
    std_alt
        standard error of difference under the alternative hypothesis
        (without sqrt(nobs1))

References
----------
.. [1] Zhu, Haiyuan. 2017. “Sample Size Calculation for Comparing Two
   Poisson or Negative Binomial Rates in Noninferiority or Equivalence
   Trials.” Statistics in Biopharmaceutical Research, March.
   https://doi.org/10.1080/19466315.2016.1225594
.. [2] Zhu, Haiyuan, and Hassan Lakkis. 2014. “Sample Size Calculation for
   Comparing Two Negative Binomial Rates.” Statistics in Medicine 33 (3):
   376–87. https://doi.org/10.1002/sim.5947.
.. [3] PASS documentation
r   r   r	   r   r   r   rF   std_null_lowstd_null_uppr   r   Nr  
r  power_marginsr  r  r  r  r  r  rF   r  )	r   r+   r   r   r   r   _power_equivalence_hetr   powr   r   r  rU   rV   r  rO   rF   r8   r
  r  r  r  v0_lowv0_uppes_lowes_uppr  r  r   r  r@   s                         rA    power_equivalence_poisson_2indepr  "  s   X bjj5*?@E%E		!e)a:3E.F"F	GBU	w	&!c.>*>)BB
"eE/A&BCC&!c.>*>)BB
"eE/A&BCC!K
|?"KLLVVEM"RVVC[0FVVEM"RVVC[0F776?L776?LggbkO!&&%/;/;2ACD
 q'ab'%%#! 
AwrC   c                    UnUnUn	[         R                  U5      n
[         R                  [        R                  " U5      U -  X-  -
  U	-  5      [         R                  [        R                  " U5      U-  X-  -
  U	-  5      -   S-
  nU$ z power for equivalence test

    r   )r,   r4   r0   r+   r   )r  r  r)   rF   r  r  r   s0_lows0_upps1r?   r  s               rA   _power_equivalence_het_v0r$    s     FF	B88E?D"''$-&(4=8B>?"''$-&(4=8B>?	@BC	D 	 KrC   c                    UnUnUn	[         R                  U5      n
[         R                  [        R                  " U5      U -  X-  -
  U	-  5      n[         R                  [        R                  " U5      U-  X-  -   U	-  5      nSX-   -
  nXU4$ r   )r,   r4   r-   r+   r   r0   )r  r  r)   rF   r  r  r   r!  r"  r#  r?   p1p2r  s                 rA   r  r    s     FF	B88E?D 
"''$-&(4=8B>	?B	2774=6)DM9R?	@B=DR<rC   c           	          XU-  -   SU-   -  nUS:X  a	  XU-  -   =pO [        U SX-  X&SS9u  pnXU-  -   n
XU-  -   n	U[        R                  " U	5      [        R                  " U
5      4$ )Nr   r   Tr   )r   r+   r   )r   r   r  rF   rO   r8   r7   r
  rates_pooledr  r  r   r   r   s                 rA   _std_2poisson_powerr*    s     J..1z>BLU*,,,R *1e(*G Z''++bggbk11rC   c	                     SSK Jn	  [        [        R                  XU/5      u  pnX-
  n
[        U UUUUUS9u  pnU	" X-
  X$UUUS9nU(       a  [        UX-   U4UUUX2-  UUSS9	nU$ U$ )uT	  Power of ztest for the difference between two independent poisson rates.

Parameters
----------
rate1 : float
    Poisson rate for the first sample, treatment group, under the
    alternative hypothesis.
rate2 : float
    Poisson rate for the second sample, reference group, under the
    alternative hypothesis.
nobs1 : float or int
    Number of observations in sample 1.
nobs_ratio : float
    Sample size ratio, nobs2 = nobs_ratio * nobs1.
alpha : float in interval (0,1)
    Significance level, e.g. 0.05, is the probability of a type I
    error, that is wrong rejections if the Null Hypothesis is true.
value : float
    Difference between rates 1 and 2 under the null hypothesis.
method_var : {"score", "alt"}
    The variance of the test statistic for the null hypothesis given the
    rates uder the alternative, can be either equal to the rates under the
    alternative ``method_var="alt"``, or estimated under the constrained
    of the null hypothesis, ``method_var="score"``.
alternative : string, 'two-sided' (default), 'larger', 'smaller'
    Alternative hypothesis whether the power is calculated for a
    two-sided (default) or one sided test. The one-sided test can be
    either 'larger', 'smaller'.
return_results : bool
    If true, then a results instance with extra information is returned,
    otherwise only the computed power is returned.

Returns
-------
results : results instance or float
    If return_results is False, then only the power is returned.
    If return_results is True, then a results instance with the
    information in attributes is returned.

    power : float
        Power of the test, e.g. 0.8, is one minus the probability of a
        type II error. Power is the probability that the test correctly
        rejects the Null Hypothesis if the Alternative Hypothesis is true.

    Other attributes in results instance include :

    std_null
        standard error of difference under the null hypothesis (without
        sqrt(nobs1))
    std_alt
        standard error of difference under the alternative hypothesis
        (without sqrt(nobs1))

References
----------
.. [1] Stucke, Kathrin, and Meinhard Kieser. 2013. “Sample Size
   Calculations for Noninferiority Trials with Poisson Distributed Count
   Data.” Biometrical Journal 55 (2): 203–16.
   https://doi.org/10.1002/bimj.201200142.
.. [2] PASS manual chapter 436

r   r   )r  rF   r7   r
  r   r  )	r  	rates_altr   r  r  r  r  rF   r  )r	  r   r   r+   r   r*  r   )r   r   r  r  rF   r7   r
  r'   r  r   r   r   r   r  r  r@   s                   rA   power_poisson_diff_2indepr-    s    H 9bjj5*?@E%=D.
A DL%,3(35D |U+$!
 
rC   c                 2   UnSU-  nU* U-  U-  SU-   -  nXS-  Xd-  X -  -   -  SX$-  -   -
  nXbU -  -   n	US:X  a  U	* U-  n
O,U* [         R                  " US-  SU-  U	-  -
  5      -
  SU-  -  n
X-  nSU-  U
-  SSU-  U-  -   -  SU-   U-  U-  -   nU
nX-  X4$ )z
variance based on constrained cmle, for score test version

for ratio comparison of two negative binomial samples

value = rate1 / rate2 under the null
r   r   r   rE   r   )r   r   r  rO   r7   r8   rate0abr   r0r1ri   r2s                 rA   _var_cmle_negbinr5  @  s     EZJ
x%'1z>:A		%-*2D"D	E
j 
 
"AU""AQR!Vb2771a4!a%!)+,,Q7	B	
X	a!e)j"88	9
j.J	&	3
4A 
B>2!!rC   c                 F   SSK Jn  [        [        R                  XU/5      u  pnX2-  nSU -  SX1-  -  -   U-  SU-   U-  U-  -   nU	S:X  a  UnOTU	S:X  a)  SXS-  -   S-  XC-  U-  XU-  -   -  -  nUSU-   U-  U-  -  nO%U	S:X  a  [        XUXEUS9S   nO[        S	U	 S
35      e[        R                  " U5      n[        R                  " U5      n[        R                  " X-  5      [        R                  " U5      -
  nU" UX&UUUS9nU
(       a  [        UUUUUUUSS9nU$ U$ )u  
Power of test of ratio of 2 independent negative binomial rates.

Parameters
----------
rate1 : float
    Poisson rate for the first sample, treatment group, under the
    alternative hypothesis.
rate2 : float
    Poisson rate for the second sample, reference group, under the
    alternative hypothesis.
nobs1 : float or int
    Number of observations in sample 1.
low : float
    Lower equivalence margin for the rate ratio, rate1 / rate2.
upp : float
    Upper equivalence margin for the rate ratio, rate1 / rate2.
nobs_ratio : float
    Sample size ratio, nobs2 = nobs_ratio * nobs1.
exposure : float
    Exposure for each observation. Total exposure is nobs1 * exposure
    and nobs2 * exposure.
value : float
    Rate ratio, rate1 / rate2, under the null hypothesis.
alpha : float in interval (0,1)
    Significance level, e.g. 0.05, is the probability of a type I
    error, that is wrong rejections if the Null Hypothesis is true.
dispersion : float >= 0.
    Dispersion parameter for Negative Binomial distribution.
    The Poisson limiting case corresponds to ``dispersion=0``.
method_var : {"score", "alt"}
    The variance of the test statistic for the null hypothesis given the
    rates under the alternative, can be either equal to the rates under the
    alternative ``method_var="alt"``, or estimated under the constrained
    of the null hypothesis, ``method_var="score"``, or based on a moment
    constrained estimate, ``method_var="ftotal"``. see references.
alternative : string, 'two-sided' (default), 'larger', 'smaller'
    Alternative hypothesis whether the power is calculated for a
    two-sided (default) or one sided test. The one-sided test can be
    either 'larger', 'smaller'.
return_results : bool
    If true, then a results instance with extra information is returned,
    otherwise only the computed power is returned.

Returns
-------
results : results instance or float
    If return_results is False, then only the power is returned.
    If return_results is True, then a results instance with the
    information in attributes is returned.

    power : float
        Power of the test, e.g. 0.8, is one minus the probability of a
        type II error. Power is the probability that the test correctly
        rejects the Null Hypothesis if the Alternative Hypothesis is true.

    Other attributes in results instance include :

    std_null
        standard error of difference under the null hypothesis (without
        sqrt(nobs1))
    std_alt
        standard error of difference under the alternative hypothesis
        (without sqrt(nobs1))

References
----------
.. [1] Zhu, Haiyuan. 2017. “Sample Size Calculation for Comparing Two
   Poisson or Negative Binomial Rates in Noninferiority or Equivalence
   Trials.” Statistics in Biopharmaceutical Research, March.
   https://doi.org/10.1080/19466315.2016.1225594
.. [2] Zhu, Haiyuan, and Hassan Lakkis. 2014. “Sample Size Calculation for
   Comparing Two Negative Binomial Rates.” Statistics in Medicine 33 (3):
   376–87. https://doi.org/10.1002/sim.5947.
.. [3] PASS documentation
r   r   r   r   ftotalr   r	   rO   r7   r8   r   r   r   r  )r  r   r  r  r  r  rF   r  )
r	  r   r   r+   r   r5  r   r   r   r   )r   r   r  r  rO   r7   rF   r8   r'   r
  r  r   r  r  r  r   r  r  r  r@   s                       rA   power_negbin_ratio_2indepr9  _  sr   n 9bjj5*?@E%Eu9qJ.//8
;z>Z
'*
45BU	x	%$$q("U*e56H.HIK
q:~+j88	w	eJ'/)35568 "K
|?"KLLwwr{HggbkG			.BBx,3(35D !	 
KrC   c                 Z   [        [        R                  XU/5      u  pnXR-  nSU-  SXP-  -  -   U-  SU-   U-  U-  -   nU	S:X  a  U=pOU	S:X  aQ  SX5-  -   S-  Xe-  U-  XU-  -   -  -  nUSU-   U-  U-  -  nSXE-  -   S-  Xe-  U-  XU-  -   -  -  nUSU-   U-  U-  -  nO4U	S:X  a  [        XUXcUS9S   n[        XUXdUS9S   nO[	        SU	 S	35      e[        R
                  " X-  5      [        R
                  " U5      -
  n[        R
                  " X-  5      [        R
                  " U5      -
  n[        R                  " U5      n[        R                  " U5      n[        R                  " U5      n[        UUX'UUUS
9nU
(       a  [        US   [        SS UUUUUUUSS9
nU$ US   $ )uf  
Power of equivalence test of ratio of 2 indep. negative binomial rates.

Parameters
----------
rate1 : float
    Poisson rate for the first sample, treatment group, under the
    alternative hypothesis.
rate2 : float
    Poisson rate for the second sample, reference group, under the
    alternative hypothesis.
nobs1 : float or int
    Number of observations in sample 1.
low : float
    Lower equivalence margin for the rate ratio, rate1 / rate2.
upp : float
    Upper equivalence margin for the rate ratio, rate1 / rate2.
nobs_ratio : float
    Sample size ratio, nobs2 = nobs_ratio * nobs1.
alpha : float in interval (0,1)
    Significance level, e.g. 0.05, is the probability of a type I
    error, that is wrong rejections if the Null Hypothesis is true.
dispersion : float >= 0.
    Dispersion parameter for Negative Binomial distribution.
    The Poisson limiting case corresponds to ``dispersion=0``.
method_var : {"score", "alt"}
    The variance of the test statistic for the null hypothesis given the
    rates under the alternative, can be either equal to the rates under the
    alternative ``method_var="alt"``, or estimated under the constrained
    of the null hypothesis, ``method_var="score"``, or based on a moment
    constrained estimate, ``method_var="ftotal"``. see references.
alternative : string, 'two-sided' (default), 'larger', 'smaller'
    Alternative hypothesis whether the power is calculated for a
    two-sided (default) or one sided test. The one-sided test can be
    either 'larger', 'smaller'.
return_results : bool
    If true, then a results instance with extra information is returned,
    otherwise only the computed power is returned.

Returns
-------
results : results instance or float
    If return_results is False, then only the power is returned.
    If return_results is True, then a results instance with the
    information in attributes is returned.

    power : float
        Power of the test, e.g. 0.8, is one minus the probability of a
        type II error. Power is the probability that the test correctly
        rejects the Null Hypothesis if the Alternative Hypothesis is true.

    Other attributes in results instance include :

    std_null
        standard error of difference under the null hypothesis (without
        sqrt(nobs1))
    std_alt
        standard error of difference under the alternative hypothesis
        (without sqrt(nobs1))


References
----------
.. [1] Zhu, Haiyuan. 2017. “Sample Size Calculation for Comparing Two
   Poisson or Negative Binomial Rates in Noninferiority or Equivalence
   Trials.” Statistics in Biopharmaceutical Research, March.
   https://doi.org/10.1080/19466315.2016.1225594
.. [2] Zhu, Haiyuan, and Hassan Lakkis. 2014. “Sample Size Calculation for
   Comparing Two Negative Binomial Rates.” Statistics in Medicine 33 (3):
   376–87. https://doi.org/10.1002/sim.5947.
.. [3] PASS documentation
r   r   r7  r   r	   r8  r   r   r   r  Nr  r  )
r   r+   r   r5  r   r   r   r  r   r  r  s                         rA   power_equivalence_neginb_2indepr;    s   Z bjj5*?@E%Eu9qJ.//8
;z>Z
'*
45BU	x	c&&*"S(E4F,FGI1z>Z/*<<c&&*"S(E4F,FGI1z>Z/*<<	w	!%
+3-799:< "%
+3-799:< "K
|?"KLLVVEM"RVVC[0FVVEM"RVVC[0F776?L776?LggbkO!&&%/;/;2ACD
 q'ab'%%#! 
AwrC   )Nr   r   )N皙?)gffffff?      ?Nr<  r   )r=  Nr<  r   )r<  r   r
   )r<  r	   r   r   )NNNr   r   N)r   F)NNr	   r   r   NN)r	   r   )r	   r   r<  r	   )r   r   r   r<  r   r   r   T)r   r   r<  r   r   F)r<  NNN)r   r<  r   r   r   r	   )r   r<  r   r	   r   T)r   r   r   )r   r   r   r<  g{Gz?r   r   T)r   r   r<  r   r   F)%__doc__numpyr+   r   scipyr   r   statsmodels.stats.baser   statsmodels.stats.weightstatsr   "statsmodels.stats._inference_toolsr   r,   method_names_poisson_1samprB   rX   rc   re   rI   r{   method_names_poisson_2indeprt   r   r   r   r   rz   r  r  r$  r  r*  r-  r5  r9  r;   rC   rA   <module>rG     s     ! . 9 = zz	

 6 ?JIXtn DF-1&1Nb BD04)4BJ :B&/& 6

*
+% P EI#'-4<@Yx( KO=D8< $}B 18aJ ELBL CG(/j^ }B ;<HI0549	up ;?+/+/.2( 8<(,(,+/. +/2* HL$%)0*5-1	dN BC !"B @H :;GH/438	@rC   