-
Notifications
You must be signed in to change notification settings - Fork 3
/
map.py
executable file
·287 lines (262 loc) · 10.7 KB
/
map.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
# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import State, Event, Input, Output
import plotly
import plotly.graph_objs as go
import pandas as pd
import functools
from common import app
from common import graphconfig
import bwypy
import json
from tools import errorfig, logging_config
import logging
from logging.config import dictConfig
dictConfig(logging_config)
logger = logging.getLogger()
app.config.supress_callback_exceptions=True
bwypy.set_options(database='Bookworm2016', endpoint='https://bookworm.htrc.illinois.edu/cgi-bin/dbbindings.py')
bw_map = bwypy.BWQuery(verify_fields=False)
bw_map.counttype = ['WordsPerMillion']
bw_map.json['words_collation'] = 'case_insensitive'
bw_html = bwypy.BWQuery(verify_fields=False)
bw_html.json['method'] = 'search_results'
bw_html.json['words_collation'] = 'case_insensitive'
keys = ['word', 'compare_word', 'type', 'scope']
defaults = ['color', 'colour', 'scattergeo', 'country']
# Future support for pre-load param insertion
params = None
if params is not None:
q = dict(zip(keys,params))
else:
q = dict(zip(keys,defaults))
header = '''
# Bookworm Map
See where a word occurs in the 15 million volume [HathiTrust](https://www.hathitrust.org) collection.
Locations correspond to the places that volumes were published in.
'''
country_codes = pd.read_csv('data/country_codes.csv')
state_codes = pd.read_csv('data/state_codes_us.csv')
@functools.lru_cache(maxsize=32)
def get_word_by_us_state(word):
words = [token.strip() for token in word.split(',')]
bw_map.search_limits = { 'word':word.split(','), 'publication_country': 'USA' }
bw_map.groups = ['*publication_country', 'publication_state']
results = bw_map.run()
df = results.frame(index=False, drop_unknowns=True)
data = pd.merge(df, state_codes)
return data
@functools.lru_cache(maxsize=32)
def get_word_by_country(word):
words = [token.strip() for token in word.split(',')]
bw_map.search_limits = { 'word':words }
bw_map.groups = ['publication_country']
results = bw_map.run()
df = results.frame(index=False, drop_unknowns=True)
data = pd.merge(df, country_codes)
return data
def build_map(word, compare_word=None, type='scattergeo', scope='country'):
import pandas as pd
import numpy as np
transform = lambda x: np.log(1+x/maxval)
if scope == 'country':
data = get_word_by_country(word).copy()
if compare_word:
data2 = get_word_by_country(compare_word).copy()
field = 'publication_country'
scope = 'world'
projection = 'Mercator'
locationmode = 'ISO-3'
elif scope == 'state':
data = get_word_by_us_state(word).copy()
if compare_word:
data2 = get_word_by_us_state(compare_word).copy()
field = 'publication_state'
scope = 'usa'
projection = 'albers usa'
locationmode = 'USA-states'
if compare_word and (compare_word.strip() != ''):
sizemod = 45
data = pd.merge(data,data2, on=[field, 'code'])
if type == 'scattergeo':
data = data[(data['WordsPerMillion_x'] != 0) & (data['WordsPerMillion_y'] != 0)]
maxval = data[['WordsPerMillion_x', 'WordsPerMillion_y']].max().max()
logcounts = sizemod*(data['WordsPerMillion_x'].apply(transform) - data['WordsPerMillion_y'].apply(transform))
text = ( data[field]
+ "<br> Words Per Million<br> '{}': ".format(word)
+ data['WordsPerMillion_x'].round(1).astype(str)
+ "<br> '{}': ".format(compare_word)
+ data['WordsPerMillion_y'].round(1).astype(str)
)
title = "\'%s\' vs. '%s' in the HathiTrust" % (word, compare_word)
else:
sizemod = 40
if type == 'scattergeo':
data = data[(data['WordsPerMillion'] != 0)]
counts = data['WordsPerMillion'].astype(int)
maxval = counts.max()
logcounts = sizemod*counts.apply(transform)
text = data[field] + '<br> Words Per Million:' + data['WordsPerMillion'].round(2).astype('str')
title = "\'%s\' in the HathiTrust" % word
if compare_word:
counts2 = data2['WordsPerMillion'].astype(int)
plotdata = [ dict(
type=type,
hoverinfo = "location+text",
locationmode = locationmode,
locations = data['code'],
text = text,
marker = dict(
line = dict(width=0.5, color='rgb(40,40,40)'),
)
)]
if type == 'choropleth':
plotdata[0]['z'] = logcounts
#plotdata[0]['colorscale'] = scl,
plotdata[0]['autocolorscale'] = False
plotdata[0]['showscale'] = False
plotdata[0]['zauto'] = False
plotdata[0]['zmax'] = logcounts.abs().max()
plotdata[0]['zmin'] = -logcounts.abs().max()
elif type == 'scattergeo':
plotdata[0]['marker']['size'] = logcounts.abs()
plotdata[0]['marker']['color'] = logcounts
plotdata[0]['marker']['cauto'] = False
plotdata[0]['marker']['cmax'] = logcounts.abs().max()
plotdata[0]['marker']['cmin'] = -logcounts.abs().max()
layout = dict(
title = title,
margin=go.Margin(
l=10,r=10, b=10, t=50, pad=4
),
geo = dict(
scope=scope,
projection=dict( type=projection ),
showframe = False,
showcoastlines = True,
showland = True,
landcolor = "rgb(229, 229, 229)",
countrycolor = "rgb(255, 255, 255)" ,
coastlinecolor = "rgb(255, 255, 255)",
showlakes = True,
lakecolor = 'rgb(255, 255, 255)')
)
return (plotdata, layout)
app.layout = html.Div([
html.Div([
html.Div([
dcc.Markdown(header),
html.Div(
[html.Label("Search For a Term"),
html.Br(),
dcc.Input(id='search-term', type='text', value=q['word'],
style={'color': 'darkorange','font-weight':'bold'}),
dcc.Input(id='map-search-term-hidden', type='hidden',
value=json.dumps(dict(word=q['word'], compare=q['compare_word']))),
html.Br(),
html.Small("Combine search words with a comma. Only single word queries supported."),
],
className="form-group"
),
html.Div(
[html.Label("Optional: Compare to another term"),
dcc.Input(id='compare-term', type='text', value=q['compare_word'],
style={'color': 'navy','font-weight':'bold'})],
className="form-group"
),
html.Button('Update Words', id='word_search_button', className='btn btn-primary'),
html.Div(
[html.Label("Type of Map"),
html.Div(dcc.RadioItems(
id='map_type',
options=[
{'label': u'Scatter', 'value': 'scattergeo'},
{'label': u'Color', 'value': 'choropleth'}
],
value=q['type']
), className='radio')],
className="form-group"
),
html.Div(
[html.Label("Map Scope"),
html.Div(dcc.RadioItems(
id='map_scope',
options=[
{'label': u'World', 'value': 'country'},
{'label': u'USA', 'value': 'state'}
],
value=q['scope']
), className='radio')],
className="form-group"
)
],
className='col-md-3'),
html.Div(
[dcc.Graph(id='main-map-graph', animate=False, config=graphconfig)],
className='col-md-9')
], className='row'),
html.Div([
html.Div([
dcc.Markdown("""**Example Books**
Choose a place on the map to see matching books from there. All search and compare words included in matches.
"""),
html.Div(id='select-data'),
], className='col-md-offset-4 col-md-8')
], className='row')
], className='container-fluid')
@app.callback(
Output('select-data', 'children'),
[Input('main-map-graph', 'clickData')],
state=[State('search-term', 'value'), State('compare-term', 'value'),
State('map_scope', 'value')])
def display_click_data(clickData, word, compare_word, mapscope):
import json
import re
try:
limit = clickData['points'][0]['text'].split('<br>')[0]
except:
return html.Ul(html.Li(html.Em("Nothing selected")))
if compare_word and compare_word.strip() != '':
word = word + "," + compare_word
q = word.split(",")
bw_html.search_limits = { 'publication_' + mapscope : [limit], 'word': q }
results = bw_html.run()
# Format results
links = []
for result in results.json():
try:
groups = re.search("href=(.*)><em>(.*?)</em> \((.*?)\)", result).groups()
link = html.Li(html.A(href=groups[0], target='_blank', children=["%s (%s)" % (groups[1], groups[2])]))
links.append(link)
except:
raise
return html.Ul(links)
@app.callback(
Output('map-search-term-hidden', 'value'),
events=[Event('word_search_button', 'click')],
state=[State('search-term', 'value'), State('compare-term', 'value')]
)
def update_hidden_search_term(word, compare):
return json.dumps(dict(word=word, compare=compare))
@app.callback(
Output('main-map-graph', 'figure'),
[Input('map-search-term-hidden', 'value'),
Input('map_type', 'value'), Input('map_scope', 'value')]
)
def map_search(word_query, maptype, mapscope):
try:
word_query=json.loads(word_query)
word = word_query['word']
compare_word = word_query['compare']
plotdata, layout = build_map(word, compare_word, maptype, mapscope)
fig = dict( data=plotdata, layout=layout )
except:
logging.exception(json.dumps(dict(page='map', word_query=word_query,
maptype=maptype, mapscope=mapscope)))
fig = errorfig()
return fig
if __name__ == '__main__':
app.config.supress_callback_exceptions = True
app.run_server(debug=True, port=8080, threaded=True, host='0.0.0.0')