/
uxsim.py
3099 lines (2688 loc) · 118 KB
/
uxsim.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
"""
Macroscopic/mesoscopic traffic flow simulator in a network.
"""
import numpy as np
import matplotlib.pyplot as plt
import random, glob, os, csv, time, math, string
import pandas as pd
from PIL import Image, ImageDraw, ImageFont, ImageOps
from PIL.Image import Resampling, Transpose
from tqdm.auto import tqdm
from collections import deque, OrderedDict
from collections import defaultdict as ddict
from .utils import *
from importlib.resources import read_binary #according to official doc, this is also not recommended
import io
from scipy.sparse.csgraph import floyd_warshall
import warnings
plt.rcParams["font.family"] = "monospace"
if "MS Gothic" in plt.rcParams["font.family"]:
plt.rcParams["font.family"] = "MS Gothic"
# ノードクラス
class Node:
"""
Node in a network.
"""
def __init__(s, W, name, x, y, signal=[0], signal_offset=0, flow_capacity=None, auto_rename=False):
"""
Create a node
Parameters
----------
W : object
The world to which the node belongs.
name : str
The name of the node.
x : float
The x-coordinate of the node (for visualization purposes).
y : float
The y-coordinate of the node (for visualization purposes).
signal : list of int, optional
A list representing the signal at the node. Default is [0], representing no signal.
If a signal is present, the list contains the green times for each group.
For example, `signal`=[60, 10, 50, 5] means that this signal has 4 phases, and green time for the 1st group is 60 s.
signal_offset : float, optional
The offset of the signal. Default is 0.
flow_capacity : float, optional
The maximum flow capacity of the node. Default is None, meaning infinite capacity.
auto_rename : bool, optional
Whether to automatically rename the node if the name is already used. Default is False.
Attributes
----------
signal_phase : int
The phase of current signal. Links that have the same `signal_group` have a green signal.
signal_t : float
The elapsed time since the current signal phase started. When it is larger than `Link.signal[Link.signal_phase]`, the phase changes to the next one.
"""
s.W = W
#ノード位置(可視化用)
s.x = x
s.y = y
#流入・流出リンク
s.inlinks = {}
s.outlinks = {}
#リンク間遷移リクエスト(デマンド)
s.incoming_vehicles = []
#発生車両流入待ち行列(vertical queue)
s.generation_queue = deque()
#信号交差点
#signal=[0]であれば信号無し
#信号ありにするときはsignal=[group0の青時間,group1の青時間,...]とする
s.signal = signal
s.signal_phase = 0
s.signal_t = 0
s.signal_offset = signal_offset
offset = s.signal_offset
if s.signal != [0]:
i = 0
while 1:
if offset < s.signal[i]:
s.signal_phase = i
s.signal_t = offset
break
offset -= s.signal[i]
i += 1
if i >= len(s.signal):
i = 0
s.signal_log = []
#流量制限
if flow_capacity != None:
s.flow_capacity = flow_capacity
s.flow_capacity_remain = flow_capacity*s.W.DELTAT
else:
s.flow_capacity = None
s.flow_capacity_remain = 99999999999
s.id = len(s.W.NODES)
s.name = name
if s.name in [n.name for n in s.W.NODES]:
if auto_rename:
s.name = s.name+"_renamed"+"".join(random.choices(string.ascii_letters + string.digits, k=8))
else:
raise ValueError(f"Node name {s.name} already used by another node. Please specify a unique name.")
s.W.NODES.append(s)
def __repr__(s):
return f"<Node {s.name}>"
def signal_control(s):
"""
Updates the signal timings for a traffic signal node.
"""
if s.signal_t > s.signal[s.signal_phase]:
s.signal_phase += 1
s.signal_t = 0
if s.signal_phase >= len(s.signal):
s.signal_phase = 0
s.signal_t += s.W.DELTAT
s.signal_log.append(s.signal_phase)
def flow_capacity_update(s):
"""
flow capacity updates.
"""
if s.flow_capacity != None and s.flow_capacity_remain < s.W.DELTAN:
s.flow_capacity_remain += s.flow_capacity*s.W.DELTAT
def generate(s):
"""
Departs vehicles from the waiting queue.
Notes
-----
If there are vehicles in the generation queue of the node, this method attempts to depart a vehicle to one of the outgoing links.
The choice of the outgoing link is based on the vehicle's route preference for each link. Once a vehicle is departed, it is removed from the generation queue, added to the list of vehicles on the chosen link, and its state is set to "run".
"""
if len(s.generation_queue) > 0:
veh = s.generation_queue[0]
outlinks = list(s.outlinks.values())
if len(outlinks):
preference = [veh.route_pref[l] for l in outlinks]
if sum(preference) > 0:
outlink = random.choices(outlinks, preference)[0]
else:
outlink = random.choices(outlinks)[0]
if (len(outlink.vehicles) == 0 or outlink.vehicles[-1].x > outlink.delta*s.W.DELTAN) and outlink.capacity_in_remain >= s.W.DELTAN:
#受け入れ可能な場合,リンク優先度に応じて選択
veh = s.generation_queue.popleft()
veh.state = "run"
veh.link = outlink
veh.x = 0
veh.v = outlink.u #端部の挙動改善
s.W.VEHICLES_RUNNING[veh.name] = veh
if len(outlink.vehicles) > 0:
veh.leader = outlink.vehicles[-1]
veh.leader.follower = veh
outlink.vehicles.append(veh)
outlink.cum_arrival[-1] += s.W.DELTAN
veh.link_arrival_time = s.W.T*s.W.DELTAT
outlink.capacity_in_remain -= s.W.DELTAN
def transfer(s):
"""
Transfers vehicles between links at the node.
Notes
-----
This method handles the transfer of vehicles from one link to another at the node.
A vehicle is eligible for transfer if:
- The next link it intends to move to has space.
- The vehicle has the right signal phase to proceed.
- The current link has enough capacity to allow the vehicle to exit.
- The node capacity is not exceeded.
"""
for outlink in {veh.route_next_link for veh in s.incoming_vehicles if veh.route_next_link != None}:
if (len(outlink.vehicles) == 0 or outlink.vehicles[-1].x > outlink.delta*s.W.DELTAN) and outlink.capacity_in_remain >= s.W.DELTAN and s.flow_capacity_remain >= s.W.DELTAN:
#受け入れ可能かつ流出可能の場合,リンク優先度に応じて選択
vehs = [
veh for veh in s.incoming_vehicles
if veh.route_next_link == outlink and
(s.signal_phase in veh.link.signal_group or len(s.signal)<=1) and
veh.link.capacity_out_remain >= s.W.DELTAN
]
if len(vehs) == 0:
continue
veh = random.choices(vehs, [veh.link.merge_priority for veh in vehs])[0]
inlink = veh.link
#累積台数関連更新
inlink.cum_departure[-1] += s.W.DELTAN
outlink.cum_arrival[-1] += s.W.DELTAN
inlink.traveltime_actual[int(veh.link_arrival_time/s.W.DELTAT):] = s.W.T*s.W.DELTAT - veh.link_arrival_time #自分の流入時刻より後の実旅行時間も今の実旅行時間で仮決め.後に流出した車両が上書きする前提
veh.link_arrival_time = s.W.T*s.W.DELTAT
inlink.capacity_out_remain -= s.W.DELTAN
outlink.capacity_in_remain -= s.W.DELTAN
if s.flow_capacity != None:
s.flow_capacity_remain -= s.W.DELTAN
#リンク間遷移実行
inlink.vehicles.popleft()
veh.link = outlink
veh.x = 0
if veh.follower != None:
veh.follower.leader = None
veh.follower = None
veh.leader = None
if len(outlink.vehicles):
veh.leader = outlink.vehicles[-1]
veh.leader.follower = veh
#走り残し処理
x_next = veh.move_remain*outlink.u/inlink.u
if veh.leader != None:
x_cong = veh.leader.x_old - veh.link.delta*veh.W.DELTAN
if x_cong < veh.x:
x_cong = veh.x
if x_next > x_cong:
x_next = x_cong
if x_next >= outlink.length:
x_next = outlink.length
veh.x = x_next
outlink.vehicles.append(veh)
s.incoming_vehicles.remove(veh)
s.incoming_vehicles = []
def update(s):
"""
Make necessary updates when the timestep is incremented.
"""
s.signal_control()
s.flow_capacity_update()
# リンククラス
class Link:
"""
Link in a network.
"""
def __init__(s, W, name, start_node, end_node, length, free_flow_speed, jam_density, merge_priority=1, signal_group=0, capacity_out=None, capacity_in=None, eular_dx=None, attribute=None, auto_rename=False):
"""
Create a link
Parameters
----------
W : object
The network to which the link belongs.
name : str
The name of the link.
start_node : str
The name of the start node of the link.
end_node : str
The name of the end node of the link.
length : float
The length of the link.
free_flow_speed : float
The free flow speed on the link.
jam_density : float
The jam density on the link.
merge_priority : float, optional
The priority of the link when merging at the downstream node, default is 1.
signal_group : int or list, optional
The signal group to which the link belongs, default is 0. If `signal_group` is int, say 0, it becomes green if `end_node.signal_phase` is 0. the If `signal_group` is list, say [0,1], it becomes green if the `end_node.signal_phase` is 0 or 1.
capacity_out : float, optional
The capacity out of the link, default is calculated based on other parameters.
capacity_in : float, optional
The capacity into the link, default is calculated based on other parameters.
eular_dx : float, optional
The default space aggregation size for link traffic state computation, default is None. If None, the global eular_dx value is used.
attribute : any, optinonal
Additional (meta) attributes defined by users.
auto_rename : bool, optional
Whether to automatically rename the link if the name is already used. Default is False.
Attributes
----------
speed : float
Average speed of traffic on the link.
density : float
Density of traffic on the link.
flow : float
Flow of traffic on the link.
num_vehicles : float
Number of vehicles on the link.
num_vehicles_queue : float
Number of slow vehicles (due to congestion) on the link.
free_flow_speed : float
Free flow speed of the link.
jam_density : float
Jam density of the link.
capacity_out : float
Capacity for outflow from the link.
capacity_in : float
Capacity for inflow to the link.
merge_priority : float
The priority of the link when merging at the downstream node.
Notes
-----
The `capacity_out` and `capacity_in` parameters are used to set the capacities, and if not provided, they are calculated based on other parameters.
Real-time link status for external reference is maintained with attributes `speed`, `density`, `flow`, `num_vehicles`, and `num_vehicles_queue`.
Some of the traffic flow model parameters can be altered during simulation by changing `free_flow_speed`, `jam_density`, `capacity_out`, `capacity_in`, and `merge_priority`.
"""
s.W = W
#起点・終点ノード
s.start_node = s.W.get_node(start_node)
s.end_node = s.W.get_node(end_node)
#リンク長
s.length = length
#フローモデルパラメータ
s.u = free_flow_speed
s.kappa = jam_density
s.tau = s.W.REACTION_TIME
s.w = 1/s.tau/s.kappa
s.capacity = s.u*s.w*s.kappa/(s.u+s.w)
s.delta = 1/s.kappa
s.q_star = s.capacity #flow capacity
s.k_star = s.capacity/s.u #critical density
#合流時優先度
s.merge_priority = merge_priority
#リンク内車両一覧
s.vehicles = deque()
#旅行時間
s.traveltime_instant = []
#経路選択補正
s.route_choice_penalty = 0
#累積図関係
s.cum_arrival = []
s.cum_departure = []
s.traveltime_actual = []
#信号関係
s.signal_group = signal_group
if type(s.signal_group) == int:
s.signal_group = [s.signal_group]
#流出容量
s.capacity_out = capacity_out
if capacity_out == None:
s.capacity_out = s.capacity*2
#todo_later: capacity_outは微妙にバグがあるらしい(多分離散化誤差).少なくとも未設定時にはバグが顕在化しないように2倍にしている
s.capacity_out_remain = s.capacity_out*s.W.DELTAT
#流入容量
s.capacity_in = capacity_in
if capacity_in == None:
s.capacity_in = s.capacity*2
#todo_later: capacity_inは微妙にバグがあるらしい(多分離散化誤差).少なくとも未設定時にはバグが顕在化しないように2倍にしている
s.capacity_in_remain = s.capacity_in*s.W.DELTAT
s.id = len(s.W.LINKS)
s.name = name
if s.name in [l.name for l in s.W.LINKS]:
if auto_rename:
s.name = s.name+"_renamed"+"".join(random.choices(string.ascii_letters + string.digits, k=8))
else:
raise ValueError(f"Link name {s.name} already used by another link. Please specify a unique name.")
s.W.LINKS.append(s)
s.start_node.outlinks[s.name] = s
s.end_node.inlinks[s.name] = s
s.attribute = attribute
#リアルタイムリンク状態(外部から参照する用)
s._speed = -1 #リンク全体の平均速度
s._density = -1
s._flow = -1
s._num_vehicles = -1 #車両数
s._num_vehicles_queue = -1 #自由流速度未満の車両数
#より正確な車両軌跡
s.tss = []
s.xss = []
s.cs = []
s.names = []
if eular_dx == None:
s.eular_dx = s.length/10
if s.eular_dx < s.u*s.W.DELTAT:
s.eular_dx = s.u*s.W.DELTAT
def __repr__(s):
return f"<Link {s.name}>"
def init_after_tmax_fix(s):
"""
Initalization before simulation execution.
"""
#Euler型交通状態
s.edie_dt = s.W.EULAR_DT
s.edie_dx = s.eular_dx
s.k_mat = np.zeros([int(s.W.TMAX/s.edie_dt)+1, int(s.length/s.edie_dx)])
s.q_mat = np.zeros(s.k_mat.shape)
s.v_mat = np.zeros(s.k_mat.shape)
s.tn_mat = np.zeros(s.k_mat.shape)
s.dn_mat = np.zeros(s.k_mat.shape)
s.an = s.edie_dt*s.edie_dx
#累積
s.traveltime_actual = np.array([s.length/s.u for t in range(s.W.TSIZE)])
def update(s):
"""
Make necessary updates when the timestep is incremented.
"""
s.in_out_flow_constraint()
s.set_traveltime_instant()
s.cum_arrival.append(0)
s.cum_departure.append(0)
if len(s.cum_arrival) > 1:
s.cum_arrival[-1] = s.cum_arrival[-2]
s.cum_departure[-1] = s.cum_departure[-2]
#リアルタイム状態リセット
s._speed = -1
s._density = -1
s._flow = -1
s._num_vehicles = -1
s._num_vehicles_queue = -1
def in_out_flow_constraint(s):
"""
Link capacity updates.
"""
#リンク流入出率を流出容量以下にするための処理
if s.capacity_out_remain < s.W.DELTAN:
s.capacity_out_remain += s.capacity_out*s.W.DELTAT
if s.capacity_in_remain < s.W.DELTAN:
s.capacity_in_remain += s.capacity_in*s.W.DELTAT
def set_traveltime_instant(s):
"""
Compute instantanious travel time.
"""
if s.speed > 0:
s.traveltime_instant.append(s.length/s.speed)
else:
s.traveltime_instant.append(s.length/(s.u/100))
def arrival_count(s, t):
"""
Get cumulative vehicle count of arrival to this link on time t
Parameters
----------
t : float
Time in seconds.
Returns
-------
float
The cumulative arrival vehicle count.
"""
tt = int(t//s.W.DELTAT)
if tt >= len(s.cum_arrival):
return s.cum_arrival[-1]
if tt < 0:
return s.cum_arrival[0]
return s.cum_arrival[tt]
def departure_count(s, t):
"""
Get cumulative vehicle count of departure from this link on time t
Parameters
----------
t : float
Time in seconds.
Returns
-------
float
The cumulative departure vehicle count.
"""
tt = int(t//s.W.DELTAT)
if tt >= len(s.cum_departure):
return s.cum_departure[-1]
if tt < 0:
return s.cum_departure[0]
return s.cum_departure[tt]
def instant_travel_time(s, t):
"""
Get instantanious travel time of this link on time t
Parameters
----------
t : float
Time in seconds.
Returns
-------
float
The instantanious travel time.
"""
tt = int(t//s.W.DELTAT)
if tt >= len(s.traveltime_instant):
return s.traveltime_instant[-1]
if tt < 0:
return s.traveltime_instant[0]
return s.traveltime_instant[tt]
def actual_travel_time(s, t):
"""
Get actual travel time of vehicle who enters this link on time t. Note that small error may occur due to fractional processing.
Parameters
----------
t : float
Time in seconds.
Returns
-------
float
The actual travel time.
"""
tt = int(t//s.W.DELTAT)
if tt >= len(s.traveltime_actual):
return s.traveltime_actual[-1]
if tt < 0:
return s.traveltime_actual[0]
return s.traveltime_actual[tt]
#getter/setter
@property
def speed(s):
if s._speed == -1:
if len(s.vehicles):
s._speed = np.average([veh.v for veh in s.vehicles])
else:
s._speed = s.u
return s._speed
@property
def density(s):
if s._density == -1:
s._density = s.num_vehicles/s.length
return s._density
@property
def flow(s):
if s._flow == -1:
s._flow = s.density*s.speed
return s._flow
@property
def num_vehicles(s):
if s._num_vehicles == -1:
s._num_vehicles = len(s.vehicles)*s.W.DELTAN
return s._num_vehicles
@property
def num_vehicles_queue(s):
if s._num_vehicles_queue == -1:
s._num_vehicles_queue = sum([veh.v < s.u for veh in s.vehicles])*s.W.DELTAN
return s._num_vehicles_queue
@property
def free_flow_speed(s):
return s.u
@free_flow_speed.setter
def free_flow_speed(s, new_value):
if new_value >= 0:
s.u = new_value
s.w = 1/s.tau/s.kappa
s.capacity = s.u*s.w*s.kappa/(s.u+s.w)
s.delta = 1/s.kappa
else:
warnings.warn(f"ignored negative free_flow_speed at {s}", UserWarning)
@property
def jam_density(s):
return s.kappa
@jam_density.setter
def jam_density(s, new_value):
if new_value >= 0:
s.kappa = new_value
s.w = 1/s.tau/s.kappa
s.capacity = s.u*s.w*s.kappa/(s.u+s.w)
s.delta = 1/s.kappa
else:
warnings.warn(f"ignored negative jam_density at {s}", UserWarning)
# 車両クラス
class Vehicle:
"""
Vehicle or platoon in a network.
"""
def __init__(s, W, orig, dest, departure_time, name=None, route_pref=None, route_choice_principle=None, links_prefer=[], links_avoid=[], trip_abort=1, departure_time_is_time_step=0, attribute=None, auto_rename=False):
"""
Create a vehicle (more precisely, platoon)
Parameters
----------
W : object
The world to which the vehicle belongs.
orig : str
The origin node.
dest : str
The destination node.
departure_time : int
The departure time step of the vehicle.
name : str, optional
The name of the vehicle, default is the id of the vehicle.
route_pref : dict, optional
The preference weights for links, default is 0 for all links.
route_choice_principle : str, optional
The route choice principle of the vehicle, default is the network's route choice principle.
links_prefer : list of str, optional
The names of the links the vehicle prefers, default is empty list.
links_avoid : list of str, optional
The names of the links the vehicle avoids, default is empty list.
trip_abort : int, optional
Whether to abort the trip if a dead end is reached, default is 1.
attribute : any, optinonal
Additional (meta) attributes defined by users.
auto_rename : bool, optional
Whether to automatically rename the vehicle if the name is already used. Default is False.
"""
s.W = W
#出発・目的地ノード
s.orig = s.W.get_node(orig)
s.dest = s.W.get_node(dest)
#出発・到着時刻
if departure_time_is_time_step:#互換性のため,departure_timeは常にタイムステップ表記 -> TODO: 要訂正!
s.departure_time = departure_time
else:
s.departure_time = int(departure_time/s.W.DELTAT)
s.arrival_time = -1
s.link_arrival_time = -1
s.travel_time = -1
#状態:home, wait, run,end
s.state = "home"
#リンク内位置
s.link = None
s.x = 0
s.x_next = 0
s.x_old = 0
s.v = 0
#先行・後行車
s.leader = None
s.follower = None
#リンク端部の走り残し処理
s.move_remain = 0
#経路選択
if route_choice_principle == None:
s.route_choice_principle = s.W.route_choice_principle
else:
s.route_choice_principle = route_choice_principle
#希望リンク重み:{link:重み}
s.route_pref = route_pref
if s.route_pref == None:
s.route_pref = {l:0 for l in s.W.LINKS}
#好むリンクと避けるリンク(近視眼的)
s.links_prefer = [s.W.get_link(l) for l in links_prefer]
s.links_avoid = [s.W.get_link(l) for l in links_avoid]
#行き止まりに行ってしまったときにトリップを止める
s.trip_abort = trip_abort
s.flag_trip_aborted = 0
#ログなど
s.log_t = [] #時刻
s.log_state = [] #状態
s.log_link = [] #リンク
s.log_x = [] #位置
s.log_s = [] #車頭距離
s.log_v = [] #現在速度
s.color = (random.random(), random.random(), random.random())
s.log_t_link = [[int(s.departure_time*s.W.DELTAT), "home"]] #新たなリンクに入った時にその時刻とリンクのみを保存.経路分析用
s.attribute = attribute
s.id = len(s.W.VEHICLES)
if name != None:
s.name = name
else:
s.name = str(s.id)
if s.name in [veh.name for veh in s.W.VEHICLES.values()]:
if auto_rename:
s.name = s.name+"_renamed"+"".join(random.choices(string.ascii_letters + string.digits, k=8))
else:
raise ValueError(f"Vehicle name {s.name} already used by another vehicle. Please specify a unique name.")
s.W.VEHICLES[s.name] = s
s.W.VEHICLES_LIVING[s.name] = s
def __repr__(s):
return f"<Vehicle {s.name}: {s.state}, x={s.x}, link={s.link}>"
def update(s):
"""
Updates the vehicle's state and position.
Notes
-----
This method updates the state and position of the vehicle based on its current situation.
- If the vehicle is at "home", it checks if the current time matches its departure time. If so, the vehicle's state is set to "wait" and it is added to the generation queue of its origin node.
- If the vehicle is in the "wait" state, it remains waiting at its departure node.
- If the vehicle is in the "run" state, it updates its speed and position. If the vehicle reaches the end of its current link, it either ends its trip if it has reached its destination, or requests a transfer to the next link.
- If the vehicle's state is "end" or "abort", no further actions are taken.
"""
s.record_log()
if s.state == "home":
#需要生成
if s.W.T >= s.departure_time:
s.state = "wait"
s.orig.generation_queue.append(s)
if s.state == "wait":
#出発ノードで待つ
pass
if s.state == "run":
#走行
s.v = (s.x_next-s.x)/s.W.DELTAT
s.x_old = s.x
s.x = s.x_next
#リンク下流端
if s.x == s.link.length:
if s.link.end_node == s.dest:
#トリップ終了
s.end_trip()
elif len(s.link.end_node.outlinks.values()) == 0 and s.trip_abort == 1:
s.flag_trip_aborted = 1
s.route_next_link = None
s.end_trip()
else:
#リンク間遷移リクエスト
s.route_next_link_choice()
s.link.end_node.incoming_vehicles.append(s)
if s.state in ["end", "abort"] :
#終わり
pass
def end_trip(s):
"""
Procedure when the vehicle finishes its trip.
"""
s.state = "end"
s.link.cum_departure[-1] += s.W.DELTAN
s.link.traveltime_actual[int(s.link_arrival_time/s.W.DELTAT):] = (s.W.T+1)*s.W.DELTAT - s.link_arrival_time #端部の挙動改善 todo: 精査
if s.follower != None:
s.follower.leader = None
s.link.vehicles.popleft()
s.link = None
s.x = 0
s.arrival_time = s.W.T #TODO: arrival_timeもタイムステップ表記.要修正
s.travel_time = (s.arrival_time - s.departure_time)*s.W.DELTAT
s.W.VEHICLES_RUNNING.pop(s.name)
s.W.VEHICLES_LIVING.pop(s.name)
if s.flag_trip_aborted:
s.state = "abort"
s.arrival_time = -1
s.travel_time = -1
s.record_log()
def carfollow(s):
"""
Drive withing a link.
"""
s.x_next = s.x + s.link.u*s.W.DELTAT
if s.leader != None:
x_cong = s.leader.x - s.link.delta*s.W.DELTAN
if x_cong < s.x:
x_cong = s.x
if s.x_next > x_cong:
s.x_next = x_cong
if s.x_next > s.link.length:
s.move_remain = s.x_next - s.link.length
s.x_next = s.link.length
def route_pref_update(s, weight):
"""
Updates the vehicle's link preferences for route choice.
Parameters
----------
weight : float
The weight for updating the link preferences based on the recent travel time.
Should be in the range [0, 1], where 0 means the old preferences are fully retained and 1 means the preferences are completely updated.
Notes
-----
This method updates the link preferences used by the vehicle to select its route based on its current understanding of the system.
- If the vehicle's route choice principle is "homogeneous_DUO", it will update its preferences based on a global, homogenous dynamic user optimization (DUO) model.
- If the route choice principle is "heterogeneous_DUO", it will update its preferences based on a heterogeneous DUO model, considering both its past preferences and the system's current state.
The updated preferences guide the vehicle's decisions in subsequent route choices.
"""
if s.route_choice_principle == "homogeneous_DUO":
s.route_pref = s.W.ROUTECHOICE.route_pref[s.dest.id]
elif s.route_choice_principle == "heterogeneous_DUO":
route_pref_new = {l:0 for l in s.W.LINKS}
k = s.dest.id
for l in s.W.LINKS:
i = l.start_node.id
j = l.end_node.id
if j == s.W.ROUTECHOICE.next[i,k]:
route_pref_new[l] = 1
if sum(list(s.route_pref.values())) == 0:
#最初にpreferenceが空なら確定的に初期化
weight = 1
for l in s.route_pref.keys():
s.route_pref[l] = (1-weight)*s.route_pref[l] + weight*route_pref_new[l]
def route_next_link_choice(s):
"""
Select a next link from the current link.
"""
if s.dest != s.link.end_node:
outlinks = list(s.link.end_node.outlinks.values())
if len(outlinks):
#好むリンク・避けるリンクがあれば優先する
if set(outlinks) & set(s.links_prefer):
outlinks = list(set(outlinks) & set(s.links_prefer))
if set(outlinks) & set(s.links_avoid):
outlinks = list(set(outlinks) - set(s.links_avoid))
preference = [s.route_pref[l] for l in outlinks]
if sum(preference) > 0:
s.route_next_link = random.choices(outlinks, preference)[0]
else:
s.route_next_link = random.choices(outlinks)[0]
else:
s.route_next_link = None
def traveled_route(s):
"""
Returns the route this vehicle traveled.
"""
link_old = -1
t = -1
route = []
ts = []
for i, link in enumerate(s.log_link):
if link_old != link:
route.append(link)
ts.append(s.log_t[i])
link_old = link
return Route(s.W, route[:-1]), ts
def record_log(s):
"""
Record travel logs.
"""
if s.state != "run":
if s.state == "end" and s.log_t_link[-1][1] != "end":
s.log_t_link.append([s.W.T*s.W.DELTAT, "end"])
s.log_t.append(s.W.T*s.W.DELTAT)
s.log_state.append(s.state)
s.log_link.append(-1)
s.log_x.append(-1)
s.log_s.append(-1)
s.log_v.append(-1)
if s.state == "wait":
s.W.analyzer.average_speed_count += 1
s.W.analyzer.average_speed += 0
else:
if len(s.log_link) == 0 or s.log_link[-1] != s.link:
s.log_t_link.append([s.W.T*s.W.DELTAT, s.link])
s.log_t.append(s.W.T*s.W.DELTAT)
s.log_state.append(s.state)
s.log_link.append(s.link)
s.log_x.append(s.x)
s.log_v.append(s.v)
if s.leader != None and s.link == s.leader.link:
s.log_s.append(s.leader.x-s.x)
else:
s.log_s.append(-1)
s.W.analyzer.average_speed_count += 1
s.W.analyzer.average_speed += (s.v - s.W.analyzer.average_speed)/s.W.analyzer.average_speed_count
# 経路選択クラス
class RouteChoice:
"""
Class for computing shortest path for all vehicles.
"""
def __init__(s, W):
"""
Create route choice computation object.
Parameters
----------
W : object
The world to which this belongs.
"""
s.W = W
#リンク旅行時間行列
s.adj_mat_time = np.zeros([len(s.W.NODES), len(s.W.NODES)])
#ij間最短距離
s.dist = np.zeros([len(s.W.NODES), len(s.W.NODES)])
#iからjに行くために次に進むべきノード
s.next = np.zeros([len(s.W.NODES), len(s.W.NODES)])
#iからjに行くために来たノード
s.pred = np.zeros([len(s.W.NODES), len(s.W.NODES)])
#homogeneous DUO用.kに行くための最短経路的上にあれば1
s.route_pref = {k.id: {l:0 for l in s.W.LINKS} for k in s.W.NODES}
def route_search_all(s, infty=np.inf, noise=0):
"""
Compute the current shortest path based on instantanious travel time.
Parameters
----------
infty : float
value representing infinity.
noise : float
very small noise to slightly randomize route choice. useful to eliminate strange results at an initial stage of simulation where many routes has identical travel time.
"""
for link in s.W.LINKS:
i = link.start_node.id
j = link.end_node.id
if s.W.ADJ_MAT[i,j]:
s.adj_mat_time[i,j] = link.traveltime_instant[-1]*random.uniform(1, 1+noise) + link.route_choice_penalty
if link.capacity_in == 0: #流入禁止の場合は通行不可
s.adj_mat_time[i,j] = np.inf
else:
s.adj_mat_time[i,j] = np.inf
s.dist, s.pred = floyd_warshall(s.adj_mat_time, return_predecessors=True)
n_vertices = s.pred.shape[0]
s.next = -np.ones((n_vertices, n_vertices), dtype=int)
for i in range(n_vertices):
for j in range(n_vertices):
# iからjへの最短経路を逆にたどる... -> todo: 起終点を逆にした最短経路探索にすればよい
if i != j:
prev = j
while s.pred[i, prev] != i and s.pred[i, prev] != -9999:
prev = s.pred[i, prev]
s.next[i, j] = prev