
    M/Ph.                       d Z ddlZddlZddlmZmZ ddlmZ ddl	m
Z
 ddlmZ ej        Zg dg dd	Z	 	 d4dZd5dZ	 	 	 d6dZ	 	 	 d7dZ	 	 d8dZ	 	 	 	 d9dZg dg ddg dg ddd	Z	 	 	 	 d:d Zd;d"Z	 	 	 	 d<d#Z	 d=d$Z	 d=d%Z	 	 d>d&Z	 	 	 	 	 	 	 	 d?d*Z	 	 	 	 d@d+Z	 	 	 	 dAd,Z	 	 	 	 dAd-Z	 	 	 	 	 dBd.Z 	 	 	 	 	 dCd/Z!	 	 dDd0Z"	 	 	 	 	 	 	 	 dEd2Z#	 	 	 	 dFd3Z$dS )Gzj
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confint	two-sided   c           	      p   |}| |z  }|d}t          |          |dk    r|dvrd}t          |          d}	|dk    r$t          j        ||z  |z            }
||z
  |
z  }n|dk    r*t          j        ||d	|z  z   z  |z            }
||z
  |
z  }n`|d
k    rCt          j        ||z  |z            }
||z
  |
z  }t          j                            |          }n|                    d          s|                    d          rt          j                            | ||z            }t          j                            | dz
  ||z            }|                    d          rR|d	t          j        	                    | ||z            z  z
  }|d	t          j        	                    | ||z            z  z
  }|dk    rdt          j
        ||          z  }n#|dk    r|}n|dk    r|}nd}t          |          t          j        }d}	n|dk    r2d	}
t          j        |           t          j        ||z            z
  |
z  }n|dk    r8d	}
t          j        | dz             t          j        ||z  dz             z
  |
z  }nu|dk    r]d	}
t          j                            d          }t          j        | |dz  dz   dz  z             t          j        ||z            z
  |
z  }nt          d|z            |	dk    rt          |d|          \  }}t          |t          j        |dd          |	||||          }|S )a  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

    N9method needs to be specified, currently no default methodr   )r   waldccr	   z:excess dispersion only supported in wald and score methodsnormalr   r         ?r	   r
   r   r      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                    W/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/stats/rates.pytest_poissonrB   1   s   n 	A19D~IooQ444NCS//!Dgj4'!+,,E\S(			9		
 gjD37N3a788E\S(			7		gj5(1,--E\S(	y))			9	%	% %7):):8)D)D %7mq5y11muqy!e)44X&& 	Bem//q5yAAAACem//q5yAAAAC+%%C---FFH$$FFI%%FFLCS//!F		6		WU^^bga%i&8&88C?			8		WUU]++bga%i%6G.H.HHCO			8		z~~e$$WUdAgkR%7788WQY''(+./		
 ,v5666x+Iq+FF	6
wvq!$$
 
 
C J    皙?c                 r	   |}| |z  }|dz  }|d}t          |          |dk    rCt          j                            |          t	          j        ||z            z  }||z
  ||z   f}n+|dk    rIt          j                            |          t	          j        |d|z  z   |z            z  }||z
  ||z   f}n|dk    r\t          j                            |          }	| |	dz  dz  z   }
|	t	          j        | |	dz  dz  z             z  }|
|z
  |z  |
|z   |z  f}nz|d	k    rt          | |d|z  d	d
          }n[|dk    rSt          j                            |          }	||	dz  d|z  z  z   }
|	t	          j        ||z            z  }|
|z
  |
|z   f}n|dk    rVt          j                            |          }	| |	dz  dz  z   }
|	t	          j        | dz             z  }|
|z
  |z  |
|z   |z  f}n|dk    rt          j                            |          }	t	          j        t	          j        | dz   dz
  d                    }t	          j        | dz   dz             }|	dz  }t	          j        ||z
  d          dz  dz
  |z  ||z   dz  dz
  |z  f}n|dk    rlt          j                            |          }	t	          j        | dz             }
|	dz  }t	          j        |
|z
  d          dz  dz
  |z  |
|z   dz  dz
  |z  f}n|dk    rot          j                            |          }	t	          j        | |	dz  dz   dz  z             }
|	dz  }t	          j        |
|z
  d          dz  |z  |
|z   dz  |z  f}n|dv rt          j        	                    ||           |z  }t          j                            || dz             |z  }t	          j
        |                                          r2t	          j        |          dk    rd}nd|t	          j
        |          <   ||f}ns|                    d          rL| dz   }t          j        	                    ||          |z  t          j                            ||          |z  f}nt          d|z            t	          j        |d         d          |d         f}|S )uX  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   Nr   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maximumrI   ppfisnananysizer.   )r6   exposurer&   rG   r9   r(   r:   whalfcir?   center
center_low
center_upplowuppcountcs                   rA   confint_poissonrY      s   d 	A8DAIE~Ioo
u%%q(9(99UlD5L)	9		 
u%%a10D(E(EEUlD5L)	7		z~~e$$q1$rwutQw{2333~"Ve^q$89	8		!%!e)H/8: : : 
6		z~~e$$a1q5))rwtax(((unfun-	;		z~~e$$q1$rwuu}---~"Ve^q$89	=	 	 z~~e$$WRZ(;Q??@@
WUU]S011
q
:-q11A5=BU"Q&.!35 
8		z~~e$$''q
6E>1--1E9Q>"U*a/1 
8		z~~e$$$'A+!3344qj%++a/!3funq5H15LL	'	'	'kooeU++h6kooeU1W--88C== 	)ws||q  %(BHSMM"3Z			6	"	" 7kooeV,,x7kooeV,,x79 ,v5666
*RUA

1	&BIrC   ffffff?      ?c                     d|z
  }|}|dk    r|dz  }t          | |||          \  }	}
|dk    r
|	|z  }	|
|z  }
|dk    rJt          j                            |dz  |	          }t          j                            d|dz  z
  |
          }n^|dk    r&d}t          j                            d|z
  |
          }n2|dk    r,t          j                            ||	          }t          j        }t	          j        |d          }||fS )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&   rG   r   r   r   rY   r   r/   rL   r+   infrK   )r6   rP   probexposure_newr&   rG   r'   	prob_tailalpha_rV   rW   low_predupp_preds                rA   tolerance_int_poissonrf   t  s   n DIFk!!uhvVLLLHCq||k!!=$$Y]C88=$$QQ%6<<		 	 =$$Q]C88			!	!=$$Y446 z(A&&HXrC   c                    |}|dk    r|dz  }t          | |||          \  }}	|dk    r
||z  }|	|z  }	|dk    rAt          j                            ||          }
t          j                            ||	          }n[|dk    r#d}
t          j                            ||	          }n2|dk    r,t          j                            ||          }
t          j        }t	          j        |
d          }
|
|fS )a	  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   r]   r   r   r   r   r^   )r6   rP   r`   ra   r&   rG   r'   rc   rV   rW   rd   re   s               rA   confint_quantile_poissonrh     s   Z Fk!!uhvVLLLHCq||k!!=$$T3//=$$T3//		 	 =$$T3//			!	!=$$T3//6 z(A&&HXrC   r   r
   c                 
     fd}t           |          }t          j        ||d         dd          }t          j        ||d         dd          }t          j        |          dk    sJ |d         |d         fS )z6invert hypothesis test to get confidence interval
    c                 F    t          |           d         z
  dz  }|S )N)r7   r&   r   r   )rB   )rvrG   r6   r&   r)   s     rA   funcz"_invert_test_confint.<locals>.func  s3    %Qv>>>qArC   )r&   r   :0yE>Fxtoldispr   )rY   r   fminr+   rO   )	r6   r)   rG   r&   rH   rm   rR   rV   rW   s	   ````     rA   rJ   rJ   
  s    
       
 
