/
mongoTools.py
563 lines (400 loc) · 12 KB
/
mongoTools.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
import pymongo
from pymongo import Connection
from pymongo.code import Code
import copy
import glob
import os
class MongoAdmin:
"""
This is a simple class to provide easy
access to a mongo database
"""
def __init__(self, db="test_database"):
self.connection = Connection()
self.db = self.connection[db]
return None
def getDB(self):
return self.db
def getTable(self, table="test_table"):
return self.db[table]
def GetKeys(p):
mr = Code("function() {for (var key in this) { emit(key, null);}}")
r = Code("function(key, stuff) { return null;}")
result = p.map_reduce(map=mr, reduce=r)
keys = result.distinct("_id")
return keys
def KeySafe(key):
key = key.replace(".", "_")
return key
def StringToType(value):
if value.isdigit():
val = int(value)
elif value.count('.') == 1:
val = value.split('.')
if val[0].isdigit() and val[1].isdigit():
val = float(value)
else:
val = value
return val
def strip(i):
i = i.strip()
i = i.replace('\t', '')
return i
class RecursiveTrim:
def __init__(self, cursor, measure, maxSD):
#first determine the M and SD of the posts
db = MongoAdmin("Trimmer")
posts = db.getTable("Trim").posts
posts.remove({})
for row in cursor:
posts.insert(row)
self.posts = posts
self.measure = measure
self.maxSD = maxSD
self.Trim()
def Trim(self):
reduceFunc = Code("function(obj,prev) { meas = obj.%s; prev.csum += meas; prev.ccount++; prev.ss += meas * meas;}" % self.measure)
initial = {"csum":0, "ccount":0, "ss":0, "avg":0, "std":0}
finalize = Code("function(prev){ prev.avg = prev.csum / prev.ccount; prev.std = Math.sqrt((prev.ss - (prev.csum * prev.csum/ prev.ccount)) / prev.ccount);}")
mapFunc = Code("function () {emit(this.%s, 1);}" % self.measure)
summary = self.posts.group({}, {}, initial, reduceFunc, finalize)
if summary:
self.avg = summary[0]['avg']
self.std = summary[0]['std']
self.count = summary[0]['ccount']
if str(self.count) == "NA" or str(self.count) == "nan":
self.count = 0
if self.maxSD:
mapFunc = Code("function() {"
"emit(this.%s, 1);"
"}" % (self.measure))
reduceFunc = Code("function(obj, prev) {"
"zscore = Math.abs(obj - %s) / %s;"
"return zscore; }" % (self.avg, self.std))
result = self.posts.map_reduce(map=mapFunc, reduce=reduceFunc)
item = result.find().sort('value', -1)[0]
if item['value'] > self.maxSD:
self.posts.remove({self.measure:item['_id']})
self.Trim()
else:
self.avg = 0
self.std = 0
self.count = 0
def GetValues(self):
return self.avg, self.std, self.count
class ReadTable:
"""
Class to read single or a set of data files
Args are...
fileName (String) - name of the file, or a pattern to be globbed
dbName (String) - name of the DB you'd like to submit this data to
tableName (String) - name of the table you'd like to enter this data into
clear (Boolean) - Whether or not to erase the contents of the table
before uploading this data into it
startLine (int) - The line on which the headers appear in the file
columns (String List) - If you want to upload only specific columns
from the data files, put the header names in this list
sep (String) - the character which separates data in your data file
"""
def __init__(self, fileName, dbName, tableName, kind="", clear=False, startLine=0, columns=[], sep=","):
db = MongoAdmin(dbName)
table = db.getTable(tableName)
if clear:
table.posts.remove({})
self.posts = table.posts
self.sep = ","
if fileName.count('*'):
self.fileList = glob.glob(fileName)
else:
self.fileList = [fileName]
self.startLine = startLine
self.columns = columns
for f in self.fileList:
if kind != "eprime":
self.processCSV(f)
else:
self.processEPrime(f)
def processCSV(self, csv):
f = open(csv, 'r')
lines = f.readlines()
#get the headers, make the variables
headers = lines[self.startLine].split(',')
headers = map(strip, headers)
VARs = {}
index = {}
for k in headers:
if self.columns:
if k in self.columns:
index[k] = headers.index(k)
VARs[k] = []
else:
index[k] = headers.index(k)
VARs[k] = []
for line in lines[self.startLine+1:]:
print line
line = line.split(',')
line = map(strip, line)
row = {}
for k in VARs.keys():
try:
value = line[index[k]]
if value:
row[k] = StringToType(value)
except:
pass
self.posts.insert(row)
print "The contents of %s have been uploaded" % (csv)
def processEPrime(self, txt):
f = open(txt, 'r')
lines = map(strip, f.readlines())
i1 = lines.index("*** Header Start ***")
i2 = lines.index("*** Header End ***")
header = lines[i1+1:i2]
info = {}
data = {}
for h in header:
frags = h.split(":")
frags = map(strip, frags)
if self.columns:
if frags[0] in self.columns:
info[KeySafe(frags[0])] = StringToType(frags[1])
else:
info[KeySafe(frags[0])] = StringToType(frags[1])
i1 = i2
dataLines = lines[i1 + 1:]
trial = 1
row = {}
for d in dataLines:
for k in info.keys():
row[k] = info[k]
if d.count(":"):
frags = d.split(":")
frags = map(strip, frags)
if self.columns:
if frags[0] in self.columns:
row[KeySafe(frags[0])] = StringToType(frags[1])
else:
row[KeySafe(frags[0])] = StringToType(frags[1])
elif d == "*** LogFrame End ***":
if row:
row['trial'] = trial
trial = trial + 1
self.posts.insert(row)
row = {}
print "The contents of %s have been uploaded" % (txt)
class WriteTable:
def __init__(self, measures, groupBy, condition, dbName, table, name="", maxSD = 3, subject="s_id", count=False, level="subject"):
if groupBy:
if type(groupBy) == str:
self.groupBy = [groupBy]
else:
self.groupBy = groupBy
else:
self.groupBy = []
if level == "trial":
self.groupBy += ["trial"]
self.level = level
dbA = MongoAdmin(dbName)
my_table = dbA.getTable(table)
self.posts = my_table.posts
self.condition = condition
self.maxSD = maxSD
self.name = "%s_%s" % (dbName, table)
for g in self.groupBy:
self.name = self.name + "_" + g
for m in measures:
self.name = self.name + "_" + m
if name:
self.name += "_%s" % name
if type(measures) == str:
self.measures = [measures]
else:
self.measures = measures
self.subject = subject
self.count = count
#initialization and finalization for the groupBy query - note that the reduce functions are constructed at run time to correspond with the necessary subject SD screen
self.initial = {"csum":0, "ccount":0, "ss":0, "avg":0, "std":0}
self.finalize = Code("function(prev){ prev.avg = prev.csum / prev.ccount; prev.std = Math.sqrt(Math.abs(prev.ss - prev.avg * prev.csum) / prev.ccount);} ")
self.s_ids = self.posts.find(condition).distinct(subject)
self.Compute()
def Compute(self):
sDict = {}
gDict = {}
#get a list of all the conditions within each grouping factor
matchingPosts = self.posts.find(self.condition)
for g in self.groupBy:
cats = matchingPosts.distinct(g)
gDict[g] = cats
myString = "headerItems = []\nheaderList = []\n"
tabby = ""
gString = str(self.groupBy)
gString = gString.strip('[')
gString = gString.strip(']')
dString = ""
lString = ""
for g in self.groupBy:
dString = "%s,'%s' : %s" % (dString, g, g)
if lString == "":
lString = "str(%s)" % g
else:
lString = lString + "+ \"_\" + str(" + g + ")"
dString = "{" + dString.lstrip(',') + "}"
#create the big ol' for loop, one for each grouping factor
for g in self.groupBy:
myString = "%s%sfor %s in gDict['%s']:\n" % (myString, tabby, g, g)
tabby = tabby + "\t"
myString = "%s%sheaderItems.append(%s)\n" % (myString, tabby, dString)
myString = "%s%sheaderList.append(%s)" % (myString, tabby, lString)
subjects = self.posts.distinct(self.subject)
if self.groupBy:
exec(myString)
groupBy = [self.subject] + self.groupBy
else:
groupBy = [self.subject]
headerItems = []
headerList = []
#firstly, let's check and see whether these combos are even valid
validHeaderItems = []
validHeaderList = []
for h, hl in zip(headerItems, headerList):
myC = copy.deepcopy(self.condition)
for k in h.keys():
myC[k] = h[k]
valid = self.posts.find(myC).count()
if valid:
validHeaderItems.append(h)
validHeaderList.append(hl)
headerItems = validHeaderItems
self.headerItems = headerItems
finalHeaders = []
self.headerList = validHeaderList
for h in validHeaderList:
for m in self.measures:
finalHeaders.append(h + "_%s" % m)
if self.count:
finalHeaders.append(h + "%s_count" % m)
self.finalHeaders = finalHeaders
#now let's go through and calculate the means for the valid combos
for s_id in self.s_ids:
print "Processing Subject %s" % s_id
c = copy.deepcopy(self.condition)
c[self.subject] = s_id
gbKey = {}
for g in groupBy:
gbKey[g] = True
items = []
if validHeaderItems:
for h in validHeaderItems:
r = {self.subject : s_id}
for k in h.keys():
r[k] = h[k]
c[k] = h[k]
items = self.getRows(c, r, items)
else:
items = self.getRows(c, {self.subject : s_id}, items)
sDict[str(s_id)] = items
self.sDict = sDict
def getRows(self, c, r, items):
meas = self.measures
for m in meas:
rows = self.posts.find(c)
if rows.count() ==1:
row = self.posts.find_one(c)
if m == "count":
avg = 1
else:
avg = row[m]
std = "NA"
count = 1
elif rows.count() > 1:
trimmer = RecursiveTrim(rows, m, self.maxSD)
avg, std, count = trimmer.GetValues()
else:
avg = "NA"
std = "NA"
count = 0
r['%s' % m] = avg
r['%s_std' % m] = std
r['%s_count' % m] = int(count)
items.append(copy.deepcopy(r))
#compute the total amount of measurements here
for m in meas:
total = 0.
for i in items:
total += total + i['%s_count' % m]
#add a frequency field to the items
for i in items:
if total > 0:
i['%s_freq' % m] = i['%s_count' % m] / total * 100.
else:
i['freq_%s' % m] = "NA"
return items
def WriteForR(self):
headers = [self.subject] + self.groupBy + self.measures
lines = []
for k in self.sDict.keys():
for row in self.sDict[k]:
line = ""
valid = 0
#first check for the validity of this line
meas = self.measures
for m in meas:
if str(row[m]) != "NA":
valid = 1
if valid:
print headers
for h in headers:
if h == "count":
h = "count_count"
value = str(row[h])
if value != "NA":
line = "%s,%s" % (line, row[h])
else:
if h == "freq" or h == "count":
line = "%s,0" % (line)
else:
line = "%s,NA" % (line)
line = line.lstrip(',')
line = "%s" % line
lines.append(line)
self.Write(headers,lines,"dat")
return "%s.dat" % (self.name)
def WriteForSPSS(self):
lines = []
for s_id in self.sDict.keys():
line = "%s" % s_id
lineDict = {}
print "Writing Subject %s" % s_id
for row in self.sDict[s_id]:
col = ""
for g in self.groupBy:
col = col + "_" + str(row[g])
col = col.strip("_")
for m in self.measures:
lineDict[col+ "_%s" % m] = row[m]
if self.count:
lineDict[col+ "_count"] = row['count']
for header in self.headerList:
try:
for m in self.measures:
line = "%s, %s" % (line, lineDict["%s_%s" % (header, m)])
if self.count:
line = "%s, %i" % (line, lineDict[header + "_count"])
except KeyError:
line = "%s, NA" % line
if self.count:
line = "%s, NA" % line
lines.append(line)
self.Write([self.subject] + self.finalHeaders,lines,"csv")
def Write(self, headers, lines, ext):
#now, write the output file
path = os.path.join("output", "%s.%s" % (self.name, ext))
f = open(path, "w")
hString = ""
for h in headers:
hString = "%s,%s" % (hString, h)
f.write(hString[1:])
f.write("\n")
for l in lines:
f.write(l + "\n")
f.close()