-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
354 lines (299 loc) · 12.6 KB
/
app.py
File metadata and controls
354 lines (299 loc) · 12.6 KB
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
from flask import Flask, redirect, render_template, request, url_for, abort
from flask import jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_compress import Compress
import decimal
import pandas as pd
import json
import geojson
import datetime
import os
import math
import timeit
########## CONFIG ###########
app = Flask(__name__)
# enable compression of response objects
Compress(app)
# WINDOWS setup
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:root@localhost:5432/ChinaVis'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 # change this before production!
db = SQLAlchemy(app)
# ROUTE_DAYSBACK = 730
# BORO_DAYSBACK = 30
########## SQLALCHEMY MODELS ###########
class GpsMetric(db.Model):
__tablename__ = 'gps_metrics'
# id, time, longitude, latitude
order_id = db.Column(db.String(40), primary_key=True)
time = db.Column(db.Integer, primary_key=True)
longitude = db.Column(db.DECIMAL(15, 12))
latitude = db.Column(db.DECIMAL(15, 13))
def __init__(self, name, color):
self.order_id = order_id
self.time = time
self.longitude = longitude
self.latitude = latitude
# def __repr__(self):
# res = {"order_id": "", "time": 0, "longitude": 0, "latitude": 0}
# res["order_id"] = self.order_id
# res["time"] = self.time
# res["longitude"] = self.longitude
# res["latitude"] = self.latitude
# return res
# return 'Gps metric set: {}, {}:{}, {}'.format(
# self.order_id,
# self.time,
# self.longitude,
# self.latitude)
def to_json(self):
model_dict = dict(self.__dict__)
del model_dict['_sa_instance_state']
return model_dict
class OrderMetric(db.Model):
__tablename__ = 'order_metrics'
# id, time, longitude, latitude
order_id = db.Column(db.String(40), primary_key=True)
s_time = db.Column(db.Integer, primary_key=True)
e_time = db.Column(db.Integer, primary_key=True)
s_longitude = db.Column(db.Float(precision=50, scale=10))
s_latitude = db.Column(db.Float(precision=50, scale=10))
e_longitude = db.Column(db.Float(precision=50, scale=10))
e_latitude = db.Column(db.Float(precision=50, scale=10))
def __init__(self, name, color):
self.order_id = order_id
self.s_time = s_time
self.e_time = e_time
self.s_longitude = s_longitude
self.s_latitude = s_latitude
self.e_longitude = e_longitude
self.e_latitude = e_latitude
# def __repr__(self):
#
# return '<Order metric set: {}, {}:{}, {}>'.format(
# self.order_id,
# self.s_time,
# self.e_time,
# self.s_longitude,
# self.s_latitude,
# self.e_longitude,
# self.e_latitude)
def to_json(self):
model_dict = dict(self.__dict__)
del model_dict['_sa_instance_state']
return model_dict
########## UTILITY ###########
# subclass standard python dict, implementing __missing__ to generate intermediate keys on the fly
# class InterDict(dict):
# def __missing__(self, key):
# self[key] = InterDict()
# return self[key]
# def split_direc_stop(rds_index, col):
# route, direc, stop = rds_index.split('_')
# if col == 'direc':
# return int(direc)
# elif col == 'stop':
# return int(stop)
def clean_nan(val):
try:
if math.isnan(val):
return None
elif val == 'null':
return None
else:
return val
except:
return val
gps_metric_list = ['order_id', 'time', 'longitude', 'latitude']
order_metric_list = ['order_id', 's_time', 'e_time', 's_longitude', 's_latitude', 'e_longitude', 'e_latitude']
########## APP LOGIC ###########
def get_last_update():
print('server: getting last update')
# assumes that all metric tables are updated in synchro (so, just query one)
print(OrderMetric.query.order_by(OrderMetric.s_time.desc()).first().s_time)
print(GpsMetric.query.order_by(GpsMetric.time.desc()).first().time)
def get_data_by_hour_GPS():
start_time = GpsMetric.query.order_by(GpsMetric.time).first().time
end_time = GpsMetric.query.order_by(GpsMetric.time.desc()).first().time
print(start_time)
print(end_time)
time = start_time
count = 1
while time < end_time:
res = []
df = GpsMetric.query.filter(GpsMetric.time.between(time, time + 3600)).all()
for item in df:
res.append(item.to_json())
with open('data/{}.json'.format(count), 'w') as f:
json.dump(res, f)
time = time + 3600
count = count + 1
def get_data_by_hour_ORDER():
start_time = OrderMetric.query.order_by(OrderMetric.e_time).first().e_time
end_time = OrderMetric.query.order_by(OrderMetric.e_time.desc()).first().e_time
print(start_time)
print(end_time)
interval = 3600
time = start_time
count = 1
while time < end_time:
res = []
df = OrderMetric.query.filter(OrderMetric.e_time.between(time, time + 3600)).all()
for item in df:
res.append(item.to_json())
with open('data/ORDER_BY_HOUR_END/{}.json'.format(count), 'w') as f:
json.dump(res, f)
time = time + 3600
count = count + 1
def get_frequency_by_coordinate():
# s = GpsMetric.query.distinct(GpsMetric.longitude, GpsMetric.latitude).all()
# s = OrderMetric.query.distinct(OrderMetric.s_longitude, OrderMetric.s_latitude).all()
res = []
# print(s)
start_time = GpsMetric.query.order_by(GpsMetric.time).first().time
end_time = GpsMetric.query.order_by(GpsMetric.time.desc()).first().time
interval = 3600
time = start_time
count = 1
while time < end_time:
s = db.session.query(GpsMetric.latitude, GpsMetric.longitude, db.func.count().label("value")) \
.filter(GpsMetric.time.between(time, time + 3600)) \
.group_by(GpsMetric.longitude, GpsMetric.latitude).all()
res = []
for item in s:
dic_list = dict(zip(item.keys(), item))
temp = {'longitude': float(dic_list['longitude']), 'latitude': float(dic_list['latitude']),
'value': dic_list['value']}
res.append(temp)
with open('data/FREQUENCY_ORDER/top-10/frequency_{}.json'.format(count), 'w') as f:
json.dump(res, f)
time = time + 3600
count = count + 1
def frequency_order_by_hour():
# s = GpsMetric.query.distinct(GpsMetric.longitude, GpsMetric.latitude).all()
# s = OrderMetric.query.distinct(OrderMetric.s_longitude, OrderMetric.s_latitude).all()
res = []
# print(s)
start_time = GpsMetric.query.order_by(GpsMetric.time).first().time
end_time = GpsMetric.query.order_by(GpsMetric.time.desc()).first().time
time = start_time
count = 1
while time < end_time:
s = db.session.query(GpsMetric.latitude, GpsMetric.longitude, db.func.count().label("value")) \
.filter(GpsMetric.time.between(time, time + 3600)) \
.group_by(GpsMetric.longitude, GpsMetric.latitude).order_by(db.desc('value')).all()
cnt = 1
res = []
for item in s:
if cnt > 10:
break
dic_list = dict(zip(item.keys(), item))
_time = start_time
_count = 1
print("point{}".format(cnt))
while _time < end_time:
print("Hour{}".format(_count))
print("Time{}-{}".format(_time, _time + 3600))
k = GpsMetric.query \
.filter(GpsMetric.longitude == dic_list['longitude'] and GpsMetric.latitude == dic_list['latitude']) \
.filter(GpsMetric.time.between(_time, _time + 3600)).count()
print(k)
temp = {'longitude': float(dic_list['longitude']), 'latitude': float(dic_list['latitude']),
'location': 'Point{}'.format(cnt), 'hour': _count, 'value': k}
res.append(temp)
_time = _time + 3600
_count = _count + 1
cnt = cnt + 1
with open('data/frequency_10_{}.json'.format(count), 'w') as f:
json.dump(res, f)
print("Successfully load frequency_10_{}".format(count))
time = time + 3600
count = count + 1
def traffic_by_hour():
start_time = GpsMetric.query.order_by(GpsMetric.time).first().time
end_time = GpsMetric.query.order_by(GpsMetric.time.desc()).first().time
print(start_time)
print(end_time)
time = start_time
hour_count = 1
while time < end_time:
res = []
minute_count = 1
while minute_count < 4:
df = GpsMetric.query.filter(GpsMetric.time.between(time, time + 1200)).all()
for item in df:
dict_list = dict(zip(item.keys(), item))
temp = {'longitude': float(dict_list['longitude']), 'latitude': float(dict_list['latitude']),
'order_id': dict_list['order_id'], 'time': dict_list['time'], 'hour': hour_count, 'minute': minute_count}
res.append(temp)
time = time + 1200
minute_count = minute_count + 1
with open('data/{}.json'.format(hour_count), 'w') as f:
json.dump(res, f)
hour_count = hour_count + 1
def co_occurrence_matrix():
# s = GpsMetric.query.distinct(GpsMetric.longitude, GpsMetric.latitude).all()
# s = OrderMetric.query.distinct(OrderMetric.s_longitude, OrderMetric.s_latitude).all()
res = []
# print(s)
start_time = GpsMetric.query.order_by(GpsMetric.time).first().time
end_time = GpsMetric.query.order_by(GpsMetric.time.desc()).first().time
time = start_time
count = 1
set = {}
while time < end_time:
s = db.session.query(GpsMetric.latitude, GpsMetric.longitude, db.func.count().label("value")) \
.filter(GpsMetric.time.between(time, time + 3600)) \
.group_by(GpsMetric.longitude, GpsMetric.latitude).order_by(db.desc('value')).all()
cnt = 1
temp = []
res = []
for item in s:
if cnt > 10:
break
dic_list = dict(zip(item.keys(), item))
dic = {'longitude': dic_list['longitude'], 'latitude': dic_list['latitude']}
temp.append(dic)
cnt = cnt + 1
set['hour{}'.format(count)] = temp
time = time + 3600
count = count + 1
hour_count = 1
while hour_count < 25:
co_occ = []
cnt1 = 1
for item1 in set['hour{}'.format(hour_count)]:
cnt2 = 1
for item2 in set['hour{}'.format(hour_count)]:
if cnt2 >= cnt1:
cnt12 = 0
for k in range(1, 24):
if item1 in set['hour{}'.format(k)] and item2 in set['hour{}'.format(k)]:
cnt12 = cnt12 + 1
temp1 = {'s1': 'point{}'.format(cnt1), 's2': 'point{}'.format(cnt2),
's1_longitude': float(item1['longitude']),
's1_latitude': float(item1['latitude']), 's2_longitude': float(item2['longitude']),
's2_latitude': float(item2['latitude']), 'value': cnt12}
co_occ.append(temp1)
if cnt1 != cnt2:
temp2 = {'s1': 'point{}'.format(cnt2), 's2': 'point{}'.format(cnt1),
's1_longitude': float(item2['longitude']),
's1_latitude': float(item2['latitude']), 's2_longitude': float(item1['longitude']),
's2_latitude': float(item1['latitude']), 'value': cnt12}
co_occ.append(temp2)
cnt2 = cnt2 + 1
cnt1 = cnt1 + 1
with open('data/co_occurrence_{}.json'.format(hour_count), 'w') as f:
json.dump(co_occ, f)
print("Successfully load co_occurrence_{}".format(hour_count))
hour_count = hour_count + 1
########## FLASK ROUTES ###########
# standard template route
@app.route('/')
def dashboard():
return render_template('heatmap.html')
if __name__ == '__main__':
# app.debug = True
# app.run()
#frequency_order_by_hour()
co_occurrence_matrix()