\	:	:	:B
-be$U
;
;
;C
-be$U
;
;
;C73<<1q63q6>rC   r	   diffr   c                      fd}t           |          }	t          j        ||	d         dd          }
t          j        ||	d         dd          }t          j        |
          dk    sJ |
d         |d         fS )zAinvert hypothesis test to get confidence interval for 2indep
    c           	      L    t          |           d         z
  dz  }|S )N)r7   r&   comparer   r   )test_poisson_2indep)	rk   rl   rG   rv   count1count2	exposure1	exposure2r&   s	     rA   rm   z)_invert_test_confint_2indep.<locals>.func%  sL     Y	VW      rC   )r&   rv   r   rn   Fro   r   )confint_poisson_2indepr   rr   r+   rO   )rx   rz   ry   r{   rG   r&   rv   rH   rm   rR   rV   rW   s   ```````     rA   _invert_test_confint_2indepr}     s               
 	69'3W
F 
F 
FB
-be$U
;
;
;C
-be$U
;
;
;C73<<1q63q6>rC   )	r   r	   	score-logwald-log
exact-cond	cond-midpr   etest-score
etest-wald)r   r	   r   r   r   )ratiors   )r   r	   r~   r   sqrtccmover)r   r	   r   r   r   c
                    t          t          j        | |||g          \  }
}}}||z  }|
|z  ||z  }}d}|dk    r\|d}|t          j        dt
                     |}||dx}}n|}|}||z  }|dv r'|
||z  z
  t          j        |
|z   |z            z  }d}n`|dv r*|
||z  z
  t          j        |
||d	z  z  z             z  }d}n2|d
v rVt          j        |
|z            t          j        |          z
  }|t          j        d	d|z  z   |z   |
