-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.py
385 lines (251 loc) · 11.4 KB
/
server.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
"""Brain Odyssey server"""
from jinja2 import StrictUndefined
from model import Location, Activation, Study, StudyTerm, Term, TermCluster, Cluster, connect_to_db
from flask import Flask, render_template, jsonify, request
from operator import itemgetter
import numpy as np
app = Flask(__name__)
# If you use an undefined variable in Jinja2, it raises an error.
app.jinja_env.undefined = StrictUndefined
################################################################################
# HOMEPAGE ROUTES
################################################################################
@app.route('/')
def index():
"""Homepage."""
return render_template('index.html')
@app.route('/words')
def retrieve_words():
"""Retrieves all available words in the db for autocomplete functionality."""
words = Term.get_all()
return jsonify({'words': words})
################################################################################
# ROUTE FOR D3 CREATION
################################################################################
@app.route('/d3topic.json')
def generate_topic_d3():
"""Returns JSON with a topic cluster as the root node."""
# TO DO Adding cluster ID validation and then extra tests to tests.py
cluster_id = request.args.get("cluster")
words = TermCluster.get_words_in_cluster(cluster_id)
root_dict = {'name': '', 'children': []}
for word in words:
root_dict['children'].append(
{'name': '', 'children': [{'name': word, 'size': 40000}]})
return jsonify(root_dict)
@app.route('/d3word.json')
def generate_word_d3():
""" Returns JSON with a word as the root node."""
# TO DO Adding word validation and then extra tests to tests.py
word = request.args.get("word")
clusters = TermCluster.get_top_clusters(word, n=25)
root_dict = {'name': '', 'children': []}
for cluster in clusters:
root_dict['children'].append(
{'name': cluster, 'children': [{'name': word, 'size': 40000}]})
return jsonify(root_dict)
@app.route('/d3.json')
def generate_d3(radius=3):
""" Returns JSON with xyz at the root node.
Test with parameters: 40, -45, -25 (Fusiform face area)
"""
clicked_on = request.args.get("options")
if clicked_on == 'location':
x_coord = float(request.args.get("xcoord"))
y_coord = float(request.args.get("ycoord"))
z_coord = float(request.args.get("zcoord"))
pmids = Activation.get_pmids_from_xyz(x_coord, y_coord, z_coord, radius)
scale = 70000
# Get [(wd, freq), ...] and [wd1, wd2] for most frequent words
elif clicked_on == 'study':
pmid = request.args.get('pmid')
study = Study.get_study_by_pmid(pmid)
pmids = study.get_cluster_mates()
scale = 30000
terms_for_dict, words = StudyTerm.get_terms_by_pmid(pmids)
# Optional: transform the terms
# Get the top clusters
top_clusters = TermCluster.get_top_clusters(words)
# Get the cluster-word associations
associations = TermCluster.get_word_cluster_pairs(top_clusters, words)
# Make the root node:
root_dict = {'name': '', 'children': []}
# Build the terminal nodes (leaves) first using (wd, freq) tuples
# Output: {word: {'name': word, 'size': freq}, word2: ... }
leaves = {}
for (word, freq) in terms_for_dict:
if word not in leaves:
leaves[word] = {'name': word, 'size': freq * scale}
else:
leaves[word]['size'] += freq * scale
# Embed the leaves in the clusters:
# Output: {cluster_id: {'name': ID, 'children': [...]}, ... }
clusters = {}
for (cluster_id, word) in associations:
if cluster_id not in clusters:
clusters[cluster_id] = {'name': cluster_id, 'children': [leaves[word]]}
else:
clusters[cluster_id]['children'].append(leaves[word])
# Put the clusters in the root dictionary
# Output: {'name': root, children: [{'name': id, 'children': []}, ...]
for cluster in top_clusters:
root_dict['children'].append(clusters[cluster])
return jsonify(root_dict)
################################################################################
# ROUTE FOR GENERATING CITATIONS
################################################################################
@app.route('/citations.json')
def generate_citations(radius=3):
"""Returns a list of text citations associated with some location, word
or topic (cluster)."""
clicked_on = request.args.get("options")
if clicked_on == 'location':
x_coord = float(request.args.get('xcoord'))
y_coord = float(request.args.get('ycoord'))
z_coord = float(request.args.get('zcoord'))
pmids = Activation.get_pmids_from_xyz(x_coord, y_coord, z_coord, radius)
elif clicked_on == 'word':
word = request.args.get('word')
# Get the pmids for a word
pmids = StudyTerm.get_pmid_by_term(word)
elif clicked_on == 'cluster':
cluster = request.args.get('cluster')
# Get the words for a cluster
# Then get the top studies for the words
words = TermCluster.get_words_in_cluster(cluster)
pmids = StudyTerm.get_pmid_by_term(words)
elif clicked_on == 'study':
pmid = request.args.get('pmid')
study = Study.get_study_by_pmid(pmid)
# Look for cluster-mate studies
pmids = study.get_cluster_mates()
citations = Study.get_references(pmids)
return jsonify(citations)
################################################################################
# ROUTES FOR GENERATING ACTIVATION PATTERNS IN BRAINBROWSER
################################################################################
# @app.route('/locations.json')
# def generate_locations():
# """Returns a list of locations [(x, y, z), (x, y, z) ...]
# associated with some word.
# NO LONGER IN USE"""
# word = request.args.get("word")
# loc_ids = {word: Location.get_xyzs_from_word(word)}
# return jsonify(loc_ids)
@app.route('/intensity')
def generate_intensity():
"""Generates an intensity data file related to some user action.
Clear: clear the old intensity mapping
Cluster: intensity mapping associated with a topic cluster
Word: intensity mapping associated with a particular word
Study: intensity mapping associated with a study cluster"""
clicked_on = request.args.get("options")
if clicked_on == 'clear':
intensities_by_location = {}
elif clicked_on == 'cluster' or clicked_on == 'word':
if clicked_on == 'cluster':
cluster = request.args.get('cluster')
word = TermCluster.get_words_in_cluster(cluster)
else:
word = request.args.get('word')
studies = StudyTerm.get_by_word(word)
# Create a dictionary of {pmid: frequency} values
frequencies_by_pmid, max_intensity = organize_frequencies_by_study(studies)
pmids = frequencies_by_pmid.keys()
# Get the activations for the keys of the dictionary
activations = Activation.get_activations_from_studies(pmids)
# Assemble the final dictionary of {location:intensity} values, scaling
# each value as we go
intensities_by_location = scale_frequencies_by_loc(
activations, max_intensity, frequencies_by_pmid)
elif clicked_on == 'study':
pmid = request.args.get('pmid')
study = Study.get_study_by_pmid(pmid)
# Look for cluster-mate studies
cluster_mates = study.get_cluster_mates()
# Get (location, study count) tuples from db
activations = Activation.get_location_count_from_studies(cluster_mates)
# Scale study counts in preparation for intensity mapping
intensities_by_location = scale_study_counts(activations)
print "Found intensities: ", intensities_by_location
# Assemble the intensity map
intensity_vals = generate_intensity_map(intensities_by_location)
return intensity_vals
@app.route('/intensitytest')
def generate_example_intensity():
"""Returns the sample intensity data provided by Brainbrowser.
Used for testing intensity mapping."""
intensity_file = open('static/models/cortical-thickness.txt')
intensity_data = ''.join(intensity_file.readlines())
intensity_file.close()
return intensity_data
@app.route('/colors')
def generate_color_map():
"""Retrieves a color map for Brainbrowser."""
color_map_file = open('static/models/spectral.txt')
color_data = ''.join(color_map_file.readlines())
color_map_file.close()
return color_data
################################################################################
# Helper functions
################################################################################
def organize_frequencies_by_study(studies):
"""Returns a dictionary of {PubMed ID : word frequency} values, given
some raw data from StudyTerm table.
Used as an intermediate lookup when building final intensity map, in lieu of
performing a complex join query."""
frequencies_by_pmid = {}
# Add the {study : frequency} values to dictionary, summing by PubMed ID
for study in studies:
if study.pmid not in frequencies_by_pmid:
frequencies_by_pmid[study.pmid] = study.frequency
else:
frequencies_by_pmid[study.pmid] += study.frequency
# Get the maximal frequency for scaling
max_intensity = max(frequencies_by_pmid.values())
return frequencies_by_pmid, max_intensity
def scale_frequencies_by_loc(activations, max_intensity, frequencies_by_pmid):
"""Returns a dictionary of {location_id : scaled intensity} values.
Intensity values are derived from word frequency metrics and scaled using
the maximal values."""
intensities_by_location = {}
for activation in activations:
intensity_to_add = frequencies_by_pmid[activation.pmid]
if activation.location_id not in intensities_by_location:
intensities_by_location[activation.location_id] = (
intensity_to_add / max_intensity)
else:
intensities_by_location[activation.location_id] += (
intensity_to_add / max_intensity)
return intensities_by_location
def generate_intensity_map(intensities_by_location):
"""Returns a string with intensity values for each of 81925 surface
locations."""
intensity_vals = ""
for i in range(0, 81925):
if i not in intensities_by_location:
intensity_vals = intensity_vals + "0\n"
else:
intensity_vals = intensity_vals + str(intensities_by_location[i]) + "\n"
return intensity_vals
def scale_study_counts(activations):
"""Returns a dictionary of {location_id : scaled intensity} values.
Intensity values are derived from study counts and scaled using the
maximal counts."""
max_count = max(activations, key=itemgetter(1))[1]
intensities_by_location = {}
for activation in activations:
location_id, count = activation
if location_id not in intensities_by_location:
intensities_by_location[location_id] = float(count)/float(max_count)
else:
intensities_by_location[location_id] += float(count)/float(max_count)
return intensities_by_location
if __name__ == "__main__":
# We have to set debug=True here, since it has to be True at the point
# that we invoke the DebugToolbarExtension
app.debug = True
connect_to_db(app)
# Use the DebugToolbar
# DebugToolbarExtension(app)
app.run()