Кратчайшие пути и OD-матрицы¶
В общих функциях Дейкстры и OD выбирайте output="distances", "paths" или "both". Совместные результаты рассчитывают стоимости и пути одними и теми же поисками. Этот ноутбук охватывает запросы от одного источника, от ближайшего источника, от независимых источников, «все со всеми» и попарные запросы, ленивые маршруты и блоки OD. Стоимости измеряются в минутах для time_min и в метрах для length_meter; cutoff включается в диапазон.
# To install IduEdu in a clean environment:
# !pip install IduEdu
OSM_ID = 1114252
from iduedu import get_intermodal_graph
G_intermodal = get_intermodal_graph(osm_id=OSM_ID, clip_by_territory=True)
G_intermodal.update_adjacency_matrix(weight="time_min")
sample_nodes = G_intermodal.nodes_gdf.index[:6].tolist()
source = sample_nodes[0]
destinations = sample_nodes[1:]
print(sample_nodes)
2026-10-22 17:07:07.558 | WARNING | Removing 330 nodes outside the largest strongly connected component. Retaining 21082 of 21412 nodes.
2026-10-22 17:07:07.599 | WARNING | Public transport nodes dropped with the smaller components: {'trolleybus': 2}
[0, 1, 2, 3, 4, 5]
Один маршрут, его стоимость и геометрия¶
single_source_dijkstra(..., output="both") возвращает согласованные Series расстояний и путей. get_path(target) восстанавливает один маршрут из ленивого результата. path_to_edges сохраняет реальную геометрию рёбер и атрибуты транспорта для отображения на карте. У отсутствующих целей стоимость inf и маршрут None.
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from iduedu import path_to_edges, single_source_dijkstra
# Choose a distant graph node so that the resulting route is clearly visible.
source_geometry = G_intermodal.nodes_gdf.loc[source].geometry
route_target = G_intermodal.nodes_gdf.geometry.distance(source_geometry).idxmax()
single_route = single_source_dijkstra(
G_intermodal, source, target_nodes=[route_target],
weight="time_min", output="both", path_storage="lazy",
)
print(f"Travel time: {single_route.distances.loc[route_target]:.1f} min")
node_path = single_route.get_path(route_target) or []
route_edges = path_to_edges(G_intermodal, node_path, weight="time_min")
EDGE_COLORS = {
"walk": ("Walk", "#4d4d4d"),
"bus": ("Bus", "#e41a1c"),
"trolleybus": ("Trolleybus", "#984ea3"),
"tram": ("Tram", "#ff7f00"),
"subway": ("Subway", "#377eb8"),
"boarding": ("Boarding / alighting", "#8c8c8c"),
"alighting": ("Boarding / alighting", "#8c8c8c"),
"subway_station": ("Boarding / alighting", "#8c8c8c"),
}
ROUTE_LINESTYLES = ["-", (0, (7, 3)), (0, (1, 2)), (0, (5, 2, 1, 2))]
def plot_route_by_edge_type(ax, edges, *, linestyle="-", linewidth=1.7, zorder=3):
"""Plot one OD route using edge color for mode and line style for route."""
used_colors = {}
for edge_type, edge_group in edges.groupby("type", sort=False, dropna=False):
label, color = EDGE_COLORS.get(edge_type, ("Other", "#bdbdbd"))
edge_group.plot(
ax=ax,
color=color,
linewidth=linewidth,
linestyle=linestyle,
zorder=zorder,
)
used_colors[label] = color
return used_colors
fig, ax = plt.subplots(figsize=(10, 8))
G_intermodal.edges_gdf.plot(ax=ax, color="#dddddd", linewidth=0.2, alpha=0.4, zorder=1)
used_colors = plot_route_by_edge_type(ax, route_edges, linewidth=1.8)
G_intermodal.nodes_gdf.loc[[source]].plot(
ax=ax, color="#2ca02c", edgecolor="white", linewidth=0.8, markersize=75, zorder=5
)
G_intermodal.nodes_gdf.loc[[route_target]].plot(
ax=ax, color="#1f77b4", edgecolor="white", linewidth=0.8, markersize=75, zorder=5
)
route_handle = Line2D([0], [0], color="#333333", linewidth=2, linestyle="-", label=f"{source} → {route_target}")
mode_handles = [
Line2D([0], [0], color=color, linewidth=2.5, linestyle="-", label=label)
for label, color in used_colors.items()
]
route_legend = ax.legend(handles=[route_handle], title="OD route", loc="upper left")
ax.add_artist(route_legend)
ax.legend(handles=mode_handles, title="Edge type", loc="lower right")
ax.set_title(f"Shortest intermodal route: {len(node_path)} nodes")
ax.set_axis_off()
fig.tight_layout()
Travel time: 53.6 min
Матрицы путей и попарные запросы¶
Используйте od_matrix(output="paths") для матрицы маршрутов по узлам «все со всеми». mode="pairwise" сопоставляет отправления и назначения по позиции и возвращает таблицу с индексом (origin, destination). Совместные попарные результаты содержат и столбец dist, и столбец path.
from iduedu import od_matrix
distance_rank = G_intermodal.nodes_gdf.geometry.distance(source_geometry).sort_values()
rank_positions = [len(distance_rank) // 4, len(distance_rank) // 2, 3 * len(distance_rank) // 4, -1]
matrix_origins = [source, distance_rank.index[len(distance_rank) // 10]]
matrix_destinations = distance_rank.iloc[rank_positions].index.tolist()
path_matrix = od_matrix(
G_intermodal,
origins_nodes=matrix_origins,
destination_nodes=matrix_destinations,
output="paths",
)
pairs = od_matrix(
G_intermodal,
origins_nodes=matrix_origins,
destination_nodes=matrix_destinations[:2],
mode="pairwise",
output="both",
)
print(pairs.distances)
pairwise_paths = pairs.paths
path_matrix
dist
origin destination
0 3839 24.279999
1657 8747 26.286999
| 3839 | 8747 | 14479 | 19240 | |
|---|---|---|---|---|
| 0 | [0, 17165, 1, 7, 15, 17, 20044, 26, 41, 35, 37... | [0, 17165, 1, 7, 15, 17, 20044, 20298, 20538, ... | [0, 17165, 1, 3, 2, 5, 18, 19, 20045, 20299, 2... | [0, 17165, 1, 7, 15, 17, 20044, 20298, 20538, ... |
| 1657 | [1657, 1664, 1577, 1588, 1590, 1586, 1566, 156... | [1657, 1660, 1645, 1698, 1717, 1718, 17488, 17... | [1657, 1660, 1645, 1698, 1885, 1916, 20150, 20... | [1657, 1660, 1645, 1698, 1717, 1718, 17488, 17... |
Несколько маршрутов матрицы на карте¶
Любую непустую ячейку матрицы можно напрямую передать в path_to_edges. На графике ниже наложены все маршруты от первой точки отправления до выбранных назначений. Цвета различают виды транспорта, а сплошные и пунктирные линии — маршруты OD.
fig, ax = plt.subplots(figsize=(10, 8))
G_intermodal.edges_gdf.plot(ax=ax, color="#dddddd", linewidth=0.2, alpha=0.35, zorder=1)
first_origin = path_matrix.index[0]
route_handles = []
all_used_colors = {}
for linestyle, destination in zip(ROUTE_LINESTYLES, path_matrix.columns):
path = path_matrix.loc[first_origin, destination]
if isinstance(path, list):
edges = path_to_edges(G_intermodal, path)
all_used_colors.update(plot_route_by_edge_type(ax, edges, linestyle=linestyle, linewidth=1.7))
route_handles.append(
Line2D(
[0], [0], color="#333333", linewidth=2, linestyle=linestyle, label=f"{first_origin} → {destination}"
)
)
G_intermodal.nodes_gdf.loc[[first_origin]].plot(
ax=ax, color="#2ca02c", edgecolor="white", linewidth=0.8, markersize=75, zorder=5
)
G_intermodal.nodes_gdf.loc[path_matrix.columns].plot(
ax=ax, color="#111111", edgecolor="white", linewidth=0.6, markersize=38, zorder=5
)
mode_handles = [
Line2D([0], [0], color=color, linewidth=2.5, linestyle="-", label=label)
for label, color in all_used_colors.items()
]
route_legend = ax.legend(handles=route_handles, title="OD route", loc="upper left")
ax.add_artist(route_legend)
ax.legend(handles=mode_handles, title="Edge type", loc="lower right", ncol=2)
ax.set_title("All-to-all path matrix: routes from the first origin")
ax.set_axis_off()
fig.tight_layout()
Расстояния от одного источника¶
Подходит для одной точки отправления и многих возможных назначений, например для зоны интермодальной доступности по времени вокруг одной точки.
from iduedu import single_source_dijkstra
single = single_source_dijkstra(
G_intermodal, source, weight="time_min", cutoff=15, output="distances",
)
single.sort_values().head(10)
node
0 0.0
17165 0.151
8 0.612
9 0.972
1 1.413
3 1.472
7 1.48
6 1.491
10 1.523
2 1.549
Name: dist, dtype: Sparse[float32, inf]
Расстояние до ближайшего из нескольких источников¶
Все источники помещаются в одну очередь Дейкстры. Результат даёт расстояние до ближайшего источника, а не строку на каждый источник.
from iduedu import multi_source_dijkstra
multi = multi_source_dijkstra(
G_intermodal, source_nodes=sample_nodes[:3],
weight="time_min", cutoff=15, output="distances",
)
multi.sort_values().head(10)
node
0 0.0
1 0.0
2 0.0
3 0.059
7 0.067
6 0.078
5 0.144
17165 0.151
18 0.213
15 0.217
Name: dist, dtype: Sparse[float32, inf]
Ближайший источник, стоимость и маршрут вместе¶
С output="both" результат поиска от ближайшего источника содержит узел-победитель в nearest_sources. Это идентификаторы узлов графа, даже если у объектов-источников есть собственные метки.
nearest = multi_source_dijkstra(
G_intermodal, source_nodes=sample_nodes[:3], cutoff=15,
output="both", path_storage="lazy",
)
nearest.nearest_sources.to_frame().join(nearest.distances).head(10)
| source_node | dist | |
|---|---|---|
| node | ||
| 0 | 0 | 0.0 |
| 1 | 1 | 0.0 |
| 2 | 2 | 0.0 |
| 3 | 1 | 0.059 |
| 4 | 2 | 1.61 |
| 5 | 2 | 0.144 |
| 6 | 1 | 0.078 |
| 7 | 1 | 0.067 |
| 8 | 0 | 0.612 |
| 9 | 0 | 0.972 |
Независимые параллельные поиски¶
dijkstra_parallel сохраняет строку для каждого источника. В этом отличие от multi_source_dijkstra, которая для каждого узла выбирает только ближайший источник. Ленивое хранение позволяет не создавать все списки маршрутов.
from iduedu import dijkstra_parallel
parallel = dijkstra_parallel(
G_intermodal, source_nodes=sample_nodes[:3], target_nodes=destinations,
weight="time_min", cutoff=15, output="both", path_storage="lazy",
)
parallel.distances
| node | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| 0 | 1.413 | 1.549 | 1.472 | 3.159 | 1.693 |
| 1 | 0.0 | 0.136 | 0.059 | 1.746 | 0.28 |
| 2 | 0.136 | 0.0 | 0.077 | 1.61 | 0.144 |
Расстояния OD и ленивые пути из одних и тех же поисков¶
od_matrix принимает списки узлов или таблицы объектов. Строки соответствуют меткам отправлений, столбцы — меткам назначений. По умолчанию output="distances" возвращает только стоимости; output="both" возвращает ShortestPathResult. get_path(origin, destination) не запускает Дейкстру заново и не создаёт другие маршруты. Обращение к .paths строит и кеширует полную таблицу путей. Ленивое хранение требует output="both".
joint = G_intermodal.od_matrix(
origins_nodes=sample_nodes[:3], destination_nodes=destinations,
weight="time_min", cutoff=30, output="both", path_storage="lazy",
)
print(joint.distances)
print(joint.get_path(source, destinations[0]))
assert not joint.paths_materialized
od_paths = joint.paths
assert joint.paths_materialized
od_paths
1 2 3 4 5
0 1.413 1.549 1.472 3.159 1.693
1 0.0 0.136 0.059 1.746 0.28
2 0.136 0.0 0.077 1.61 0.144
[0, 17165, 1]
| 1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|
| 0 | [0, 17165, 1] | [0, 17165, 1, 3, 2] | [0, 17165, 1, 3] | [0, 17165, 1, 3, 2, 5, 4] | [0, 17165, 1, 3, 2, 5] |
| 1 | [1] | [1, 3, 2] | [1, 3] | [1, 3, 2, 5, 4] | [1, 3, 2, 5] |
| 2 | [2, 3, 1] | [2] | [2, 3] | [2, 5, 4] | [2, 5] |
Обработка строк OD блоками¶
batch_size в полном расчёте ограничивает число одновременных поисков. iter_od_matrix выдаёт блоки строк по отправлениям, поэтому обрабатывайте и освобождайте каждый блок, чтобы ограничить занятую результатами память. В попарном режиме нарезаются и назначения. Ленивые деревья всё равно занимают память, а построение всех маршрутов может быть затратным.
for block in G_intermodal.iter_od_matrix(
origins_nodes=sample_nodes[:5], destination_nodes=destinations,
cutoff=30, output="both", path_storage="lazy", batch_size=2,
):
print(block.distances)
# Inspect selected routes with block.get_path(origin_label, destination_label).
# Process and release this block before requesting the next one.
1 2 3 4 5
0 1.413 1.549 1.472 3.159 1.693
1 0.0 0.136 0.059 1.746 0.28
1 2 3 4 5
2 0.136 0.0 0.077 1.61 0.144
3 0.059 0.077 0.0 1.687 0.221
1 2 3 4 5
4 1.746 1.61 1.687 0.0 1.466
Функции и методы; совместимость¶
Каждая общая функция есть и как метод UrbanGraph: single_source_dijkstra, multi_source_dijkstra, dijkstra_parallel, od_matrix и iter_od_matrix. Таблицы объектов передаются через gdf_sources, gdf_origins или gdf_destinations; существующее сопоставление graph_node_id используется повторно, иначе геометрии сопоставляются с узлами графа. К повторяющимся меткам результата можно обращаться через result.get_path_at(row, column).
single_source_dijkstra_path возвращает один маршрут в виде списка, а multi_source_dijkstra_nearest_source — ближайший источник с расстоянием. threshold — совместимый псевдоним cutoff в функциях OD; передавайте только один из них.