|z   z            z  }d}n|dv rNt          j        |
|z            t          j        |          z
  t          j        d|
z  d|z  z             z  }d}n|dv rSd	t          j        |
dz             t          j        |dz   |z            z
  z  }|t          j        d|z             z  }d}n/|dv rgddlm	} |d|z   z  }|
|z   }t          j
        }|                    |
|||          }|dv r'|dt          j                            |
||          z  z
  }d}n|                    d          r9|                    d          rd}nd}|	i }	t#          | |||f|||d|	\  }}d}nvt%          d| d          |dk    rM|d}|dv r*||z
  |z
  t          j        ||z  ||z  z             z  }d}n*|dv r7||z
  |z
  }|t          j        | dz   |d	z  z  |dz   |d	z  z  z             z  }d}n|dv rp|
|z   }|||z   z  }||z
  }d|t          j        |d	z  d|z  |z  ||z   z  z             z   z  }||z   }||z
  |z
  t          j        ||z  ||z  z             z  }||f}d}n{|                    d          rD|                    d          rd}nd}|dk    r|dz   }|	i }	t#          | |||f||d|d|	\  }}d}n"t%          d| d          t'          d           |dk    rt)          |d|          \  }}||f} ||z  }!||z
  }"t+          ||||||| |!|"|||!          }#|#S )"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 recognizedrs   r   rF   z-scorer7   r&   rv   r'   #"compare" needs to be ratio or diff)r#   r$   r%   rv   r&   r'   ratesr   rs   r7   
rates_cmle
ratio_null)mapr+   asarraywarningswarnFutureWarningr   logstatsmodels.statsr   r3   
binom_testr   binomr1   r.   endswithetest_poisson_2indepr*   NotImplementedErrorr   r   )$rx   rz   ry   r{   r7   r   r&   rv   r'   
etest_kwdsy1n1y2n2drate1rate2r   rk   r_dstatr;   r   bpy_totalr$   method_etestcount_pooledrate_pooleddtr2_cmler1_cmler   r   rs   r@   s$                                       rA   rw   rw   \  s   f fi%KLLNBB
RA7BG5EJ'>F!MK') ) )E%-!""EJJ J!eYcMRWb2g_%=%==DDDxcMRWR"sAv+-=%>%>>DDD}$$F27OObfSkk1DBGQS[3.27;<<<DDD|##F27OObfSkk1RWQVa"f_5M5MMDDDxV,,rwVs7J/K/KKLDBGAG$$$DDD222444444CB2gG6D**2wR7B + D DF&&#GR(H(H"HHDDw'' 	Bv&& '%&!
/	69L<A#L L@JL LLD& DD@@@@AAA	F		=EXEME)RWURZ%"*5L-M-MMDD{""EME)DBGVc\RU2fslb!e5KKLLLDDDy  7L&"r'2Ku$BR"'"a%!e)b.BG2L*L"M"MMNGoGU]U*GGbL7R<7889D!7+JDDw'' 	Bv&& /%&W$$#h.F!
/	697<A#V'7 7 ,67 7LD&
 DD@@@@AAA!"GHHHx&tQ<<fENEEME5=D
