-
Notifications
You must be signed in to change notification settings - Fork 0
/
osm_net_to_matsim.py
1933 lines (1665 loc) · 56 KB
/
osm_net_to_matsim.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
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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 21 18:48:31 2023
@author: leonefamily
"""
import re
import sys
import json
import momepy
import pyrosm
import logging
import argparse
import itertools
import numpy as np
import pandas as pd
import networkx as nx
import geopandas as gpd
from pathlib import Path
from collections import defaultdict
from shapely.ops import split, unary_union
from typing import Union, Optional, Dict, List, Tuple, Any, Set, Literal
from shapely.geometry import (
LineString, MultiLineString, Point, MultiPoint, Polygon
)
DEFAULT_SPEEDS = {
'motorway': 130,
'motorway_link': 80,
'trunk': 110,
'primary': 90,
'primary_link': 70,
'secondary': 60,
# 'secondary_link': 50,
# 'tertiary': 50,
# 'tertiary_link': 50,
'residential': 30,
'living_street': 20
}
DEFAULT_SPEED = 50
DEFAULT_TRAM_SPEED = 50
DEFAULT_METRO_SPEED = 70
DEFAULT_RAIL_SPEED = 80
DEFAULT_LANES = {
'motorway': 2,
'trunk': 2,
'primary': 2,
# 'secondary': 1,
# 'tertiary': 1,
# 'residential': 1
}
DEFAULT_LANE = 1
SMOOTHNESS_SPEED_COEFFS = {
# 'excellent': 1.0,
'good': 0.9,
'intermediate': 0.7,
'bad': 0.5,
'very_bad': 0.4,
'horrible': 0.3,
'very_horrible': 0.15,
'impassable': 0
}
DEFAULT_SMOOTHNESS_SPEED_COEFF = 1
CATEGORY_CAPACITY_COEFFS = {
'motorway': 1.1,
'motorway_link': 1.1,
# 'trunk': 1,
# 'primary': 1,
# 'primary_link': 1,
'secondary': 0.95,
'secondary_link': 0.95,
'tertiary': 0.9,
'tertiary_link': 0.9,
'residential': 0.8,
'living_street': 0.7
}
DEFAULT_CATEGORY_CAPACITY_COEFF = 1
MAX_LANE_CAPACITY = 1800 # common saturated flow value, vehicle each 2 seconds
DEFAULT_TRAM_CAPACITY = 180 # 3 consists a minute
DEFAULT_METRO_CAPACITY = 60 # 1 consist a minute
DEFAULT_RAIL_CAPACITY = 60 # 1 consist a minute
TO_CRS = 'epsg:5514'
EdgeWithData = Tuple[Tuple[float, float], Tuple[float, float], int, Dict[str, Any]]
NodeWithData = Tuple[Tuple[float, float], Dict[str, Any]]
Edge = Tuple[Tuple[float, float], Tuple[float, float], int]
ForbiddenTurns = AllowedTurns = Set[Tuple[Edge, Edge]]
def parse_args(
args_list: Optional[List[str]] = None
) -> argparse.Namespace:
if args_list is None:
args_list = sys.argv[1:]
parser = argparse.ArgumentParser()
parser.add_argument(
'-p', '--pbf-path',
help='Path to OSM PBF file'
)
parser.add_argument(
'-c', '--crs',
help='Projected (not geographic) CRS of output files',
default=TO_CRS
)
parser.add_argument(
'-o', '--outer-border-poly-path',
help=(
'Path to a polygon'
'Must be in the same CRS as -c/--crs option'
)
)
parser.add_argument(
'-d', '--higher-detail-poly-path',
help=(
'Path to a polygon, in which high detailed roads are kept. '
'Must be in the same CRS as -c/--crs option'
)
)
parser.add_argument(
'-n', '--network-save-path',
help='Save path for ouptut network'
)
parser.add_argument(
'-l', '--lane-definitions-save-path',
help='Save path for lane definitions'
)
parser.add_argument(
'-e', '--edges-save-path',
help='Save path for edges shapefile'
)
parser.add_argument(
'-N', '--nodes-save-path',
help='Save path for nodes shapefile'
)
args = parser.parse_args(args_list)
return args
def get_road_net(
osm: pyrosm.pyrosm.OSM,
crs: str,
higher_detail_poly: Optional[Polygon] = None,
outer_border_poly: Optional[Polygon] = None,
extract_lane_definitions: bool = True,
split_at_stops: bool = True
) -> Tuple[nx.MultiDiGraph, Optional[ForbiddenTurns]]:
"""
Extract road network from OSM and turn it into a cleaned directed graph.
Parameters
----------
osm : pyrosm.pyrosm.OSM
OSM object of pyrosm module with a linked PBF file.
crs: str
Name of coordinate reference system.
higher_detail_poly : Optional[Polygon], optional
Polygon to keep high detail of roads in. The default is None.
outer_border_poly : Optional[Polygon], optional
Polygon to crop net with. The default is None.
extract_lane_definitions : bool, optional
Whether to apply basic turn restrictions from OSM. The default is True.
split_at_stops : Optional[bool], optional
Split links at the locations of tram stops. The default is False.
Turns out, this feature doesn't work much on the road network
Raises
------
RuntimeError
If no edges are found.
Returns
-------
nx.MultiDiGraph
"""
road_net = osm.get_data_by_custom_criteria(
custom_filter={
'area': ['yes'],
'highway': ['cycleway',
'footway',
'path',
'pedestrian',
'steps',
'track',
'corridor',
'elevator',
'escalator',
'proposed',
'construction',
'bridleway',
'abandoned',
'platform',
'raceway'],
'motor_vehicle': ['no'],
'motorcar': ['no'],
'service': ['parking', 'parking_aisle', 'private', 'emergency_access']
},
osm_keys_to_keep=['highway'],
extra_attributes=['railway', 'maxspeed', 'lanes', 'smoothness', 'roundabout'],
filter_type='exclude',
keep_nodes=False,
keep_relations=False
)
if road_net is None:
raise RuntimeError('No road network edges found')
road_net.to_crs(crs, inplace=True)
if outer_border_poly is not None:
road_net = gpd.clip(road_net, outer_border_poly, keep_geom_type=True)
if higher_detail_poly is not None:
road_net.drop(
road_net[
~road_net.within(higher_detail_poly) &
(road_net['highway'].isin(['residential', 'living_street']))
].index,
inplace=True
)
road_net = fix_geometry(road_net)
tags_to_dict(road_net)
if split_at_stops:
road_net = split_links_by_nearest_stops(
osm=osm,
net_gdf=road_net,
outer_border_poly=outer_border_poly,
mode='bus'
)
road_net.loc[
road_net['junction'].isin({'roundabout', 'mini_roundabout'}),
'oneway'
] = 'yes'
rev_road_net = road_net[(road_net['oneway'] != 'yes')].copy()
rev_road_net['geometry'] = rev_road_net['geometry'].apply(
lambda x: LineString(list(x.coords)[::-1])
)
road_net = gpd.GeoDataFrame(
pd.concat([road_net, rev_road_net]), crs=road_net.crs
).reset_index(drop=True)
road_net = road_net[
road_net['railway'].isna() &
(road_net['access'] != 'yes') &
~road_net['highway'].isin([
'pedestrian', 'service', 'cycleway', 'unclassified', 'track',
'footway', 'steps', 'path', 'rest_area', 'construction',
'services', 'raceway', 'bus_stop', 'toll_gantry', 'via_ferrata',
'crossing'
])
]
road_net['lanes'] = road_net['lanes'].apply(get_lanes_number)
road_net['maxspeed'] = road_net['maxspeed'].apply(
convert_maxspeed_to_float
)
guess_road_parameters(road_net)
graph = momepy.gdf_to_nx(road_net, directed=True)
delete_islands(graph)
if extract_lane_definitions:
forbidden_turns = get_all_forbidden_turns(osm, graph)
graph, turnsgraph = check_restrictions_integrity(graph, forbidden_turns)
else:
forbidden_turns = None
return graph, forbidden_turns
def get_stops_geoms(
osm: pyrosm.pyrosm.OSM,
crs: str,
outer_border_poly: Optional[Polygon] = None,
mode: Literal['tram', 'bus', 'rail'] = 'bus'
) -> gpd.GeoDataFrame:
"""
Get stops of the selected mode as nodes.
Parameters
----------
osm : pyrosm.pyrosm.OSM
OSM object of pyrosm module with a linked PBF file.
crs: str
Name of coordinate reference system.
outer_border_poly : Optional[Polygon], optional
Only include stops within this polygon. The default is None.
mode : Literal['tram', 'bus', 'rail'], optional
Stops for which mode. The default is 'bus'.
Returns
-------
gpd.GeoDataFrame
"""
if mode == 'tram':
stops_geoms = osm.get_data_by_custom_criteria(
custom_filter={
'railway': ['tram_stop']
}
)
elif mode == 'bus':
stops_geoms = osm.get_data_by_custom_criteria(
custom_filter={
'highway': ['bus_stop']
}
)
elif mode == 'rail':
stops_geoms = osm.get_data_by_custom_criteria(
custom_filter={
'railway': ['stop']
},
extra_attributes=['tram']
)
stops_geoms.drop(
stops_geoms[stops_geoms['tram'] == 'yes'].index,
inplace=True
)
else:
raise RuntimeError(f'Unsupported mode "{mode}"')
stops_geoms = stops_geoms.to_crs(crs)
stops_geoms.geometry = stops_geoms.centroid
if outer_border_poly is not None:
stops_geoms.drop(
stops_geoms[
~stops_geoms.within(outer_border_poly)
].index,
inplace=True
)
return stops_geoms
def split_links_by_nearest_stops(
osm: pyrosm.pyrosm.OSM,
net_gdf: gpd.GeoDataFrame,
outer_border_poly: Optional[Polygon] = None,
tolerance: Union[int, float] = 10, # meters
mode: Literal['tram', 'bus', 'rail'] = 'tram'
) -> gpd.GeoDataFrame:
"""
Split links by provided stops geometries.
Snap stops that are up to ``tolerance`` meters to links and split.
Parameters
----------
osm : pyrosm.pyrosm.OSM
OSM object of pyrosm module with a linked PBF file.
net_gdf : gpd.GeoDataFrame
Network GeoDataFrame of mode. Preferably after running ``fix_geometry``
outer_border_poly : Optional[Polygon], optional
Only include stops within this polygon. The default is None.
tolerance : Union[int, float], optional
From what distance should stops be snapped. The default is 10 (meters).
mode : Literal['tram', 'bus', 'rail'], optional
For which mode is this network. The default is 'bus'.
Returns
-------
gpd.GeoDataFrame
"""
stops_geoms = get_stops_geoms(
osm=osm,
crs=net_gdf.crs,
outer_border_poly=outer_border_poly,
mode=mode
)
split_bys = defaultdict(set)
for i, row in net_gdf.iterrows():
dists = stops_geoms.distance(row.geometry)
dists = dists[dists < tolerance]
if len(dists) == 0:
continue
for idx in dists.index:
split_bys[i].add(idx)
split_gdf_rows = []
for i, row in net_gdf.iterrows():
if i in split_bys:
orig_geom = row.geometry
splitters = []
for idx in split_bys[i]:
proj_dist = orig_geom.project(stops_geoms.loc[idx, 'geometry'])
proj_stop = orig_geom.interpolate(proj_dist)
splitters.append(proj_stop)
geoms = split(orig_geom, unary_union(splitters))
for geom in list(geoms.geoms):
row_copy = row.copy()
row_copy['geometry'] = geom
split_gdf_rows.append(row_copy)
else:
split_gdf_rows.append(row)
split_gdf = gpd.GeoDataFrame(
split_gdf_rows,
crs=stops_geoms.crs
).reset_index(drop=True)
return split_gdf
def get_tram_net(
osm: pyrosm.pyrosm.OSM,
crs: str,
outer_border_poly: Optional[Polygon] = None,
split_at_stops: bool = True
) -> nx.MultiDiGraph:
"""
Extract tram network from OSM and turn them into a cleaned directed graph.
Parameters
----------
osm : pyrosm.pyrosm.OSM
OSM object of pyrosm module with a linked PBF file.
crs: str
Name of coordinate reference system.
outer_border_poly : Optional[Polygon], optional
Polygon to crop net with. The default is None.
split_at_stops : Optional[bool], optional
Split links at the locations of tram stops. The default is True.
Returns
-------
nx.MultiDiGraph
"""
tram_net = osm.get_data_by_custom_criteria(
custom_filter={
'railway': ['tram']
},
keep_nodes=False,
keep_relations=False,
extra_attributes=['maxspeed', 'railway', 'osmid']
)
if tram_net is None:
logging.info('No tram links were found in the selection')
return nx.MultiDiGraph()
tram_net.to_crs(crs, inplace=True)
if outer_border_poly is not None:
tram_net.drop(
tram_net[
~tram_net.within(outer_border_poly)
].index,
inplace=True
)
tram_net = fix_geometry(tram_net)
tags_to_dict(tram_net)
if split_at_stops:
tram_net = split_links_by_nearest_stops(
osm=osm, net_gdf=tram_net, mode='tram'
)
tram_net['modes'] = 'tram'
tram_net['lanes'] = 1
tram_net['capacity'] = DEFAULT_TRAM_CAPACITY
tram_net['maxspeed'] = tram_net['maxspeed'].apply(convert_maxspeed_to_float)
tram_net.loc[tram_net['maxspeed'].isna(), 'maxspeed'] = DEFAULT_TRAM_SPEED
add_rows = []
rev_rows = []
for i, row in tram_net.iterrows():
if row['tags'] is not None:
if 'railway:preferred_direction' in row['tags']:
if row['tags']['railway:preferred_direction'] == 'backward':
rev_row = row.copy()
rev_geom = LineString(list(row['geometry'].coords)[::-1])
rev_row['geometry'] = rev_geom
rev_rows.append(rev_row)
if row['tags']['railway:preferred_direction'] != 'forward':
add_row = row.copy()
add_geom = LineString(list(row['geometry'].coords)[::-1])
add_row['geometry'] = add_geom
add_rows.append(add_row)
add_gdf = gpd.GeoDataFrame(add_rows, crs=tram_net.crs)
rev_gdf = gpd.GeoDataFrame(rev_rows, crs=tram_net.crs)
tram_net.loc[rev_gdf.index] = rev_gdf
tram_net = gpd.GeoDataFrame(
pd.concat([tram_net, add_gdf]), crs=tram_net.crs
).reset_index(drop=True)
for i, row in tram_net.iterrows():
if row['tags'] is not None:
if 'railway:preferred_direction' in row['tags']:
if row['tags']['railway:preferred_direction'] in ['forward', 'backward']:
tram_net.loc[i, 'oneway'] = 'yes'
graph = momepy.gdf_to_nx(tram_net, directed=True)
delete_islands(graph)
return graph
def get_metro_net(
osm: pyrosm.pyrosm.OSM,
crs: str,
outer_border_poly: Optional[Polygon] = None
) -> nx.MultiDiGraph:
"""
Extract metro network from OSM and turn it into a cleaned directed graph.
Parameters
----------
osm : pyrosm.pyrosm.OSM
OSM object of pyrosm module with a linked PBF file.
crs: str
Name of coordinate reference system.
outer_border_poly : Optional[Polygon], optional
Polygon to crop net with. The default is None.
Returns
-------
nx.MultiDiGraph
"""
metro_net = osm.get_data_by_custom_criteria(
custom_filter={
'railway': ['metro']
},
keep_nodes=False,
keep_relations=False,
extra_attributes=['maxspeed', 'railway', 'osmid']
)
if metro_net is None:
return nx.MultiDiGraph()
metro_net.to_crs(crs, inplace=True)
if outer_border_poly is not None:
metro_net.drop(
metro_net[
~metro_net.within(outer_border_poly)
].index,
inplace=True
)
metro_net = fix_geometry(metro_net)
tags_to_dict(metro_net)
metro_net['modes'] = 'metro'
metro_net['lanes'] = 1
metro_net['capacity'] = DEFAULT_TRAM_CAPACITY
metro_net['maxspeed'] = metro_net['maxspeed'].apply(convert_maxspeed_to_float)
metro_net.loc[metro_net['maxspeed'].isna(), 'maxspeed'] = DEFAULT_METRO_SPEED
add_rows = []
rev_rows = []
for i, row in metro_net.iterrows():
if row['tags'] is not None:
if 'railway:preferred_direction' in row['tags']:
if row['tags']['railway:preferred_direction'] == 'backward':
rev_row = row.copy()
rev_geom = LineString(list(row['geometry'].coords)[::-1])
rev_row['geometry'] = rev_geom
rev_rows.append(rev_row)
if row['tags']['railway:preferred_direction'] != 'forward':
add_row = row.copy()
add_geom = LineString(list(row['geometry'].coords)[::-1])
add_row['geometry'] = add_geom
add_rows.append(add_row)
add_gdf = gpd.GeoDataFrame(add_rows, crs=metro_net.crs)
rev_gdf = gpd.GeoDataFrame(rev_rows, crs=metro_net.crs)
metro_net.loc[rev_gdf.index] = rev_gdf
metro_net = gpd.GeoDataFrame(
pd.concat([metro_net, add_gdf]), crs=metro_net.crs
).reset_index(drop=True)
for i, row in metro_net.iterrows():
if row['tags'] is not None:
if 'railway:preferred_direction' in row['tags']:
if row['tags']['railway:preferred_direction'] in ['forward', 'backward']:
metro_net.loc[i, 'oneway'] = 'yes'
graph = momepy.gdf_to_nx(metro_net, directed=True)
delete_islands(graph)
return graph
def tags_to_dict(
net: gpd.GeoDataFrame
):
"""
Parse string tags in JSON format and keep None unchanged.
Changes are made in place.
Parameters
----------
net : gpd.GeoDataFrame
Any network GeoDataFrame.
"""
net['tags'] = net['tags'].apply(
lambda v: None if v is None else json.loads(v)
)
def get_rail_net(
osm: pyrosm.pyrosm.OSM,
crs: str,
outer_border_poly: Optional[Polygon] = None,
split_at_stops: bool = True
) -> nx.MultiDiGraph:
"""
Extract railways from OSM ways and turn them into a cleaned directed graph.
Omits links marked as 'service'.
Parameters
----------
osm : pyrosm.pyrosm.OSM
OSM object of pyrosm module with a linked PBF file.
crs: str
Name of coordinate reference system.
outer_border_poly : Optional[Polygon], optional
Polygon to crop net with. The default is None.
split_at_stops : Optional[bool], optional
Split links at the locations of rail platforms. The default is True.
Returns
-------
nx.MultiDiGraph
"""
rail_net = osm.get_data_by_custom_criteria(
custom_filter={
'railway': ['rail']
},
keep_relations=False,
extra_attributes=['railway', 'service', 'maxspeed']
)
if rail_net is None:
return nx.MultiDiGraph()
rail_net.to_crs(crs, inplace=True)
if outer_border_poly is not None:
rail_net.drop(
rail_net[
~rail_net.within(outer_border_poly)
].index,
inplace=True
)
rail_net = rail_net[
rail_net['service'].isna()
]
rail_net = fix_geometry(rail_net)
tags_to_dict(rail_net)
if split_at_stops:
rail_net = split_links_by_nearest_stops(
osm=osm,
outer_border_poly=outer_border_poly,
net_gdf=rail_net,
mode='rail',
tolerance=50
)
rail_net['modes'] = 'rail'
rail_net['capacity'] = DEFAULT_RAIL_CAPACITY
rail_net['lanes'] = 1
rail_net['maxspeed'] = rail_net['maxspeed'].apply(convert_maxspeed_to_float)
rail_net.loc[rail_net['maxspeed'].isna(), 'maxspeed'] = DEFAULT_RAIL_SPEED
rev_geoms = rail_net['geometry'].apply(
lambda x: LineString(list(x.coords)[::-1])
)
rev_rail_net = rail_net.copy()
rev_rail_net['geometry'] = rev_geoms
rail_net = gpd.GeoDataFrame(
pd.concat([rail_net, rev_rail_net]), crs=rail_net.crs
).reset_index(drop=True)
graph = momepy.gdf_to_nx(rail_net, directed=True)
delete_islands(graph)
return graph
def guess_road_speed(
row: pd.Series
) -> Union[int, float]:
"""
Estimate car roads' speeds based on OSM attributes.
Parameters
----------
row : pd.Series
Pandas Series with OSM attributes.
Returns
-------
Union[int, float]
"""
speed = DEFAULT_SPEED
if row['highway'] in DEFAULT_SPEEDS:
speed = DEFAULT_SPEEDS[row['highway']]
if row['smoothness'] in SMOOTHNESS_SPEED_COEFFS:
speed *= SMOOTHNESS_SPEED_COEFFS[row['smoothness']]
else:
speed *= DEFAULT_SMOOTHNESS_SPEED_COEFF
return speed
def guess_road_lanes(
row: pd.Series
) -> Union[int, float]:
"""
Estimate car roads' lane count based on OSM attributes.
Parameters
----------
row : pd.Series
Pandas Series with OSM attributes.
Returns
-------
Union[int, float]
"""
lanes = DEFAULT_LANE
if row['highway'] in DEFAULT_LANES:
lanes = DEFAULT_LANES[row['highway']]
return lanes
def deduce_bus_lanes(
net: gpd.GeoDataFrame
) -> gpd.GeoDataFrame:
"""
Change original net lanes count and deduce bus only links from it.
Parameters
----------
net : gpd.GeoDataFrame
OSM network with 'busway' attribute and possibly busway related tags.
Returns
-------
gpd.GeoDataFrame
"""
bus_rows = []
for nr, row in net.iterrows():
if row['tags'] is None:
continue
busway_tags = [t for t in row['tags'] if 'busway' in t]
if busway_tags or not pd.isna(row['busway']):
bus_rows.append(
row.copy()
)
bus_net = gpd.GeoDataFrame(bus_rows, crs=net.crs)
bus_net['lanes'] = 1
return bus_net
def delete_islands(
graph: nx.MultiDiGraph
):
"""
Remove nodes and edges from graph that are not strongly connected.
Parameters
----------
graph : nx.MultiDiGraph
OSM network graph.
"""
logging.info('Deleting islands')
islands = list(nx.strongly_connected_components(graph))
if len(islands) > 1:
conns_num = {i: len(isle) for i, isle in enumerate(islands)}
max_key = max(conns_num, key=conns_num.get)
components = [
graph.subgraph(c).copy() for c
in nx.strongly_connected_components(graph)
]
for i, g in enumerate(components):
if i != max_key:
graph.remove_nodes_from(g.nodes())
graph.remove_edges_from(g.edges())
logging.info(f"Removed {len(components)} islands")
def guess_road_parameters(
net: gpd.GeoDataFrame
):
"""
Estimate lanes count, maxspeed and capacity on car roads.
Parameters
----------
net : gpd.GeoDataFrame
OSM car network.
"""
# where lanes are known, divide by 2, if is not oneway
net.loc[~net['lanes'].isna(), 'lanes'] = net[~net['lanes'].isna()].apply(
lambda r:
r['lanes'] if r['oneway'] == 'yes'
else np.ceil(r['lanes'] / 2), axis=1
)
# estimate possible max. speed
net.loc[net['maxspeed'].isna(), 'maxspeed'] = net[net['maxspeed'].isna()].apply(
guess_road_speed, axis=1
)
net.loc[net['lanes'].isna(), 'lanes'] = net[net['lanes'].isna()].apply(
guess_road_lanes, axis=1
)
bus_net = deduce_bus_lanes(net)
# reduce lanes count by 1, where there are dedicated bus lanes
net.loc[bus_net.index, 'lanes'] = net.loc[bus_net.index, 'lanes'] - 1
# lanes count can be 1 or more
net.loc[net['lanes'] < 1, 'lanes'] = 1
bus_net['modes'] = 'pt'
bus_net['capacity'] = 360 # every 10 seconds
net['modes'] = 'car,truck,pt,bus'
net['capacity'] = net.apply(guess_road_capacity, axis=1)
def convert_maxspeed_to_float(
val: Union[str, int, float, None]
) -> Optional[float]:
"""
Safely convert string speed to float.
Parameters
----------
val : Union[str, int, float, None]
Speed value to be converted.
Returns
-------
Optional[float]
If couldn't convert, returns None.
"""
if val is not None:
if isinstance(val, (int, float)):
return val
if val.isdigit() or val.isdecimal():
return float(val)
def guess_road_capacity(
row: pd.Series
) -> Union[float, int]:
"""
Estimate car road capacity based on speed, category, lanes and smoothness.
Parameters
----------
row : pd.Series
Pandas Series with OSM attributes.
Returns
-------
Union[float, int]
"""
capacity = 100 * row['lanes']
if row['maxspeed'] > 5:
capacity = int(
min(17.5 * row['maxspeed'] + 60, MAX_LANE_CAPACITY)
) * row['lanes']
if row['highway'] in CATEGORY_CAPACITY_COEFFS:
capacity *= CATEGORY_CAPACITY_COEFFS[row['highway']]
else:
capacity *= DEFAULT_CATEGORY_CAPACITY_COEFF
return capacity
def generate_link_string(
fr: str,
to: str,
attrs: Dict[str, str],
add_attrs: Tuple[str] = ('geometry',)
) -> str:
"""
Generate link string with attributes for MATSim.
Geometry is exported as WKT string, if chosen. If attrs is empty or
add_attrs is None or empty, no attributes are written.
Parameters
----------
fr : str
Origin node.
to : str
Destination node.
attrs : Dict[str, str]
Attributes dictionary from graph.
add_attrs : Tuple[str], optional
Keys to write into attribute string. The default is ('geometry',).
Returns
-------
str
"""
l_id = attrs["link_id"]
l_len = max(1, round(attrs["geometry"].length, 2))
l_spd = attrs["freespeed"]
attrstr = generate_attrs_string(
{k: v for k, v in attrs.items() if k in add_attrs}
)
return (
f' <link id="{l_id}" '
f'from="{fr}" to="{to}" '
f'length="{l_len}" '
f'capacity="{int(attrs["capacity"])}" '
f'freespeed="{l_spd}" '
f'modes="{attrs["modes"]}" permlanes="{attrs["permlanes"]}" >\n'
f'{attrstr}'
' </link>\n'
)
def generate_attrs_string(
attrs: Dict[str, str]
) -> str:
"""
Generate attributes string for MATSim link.
Geometry is exported as WKT string, if exists in the dictionary. If attrs
doesn't have elements, empty string is returned.
Parameters
----------
attrs : Dict[str, str]
Attributes dictionary from graph.
Returns
-------
str
"""
s = ' <attributes>\n'
for c, val in attrs.items():
if not pd.isnull(val):
if c == 'geometry':
val = val.wkt
s += f' <attribute name="{c}" class="java.lang.String">{val}</attribute>\n'
return s + ' </attributes>\n'
def assign_nodenums(
graph: nx.MultiDiGraph
):
"""
Set numbers to nodes attributes with 'nodenum' key.
Parameters
----------
graph : nx.MultiDiGraph
Graph with OSM network.
"""
for i, node in enumerate(graph.nodes):
graph.nodes[node]['nodenum'] = i
def write_network(
graph: nx.MultiDiGraph,
outf: Union[str, Path]
):
"""
Write network in MATSim format to disk.
Parameters
----------
graph : nx.MultiDiGraph
OSM network graph.
outf : Union[str, Path]
Output path.
"""
logging.info(f'Writing network {outf}')
bigstring = ''
bigstring += '<?xml version="1.0" encoding="utf-8"?>\n'
bigstring += (
'<!DOCTYPE network SYSTEM '
'"http://matsim.org/files/dtd/network_v2.dtd">\n'