코린이/실무를 위한 코딩 기록
[python, GIS] OSMnx를 이용한 최단경로탐색 및 계산
anweh
2020. 11. 4. 15:35
1. 필요한 라이브러리 및 그래프 생성
import osmnx as ox
place = 'Piedmont, California, USA'
G = ox.graph_from_place(place, network_type='drive')
2. 두 점 간의 (거리기반) 최단경로 찾기
'''
1. Basic routing by distance
'''
# 출발지와 목적지 설정
orig = list(G)[0]
dest = list(G)[120]
# 거리 기반 최단경로 1개 탐색
route = ox.shortest_path(G, orig, dest, weight='length')
fig1_1, ax = ox.plot_graph_route(G, route, route_color='y', route_linewidth=6, node_size=0.5)
# 거리 기반 최단경로 여러개 탐색
routes = ox.k_shortest_paths(G, orig, dest, k=30, weight='length')
fig1_2, ax = ox.plot_graph_routes(G, list(routes), route_colors='y', route_linewidth=4, node_size=0.5)
3. 속도와 시간 정보 그래프에 넣기
'''
2. Imputing travel speeds and times
'''
# impute speed on all edges missing data
G = ox.add_edge_speeds(G)
# calculate travel time (seconds) for all edges
G = ox.add_edge_travel_times(G)
# see mean speed/time values by road type
edges = ox.graph_to_gdfs(G, nodes=False)
edges['highway'] = edges['highway'].astype(str)
mean_num = edges.groupby('highway')[['length', 'speed_kph', 'travel_time']].mean().round(1)
4. 거리기반 or 시간기반 최단경로 비교
'''
3. Compare two routes
'''
# calculate two routes by minimizing travel distance vs travel time
orig = list(G)[1]
dest = list(G)[120]
route1 = ox.shortest_path(G, orig, dest, weight='length')
route2 = ox.shortest_path(G, orig, dest, weight='travel_time')
# plot the routes
fig2, ax = ox.plot_graph_routes(G, routes=[route1, route2], route_colors=['r', 'y'],
route_linewidth=6, node_size=0)
route1(빨간색)은 거리 기반의 최단경로이고,
route2(노랑색)은 시간 기반의 최단경로이다.
위의 출력 결과에서 볼 수 있듯이, 동일한 두 개의 노드의 최단 경로가 거리 기반이냐, 시간 기반이냐에 따라 다르게 표시된다.