Skip to content

power: 2 or k samples with different variance under alternative #1197

Closed

Description

@josef-pkt

Skipper wrote an explicit sample size or power calculation for 2 proportions, that matches R base stats and Stata.
https://groups.google.com/d/msg/pystatsmodels/yerxcPsI2bc/prvlH0MUDCcJ
R pwr uses the effect size approach and produces the same result as my version in statsmodels.

Because the variance depends on the mean (as in linear exponential family), the variances for the two samples are not the same under the alternative.
Check details and see if there are general results.

This doesn't fit in the current effect size based power calculations, since the variance is absorbed into the effect size, and there is no argument included that allows for additional variance specification.

Since the rootfinding class is completely generic and allows extra arguments, it shouldn't be difficult to add this.
However, maybe solving for the effect size is not clear if the variance differs.

There are still two different cases:

normal or t distribution: variance is an extra parameter
proportions, binary, count data in LEF family: variance depends on the mean and we don't have a separate variance parameter.

The second case might actually fit quite well into the current framework.

Activity

  1. josef-pkt commented on Nov 21, 2013

    @josef-pkt
    MemberAuthor

    Actually I do have a case in stats.proportions, but it's not included in the power classes

    power_ztost_prop has various ways of calculating the distribution under the alternatives (but this is driven by using two tests)
    https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/proportion.py#L220
    also it calculates optionally the power under the binomial instead of the normal distribution.

  2. jseabold commented on Nov 21, 2013

    @jseabold
    Member

    Here's the (updated) code. The root-finding isn't super robust, and it could be made to handle each case with closed form solutions I think.

    def prop_power_test(prop1=None, prop2=None, nobs=None, power=None,
                        alpha=.05, r=1., two_sided=True, cont=True,
                        **optimize_kwargs):
        """
        Solve for exactly one of prop1, prop2, nobs, or power.
    
        Notes
        -----
        This differs from the other power functions in that you do not need
        to do a transformation to get an effect size.
    
        References
        ----------
        Fleiss, J. Levin, B., and Paik, M. C. Statistical Methods for Rates &
            Proportions. Chapter 4.
        """
        args = [prop1, prop2, power, nobs]
        if not len(filter(lambda x : x is None, args)) == 1:
            raise ValueError("Exactly one of prop1, prop2, nobs, and power"
                             " must be None.")
        nsides = two_sided * 2. or 1.
    
        z_alpha = stats.norm.ppf(1 - alpha/nsides)
    
        def func(prop1, prop2, power):
            # for variance of p1 and p2
            var1 = prop1 * (1 - prop1)
            var2 = prop2 * (1 - prop2)
    
            # corrections for unequal sample size
            p_bar = (prop1 + r*prop2)/(r+1.)
            q_bar = 1 - p_bar
    
            z_beta = stats.norm.ppf(power)
    
            n_prime = ((z_alpha * np.sqrt((r+1) * p_bar * q_bar) +
                        z_beta * np.sqrt(r * var1 + var2))**2/
                        (r*(prop2 - prop1)**2))
            if cont:
                n = n_prime/4. * (1 +
                                np.sqrt(1 + (2 * (r + 1))/
                                (n_prime * r * np.abs(prop2 - prop1))))**2
            else:
                n = n_prime
            if nobs is None:
                return n
            else:
                return nobs - n
    
        if nobs is None:
            return func(prop1, prop2, power)
    
        # anything other than nobs is None
    
        find_root = lambda x, bounds, kws : optimize.brentq(x, *bounds, **kws)
        funcs = [
                lambda x, bounds, kwargs : find_root(
                    lambda x : func(x, prop2, power), bounds, kwargs),
                lambda x, bounds, kwargs : find_root(
                    lambda x, : func(prop1, x, power), bounds, kwargs),
                lambda x, bounds, kwargs : find_root(
                    lambda x : func(prop1, prop2, x), bounds, kwargs),
                ]
    
        eps = np.finfo(float).eps
        prop1_bound = prop2 - eps if prop2 else None
        prop2_bound = prop1 + eps if prop1 else None
    
        bounds = [(0, prop1_bound), (prop2_bound, 1), (1e-6, 1-eps)][args.index(None)]
        return funcs[args.index(None)](0, bounds, optimize_kwargs)
  3. josef-pkt commented on Nov 21, 2013

    @josef-pkt
    MemberAuthor

    The root-finding isn't super robust

    I spend a lot of time on rootfinding, and I think my version is pretty robust now.

    After looking at my power_ztost_prop and remembering the sawtooth:

    • it would be relatively easy to calculate power using the binomial distribution
    • to calculate the sample size, we could do an explicit search in the neighborhood of the continuous normal distributed solution.

    Not sure about how large the neigborhood would have to be. And I didn't pay a lot of attention to this in the SAS manual. A user could just calculate the binomial based power for values in the neighborhood themselves.

    (But I have lots of things much higher on my priority list.)

  4. josef-pkt commented on Feb 16, 2018

    @josef-pkt
    MemberAuthor

    general idea: e.g. two sample proportions test for equality
    we need more specific test for specific values of the proportion under the Null and Alternative, the difference or effect size is not enough

    H0; p_1 = p_2 = p_null
    H1: p_1 = p_null, p_2 = p_alternative = p_null + diff or = p_null * p_ratio

    p_null and p_alternative are only relevant for variance, i.e. nuisance parameters with assumed values

    Then:
    we can parameterize power in terms of p_null and diff taking the place of effect size
    parameters: power, p_null, p_diff/p_ratio, alpha, nobs1, ratio (= nobs2 / nobs1)

    I guess the general solve power class still works just with some parameters replaced.
    diff or p_ratio can be used as size of effect for fixed p_null (but is not a Cohen effect size)

    example twosamplefreq in SAS https://support.sas.com/documentation/cdl/en/statug/63962/HTML/default/viewer.htm#statug_power_a0000001001.htm (old 9.3 documentation that still comes up in Google)
    Aside both Pearson chisquare and LR chisquare test in the two sample case are actually z-tests, i.e. using normal distribution.

  5. josef-pkt commented on Aug 8, 2018

    @josef-pkt
    MemberAuthor

    parking a draft version of general normal_power when var_null != var_alternative
    works on example, now compared to Stata 14 for one and two proportions
    related to #4829 inference for 2 independent binomial proportions

    general formula is based on Dupont Plummer in Controlled Clinical Trials 1990 (which I had printed some time ago), checked with the Stata docs for proportions.
    implementation is an adjustment to statsmodels.stats.power.normal_power
    (Note: notation/interpretation for sample1 and sample2 differs across references, Stata refers to p1 as the reference case, but the technical documentation uses effect = p2 - p1. I think I have it different from Stata's function signature, i.e. p1, p2 are reversed.)

    Current function is for equality test of two proportions, but I want to get the value !=0 case so I can include inferiority tests and similar. H0: p1 - p2 - diff = 0 H1_power: p1 = p2 + diff_alternative.
    Basic design for that will follow PASS documentation.

    # -*- coding: utf-8 -*-
    """
    Created on Tue Aug  7 13:34:21 2018
    
    Author: josef
    """
    
    import numpy as np
    from scipy import stats
    
    
    def normal_power(diff, nobs, alpha, std_null=1., std_alternative=None,
                     alternative='two-sided'):
        '''Calculate power of a normal distributed test statistic
    
        '''
        d = diff
        if std_alternative is None:
            std_alternative = std_null
    
        if alternative in ['two-sided', '2s']:
            alpha_ = alpha / 2.  #no inplace changes, doesn't work
        elif alternative in ['smaller', 'larger']:
            alpha_ = alpha
        else:
            raise ValueError("alternative has to be 'two-sided', 'larger' " +
                             "or 'smaller'")
    
        std_ratio = std_null / std_alternative
        pow_ = 0
        if alternative in ['two-sided', '2s', 'larger']:
            crit = stats.norm.isf(alpha_)
            pow_ = stats.norm.sf(crit * std_ratio - 
                                 d*np.sqrt(nobs) / std_alternative)
        if alternative in ['two-sided', '2s', 'smaller']:
            crit = stats.norm.ppf(alpha_)
            pow_ += stats.norm.cdf(crit * std_ratio - 
                                   d*np.sqrt(nobs) / std_alternative)
        return pow_
    
        
    class Holder(object):
        def __init__(self, **kwargs):
            self.__dict__.update(kwargs)
        
    def power_proportion_2indep(p1, p2, diff_alt, nobs, ratio=1, alpha=0.05,
                                alternative='two-sided'):
        nobs_ratio = ratio
    
        p_pooled = (p1 + p2 * ratio) / (1 + ratio)
        #p1_vnull, p2_vnull = p1_obs, p2_obs  # Wald
        p1_vnull, p2_vnull = p_pooled, p_pooled
        p2_alt = p2
        p1_alt = p2_alt + diff_alt
            
        std_null = std_diff_prop(p1_vnull, p2_vnull)
        std_alt = std_diff_prop(p1_alt, p2_alt, ratio=nobs_ratio)
        
        diff = diff_alt
        power = normal_power(diff, nobs, alpha, std_null=std_null, 
                             std_alternative=std_alt,
                             alternative=alternative)
    
        res = Holder(p_pooled=p_pooled,
                     std_null=std_null,
                     std_alt=std_alt)
        return power, res
        
        
        
        
    
    alpha = 0.05
    delta_alt = 0.2
    nobs_ratio = 1.
    p1_obs, p2_obs = 0.5, 0.3
    #p1_obs, p2_obs = 0.3, 0.3
    p1_obs, p2_obs = 0.4, 0.4
    #p1_obs, p2_obs = 0.5, 0.5
    p1_obs, p2_obs = 0.85, 0.65
    p1_vnull, p2_vnull = p1_obs, p2_obs  # Wald
    p2_alt = p2_obs
    p1_alt = p2_obs + delta_alt
    
    def std_diff_prop(p1, p2, ratio=1):
        return np.sqrt(p1 * (1 - p1) + p2 * (1 - p2) / ratio)
        
    std_null = std_diff_prop(p1_vnull, p2_vnull)
    std_alt = std_diff_prop(p1_alt, p2_alt)
    
    diff = delta_alt
    nobs = 70
    power = normal_power(diff, nobs, alpha, std_null=std_null, 
                         std_alternative=std_alt,
                         alternative='two-sided')
    print(power)
    
    power = normal_power(diff, nobs, alpha, std_null=std_null, 
                         std_alternative=std_alt,
                         alternative='larger')
    print(power)
    
    power = normal_power(diff, nobs, alpha, std_null=std_null, 
                         std_alternative=std_alt,
                         alternative='smaller')
    print(power)
    
    print()
    pp = power_proportion_2indep(0.25, 0.6, -0.35, 50, ratio=2)
    print(pp)    
    
    pone = normal_power(-0.2, 30, alpha, std_null=np.sqrt(0.3 * (1-0.3)), 
                         std_alternative=np.sqrt(0.5*(1-0.5)),
                         alternative='two-sided')
    print('\np one sample')
    print(pone)
    print('Stata', 0.6534)  # p. 144
    
    
    #normal_power(diff, nobs, alpha, std_null=std_null, std_alternative=std_alt, alternative='two-sided')
    
    print(normal_power(0.014, 550, 0.05, std_null=0.12598, std_alternative=0.1255945, alternative='two-sided'))
    res = power_proportion_2indep(0.001, 0.015, -0.014, 550, ratio=1.)
    print(res[0])
    print(vars(res[1]))
    
  6. josef-pkt commented on Aug 8, 2018

    @josef-pkt
    MemberAuthor

    aside : NCSS PASS documentation has a separate chapter for two proportion power using effect size similar to what we have now. But then additional chapters with the proper versions with variance depending on proportions that differ across null and alternative.

    PASS also distinguishes between equality hypothesis p1=p2 from inferiority, superiority and equivalence tests with p1 - p2 = diff or p1 - p2 <= diff, and their (risk) ratio and odds-ratio analogues.
    I would prefer to merge those into one set of functions.
    (furthermore superiority and inferiority tests in NCSS/PASS only differ in the sign of diff.)

  7. josef-pkt commented on Aug 8, 2018

    @josef-pkt
    MemberAuthor

    Some explanation to one-tail sample size formula:

    power for two-sided test, e.g. z-test includes the probability of being in the "wrong", far tail. If this part is ignored or the test has a one-sided alternative, then we can explicitly invert the power function to compute the sample size.
    My initial version is below.

    However, we have power only in the "correct" tail, i.e. if the alternative is in the direction of the one-sided alternative. In general we can compute "power", i.e. prob of rejection even for opposite sign of the effect under the alternative, then power < alpha. In this case no sample size can achieve a large desired power.
    So, for sample size computation we can only look at alternatives that are in the correct, detectable direction.
    The sample size formula uses the square of the effect and only considers the "correct" tail.
    The alternative option is irrelevant, because the computation doesn't allow us to be in the "wrong" tail.

    I'm parking this here because the simplified function will not allow a choice of which tail is used, and sign of diff or effect is irrelevant/ignored.

    I'm using one_tail in the name instead of one-sided to emphasize that we use a tail but don't have a directed one-sided test, or that we look at one tail in a two-sided tests.

    def normal_sample_size_one_tail(diff, power, alpha, std_null=1., 
                                     std_alternative=None, ratio=1.,
                                     alternative='larger'):
        """explicit sample size computation if only one tail is relevant
        
        The sample size is based on the power in one tail assuming that the
        alternative is in the tail where the test has power that increases
        with sample size.
        Use alpha/2 to compute the one tail approximation for the two-sided
        test, i.e. consider only one tail of two-sided test.
        """
    
        crit_power = stats.norm.isf(power)
        if alternative == 'larger':
            crit = stats.norm.isf(alpha)
            n1 = ((crit * std_null - crit_power * std_alternative) / diff)**2
            
        elif alternative == 'smaller':
            crit = stats.norm.ppf(alpha)
            n1 = ((crit * std_null + crit_power * std_alternative) / diff)**2
            
        return n1 
    

    example,
    round trip, two-sided test with alpha=0.05

    • compute power for given sample size
    • compute sample size for obtained power
    res = power_proportion_2indep(0.001, 0.015, -0.014, 550, ratio=1.)
    n_ex = normal_sample_size_one_sided(-0.014, 0.7415600, 0.05 / 2, std_null=res[1].std_null, 
                                     std_alternative=res[1].std_alt, ratio=1.,
                                     alternative='larger')
    

    n_ex is 550.003

  8. josef-pkt commented on Feb 28, 2022

    @josef-pkt
    MemberAuthor

    the current normal_power_het has one std_alternative

    For equivalence tests we need separate std_alternative for the lower margin and upper margin.

    Zhu, Haiyuan. 2017. “Sample Size Calculation for Comparing Two Poisson or Negative Binomial Rates in Noninferiority or Equivalence Trials.” Statistics in Biopharmaceutical Research 9 (1): 107–15. https://doi.org/10.1080/19466315.2016.1225594.

    Pass uses Zhu method for power, sample size of equivalence test comparing Poisson and comparing NegBin2 rates

    current power_proportions_2indep only allows equal null hypothesis, i.e. no nonzero margin value
    i.e. it cannot handle power for non-inferiority or equivalence tests.
    However, normal_power_het should work with one-sided tests where we need only one std_alternative (which differs by value under null hypothesis)

    relevant for #8138

    power.normal_power has undocumented and unused (?) sigma argument

  9. josef-pkt commented on Feb 28, 2022

    @josef-pkt
    MemberAuthor

    related issue I found now in the literature

    nuisance parameter and variance under local alternatives:

    under local alternatives, the parameter estimates converge to those under the null.

    Some articles take this to assume that variance is unchanged under the alternative and still is at the null value.

    example:

    • score_test: everything is computed locally using the null parameters
    • score confidence interval computed under the alternative that values are at confint bounds, i.e. solve constrained optimization problem. In those cases, the parameter estimates change to MLE under different constraints than original Null model. Similar for profile likelihood and profile likelihood confidence intervals.

    Tang, Yongqiang, Liang Zhu, and Jiezhun Gu. 2021. “An Improved Sample Size Calculation Method for Score Tests in Generalized Linear Models.” Statistics in Biopharmaceutical Research 13 (4): 415–24. https://doi.org/10.1080/19466315.2020.1756398.

  10. josef-pkt commented on Nov 22, 2024

    @josef-pkt
    MemberAuthor

    The power and samplesize_xxx_onetail function are now implemented, or we have the pattern and helper functions for those.

    However, we don't have power classes for those cases. #8159

    Closing this issue.
    The issue remains informative because it has the main design and reference information.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions