-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsalstat_stats.py
executable file
·1314 lines (1204 loc) · 35.6 KB
/
salstat_stats.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# stats.py - reworked module for statistical analysis using OOP
"""
This module has been written specifically for the SalStat statistics package.
It is an object oriented (and more limited) version of Gary Strangmans
stats.y module, and much code has been taken from there. The classes and
methods are usable from the command line, and some may prefer the OO style
to stats.py's functional style.
Most of the code in this file is copyright 2002 Alan James Salmoni, and is
released under version 2 or later of the GNU General Public Licence (GPL).
See the enclosed file COPYING for the full text of the licence.
Other parts of this code were taken from stats.py by Gary Strangman of
Harvard University (c) Not sure what year, Gary Strangman, released under the
GNU General Public License."""
import math
import copy
# Short routines used in the functional constructs to reduce analysis time
def add(a,b): return a+b
def squared(a): return math.pow(a, 2)
def cubed(a): return math.pow(a, 3)
def quaded(a): return math.pow(a, 4)
def multiply(a,b): return a*b
def obsMinusExp(a,b): return (a-b)**2/b
def diffsquared(a,b): return (a-b)**2
def higher(a,b):
if a>b:
return 1
else:
return 0
def lower(a,b):
if a<b:
return 1
else:
return 0
def shellsort(inlist):
""" Shellsort algorithm. Sorts a 1D-list.
Usage: shellsort(inlist)
Returns: sorted-inlist, sorting-index-vector (for original list)
"""
n = len(inlist)
svec = copy.deepcopy(inlist)
ivec = range(n)
gap = n/2 # integer division needed
while gap >0:
for i in range(gap,n):
for j in range(i-gap,-1,-gap):
while j>=0 and svec[j]>svec[j+gap]:
temp = svec[j]
svec[j] = svec[j+gap]
svec[j+gap] = temp
itemp = ivec[j]
ivec[j] = ivec[j+gap]
ivec[j+gap] = itemp
gap = gap / 2 # integer division needed
# svec is now sorted inlist, and ivec has the order svec[i] = vec[ivec[i]]
return svec, ivec
def rankdata(inlist):
"""
Ranks the data in inlist, dealing with ties appropritely. Assumes
a 1D inlist. Adapted from Gary Perlman's |Stat ranksort.
Usage: rankdata(inlist)
Returns: a list of length equal to inlist, containing rank scores
"""
n = len(inlist)
svec, ivec = shellsort(inlist)
sumranks = 0
dupcount = 0
newlist = [0]*n
for i in range(n):
sumranks = sumranks + i
dupcount = dupcount + 1
if i==n-1 or svec[i] != svec[i+1]:
averank = sumranks / float(dupcount) + 1
for j in range(i-dupcount+1,i+1):
newlist[ivec[j]] = averank
sumranks = 0
dupcount = 0
return newlist
def tiecorrect(rankvals):
"""
Corrects for ties in Mann Whitney U and Kruskal Wallis H tests. See
Siegel, S. (1956) Nonparametric Statistics for the Behavioral Sciences.
New York: McGraw-Hill. Code adapted from |Stat rankind.c code.
Usage: tiecorrect(rankvals)
Returns: T correction factor for U or H
"""
sorted = copy.copy(rankvals)
sorted.sort()
n = len(sorted)
T = 0.0
i = 0
while (i<n-1):
if sorted[i] == sorted[i+1]:
nties = 1
while (i<n-1) and (sorted[i] == sorted[i+1]):
nties = nties +1
i = i +1
T = T + nties**3 - nties
i = i+1
T = T / float(n**3-n)
return 1.0 - T
def sum (inlist):
"""
Returns the sum of the items in the passed list.
Usage: sum(inlist)
"""
s = 0
for item in inlist:
s = s + item
return s
# this is used by the single factor anova routines (only I think) & the SS
# value may not actually be needed!
def minimaldescriptives(inlist):
"""this function takes a clean list of data and returns the N, sum, mean
and sum of squares. """
N = 0
sum = 0.0
SS = 0.0
for i in range(len(inlist)):
N = N + 1
sum = sum + inlist[i]
SS = SS + (inlist[i] ** 2)
mean = sum / float(N)
return N, sum, mean, SS
###########################
## Probability functions ##
###########################
def chisqprob(chisq,df):
"""
Returns the (1-tailed) probability value associated with the provided
chi-square value and df. Adapted from chisq.c in Gary Perlman's |Stat.
Usage: chisqprob(chisq,df)
"""
BIG = 20.0
def ex(x):
BIG = 20.0
if x < -BIG:
return 0.0
else:
return math.exp(x)
if chisq <=0 or df < 1:
return 1.0
a = 0.5 * chisq
if df%2 == 0:
even = 1
else:
even = 0
if df > 1:
y = ex(-a)
if even:
s = y
else:
s = 2.0 * zprob(-math.sqrt(chisq))
if (df > 2):
chisq = 0.5 * (df - 1.0)
if even:
z = 1.0
else:
z = 0.5
if a > BIG:
if even:
e = 0.0
else:
e = math.log(math.sqrt(math.pi))
c = math.log(a)
while (z <= chisq):
e = math.log(z) + e
s = s + ex(c*z-a-e)
z = z + 1.0
return s
else:
if even:
e = 1.0
else:
e = 1.0 / math.sqrt(math.pi) / math.sqrt(a)
c = 0.0
while (z <= chisq):
e = e * (a/float(z))
c = c + e
z = z + 1.0
return (c*y+s)
else:
return s
def inversechi(prob, df):
"""This function calculates the inverse of the chi square function. Given
a p-value and a df, it should approximate the critical value needed to
achieve these functions. Adapted from Gary Perlmans critchi function in
C. Apologies if this breaks copyright, but no copyright notice was
attached to the relevant file."""
minchisq = 0.0
maxchisq = 99999.0
chi_epsilon = 0.000001
if (prob <= 0.0):
return maxchisq
elif (prob >= 1.0):
return 0.0
chisqval = df / math.sqrt(prob)
while ((maxchisq - minchisq) > chi_epsilon):
if (chisqprob(chisqval, df) < prob):
maxchisq = chisqval
else:
minchisq = chisqval
chisqval = (maxchisq + minchisq) * 0.5
return chisqval
def erfcc(x):
"""
Returns the complementary error function erfc(x) with fractional
error everywhere less than 1.2e-7. Adapted from Numerical Recipies.
Usage: erfcc(x)
"""
z = abs(x)
t = 1.0 / (1.0+0.5*z)
ans = t * math.exp(-z*z-1.26551223 + t*(1.00002368+t*(0.37409196+t* \
(0.09678418+t*(-0.18628806+t* \
(0.27886807+t*(-1.13520398+t* \
(1.48851587+t*(-0.82215223+t* \
0.17087277)))))))))
if x >= 0:
return ans
else:
return 2.0 - ans
def zprob(z):
"""
Returns the area under the normal curve 'to the left of' the given z value.
Thus,
for z<0, zprob(z) = 1-tail probability
for z>0, 1.0-zprob(z) = 1-tail probability
for any z, 2.0*(1.0-zprob(abs(z))) = 2-tail probability
Adapted from z.c in Gary Perlman's |Stat.
Usage: zprob(z)
"""
Z_MAX = 6.0 # maximum meaningful z-value
if z == 0.0:
x = 0.0
else:
y = 0.5 * math.fabs(z)
if y >= (Z_MAX*0.5):
x = 1.0
elif (y < 1.0):
w = y*y
x = ((((((((0.000124818987 * w
-0.001075204047) * w +0.005198775019) * w
-0.019198292004) * w +0.059054035642) * w
-0.151968751364) * w +0.319152932694) * w
-0.531923007300) * w +0.797884560593) * y * 2.0
else:
y = y - 2.0
x = (((((((((((((-0.000045255659 * y
+0.000152529290) * y -0.000019538132) * y
-0.000676904986) * y +0.001390604284) * y
-0.000794620820) * y -0.002034254874) * y
+0.006549791214) * y -0.010557625006) * y
+0.011630447319) * y -0.009279453341) * y
+0.005353579108) * y -0.002141268741) * y
+0.000535310849) * y +0.999936657524
if z > 0.0:
prob = ((x+1.0)*0.5)
else:
prob = ((1.0-x)*0.5)
return prob
def ksprob(alam):
"""
Computes a Kolmolgorov-Smirnov t-test significance level. Adapted from
Numerical Recipies.
Usage: ksprob(alam)
"""
fac = 2.0
sum = 0.0
termbf = 0.0
a2 = -2.0*alam*alam
for j in range(1,201):
term = fac*math.exp(a2*j*j)
sum = sum + term
if math.fabs(term)<=(0.001*termbf) or math.fabs(term)<(1.0e-8*sum):
return sum
fac = -fac
termbf = math.fabs(term)
return 1.0 # Get here only if fails to converge; was 0.0!!
def fprob (dfnum, dfden, F):
"""
Returns the (1-tailed) significance level (p-value) of an F
statistic given the degrees of freedom for the numerator (dfR-dfF) and
the degrees of freedom for the denominator (dfF).
Usage: fprob(dfnum, dfden, F) where usually dfnum=dfbn, dfden=dfwn
"""
p = betai(0.5*dfden, 0.5*dfnum, dfden/float(dfden+dfnum*F))
return p
def tprob(df, t):
return betai(0.5*df,0.5,float(df)/(df+t*t))
def inversef(prob, df1, df2):
"""This function returns the f value for a given probability and 2 given
degrees of freedom. It is an approximation using the fprob function.
Adapted from Gary Perlmans critf function - apologies if copyright is
broken, but no copyright notice was attached """
f_epsilon = 0.000001
maxf = 9999.0
minf = 0.0
if (prob <= 0.0) or (prob >= 1.0):
return 0.0
fval = 1.0 / prob
while (abs(maxf - minf) > f_epsilon):
if fprob(fval, df1, df2) < prob:
maxf = fval
else:
minf = fval
fval = (maxf + minf) * 0.5
return fval
def betacf(a,b,x):
"""
This function evaluates the continued fraction form of the incomplete
Beta function, betai. (Adapted from: Numerical Recipies in C.)
Usage: betacf(a,b,x)
"""
ITMAX = 200
EPS = 3.0e-7
bm = az = am = 1.0
qab = a+b
qap = a+1.0
qam = a-1.0
bz = 1.0-qab*x/qap
for i in range(ITMAX+1):
em = float(i+1)
tem = em + em
d = em*(b-em)*x/((qam+tem)*(a+tem))
ap = az + d*am
bp = bz+d*bm
d = -(a+em)*(qab+em)*x/((qap+tem)*(a+tem))
app = ap+d*az
bpp = bp+d*bz
aold = az
am = ap/bpp
bm = bp/bpp
az = app/bpp
bz = 1.0
if (abs(az-aold)<(EPS*abs(az))):
return az
#print 'a or b too big, or ITMAX too small in Betacf.'
def gammln(xx):
"""
Returns the gamma function of xx.
Gamma(z) = Integral(0,infinity) of t^(z-1)exp(-t) dt.
(Adapted from: Numerical Recipies in C.)
Usage: gammln(xx)
"""
coeff = [76.18009173, -86.50532033, 24.01409822, -1.231739516,
0.120858003e-2, -0.536382e-5]
x = xx - 1.0
tmp = x + 5.5
tmp = tmp - (x+0.5)*math.log(tmp)
ser = 1.0
for j in range(len(coeff)):
x = x + 1
ser = ser + coeff[j]/x
return -tmp + math.log(2.50662827465*ser)
def betai(a,b,x):
"""
Returns the incomplete beta function:
I-sub-x(a,b) = 1/B(a,b)*(Integral(0,x) of t^(a-1)(1-t)^(b-1) dt)
where a,b>0 and B(a,b) = G(a)*G(b)/(G(a+b)) where G(a) is the gamma
function of a. The continued fraction formulation is implemented here,
using the betacf function. (Adapted from: Numerical Recipies in C.)
Usage: betai(a,b,x)
"""
if (x<0.0 or x>1.0):
raise ValueError
if (x==0.0 or x==1.0):
bt = 0.0
else:
bt = math.exp(gammln(a+b)-gammln(a)-gammln(b)+a*math.log(x)+b*
math.log(1.0-x))
if (x<(a+1.0)/(a+b+2.0)):
return bt*betacf(a,b,x)/float(a)
else:
return 1.0-bt*betacf(b,a,1.0-x)/float(b)
class Probabilities:
def __init__(self):
pass
# is this necessary?
def betai(self, a, b, x):
"""
returns the incomplete beta function
"""
if (x<0.0 or x>1.0):
raise ValueError
if (x==0.0 or x==1.0):
bt = 0.0
else:
bt = math.exp(gammln(a+b)-gammln(a)-gammln(b)+a*math.log(x)+b*
math.log(1.0-x))
if (x<(a+1.0)/(a+b+2.0)):
self.prob = bt*betacf(a,b,x)/float(a)
else:
self.prob = 1.0-bt*betacf(b,a,1.0-x)/float(b)
def gammln(self, xx):
"""
returns the gamma function of xx.
"""
coeff = [76.18009173, -86.50532033, 24.01409822, -1.231739516,
0.120858003e-2, -0.536382e-5]
x = xx - 1.0
tmp = x + 5.5
tmp = tmp - (x+0.5)*math.log(tmp)
ser = 1.0
for j in range(len(coeff)):
x = x + 1
ser = ser + coeff[j]/x
return -tmp + math.log(2.50662827465*ser)
def betacf(self, a, b, x):
ITMAX = 200
EPS = 3.0e-7
bm = az = am = 1.0
qab = a+b
qap = a+1.0
qam = a-1.0
bz = 1.0-qab*x/qap
for i in range(ITMAX+1):
em = float(i+1)
tem = em + em
d = em*(b-em)*x/((qam+tem)*(a+tem))
ap = az + d*am
bp = bz+d*bm
d = -(a+em)*(qab+em)*x/((qap+tem)*(a+tem))
app = ap+d*az
bpp = bp+d*bz
aold = az
am = ap/bpp
bm = bp/bpp
az = app/bpp
bz = 1.0
if (abs(az-aold)<(EPS*abs(az))):
return az
###########################
## Test Classes ##
###########################
class FullDescriptives:
"""
class for producing a series of continuous descriptive statistics. The
variable "inlist" must have been cleaned of missing data. Statistics
available by method are: N, sum, mean, sample variance (samplevar),
variance, standard deviation (stddev), standard error (stderr), sum of
squares (sumsquares), sum of squared deviations (ssdevs), coefficient of
variation (coeffvar), skewness, kurtosis, median, mode, median absolute
deviation (mad), number of unique values (numberuniques).
"""
def __init__(self, inlist, name = '', missing = 0):
self.Name = name
if len(inlist) == 0:
self.N = 0
self.sum = self.mean = self.sumsquares = self.minimum = self.maximum = self.median = 0
self.mad = self.numberuniques = self.harmmean = self.ssdevs = self.samplevar = 0
self.geomean = self.variance = self.coeffvar = self.skewness = self.kurtosis = self.mode = 0
elif len(inlist) == 1:
self.N = self.numberuniques = 1
self.sum = self.mean = self.minimum = self.maximum = self.median = inlist[0]
self.mad = self.harmmean = self.geomean = inlist[0]
self.samplevar = self.variance = self.coeffvar = self.skewness = self.mode = 0
self.kurtosis = self.sumsquares = ssdevs = 0
elif len(inlist) > 1:
self.missing = missing
self.N = len(inlist)
self.sum = reduce(add, inlist)
try:
self.mean = self.sum / float(self.N)
except ZeroDivisionError:
self.mean = 0.0
self.sumsquares = reduce(add, map(squared, inlist))
difflist = []
self.sortlist = copy.copy(inlist)
self.sortlist.sort()
self.minimum = self.sortlist[0]
self.maximum = self.sortlist[len(self.sortlist)-1]
self.range = self.maximum - self.minimum
self.harmmean=0.0
medianindex = self.N / 2
if (self.N % 2):
self.median = self.sortlist[medianindex]
self.firstquartile = self.sortlist[((self.N + 1) / 4) - 1]
#print 'md ' + str(inlist[:medianindex])
else:
self.median = (self.sortlist[medianindex] + self.sortlist[medianindex-1]) / 2.0
self.firstquartile = self.sortlist[(self.N / 4) - 1]
#print 'md ' + str(self.firstquartile)
# median of ranks - useful in comparisons for KW & Friedmans
ranklist = rankdata(self.sortlist)
if (self.N % 2):
self.medianranks = ranklist[(self.N + 1) / 2]
else:
self.medianranks = ranklist[self.N / 2]
self.mad = 0.0
self.numberuniques = 0
for i in range(self.N):
difflist.append(inlist[i] - self.mean)
self.mad = self.mad + (inlist[i] - self.median)
uniques = 1
for j in range(self.N):
if (i != j):
if (inlist[i] == inlist[j]):
uniques = 0
if uniques:
self.numberuniques = self.numberuniques + 1
if (inlist[i] != 0.0):
self.harmmean = self.harmmean + (1.0/inlist[i])
if (self.harmmean != 0.0):
self.harmmean = self.N / self.harmmean
self.ssdevs = reduce(add, map(squared, difflist))
self.geomean = reduce(multiply, difflist)
try:
self.samplevar = self.ssdevs / float(self.N - 1)
except ZeroDivisionError:
self.samplevar = 0.0
try:
moment2 = self.ssdevs / float(self.N)
moment3 = reduce(add, map(cubed, difflist)) / float(self.N)
moment4 = reduce(add, map(quaded, difflist)) / float(self.N)
self.variance = self.ssdevs / float(self.N)
self.stddev = math.sqrt(self.samplevar)
self.coeffvar = self.stddev / self.mean
self.skewness = moment3 / (moment2 * math.sqrt(moment2))
self.kurtosis = (moment4 / math.pow(moment2, 2)) - 3.0
except ZeroDivisionError:
moment2 = 0.0
moment3 = 0.0
moment4 = 0.0
self.variance = 0.0
self.stderr = 0.0
self.coeffvar = 0.0
self.skewness = 0.0
self.kurtosis = 0.0
self.stderr = self.stddev / math.sqrt(self.N)
h = {}
for n in inlist:
try: h[n] = h[n]+1
except KeyError: h[n] = 1
a = map(lambda x: (x[1], x[0]), h.items())
self.mode = max(a)[1]
class OneSampleTests:
"""
This class produces single factor statistical tests.
"""
def __init__(self, data1, name = '', missing = 0):
"""
Pass the data to the init function.
"""
self.d1 = FullDescriptives(data1, name, missing)
def OneSampleTTest(self, usermean):
"""
This performs a single factor t test for a set of data and a user
hypothesised mean value.
Usage: OneSampleTTest(self, usermean)
Returns: t, df (degrees of freedom), prob (probability)
"""
if self.d1.N < 2:
self.t = 1.0
self.prob = -1.0
else:
self.df = self.d1.N - 1
svar = (self.df * self.d1.samplevar) / float(self.df)
self.t = (self.d1.mean - usermean) / math.sqrt(svar*(1.0/self.d1.N))
self.prob = betai(0.5*self.df,0.5,float(self.df)/(self.df+ \
self.t*self.t))
def OneSampleSignTest(self, data1, usermean):
"""
This method performs a single factor sign test. The data must be
supplied to this method along with a user hypothesised mean value.
Usage: OneSampleSignTest(self, data1, usermean)
Returns: nplus, nminus, z, prob.
"""
self.nplus=0
self.nminus=0
for i in range(len(data1)):
if (data1[i] < usermean):
self.nplus=self.nplus+1
if (data1[i] > usermean):
self.nminus=self.nminus+1
self.ntotal = add(self.nplus, self.nminus)
try:
self.z=(self.nplus-(self.ntotal/2)/math.sqrt(self.ntotal/2))
except ZeroDivisionError:
self.z=0
self.prob=-1.0
else:
self.prob=erfcc(abs(self.z) / 1.4142136)
def ChiSquareVariance(self, usermean):
"""
This method performs a Chi Square test for the variance ratio.
Usage: ChiSquareVariance(self, usermean)
Returns: df, chisquare, prob
"""
self.df = self.d1.N - 1
try:
self.chisquare = (self.d1.stderr / usermean) * self.df
except ZeroDivisionError:
self.chisquare = 0.0
self.prob = chisqprob(self.chisquare, self.df)
# class for two sample tests - instantiates descriptives class for both
# data sets, then has each test as a method
class TwoSampleTests:
"""This class performs a series of 2 sample statistical tests upon two
sets of data.
"""
def __init__(self, data1, data2, name1 = '', name2 = '', \
missing1=0,missing2=0):
"""
The __init__ method retrieves a full set of descriptive statistics
for the two supplied data vectors.
"""
self.d1 = FullDescriptives(data1, name1, missing1)
self.d2 = FullDescriptives(data2, name2, missing2)
def TTestUnpaired(self):
"""
This performs an unpaired t-test.
Usage: TTestUnpaired()
Returns: t, df, prob
"""
self.df = (self.d1.N + self.d2.N) - 2
svar = ((self.d1.N-1)*self.d1.samplevar+(self.d2.N-1)* \
self.d2.samplevar)/float(self.df)
self.t = (self.d1.mean-self.d2.mean)/math.sqrt(svar* \
(1.0/self.d1.N + 1.0/self.d2.N))
self.prob = betai(0.5*self.df,0.5,float(self.df)/(self.df+self.t* \
self.t))
def TTestPaired(self, data1, data2):
"""
This method performs a paired t-test on two data sets. Both sets (as
vectors) need to be supplied.
Usage: TTestPaired(data1, data2)
Returns: t, df, prob
"""
if (self.d1.N != self.d2.N):
self.prob = -1.0
self.df = 0
self.t = 0.0
else:
cov = 0.0
self.df = self.d1.N - 1
for i in range(self.d1.N):
cov = cov + ((data1[i] - self.d1.mean) * (data2[i] - \
self.d2.mean))
cov = cov / float(self.df)
sd = math.sqrt((self.d1.samplevar + self.d2.samplevar - 2.0 * \
cov) / float(self.d1.N))
try:
self.t = (self.d1.mean - self.d2.mean) / sd
self.prob = betai(0.5*self.df,0.5,float(self.df)/(self.df+ \
self.t*self.t))
except ZeroDivisionError:
self.t = -1.0
self.prob = 0.0
def PearsonsCorrelation(self, data1, data2):
"""
This method performs a Pearsons correlation upon two sets of
data which are passed as vectors.
Usage: PearsonsCorrelation(data1, data2)
Returns: r, t, df, prob
"""
TINY = 1.0e-60
if (self.d1.N != self.d2.N):
self.prob = -1.0
else:
summult = reduce(add, map(multiply, data1, data2))
r_num = self.d1.N * summult - self.d1.sum * self.d2.sum
r_left = self.d1.N*self.d1.sumsquares-(self.d1.sum**2)
r_right= self.d2.N*self.d2.sumsquares-(self.d2.sum**2)
r_den = math.sqrt(r_left*r_right)
self.df = self.d1.N - 2
try:
self.r = r_num / r_den
self.t = self.r*math.sqrt(self.df/((1.0-self.r+TINY)* \
(1.0+self.r+TINY)))
self.prob = betai(0.5*self.df,0.5,self.df/float \
(self.df+self.t*self.t))
except ZeroDivisionError:
self.r = 1.0
self.t = 0
self.prob = 1.0
TINY = 1e-30
if self.d1.N != self.d2.N:
self.prob= -1.0
else:
rankx = rankdata(data1)
ranky = rankdata(data2)
dsq = reduce(add, map(diffsquared, rankx, ranky))
self.rho = 1 - 6*dsq / float(self.d1.N*(self.d1.N**2-1))
self.t = self.rho * math.sqrt((self.d1.N-2) / \
((self.rho+1.0+TINY)*(1.0-self.rho+TINY)))
self.df = self.d1.N-2
self.prob = betai(0.5*self.df,0.5,self.df/(self.df+self.t*self.t))
def FTest(self, uservar):
"""
This method performs a F test for variance and needs a user
hypothesised variance to be supplied.
Usage: FTest(uservar)
Returns: f, df1, df2, prob
"""
try:
self.f = (self.d1.samplevar / self.d2.samplevar) / uservar
except ZeroDivisionError:
self.f = 1.0
self.df1 = self.d1.N - 1
self.df2 = self.d2.N - 1
self.prob=fprob(self.df1, self.df2, self.f)
def TwoSampleSignTest(self, data1, data2):
"""
This method performs a 2 sample sign test for matched samples on 2
supplied data vectors.
Usage: TwoSampleSignTest(data1, data2)
Returns: nplus, nminus, ntotal, z, prob
"""
if (self.d1.N != self.d2.N):
self.prob=-1.0
else:
nplus=map(higher,data1,data2).count(1)
nminus=map(lower,data1,data2).count(1)
self.ntotal=nplus-nminus
mean=self.d1.N / 2
sd = math.sqrt(mean)
self.z = (nplus-mean)/sd
self.prob = erfcc(abs(self.z)/1.4142136)
def KendallsTau(self, data1, data2):
"""
This method performs a Kendalls tau correlation upon 2 data vectors.
Usage: KendallsTau(data1, data2)
Returns: tau, z, prob
"""
n1 = 0
n2 = 0
if len(data1) != len(data2):
self.tau = "n/a"
self.z = "n/a"
self.prob = -1.0
else:
iss = 0
for j in range(self.d1.N-1):
for k in range(j,self.d2.N):
a1 = data1[j] - data1[k]
a2 = data2[j] - data2[k]
aa = a1 * a2
if (aa): # neither list has a tie
n1 = n1 + 1
n2 = n2 + 1
if aa > 0:
iss = iss + 1
else:
iss = iss -1
else:
if (a1):
n1 = n1 + 1
else:
n2 = n2 + 1
self.tau = iss / math.sqrt(n1*n2)
svar = (4.0*self.d1.N+10.0) / (9.0*self.d1.N*(self.d1.N-1))
self.z = self.tau / math.sqrt(svar)
self.prob = erfcc(abs(self.z)/1.4142136)
def KolmogorovSmirnov(self):
"""
This method performs a Kolmogorov-Smirnov test for unmatched samples
upon 2 data vectors.
Usage: KolmogorovSmirnov()
Returns: d, prob
"""
j1 = 0
j2 = 0
fn1 = 0.0
fn2 = 0.0
self.d = 0.0
data3 = self.d1.sortlist
data4 = self.d2.sortlist
while j1 < self.d1.N and j2 < self.d2.N:
d1=data3[j1]
d2=data4[j2]
if d1 <= d2:
fn1 = (j1)/float(self.d1.N)
j1 = j1 + 1
if d2 <= d1:
fn2 = (j2)/float(self.d2.N)
j2 = j2 + 1
dt = (fn2-fn1)
if math.fabs(dt) > math.fabs(self.d):
self.d = dt
try:
en = math.sqrt(self.d1.N*self.d2.N/float(self.d1.N+self.d2.N))
self.prob = ksprob((en+0.12+0.11/en)*abs(self.d))
except:
self.prob = 1.0
def SpearmansCorrelation(self, data1, data2):
"""
This method performs a Spearmans correlation upon 2 data sets as
vectors.
Usage: SpearmansCorrelation(data1, data2)
Returns: t, df, prob
"""
TINY = 1e-30
if self.d1.N != self.d2.N:
self.prob= -1.0
else:
rankx = rankdata(data1)
ranky = rankdata(data2)
dsq = reduce(add, map(diffsquared, rankx, ranky))
self.rho = 1 - 6*dsq / float(self.d1.N*(self.d1.N**2-1))
self.t = self.rho * math.sqrt((self.d1.N-2) / \
((self.rho+1.0+TINY)*(1.0-self.rho+TINY)))
self.df = self.d1.N-2
self.prob = betai(0.5*self.df,0.5,self.df/(self.df+self.t*self.t))
def RankSums(self, data1, data2):
"""
This method performs a Wilcoxon rank sums test for unpaired designs
upon 2 data vectors.
Usage: RankSums(data1, data2)
Returns: z, prob
"""
x = copy.copy(data1)
y = copy.copy(data2)
alldata = x + y
ranked = rankdata(alldata)
x = ranked[:self.d1.N]
y = ranked[self.d1.N:]
s = reduce(add, x)
expected = self.d1.N*(self.d1.N+self.d2.N+1) / 2.0
self.z = (s - expected) / math.sqrt(self.d1.N*self.d2.N* \
(self.d2.N+self.d2.N+1)/12.0)
self.prob = 2*(1.0 -zprob(abs(self.z)))
def SignedRanks(self, data1, data2):
"""
This method performs a Wilcoxon Signed Ranks test for matched samples
upon 2 data vectors.
Usage: SignedRanks(data1, data2)
Returns: wt, z, prob
"""
if self.d1.N != self.d2.N:
self.prob = -1.0
else:
d=[]
for i in range(self.d1.N):
diff = data1[i] - data2[i]
if diff != 0:
d.append(diff)
count = len(d)
absd = map(abs,d)
absranked = rankdata(absd)
r_plus = 0.0
r_minus = 0.0
for i in range(len(absd)):
if d[i] < 0:
r_minus = r_minus + absranked[i]
else:
r_plus = r_plus + absranked[i]
self.wt = min(r_plus, r_minus)
mn = count * (count+1) * 0.25
se = math.sqrt(count*(count+1)*(2.0*count+1.0)/24.0)
self.z = math.fabs(self.wt-mn) / se
self.prob = 2*(1.0 -zprob(abs(self.z)))
def MannWhitneyU(self, data1, data2):
"""
This method performs a Mann Whitney U test for unmatched samples on
2 data vectors.
Usage: MannWhitneyU(data1, data2)
Returns: bigu, smallu, z, prob
"""
ranked = rankdata(data1+data2)
rankx = ranked[0:self.d1.N]
u1 = self.d1.N*self.d2.N+(self.d1.N*(self.d1.N+1))/2.0-reduce\
(add, rankx)
u2 = self.d1.N*self.d2.N - u1
self.bigu = max(u1,u2)
self.smallu = min(u1,u2)
T = math.sqrt(tiecorrect(ranked))
if T == 0:
self.prob = -.10
self.z = -1.0
else:
sd = math.sqrt(T*self.d1.N*self.d2.N*(self.d1.N+self.d2.N+1)/12.0)
self.z = abs((self.bigu-self.d1.N*self.d2.N/2.0) / sd)
self.prob = 1.0-zprob(self.z)
def LinearRegression(self, x, y):
"""
This method performs a linear regression upon 2 data vectors.
Usage(LinearRegression(x,y)
Returns: r, df, t, prob, slope, intercept, sterrest
"""
TINY = 1.0e-20
if (self.d1.N != self.d2.N):
self.prob = -1.0
else:
summult = reduce(add, map(multiply, x, y))
r_num = float(self.d1.N*summult - self.d1.sum*self.d2.sum)
r_den = math.sqrt((self.d1.N*self.d1.sumsquares - \
(self.d1.sum**2))*(self.d2.N* \
self.d2.sumsquares - (self.d2.sum**2)))
try:
self.r = r_num / r_den
except ZeroDivisionError:
self.r = 0.0
#[] warning - z not used - is there a line missing here?
z = 0.5*math.log((1.0+self.r+TINY)/(1.0-self.r+TINY))
self.df = self.d1.N - 2
self.t = self.r*math.sqrt(self.df/((1.0-self.r+TINY)*(1.0+ \
self.r+TINY)))
self.prob = betai(0.5*self.df,0.5,self.df/(self.df+self.t*self.t))
self.slope = r_num / float(self.d1.N*self.d1.sumsquares - \
(self.d1.sum**2))
self.intercept = self.d2.mean - self.slope*self.d1.mean
self.sterrest = math.sqrt(1-self.r*self.r)*math.sqrt \
(self.d2.variance)