##'%#"-!!!!+!+  C JrC   Fc                    | |z   }| |z  ||z  }}|||z   z  }	|	|z
  }
d|
t          j        |
dz  d|z  |z  ||z   z  z             z   z  }||z   }d}||z  ||z  z   }||z
  |z
  t          j        ||z             z  }|r|||fS |S )zGscore test and cmle for difference of 2 independent poisson rates

    r   r   rF   #B;r+   r   )r   r   r   r   r7   return_cmler   r   r   r   r   r   r   epsrl   r   s                   rA   _score_diffr   x  s     7L7BG5E"r'*K	u	BR"'"a%!e)b.BG*D"DEEEFGoG
C"w|#AEME!RWQW%5%55D Wg%%rC   c                 :   !" t          t          j        | |||g          \  } }!! z  }d|dk    rd|dn|t          j        dt
                     |}||z  "||z   !z  d"z   z  }||z  }|dv r"fd}ng|dv r"fd	}n\t          d
          |dk    rGdt          | |!d          }|\  }}}|dv r !fd}n|dv r	 !fd}nt          d
          |}|} |z  }!|z  } |||          }|	t          j        dt
                     |
|
n|	}
|
Vt          j	        
                    dt          ||                    }t          |d          }t          j        |dz             }
n.t          j        |
          }
|
j        dk    rt          d          t          j	                            |
|          }t          j	                            |
|          } ||
dddf         |
dddf                   }d|dv r.t          j        |          t          j        |          z
  k    }n+|dv r
||z
  k    }n|dv r
||z   k    }nt          d          |dddf         |dddf         z  |                                         }||fS )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    | |z  z
  t          j        | |z   z  z             z  S Nr   x1x2r   r   s     rA   	stat_funcz'etest_poisson_2indep.<locals>.stat_func  s-    R#X"r'S31F)G)GGGrC   r   c                 V    | |z  z
  t          j        | |dz  z  z   z             z  S )Nr   r   r   s     rA   r   z'etest_poisson_2indep.<locals>.stat_func   s2    R#Xb36k1AC1G)H)HHHrC   zmethod not recognizedrs   r   Tr7   r   c                 ,    t          | |          S )N)r7   )r   )r   r   r   r   r7   s     rA   r   z'etest_poisson_2indep.<locals>.stat_func  s    "2r2r????rC   c                 r    | z  |z  }}||z
  z
  }|t          j        |z  |z  z   z             z  }|S r   r   )	r   r   r   r   r   r   r   r   r7   s	        rA   r   z'etest_poisson_2indep.<locals>.stat_func  sM    !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)#rx   rz   ry   r{   r   r7   r&   rv   r'   ygridy_gridr   r   r   rk   
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 fi%KLLNBB
RA
C'%-EE#MK') ) )E!e2g^q3w/
!^
YH H H H H H H xI I I I I I I 4555	F		=E"b"b4HHH$'!:zY@ @ @ @ @ @ @ @ x         4555 EEJEJE)B##K7GGG)VVuF ~M%%eS->->??		3''	9q=))F##;!MNNN=VU++D=VU++D6!!!T'?F47O<<J
C444vj!!bf[&9&9C&?@		'	'kC/0	(	(	(kC/0.///AAAtG}tD!!!G},d388::FrC   c           
      h   t          | ||||||d          }t          | ||||||d          }	t          j        |j        |	j        k     t                    }
t          j        |
|j        |	j        g          }t          j        |
|j        |	j        g          }t          ||||||f||	d          }|S )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&   rv   equiv_limitsresults_largerresults_smallertitle)rw   r+   r   r$   intchooser#   r   )rx   rz   ry   r{   rV   rW   r&   rv   tt1tt2idx_maxr#   r$   r@   s                 rA   tost_poisson_2indepr   L  s    R fi$'&-*24 4 4C fi$'&-*35 5 5C jcj0#66G	'CM3=#ABBIYwSZ 899F
	##%$':%(&)N  C JrC   c           
      b   t          | ||||||d          }t          | ||||||d          }	t          j        |j        |	j        k     t                    }
