-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathdb.py
527 lines (480 loc) · 12.6 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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
# functions involving BD interaction
import psycopg2, json, math
from conf import conf
from shapely.wkb import loads as loadWKB
from minor_objects import Stop, Vehicle
# 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(ST_Transform(orig_geom,4326))).geom,
unnest(times)
FROM {trips}
WHERE trip_id = %(trip_id)s
""".format(**conf['db']['tables']),
{ 'trip_id':trip_id }
)
vehicle_records = []
for (bid, did, rid, vid, WGS84geom, epoch_time ) in c:
# only consider the last three variables, as the rest are
# the same for every record
WGS84geom = loadWKB(WGS84geom,hex=True)
# Vehicle( epoch_time, longitude, latitude)
vehicle_records.append( Vehicle( epoch_time, WGS84geom.x, WGS84geom.y ) )
result = {
'block_id': bid,
'direction_id': did,
'route_id': rid,
'vehicle_id': vid,
'points': vehicle_records
}
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.
This is used to group sequential trips by the same vehicle."""
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 = '',
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_direction_uid(direction_id,trip_time):
"""Find the correct direction entry based on the direction_id and the time
of the trip. Trip_time is an epoch value, direction_id is a string."""
c = cursor()
c.execute(
"""
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 }
)
uid, = c.fetchone()
return uid
def get_stops(direction_id, trip_time):
"""Get an ordered list of Stop objects from the schedule data."""
c = cursor()
# get the uid of the relevant direction entry
direction_uid = get_direction_uid(direction_id,trip_time)
if not direction_uid: return None
c.execute(
"""
SELECT uid, the_geom FROM (
SELECT
DISTINCT ON (a.stop) a.stop AS stop_id,
s.uid,
a.seq,
s.the_geom
FROM {directions} AS d, unnest(d.stops) WITH ORDINALITY a(stop, seq)
JOIN {stops} AS s ON s.stop_id = a.stop
WHERE d.uid = %(direction_uid)s AND s.report_time <= %(trip_time)s
-- get uniques stops with the earliest report time and order by sequence
ORDER BY a.stop, s.report_time
) AS whatever ORDER BY seq
""".format(**conf['db']['tables']),
{ 'direction_uid':direction_uid, 'trip_time':trip_time }
)
# return a schedule-ordered list of stop objects
return [ Stop( stop_uid, geom ) for stop_uid, geom in c.fetchall() ]
def get_route_geom(direction_id, trip_time):
"""Get the geometry of a direction or return None. This is meant to be a
backup in case map-matching is going badly. Direction geometries must be
supplied manually. If all goes well this returns a shapely geometry in
the local projection. Else, None."""
c = cursor()
# get the uid of the relevant direction entry
uid = get_direction_uid(direction_id,trip_time)
if not uid: return None
# now find the geometry
c.execute(
"""
SELECT
route_geom
FROM {directions}
WHERE uid = %(uid)s;
""".format(**conf['db']['tables']),
{ 'uid':uid }
)
geom, = c.fetchone()
if geom: return loadWKB(geom,hex=True)
else: return None
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 get_trip_problem(trip_id):
"""What problem was associated with the processing of this trip?"""
c = cursor()
c.execute(
"""
SELECT problem FROM {trips} WHERE trip_id = %(trip_id)s;
""".format(**conf['db']['tables']),
{ 'trip_id':trip_id }
)
problem, = c.fetchone()
return problem if problem != '' else None
def store_timepoints(trip_id,timepoints):
"""store the estimated stop times for a trip"""
assert len(timepoints) > 1
c = cursor()
# be sure the timepoints are in ascending temporal order
timepoints = sorted(timepoints,key=lambda tp: tp.arrival_time)
# insert the stops
records = []
seq = 1
for timepoint in timepoints:
# list of tuples
records.append( (trip_id,timepoint.stop_id,timepoint.arrival_time,seq) )
seq += 1
args_str = ','.join( [ "({},{},{},{})".format(*x) for x in records ] )
c.execute("INSERT INTO {stop_times} (trip_id, stop_uid, etime, stop_sequence) VALUES ".format(**conf['db']['tables']) + args_str)
def get_timepoints(trip_id):
"""Essentially, this should be the inverse of the above function."""
c = cursor()
c.execute("""
SELECT stop_id, etime, stop_sequence
FROM {stop_times}
WHERE trip_id = %(trip_id)s
ORDER BY stop_sequence
""".format(**conf['db']['tables']),
{ 'trip_id':trip_id })
return c.fetchall()
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 get_trip_ids_unfinished():
""""""
c = cursor()
c.execute(
"""
SELECT trip_id
FROM {trips}
WHERE problem IN ('','connection issue','match problem') AND ignore
ORDER BY trip_id ASC;
""".format(**conf['db']['tables'])
)
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