-
Notifications
You must be signed in to change notification settings - Fork 3
/
CorpusViewer.py
239 lines (215 loc) · 8.23 KB
/
CorpusViewer.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
# coding=utf-8
__author__ = 'ealexand'
import csv
import os
import time
from flask import Blueprint, render_template, abort, current_app, jsonify, request
import numpy
import MikeTM
import Utilities as util
def index():
return view_by_name("foo")
def view_by_name(model_name):
return render_template(
"slimCV.html",
title=model_name + " (Matrix View)",
model_name=model_name,
models=os.listdir(current_app.config['METADATA_ROOT'])
)
def get_metadata(model_name):
metadataCSV = os.path.join(util.get_model_root(model_name), 'metadata.csv')
metadata = []
with open(metadataCSV, 'rb') as f:
reader = csv.reader(f)
rowNum = 0
for row in reader:
if rowNum == 0:
colNames = row
elif rowNum == 1:
dataTypes = row
else:
temp = {}
for i in range(len(row)):
temp[colNames[i]] = row[i]
metadata.append(temp)
rowNum += 1
try:
return jsonify({'metadata': metadata, 'fieldNames': colNames, 'dataTypes': dataTypes})
except UnicodeDecodeError:
for i in range(len(metadata)):
try:
jsonify({'metadata': metadata[i]})
except UnicodeDecodeError:
print 'UnicodeDecodeError on metadata row %d' % i
print metadata[i]
raise
def get_theta(model_name):
start = time.time()
includedMetadataIndices = getIncludedMetadata(model_name)
print 'Got metadata (%.2f sec)' % (time.time() - start)
start = time.time()
model_root = util.get_model_root(model_name)
thetaCSV = os.path.join(model_root, 'theta.csv')
theta = []
topicProps = {}
with open(thetaCSV, 'rb') as f:
reader = csv.reader(f)
currDoc = 0
currIndex = 0 # This is only incremented if we actually include the doc
maxTopic = 0
for row in reader:
if currDoc in includedMetadataIndices:
theta.append({})
for i in range(0, len(row), 2):
topicNum = int(row[i])
prop = float(row[i+1])
theta[currIndex][topicNum] = prop
maxTopic = max(maxTopic, topicNum)
if topicNum in topicProps:
topicProps[topicNum].append(prop)
else:
topicProps[topicNum] = [prop]
currIndex += 1
currDoc += 1
print 'Got theta (%.2f sec)' % (time.time() - start)
start = time.time()
topicMetadataList = [{} for i in range(maxTopic+1)]
for i in range(maxTopic+1):
if i in topicProps:
currTopicList = topicProps[i]
topicMetadataList[i]['numDocs'] = len(currTopicList)
topicMetadataList[i]['min'] = numpy.min(currTopicList)
topicMetadataList[i]['max'] = numpy.max(currTopicList)
topicMetadataList[i]['median'] = numpy.median(currTopicList)
topicMetadataList[i]['mean'] = numpy.mean(currTopicList)
topicMetadataList[i]['variance'] = numpy.var(currTopicList)
topicMetadataList[i]['range'] = topicMetadataList[i]['max'] - topicMetadataList[i]['min']
#topicMetadataList[i]['outliers'] = 0 #TODO: fill this in
#topicMetadataList[i]['uniformity'] = 0 #TODO: fill this in
else:
topicMetadataList[i] = {
'numDocs': 0,
'min': 0,
'max': 0,
'median': 0,
'mean': 0,
'variance': 0,
'range': 0
}
topicMetadataFields = ['min','max','median','mean','variance','range','numDocs']#,'outliers','uniformity']
print 'Got topic metadata (%.2f sec)' % (time.time() - start)
returnDict = {
'theta': theta,
'numDocs': len(theta),
'numTopics': maxTopic + 1,
'topicMetadata': topicMetadataList,
'topicMetadataFields': topicMetadataFields
}
try:
topicNameFile = os.path.join(model_root, 'topicNames.csv')
topicNames = []
with open(topicNameFile, 'rb') as f:
reader = csv.reader(f)
for row in reader:
topicNames = row
break
returnDict['colList'] = topicNames
except IOError:
pass
try:
groupFilePath = os.path.join(model_root, 'docGroups.csv')
groups = {}
with open(groupFilePath, 'rb') as f:
reader = csv.reader(f)
for row in reader:
groups[row[0]] = map(int, row[1:])
returnDict['docGroups'] = groups
except IOError:
returnDict['docGroups'] = {}
try:
groupFilePath = os.path.join(model_root, 'topicGroups.csv')
groups = {}
with open(groupFilePath, 'rb') as f:
reader = csv.reader(f)
for row in reader:
groups[row[0]] = map(int, row[1:])
returnDict['topicGroups'] = groups
except IOError:
returnDict['topicGroups'] = {}
print 'Jsonifying and sending...'
return jsonify(returnDict)
def getIncludedMetadata(model_name):
metadataCSV = os.path.join(util.get_model_root(model_name), 'metadata.csv')
includedMetadataIndices = []
with open(metadataCSV, 'rb') as f:
reader = csv.reader(f)
rowNum = 0
for row in reader:
if rowNum == 0:
colNames = row
elif rowNum == 1:
dataTypes = row
else:
temp = {}
for i in range(len(row)):
temp[colNames[i]] = row[i]
includedMetadataIndices.append(rowNum - 2)
rowNum += 1
return includedMetadataIndices
def set_group_name(model_name, group_file, group_name, group):
# First, load any pre-existing groups to compare
groups = {}
groupFilePath = os.path.join(util.get_model_root(model_name), group_file)
try:
with open(groupFilePath, 'rb') as f:
reader = csv.reader(f)
for row in reader:
groups[row[0]] = row[1:]
except IOError:
pass
groups[group_name] = map(int, group.split(','))
with open(groupFilePath, 'wb') as f:
writer = csv.writer(f)
for groupName in groups:
writer.writerow([groupName] + groups[groupName])
return jsonify({'groups':groups})
def get_groups(model_name, group_file):
try:
groupFilePath = os.path.join(util.get_model_root(model_name), group_file)
groups = {}
with open(groupFilePath, 'rb') as f:
reader = csv.reader(f)
for row in reader:
groups[row[0]] = map(int, row[1:])
return jsonify({'groups':groups})
except IOError:
return jsonify({})
def getAnovaOrder(model_name, fieldName, debug=False):
try:
mtm = MikeTM.TopicModel(current_app.config['METADATA_ROOT'], model_name)
anovaOrder = mtm.anovaColsRanks(fieldName)
if debug:
return anovaOrder
else:
return jsonify({'anovaOrder':[str(v) for v in anovaOrder]})
except KeyError:
print 'KeyError while getting ANOVA order. Probably from bad metadata field name. Check capitalization?'
return jsonify({'anovaOrder':[]})
def getContrastOrder(model_name, fieldName, group1, group2=[], debug=False):
group1 = group1.split(',')
if group2=='matrix' or group2=='[ALL]':
group2 = []
else:
group2 = group2.split(',')
mtm = MikeTM.TopicModel(current_app.config['METADATA_ROOT'], model_name)
contrastOrder = mtm.contrastColsRanks(fieldName, group1, group2)
if debug:
return contrastOrder
else:
return jsonify({'contrastOrder':[str(v) for v in contrastOrder]})
if __name__=='__main__':
print getAnovaOrder('ShakespeareChunkedOptimized_50','Genre',debug=True)
print getContrastOrder('ShakespeareChunkedOptimized_50','Genre','comedy',debug=True)
print getContrastOrder('ShakespeareChunkedOptimized_50','Genre','tragedy','history',debug=True)
print getContrastOrder('ShakespeareChunkedOptimized_50','Genre','romance',debug=True)
print getContrastOrder('ShakespeareChunkedOptimized_50','Genre',['comedy','tragedy'],debug=True)