dt          j        |j        |	j                  z  }t          j        |
|j        |	j        g          }t          |||||	d          }|S )us  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   )	rw   r+   r   r$   r   r2   r   r#   r   )rx   rz   ry   r{   rV   rW   r&   rv   r   r   idx_minr$   r#   r@   s                 rA   nonequivalence_poisson_2indepr     s    ^ fi$'*35 5 5C fi$'*24 4 4C
 jcj0#66GCJ
333F	'CM3=#ABBI
	##%(&)N  C JrC   c           
      *   t          t          j        | |||g          \  }}	}
}||	z  |
|z  }}|dz  }|dk    r|dk    r#t          | ||||dz  ddd          \  }}||f}n=|dk    rt          j                            |          }d}| |z   ||z   z  |z  |	z  }t          j        d| |z   z  d||z   z  z             }|t          j        | |z            z  |t          j        ||z            z  f}n|d	k    r#t          | ||||dz  d	dd          \  }}||f}n|dk    rt          j                            |          }| d
z   |d
z   z  |z  |	z  }t          j        d| d
z   z  d|d
z   z  z             }|t          j        | |z            z  |t          j        ||z            z  f}n|dk    rt          j                            |          }t          j        | d
z   |d
z   z            }d
t          j        | d
z   |z   d
z   d|z  z
            z  }|d
z   d|dz  z  z
  }|||z  z
  |z  }|||z  z   |z  }|dz  |dz  f}n\|dk    rC|}t          ||	|d|z            }t          |
||d|z            }t          ||||d          }nt          d| d          t          j        |d         d          |d         f}nN|dk    r8|dv rOt          j                            |          }||z
  }|t          j        ||	z  ||z  z             z  }||z
  ||z   f}n|dv r]t          j                            |          }||z
  }t          j        | d
z   |	dz  z  |d
z   |dz  z  z             }||z  }||z
  ||z   f}n|dk    r"t          | ||||dz  ddd          \  }}||f}nk|dk    rC|}t          ||	|d|z            }t          |
||d|z            }t          ||||d          }n"t          d| d          t          d          |S )ak  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   )rG   r&   rv   rH   r   r   r   r~   r   r   g      ?r   r]   )contrastr   r   rs   r   r   r   r   )r   r+   r   r}   r   r,   r4   r   exprY   r   r*   rK   r   )rx   rz   ry   r{   r&   rv   rG   method_moverr   r   r   r   r   r   rV   rW   rR   r?   crS   r<   denomlow_sqrtupp_sqrtmethod_pci1ci2halfs                               rA   r|   r|     s   J fi%KLLNBB7BG5EAIE'W2	69ai%  HC sBBz!!:>>%((DAqjVaZ025:F'!vz*Q&1*-==>>C26D&3,///"&:L:L1LMBB{""2	69ai"%  HC sBBx:>>%((Dslv|4r9B>F'!v|,qFSL/AABBC26D&3,///"&:L:L1LMBBx:>>%((DWfslv|<==Fv 5 ;dTk IJJJCc\D47N2E+u4H+u4HA+x{+BBw#H!"b5IIIC!"b5IIICuc3IIIBB @@@@AAAjA""BqE*	F		X:>>%((DU]F"'%"*urz"9:::D$-BB{"":>>%((DU]F'6C<2q50FSLBE3IIJJC#:D$-BBw2	69ai&  HC sBBw#H!"b5IIIC!"b5IIICuc3HHHBB@@@@AAA!"GHHHIrC   r   altTc                    ddl m} t          t          j        | ||g          \  } }}||z  }||z  d| z  d||z  z  z   z  }|	dk    r|}n<|	dk    r#||z  d||z  z   dz  z  }|||z  | ||z  z   z  z  }nt          d|	 d          t          j        |          }t          j        |          }t          j        | |z            t          j        |          z
  } |||||||	          }d
}|
rt          ||||||||d	  	        }|S |S )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   r   r	   r   method_var  not recognizedstd_nullstd_alternativer'   Npower)	r  p_pooledr   std_altnobs1nobs2
nobs_ratiorG   tuple_)	statsmodels.stats.powerr   r   r+   r   r   r   r   r   )r   r   r  r  rP   r7   rG   r8   r'   
method_varreturn_resultsr   r  v1v0r   r  espow_r  r@   s                        rA   power_poisson_ratio_2indepr    s   l 988888bj5%*?@@E5%E	h	!e)a:3E.F"F	GBU	w		("a%**<&<q%@@
ej EZ%-?$@AA!"K
"K"K"KLLLwr{{HgbkkG				.BBux,3(35 5 5D H !
 
 
 
