{
"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": [
"
\n",
"\n",
"
\n",
" \n",
" \n",
" | \n",
" WKT | \n",
" osm_id | \n",
" highway | \n",
" maxspeed:forward | \n",
" maxspeed:backward | \n",
" source:maxspeed | \n",
" maxspeed:advisory | \n",
" maxspeed | \n",
" maxspeed:practical | \n",
"
\n",
" \n",
" \n",
" \n",
" | 0 | \n",
" LINESTRING (-83.6889144 42.3061218,-83.6890468... | \n",
" 4411729 | \n",
" motorway_link | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 25 mph | \n",
"
\n",
" \n",
" | 1 | \n",
" LINESTRING (-83.7392397 42.2366692,-83.7392406... | \n",
" 4439869 | \n",
" secondary | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 35 mph | \n",
" 0 | \n",
"
\n",
" \n",
" | 2 | \n",
" LINESTRING (-83.6855813 42.3070306,-83.6852592... | \n",
" 4569607 | \n",
" motorway_link | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 25 mph | \n",
"
\n",
" \n",
" | 3 | \n",
" LINESTRING (-83.8373697 42.2896413,-83.8366383... | \n",
" 4569609 | \n",
" motorway_link | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 70 mph | \n",
" 0 | \n",
"
\n",
" \n",
" | 4 | \n",
" LINESTRING (-83.7733019 42.2692107,-83.7730861... | \n",
" 4574780 | \n",
" service | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
"
\n",
" \n",
"
\n",
"
"
],
"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": [
"\n",
"\n",
"
\n",
" \n",
" \n",
" | \n",
" osm_id | \n",
" highway | \n",
" maxspeed:forward | \n",
" maxspeed:backward | \n",
" source:maxspeed | \n",
" maxspeed:advisory | \n",
" maxspeed | \n",
" maxspeed:practical | \n",
" geometry | \n",
"
\n",
" \n",
" \n",
" \n",
" | 0 | \n",
" 4411729 | \n",
" motorway_link | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 25 mph | \n",
" LINESTRING (-83.68891 42.30612, -83.68905 42.3... | \n",
"
\n",
" \n",
" | 1 | \n",
" 4439869 | \n",
" secondary | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 35 mph | \n",
" 0 | \n",
" LINESTRING (-83.73924 42.23667, -83.73924 42.2... | \n",
"
\n",
" \n",
" | 2 | \n",
" 4569607 | \n",
" motorway_link | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 25 mph | \n",
" LINESTRING (-83.68558 42.30703, -83.68526 42.3... | \n",
"
\n",
" \n",
" | 3 | \n",
" 4569609 | \n",
" motorway_link | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 70 mph | \n",
" 0 | \n",
" LINESTRING (-83.83737 42.28964, -83.83664 42.2... | \n",
"
\n",
" \n",
" | 4 | \n",
" 4574780 | \n",
" service | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" 0 | \n",
" LINESTRING (-83.77330 42.26921, -83.77309 42.2... | \n",
"
\n",
" \n",
"
\n",
"
"
],
"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='