File size: 25,032 Bytes
10927b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4e14ec4d",
   "metadata": {},
   "source": [
    "### This notebook performs spatial joins of the roads and VED coordinates to assign each point a speed limit (if possible) ."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "8a1d5196",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/fahmed/anaconda3/lib/python3.8/site-packages/geopandas/_compat.py:111: UserWarning: The Shapely GEOS version (3.9.1-CAPI-1.14.2) is incompatible with the GEOS version PyGEOS was compiled with (3.10.1-CAPI-1.16.0). Conversions between both will be slow.\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "from shapely.geometry import Point, LineString\n",
    "from shapely.wkt import loads\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "from tqdm.notebook import tqdm\n",
    "import matplotlib.pyplot as plt\n",
    "import geopandas as gpd\n",
    "from shapely import wkt\n",
    "import math\n",
    "import os"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "efd0fe22",
   "metadata": {},
   "source": [
    "Read the lines layer from OSM into a Pandas DataFrame"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "545d2995",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>WKT</th>\n",
       "      <th>osm_id</th>\n",
       "      <th>highway</th>\n",
       "      <th>maxspeed:forward</th>\n",
       "      <th>maxspeed:backward</th>\n",
       "      <th>source:maxspeed</th>\n",
       "      <th>maxspeed:advisory</th>\n",
       "      <th>maxspeed</th>\n",
       "      <th>maxspeed:practical</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>LINESTRING (-83.6889144 42.3061218,-83.6890468...</td>\n",
       "      <td>4411729</td>\n",
       "      <td>motorway_link</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>25 mph</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>LINESTRING (-83.7392397 42.2366692,-83.7392406...</td>\n",
       "      <td>4439869</td>\n",
       "      <td>secondary</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>35 mph</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>LINESTRING (-83.6855813 42.3070306,-83.6852592...</td>\n",
       "      <td>4569607</td>\n",
       "      <td>motorway_link</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>25 mph</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>LINESTRING (-83.8373697 42.2896413,-83.8366383...</td>\n",
       "      <td>4569609</td>\n",
       "      <td>motorway_link</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>70 mph</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>LINESTRING (-83.7733019 42.2692107,-83.7730861...</td>\n",
       "      <td>4574780</td>\n",
       "      <td>service</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                                 WKT   osm_id        highway  \\\n",
       "0  LINESTRING (-83.6889144 42.3061218,-83.6890468...  4411729  motorway_link   \n",
       "1  LINESTRING (-83.7392397 42.2366692,-83.7392406...  4439869      secondary   \n",
       "2  LINESTRING (-83.6855813 42.3070306,-83.6852592...  4569607  motorway_link   \n",
       "3  LINESTRING (-83.8373697 42.2896413,-83.8366383...  4569609  motorway_link   \n",
       "4  LINESTRING (-83.7733019 42.2692107,-83.7730861...  4574780        service   \n",
       "\n",
       "  maxspeed:forward maxspeed:backward source:maxspeed maxspeed:advisory  \\\n",
       "0                0                 0               0                 0   \n",
       "1                0                 0               0                 0   \n",
       "2                0                 0               0                 0   \n",
       "3                0                 0               0                 0   \n",
       "4                0                 0               0                 0   \n",
       "\n",
       "  maxspeed maxspeed:practical  \n",
       "0        0             25 mph  \n",
       "1   35 mph                  0  \n",
       "2        0             25 mph  \n",
       "3   70 mph                  0  \n",
       "4        0                  0  "
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fields = ['WKT', 'osm_id',  'highway', 'maxspeed:forward', 'maxspeed:backward', 'source:maxspeed', \n",
    "          'maxspeed:advisory', 'maxspeed', 'maxspeed:practical']\n",
    "\n",
    "\n",
    "dtype = {'maxspeed:forward': 'str', 'maxspeed:backward': 'str', 'source:maxspeed': 'str',\n",
    "         'maxspeed:advisory': 'str', 'maxspeed': 'str', 'maxspeed:practical': 'str'}\n",
    "\n",
    "roads_df = pd.read_csv('../data/osm/highways-lines-layer.csv', usecols=fields, dtype=dtype).fillna('0')\n",
    "roads_df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "33674615",
   "metadata": {},
   "source": [
    "Build a dictionary of roads, where keys are the OSM IDs and the values are the coordinates of the nodes in each road."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ff3a1d34",
   "metadata": {},
   "outputs": [],
   "source": [
    "roads_arr = roads_df.to_numpy()\n",
    "roads_dict = {roads_arr[i,1]: loads(roads_arr[i,0]) for i in range(len(roads_arr))}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4725b1fc",
   "metadata": {},
   "source": [
    "Convert the roads DataFrame to GeoDataFrame."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "7ffb3615",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>osm_id</th>\n",
       "      <th>highway</th>\n",
       "      <th>maxspeed:forward</th>\n",
       "      <th>maxspeed:backward</th>\n",
       "      <th>source:maxspeed</th>\n",
       "      <th>maxspeed:advisory</th>\n",
       "      <th>maxspeed</th>\n",
       "      <th>maxspeed:practical</th>\n",
       "      <th>geometry</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>4411729</td>\n",
       "      <td>motorway_link</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>25 mph</td>\n",
       "      <td>LINESTRING (-83.68891 42.30612, -83.68905 42.3...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>4439869</td>\n",
       "      <td>secondary</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>35 mph</td>\n",
       "      <td>0</td>\n",
       "      <td>LINESTRING (-83.73924 42.23667, -83.73924 42.2...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4569607</td>\n",
       "      <td>motorway_link</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>25 mph</td>\n",
       "      <td>LINESTRING (-83.68558 42.30703, -83.68526 42.3...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>4569609</td>\n",
       "      <td>motorway_link</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>70 mph</td>\n",
       "      <td>0</td>\n",
       "      <td>LINESTRING (-83.83737 42.28964, -83.83664 42.2...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>4574780</td>\n",
       "      <td>service</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>LINESTRING (-83.77330 42.26921, -83.77309 42.2...</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    osm_id        highway maxspeed:forward maxspeed:backward source:maxspeed  \\\n",
       "0  4411729  motorway_link                0                 0               0   \n",
       "1  4439869      secondary                0                 0               0   \n",
       "2  4569607  motorway_link                0                 0               0   \n",
       "3  4569609  motorway_link                0                 0               0   \n",
       "4  4574780        service                0                 0               0   \n",
       "\n",
       "  maxspeed:advisory maxspeed maxspeed:practical  \\\n",
       "0                 0        0             25 mph   \n",
       "1                 0   35 mph                  0   \n",
       "2                 0        0             25 mph   \n",
       "3                 0   70 mph                  0   \n",
       "4                 0        0                  0   \n",
       "\n",
       "                                            geometry  \n",
       "0  LINESTRING (-83.68891 42.30612, -83.68905 42.3...  \n",
       "1  LINESTRING (-83.73924 42.23667, -83.73924 42.2...  \n",
       "2  LINESTRING (-83.68558 42.30703, -83.68526 42.3...  \n",
       "3  LINESTRING (-83.83737 42.28964, -83.83664 42.2...  \n",
       "4  LINESTRING (-83.77330 42.26921, -83.77309 42.2...  "
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "roads_df['geometry'] = roads_df.WKT.apply(wkt.loads)\n",
    "roads_df.drop('WKT', axis=1, inplace=True) #Drop WKT column\n",
    "\n",
    "roads_gdf = gpd.GeoDataFrame(roads_df, geometry='geometry')\n",
    "roads_gdf.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "00f520db",
   "metadata": {},
   "source": [
    "Function that calculates the bearing of the two points whose coordinates are given in the parameters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "d378fee8",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_bearing(lat1, lat2, lon1, lon2):\n",
    "    \"\"\" Calculate the initial bearing for start point (lat1, lon1) and end point (lat2, lon2) \"\"\"\n",
    "    lat1, lat2 = math.radians(lat1), math.radians(lat2), \n",
    "    lon1, lon2 = math.radians(lon1), math.radians(lon2)\n",
    "    dLon = lon2 - lon1\n",
    "    y = math.sin(dLon) * math.cos(lat2)\n",
    "    x = math.cos(lat1) * math.sin(lat2) - math.sin(lat1) * math.cos(lat2) * math.cos(dLon)\n",
    "    brng = math.atan2(y, x)\n",
    "    return brng"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "27a18498",
   "metadata": {},
   "outputs": [],
   "source": [
    "def mph2kph(speed):\n",
    "    return round(speed * 1.609344)\n",
    "\n",
    "def speed2numeric(speed):\n",
    "    return mph2kph(int(speed.split()[0]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "fa9cda87",
   "metadata": {},
   "outputs": [],
   "source": [
    "def_maxspeed = {'residential': (1, speed2numeric('25 mph')), \n",
    "                'motorway': (1, speed2numeric('70 mph')), \n",
    "                'trunk': (1, speed2numeric('55 mph')),\n",
    "                'primary': (1, speed2numeric('55 mph')),\n",
    "                'secondary': (1, speed2numeric('45 mph')),\n",
    "                'tertiary': (1, speed2numeric('35 mph')),\n",
    "                'unclassified': (1, speed2numeric('55 mph')),\n",
    "                'service': (1, speed2numeric('25 mph'))}\n",
    "\n",
    "\n",
    "def get_speed(highway, maxspeed):\n",
    "    \"\"\" Returns two values, the class of the speed limit and the speed limit.\"\"\"\n",
    "    if maxspeed['maxspeed'] != '0':\n",
    "        return 0, speed2numeric(maxspeed['maxspeed'])\n",
    "    elif maxspeed['maxspeed:forward'] != '0':\n",
    "        sp = '{}-{}'.format(speed2numeric(maxspeed['maxspeed:forward']), \n",
    "                            speed2numeric(maxspeed['maxspeed:backward']))\n",
    "        return -1, sp\n",
    "    elif maxspeed['maxspeed:advisory'] != '0':\n",
    "        return 2, speed2numeric(maxspeed['maxspeed:advisory'])\n",
    "    elif maxspeed['maxspeed:practical'] != '0':\n",
    "        return 3, str(speed2numeric(maxspeed['maxspeed:practical']))\n",
    "    else:\n",
    "        return def_maxspeed.get(highway, (np.nan, np.nan))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c1ac5816",
   "metadata": {},
   "source": [
    "The function below looks a bit messy and could probably be written in a clearer and better way, but it does the job. It first checks if the current point has two different speed limits depending on the direction (is of class -1). If so, it saves the coordinates of this point and goes forward until it finds a point in the same trip that has different coordinates. It then uses these two points to calculate the bearing and decides on the direction of travel. The second case is when the road the point lies has the same speed limit regardless of the direction. In such case, it checks if the point that follows along the same trip is of class -1. If this is the case, it uses these two points to decide on the direction and updates all duplicate points (if any) that follow. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "8b5872c1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1: VehId, 2: Trip, 4: Latitude, 5: Longitude, 22: matched_lat, 23: matched_lon, 24: match_type\n",
    "\n",
    "def set_direction_sp(records):\n",
    "    np_arr = np.zeros(len(records)) # set the size to the correct one\n",
    "    for i in range(len(records)):\n",
    "        p_lat1, p_lon1 = records[i, 22], records[i, 23]\n",
    "\n",
    "        if records[i, 25] == -1 and np_arr[i] == 0:\n",
    "            j = i\n",
    "            osm_id = records[i, 27]\n",
    "            road_lon1, road_lat1 = roads_dict[osm_id].coords[0]\n",
    "            road_lon2, road_lat2 = roads_dict[osm_id].coords[-1]\n",
    "\n",
    "            while (records[j, 4] == records[i, 4]) and \\\n",
    "                (records[j, 5] == records[i, 5]) and \\\n",
    "                (records[j, 1] == records[i, 1]) and \\\n",
    "                (records[j, 2] == records[i, 2]) and \\\n",
    "                (j < len(records)-1):\n",
    "                j += 1\n",
    "\n",
    "            if i != j:\n",
    "                p_lat2, p_lon2 = records[j, 22], records[j, 23]\n",
    "                # perform the computations and update all relevant rows\n",
    "                br1 = get_bearing(p_lat1, p_lat2, p_lon1, p_lon2)\n",
    "                br2 = get_bearing(road_lat1, road_lat2, road_lon1, road_lon2)\n",
    "                direction = math.cos(br1-br2)\n",
    "                speed = None\n",
    "\n",
    "                while i <= j:\n",
    "                    if records[i, 25] == -1:\n",
    "                        if direction > 0: # same direction\n",
    "                            # extract the correct speed limit and set it\n",
    "                            speed = records[i, 26].split('-')[0]\n",
    "                        else:\n",
    "                            speed = records[i, 26].split('-')[1]\n",
    "                    else:\n",
    "                        speed = records[i, 26]\n",
    "                    np_arr[i] = speed\n",
    "                    i += 1\n",
    "            else:\n",
    "                np_arr[i] = records[i, 26]\n",
    "        else:\n",
    "            if np_arr[i] == 0:\n",
    "                np_arr[i] = records[i, 26]\n",
    "                j = i + 1\n",
    "                if j < len(records):\n",
    "                    if records[j, 25] == -1:\n",
    "                        i = j\n",
    "                        p_lat2, p_lon2 = records[i, 22], records[i, 23]\n",
    "                        osm_id = records[i, 27]\n",
    "                        road_lon1, road_lat1 = roads_dict[osm_id].coords[0]\n",
    "                        road_lon2, road_lat2 = roads_dict[osm_id].coords[-1]\n",
    "                        \n",
    "                        while (records[j, 4] == records[i, 4]) and \\\n",
    "                        (records[j, 5] == records[i, 5]) and \\\n",
    "                        (records[j, 1] == records[i, 1]) and \\\n",
    "                        (records[j, 2] == records[i, 2]) and \\\n",
    "                        (j < len(records)-1):\n",
    "                            j += 1\n",
    "        \n",
    "                        # perform the computations and update all relevant rows\n",
    "                        br1 = get_bearing(p_lat1, p_lat2, p_lon1, p_lon2)\n",
    "                        br2 = get_bearing(road_lat1, road_lat2, road_lon1, road_lon2)\n",
    "                        direction = math.cos(br1-br2)\n",
    "                        speed = None\n",
    "                        while i <= j:\n",
    "                            if records[i, 25] == -1:\n",
    "                                if direction > 0: # same direction\n",
    "                                    # extract the correct speed limit and set it\n",
    "                                    speed = records[i, 26].split('-')[0]\n",
    "                                else:\n",
    "                                    speed = records[i, 26].split('-')[1]\n",
    "                            else:\n",
    "                                speed = records[i, 26]\n",
    "                            np_arr[i] = speed\n",
    "                            i += 1\n",
    "    return np_arr"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "401d6fd8",
   "metadata": {},
   "source": [
    "Read all files that contain the matched coordinates."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "a4bd3a80",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "3bfd0cb4118a4746b51862d20096674a",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "  0%|          | 0/54 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "data_path = \"../data/ved-valhalla/\"\n",
    "files = [os.path.join(data_path, file) for file in tqdm(os.listdir(data_path)) if file.endswith(\".csv\")]\n",
    "files.sort()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d6bab521",
   "metadata": {},
   "source": [
    "Converting each into a Pandas GeoDataFrame, spatially joining of the two GeoDataFrames and removing the duplicates which are as a result of intersections."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "469930dc",
   "metadata": {},
   "outputs": [],
   "source": [
    "def spatial_join(file):\n",
    "    data_df = pd.read_csv(file)\n",
    "    data_gdf = gpd.GeoDataFrame(data_df, geometry=gpd.points_from_xy(data_df.matched_lon, data_df.matched_lat))\n",
    "    sjoined_gdf = gpd.sjoin_nearest(data_gdf, roads_gdf, how=\"left\", max_distance=1e-05, distance_col='distance')\n",
    "    sjoined_gdf_grouped = sjoined_gdf.groupby(sjoined_gdf.index).first() # remove duplicates\n",
    "    gdf_cols = ['osm_id', 'highway', 'maxspeed:forward', 'maxspeed:backward', \n",
    "                'maxspeed:advisory', 'maxspeed', 'maxspeed:practical']\n",
    "    data_df = data_df.drop('geometry', 1)\n",
    "    data_df = data_df.merge(sjoined_gdf_grouped[gdf_cols], left_index=True, right_index=True)\n",
    "    return data_df\n",
    "\n",
    "def add_speed_limits(file):\n",
    "    data_df = spatial_join(file)\n",
    "    columns = [col for col in data_df.columns]\n",
    "    maxspeed_cols = list(range(columns.index('highway'), len(columns)))\n",
    "\n",
    "    data_arr = data_df.to_numpy()\n",
    "    N = len(data_arr)\n",
    "    ved_out_df = np.c_[data_arr, np.zeros(N), np.empty(N, dtype='<U10')]\n",
    "    for row in ved_out_df:\n",
    "        # ms_cols dictionary: keys: maxspeed tag, values: speed limit\n",
    "        ms_cols = {columns[j]: row[j] for j in range(27, len(columns))}\n",
    "        if row[26] is None:\n",
    "            sp_cls, speed_limit = np.nan, np.nan\n",
    "        else:\n",
    "            sp_cls, speed_limit = get_speed(row[26], ms_cols)\n",
    "        row[32], row[33] = sp_cls, speed_limit\n",
    "\n",
    "    columns.extend(['Class of Speed Limit', 'Speed Limit[km/h]'])\n",
    "    ved_out_df = pd.DataFrame(ved_out_df, columns=columns) \n",
    "    ved_out_df = ved_out_df.drop([columns[i] for i in maxspeed_cols], axis=1)\n",
    "    osm_col = ved_out_df['osm_id']\n",
    "    ved_out_df = ved_out_df.drop(['osm_id'], 1)\n",
    "    ved_out_df = ved_out_df.merge(osm_col, left_index=True, right_index=True)\n",
    "    speed_column = set_direction_sp(ved_out_df.to_numpy())\n",
    "    speed_column = pd.DataFrame(speed_column, columns={'Speed Limit with Direction'})\n",
    "    ved_out_df = ved_out_df.merge(speed_column, left_index=True, right_index=True)\n",
    "    return ved_out_df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "6d7aff86",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "26d17b74c9f14a68b0c4b8edb1d4e556",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "  0%|          | 0/54 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "def get_save_path(filename):\n",
    "    return f\"../data/ved-speed-limits/{filename[len(data_path)-1:]}\"\n",
    "\n",
    "for file in tqdm(files):\n",
    "    ved_file = add_speed_limits(file)\n",
    "    ved_file = ved_file.drop('osm_id', 1)\n",
    "    ved_file.to_csv(get_save_path(file), na_rep=np.nan, index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "63caeded",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}