Skip to content

zt_ind_solve_power returns numpy array instead of float #4022

Open

Description

@jaradc

sm.stats.zt_ind_solve_power returns an array if nobs1 is less than 197. I'm sure 197 is not special; it's just the result of the other settings in this specific case. The documentation says that a float is returned, not an array. If an array is returned, should it be assumed that there is no answer for the ratio?

es = 0.20
alpha = 0.05
power = 0.80
for n1 in range(1, 401, 10):
	n1, sm.stats.zt_ind_solve_power(es, n1, alpha, power, ratio=None, alternative='two-sided')

(1, array([ 12926.]))
(11, array([ 7233.36610346]))
(21, array([ 14302.63047839]))
(31, array([ 294141.47907722]))
(41, array([ 424723.9626395]))
(51, array([ 653547.47554599]))
(61, array([ 1047796.24848788]))
(71, array([ 864465.36172393]))
(81, array([ 1457060.60164413]))
(91, array([ 1248130.6972059]))
(101, array([ 2165978.03108565]))
(111, array([ 1886292.83657938]))
(121, array([ 3004670.74975744]))
(131, array([ 4855495.1619719]))
(141, array([ 3969905.79322159]))
(151, array([ 6555037.82106867]))
(161, array([ 5454723.46003231]))
(171, array([ 9135790.240248]))
(181, array([ 15376233.87906924]))
(191, array([ 41926014.47320025]))
(201, 41.06351974728969)
(211, 13.277510022299376)
(221, 7.919027208755753)
(231, 5.642037224648649)
(241, 4.382048715544689)
(251, 3.5820930501426567)
(261, 3.029115166586838)
(271, 2.6240369376713617)
(281, 2.314520102141116)
(291, 2.070316800463505)
(301, 1.8727279560623094)
(311, 1.709566984615799)
(321, 1.5725585411403584)
(331, 1.4558815605038435)
(341, 1.3553226926244626)
(351, 1.267757015041292)
(361, 1.1908199627958316)
(371, 1.122686872917464)
(381, 1.0619267276423723)
(391, 1.0074094489317402)

Just for reference, with R using rpy2 pwr library, if I attempt this same thing, an error is thrown with the following:

>>> for i in range(2, 1000):
	pwr.pwr_2p2n_test(h=0.20, n1=i, sig_level=alpha, power=power, alternative="two.sided")[2][0]

	
Traceback (most recent call last):
  File "<pyshell#45>", line 2, in <module>
    pwr.pwr_2p2n_test(h=0.20, n1=i, sig_level=alpha, power=power, alternative="two.sided")[2][0]
  File "C:\Python35\lib\site-packages\rpy2\robjects\functions.py", line 178, in __call__
    return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
  File "C:\Python35\lib\site-packages\rpy2\robjects\functions.py", line 106, in __call__
    res = super(Function, self).__call__(*new_args, **new_kwargs)
rpy2.rinterface.RRuntimeError: Error in uniroot(function(n2) eval(p.body) - power, c(2 + 1e-10, 1e+09)) : 
  f() values at end points not of opposite sign
>>> es = 0.20
>>> for i in range(196, 1000):
	pwr.pwr_2p2n_test(es, n1=i, sig_level=alpha, power=power, alternative="two.sided")[2][0]

	
Traceback (most recent call last):
  File "<pyshell#48>", line 2, in <module>
    pwr.pwr_2p2n_test(es, n1=i, sig_level=alpha, power=power, alternative="two.sided")[2][0]
  File "C:\Python35\lib\site-packages\rpy2\robjects\functions.py", line 178, in __call__
    return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
  File "C:\Python35\lib\site-packages\rpy2\robjects\functions.py", line 106, in __call__
    res = super(Function, self).__call__(*new_args, **new_kwargs)
rpy2.rinterface.RRuntimeError: Error in uniroot(function(n2) eval(p.body) - power, c(2 + 1e-10, 1e+09)) : 
  f() values at end points not of opposite sign

>>> for i in range(197, 1000):
	pwr.pwr_2p2n_test(es, n1=i, sig_level=alpha, power=power, alternative="two.sided")[2][0]

	
49654.8108846919
21845.45271925996
14053.719626671102