KrC   c                    t          t          j        | ||g          \  } }}||z  }||z  d| z  d||z  z  z   z  }|	dk    r|x}}n^|	dk    rE||z  d||z  z   dz  z  }|||z  | ||z  z   z  z  }||z  d||z  z   dz  z  }|||z  | ||z  z   z  z  }nt          d|	 d          t          j        | |z            t          j        |          z
  }t          j        | |z            t          j        |          z
  }t          j        |          }t          j        |          }t          j        |          }t          |||||||          }|
r.t          |d         t          dd	         |||||||d

  
        }|S |d         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   rG   std_null_lowstd_null_uppr   r   Nr  
r  power_marginsr  r  r  r  r  r  rG   r  )	r   r+   r   r   r   r   _power_equivalence_hetr   powr   r   r  rV   rW   r  rP   rG   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 bj5%*?@@E5%E	h	!e)a:3E.F"F	GBU	w		h&!cJ.>*>)BB#
"ezE/A&BCCh&!cJ.>*>)BB#
"ezE/A&BCC!"K
"K"K"KLLLVEEM""RVC[[0FVEEM""RVC[[0F76??L76??LgbkkO!&&%u/;/;2AC C CD
  q'abb'%%#!   
AwrC   c                 .   |}|}|}	t                               |          }
t                               t          j        |          | z  |
|z  z
  |	z            t                               t          j        |          |z  |
|z  z
  |	z            z   dz
  }|S z power for equivalence test

    r   )r,   r4   r0   r+   r   )r  r  r)   rG   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                 <   |}|}|}	t                               |          }
t                               t          j        |          | z  |
|z  z
  |	z            }t                               t          j        |          |z  |
|z  z   |	z            }d||z   z
  }|||fS r   )r,   r4   r-   r+   r   r0   )r  r  r)   rG   r  r  r   r!  r"  r#  r?   p1p2r  s                 rA   r  r    s     FF	B88E??D 
"'$--&(4&=8B>	?	?B	274==6)D6M9R?	@	@BR=DR<rC   c                     | ||z  z   d|z   z  }|dk    r| ||z  z   x}	}
n,t          | d||z  ||d          \  }}}| ||z  z   }
|||z  z   }	|t          j        |	          t          j        |
          fS )Nr   r   Tr   )r   r+   r   )r   r   r  rG   rP   r8   r7   r
  rates_pooledr  r  r   r   r   s                 rA   _std_2poisson_powerr*    s     EJ..1z>BLU%*,,,RR *1ej(*E  7G UZ''w++bgbkk11rC   c	                     ddl m}	 t          t          j        | ||g          \  } }}| |z
  }
t          | |||||          \  }}} |	|
|z
  |||||          }|r"t          |||
z   |f|||||z  ||d	  	        }|S |S )u,
  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  rG   r7   r
  r   r  )	r  	rates_altr   r  r  r  r  rG   r  )r	  r   r   r+   r   r*  r   )r   r   r  r  rG   r7   r
  r'   r  r   rs   r   r   r  r  r@   s                   rA   power_poisson_diff_2indepr-    s    H 988888bj5%*?@@E5%5=D.
 
 
Ax D5L%,3(35 5 5D  t|U+u$!
 
 
 
rC   c                 >   |}d|z  }| |z  |z  d|z   z  }||z  ||z  || z  z   z  d||z  z   z
  }||| z  z   }	|dk    r|	 |z  }
n*| t          j        |dz  d|z  |	z  z
            z
  d|z  z  }
|
|z  }d|z  |
z  dd|z  |z  z   z  d|z   |z  |z  z   }|
}||z  ||fS )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   rF   r   )r   r   r  rP   r7   r8   rate0abr   r0r1rl   r2s                 rA   _var_cmle_negbinr5  @  s    EZJ
x%'1z>:A	h	%%-*u2D"D	E
j5 
 
"A
U""AQR!Vb271a4!a%!)+,,,Q7	eB	
X	a!e)j"88	9
j.J	&	3
4A 
Bz>2r!!rC   {Gz?c           
      x   ddl m} t          t          j        | ||g          \  } }}||z  }d| z  d||z  z  z   |z  d|z   |z  |z  z   }|	dk    r|}ng|	dk    r,d||z  z   dz  ||z  |z  | ||z  z   z  z  }|d|z   |z  |z  z  }n5|	dk    rt          | |||||          d         }nt          d	|	 d
          t          j        |          }t          j        |          }t          j        | |z            t          j        |          z
  } |||||||          }|
rt          |||||||d          }|S |S )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	   rP   r7   r8   r   r   r   r  )r  r   r  r  r  r  rG   r  )
r	  r   r   r+   r   r5  r   r   r   r   )r   r   r  r  rP   r7   rG   r8   r'   r
  r  r   r  r  r  r   r  r  r  r@   s                       rA   power_negbin_ratio_2indepr:  _  s   n 988888bj5%*?@@E5%Eu9qJ.//8
;z>Z
'*
45BU	x		%*$$q(
"U*ej56H.HIK
q:~+j88	w		eUJ'/u)35 5 5568 ""K
"K"K"KLLLwr{{HgbkkG				.BBux,3(35 5 5D  !	 	 	 
KrC   c                    t          t          j        | ||g          \  } }}||z  }d|z  d|| z  z  z   |z  d|z   |z  |z  z   }|	dk    r|x}}n|	dk    rWd||z  z   dz  ||z  |z  | ||z  z   z  z  }|d|z   |z  |z  z  }d||z  z   dz  ||z  |z  | ||z  z   z  z  }|d|z   |z  |z  z  }nP|	dk    r7t          | |||||          d         }t          | |||||          d         }nt	          d|	 d	          t          j        | |z            t          j        |          z
  }t          j        | |z            t          j        |          z
  }t          j        |          }t          j        |          }t          j        |          }t          |||||||
          }|
r.t          |d         t          dd         |||||||d
  
        }|S |d         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   r8  r   r	   r9  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 bj5%*?@@E5%Eu9qJ.//8
;z>Z
'*
45BU	x		cJ&&*
"S(EJ4F,FGI1z>Z/*<<cJ&&*
"S(EJ4F,FGI1z>Z/*<<	w		!%
+33-79 9 99:< "%
+33-79 9 99:< ""K
"K"K"KLLLVEEM""RVC[[0FVEEM""RVC[[0F76??L76??LgbkkO!&&%u/;/;2AC C CD
  q'abb'%%#!   
AwrC   )Nr   r   )NrD   )rZ   r[   NrD   r   )r[   NrD   r   )rD   r   r
   )rD   r	   rs   r   )NNNr   r   N)r   F)NNr	   r   r   NN)r	   r   )r	   r   rD   r	   )r   r   r   rD   r   r   r   T)r   r   rD   r   r   F)rD   NNN)r   rD   r   r   r   r	   )r   rD   r   r	   r   T)r   r   r   )r   r   r   rD   r6  r   r   T)r   r   rD   r   r   F)%__doc__numpyr+   r   scipyr   r   statsmodels.stats.baser   statsmodels.stats.weightstatsr   "statsmodels.stats._inference_toolsr   r,   method_names_poisson_1samprB   rY   rf   rh   rJ   r}   method_names_poisson_2indeprw   r   r   r   r   r|   r  r  r$  r  r*  r-  r5  r:  r<   rC   rA   <module>rF     s         ! ! ! ! ! ! ! ! . . . . . . 9 9 9 9 9 9 = = = = = = z	
 	
 	

 
 
  6 ?JI I I IXt t t tn DF-1&1N N N Nb BD04)4B B B BJ :B&/   &    6
 
 
  
 
*    
 
+% % P EI#'-4<@Y Y Y Yx   ( KO=D8< $} } } }B 18a a a aJ ELB B B BL CG(/j j j j^ } } } }B ;<HI0549	u u u up ;?+/+/.2   ( 8<(,(,+/   . +/2 2 2 2* HL$%)0*5-1	d d d dN BC !" " " "B @ @ @ @H :;GH/438	@ @ @ @ @ @rC   