-
Notifications
You must be signed in to change notification settings - Fork 4
/
plan_handlers.py
1610 lines (1285 loc) · 59.1 KB
/
plan_handlers.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
import numpy as np
from math import floor
import pandas as pd
from datetime import datetime, timedelta
from typing import Optional
import logging
import json
from elara.factory import Tool, WorkStation
class PlanHandlerTool(Tool):
"""
Base Tool class for Plan Handling.
"""
options_enabled = True
def __init__(self, config, mode=None, groupby_person_attribute=None, **kwargs):
self.logger = logging.getLogger(__name__)
super().__init__(config=config, mode=mode, groupby_person_attribute=groupby_person_attribute, **kwargs)
def build(
self,
resources: dict,
write_path=None) -> None:
super().build(resources, write_path)
def extract_mode_from_route_elem(self, leg_mode, route_elem):
"""
Extract mode and route identifieers from a MATSim route xml element.
"""
if self.config.version == 11:
if leg_mode == "pt":
return self.extract_mode_from_v11_route_elem(route_elem)
return leg_mode
return leg_mode
def extract_mode_from_v11_route_elem(self, route_elem):
"""
Extract mode and route identifieers from a MATSim v12 route xml element.
"""
route = route_elem.text.split('===')[-2]
mode = self.resources['transit_schedule'].route_to_mode_map.get(route)
return mode
def extract_routeid_from_v12_route_elem(self, route_elem):
"""
Extract mode and route identifieers from a route xml element.
"""
route_dict = json.loads(route_elem.text.strip())
route = route_dict["transitRouteId"]
return route
@staticmethod
def get_furthest_mode(modes):
"""
Return key with greatest value. Note that in the case of join max, the first is returned only.
"""
if len(modes) > 2 and 'transit_walk' in modes:
del modes['transit_walk']
return max(modes, key=modes.get)
@staticmethod
def generate_indices_map(list_in):
"""
Generate element ID list and index dictionary from given list.
:param list_in: list
:return: (list, list_indices_map)
"""
list_indices_map = {
key: value for (key, value) in zip(list_in, range(0, len(list_in)))
}
return list_in, list_indices_map
class ModeShares(PlanHandlerTool):
"""
Extract Mode Share from Plans.
"""
requirements = [
'plans',
'attributes',
'transit_schedule',
'output_config',
]
valid_modes = ['all']
def __init__(self, config, mode=None, groupby_person_attribute=None, **kwargs) -> None:
"""
Initiate Handler.
:param config: Config
:param mode: str, mode
"""
super().__init__(config=config, mode=mode, groupby_person_attribute=groupby_person_attribute, **kwargs)
self.mode = mode # todo options not implemented
self.groupby_person_attribute = groupby_person_attribute
self.modes = None
self.mode_indices = None
self.classes = None
self.class_indices = None
self.mode_counts = None
self.results = None
# Initialise results storage
self.results = dict() # Result geodataframes ready to export
def build(self, resources: dict, write_path=None) -> None:
"""
Build Handler.
:param resources: dict, supplier resources
:param write_path: Optional output path overwrite
"""
super().build(resources, write_path=write_path)
modes = list(set(self.resources['output_config'].modes + self.resources['transit_schedule'].modes))
self.logger.debug(f'modes = {modes}')
# Initialise mode classes
self.modes, self.mode_indices = self.generate_id_map(modes)
if self.groupby_person_attribute:
self.attributes = self.resources["attributes"]
availability = self.attributes.attribute_key_availability(self.groupby_person_attribute)
self.logger.debug(f'availability of attribute {self.groupby_person_attribute} = {availability*100}%')
if availability < 1:
self.logger.warning(f'availability of attribute {self.groupby_person_attribute} = {availability*100}%')
found_attributes = self.resources['attributes'].attribute_values(self.groupby_person_attribute) | {None}
else:
self.attributes = {}
found_attributes = [None]
self.logger.debug(f'attributes = {found_attributes}')
# Initialise class classes
self.classes, self.class_indices = self.generate_id_map(found_attributes)
# Initialise mode count table
self.mode_counts = np.zeros((
len(self.modes),
len(self.classes),
self.config.time_periods))
self.results = dict()
def process_plans(self, elem):
"""
Iteratively aggregate 'vehicle enters traffic' and 'vehicle exits traffic'
events to determine link volume counts.
:param elem: Plan XML element
"""
for plan in elem.xpath(".//plan"):
if plan.get('selected') == 'yes':
ident = elem.get('id')
attribute_class = self.attributes.get(ident, {}).get(self.groupby_person_attribute)
end_time = None
modes = {}
for stage in plan:
if stage.tag == 'leg':
leg_mode = stage.get('mode')
route_elem = stage.xpath('route')[0]
mode = self.extract_mode_from_route_elem(leg_mode, route_elem)
distance = float(route_elem.get("distance", 0))
mode = {"egress_walk":"walk", "access_walk":"walk"}.get(mode, mode) # ignore access and egress walk
modes[mode] = modes.get(mode, 0) + distance
elif stage.tag == 'activity':
if stage.get('type') == 'pt interaction': # ignore pt interaction activities
continue
# only add activity modes when there has been previous activity
# (ie trip start time)
if end_time:
mode = self.get_furthest_mode(modes)
x, y, z = self.table_position(
mode,
attribute_class,
end_time
)
self.mode_counts[x, y, z] += 1
# update endtime for next activity
end_time = convert_time_to_seconds(stage.get('end_time'))
# reset modes
modes = {}
def finalise(self):
"""
Following plan processing, the raw mode share table will contain counts by mode,
population attribute class, activity and period (where period is based on departure
time).
Finalise aggregates these results as required and creates a dataframe.
"""
# Scale final counts
self.mode_counts *= 1.0 / self.config.scale_factor
names = ['mode', 'class', 'hour']
indexes = [self.modes, self.classes, range(self.config.time_periods)]
index = pd.MultiIndex.from_product(indexes, names=names)
counts_df = pd.DataFrame(self.mode_counts.flatten(), index=index)[0]
# mode counts breakdown output
counts_df = counts_df.unstack(level='mode').sort_index()
if self.groupby_person_attribute:
key = f"{self.name}_{self.groupby_person_attribute}_counts"
self.results[key] = counts_df
# mode counts totals output
total_counts_df = counts_df.sum(0)
key = f"{self.name}_counts"
self.results[key] = total_counts_df
# convert to mode shares
total = self.mode_counts.sum()
# mode shares breakdown output
if self.groupby_person_attribute:
key = f"{self.name}_{self.groupby_person_attribute}"
self.results[key] = counts_df / total
# mode shares totals output
key = f"{self.name}"
self.results[key] = total_counts_df / total
@staticmethod
def generate_id_map(list_in):
"""
Generate element ID list and index dictionary from given list.
:param list_in: list
:return: (list, list_indices_map)
"""
if not len(set(list_in)) == len(list_in):
raise UserWarning("non unique mode list found")
list_indices_map = {
key: value for (key, value) in zip(list_in, range(0, len(list_in)))
}
return list_in, list_indices_map
def table_position(
self,
mode,
attribute_class,
time
):
"""
Calculate the result table coordinates from given maps.
:param mode: String, mode id
:param attribute_class: String, class id
:param time: Timestamp of event
:return: (x, y, z, w) tuple of integers to index results table
"""
x = self.mode_indices[mode]
y = self.class_indices[attribute_class]
z = floor(time / (86400.0 / self.config.time_periods)) % self.config.time_periods
return x, y, z
class TripDestinationModeShare(PlanHandlerTool):
"""
Extract mode shares for specified activities from plans. This handler takes a list of activities and computes the mode shares for each
independant activity trip.
"""
requirements = [
'plans',
'attributes',
'transit_schedule',
'output_config',
]
valid_modes = ['all']
def __init__(self, config, mode=None, groupby_person_attribute=None,destination_activity_filters=None, **kwargs) -> None:
"""
Initiate Handler.
:param config: Config
:param mode: str, mode
:param groupby_person_attribute: list, attributes
:param destination_activity_filters: list, activities
"""
super().__init__(config=config, mode=mode, groupby_person_attribute=groupby_person_attribute, **kwargs)
self.mode = mode # todo options not implemented
self.groupby_person_attribute = groupby_person_attribute
self.destination_activity_filters = destination_activity_filters
self.modes = None
self.mode_indices = None
self.classes = None
self.class_indices = None
self.mode_counts = None
self.results = None
# Initialise results storage
self.results = dict() # Result geodataframes ready to export
def build(self, resources: dict, write_path=None) -> None:
"""
Build Handler.
:param resources: dict, supplier resources
:param write_path: Optional output path overwrite
"""
super().build(resources, write_path=write_path)
modes = list(set(self.resources['output_config'].modes + self.resources['transit_schedule'].modes))
self.logger.debug(f'modes = {modes}')
# Initialise mode classes
self.modes, self.mode_indices = self.generate_id_map(modes)
if self.groupby_person_attribute:
self.attributes = self.resources["attributes"]
availability = self.attributes.attribute_key_availability(self.groupby_person_attribute)
self.logger.debug(f'availability of attribute {self.groupby_person_attribute} = {availability*100}%')
if availability < 1:
self.logger.warning(f'availability of attribute {self.groupby_person_attribute} = {availability*100}%')
found_attributes = self.resources['attributes'].attribute_values(self.groupby_person_attribute) | {None}
else:
self.attributes = {}
found_attributes = [None]
self.logger.debug(f'attributes = {found_attributes}')
# Initialise class classes
self.classes, self.class_indices = self.generate_id_map(found_attributes)
# Initialise mode count table, if have list of activities then initiallise as dictionary of tables
self.mode_counts = np.zeros((
len(self.modes),
len(self.classes),
self.config.time_periods))
self.results = dict()
def process_plans(self, elem):
"""
Iterate through the plans and produce counts / mode shares for trips to the destination activities specified in the list.
This handler counts the longest travelling mode of the trip leg leading to each instance of the destination activity(ies) specified
e.g. if the destination acitivity list consists of ['work_a', work_b] and a plan consists of the trips
[home] --> (bus,11km) --> [work_a] --> (train, 10km) --> [work_b], the resulting counts will see (bus) +1 & (train) + 1.
:param elem: Plan XML element
"""
for plan in elem.xpath(".//plan"):
if plan.get('selected') == 'yes':
ident = elem.get('id')
attribute_class = self.attributes.get(ident, {}).get(self.groupby_person_attribute)
end_time = None
modes = {}
for stage in plan:
if stage.tag == 'leg':
leg_mode = stage.get('mode')
route_elem = stage.xpath('route')[0]
mode = self.extract_mode_from_route_elem(leg_mode, route_elem)
distance = float(route_elem.get("distance", 0))
mode = {"egress_walk":"walk", "access_walk":"walk"}.get(mode, mode) # ignore access and egress walk
modes[mode] = modes.get(mode, 0) + distance
elif stage.tag == 'activity':
activity = stage.get('type')
if activity == 'pt interaction': # ignore pt interaction activities
continue
# only add activity modes when there has been previous activity
# (ie trip start time) AND the activity is in specified list
if end_time and (activity in self.destination_activity_filters):
mode = self.get_furthest_mode(modes)
x, y, z = self.table_position(
mode,
attribute_class,
end_time
)
self.mode_counts[x, y, z] += 1
# update endtime for next activity
end_time = convert_time_to_seconds(stage.get('end_time'))
# reset modes
modes = {}
def finalise(self):
"""
Following plan processing, the raw mode share table will contain counts by mode,
population attribute class, activity and period (where period is based on departure
time).
Finalise aggregates these results as required and creates a dataframe.
"""
# Scale final counts
self.mode_counts *= 1.0 / self.config.scale_factor
activity_filter_name = '_'.join(self.destination_activity_filters)
names = ['mode', 'class', 'hour']
indexes = [self.modes, self.classes, range(self.config.time_periods)]
index = pd.MultiIndex.from_product(indexes, names=names)
counts_df = pd.DataFrame(self.mode_counts.flatten(), index=index)[0]
# mode counts breakdown output
counts_df = counts_df.unstack(level='mode').sort_index()
counts_df = counts_df.reset_index().drop("hour", axis=1)
counts_df = counts_df.groupby(counts_df["class"]).sum()
# this removes the breakdown by hour which no one has been using
if self.groupby_person_attribute:
key = f"{self.name}_{self.groupby_person_attribute}_{activity_filter_name}_counts"
self.results[key] = counts_df
# mode counts totals output
total_counts_df = counts_df.sum(0)
key = f"{self.name}_{activity_filter_name}_counts"
self.results[key] = total_counts_df
# convert to mode shares
total = self.mode_counts.sum()
# mode shares breakdown output
if self.groupby_person_attribute:
key = f"{self.name}_{self.groupby_person_attribute}_{activity_filter_name}"
self.results[key] = counts_df / total
# mode shares totals output
key = f"{self.name}_{activity_filter_name}"
self.results[key] = total_counts_df / total
@staticmethod
def generate_id_map(list_in):
"""
Generate element ID list and index dictionary from given list.
:param list_in: list
:return: (list, list_indices_map)
"""
if not len(set(list_in)) == len(list_in):
raise UserWarning("non unique mode list found")
list_indices_map = {
key: value for (key, value) in zip(list_in, range(0, len(list_in)))
}
return list_in, list_indices_map
def table_position(
self,
mode,
attribute_class,
time
):
"""
Calculate the result table coordinates from given maps.
:param mode: String, mode id
:param attribute_class: String, class id
:param time: Timestamp of event
:return: (x, y, z, w) tuple of integers to index results table
"""
x = self.mode_indices[mode]
y = self.class_indices[attribute_class]
z = floor(time / (86400.0 / self.config.time_periods)) % self.config.time_periods
return x, y, z
class LegLogs(PlanHandlerTool):
requirements = ['plans', 'transit_schedule', 'attributes']
valid_modes = ['all']
# todo make it so that 'all' option not required (maybe for all plan handlers)
"""
Note that MATSim plan output plans display incorrect 'dep_time' (they show departure time of
original init plan) and do not show activity start time. As a result, we use leg 'duration'
to calculate the start of the next activity. This results in time waiting to enter
first link as being activity time. Therefore activity durations are slightly over reported
and leg duration under reported.
"""
def __init__(self, config, mode=None, groupby_person_attribute="subpopulation", **kwargs):
"""
Initiate handler.
:param config: config
:param mode: str, mode option
:param attributes: str, attribute key defaults to 'subpopulation'
"""
super().__init__(config=config, mode=mode, groupby_person_attribute=groupby_person_attribute, **kwargs)
self.mode = mode
self.groupby_person_attribute = groupby_person_attribute
self.start_datetime = datetime.strptime("2020:4:1-00:00:00", '%Y:%m:%d-%H:%M:%S')
self.activities_log = None
self.legs_log = None
# Initialise results storage
self.results = dict() # Result dataframes ready to export
def build(self, resources: dict, write_path=None) -> None:
"""
Build handler from resources.
:param resources: dict, supplier resources
:param write_path: Optional output path overwrite
"""
super().build(resources, write_path=write_path)
self.attributes = self.resources["attributes"]
activity_csv_name = f"{self.name}_activities.csv"
legs_csv_name = f"{self.name}_legs.csv"
self.activities_log = self.start_chunk_writer(activity_csv_name, write_path=write_path)
self.legs_log = self.start_chunk_writer(legs_csv_name, write_path=write_path)
def process_plans(self, elem):
"""
Build list of leg and activity logs (dicts) for each selected plan.
Note that this assumes that first stage of a plan is ALWAYS an activity.
Note that activity wrapping is not dealt with here.
:return: Tuple[List[dict]]
"""
ident = elem.get('id')
for plan in elem.xpath(".//plan"):
if plan.get('selected') == 'yes':
activities = []
legs = []
attribute = self.attributes.get(ident, {}).get(self.groupby_person_attribute, None)
leg_seq_idx = 0
trip_seq_idx = 0
act_seq_idx = 0
arrival_dt = self.start_datetime
activity_end_dt = None
x = None
y = None
for stage in plan:
if stage.tag == 'activity':
act_seq_idx += 1
act_type = stage.get('type')
if not act_type == 'pt interaction':
trip_seq_idx += 1 # increment for a new trip idx
end_time_str = stage.get('end_time', '23:59:59')
activity_end_dt = matsim_time_to_datetime(
arrival_dt, end_time_str, self.logger, idx=ident
)
duration = activity_end_dt - arrival_dt
else:
activity_end_dt = arrival_dt
duration = arrival_dt - arrival_dt # zero duration
x = stage.get('x')
y = stage.get('y')
activities.append(
{
'agent': ident,
'attribute': attribute,
'seq': act_seq_idx,
'act': act_type,
'x': x,
'y': y,
'start': arrival_dt.time(),
'end': activity_end_dt.time(),
'end_day': activity_end_dt.day,
# 'duration': duration,
'start_s': self.get_seconds(arrival_dt),
'end_s': self.get_seconds(activity_end_dt),
'duration_s': duration.total_seconds()
}
)
elif stage.tag == 'leg':
leg_seq_idx += 1
leg_mode = stage.get('mode')
route_elem = stage.xpath('route')[0]
mode = self.extract_mode_from_route_elem(leg_mode, route_elem)
mode = {"egress_walk":"walk", "access_walk":"walk"}.get(mode, mode)
trav_time = stage.get('trav_time')
h, m, s = trav_time.split(":")
td = timedelta(hours=int(h), minutes=int(m), seconds=int(s))
arrival_dt = activity_end_dt + td
legs.append(
{
'agent': ident,
'attribute': attribute,
'seq': leg_seq_idx,
'trip': trip_seq_idx,
'mode': mode,
'ox': x,
'oy': y,
'dx': None,
'dy': None,
'o_act': act_type,
'd_act': None,
'start': activity_end_dt.time(),
'end': arrival_dt.time(),
'end_day': arrival_dt.day,
# 'duration': td,
'start_s': self.get_seconds(activity_end_dt),
'end_s': self.get_seconds(arrival_dt),
'duration_s': td.total_seconds(),
'distance': route_elem.get('distance')
}
)
for idx, leg in enumerate(legs):
# back-fill leg destinations
leg['dx'] = activities[idx + 1]['x']
leg['dy'] = activities[idx + 1]['y']
# back-fill destination activities for legs
leg['d_act'] = activities[idx + 1]['act']
self.activities_log.add(activities)
self.legs_log.add(legs)
def finalise(self):
"""
Finalise aggregates and joins these results as required and creates a dataframe.
"""
self.activities_log.finish()
self.legs_log.finish()
@staticmethod
def get_seconds(dt: datetime) -> int:
"""
Extract time of day in seconds from datetime.
:param dt: datetime
:return: int, seconds
"""
d = dt.day
h = dt.hour
m = dt.minute
s = dt.second
return s + (60 * (m + (60 * (h + ((d-1) * 24)))))
class TripLogs(PlanHandlerTool):
requirements = ['plans', 'transit_schedule', 'attributes']
valid_modes = ['all'] #mode and purpose options need to be enabled for post-processing cross tabulation w euclidian distance
# todo make it so that 'all' option not required (maybe for all plan handlers)
"""
Note that MATSim plan output plans display incorrect 'dep_time' (they show departure time of
original init plan) and do not show activity start time. As a result, we use leg 'duration'
to calculate the start of the next activity. This results in time waiting to enter
first link as being activity time. Therefore activity durations are slightly over reported
and leg duration under reported.
"""
def __init__(self, config, mode=None, groupby_person_attribute="subpopulation", **kwargs):
"""
Initiate handler.
:param config: config
:param mode: str, mode option
:param attributes: str, attribute key defaults to 'subpopulation'
"""
super().__init__(config=config, mode=mode, groupby_person_attribute=groupby_person_attribute, **kwargs)
self.mode = mode
self.groupby_person_attribute = groupby_person_attribute
self.start_datetime = datetime.strptime("2020:4:1-00:00:00", '%Y:%m:%d-%H:%M:%S')
self.activities_log = None
self.trips_log = None
# Initialise results storage
self.results = dict() # Result dataframes ready to export
def build(self, resources: dict, write_path=None) -> None:
"""
Build handler from resources.
:param resources: dict, supplier resources
:param write_path: Optional output path overwrite
"""
super().build(resources, write_path=write_path)
self.attributes = self.resources["attributes"]
activity_csv_name = f"{self.name}_activities.csv"
trips_csv_name = f"{self.name}_trips.csv"
self.activities_log = self.start_chunk_writer(activity_csv_name, write_path=write_path)
self.trips_log = self.start_chunk_writer(trips_csv_name, write_path=write_path)
def process_plans(self, elem):
"""
Build list of trip and activity logs (dicts) for each selected plan.
Note that this assumes that first stage of a plan is ALWAYS an activity.
Note that activity wrapping is not dealt with here.
:return: Tuple[List[dict]]
"""
ident = elem.get('id')
for plan in elem.xpath(".//plan"):
attribute = self.attributes.get(ident, {}).get(self.groupby_person_attribute, None)
if plan.get('selected') == 'yes':
# check that plan starts with an activity
if not plan[0].tag == 'activity':
raise UserWarning('Plan does not start with activity.')
if plan[0].get('type') == 'pt interaction':
raise UserWarning('Plan cannot start with activity type "pt interaction".')
activities = []
trips = []
act_seq_idx = 0
activity_start_dt = self.start_datetime
activity_end_dt = self.start_datetime
# todo replace this start datetime with a real start datetime using config
x = None
y = None
modes = {}
trip_distance = 0
for stage in plan:
if stage.tag == 'activity':
act_type = stage.get('type')
if not act_type == 'pt interaction':
act_seq_idx += 1 # increment for a new trip idx
trip_duration = activity_start_dt - activity_end_dt
end_time_str = stage.get('end_time', '23:59:59')
activity_end_dt = matsim_time_to_datetime(
activity_start_dt, end_time_str, self.logger, idx=ident
)
activity_duration = activity_end_dt - activity_start_dt
x = stage.get('x')
y = stage.get('y')
if modes: # add to trips log
trips.append(
{
'agent': ident,
'attribute': attribute,
'seq': act_seq_idx-1,
'mode': self.get_furthest_mode(modes),
'ox': activities[-1]['x'],
'oy': activities[-1]['y'],
'dx': x,
'dy': y,
'o_act': activities[-1]['act'],
'd_act': act_type,
'start': activities[-1]['end'],
'start_day': activities[-1]['end_day'],
'end': activity_start_dt.time(),
'end_day': activity_start_dt.day,
'start_s': activities[-1]['end_s'],
'end_s': self.get_seconds(activity_start_dt),
'duration': trip_duration,
'duration_s': trip_duration.total_seconds(),
'distance': trip_distance,
}
)
modes = {} # reset for next trip
trip_distance = 0 # reset for next trip
activities.append(
{
'agent': ident,
'attribute': attribute,
'seq': act_seq_idx,
'act': act_type,
'x': x,
'y': y,
'start': activity_start_dt.time(),
'start_day': activity_start_dt.day,
'end': activity_end_dt.time(),
'end_day': activity_end_dt.day,
'start_s': self.get_seconds(activity_start_dt),
'end_s': self.get_seconds(activity_end_dt),
'duration': activity_duration,
'duration_s': activity_duration.total_seconds()
}
)
activity_start_dt = activity_end_dt
elif stage.tag == 'leg':
leg_mode = stage.get('mode')
route_elem = stage.xpath('route')[0]
distance = float(route_elem.get("distance", 0))
mode = self.extract_mode_from_route_elem(leg_mode, route_elem)
mode = {"egress_walk": "walk", "access_walk": "walk"}.get(mode, mode) # ignore access and egress walk
modes[mode] = modes.get(mode, 0) + distance
trip_distance += distance
trav_time = stage.get('trav_time')
h, m, s = trav_time.split(":")
td = timedelta(hours=int(h), minutes=int(m), seconds=int(s))
activity_start_dt += td
self.activities_log.add(activities)
self.trips_log.add(trips)
def finalise(self):
"""
Finalise aggregates and joins these results as required and creates a dataframe.
"""
self.activities_log.finish()
self.trips_log.finish()
@staticmethod
def get_seconds(dt: datetime) -> int:
"""
Extract time of day in seconds from datetime.
:param dt: datetime
:return: int, seconds
"""
d = dt.day
h = dt.hour
m = dt.minute
s = dt.second
return s + (60 * (m + (60 * (h + ((d-1) * 24)))))
class UtilityLogs(PlanHandlerTool):
requirements = ['plans']
valid_modes = ['all']
# todo make it so that 'all' option not required (maybe for all plan handlers)
def __init__(self, config, mode=None, groupby_person_attribute=None, **kwargs):
"""
Initiate handler.
:param config: config
:param mode: str, mode option
"""
super().__init__(config=config, mode=mode, groupby_person_attribute=groupby_person_attribute, **kwargs)
self.mode = mode
self.utility_log = None
# Initialise results storage
self.results = dict() # Result dataframes ready to export
def build(self, resources: dict, write_path=None) -> None:
"""
Build handler from resources.
:param resources: dict, supplier resources
:param write_path: Optional output path overwrite
"""
super().build(resources, write_path=write_path)
utility_csv_name = f"{self.name}.csv"
self.utility_log = self.start_chunk_writer(utility_csv_name, write_path=write_path)
def process_plans(self, elem):
"""
Build list of the utility of the selected plan for each agent.
:return: Tuple[List[dict]]
"""
ident = elem.get('id')
for plan in elem.xpath(".//plan"):
if plan.get('selected') == 'yes':
score = plan.get('score')
utilities = [{'agent': ident,'score': score}]
self.utility_log.add(utilities)
return None
def finalise(self):
"""
Finalise aggregates and joins these results as required and creates a dataframe.
"""
self.utility_log.finish()
class PlanLogs(PlanHandlerTool):
"""
Write log of all plans, including selection and score.
Format will we mostly duplicate of legs log.
"""
"""
Note that MATSim plan output plans display incorrect 'dep_time' (they show departure time of
original init plan) and do not show activity start time. As a result, we use leg 'duration'
to calculate the start of the next activity. This results in time waiting to enter
first link as being activity time. Therefore activity durations are slightly over reported
and leg duration under reported.
"""
requirements = ['plans', 'attributes']
def __init__(self, config, mode=None, groupby_person_attribute="subpopulation", **kwargs):
"""
Initiate handler.
:param config: config
:param mode: str, mode option
"""
super().__init__(config=config, mode=mode, groupby_person_attribute=groupby_person_attribute, **kwargs)
self.mode = mode
self.groupby_person_attribute = groupby_person_attribute
self.plans_log = None
# Initialise results storage
self.results = dict() # Results will remain empty as using writer
def build(self, resources: dict, write_path=None) -> None:
"""
Build handler from resources.
:param resources: dict, supplier resources
:param write_path: Optional output path overwrite
:return: None
"""
super().build(resources, write_path=write_path)
self.attributes = self.resources["attributes"]
csv_name = f"{self.name}.csv"
self.plans_log = self.start_chunk_writer(csv_name, write_path=write_path)
def process_plans(self, elem):
"""
Build list of leg logs (dicts) for each selected plan.
Note that this assumes that first stage of a plan is ALWAYS an activity.
Note that activity wrapping is not dealt with here.
:return: Tuple[List[dict]]
"""
ident = elem.get('id')
attribute = self.attributes.get(ident, {}).get(self.groupby_person_attribute, None)
if not self.mode == "all" and not attribute == self.mode:
return None
for pidx, plan in enumerate(elem.xpath(".//plan")):
selected = str(plan.get('selected'))
score = float(plan.get('score', 0))
trip_records = []
trip_seq = 0
arrival_dt = None
in_transit = False
trip_start_time = None
prev_mode = "NA"
prev_act = "NA"
leg_mode = None
prev_x = None
prev_y = None