/
statistician.py
242 lines (177 loc) · 6 KB
/
statistician.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
from rpy2.robjects.vectors import DataFrame
import rpy2.robjects as robjects
from mongoTools import MongoAdmin
import random
class Statistician():
def __init__(self, db):
#initialize a lookup, dataFile table of terms
self.db = MongoAdmin(db)
self.hypotheses = ["It was expected that ", "It was predicted that "]
self.interpretations = ["This is probably because", "This could be due to "]
self.acceptnull = ["Contrary to the hypothesis, however ", "Against prediction,", "Contrary to expectation, "]
self.rejectnull = ["as predicted", "as expected"]
self.signs = {'>' : 'greater than', '<' : 'less than', '==' : 'equal to'}
def translate(self, term, units=False):
#if a string return the available translation
output = ""
posts = self.db.getTable('factors').posts
if type(term) == str:
row = posts.find_one({'name': term})
print row
if row:
output = row['label']
else:
output = term
if units:
output += " %s" % row['units']
#if a list/tree get all available translations
elif type(term) == list:
output = "%s" % self.translate(term[0])
for t in term[1:]:
output += " and %s" % self.translate(t)
#otherwise just return a string of the term
else:
output = str(term)
return output
def describeFactor(self, factor):
posts = self.db.getTable('factors').posts
if type(factor) == str:
row = posts.find_one({'name': factor})
else:
row = posts.find_one({'name': factor[0]})
return None
def parseAssertion(self, hyp, measure, tense="future"):
tenses = {}
tenses['future'] = 'would be'
tenses['past'] = 'was'
output = ""
if hyp == "?":
pass
else:
for s in [">", "<", "=="]:
if s in hyp:
frags = hyp.split(s)
output += "%s %s %s %s %s %s" % (self.translate(frags[0]), measure, tenses[tense], self.signs[s], self.translate(frags[1]), measure)
#now we should sort the fragments in ascending order and ditch the sign
if s == ">":
frags.reverse()
return output, s, frags
def interpret(self, factors, measure, model, dataFile, condition={}):
posts = self.db.getTable('hypotheses').posts
q = condition
for f in factors:
q[f] = unicode('TARGET')
row = posts.find_one(q)
output = ""
if row:
hyp = random.choice(self.hypotheses)
if row.has_key(measure):
assertion, s, frags = self.parseAssertion(row[measure], measure)
output += "%s%s.\n" % (hyp, assertion)
result = self.compareMeans(dataFile, model, frags, factors, measure)
if result:
output += result
output += "\n"
return output
def hypothesize(self, factors, measure, condition={}):
posts = self.db.getTable('hypotheses').posts
q = condition
for f in factors:
q[f] = unicode('TARGET')
row = posts.find_one(q)
output = ""
if row:
hyp = random.choice(self.hypotheses)
if row.has_key(measure):
assertion, s, frags = self.parseAssertion(row[measure], measure)
output += "%s %s." % (random.choice(self.hypotheses), assertion)
return output
def attachData(self, dataFile):
argString = "read.table(\"output/%s\", header=T, sep=\",\")" % dataFile
df = robjects.r(argString)
robjects.r.attach(df)
return df
def correlate(self, m1, m2, dataFile, siglevel = 0.05):
df = self.attachData(dataFile)
cor = robjects.r("cor.test(%s, %s)" % (m1, m2))
p = cor.rx2("p.value")
p = p[0]
r = cor.rx2("estimate")
r = r[0]
if p <= siglevel:
sig = True
else:
sig = False
return sig, r, p
def anova(self, model, dataFile, siglevel = 0.05, within = False):
df = self.attachData(dataFile)
argString = 'aov(%s)' % model
aov = robjects.r(argString)
summary = robjects.r("summary")
result = summary(aov)
ew = result.rx2('Error: Within')
F = ew[0][3][0]
p = ew[0][4][0]
if p <= siglevel:
sig = True
else:
sig = False
return sig, F, p
def ttest(self, model, dataFile, siglevel = 0.05):
df = self.attachData(dataFile)
model = model.split('+')[0]
result = robjects.r('t.test(%s)' % model)
p = result.rx2('p.value')
t = result.rx2('statistic')
e = result.rx2('estimate')
if p[0] < siglevel:
sig = True
else:
sig = False
return sig, t[0], p[0]
def compareMeans(self, dataFile, model, levels, factors, measure):
df = self.attachData(dataFile)
means = robjects.r('tapply(%s, %s, mean)' % (measure, factors[0]))
sds = robjects.r('tapply(%s, %s, sd)' % (measure, factors[0]))
d = {}
largest = 0
largeNum = 0
for l in levels:
m = means.rx2(l)
sd = sds.rx2(l)
if m[0] > largeNum:
largest = l
largeNum = m[0]
d[l] = {'mean': m[0], 'sd' : sd[0]}
output = ""
meanString = ""
for k in d.keys():
meanString += "%s(M=%2.2f, SD=%2.2f) and " % (self.translate(k), d[k]['mean'], d[k]['sd'])
meanString = meanString.rstrip(' and ')
sig, F, p = self.anova(model, dataFile)
f_result = "F=%2.2f, p<%0.2f" %(F, p)
if sig:
output += "The F test passed, with %s. " % (f_result)
if len(levels) == 2:
output += "A t test was conducted, comparing the means of %s. " % meanString
sig, t, p = self.ttest(model, dataFile)
result = "t = %2.2f, p<%0.2f" % (t, p)
if sig and largest == levels[1]:
output += "This passed with %s, %s. " % (result, random.choice(self.rejectnull))
elif sig:
output += "This passed but in the wrong direction, with %s. Looks like we called that one pretty badly. " % result
else:
if t != "nan":
if largest == levels[1]:
output += "The t test did not pass. That the mean %s of %s was the larger mean (as was predicted), though this difference was non-significant. " % (measure, levels[1])
else:
output += "The t test did not pass, with %s. " % result
else:
print "Tukey's HSD Time!"
else:
if str(F) != "nan":
output += "The F test did not pass, with %s. " % (f_result)
if largest == levels[1]:
output += "However, the mean %s of %s was the larger mean (as expected), though this difference was non-significant." % (measure, levels[1])
output += "\n"
return output