Activity

  1. josef-pkt commented on Oct 11, 2017

    @josef-pkt
    Member

    I need to check what's going on with these numbers the array numbers look too large.
    What is your scipy version for this?

    In general, we pay attention in some function, but overall we don't have enough checks about python scalar, numpy scalar or 1-element array.

    In this case, I think the problem is that there are different rootfinders used below and above 200. The way it is written the root solving has several backups, i.e. if the first fails to find a solution, then we try a second and maybe a third solver. It could also be that the scipy rootfinders don't consistently return scalars.

    running your example I get the same results, but it prints ConvergenceWarnings, e.g.

    191 [ 41926014.47320025]
    m:\...\statsmodels\stats\power.py:280: ConvergenceWarning: 
    Failed to converge on a solution.
    
      warnings.warn(convergence_doc, ConvergenceWarning)
    

    If I read the example correctly (without having thought about all the details yet):
    There might or will be cases like this where a solution just doesn't exist. i.e. with only 1 observation in the first groups it is not possible to achieve the desired power and alpha, even with an infinite number of observations in the other group.
    (I try to check the details later.)

  2. jaradc commented on Oct 11, 2017

    @jaradc
    Author

    Scipy Version:
    scipy.version : 0.19.1

    Python Version: 3.5 64-bit

    Operating system: Windows 7 Professional

    You know what, you're right. I did have warnings.filterwarnings("ignore") set to ignore another warning (clearly not a good idea to do this I know :) ) so I didn't see the convergence warning. I uncommented that line and saw the same convergence warning as you.

    I saw on your blog that you mentioned root-finding in the power calculations is based on scipy.optimize. Would you venture to go out on a limb and say if the returned value is a float instance then it converged, else no solution is possible?

  3. josef-pkt commented on Oct 11, 2017

    @josef-pkt
    Member

    a quick check of the achievable power
    computing power uses an explicit formula and doesn't need rootfinding
    fixing ratio at 1 million (as something very large), and checking power for different nobs1:

    Based on this we need at least nobs=197 to have a power=0.8. For smaller nobs1, there will be no ratio to achieve that power.
    I think the numbers is your list up to 191, are just the large numbers where the rootfinder "gave up"

    edit to add import, I'm using
    from statsmodels.stats import power as pwr

    >>> for n1 in range(190, 210): print(n1, pwr.NormalIndPower().power(es, n1, alpha=alpha, ratio=1000000, alternative='two-sided'))
     
    190 0.787230491864
    191 0.78932854835
    192 0.791408981329
    193 0.793471890639
    194 0.795517376397
    195 0.797545538973
    196 0.799556478973
    197 0.801550297218
    198 0.803527094729
    199 0.805486972702
    200 0.807430032496
    201 0.809356375611
    202 0.811266103674
    203 0.813159318418
    204 0.815036121668
    205 0.816896615324
    206 0.818740901343
    207 0.820569081728
    208 0.822381258506
    209 0.824177533718
    

    another check based on nobs1=197

    >>> pwr.zt_ind_solve_power(es, 197, alpha=alpha, power=power, ratio=None, alternative='two-sided')
    252.054877568191
    
    >>> pwr.NormalIndPower().power(es, 197, alpha=alpha, ratio=252.05, alternative='two-sided')
    0.79999997001057854
    
    >>> pwr.zt_ind_solve_power(es, 196, alpha=alpha, power=power, ratio=None, alternative='two-sided')
    array([  1.35000781e+09])
    >>> m:\...\statsmodels\stats\power.py:280: ConvergenceWarning: 
    Failed to converge on a solution.
    
      warnings.warn(convergence_doc, ConvergenceWarning)
    

    So from this it looks like the results are as expected.

    I didn't try to figure out where the array is created. (postponed to 0.10)

  4. added this to the 0.10 milestone on Oct 11, 2017
  5. jaradc commented on Oct 12, 2017

    @jaradc
    Author

    I looked at the source code and tracked it back to the Power class in /stats/power.py. I believe the array is being returned by optimize.fsolve. I hope this helps.

    # this portion of code found in the Power class
    if (not failed) and res.converged:
                success = 1
            else:
                # try backup
                #TODO: check more cases to make this robust
                val, infodict, ier, msg = optimize.fsolve(func, start_value,
                                                          full_output=True) #scalar
                print(val) ####### <---------------- HERE RETURNS NUMPY ARRAY
                #val = optimize.newton(func, start_value) #scalar
                fval = infodict['fvec']
                fit_res.append(infodict)
                if ier == 1 and np.abs(fval) < 1e-4 :
                    success = 1
                else:
    

    Also, I just want to clarify that there was nothing special about iteration 197; it was just the point where arrays stopped printing and floats started with those specific alphas, effect size, etc. I assume floats starting to print is synonymous with convergence starting to happen.

    The take-away that I'm trying to convey is that the point at which an array is returned (did not converge) and a float is returned is dependent on the other settings of alpha, power, effect size, etc. And no-doubt you already know that.

    This function is so useful! My intent of reaching out was just to figure out:

    1. if an array is returned, does that mean it did not converge?
      1a. if it did not converge, is it safe to assume it's either an infinite loop or there's no solution?

    I don't need an answer, these questions are more rhetorical. I love this function, it's so valuable and useful!

    >>> import statsmodels.api as sm
    
    Warning (from warnings module):
      File "C:\Python35\lib\site-packages\statsmodels\compat\pandas.py", line 56
        from pandas.core import datetools
    FutureWarning: The pandas.core.datetools module is deprecated and will be removed in a future version. Please use the pandas.tseries module instead.
    >>> import warnings
    >>> es = 0.20
    >>> alpha = 0.05
    >>> power = 0.80
    >>> for n1 in range(193, 200, 1):
    	warnings.filterwarnings('ignore')
    	n1, sm.stats.zt_ind_solve_power(es, n1, alpha, power, ratio=None, alternative='two-sided')
    
    	
    (193, array([ 68281765.06499192]))
    (194, array([  1.16360516e+08]))
    (195, array([  1.79189863e+08]))
    (196, array([  1.35000781e+09]))
    (197, 252.054877568191)
    (198, 110.33056935034112)
    (199, 70.62170666551185)
    >>> # changing es
    >>> es = 0.15
    >>> # note the range
    >>> for n1 in range(346, 352, 1):
    	warnings.filterwarnings('ignore')
    	n1, sm.stats.zt_ind_solve_power(es, n1, alpha, power, ratio=None, alternative='two-sided')
    
    	
    (346, array([  2.01772754e+08]))
    (347, array([  3.34731686e+08]))
    (348, array([  4.71290189e+08]))
    (349, 2156.5821189856647)
    (350, 300.2683031517782)
    (351, 161.36806535400672)
    >>> alpha = 0.025
    >>> # leaving es 0.15 still
    >>> for n1 in range(420, 426, 1):
    	warnings.filterwarnings('ignore')
    	n1, sm.stats.zt_ind_solve_power(es, n1, alpha, power, ratio=None, alternative='two-sided')
    
    	
    (420, array([  3.47374961e+08]))
    (421, array([  5.53476752e+08]))
    (422, array([  1.30189303e+09]))
    (423, 762.5764959487844)
    (424, 271.84918859426733)
    (425, 165.40746245523778)
    
  6. josef-pkt commented on Oct 12, 2017

    @josef-pkt
    Member

    just replying to two parts

    1. if an array is returned, does that mean it did not converge?

    No, all we can infer is that it uses a different code path, in this case rootfinder. Whether that one converged is independent of the return type.
    If printing the warning is the only indication of non-convergence, then we might need to provide more information to the user.
    Actually, I didn't know that there are impossible cases like this. For equivalence test I explicitly checked cases where no solution that satisfies the requirements exists.

    1a. if it did not converge, is it safe to assume it's either an infinite loop or there's no solution?

    Unfortunately not. Non-convergence is a strong indication that there is a problem with the "question", but all numerical optimizers and rootfinders can fail for many reasons. This was my initial motivation to layer several rootfinders in the hope that at least one works. But there is no guarantee that the solution is found even if one exists.

    The "non-rhetorical" parts are

    • knowing in which cases it doesn't work, or no solution exists
    • figuring out what can be improved.

    Issues and feedback like this is helpful for both.

    Just as background:
    I spent most of the time when implementing power on getting a good generic solution that we can use for many different cases. There is currently very little in terms of handling specific cases or exploiting computational shortcuts that apply in specific cases, or safeguards for special cases when the generic setting breaks down in specific cases.
    On the other hand it covers many different cases without having to write much code for each of those cases.

    For example. in this case:
    I think we could compute the minimum nobs1 that is required to satisfy the requirements and for which a solution for ratio or nobs2 exists. The extreme case when ratio and nobs2 is very large is when the second mean has zero sampling error.

    e.g. using the current implementation
    solve for nobs1 given a large ratio, gives an answer close to 197 and similar in the example cases

    >>> pwr.zt_ind_solve_power(es, nobs1=None, alpha=alpha, power=power, ratio=1000000, alternative='two-sided')
    196.22170895710894
    
    >>> pwr.zt_ind_solve_power(effect_size=0.15, nobs1=None, alpha = 0.05, power=power, ratio=1000000, alternative='two-sided')
    348.83859398892815
    
    >>> pwr.zt_ind_solve_power(effect_size=0.15, nobs1=None, alpha = 0.025, power=power, ratio=1000000, alternative='two-sided')
    422.44645038508776
    

    This looks fine, and it even works, once we know what the specific problem and question are.

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

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions