ó
áp7]c           @   s}  d  Z  d d l m Z m 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 d d	 d
 „ Z d d d „ Z d d	 d „ Z d	 d „ Z d „  Z d e d d d d d „ Z d „  Z d d „ Z d d d „ Z d d d „ Z d d d „ Z d d d e d d d „ Z d „  Z d d e d „ Z d d „ Z  d d „ Z! d  d! „ Z" d d  d d" „ Z# d S(#   s„   Tests and Confidence Intervals for Binomial Proportions

Created on Fri Mar 01 00:23:07 2013

Author: Josef Perktold
License: BSD-3
iÿÿÿÿ(   t   lzipt   rangeN(   t   statst   optimize(   t
   float_info(   t   AllPairsResults(   t   HypothesisTestWarninggš™™™™™©?t   normalc            sd  t  |  d d ƒ } | d k	 r3 t | ƒ r3 d } n  t j |  ƒ }  t j ˆ ƒ ‰ |  d ˆ ‰ d ˆ  } | d k rÁ t j ˆ d ˆ ˆ ƒ } t j j ˆ  d ƒ | } ˆ | } ˆ | }	 n¬| d k rC‡  ‡ ‡ f d †  }
 |  d	 k r÷ d	 } n t	 j
 |
 t j ˆ ƒ } |  ˆ k r$d }	 qmt	 j
 |
 ˆ d t j ƒ }	 n*| d
 k rút j j | |  ˆ |  d ƒ } t j j | |  d ˆ |  ƒ }	 t j | ƒ d	 k rÇd	 | ˆ d	 k <d |	 ˆ d k <qmˆ d	 k rÙ| n d	 } ˆ d k rñ|	 n d }	 ns| d k r|t j j ˆ  d ƒ } ˆ | d } |  | d d | } t j | d | | ƒ } | | } | | } | | }	 nñ | d k rt j j ˆ  d ƒ } | d } d | ˆ } ˆ | d ˆ | } | t j ˆ d ˆ ˆ | d ˆ d ƒ } | | :} | | } | | }	 nQ | d  d k r]t j j d ˆ  |  d ˆ |  d ƒ \ } }	 n t d | ƒ ‚ | d k r¦t j | d	 d ƒ } t j |	 d	 d ƒ }	 n  | d k	 rZt j | ƒ d	 k rZd d l } t j | ƒ d k r| j | d | ƒ} | j |	 d | ƒ}	 n  t j | ƒ d k rZ| j | d | ƒ} | j |	 d | ƒ}	 qZn  | |	 f S(   sï  confidence interval for a binomial proportion

    Parameters
    ----------
    count : int or array_array_like
        number of successes, can be pandas Series or DataFrame
    nobs : int
        total number of trials
    alpha : float in (0, 1)
        significance level, default 0.05
    method : {'normal', 'agresti_coull', 'beta', 'wilson', 'binom_test'}
        default: 'normal'
        method to use for confidence interval,
        currently available methods :

         - `normal` : asymptotic normal approximation
         - `agresti_coull` : Agresti-Coull interval
         - `beta` : Clopper-Pearson interval based on Beta distribution
         - `wilson` : Wilson Score interval
         - `jeffreys` : Jeffreys Bayesian Interval
         - `binom_test` : experimental, inversion of binom_test

    Returns
    -------
    ci_low, ci_upp : float, ndarray, or pandas Series or DataFrame
        lower and upper confidence level with coverage (approximately) 1-alpha.
        When a pandas object is returned, then the index is taken from the
        `count`.

    Notes
    -----
    Beta, the Clopper-Pearson exact interval has coverage at least 1-alpha,
    but is in general conservative. Most of the other methods have average
    coverage equal to 1-alpha, but will have smaller coverage in some cases.

    The 'beta' and 'jeffreys' interval are central, they use alpha/2 in each
    tail, and alpha is not adjusted at the boundaries. In the extreme case
    when `count` is zero or equal to `nobs`, then the coverage will be only
    1 - alpha/2 in the case of 'beta'.

    The confidence intervals are clipped to be in the [0, 1] interval in the
    case of 'normal' and 'agresti_coull'.

    Method "binom_test" directly inverts the binomial test in scipy.stats.
    which has discrete steps.

    TODO: binom_test intervals raise an exception in small samples if one
       interval bound is close to zero or one.

    References
    ----------
    http://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval

    Brown, Lawrence D.; Cai, T. Tony; DasGupta, Anirban (2001). "Interval
        Estimation for a Binomial Proportion",
        Statistical Science 16 (2): 101â€“133. doi:10.1214/ss/1009213286.
        TODO: Is this the correct one ?

    t   indexg      ð?g      à?R   i   g       @t
   binom_testc            s   t  j ˆ ˆ ˆ d |  ƒˆ  S(   Nt   p(   R   R	   (   t   qi(   t   alphat   nobst   q_(    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt   funca   s    i    t   betat   agresti_coulli   t   wilsong      @i   t   jeffs   method "%s" is not availableiÿÿÿÿN(   R   R   (   t   getattrt   Nonet   callablet   npt   asarrayt   sqrtR   t   normt   isfR   t   brentqR   t   mint   epsilonR   t   ppft   ndimt   intervalt   NotImplementedErrort   clipt   pandast   Seriest	   DataFrame(   t   countR   R   t   methodt   pd_indext   alpha_2t   std_t   distt   ci_lowt   ci_uppR   t   critt   nobs_ct   q_ct   std_ct   crit2t   denomt   centert   pd(    (   R   R   R   s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt   proportion_confint   sz    =	

		  


/

!t   goodmanc            s†  | d k s | d k r' t  d ƒ ‚ n  t j ˆ d t j ƒ‰ ˆ d k  j ƒ  r` t  d ƒ ‚ n  ˆ j ƒ  ‰ t ˆ ƒ } ˆ ˆ } | d k rt j j	 d | | d ƒ } | d d ˆ | | d | } d ˆ | | t j t j
 | ƒ t j
 | ƒ g ƒ d | ˆ j } nk| d	  d
 k rrd „  ‰ ‡ f d †  ‰ ‡ ‡ ‡ f d †  ‰ ‡ ‡ ‡ ‡ f d †  ‰  ‡  ‡ ‡ f d †  } d }	 | |	 ƒ }
 | |	 d ƒ } x_ |
 d | k oÁ| k  n s|	 ˆ k rát d ƒ ‚ n  |	 d 7}	 | }
 | |	 d ƒ } q¦Wd | |
 | |
 } t j | |	 ˆ d ƒ } t j | |	 d | ˆ d ƒ } t j | | g ƒ j } n t d | ƒ ‚ | S(   s  Confidence intervals for multinomial proportions.

    Parameters
    ----------
    counts : array_like of int, 1-D
        Number of observations in each category.
    alpha : float in (0, 1), optional
        Significance level, defaults to 0.05.
    method : {'goodman', 'sison-glaz'}, optional
        Method to use to compute the confidence intervals; available methods
        are:

         - `goodman`: based on a chi-squared approximation, valid if all
           values in `counts` are greater or equal to 5 [2]_
         - `sison-glaz`: less conservative than `goodman`, but only valid if
           `counts` has 7 or more categories (``len(counts) >= 7``) [3]_

    Returns
    -------
    confint : ndarray, 2-D
        Array of [lower, upper] confidence levels for each category, such that
        overall coverage is (approximately) `1-alpha`.

    Raises
    ------
    ValueError
        If `alpha` is not in `(0, 1)` (bounds excluded), or if the values in
        `counts` are not all positive or null.
    NotImplementedError
        If `method` is not kown.
    Exception
        When ``method == 'sison-glaz'``, if for some reason `c` cannot be
        computed; this signals a bug and should be reported.

    Notes
    -----
    The `goodman` method [2]_ is based on approximating a statistic based on
    the multinomial as a chi-squared random variable. The usual recommendation
    is that this is valid if all the values in `counts` are greater than or
    equal to 5. There is no condition on the number of categories for this
    method.

    The `sison-glaz` method [3]_ approximates the multinomial probabilities,
    and evaluates that with a maximum-likelihood estimator. The first
    approximation is an Edgeworth expansion that converges when the number of
    categories goes to infinity, and the maximum-likelihood estimator converges
    when the number of observations (``sum(counts)``) goes to infinity. In
    their paper, Sison & Glaz demo their method with at least 7 categories, so
    ``len(counts) >= 7`` with all values in `counts` at or above 5 can be used
    as a rule of thumb for the validity of this method. This method is less
    conservative than the `goodman` method (i.e. it will yield confidence
    intervals closer to the desired significance level), but produces
    confidence intervals of uniform width over all categories (except when the
    intervals reach 0 or 1, in which case they are truncated), which makes it
    most useful when proportions are of similar magnitude.

    Aside from the original sources ([1]_, [2]_, and [3]_), the implementation
    uses the formulas (though not the code) presented in [4]_ and [5]_.

    References
    ----------
    .. [1] Levin, Bruce, "A representation for multinomial cumulative
           distribution functions," The Annals of Statistics, Vol. 9, No. 5,
           1981, pp. 1123-1126.

    .. [2] Goodman, L.A., "On simultaneous confidence intervals for multinomial
           proportions," Technometrics, Vol. 7, No. 2, 1965, pp. 247-254.

    .. [3] Sison, Cristina P., and Joseph Glaz, "Simultaneous Confidence
           Intervals and Sample Size Determination for Multinomial
           Proportions," Journal of the American Statistical Association,
           Vol. 90, No. 429, 1995, pp. 366-369.

    .. [4] May, Warren L., and William D. Johnson, "A SASÂ® macro for
           constructing simultaneous confidence intervals  for multinomial
           proportions," Computer methods and programs in Biomedicine, Vol. 53,
           No. 3, 1997, pp. 153-162.

    .. [5] May, Warren L., and William D. Johnson, "Constructing two-sided
           simultaneous confidence intervals for multinomial proportions for
           small counts in a large number of cells," Journal of Statistical
           Software, Vol. 5, No. 6, 2000, pp. 1-24.
    i    i   s(   alpha must be in (0, 1), bounds excludedt   dtypes   counts must be >= 0R8   i   i   i   t   sisonc         S   sk   |  \ } } t  j j | | ƒ t  j j | d | ƒ } | d k rg t j | ƒ rg t | d d k  ƒ S| S(   sP   Compute P(b <= Z <= a) where Z ~ Poisson(p) and
            `interval = (b, a)`.i   i    (   R   t   poissont   cdfR   t   isnant   int(   R!   R
   t   bt   at   prob(    (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt   poisson_interval  s
    ,c            sa   |  \ } } | | d ˆ  | | d | f | ƒ ˆ  | | | d f | ƒ ˆ  | | f | ƒ S(   sƒ   Compute mu_r, the r-th factorial moment of a poisson random
            variable of parameter `p` truncated to `interval = (b, a)`.i   (    (   R!   t   rR
   R?   R@   (   RB   (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt"   truncated_poisson_factorial_moment  s    $c      	      s9  g  t  d d ƒ D]C } t j g  t |  ˆ  ƒ D] \ } } ˆ | | | ƒ ^ q, ƒ ^ q \ } } } } | } | | | d }	 | | d d | | d | d d | d }
 | | d d | | d d | d | d | d | d d | d d | d } |
 j ƒ  |	 j ƒ  d	 } | j ƒ  d |	 d j ƒ  |	 j ƒ  d } ˆ | j ƒ  t j |	 j ƒ  ƒ } t j | d d ƒ t j d t j ƒ } | d d | } | d d | d d } | d d
 | d d | d d
 } | d | | d | | d | d | d } | t j |	 j ƒ  ƒ S(   s¡   Compute the Edgeworth expansion term of Sison & Glaz's formula
            (1) (approximated probability for multinomial proportions in a
            given box).i   i   i   i   i   i   i   i   g      ø?i   i-   i   iH   (   R   R   t   arrayt   zipt   sumR   t   expt   pi(   t	   intervalsRC   R!   R
   t   mu_r1t   mu_r2t   mu_r3t   mu_r4t   mut   mu2t   mu3t   mu4t   g1t   g2t   xt   phit   H3t   H4t   H6t   f(   t   countst   nRD   (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt	   edgeworth  s    b2Z,#,&2c            sy   t  j t  j t  j g  t |  ˆ  ƒ D] \ } } ˆ | | ƒ ^ q" ƒ ƒ t  j ˆ |  ƒ ƒ t  j t j j ˆ ˆ ƒ ƒ ƒ S(   s   Compute approximated probability for Multinomial(n, proportions)
            to be in `intervals` (Sison & Glaz's formula (1)).(   R   RH   RG   t   logRF   R   R;   t   _pmf(   RJ   R!   R
   (   R[   R]   R\   RB   (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt!   approximated_multinomial_interval8  s    Sc            sC   ˆ  g  ˆ D]2 } t  j | |  d ƒ t  j | |  ˆ ƒ f ^ q
 ƒ S(   sS   Compute interval coverage for a given `c` (Sison & Glaz's
            formula (7)).i    (   R   t   maximumt   minimum(   t   cR'   (   R`   R[   R\   (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt   nuB  s    g      ð?sH   Couldn't find a value for `c` that solves nu(c) <= 1 - alpha < nu(c + 1)s   method "%s" is not available(   t
   ValueErrorR   RE   t   floatt   anyRG   t   lenR   t   chi2R   R   t   Tt	   ExceptionRa   Rb   R"   (   R[   R   R(   t   kt   proportionsRi   t   deltat   regionRd   Rc   t   nuct   nucp1t   gt   ci_lowert   ci_upper(    (   R`   R[   R]   R\   RB   RD   s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt   multinomial_proportions_confint¡   sF    T
"&	
 
	#
"c         C   sO   |  } | d k r? | d | | t  j j | d ƒ d } n t d ƒ ‚ | S(   s   find sample size to get desired confidence interval length

    Parameters
    ----------
    proportion : float in (0, 1)
        proportion or quantile
    half_length : float in (0, 1)
        desired half length of the confidence interval
    alpha : float in (0, 1)
        significance level, default 0.05,
        coverage of the two-sided interval is (approximately) ``1 - alpha``
    method : string in ['normal']
        method to use for confidence interval,
        currently only normal approximation

    Returns
    -------
    n : float
        sample size to get the desired half length of the confidence interval

    Notes
    -----
    this is mainly to store the formula.
    possible application: number of replications in bootstrap samples

    R   i   g       @i   s   only "normal" is available(   R   R   R   R"   (   t
   proportiont   half_lengthR   R(   R   R\   (    (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt   samplesize_confint_proportion`  s
    -c         C   sQ   | d k r t  d ƒ ‚ n  d t j t j |  ƒ ƒ t j t j | ƒ ƒ } | S(   s6  effect size for a test comparing two proportions

    for use in power function

    Parameters
    ----------
    prop1, prop2: float or array_like

    Returns
    -------
    es : float or ndarray
        effect size for (transformed) prop1 - prop2

    Notes
    -----
    only method='normal' is implemented to match pwr.p2.test
    see http://www.statmethods.net/stats/power.html

    Effect size for `normal` is defined as ::

        2 * (arcsin(sqrt(prop1)) - arcsin(sqrt(prop2)))

    I think other conversions to normality can be used, but I need to check.

    Examples
    --------
    >>> import statsmodels.api as sm
    >>> sm.stats.proportion_effectsize(0.5, 0.4)
    0.20135792079033088
    >>> sm.stats.proportion_effectsize([0.3, 0.4, 0.5], 0.4)
    array([-0.21015893,  0.        ,  0.20135792])

    R   s   only "normal" is implementedi   (   Re   R   t   arcsinR   (   t   prop1t   prop2R(   t   es(    (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt   proportion_effectsize„  s    "2c         C   s   t  j |  d |  | ƒ S(   s`  standard error for the estimate of a proportion

    This is just ``np.sqrt(p * (1. - p) / nobs)``

    Parameters
    ----------
    prop : array_like
        proportion
    nobs : int, array_like
        number of observations

    Returns
    -------
    std : array_like
        standard error for a proportion of nobs independent observations
    g      ð?(   R   R   (   t   propR   (    (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt   std_prop¬  s    R   i    c         C   sÛ  t  |
 t ƒ s |
 |
 f }
 n  t j j | ƒ } |  t j | ƒ | } | t j | ƒ | } | sp | d k rÔ t j | |	 d | ƒ } t j | |	 d | ƒ } | d k rÔ | d |	 } | d |	 } qÔ n  t j	 | | k ƒ rd d l
 } | j d t ƒ n  t j | ƒ } | | |
 d d |	 | } | | |
 d	 d |	 | } | d k r„t j j | ƒ t j j | ƒ } nA | d k rÅt j j | |	 | ƒ t j j | d	 |	 | ƒ } n  | | | | | f f S(
   s  Generic statistical power function for normal based equivalence test

    This includes options to adjust the normal approximation and can use
    the binomial to evaluate the probability of the rejection region

    see power_ztost_prob for a description of the options
    t   binomg      à?R   g      ð?iÿÿÿÿNs   no overlap, power is zeroi    i   (   t
   isinstancet   tupleR   R   R   R   R   t   ceilt   truncRg   t   warningst   warnR   R<   R€   (   t   mean_lowt   var_lowt   mean_uppt   var_uppt   mean_altt   var_altR   t   discreteR,   R   t
   continuityt   critval_continuityR/   t   k_lowt   k_uppR…   t   std_altt   z_lowt   z_uppt   power(    (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt   _power_ztost¿  s.    % c         C   sO   t  |  | d d d | ƒ} t  |  | d d d | ƒ} t j | | ƒ | | f S(   sä  exact TOST test for one proportion using binomial distribution

    Parameters
    ----------
    count : integer or array_like
        the number of successes in nobs trials.
    nobs : integer
        the number of trials or observations.
    low, upp : floats
        lower and upper limit of equivalence region

    Returns
    -------
    pvalue : float
        p-value of equivalence test
    pval_low, pval_upp : floats
        p-values of lower and upper one-sided tests

    t   alternativet   largerR~   t   smaller(   R	   R   Ra   (   R'   R   t   lowt   uppt   tt1t   tt2(    (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt
   binom_tostë  s    c         C   sB   t  j j | | |  ƒ d } t  j j | | | ƒ d } | | f S(   sË  rejection region for binomial TOST

    The interval includes the end points,
    `reject` if and only if `r_low <= x <= r_upp`.

    The interval might be empty with `r_upp < r_low`.

    Parameters
    ----------
    low, upp : floats
        lower and upper limit of equivalence region
    nobs : integer
        the number of trials or observations.

    Returns
    -------
    x_low, x_upp : float
        lower and upper bound of rejection region

    i   (   R   R€   R   R   (   Rš   R›   R   R   t   x_lowt   x_upp(    (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt   binom_tost_reject_interval  s    s	   two-sidedc         C   s‹   | d k r d } | d } n  | d	 k rJ t  j j | | |  ƒ d } n d } | d
 k r{ t  j j | | |  ƒ d } n | } | | f S(   sŠ  rejection region for binomial test for one sample proportion

    The interval includes the end points of the rejection region.

    Parameters
    ----------
    value : float
        proportion under the Null hypothesis
    nobs : integer
        the number of trials or observations.


    Returns
    -------
    x_low, x_upp : float
        lower and upper bound of rejection region


    t   2ss	   two-sidedi   R™   i   i    R˜   (   R¢   s	   two-sided(   R¢   R™   (   R¢   R˜   (   R   R€   R   R   (   t   valueR   R   R—   RŸ   R    (    (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt   binom_test_reject_interval  s    g      à?c         C   sÅ   t  j | d k ƒ s* t  j | d k  ƒ r9 t d ƒ ‚ n  | d k rc t j |  d | d | ƒ} n^ | d k rŽ t j j |  d
 | | ƒ } n3 | d k rµ t j j |  | | ƒ } n t d ƒ ‚ | S(   s]  Perform a test that the probability of success is p.

    This is an exact, two-sided test of the null hypothesis
    that the probability of success in a Bernoulli experiment
    is `p`.

    Parameters
    ----------
    count : integer or array_like
        the number of successes in nobs trials.
    nobs : integer
        the number of trials or observations.
    prop : float, optional
        The probability of success under the null hypothesis,
        `0 <= prop <= 1`. The default value is `prop = 0.5`
    alternative : string in ['two-sided', 'smaller', 'larger']
        alternative hypothesis, which can be two-sided or either one of the
        one-sided tests.

    Returns
    -------
    p-value : float
        The p-value of the hypothesis test

    Notes
    -----
    This uses scipy.stats.binom_test for the two-sided alternative.

    g      ð?g        s   p must be in range [0,1]R¢   s	   two-sidedR\   R
   t   lR˜   i   t   sR™   sA   alternative not recognized
should be two-sided, larger or smaller(   R¢   s	   two-sided(   R¥   R˜   (   R¦   R™   (   R   Rg   Re   R   R	   R€   t   sfR<   (   R'   R   R~   R—   t   pval(    (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyR	   A  s    *c         C   sq   | d  k r d |  | } n  t |  | | d | ƒ\ } } t j j | | | ƒ t j j | d | | ƒ } | S(   Ng      à?R   i   (   R   R¡   R   R€   R<   (   Rš   R›   R   t   p_altR   RŸ   R    R•   (    (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt   power_binom_tostn  s    c
         C   sÎ   |  }
 t  |  | ƒ d } | } t  | | ƒ d } | } t  | | ƒ d } | d
 k	 rq t  | | ƒ d } } n  t |
 | | | | | d | d | d | d | d | d |	 ƒ} t j | d d ƒ | d	 f S(   s¦  Power of proportions equivalence test based on normal distribution

    Parameters
    ----------
    low, upp : floats
        lower and upper limit of equivalence region
    nobs : int
        number of observations
    p_alt : float in (0,1)
        proportion under the alternative
    alpha : float in (0,1)
        significance level of the test
    dist : string in ['norm', 'binom']
        This defines the distribution to evalute the power of the test. The
        critical values of the TOST test are always based on the normal
        approximation, but the distribution for the power can be either the
        normal (default) or the binomial (exact) distribution.
    variance_prop : None or float in (0,1)
        If this is None, then the variances for the two one sided tests are
        based on the proportions equal to the equivalence limits.
        If variance_prop is given, then it is used to calculate the variance
        for the TOST statistics. If this is based on an sample, then the
        estimated proportion can be used.
    discrete : bool
        If true, then the critical values of the rejection region are converted
        to integers. If dist is "binom", this is automatically assumed.
        If discrete is false, then the TOST critical values are used as
        floating point numbers, and the power is calculated based on the
        rejection region that is not discretized.
    continuity : bool or float
        adjust the rejection region for the normal power probability. This has
        and effect only if ``dist='norm'``
    critval_continuity : bool or float
        If this is non-zero, then the critical values of the tost rejection
        region are adjusted before converting to integers. This affects both
        distributions, ``dist='norm'`` and ``dist='binom'``.

    Returns
    -------
    power : float
        statistical power of the equivalence test.
    (k_low, k_upp, z_low, z_upp) : tuple of floats
        critical limits in intermediate steps
        temporary return, will be changed

    Notes
    -----
    In small samples the power for the ``discrete`` version, has a sawtooth
    pattern as a function of the number of observations. As a consequence,
    small changes in the number of observations or in the normal approximation
    can have a large effect on the power.

    ``continuity`` and ``critval_continuity`` are added to match some results
    of PASS, and are mainly to investigate the sensitivity of the ztost power
    to small changes in the rejection region. From my interpretation of the
    equations in the SAS manual, both are zero in SAS.

    works vectorized

    **verification:**

    The ``dist='binom'`` results match PASS,
    The ``dist='norm'`` results look reasonable, but no benchmark is available.

    References
    ----------
    SAS Manual: Chapter 68: The Power Procedure, Computational Resources
    PASS Chapter 110: Equivalence Tests for One Proportion.

    i   R   R   R,   R   RŽ   R   i    i   N(   R   R   R–   R   Ra   (   Rš   R›   R   R©   R   R,   t   variance_propR   RŽ   R   R‡   Rˆ   R‰   RŠ   R‹   RŒ   R•   (    (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt   power_ztost_propv  s    Ic         C   sm   t  j |  | |  f ƒ } | j d ƒ | j d ƒ d d … d f d | j ƒ  } | j d } | | | f S(   sº  create a k by 2 contingency table for proportion

    helper function for proportions_chisquare

    Parameters
    ----------
    count : integer or array_like
        the number of successes in nobs trials.
    nobs : integer
        the number of trials or observations.

    Returns
    -------
    table : ndarray
        (k, 2) contingency table

    Notes
    -----
    recent scipy has more elaborate contingency table functions

    i    i   Ng      ð?(   R   t   column_stackRG   R   t   shape(   R'   R   t   tablet   expectedt   n_rows(    (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt   _table_proportionÍ  s    :c         C   sc  t  j |  ƒ }  t  j | ƒ } | j d k rC | t  j |  ƒ } n  |  d | } t  j | ƒ } | d	 k r | d k r‡ t d ƒ ‚ n  d } n  | d k r© | | } n7 | d k rÎ | d | d | } n d } t | ƒ ‚ t  j |  ƒ d t  j | ƒ }	 t  j d | ƒ }
 | r"| }	 n  |	 d |	 |
 } t  j | ƒ } d d l	 m
 } | | | | ƒ S(
   s£
  
    Test for proportions based on normal (z) test

    Parameters
    ----------
    count : integer or array_like
        the number of successes in nobs trials. If this is array_like, then
        the assumption is that this represents the number of successes for
        each independent sample
    nobs : integer or array-like
        the number of trials or observations, with the same length as
        count.
    value : float, array_like or None, optional
        This is the value of the null hypothesis equal to the proportion in the
        case of a one sample test. In the case of a two-sample test, the
        null hypothesis is that prop[0] - prop[1] = value, where prop is the
        proportion in the two samples. If not provided value = 0 and the null
        is prop[0] = prop[1]
    alternative : string in ['two-sided', 'smaller', 'larger']
        The alternative hypothesis can be either two-sided or one of the one-
        sided tests, smaller means that the alternative hypothesis is
        ``prop < value`` and larger means ``prop > value``. In the two sample
        test, smaller means that the alternative hypothesis is ``p1 < p2`` and
        larger means ``p1 > p2`` where ``p1`` is the proportion of the first
        sample and ``p2`` of the second one.
    prop_var : False or float in (0, 1)
        If prop_var is false, then the variance of the proportion estimate is
        calculated based on the sample proportion. Alternatively, a proportion
        can be specified to calculate this variance. Common use case is to
        use the proportion under the Null hypothesis to specify the variance
        of the proportion estimate.

    Returns
    -------
    zstat : float
        test statistic for the z-test
    p-value : float
        p-value for the z-test

    Examples
    --------
    >>> count = 5
    >>> nobs = 83
    >>> value = .05
    >>> stat, pval = proportions_ztest(count, nobs, value)
    >>> print('{0:0.3f}'.format(pval))
    0.695

    >>> import numpy as np
    >>> from statsmodels.stats.proportion import proportions_ztest
    >>> count = np.array([5, 12])
    >>> nobs = np.array([83, 99])
    >>> stat, pval = proportions_ztest(count, nobs)
    >>> print('{0:0.3f}'.format(pval))
    0.159

    Notes
    -----
    This uses a simple normal test for proportions. It should be the same as
    running the mean z-test on the data encoded 1 for event and 0 for no event
    so that the sum corresponds to the count.

    In the one and two sample cases with two-sided alternative, this test
    produces the same p-value as ``proportions_chisquare``, since the
    chisquare is the distribution of the square of a standard normal
    distribution.
    i   g      ð?s*   value must be provided for a 1-sample testi    i   s-   more than two samples are not implemented yetiÿÿÿÿ(   t   _zstat_generic2N(   R   R   t   sizet	   ones_likeR   Re   R"   RG   R   t   statsmodels.stats.weightstatsR³   (   R'   R   R£   R—   t   prop_varR~   t   k_samplet   difft   msgt   p_pooledt	   nobs_factt   var_t   std_diffR³   (    (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt   proportions_ztesté  s0    I	 	t   samplec   	   	   C   sÔ   | d k r | } | } nV | d k r4 t  } } n= | d k rU d | | } } n t j | ƒ rq | } } n  t |  | d d d | d | ƒ} t |  | d d	 d | d | ƒ} t j | d
 | d
 ƒ | | f S(   s_  Equivalence test based on normal distribution

    Parameters
    ----------
    count : integer or array_like
        the number of successes in nobs trials. If this is array_like, then
        the assumption is that this represents the number of successes for
        each independent sample
    nobs : integer
        the number of trials or observations, with the same length as
        count.
    low, upp : float
        equivalence interval low < prop1 - prop2 < upp
    prop_var : string or float in (0, 1)
        prop_var determines which proportion is used for the calculation
        of the standard deviation of the proportion estimate
        The available options for string are 'sample' (default), 'null' and
        'limits'. If prop_var is a float, then it is used directly.

    Returns
    -------
    pvalue : float
        pvalue of the non-equivalence test
    t1, pv1 : tuple of floats
        test statistic and pvalue for lower threshold test
    t2, pv2 : tuple of floats
        test statistic and pvalue for upper threshold test

    Notes
    -----
    checked only for 1 sample case

    t   limitsRÀ   t   nullg      à?R—   R˜   R·   R£   R™   i   (   t   FalseR   t   isrealR¿   Ra   (	   R'   R   Rš   R›   R·   t   prop_var_lowt   prop_var_uppRœ   R   (    (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt   proportions_ztostP  s    "	c   	      C   s¤   t  j | ƒ } t |  | ƒ \ } } } | d k	 ra t  j | | | d | f ƒ } | d } n | } t j | j ƒ  | j ƒ  d | ƒ\ } } | | | | f f S(   s†  test for proportions based on chisquare test

    Parameters
    ----------
    count : integer or array_like
        the number of successes in nobs trials. If this is array_like, then
        the assumption is that this represents the number of successes for
        each independent sample
    nobs : integer
        the number of trials or observations, with the same length as
        count.
    value : None or float or array_like

    Returns
    -------
    chi2stat : float
        test statistic for the chisquare test
    p-value : float
        p-value for the chisquare test
    (table, expected)
        table is a (k, 2) contingency table, ``expected`` is the corresponding
        table of counts that are expected under independence with given
        margins


    Notes
    -----
    Recent version of scipy.stats have a chisquare test for independence in
    contingency tables.

    This function provides a similar interface to chisquare tests as
    ``prop.test`` in R, however without the option for Yates continuity
    correction.

    count can be the count for the number of events for a single proportion,
    or the counts for several independent proportions. If value is given, then
    all proportions are jointly tested against this value. If value is not
    given and count and nobs are not scalar, then the null hypothesis is
    that all samples have the same proportion.

    i   t   ddofN(   R   t
   atleast_1dR²   R   R­   R   t	   chisquaret   ravel(	   R'   R   R£   R¯   R°   R±   RÈ   t   chi2statR¨   (    (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt   proportions_chisquare‚  s    *!t   hsc         C   sk   t  t j t |  ƒ d ƒ Œ  } g  | D]- } t |  t | ƒ | t | ƒ ƒ d ^ q% } t | | d | ƒS(   s2  chisquare test of proportions for all pairs of k samples

    Performs a chisquare test for proportions for all pairwise comparisons.
    The alternative is two-sided

    Parameters
    ----------
    count : integer or array_like
        the number of successes in nobs trials.
    nobs : integer
        the number of trials or observations.
    prop : float, optional
        The probability of success under the null hypothesis,
        `0 <= prop <= 1`. The default value is `prop = 0.5`
    multitest_method : string
        This chooses the method for the multiple testing p-value correction,
        that is used as default in the results.
        It can be any method that is available in  ``multipletesting``.
        The default is Holm-Sidak 'hs'.

    Returns
    -------
    result : AllPairsResults instance
        The returned results instance has several statistics, such as p-values,
        attached, and additional methods for using a non-default
        ``multitest_method``.

    Notes
    -----
    Yates continuity correction is not available.
    i   t   multitest_method(   R    R   t   triu_indicesRh   RÍ   t   listR   (   R'   R   RÏ   t	   all_pairst   pairt   pvals(    (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt   proportions_chisquare_allpairs¼  s    !7c   	      C   sœ   | d k	 s | d k r! t ‚ n  g  t d t |  ƒ ƒ D] } d | f ^ q7 } g  | D]- } t |  t | ƒ | t | ƒ ƒ d ^ qV } t | | d | ƒS(   s­  chisquare test of proportions for pairs of k samples compared to control

    Performs a chisquare test for proportions for pairwise comparisons with a
    control (Dunnet's test). The control is assumed to be the first element
    of ``count`` and ``nobs``. The alternative is two-sided, larger or
    smaller.

    Parameters
    ----------
    count : integer or array_like
        the number of successes in nobs trials.
    nobs : integer
        the number of trials or observations.
    prop : float, optional
        The probability of success under the null hypothesis,
        `0 <= prop <= 1`. The default value is `prop = 0.5`
    multitest_method : string
        This chooses the method for the multiple testing p-value correction,
        that is used as default in the results.
        It can be any method that is available in  ``multipletesting``.
        The default is Holm-Sidak 'hs'.
    alternative : string in ['two-sided', 'smaller', 'larger']
        alternative hypothesis, which can be two-sided or either one of the
        one-sided tests.

    Returns
    -------
    result : AllPairsResults instance
        The returned results instance has several statistics, such as p-values,
        attached, and additional methods for using a non-default
        ``multitest_method``.


    Notes
    -----
    Yates continuity correction is not available.

    ``value`` and ``alternative`` options are not yet implemented.

    s	   two-sidedR¢   i   i    RÏ   N(   s	   two-sidedR¢   (   R   R"   R   Rh   RÍ   RÑ   R   (	   R'   R   R£   RÏ   R—   Rl   RÒ   RÓ   RÔ   (    (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt"   proportions_chisquare_pairscontrolâ  s    *	.7($   t   __doc__t   statsmodels.compat.pythonR    R   t   numpyR   t   scipyR   R   t   sysR   t   statsmodels.stats.baseR   t   statsmodels.tools.sm_exceptionsR   R7   Ru   Rx   R}   R   t   TrueR   R–   Rž   R¡   R¤   R	   Rª   R¬   R²   RÃ   R¿   RÇ   RÍ   RÕ   RÖ   (    (    (    s;   lib/python2.7/site-packages/statsmodels/stats/proportion.pyt   <module>   s<   ¿#(	*	#-	U	f2:&