forked from SAUSy-Lab/retro-gtfs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.py
489 lines (449 loc) · 11 KB
/
db.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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
# functions involving BD interaction
import psycopg2, json, math
from conf import conf
from shapely.wkb import loads as loadWKB
# connect and establish a cursor, based on parameters in conf.py
conn_string = (
"host='"+conf['db']['host']
+"' dbname='"+conf['db']['name']
+"' user='"+conf['db']['user']
+"' password='"+conf['db']['password']+"'"
)
connection = psycopg2.connect(conn_string)
connection.autocommit = True
def reconnect():
"""renew connections inside a process"""
global connection
connection = psycopg2.connect(conn_string)
connection.autocommit = True
def cursor():
"""provide a cursor"""
return connection.cursor()
def get_trip_attributes(trip_id):
"""Return the attributes of a stored trip necessary
for the construction of a new trip object.
This now includes the vehicle report times and positions."""
c = cursor()
c.execute(
"""
SELECT
block_id,
direction_id,
route_id,
vehicle_id,
(ST_DumpPoints(orig_geom)).geom,
(ST_DumpPoints(ST_Transform(orig_geom,4326))).geom,
unnest(times)
FROM {trips}
WHERE trip_id = %(trip_id)s
""".format(**conf['db']['tables']),
{ 'trip_id':trip_id }
)
points = []
for (bid, did, rid, vid, geom, wgs84geom, time ) in c:
# only consider the last three variables, as the rest are
# the same for every record
wgs84geom = loadWKB(wgs84geom,hex=True)
points.append({
'geom':loadWKB(geom,hex=True),
'time':time,
'lat': wgs84geom.y,
'lon': wgs84geom.x
})
result = {
'block_id':bid,
'direction_id':did,
'route_id':rid,
'vehicle_id':vid,
'points':points
}
return result
def new_trip_id():
"""get a next trip_id to start from, defaulting to 1"""
c = cursor()
c.execute(
"""
SELECT MAX(trip_id) FROM {trips};
""".format(**conf['db']['tables'])
)
try:
(trip_id,) = c.fetchone()
return trip_id + 1
except:
return 1
def new_block_id():
"""get a next block_id to start from, defaulting to 1"""
c = cursor()
c.execute(
"""
SELECT MAX(block_id) FROM {trips};
""".format(**conf['db']['tables'])
)
try:
(block_id,) = c.fetchone()
return block_id + 1
except:
return 1
def empty_tables():
"""clear the tables of any processing results
but NOT of original data from the API"""
c = cursor()
c.execute(
"""
TRUNCATE {stop_times};
UPDATE {trips} SET
service_id = NULL,
match_confidence = NULL,
ignore = TRUE,
clean_geom = NULL,
problem = NULL,
active = NULL,
match_geom = NULL;
""".format(**conf['db']['tables'])
)
def ignore_trip(trip_id,reason=None):
"""mark a trip to be ignored"""
c = cursor()
c.execute(
"""
UPDATE {trips} SET ignore = TRUE WHERE trip_id = %(trip_id)s;
DELETE FROM {stop_times} WHERE trip_id = %(trip_id)s;
""".format(**conf['db']['tables']),
{ 'trip_id': trip_id }
)
if reason:
flag_trip(trip_id,reason)
return
def flag_trip(trip_id,problem_description_string):
"""Populate the 'problem' field of trip table: something must
have gone wrong and this tells us what."""
c = cursor()
c.execute(
"""
UPDATE {trips} SET problem = problem || %(description)s
WHERE trip_id = %(trip_id)s;
""".format(**conf['db']['tables']),
{
'description':problem_description_string,
'trip_id':trip_id
}
)
def add_trip_match(trip_id,confidence,wkb_geometry_match):
"""update the trip record with it's matched geometry"""
c = cursor()
# store the given values
c.execute(
"""
UPDATE {trips}
SET
match_confidence = %(confidence)s,
match_geom = ST_SetSRID(%(match)s::geometry,%(localEPSG)s)
WHERE trip_id = %(trip_id)s;
""".format(**conf['db']['tables']),
{
'localEPSG':conf['localEPSG'],
'confidence':confidence,
'match':wkb_geometry_match,
'trip_id':trip_id
}
)
def insert_trip(trip_id,block_id,route_id,direction_id,vehicle_id,times,orig_geom):
"""Store the basics of the trip in the database."""
c = cursor()
# store the given values
c.execute(
"""
INSERT INTO {trips}
(
trip_id,
block_id,
route_id,
direction_id,
vehicle_id,
times,
orig_geom
)
VALUES
(
%(trip_id)s,
%(block_id)s,
%(route_id)s,
%(direction_id)s,
%(vehicle_id)s,
%(times)s,
ST_SetSRID( %(orig_geom)s::geometry, %(localEPSG)s )
);
""".format(**conf['db']['tables']),
{
'trip_id':trip_id,
'block_id':block_id,
'route_id':route_id,
'direction_id':direction_id,
'vehicle_id':vehicle_id,
'times':times,
'orig_geom':orig_geom,
'localEPSG':conf['localEPSG']
}
)
def get_stops(direction_id,trip_time):
"""given the direction id, and the time of the trip, get a list of stops and
their attributes from the schedule data, returning as a dictionary.
Need to make temporally relevant choices. trip_time is an epoch value"""
c = cursor()
# get stop_ids from the last reported direction
# (from the perspective of this trip)
c.execute(
"""
SELECT
unnest(stops) AS stop_id
FROM {directions}
WHERE uid = (
SELECT uid
FROM {directions}
WHERE
direction_id = %(direction_id)s AND
report_time <= %(trip_time)s
ORDER BY report_time DESC
LIMIT 1
)
""".format(**conf['db']['tables']),
{ 'direction_id':direction_id, 'trip_time':trip_time }
)
# list of stop_ids
stop_ids = [ stop_id for (stop_id,) in c.fetchall() ]
# now we need to get the data for the last reported stops with these IDs
c.execute(
"""
WITH m AS (
SELECT
stop_id, max(report_time) AS max_report_time
FROM {stops}
WHERE
stop_id IN %(stop_ids)s AND
report_time <= %(trip_time)s
GROUP BY stop_id
)
SELECT
s.stop_id, s.the_geom
FROM {stops} AS s JOIN m ON
s.stop_id = m.stop_id AND
s.report_time = m.max_report_time
""".format(**conf['db']['tables']),
{ 'trip_time':trip_time, 'stop_ids':tuple(stop_ids) }
)
stops = []
for (stop_id,geom) in c.fetchall():
stops.append({
'id':stop_id,
'geom':geom
})
return stops
def set_trip_clean_geom(trip_id,localWKBgeom):
"""Store a geometry of the input to the matching process"""
c = cursor()
c.execute(
"""
UPDATE {trips}
SET clean_geom = ST_SetSRID( %(geom)s::geometry, %(EPSG)s )
WHERE trip_id = %(trip_id)s;
""".format(**conf['db']['tables']),
{
'trip_id':trip_id,
'geom':localWKBgeom,
'EPSG':conf['localEPSG']
}
)
def store_timepoints(trip_id,timepoints):
"""store the estimated stop times for a trip"""
c = cursor()
# insert the stops
records = []
seq = 1
for timepoint in timepoints:
# list of tuples
records.append( (trip_id,timepoint['stop_id'],timepoint['time'],seq) )
seq += 1
args_str = ','.join(c.mogrify("(%s,%s,%s,%s)", x) for x in records)
c.execute("INSERT INTO {stop_times} (trip_id, stop_id, etime, stop_sequence) VALUES ".format(**conf['db']['tables']) + args_str)
def set_service_id(trip_id,service_id):
"""set the service_id of a trip"""
c = cursor()
c.execute(
"""
UPDATE {trips}
SET service_id = %(service_id)s
WHERE trip_id = %(trip_id)s;
""".format(**conf['db']['tables']),
{
'service_id':service_id,
'trip_id':trip_id
}
)
def try_storing_stop(stop_id,stop_name,stop_code,lon,lat):
"""we have received a report of a stop from the routeConfig
data. Is this a new stop? Have we already heard of it?
Decide whether to store it or ignore it. If absolutely
nothing has changed about the record, ignore it. If not,
store it with the current time."""
c = cursor()
# see if precisely this record already exists
c.execute(
"""
SELECT *
FROM {stops}
WHERE
stop_id = %(stop_id)s AND
stop_name = %(stop_name)s AND
stop_code = %(stop_code)s AND
ABS(lon - %(lon)s::numeric) <= 0.0001 AND
ABS(lat - %(lat)s::numeric) <= 0.0001;
""".format(**conf['db']['tables']),
{
'stop_id':stop_id,
'stop_name':stop_name,
'stop_code':stop_code,
'lon':lon,
'lat':lat
}
)
# if any result, we already have this stop
if c.rowcount > 0:
return
# store the stop
c.execute(
"""
INSERT INTO {stops} (
stop_id, stop_name, stop_code,
the_geom,
lon, lat,
report_time
)
VALUES (
%(stop_id)s, %(stop_name)s, %(stop_code)s,
ST_Transform( ST_SetSRID( ST_MakePoint(%(lon)s, %(lat)s),4326),%(localEPSG)s ),
%(lon)s, %(lat)s,
EXTRACT(EPOCH FROM NOW())
)""".format(**conf['db']['tables']),
{
'stop_id':stop_id,
'stop_name':stop_name,
'stop_code':stop_code,
'lon':lon,
'lat':lat,
'localEPSG':conf['localEPSG']
} )
def try_storing_direction(route_id,did,title,name,branch,useforui,stops):
"""we have recieved a report of a route direction from the
routeConfig data. Is this a new direction? Have we already
heard of it? Decide whether to store it or ignore it. If
absolutely nothing has changed about the record, ignore it.
If not, store it with the current time."""
c = cursor()
# see if exactly this record already exists
c.execute(
"""
SELECT * FROM {directions}
WHERE
route_id = %s AND
direction_id = %s AND
title = %s AND
name = %s AND
branch = %s AND
useforui = %s AND
stops = %s;
""".format(**conf['db']['tables']),
(
route_id,
did,
title,
name,
branch,
useforui,
stops
)
)
if c.rowcount > 0:
return # already have the record
# store the data
c.execute(
"""
INSERT INTO {directions}
(
route_id, direction_id, title,
name, branch, useforui,
stops, report_time
)
VALUES
(
%s, %s, %s,
%s, %s, %s,
%s, EXTRACT(EPOCH FROM NOW())
)""".format(**conf['db']['tables']),
(
route_id,did,title,
name,branch,useforui,
stops
)
)
def scrub_trip(trip_id):
"""Un-mark any flag fields and leave the DB record
as though newly collected and unprocessed"""
c = cursor()
c.execute(
"""
UPDATE {trips} SET
match_confidence = NULL,
match_geom = NULL,
clean_geom = NULL,
problem = '',
ignore = FALSE,
service_id = NULL
WHERE trip_id = %(trip_id)s;
DELETE FROM {stop_times}
WHERE trip_id = %(trip_id)s;
""".format(**conf['db']['tables']),
{ 'trip_id':trip_id }
)
def get_trip_ids_by_range(min_id,max_id):
"""return a list of all trip ids in the specified range"""
c = cursor()
c.execute(
"""
SELECT trip_id
FROM {trips}
WHERE trip_id BETWEEN %(min)s AND %(max)s
ORDER BY trip_id ASC
""".format(**conf['db']['tables']),
{
'min':min_id,
'max':max_id
}
)
return [ result for (result,) in c.fetchall() ]
def get_trip_ids_by_route(route_id):
"""return a list of all trip ids operating a given route"""
c = cursor()
c.execute(
"""
SELECT trip_id
FROM {trips}
WHERE route_id = %(route_id)s
ORDER BY trip_id ASC
""".format(**conf['db']['tables']),
{
'route_id':route_id
}
)
return [ result for (result,) in c.fetchall() ]
def trip_exists(trip_id):
"""Check whether a trip exists in the database,
returning boolean."""
c = cursor()
c.execute(
"""
SELECT EXISTS (SELECT * FROM {trips} WHERE trip_id = %(trip_id)s)
""".format(**conf['db']['tables']),
{ 'trip_id':trip_id }
)
(existence,) = c.fetchone()
return existence