-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathroute.py
831 lines (763 loc) · 24.5 KB
/
route.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
import json
import folium
import plotly.graph_objects as go
from folium import plugins
from . import common, routingkit, types
# ==================== This file contains route plotting code (mode: 'route')
COLOR_UNASSIGNED = common.get_color(0, 0, 0.5)
# ==================== Pre-configured plot profiles
class RoutePlotProfile:
"""
Pre-configured plot profiles for routes.
"""
def __init__(
self,
jpath_route: str = "",
jpath_pos: str = "",
jpath_x: str = "",
jpath_y: str = "",
jpath_unassigned: str = "",
jpath_unassigned_x: str = "",
jpath_unassigned_y: str = "",
):
self.jpath_route = jpath_route
self.jpath_pos = jpath_pos
self.jpath_x = jpath_x
self.jpath_y = jpath_y
self.jpath_unassigned = jpath_unassigned
self.jpath_unassigned_x = jpath_unassigned_x
self.jpath_unassigned_y = jpath_unassigned_y
def __str__(self):
return (
"RoutePlotProfile("
+ f"jpath_route={self.jpath_route}, "
+ f"jpath_pos={self.jpath_pos}, "
+ f"jpath_x={self.jpath_x}, "
+ f"jpath_y={self.jpath_y}, "
+ f"jpath_unassigned={self.jpath_unassigned}, "
+ f"jpath_unassigned_x={self.jpath_unassigned_x}, "
+ f"jpath_unassigned_y={self.jpath_unassigned_y})"
)
# ==================== Route mode argument definition
def arguments(parser):
"""
Defines arguments specific to route plotting.
"""
parser.add_argument(
"--input_route",
type=str,
nargs="?",
default="",
help="path to the route file to plot",
)
parser.add_argument(
"--jpath_route",
type=str,
nargs="?",
default="state.vehicles[*].route",
help="JSON path to the route steps (XPATH like,"
+ " see https://goessner.net/articles/JsonPath/,"
+ ' example: "state.drivers[*].path")',
)
parser.add_argument(
"--jpath_unassigned",
type=str,
nargs="?",
default="state.unassigned",
help="JSON path to the unassigned points. Will plot them separately, if given. "
+ "(e.g. 'state.unassigned'; to skip unassigned points, use empty string: '')",
)
parser.add_argument(
"--jpath_unassigned_x",
type=str,
nargs="?",
default="",
help="JSON path to to the x-coordinate of the unassigned point. If not given, " + "--jpath_x will be used.",
)
parser.add_argument(
"--jpath_unassigned_y",
type=str,
nargs="?",
default="",
help="JSON path to to the y-coordinate of the unassigned point. If not given, " + "--jpath_y will be used.",
)
parser.add_argument(
"--input_pos",
type=str,
nargs="?",
default="",
help="path to file containing the positions, if not supplied by route file",
)
parser.add_argument(
"--jpath_pos",
type=str,
nargs="?",
default="",
help="JSON path to the positions, if routes are stored as indices",
)
parser.add_argument(
"--omit_start",
dest="omit_start",
action="store_true",
default=False,
help="indicates whether to omit the first route location",
)
parser.add_argument(
"--omit_end",
dest="omit_end",
action="store_true",
default=False,
help="indicates whether to omit the first route location",
)
parser.add_argument(
"--omit_short",
type=int,
nargs="?",
default=0,
help="omit routes with less stops than the given value",
)
parser.add_argument(
"--nextroute",
dest="nextroute",
action="store_true",
default=False,
help="overrides jpaths for nextroute outputs",
)
parser.add_argument(
"--route_direction",
type=types.RouteDirectionIndicator,
choices=list(types.RouteDirectionIndicator),
default=types.RouteDirectionIndicator.none.value,
help="specifies how to indicate route direction",
)
parser.add_argument(
"--route_animation_color",
type=str,
nargs="?",
default="FFFFFF",
help="background color of the route when using direction animation (e.g.: 000000)",
)
parser.add_argument(
"--weight_route",
type=float,
nargs="?",
default=1,
help="factor for in-/decreasing thickness of the route (e.g.: 1.5 == 50 percent more weight)",
)
parser.add_argument(
"--no_points",
action="store_true",
help="indicates whether to omit plotting the points in addition to the route",
)
parser.add_argument(
"--weight_points",
type=float,
nargs="?",
default=1,
help="point size (<1 decreases, >1 increases)",
)
parser.add_argument(
"--start_end_markers",
action="store_true",
help="indicates whether to add start and end markers",
)
parser.add_argument(
"--rk_bin",
type=str,
nargs="?",
default="routingkit",
help="path to standalone routingkit binary (uses installed 'routingkit' at default).",
)
parser.add_argument(
"--rk_osm",
type=str,
nargs="?",
default=None,
help=(
"path to the OpenStreetMap data file."
+ " ch-file will be created next to it (or re-used)."
+ " enables road plotting, if provided"
),
)
parser.add_argument(
"--rk_profile",
type=routingkit.RoutingKitProfile,
choices=list(routingkit.RoutingKitProfile),
default=routingkit.RoutingKitProfile.car.value,
help="specifies the travel profile to be used by routingkit",
)
parser.add_argument(
"--rk_distance",
action="store_true",
help="provide routingkit distance information instead of time",
)
# ==================== Route plotting specific functionality
def parse(
input_route: str,
jpath_route: str,
jpath_unassigned: str,
jpath_unassigned_x: str,
jpath_unassigned_y: str,
input_pos: str,
jpath_pos: str,
jpath_x: str,
jpath_y: str,
) -> tuple[list[list[types.Position]], list[list[types.Position]]]:
"""
Parses the route data from the file(s).
"""
# Load json data
content_route, content_pos = common.load_data(input_route, input_pos)
# Extract routes
points = common.extract_position_groups(
content_route,
jpath_route,
content_pos,
jpath_pos,
jpath_x,
jpath_y,
)
# Extract unassigned (if given)
unassigned = []
if jpath_unassigned:
unassigned = common.extract_position_groups(
content_route,
jpath_unassigned,
content_pos,
jpath_pos,
jpath_unassigned_x if jpath_unassigned_x else jpath_x,
jpath_unassigned_y if jpath_unassigned_y else jpath_y,
)
return points, unassigned
def create_plot(
routes: list[types.Route],
unassigned: list[types.Position],
label_x: str,
label_y: str,
plotly_theme: str,
omit_start: bool,
omit_end: bool,
no_points: bool,
weight_points: float,
weight_route: float,
) -> go.Figure:
"""
Plots the given routes on a plotly figure.
"""
# Init plot
fig = go.Figure(
layout=go.Layout(
xaxis_title=label_x,
yaxis_title=label_y,
template=plotly_theme,
margin={"l": 20, "r": 20, "b": 20, "t": 20, "pad": 4},
font={"size": 18},
showlegend=False,
)
)
# Plot the routes
for i, route in enumerate(routes):
if len(route.points) <= 0:
continue
route_line = route.to_polyline(omit_start, omit_end)
xs, ys = [p.lon for p in route_line], [p.lat for p in route_line]
fig.add_trace(
go.Scatter(
x=xs,
y=ys,
mode="lines",
line={"color": route.color.hex, "width": weight_route * 3},
name=f"Route {i+1}",
)
)
if not no_points:
route_points = route.to_points(omit_start, omit_end)
fig.add_trace(
go.Scatter(
x=[p.lon for p in route_points],
y=[p.lat for p in route_points],
mode="markers",
marker={"color": route.color.hex, "size": 5 * weight_points},
name=f"Route {i+1}",
)
)
# Plot the unassigned points
unassigned_points = [p for g in unassigned for p in g]
fig.add_trace(
go.Scatter(
x=[p.lon for p in unassigned_points],
y=[p.lat for p in unassigned_points],
mode="markers",
marker={"color": COLOR_UNASSIGNED, "size": 5 * weight_points},
name="Unassigned",
)
)
# Return figure
return fig
def create_map(
routes: list[types.Route],
unassigned: list[types.Position],
no_points: bool,
weight_points: float,
weight_route: float,
omit_start: bool,
omit_end: bool,
route_direction: types.RouteDirectionIndicator,
route_animation_color: str,
start_end_markers: bool,
custom_map_tile: list[str],
rk_distance: bool,
) -> folium.Map:
"""
Plots the given routes on a folium map.
"""
# Determine bbox
bbox = common.bounding_box([r.points for r in routes])
# Make map plot of routes
m = common.create_map(
(bbox.max_x + bbox.min_x) / 2.0,
(bbox.max_y + bbox.min_y) / 2.0,
custom_map_tile,
)
route_groups = {}
unassigned_group = folium.FeatureGroup("Unassigned")
# Plot the routes themselves
for i, route in enumerate(routes):
if len(route.points) <= 0:
continue
route_groups[route] = folium.FeatureGroup(f"Route {i+1}")
plot_map_route(
route_groups[route],
route,
i,
len(routes),
weight_route,
omit_start,
omit_end,
route_direction,
route_animation_color,
1.0 / 1000.0 if rk_distance else 1.0 / 1000.0,
"km" if rk_distance else "s",
)
# Plot points
if not no_points:
for route in routes:
for p, point in enumerate(route.to_points(omit_start, omit_end)):
d = point.desc.replace("\n", "<br/>").replace(r"`", r"\`")
text = (
"<p>"
+ f"Stop: {p+1} / {len(route.points)}</br>"
+ f"Distance: {point.distance:.2f} km "
+ f"({common.km_to_miles(point.distance):.2f} miles)</br>"
+ f"Location (lon/lat): {point[0]}, {point[1]}"
+ "".join([" " for _ in range(0, 80)])
+ "</p>"
+ f"JSON:</br><pre><code>{d}</code></pre></br>"
)
plot_map_point(
route_groups[route],
point,
text,
weight_points,
route.color.hex,
)
if start_end_markers:
for i, route in enumerate(routes):
points = route.to_points(omit_start, omit_end)
if len(points) > 0:
start = points[0]
d = start.desc.replace("\n", "<br/>").replace(r"`", r"\`")
text = (
"<p>"
+ f"First stop in route {i+1}</br>"
+ f"Location (lon/lat): {start[0]}, {start[1]}"
+ "".join([" " for _ in range(0, 80)])
+ "</p>"
+ f"JSON:</br><pre><code>{d}</code></pre></br>"
)
plot_map_marker(
route_groups[route],
start,
text,
"glyphicon glyphicon-chevron-up",
"lightgray",
)
if len(points) > 1:
end = points[-1]
d = end.desc.replace("\n", "<br/>").replace(r"`", r"\`")
text = (
"<p>"
+ f"Last stop in route {i+1}</br>"
+ f"Location (lon/lat): {end[0]}, {end[1]}"
+ "".join([" " for _ in range(0, 80)])
+ "</p>"
+ f"JSON:</br><pre><code>{d}</code></pre></br>"
)
plot_map_marker(
route_groups[route],
end,
text,
"glyphicon glyphicon-chevron-down",
"black",
)
for group in unassigned:
for p, point in enumerate(group):
d = point.desc.replace("\n", "<br/>").replace(r"`", r"\`")
text = (
"<p>"
+ f"Unassigned point: {p+1} / {len(group)}</br>"
+ f"Location (lon/lat): {point[0]}, {point[1]}"
+ "".join([" " for _ in range(0, 80)])
+ "</p>"
+ f"JSON:</br><pre><code>{d}</code></pre></br>"
)
plot_map_point(unassigned_group, point, text, weight_points, COLOR_UNASSIGNED)
# Add all grouped parts to the map
for k in route_groups:
route_groups[k].add_to(m)
if len(unassigned) > 0:
unassigned_group.add_to(m)
# Add control for all layers and write file
folium.LayerControl().add_to(m)
# Return map
return m
def plot(
input_route: str,
jpath_route: str,
input_pos: str,
jpath_pos: str,
jpath_x: str,
jpath_y: str,
jpath_unassigned: str,
jpath_unassigned_x: str,
jpath_unassigned_y: str,
swap: bool,
coords: str,
omit_start: bool,
omit_end: bool,
omit_short: int,
route_direction: types.RouteDirectionIndicator,
output_image: str,
output_plot: str,
output_map: str,
stats_file: str,
colors: str,
sort_color: bool,
weight_route: float,
weight_points: float,
no_points: bool,
start_end_markers: bool,
rk_osm: str,
rk_bin: str,
rk_profile: routingkit.RoutingKitProfile,
rk_distance: bool,
route_animation_color: str,
custom_map_tile: list[str],
plotly_theme: str,
nextroute: bool,
):
"""
Plots routes based on the given arguments.
Interprets args, reads .json, collects some stats,
plots a .png and plots an interactive .html map.
"""
# Determine base filename
base_name = "plot" # Default for STDIN
if input_route:
base_name = input_route
# Determine profile
profile = RoutePlotProfile(
jpath_route,
jpath_pos,
jpath_x,
jpath_y,
jpath_unassigned,
jpath_unassigned_x,
jpath_unassigned_y,
)
if nextroute:
profile = nextroute_profile()
# Parse data
points, unassigned = parse(
input_route,
profile.jpath_route,
profile.jpath_unassigned,
profile.jpath_unassigned_x,
profile.jpath_unassigned_y,
input_pos,
profile.jpath_pos,
profile.jpath_x,
profile.jpath_y,
)
# Quit on no points
if len(points) <= 0:
print("no points found in given file(s) using given filter(s)")
return
# Conduct some checks
points, world_coords, dataerror = common.preprocess_coordinates(points, swap, coords)
if dataerror:
print(dataerror)
return
if len(unassigned) > 0:
unassigned, world_coords, dataerror = common.preprocess_coordinates(unassigned, swap, coords)
if dataerror:
print(dataerror)
return
# Wrap in routes
routes = [types.Route(r) for r in points] # Wrap it
if len(routes) <= 0:
print(f"no routes could be extracted at the given path: {jpath_route}")
return
# Process routes
for route in routes:
# Collect some statistics of the route
length = 0
for i in range(1, len(route.points)):
if world_coords:
length += common.haversine(
route.points[i],
route.points[i - 1],
)
else:
length += common.euclidean(
route.points[i],
route.points[i - 1],
)
route.points[i].distance = length
route.length = length
# Determine route shapes (if routingkit is available)
if rk_osm:
routingkit.query_routes(rk_bin, rk_osm, routes, rk_profile, rk_distance)
# Dump some stats
statistics(routes, unassigned, stats_file, world_coords)
# Determine bbox
bbox = common.bounding_box([r.points for r in routes])
# Make simple plot of routes
aspect_ratio = (bbox.height) / (bbox.width) if bbox.width > 0 else 1
# Remove short routes
if omit_short > 0:
routes = [r for r in routes if len(r.points) > omit_short]
# Prepares colors for the groups
common.prepare_colors(routes, colors, sort_color)
# Create figure
fig = create_plot(
routes,
unassigned,
"lon" if world_coords else "x",
"lat" if world_coords else "y",
plotly_theme,
omit_start,
omit_end,
no_points,
weight_points,
weight_route,
)
# Save interactive plot
plot_file = output_plot
if not plot_file:
plot_file = base_name + ".plot.html"
print(f"Plotting interactive plot to {plot_file}")
fig.write_html(plot_file)
# Save plot image
image_file = output_image
if not image_file:
image_file = base_name + ".plot.png"
print(f"Plotting image to {image_file}")
fig.write_image(
image_file,
width=min(common.IMAGE_SIZE, common.IMAGE_SIZE / aspect_ratio),
height=min(common.IMAGE_SIZE, common.IMAGE_SIZE * aspect_ratio),
)
# Skip plotting on map, if no geo-coordinates
if not world_coords:
print("No world coordinates, skipping map plotting")
quit()
# Create map
m = create_map(
routes,
unassigned,
no_points,
weight_points,
weight_route,
omit_start,
omit_end,
route_direction,
route_animation_color,
start_end_markers,
custom_map_tile,
rk_distance,
)
# Save map
map_file = output_map
if not map_file:
map_file = base_name + ".map.html"
print(f"Plotting map to {map_file}")
m.save(map_file)
def nextroute_profile() -> RoutePlotProfile:
"""
Returns the nextroute profile.
"""
return RoutePlotProfile(
jpath_route="solutions[-1].vehicles[*].route",
jpath_x="stop.location.lon",
jpath_y="stop.location.lat",
jpath_unassigned="solutions[-1].unplanned",
jpath_unassigned_x="location.lon",
jpath_unassigned_y="location.lat",
)
def plot_map_point(map, point, text, weight, color):
"""
Plots a point on the given map.
"""
popup_text = folium.Html(text, script=True)
popup = folium.Popup(popup_text, max_width=450, sticky=True)
marker = folium.CircleMarker(
(point[1], point[0]), # folium operates on lat/lon
color=color,
popup=popup,
radius=3 * weight,
fill=True,
fillOpacity=1.0,
)
marker.options["fillOpacity"] = 1.0
marker.add_to(map)
def plot_map_marker(map, point, text, icon, color):
"""
Plots a marker on the given map.
"""
popup_text = folium.Html(text, script=True)
popup = folium.Popup(popup_text, max_width=450, sticky=True)
marker = folium.Marker(
(point[1], point[0]), # folium operates on lat/lon
popup=popup,
icon=folium.Icon(color=color, icon=icon),
)
marker.add_to(map)
def plot_map_route(
map: object,
route: types.Route,
route_idx: int,
route_count: int,
weight: float,
omit_start: bool,
omit_end: bool,
direction: types.RouteDirectionIndicator = types.RouteDirectionIndicator.none,
animation_bg_color: str = "FFFFFF",
rk_factor: float = None,
rk_unit: str = None,
):
"""
Plots a route on the given map.
"""
rk_text = ""
if route.legs is not None:
rk_text = f"Route cost (routingkit): {sum(route.leg_costs) * rk_factor:.2f} {rk_unit}</br>"
popup_text = folium.Html(
"<p>"
+ f"Route: {route_idx+1} / {route_count}</br>"
+ f"Route points: {len(route.points)}</br>"
+ f"Route length: {route.length:.2f} km ({common.km_to_miles(route.length):.2f} miles)</br>"
+ rk_text
+ "</p>",
script=True,
)
popup = folium.Popup(popup_text, max_width=450, sticky=True)
# Prepare polyling of route (folium operates on lat/lon)
raw_line = [(p.lat, p.lon) for p in route.to_polyline(omit_start, omit_end)]
if len(raw_line) <= 0:
return
if direction == types.RouteDirectionIndicator.none:
folium.PolyLine(
raw_line,
color=route.color.hex,
popup=popup,
weight=5 * weight,
).add_to(map)
elif direction == types.RouteDirectionIndicator.arrow:
polyline = folium.PolyLine(
raw_line,
color=route.color.hex,
popup=popup,
weight=5,
)
polyline.add_to(map)
plugins.PolyLineTextPath(
polyline,
"\u25BA ",
repeat=True,
center=True,
offset=10.35 * weight,
attributes={"fill": route.color.hex, "font-size": f"{300*weight}%"},
).add_to(map)
elif direction == types.RouteDirectionIndicator.animation:
plugins.AntPath(
locations=raw_line,
dash_array=[20, 30],
color=f"#{animation_bg_color}",
pulse_color=route.color.hex,
delay=1000,
popup=popup,
weight=5 * weight,
opacity=1,
).add_to(map)
else:
raise Exception(f"unknown direction indicator {direction}")
def statistics(
routes: list[types.Route],
unassigned: list[list[types.Point]],
stats_file: str,
world_coords: bool,
):
"""
Outlines some route statistics. Statistics are written to file, if provided.
"""
# Collect statistics
stops = [len(r.points) for r in routes]
lengths = [r.length for r in routes]
diameters = []
for r in routes:
max_diameter = 0
for p1 in r.points:
for p2 in r.points:
if world_coords:
distance = common.haversine(p1, p2)
else:
distance = common.euclidean(p1, p2)
if distance > max_diameter:
max_diameter = distance
diameters.append(max_diameter)
stats = [
types.Stat("nroutes", "Route count", len(routes)),
types.Stat("nstops_max", "Route stops (max)", max(stops)),
types.Stat("nstops_min", "Route stops (min)", min(stops)),
types.Stat("nstops_avg", "Route stops (avg)", sum(stops) / float(len(routes))),
types.Stat("nstops_total", "Route stops (total)", sum(stops)),
types.Stat("length_max", "Route length (max)", max(lengths)),
types.Stat("length_min", "Route length (min)", min(lengths)),
types.Stat("length_avg", "Route length (avg)", sum(lengths) / float(len(routes))),
types.Stat("length_total", "Route length (total)", sum(lengths)),
types.Stat("diameter_max", "Route diameter (max)", max(diameters)),
types.Stat("diameter_min", "Route diameter (min)", min(diameters)),
types.Stat("diameter_avg", "Route diameter (avg)", sum(diameters) / float(len(routes))),
types.Stat("nunassigned", "Unassigned stops", sum([len(g) for g in unassigned])),
]
if all((r.legs is not None) for r in routes):
costs = [sum(r.leg_costs) for r in routes]
stats.extend(
[
types.Stat("costs_max", "RK costs (max)", max(costs)),
types.Stat("costs_min", "RK costs (min)", min(costs)),
types.Stat("costs_avg", "RK costs (avg)", sum(costs) / float(len(routes))),
]
)
# Log statistics
print("Route stats")
for stat in stats:
print(f"{stat.desc}: {stat.val:.2f}")
# Write statistics to file
if stats_file:
stats_table = {}
for stat in stats:
stats_table[stat.name] = stat.val
with open(stats_file, "w+") as f:
json.dump(stats_table, f)