-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathK_NN.py
431 lines (371 loc) · 14.4 KB
/
K_NN.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
import random
import psycopg2
import datetime
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure
import os
class MongoDB():
def __init__(self,host, port, dbName):
client = MongoClient(host, port)
db = client.nyc
self.collection = db[dbName]
try:
# The ismaster command is cheap and does not require auth.
client.admin.command('ismaster')
print("Connected to MongoDB Server\n\n")
except ConnectionFailure:
print("Mongodb Server not available\n\n")
def k_NN(self, tripID, k):
# In order to find the k-NN of a tripID, we first need to find its coordinates; thus call the retrieveDocument method
document = self.retrieveDocument(tripID)
x = document['geometry_pk']['coordinates'][0]
y = document['geometry_pk']['coordinates'][1]
# print(x,y) - OK
query = {}
query["geometry_pk"] = {
u"$nearSphere": {
u"$geometry": {
u"type": u"Point",
u"coordinates": [
x, y
]
}
}
}
# Record the execution time of the query
start_time = datetime.datetime.now()
cursor = self.collection.find(query).limit(k)
finish_time = datetime.datetime.now()
timediff = (finish_time - start_time).total_seconds()
k_NN = set()
for doc in cursor:
k_NN.add(doc['properties']['ID_Postgres'])
del cursor
return timediff, k_NN
class postgres():
def __init__(self, dbName, userName, pswd, host, port):
try:
self.conn = psycopg2.connect(database=dbName,
user=userName,
password=pswd,
host=host,
port=port)
print("Connected to PostgreSQL Server")
except:
print("Postgres connection failed!")
# ------------------------- Data export: From Postgres to MongoDB
def postgres2GeoJSON(self, chunkSize, chunkID):
# chunkSize: number of records to be converted to GeoJSON to ease the RAM operations
# chunkID: the GeoJSON file is going to be saved by using this ID. starts from ZERO
template = \
'''
{
"type" : "Feature",
"geometry_pk" : {
"type" : "Point",
"coordinates" : [%s,%s]},
"properties": {
"ID_Postgres": %s,
"VendorID" : %s,
"passenger_count" : %s,
"store_and_fwd_flag" : "%s",
"RatecodeID" : %s,
"trip_distance" : %s,
"payment_type" : %s,
"fare_amount" : %s,
"extra" : %s,
"mta_tax" : %s,
"tip_amount" : %s,
"tolls_amount" : %s,
"improvement_surcharge" : %s,
"total_amount" : %s,
"tpep_pickup_datetime" : ISODate("%s"),
"tpep_dropoff_datetime" : ISODate("%s")},
"geometry_do" : {
"type" : "Point",
"coordinates" : [%s,%s]},
},
'''
# the head of the geojson file
output = \
'''
'''
outFileHandle = open("nyc2015_json_%s.geojson" % str(chunkID), "a")
cur = self.conn.cursor()
cur.execute(""" SELECT *
FROM staging
where id > {} and id <= {}
order by id """.format(chunkID * chunkSize, (chunkID + 1) * chunkSize))
rows = cur.fetchall()
c = 0
for row in rows:
record = ''
id = row[0]
vendorID = row[1]
t_pickup = rearrangeTimeFormat(str(row[2]))
t_dropoff = rearrangeTimeFormat(str(row[3]))
passenger_count = row[4]
trip_distance = row[5]
pickup_longitude = row[6]
pickup_latitude = row[7]
ratecodeID = row[8]
store_and_fwd_flag = row[9]
dropoff_longitude = row[10]
dropoff_latitude = row[11]
payment_type = row[12]
fare_amount = row[13]
extra = row[14]
mta_tax = row[15]
tip_amount = row[16]
tolls_amount = row[17]
improvement_surcharge = row[18]
total_amount = row[19]
record += template % (pickup_longitude,
pickup_latitude,
id,
vendorID,
passenger_count,
store_and_fwd_flag,
ratecodeID,
trip_distance,
payment_type,
fare_amount,
extra,
mta_tax,
tip_amount,
tolls_amount,
improvement_surcharge,
total_amount,
t_pickup,
t_dropoff,
dropoff_longitude,
dropoff_latitude)
# Add the record to the GeoJSON file
outFileHandle.write(record)
c += 1
# the tail of the geojson file
output += \
'''
'''
outFileHandle.write(output)
outFileHandle.close()
del rows
cur.close()
def Specifid_ID2GeoJSON(self, *kwargs):
# Input specific ID's of points
# It returns geojson file which writen points
chunkID = len(kwargs)
for num in kwargs:
template = \
'''
{
"type" : "Feature",
"geometry_pk" : {
"type" : "Point",
"coordinates" : [%s,%s]},
"properties": {
"ID_Postgres": %s,
"VendorID" : %s,
"passenger_count" : %s,
"store_and_fwd_flag" : "%s",
"RatecodeID" : %s,
"trip_distance" : %s,
"payment_type" : %s,
"fare_amount" : %s,
"extra" : %s,
"mta_tax" : %s,
"tip_amount" : %s,
"tolls_amount" : %s,
"improvement_surcharge" : %s,
"total_amount" : %s,
"tpep_pickup_datetime" : ISODate("%s"),
"tpep_dropoff_datetime" : ISODate("%s")},
"geometry_do" : {
"type" : "Point",
"coordinates" : [%s,%s]},
},
'''
# the head of the geojson file
output = \
'''
'''
outFileHandle = open("nyc2015_json_sub.geojson", "a")
cur = self.conn.cursor()
cur.execute(""" SELECT *
FROM staging
where id = {}""".format(num))
rows = cur.fetchall()
c = 0
for row in rows:
record = ''
id = row[0]
vendorID = row[1]
t_pickup = rearrangeTimeFormat(str(row[2]))
t_dropoff = rearrangeTimeFormat(str(row[3]))
passenger_count = row[4]
trip_distance = row[5]
pickup_longitude = row[6]
pickup_latitude = row[7]
ratecodeID = row[8]
store_and_fwd_flag = row[9]
dropoff_longitude = row[10]
dropoff_latitude = row[11]
payment_type = row[12]
fare_amount = row[13]
extra = row[14]
mta_tax = row[15]
tip_amount = row[16]
tolls_amount = row[17]
improvement_surcharge = row[18]
total_amount = row[19]
record += template % (pickup_longitude,
pickup_latitude,
id,
vendorID,
passenger_count,
store_and_fwd_flag,
ratecodeID,
trip_distance,
payment_type,
fare_amount,
extra,
mta_tax,
tip_amount,
tolls_amount,
improvement_surcharge,
total_amount,
t_pickup,
t_dropoff,
dropoff_longitude,
dropoff_latitude)
# Add the record to the GeoJSON file
outFileHandle.write(record)
c += 1
# the tail of the geojson file
output += \
'''
'''
outFileHandle.write(output)
outFileHandle.close()
del rows
cur.close()
def k_NN_v1(self, tripID, k, nameIDColumn, tableName):
# This query determines the k_NN of a a pickup location of a trip by joining the trip table twice
# nameIDColumn: usually id, but could also be "nid" if a single day is analysed
# tableName: which table are we relying on? trips (the whole table) or a specific day (day_yyyy_mm_dd)
cur = self.conn.cursor()
query = "SELECT y2.id " \
"FROM {} y1, {} y2 " \
"WHERE y1.{} = {} " \
"ORDER BY y1.l_pickup <-> y2.l_pickup " \
"limit {};".format(tableName, tableName, nameIDColumn, tripID, k)
# Record the execution time of the query
start_time = datetime.datetime.now()
cur.execute(query)
finish_time = datetime.datetime.now()
timediff = (finish_time - start_time).total_seconds()
# It is also important to have the NNs for comparison with other queries
rows = cur.fetchall()
k_NN = set()
for row in rows:
k_NN.add(row[0])
cur.close()
return timediff, k_NN
def k_NN_v2(self, tripID,k, nameIDColumn, tableName):
# This query determines the k_NN of a pickup location of a trip using id insertion
# It has a similar idea to MongoDB query
# nameIDColumn: usually id, but could also be "nid" if a single day is analysed
# tableName: which table are we relying on? trips (the whole table) or a specific day (day_yyyy_mm_dd)
cur = self.conn.cursor()
query = "SELECT id " \
"FROM {} " \
"ORDER BY l_pickup <-> (select l_pickup from {} where {} = {})" \
"limit {};".format(tableName, tableName, nameIDColumn, tripID, k)
# We want to record the time of execution of the query
start_time = datetime.datetime.now()
cur.execute(query)
finish_time = datetime.datetime.now()
timediff = (finish_time - start_time).total_seconds()
# It is also important to have the NNs for comparison with other queries
rows = cur.fetchall()
k_NN = set()
for row in rows:
k_NN.add(row[0])
cur.close()
return timediff, k_NN
def pickup_pos(self,id):
cur = self.conn.cursor()
query = "SELECT l_pickup_lat,l_pickup_lon " \
"FROM day_2015_05_23 " \
"where nid= {}".format(id)
cur.execute(query)
rows = cur.fetchall()
cur.close()
return rows
#Take position of neighbor
def neighbor_pos(self,id):
cur = self.conn.cursor()
query = "SELECT l_pickup_lat,l_pickup_lon " \
"FROM day_2015_05_23 " \
"where id= {}".format(id)
cur.execute(query)
rows = cur.fetchall()
cur.close()
return rows
def pickup_pos_big(self,id):
cur = self.conn.cursor()
query = "SELECT l_pickup_lat,l_pickup_lon " \
"FROM trips " \
"where id= {}".format(id)
cur.execute(query)
rows = cur.fetchall()
cur.close()
return rows
def neighbor_pos_big(self,id):
cur = self.conn.cursor()
query = "SELECT l_pickup_lat,l_pickup_lon " \
"FROM trips " \
"where id= {}".format(id)
cur.execute(query)
rows = cur.fetchall()
cur.close()
return rows
#Common Functions
def generateRandomID_List(totalNumbers, maxID):
# totalNumbers: how many random IDs are going to be generated?
# maxID: max ID
random_list = list()
count = 0
while (count < totalNumbers):
id = random.randint(1, maxID)
# Check whether the ID is indeed valid:
# We have not included the Postgres IDs: [8M1 - 10M]
if (id >= 8000001 and id <= 10000000):
continue
else:
random_list.append(id)
count += 1
return random_list
def generateSQL2SelectIDs(IDs):
# Input set of IDs
# Generate a string corresponding to the SQL to select those IDs
# Select the IDs from the main table of 'trips'
numIDs = len(IDs)
ids = ""
for i in range(numIDs):
tmp = "id = " + str(IDs[i]) + " or \n"
ids = ids + tmp
whereClause = "where " + ids
strSQL = (""" SELECT *
FROM trips
{}""").format(whereClause)
return strSQL
def rearrangeTimeFormat(t):
# print(t)
date = datetime.datetime.strptime(t, "%Y-%m-%d %H:%M:%S")
# print(str(date.isoformat()))
# Adding the 'Z' at the end:
s = str(date.isoformat())
s = ''.join((s, 'Z'))
# print(s)
return s