Repository navigation
Description
We can compare rates (positive but not smaller than one) of two samples similar to two sample proportions tests and confidence intervals.
http://stackoverflow.com/questions/33944914/implimentation-of-e-test-for-poisson-in-python/34013250#34013250
#2605 confint for proportions,
#2607 exact tests
there are also other issues for proportions, exact conditional, mid-p, approximate or unconditional exact. The structure seems to be similar in rates and proportions cases.
E-test: uses MLE or constrained MLE for unconditional test with (assumed) exact distribution
There should be also the unconditional exact and berger_boos, but I didn't look for them yet.
R stats seems to have conditional exact, some others are in various R packages.
some R related papers by Michael P. Fay. ref?
below is a copy of my current script file
'''Test for ratio of Poisson intensities in two independent samples
Author: Josef Perktold
License: BSD-3
destination statsmodels
'''
from __future__ import division
import numpy as np
from scipy import stats
# copied from statsmodels.stats.weightstats
def _zstat_generic2(value, std_diff, alternative):
'''generic (normal) z-test to save typing
can be used as ztest based on summary statistics
'''
zstat = value / std_diff
if alternative in ['two-sided', '2-sided', '2s']:
pvalue = stats.norm.sf(np.abs(zstat))*2
elif alternative in ['larger', 'l']:
pvalue = stats.norm.sf(zstat)
elif alternative in ['smaller', 's']:
pvalue = stats.norm.cdf(zstat)
else:
raise ValueError('invalid alternative')
return zstat, pvalue
def poisson_twosample(count1, exposure1, count2, exposure2, ratio_null=1,
method='score', alternative='2-sided'):
'''test for ratio of two sample Poisson intensities
If the two Poisson rates are g1 and g2, then the Null hypothesis is
H0: g1 / g2 = ratio_null
against one of the following alternatives
H1_2-sided: g1 / g2 != ratio_null
H1_larger: g1 / g2 > ratio_null
H1_smaller: g1 / g2 < ratio_null
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: float
ratio of the two Poisson rates under the Null hypothesis. Default is 1.
method: string
Method for the test statistic and the p-value. Defaults to `'score'`.
Current Methods are based on Gu et. al 2008
Implemented are 'wald', 'score' and 'sqrt', see Notes
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
Returns
-------
stat, pvalue two-sided
not yet
#results : Results instance
# The resulting test statistics and p-values are available as attributes.
Notes
-----
'wald': method W1A, wald test, variance based on separate estimates
'score': method W2A, score test, variance based on estimate under Null
'wald-log': W3A
'score-log' W4A
'sqrt': W5A, based on variance stabilizing square root transformation
References
----------
Gu, Ng, Tang, Schucany 2008: Testing the Ratio of Two Poisson Rates,
Biometrical Journal 50 (2008) 2, 2008
'''
# shortcut names
y1, n1, y2, n2 = count1, exposure1, count2, exposure2
d = n2 / n1
r = ratio_null
r_d = r / d
if method in ['score']:
stats = (y1 - y2 * r_d) / np.sqrt((y1 + y2) * r_d)
elif method in ['wald']:
stats = (y1 - y2 * r_d) / np.sqrt(y1 + y2 * r_d**2)
elif method in ['sqrt']:
stats = 2 * (np.sqrt(y1 + 3 / 8.) - np.sqrt((y2 + 3 / 8.) * r_d))
stats /= np.sqrt(1 + r_d)
return _zstat_generic2(stats, 1, alternative)
pvalue = stats.norm.sf(np.abs(stat))*2
return stat, pvalue
from numpy.testing import assert_allclose
# testing against two examples in Gu et al
print('\ntwo-sided')
# example 1
count1, n1, count2, n2 = 60, 51477.5, 30, 54308.7
s1, pv1 = poisson_twosample(count1, n1, count2, n2, method='wald')
pv1r = 0.000356
assert_allclose(pv1, pv1r*2, rtol=0, atol=5e-6)
print('wald', s1, pv1 / 2) # one sided in the "right" direction
s2, pv2 = poisson_twosample(count1, n1, count2, n2, method='score')
pv2r = 0.000316
assert_allclose(pv2, pv2r*2, rtol=0, atol=5e-6)
print('score', s2, pv2 / 2) # one sided in the "right" direction
s2, pv2 = poisson_twosample(count1, n1, count2, n2, method='sqrt')
pv2r = 0.000285
assert_allclose(pv2, pv2r*2, rtol=0, atol=5e-6)
print('sqrt', s2, pv2 / 2) # one sided in the "right" direction
print('\ntwo-sided')
# example2
# I don't know why it's only 2.5 decimal agreement, rounding?
count1, n1, count2, n2 = 41, 28010, 15, 19017
s1, pv1 = poisson_twosample(count1, n1, count2, n2, method='wald', ratio_null=1.5)
pv1r = 0.2309
assert_allclose(pv1, pv1r*2, rtol=0, atol=5e-3)
print('wald', s1, pv1 / 2) # one sided in the "right" direction
s2, pv2 = poisson_twosample(count1, n1, count2, n2, method='score', ratio_null=1.5)
pv2r = 0.2398
assert_allclose(pv2, pv2r*2, rtol=0, atol=5e-3)
print('score', s2, pv2 / 2) # one sided in the "right" direction
s2, pv2 = poisson_twosample(count1, n1, count2, n2, method='sqrt', ratio_null=1.5)
pv2r = 0.2499
assert_allclose(pv2, pv2r*2, rtol=0, atol=5e-3)
print('sqrt', s2, pv2 / 2) # one sided in the "right" direction
print('\none-sided')
# example 1 onesided
count1, n1, count2, n2 = 60, 51477.5, 30, 54308.7
s1, pv1 = poisson_twosample(count1, n1, count2, n2, method='wald', alternative='larger')
pv1r = 0.000356
assert_allclose(pv1, pv1r, rtol=0, atol=5e-6)
print('wald', s1, pv1) # one sided in the "right" direction
s2, pv2 = poisson_twosample(count1, n1, count2, n2, method='score', alternative='larger')
pv2r = 0.000316
assert_allclose(pv2, pv2r, rtol=0, atol=5e-6)
print('score', s2, pv2) # one sided in the "right" direction
s2, pv2 = poisson_twosample(count1, n1, count2, n2, method='sqrt', alternative='larger')
pv2r = 0.000285
assert_allclose(pv2, pv2r, rtol=0, atol=5e-6)
print('sqrt', s2, pv2) # one sided in the "right" direction
print('\none-sided')
# example2 onesided
# I don't know why it's only 2.5 decimal agreement, rounding?
count1, n1, count2, n2 = 41, 28010, 15, 19017
s1, pv1 = poisson_twosample(count1, n1, count2, n2, method='wald',
ratio_null=1.5, alternative='larger')
pv1r = 0.2309
assert_allclose(pv1, pv1r, rtol=0, atol=5e-4)
print('wald', s1, pv1) # one sided in the "right" direction
s2, pv2 = poisson_twosample(count1, n1, count2, n2, method='score',
ratio_null=1.5, alternative='larger')
pv2r = 0.2398
assert_allclose(pv2, pv2r, rtol=0, atol=5e-4)
print('score', s2, pv2) # one sided in the "right" direction
s2, pv2 = poisson_twosample(count1, n1, count2, n2, method='sqrt',
ratio_null=1.5, alternative='larger')
pv2r = 0.2499
assert_allclose(pv2, pv2r, rtol=0, atol=5e-4)
print('score', s2, pv2) # one sided in the "right" direction
Activity
josef-pkt commentedon Dec 1, 2015
asides:
NCSS/PASS uses Gu as main reference with the tests that I also implemented
SAS: I didn't find anything
Stata: I didn't look
Gu also has formulas for power
Total exposure is aggregate over individual exposure times. But no reference I looked at mentions dispersion issues, i.e. i.i.d. observations and consequently Poisson is assumed.
josef-pkt commentedon Dec 2, 2015
the stackoverflow version now also has conditional exact and it's mid-p version
a first draft for an overview is here https://github.com/josef-pkt/misc/wiki/Exact-and-Asymptotic-Tests---Rates,-Poisson
josef-pkt commentedon Dec 3, 2015
I just remembered: scipy.stats.distributions has the distribution of the difference of two independent Poisson random variables. This might be useful somewhere here if the different exposures and non-null difference can be appropriately used.
(I don't remember the details for it https://en.wikipedia.org/wiki/Skellam_distribution )
bscan commentedon Feb 25, 2016
This is great and should be quite useful. I'd suggest adding an additional method for generating p-values from the exact conditional test by using twice the pvalue from the smaller tail, as stated in Krishnamoorthy and Thomson. "A more powerful test for comparing two Poisson means.".
Although R uses the exact conditional as you have implemented here, Michael Fay (as you mentioned) has pushed for the 2 x min(pval) approach in https://cran.r-project.org/web/packages/exactci/vignettes/exactci.pdf. The code for this is shown below and also matches the online calculator: http://www.evanmiller.org/ab-testing/poisson-means.html
This motivating reason for this method is that it is well-aligned with confidence intervals on differences if those were to be computed as well.
bscan commentedon Feb 25, 2016
Also, I don't think that the z-score should be returned by the function, only the p-value. The z-score doesn't really make sense for many of the methods and is inconsistent with stats.proportion.binom_test
josef-pkt commentedon Feb 26, 2016
@bscan Thanks for the feedback, really appreciated
did you look at my PR @2723 or mainly here?
I'm a bit out of this area and need to come back to it later in spring. I stopped here (after the stackoverflow question), and went back to proportion tests.
about centered p-value: good idea
AFAICS, I only realized afterwards that binom_test is min-p #2735 and didn't think of going back here.
I think this should become an option for binom_test in statsmodels and maybe also in scipy.stats.
About returning z-score or a test statistic: This is still inconsistent, and my latest thinking is to always return a results class to avoid inconsistent return patterns.
Returning z-score or another (pivotal) test statistic can be useful if we want to run bootstrap or similar using the returns of the function.
The problem I had in a notebook was that in most cases the p-value is the second return, but in some cases it's the only return. This makes it difficult to write consistent functions on top of these hypothesis tests.
this_test(data).pvaluewould provide consistency independent of what else is returned or attached.If you are interested in related issues:
this https://github.com/josef-pkt/misc/blob/proportion_one/notebooks/proportion_one_power.ipynb
is my development notebook that tries to bring everything together for the simpler case of one sample proportion.
Getting there for the different cases will be longer term, and shouldn't prevent merging usable things earlier.
josef-pkt commentedon Feb 18, 2022
mostly done and merged in #6677 , was new in 0.12
Do we have an overview summ issue for rates tests, tost, confint?
similar to #4828 for proportions?