forked from daureg/illalla
/
more_query.py
472 lines (416 loc) · 16.6 KB
/
more_query.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
#! /usr/bin/python2
# vim: set fileencoding=utf-8
from multiprocessing import Pool, cpu_count
from wordplot import tag_cloud
import codecs
from persistent import save_var, load_var
from bson.son import SON
import matplotlib.cm
import scipy.io as sio
from outplot import outplot
from timeit import default_timer as clock
import json
import datetime
import pymongo
from shapely.geometry import Point, shape, mapping
from math import floor
import fiona
import numpy as np
from scipy.spatial.distance import pdist
from operator import itemgetter
from utils import to_css_hex
import cities
CITY = cities.HEL
CITY_BBOX = (CITY[:2], CITY[2:])
try:
from collections import Counter
except ImportError:
from Counter import Counter
import logging
logging.basicConfig(filename='more_query.log',
level=logging.INFO,
format='%(asctime)s [%(levelname)s]: %(message)s')
import prettytable
CSS = '#{} {{fill: {}; opacity: 0.5; stroke: {}; stroke-width: 0.25px;}}'
KARTO_CONFIG = {'bounds': {'data': [-122.4, 37.768, -122.38, 37.778],
'mode': 'bbox'},
'layers': {},
'proj': {'id': 'laea', 'lat0': 37.78, 'lon0': -122.45}}
DB = 0
SF_BBOX = [37.7123, -122.531, 37.84, -122.35]
FIRST_TIME = datetime.datetime(2008, 1, 1)
LAST_TIME = datetime.datetime.now()
PERIOD = [1, 7, 30, 91, 365]
PERIOD_NAME = ['day', 'week', 'month', 'quarter', 'year']
def total_seconds(td):
if hasattr(td, 'total_seconds'):
# python 2.7
return td.total_seconds()
# I don't care about microsecond
return td.seconds + td.days * 24 * 3600
def bbox_to_polygon(bbox, latitude_first=True):
"""Return a 5 points GeoJSON polygon based on the bottom left and upper
right coordinates of bbox [lat_bl, long_bl, lat_ur, long_ur]
(5 because the polygon needs to be closed, see:
https://groups.google.com/d/msg/mongodb-user/OPouYFHS_zU/cS21L0XAMkkJ )
Or in other words ;(
http://toblerity.org/shapely/manual.html#shapely.geometry.box
>>> bbox_to_polygon([37, -122, 35, -120])
{'type': 'Polygon', 'coordinates': [[[-122, 37], [-120, 37], [-120, 35], [-122, 35], [-122, 37]]]}
"""
assert(len(bbox) == 4)
if latitude_first:
lat_bl, long_bl, lat_ur, long_ur = bbox
else:
long_bl, lat_bl, long_ur, lat_ur = bbox
r = {}
r['type'] = 'Polygon'
r['coordinates'] = [[[long_bl, lat_bl], [long_ur, lat_bl],
[long_ur, lat_ur], [long_bl, lat_ur],
[long_bl, lat_bl]]]
return r
def inside_bbox(bbox):
return {'$geoWithin': {'$geometry': bbox_to_polygon(bbox)}}
def season_query(start_year, end_year, season):
"""Return a query operator that selects all date between start_year and
end_year and in the months corresponding to season"""
first_month = {'winter': 12, 'spring': 3, 'summer': 6, 'fall': 9}[season]
last_month = (first_month + 3) % 12
req = {'$or': []}
for year in range(start_year, end_year+1):
start = datetime.datetime(year, first_month, 15)
if season == 'winter':
end = datetime.datetime(year+1, last_month, 15)
else:
end = datetime.datetime(year, last_month, 15)
req['$or'].append({'taken': {'$gte': start, '$lte': end}})
return req
def get_photo_url(p, size='z', webpage=False):
web_url = u"http://www.flickr.com/photos/{}/{}".format(p['uid'], p['_id'])
BASE = u"http://farm{}.staticflickr.com/{}/{}_{}_{}.jpg"
url = BASE.format(p['farm'], p['server'], p['_id'], p['secret'], size)
if webpage:
return url, web_url
return url
def tag_location(collection, tag, bbox, start, end, extra_info=None,
tourist_status=False, uploaded=False, user=None):
"""Return a list of [long, lat] for each photo taken between start and end
(or uploaded) in bbox which has tag. extra_info is a list of other fields
to include after. It can also adds tourist status as [long, lat,
is_tourist]"""
query = {}
field = {'loc': 1, '_id': 0}
if extra_info is not None:
field.update(zip(extra_info, len(extra_info)*[1, ]))
else:
extra_info = []
if tourist_status:
user_stat = get_user_status()
field['uid'] = 1
# if bbox is None:
# query['hint'] = 'sf'
# else:
# query['loc'] = inside_bbox(bbox)
query['hint'] = 'helsinki'
if tag is not None:
query['ntags'] = tag
if user is not None:
query['uid'] = user
time_field = 'upload' if uploaded else 'taken'
query[time_field] = {'$gte': start, '$lte': end}
# query.update(season_query(2008, 2013, 'winter'))
cursor = collection.find(query, field)
def format_photo(p):
loc = p['loc']['coordinates']
tourist = [user_stat[p['uid']]] if tourist_status else []
extra = [p[attr] for attr in extra_info]
return loc + tourist + extra
return [format_photo(p) for p in cursor]
def tag_over_time(collection, tag, bbox, start, interval, user_status=None):
now = datetime.datetime.now()
if interval is None:
interval = now - start
num_period = 1
else:
num_period = total_seconds(now - start)
num_period = int(num_period/total_seconds(interval))
schema = {'geometry': 'Point', 'properties': {}}
# schema = {'geometry': 'Point', 'properties': {'tourist': 'int'}}
for i in range(num_period):
places = map(lambda p: {'geometry': mapping(Point(p[0], p[1])),
'properties': {}},
# 'properties': {'tourist': int(p[2])}},
tag_location(collection, tag, bbox,
start + i * interval,
start + (i+1) * interval,
tourist_status=True))
print('{} - {}: {}'.format(start + i * interval,
start + (i+1) * interval, len(places)))
name = u'{}_{}.shp'.format(tag, i+1)
with fiona.collection(name, "w", "ESRI Shapefile", schema) as f:
f.writerecords(places)
def k_split_bbox(bbox, k=2, offset=0):
long_step = (bbox[3] - bbox[1])/k
lat_step = (bbox[2] - bbox[0])/k
assert(offset <= min(long_step, lat_step))
hoffset = offset
voffset = 0
x = bbox[1]
y = bbox[0]
region = []
while y + voffset < bbox[2] - 0.5*lat_step:
while x + hoffset < bbox[3] - 0.5*long_step:
region.append([x + hoffset, y + voffset,
x + hoffset + long_step, y + voffset + lat_step])
x += long_step
y += lat_step
x = bbox[1]
def coord2region_index(coords):
longitude, latitude = coords
# TODO handle correctly edge case
x = longitude - hoffset - bbox[1] - 1e-8
y = latitude - voffset - bbox[0] - 1e-8
if x < 0 or y < 0:
return -1
r = k*int(floor(y/lat_step)) + int(floor(x/long_step))
if r > k*k - 1:
return - 1
return r
def region_index2bbox(r):
i = r/k
j = r%k
x = bbox[1] + j * long_step
y = bbox[0] + i * lat_step
return [x + hoffset, y + voffset,
x + hoffset + long_step, y + voffset + lat_step]
return region, coord2region_index, region_index2bbox
def compute_entropy(count):
c = np.array([i for i in count if i > 0])
N = np.sum(c)
return np.log(N) - np.sum(c*np.log(c))/N
def compute_KL(count, k):
""" Return D(tag || all_photos) given count of tag (including the 0
region) on a grid of size k×k."""
from math import log
Nt = float(sum(count[1:]))
d = sio.loadmat('mfreq/freq_{}__background.mat'.format(k))
N = np.sum(d['c'])
ratio = log(N/Nt)
KL = float(np.sum([(p/Nt)*(log(float(p)/q)+ratio)
for p, q in zip(count[1:], d['c'].flat) if p > 0 and q > 0]))
return KL
def compute_frequency(collection, tag, bbox, start, end, k=200,
nb_inter=19, exclude_zero=True, plot=True):
"""split bbox in k^2 rectangles and compute the frequency of tag in each of
them. Return a list of list of Polygon, grouped by similar frequency
into nb_inter bucket (potentially omitting the zero one for clarity)."""
freq_name = u'mfreq/freq_{}_{}.mat'.format(k, '_background' if tag is None else tag)
count = (k*k+1)*[0, ]
try:
count[1:] = sio.loadmat(freq_name)['c']
KL_div = 0 if tag is None else compute_KL(count, k)
except IOError:
collection = DB.photos if collection is None else collection
# coords = tag_location(collection, tag, bbox, start, end,
# tourist_status=True)
coords = tag_location(collection, tag, bbox, start, end)
# r, f, _ = k_split_bbox(bbox, k)
r, f = RECTANGLES, RECT_TO_INDEX
# count[0] is for potential points that do not fall in any region (it
# must only happens because of rounding inprecision)
count = (len(r)+1)*[0, ]
# count = (len(r)+1)*[(0, 0), ]
for loc in coords:
# rloc = loc[0:2]
# prev = count[f(rloc)+1]
# count[f(rloc)+1] = (prev[0] + int(loc[2]), prev[1]+1)
count[f(loc)+1] += 1
# save_var('alltourist', count)
# count = load_var('alltourist')
# N = len(coords)
if tag is None:
tag = '_background'
KL_div = 0
else:
KL_div = compute_KL(count, k)
sio.savemat(freq_name, {'c': np.array(count[1:])}, do_compression=True)
entropy = compute_entropy(count[1:])
print(u'Entropy and KL of {}: {:.4f}, {:.4f}'.format(tag, entropy, KL_div))
if not plot:
return entropy, KL_div
# freq = np.array(count[1:])/(1.0*N)
log_freq = np.maximum(0, np.log(count[1:]))
# log_freq = [0 if p[1] == 0 else (1.0*p[0]/p[1] - 0.5) for p in count[1:]]
# entropy = 0
# sio.savemat('tourist_ratio', {'c': np.array(log_freq)})
maxv = np.max(log_freq)
minv = np.min(log_freq)
interval_size = (maxv - minv)/nb_inter
bucket = []
for i in range(nb_inter):
bucket.append([])
for i, v in enumerate(log_freq):
if not (exclude_zero and v < 1e-8):
poly = {'geometry': mapping(shape(bbox_to_polygon(r[i], False))),
'properties': {}}
index = (min(nb_inter - 1, int(floor(v / interval_size))))
bucket[index].append(poly)
plot_polygons(bucket, tag, nb_inter, minv, maxv)
return entropy, KL_div
def plot_polygons(bucket, tag, nb_inter, minv, maxv):
schema = {'geometry': 'Polygon', 'properties': {}}
colormap_ = matplotlib.cm.ScalarMappable(cmap='YlOrBr')
vrange = np.linspace(minv, maxv, nb_inter)
colormap = [to_css_hex(c) for c in colormap_.to_rgba(vrange)]
style = []
for i in range(nb_inter):
if len(bucket[i]) > 0:
name = u'{}_freq_{:03}'.format(tag, i+1)
KARTO_CONFIG['layers'][name] = {'src': name+'.shp'}
style.append(CSS.format(name, colormap[i], colormap[i]))
with fiona.collection(name+'.shp', "w",
"ESRI Shapefile", schema) as f:
f.writerecords(bucket[i])
with open('photos.json', 'w') as f:
json.dump(KARTO_CONFIG, f)
with open('photos.css', 'w') as f:
f.write('\n'.join(style))
def simple_metrics(collection, tag, bbox, start, end):
places = tag_location(collection, tag, bbox, start, end)
p = np.array(zip(map(itemgetter(1), places), map(itemgetter(0), places)))
grav = np.mean(p, 0)
tmp = p - grav
dst = np.sum(tmp**2, 1)
sio.savemat(u'grav_' + tag, {'grav': dst})
mu_grav = np.mean(dst)
sigma_grav = np.std(dst)
H_grav = compute_entropy(dst)
H_pair = -1
try:
if len(dst) < 22000:
dst = pdist(p)
h, b = np.histogram(dst, 200)
start = clock()
H_pair = compute_entropy(dst)
print(u'H_pair_{}: {}s'.format(tag, clock() - start))
# outplot('pairwise_' + tag, ['', ''], h, b[1:])
except MemoryError:
logging.warn(u'{} is too big for pdist'.format(tag))
return [mu_grav, sigma_grav, H_grav, H_pair]
def fixed_tag_metrics(t):
return simple_metrics(DB.photos, t, None, FIRST_TIME, LAST_TIME) + [t]
def top_metrics(tags):
# pool = Pool(4)
res = map(fixed_tag_metrics, tags)
# pool.close()
outplot('e_grav.dat', ['H', 'tags'],
[v[2] for v in res], [v[4] for v in res])
outplot('e_pair.dat', ['H', 'tags'],
[v[3] for v in res], [v[4] for v in res])
mus = np.array([v[0] for v in res])
sigmas = np.array([v[1] for v in res])
sio.savemat('mu_sigma', {'A': np.vstack([mus, sigmas]).T})
tag_cloud([v[4] for v in res], zip(mus, sigmas), True)
def get_user_status(with_count=False):
name = 'user_status' + ('_full' if with_count else '')
fields = {'tourist': 1}
if with_count:
fields.update({'count': 1})
try:
d = load_var(name)
except IOError:
users = list(DB.users.find(fields=fields))
if with_count:
d = dict([(u['_id'], (u['count'], u['tourist'])) for u in users])
else:
d = dict([(u['_id'], u['tourist']) for u in users])
save_var(name, d)
return d
def classify_users(db):
users_collection = db['users']
users_from_photos = db['photos'].aggregate([
{"$match": {"hint": "sf"}},
{'$project': {'_id': 0, 'upload': 1, 'user': '$uid'}},
{'$group': {'_id': '$user',
'first': {'$min': '$upload'},
'last': {'$max': '$upload'},
"count": {"$sum": 1}}}
])['result']
month = total_seconds(datetime.timedelta(days=365.24/12))
users = []
autochthons = 0
for u in users_from_photos:
timespan = total_seconds(u['last'] - u['first'])
u['tourist'] = timespan < month
if not u['tourist']:
autochthons += 1
users.append(u)
print(100*autochthons/len(users))
try:
users_collection.insert(users, continue_on_error=True)
except pymongo.errors.DuplicateKeyError:
print('duplicate')
pass
def get_top_tags(n=100, filename='sftags.dat'):
with codecs.open(filename, 'r', 'utf8') as f:
tags = [unicode(i.strip().split()[0]) for i in f.readlines()[1:n+1]]
return tags
def users_and_tag(tag):
r = DB.photos.aggregate([
{"$match": {"hint": "sf", "ntags": tag}},
{"$project": {"uid": 1}},
{"$group": {"_id": "$uid", "count": {"$sum": 1}}},
{"$sort": SON([("count", -1), ("_id", -1)])}
])
save_var('u14', r['result'])
def sf_entropy(t):
return compute_frequency(DB.photos, t, SF_BBOX,
FIRST_TIME, LAST_TIME,
GRID_SIZE, 0, plot=False)
def time_entropy(tag):
places = tag_location(DB.photos, tag, None, FIRST_TIME, LAST_TIME,
extra_info=['taken'])
res = []
for days in PERIOD:
time_step = days*24*3600
times = [int(total_seconds(p[2] - FIRST_TIME)/time_step)
for p in places]
res.append(float(compute_entropy(Counter(times))))
return [tag] + res
GRID_SIZE = 200
RECTANGLES, RECT_TO_INDEX, INDEX_TO_RECT = k_split_bbox(SF_BBOX, GRID_SIZE)
if __name__ == '__main__':
# from random import shuffle
client = pymongo.MongoClient('localhost', 27017)
DB = client['world']
photos = DB['photos']
KARTO_CONFIG['bounds']['data'] = [SF_BBOX[1], SF_BBOX[0],
SF_BBOX[3], SF_BBOX[2]]
start = clock()
# nb_inter = 19
# e, KL = sf_entropy(None)
# tags = get_top_tags(500, 'nsf_tag.dat')
# tmp = load_var('supported')
# tags = [v[0] for v in tmp]
# shuffle(tags)
# tags = [None] + tags
# sf_entropy(None)
# p = Pool(4)
# res = p.map(sf_entropy, tags)
# p.close()
# outplot('nentropies_{}.dat'.format(GRID_SIZE), ['H', 'tag'], [r[0] for r in res], tags)
# outplot('nKentropies_{}.dat'.format(GRID_SIZE), ['D', 'tag'], [r[1] for r in res], tags)
# top_metrics(tags)
# te = [time_entropy(tag) for tag in tags]
# t = prettytable.PrettyTable(['tag'] + PERIOD_NAME, sortby='day')
# t.align['tag'] = 'l'
# t.padding_width = 0
# for row in te:
# t.add_row(row)
# with codecs.open('time_entropy.txt', 'w', 'utf8') as f:
# f.write(t.get_string(border=False, left_padding_width=0,
# right_padding_width=2))
save_var('helsinki', tag_location(photos, None, CITY_BBOX, FIRST_TIME,
LAST_TIME, extra_info=['taken']))
t = 1000*(clock() - start)
print('done in {:.3f}ms'.format(t))