-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvehicle_navigation_shortest_path.py
303 lines (225 loc) · 12 KB
/
vehicle_navigation_shortest_path.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
# -*- coding: utf-8 -*-
"""Vehicle_Navigation-Shortest_Path.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/103unhaid5NTquk2vVaEhzRrYFdc7e2Y5
"""
!pip install osmnx==0.16.2
!pip install contextily
# Commented out IPython magic to ensure Python compatibility.
#Import necessary libraries.
import numpy as np
import math
import folium
import contextily as ctx
import shapely
import osmnx as ox
import geopandas as gpd
from pyproj import Transformer
from shapely.geometry import Point, Polygon, LineString
from matplotlib.ticker import FormatStrFormatter
from matplotlib.patches import Circle
from osgeo import ogr
import matplotlib.pyplot as plt
# %matplotlib inline
def pointreproject(point_x,point_y,inp_CRS,out_CRS):
"""Converts from (latitude, longitude) to native map projection (x,y) coordinates and vice versa.
Args:
point_x: input CRS coordinate (x or latitude).
point_y: input CRS coordinate (y or longitude).
inp_CRS: reference system of input coordinates: 'epsg:4326','epsg:3857'...
out_CRS: reference system of output coordinates: 'epsg:4326','epsg:3857'...
Returns:
A tuple (latitude, longitude) or (x,y) of the reprojected coordinates of the input point in the output CRS.
"""
transformer = Transformer.from_crs(inp_CRS, out_CRS)
out_x,out_y = transformer.transform(point_x, point_y)
transformer = []
return out_x,out_y
def rgraphfrompoints(starting_point,ending_point):
"""Creates a graph, with edges (roads) and nodes (road intersections), based on the two given points.
The two given points must be in the WGS84 coordinate reference system and in the form of (latitude, longitude).
Args:
starting_point: the route's starting point. -> A tuple of (latitude, longitude).
ending_point: the route's ending point. -> A tuple of (latitude, longitude).
Returns:
A reprojected (from EPSG:4326 to EPSG:3857) MultiDiGraph from the osmnx package.
"""
#Input points geographical coordinates.
lat1 = starting_point[0]
lat2 = ending_point[0]
long1 = starting_point[1]
long2 = ending_point[1]
#Find the function's argument values.
north = lat2
south = lat1
if lat1 > lat2:
north = lat1
south = lat2
east = long2
west = long1
if long1 > long2:
east = long1
west = long2
#Construct the road graph.
roadgraph = ox.graph_from_bbox(north+0.01, south-0.01, east+0.01, west-0.01, network_type = 'drive', simplify=False )
#Reproject the road graph.
projected_roadgraph = ox.projection.project_graph(roadgraph, to_crs='epsg:3857')
return projected_roadgraph
def nearest_edge_node_id(point,roadgraph):
"""Finds the nearest network's node id for the given point, which lies in the nearest network edge.
Input Point -> Nearest Edge Point -> Nearest Network Node (Route Starting/Ending Point).
The given point's coordinates must be in the EPSG:4326.
Args:
point: The point:(latitude, longitude) that needs to be transfered to the nearest network node..
roadgraph: A reprojected (from EPSG:4326 to EPSG:3857) MultiDiGraph from the osmnx package.
Returns:
The nearest network's node id for the given point, which is in the nearest network edge.
"""
#Reproject point coordinates from EPSG:4326 to the EPSG:3857.
point_x, point_y = pointreproject(point[0], point[1],'epsg:4326','epsg:3857')
#Find the nearest road.
_, _, _, nearest_road = ox.distance.get_nearest_edge(roadgraph, (point_y,point_x), return_geom=True)
#Find all point coordinates that are constructing the specific road.
nearest_road_coords = np.array(nearest_road.xy)
#Calculate all distances between the input point and all the points constructing the nearest road line.
e_distances = []
for i in range(0,nearest_road_coords[0].size):
e_dist = ox.distance.euclidean_dist_vec(point_y,point_x,nearest_road_coords[1][i],nearest_road_coords[0][i])
e_distances.append(e_dist)
mindist = min(e_distances)
for i in range(0,len(e_distances)):
if e_distances[i]==mindist: pos=i
#Nearest edge node coordinates.
nearest_edge_node_x = nearest_road_coords[0][pos]
nearest_edge_node_y = nearest_road_coords[1][pos]
#Find the nearest network's node id, which has the minimum distance from the road point that has the minimum distance from the input point.
node_id= ox.distance.get_nearest_node(roadgraph, (nearest_edge_node_y,nearest_edge_node_x), method='euclidean')
return node_id
def pointreproject2edge(point,roadgraph):
"""
Finds the nearest network's edge for the given point, and reprojects it perpendicularly to its nearest edge.
If the orthogonal projection of the point lies outside the nearest edge's nodes, then the point isn't reprojected
but it is transferred to the nearest network node instead.
The given point's coordinates must be in the EPSG:4326, and following the form of (latitude, longitude).
Args:
point: The point:(latitude, longitude) that needs to be projected to the nearest network edge.
roadgraph: A MultiDiGraph (EPSG:3857) from the osmnx package.
Returns:
A tuple (latitude, longitude) of the reprojected coordinates of the input point.
"""
#Reproject point coordinates from EPSG:4326 to the EPSG:3857.
point_x, point_y = pointreproject(point[0], point[1],'epsg:4326','epsg:3857')
#Find the nearest road.
_, _, _, nearest_road, dist__pp = ox.distance.get_nearest_edge(roadgraph, (point_y,point_x), return_geom=True, return_dist=True)
#Extract the nearest road coordinates.
nearest_road_coords = np.array(nearest_road.xy)
#Calculate the euclidean distance between the input point and the nearest edge's first node.
dist__pv = ox.distance.euclidean_dist_vec(point_y,point_x,nearest_road_coords[1][0],nearest_road_coords[0][0])
#Calculate the hypotenuse.
dist = np.sqrt(dist__pv**2-dist__pp**2)
#Create the corresponding circle.
circle = Point(nearest_road_coords[0][0], nearest_road_coords[1][0]).buffer(dist).boundary
#Find the circle's intersection point with the given edge.
intersection_points = circle.intersection(nearest_road)
lies_in = False
#If the orthogonal projection of the point lies inside the nearest edge's nodes.
if type(intersection_points) == shapely.geometry.point.Point:
lies_in = True
intersection_point_x = intersection_points.x
intersection_point_y = intersection_points.y
#If the orthogonal projection of the point lies outside the nearest edge's nodes.
else:
gdf = ox.utils_graph.graph_to_gdfs(roadgraph)
nodes_gdf = gdf[0].reset_index(drop=True)
nearest_node_id = nearest_edge_node_id(point,roadgraph)
intersection_point_x = nodes_gdf.loc[(nodes_gdf['osmid']==nearest_node_id)].x.values[0]
intersection_point_y = nodes_gdf.loc[(nodes_gdf['osmid']==nearest_node_id)].y.values[0]
#Find the nearest node id from the intersection point.
node_id = ox.distance.get_nearest_node(roadgraph, (intersection_point_y,intersection_point_x), method='euclidean')
#Reproject the calculated grid point from epsg:3857 to epsg:4326.
point_lat, point_long = pointreproject(intersection_point_x, intersection_point_y,'epsg:3857','epsg:4326')
return point_lat, point_long, lies_in
def routeplot(starting_point,ending_point):
"""
Finds and plots the sortest route -based on Dijkstra's pathfinding algorithm- between the
two given points in the given roadgraph.The given points coordinates must be in the EPSG:4326
and they must be following the form of (latitude, longitude).
Args:
starting_point: the route's starting point. -> A tuple of (latitude, longitude).
ending_point: the route's ending point. -> A tuple of (latitude, longitude).
Returns:
A Folium map with the given starting and ending points and the shortest path between them.
"""
#Calculate the roadgraph between the starting and ending points.
roadgraph = rgraphfrompoints(starting_point,ending_point)
#Find the routes starting end ending point which lies inside the given roadgraph.
p_lat1,p_long1,lies_in1 = pointreproject2edge(starting_point,roadgraph)
p_lat2,p_long2,lies_in2 = pointreproject2edge(ending_point,roadgraph)
#Find the nearest edge node id.
node1_id = nearest_edge_node_id(starting_point,roadgraph)
node2_id = nearest_edge_node_id(ending_point,roadgraph)
#Calculate the sortest path between the two given nodes.
nodeids = ox.shortest_path(roadgraph, node1_id, node2_id)
#Create the necessary geodataframes.
gdf = ox.utils_graph.graph_to_gdfs(roadgraph)
nodes_gdf = gdf[0].reset_index(drop=True)
#Map's center point.
center_lat = (starting_point[0]+ending_point[0])/2
center_long = (starting_point[1]+ending_point[1])/2
center = [center_lat,center_long]
#Define the map.
m = folium.Map(location=center, zoom_start=13, crs='EPSG3857')
#Plot Original points.
folium.Marker((starting_point[0], starting_point[1]),
popup="Original Starting Point", tooltip="Original Starting Point",
icon=folium.Icon(color='pink', icon="fas fa-car", prefix='fa')).add_to(m);
folium.Marker((ending_point[0], ending_point[1]),
popup="Original Destination", tooltip="Original Destination",
icon=folium.Icon(color='pink', icon="fas fa-crosshairs", prefix='fa')).add_to(m);
#Plot Starting and Destination points.
folium.Marker((p_lat1,p_long1),
popup="Starting Point", tooltip="Starting Point",
icon=folium.Icon(color='darkblue', icon="fas fa-car", prefix='fa')).add_to(m);
folium.Marker((p_lat2,p_long2),
popup="Destination", tooltip="Destination",
icon=folium.Icon(color='darkblue', icon="fas fa-crosshairs", prefix='fa')).add_to(m);
#Create a list of tuples (locations) for each of route's node coordinates.
locations = []
locations.append((p_lat1,p_long1)) #Add the starting point to the route.
for node_id in nodeids:
p_lat = nodes_gdf.loc[(nodes_gdf['osmid']==node_id)].lat.values[0]
p_long = nodes_gdf.loc[(nodes_gdf['osmid']==node_id)].lon.values[0]
locations.append((p_lat,p_long))
locations.append((p_lat2,p_long2)) #Add the ending point to the route.
#Cut the final route segment if the starting point lies in it.
if lies_in1:
r1 = pointreproject(locations[1][0],locations[1][1],'epsg:4326','epsg:3857')
r2 = pointreproject(locations[2][0],locations[2][1],'epsg:4326','epsg:3857')
road1 = LineString([r1,r2])
point1_x, point1_y = pointreproject(p_lat1,p_long1,'epsg:4326','epsg:3857')
point1 = Point(point1_x, point1_y)
if road1.distance(point1) < 1e-8 :del locations[1]
#Cut the final route segment if the ending point lies in it.
if lies_in2:
r3 = pointreproject(locations[-3][0],locations[-3][1],'epsg:4326','epsg:3857')
r4 = pointreproject(locations[-2][0],locations[-2][1],'epsg:4326','epsg:3857')
road2 = LineString([r3,r4])
point2_x, point2_y = pointreproject(p_lat2,p_long2,'epsg:4326','epsg:3857')
point2 = Point(point2_x, point2_y)
if road2.distance(point2) < 1e-8 :del locations[-2]
#Create a folium polyline from the list of "locations".
route = folium.PolyLine(locations=locations,tooltip='Route', smooth_factor=0.3, color="purple", weight=2.5, opacity=1)
#Plot route.
route.add_to(m);
#Save map to html file.
m.save('route.html') #saves the .html file in the local directory.
#Plot map.
return m
#Random points to WGS84 between latitude of 37.9000-38.0000 degrees and longitude of 23.7000-23.8000 degrees. (Athens, Attiki, Greece)
starting_point = (round(37.9+np.random.random()/10,4),round(23.7+np.random.random()/10,4))
ending_point = (round(37.9+np.random.random()/10,4),round(23.7+np.random.random()/10,4))
#Plot the route between starting and ending point.
routeplot(starting_point,ending_point)
#Print a .txt file with the code requirements.
!pip freeze > /content/drive/MyDrive/Projects/Python_Projects/Vehicle_Navigation-Sortest_Path/requirements.txt