-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathpems_tasks.py
More file actions
659 lines (521 loc) · 22.5 KB
/
pems_tasks.py
File metadata and controls
659 lines (521 loc) · 22.5 KB
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
import pandas as pd
import os
from cik_benchmark.base import UnivariateCRPSTask
from cik_benchmark.data.pems import (
download_instances,
INSTANCES_DIR,
)
from . import WeightCluster
# https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement
def ordinal(n: int):
if 11 <= (n % 100) <= 13:
suffix = "th"
else:
suffix = ["th", "st", "nd", "rd", "th"][min(n % 10, 4)]
return str(n) + suffix
SHORT_BACKGROUND = "This data is the average speed in miles per hour recorded by a sensor on the {freeway_dir} freeway, in California."
MEDIUM_BACKGROUND = "This data is the average speed in miles per hour recorded by a sensor on the {freeway_dir} freeway, in {county} county, California. It is in the {district} congressional district."
LONG_BACKGROUND = "This data is the average speed in miles per hour recorded by a sensor on the {freeway_dir} freeway at its absolute postmile marker {abs_pm}. This is in {county} county, California, in the {district} congressional district."
LANE_CLOSURE_PLACEMENTS = ["before", "during", "after"]
# targets = ["Speed (mph)", "Occupancy (%)"]
HISTORY_FACTORS = {
"short": 1,
"default": 7,
}
class AbstractLaneClosureTask(UnivariateCRPSTask):
"""
Abstract traffic task, randomly sampled lane closure with all windows available.
"""
_context_sources = UnivariateCRPSTask._context_sources + ["c_i", "c_f"]
_skills = UnivariateCRPSTask._skills + ["reasoning: deduction"]
__version__ = "0.0.2" # Modification will trigger re-caching
lane_closure_placement = ""
history_length = ""
background_length = ""
def __init__(
self,
fixed_config: dict = None,
seed: int = None,
target: str = "Speed (mph)", # or 'Occupancy (%)'
):
self.init_data()
self.target = target
self.seed = seed
super().__init__(seed=seed, fixed_config=fixed_config)
def init_data(self):
"""
Check integrity of data files and download if needed.
"""
if not os.path.exists(INSTANCES_DIR):
download_instances()
def get_instance(self):
# Load the lane closure data
instance_files = [f for f in os.listdir(INSTANCES_DIR) if "lane_closure" in f]
abs_pms = [f.split("_abs_pm_")[1].split("_")[0] for f in instance_files]
# sort the abs_pms
abs_pms = sorted(abs_pms)
if self.seed is None:
self.seed = self.random.randint(0, len(abs_pms))
selected_abs_pm = abs_pms[self.seed % len(abs_pms)]
# Load the lane closure data
lane_closure_file = [
f for f in instance_files if f"abs_pm_{selected_abs_pm}" in f
][
0
] # uses abs_pm as unique identifier
lane_closure = pd.read_csv(os.path.join(INSTANCES_DIR, lane_closure_file))
lane_closure = lane_closure.iloc[0]
# Load the sensor data
sensor_file = lane_closure_file.replace("lane_closure", "sensor_window")
sensor_data = pd.read_csv(os.path.join(INSTANCES_DIR, sensor_file))
sensor_data["date"] = pd.to_datetime(sensor_data["date"])
sensor_data.set_index("date", inplace=True)
sensor_data.index = pd.to_datetime(sensor_data.index)
self.lane_closure_start = pd.to_datetime(lane_closure["Start Date"])
self.lane_closure_end = self.lane_closure_start + pd.to_timedelta(
lane_closure["Reported Duration"], unit="m"
)
return lane_closure, sensor_data
def random_instance(self):
lane_closure, window_df = self.get_instance()
history_series, future_series = self.get_history_future(
lane_closure, window_df[self.target]
)
self.past_time = history_series.to_frame()
self.future_time = future_series.to_frame()
self.constraints = None
self.background = self.get_background(window_df)
self.scenario = self.get_scenario(lane_closure)
def get_history_factor(self):
# if owning object class name has short, return 1, else return 7
if self.history_length == "short":
return HISTORY_FACTORS["short"]
return HISTORY_FACTORS["default"]
def get_history_future(self, lane_closure, window):
lane_closure_start_day = self.lane_closure_start.normalize()
lane_closure_end_day = self.lane_closure_end.normalize()
if self.lane_closure_placement == "before":
history_end_day = lane_closure_end_day + pd.DateOffset(days=1)
history_start_day = lane_closure_start_day.normalize() - pd.DateOffset(
days=self.get_history_factor()
)
history_series = window[
(window.index >= history_start_day) & (window.index < history_end_day)
]
future_series = window[
(window.index >= history_end_day)
& (window.index < history_end_day + pd.DateOffset(days=7))
]
elif self.lane_closure_placement == "during":
# get midpoint between start and end of lane closure
midpoint_duration = (self.lane_closure_end - self.lane_closure_start) / 2
lane_closure_midpoint = self.lane_closure_start + midpoint_duration
lane_closure_midpoint = lane_closure_midpoint.round("H")
history_start_day = (
lane_closure_midpoint - pd.DateOffset(days=self.get_history_factor())
).normalize()
history_end_day = lane_closure_midpoint
history_series = window[
(window.index >= history_start_day) & (window.index < history_end_day)
]
future_series = window[
(window.index >= history_end_day)
& (window.index < (history_end_day + pd.DateOffset(days=7)).normalize())
]
elif self.lane_closure_placement == "after":
history_end_day = lane_closure_start_day - pd.DateOffset(days=1)
history_start_day = history_end_day - pd.DateOffset(
days=self.get_history_factor()
)
history_series = window[
(window.index >= history_start_day) & (window.index < history_end_day)
]
future_series = window[
(window.index >= history_end_day)
& (window.index < history_end_day + pd.DateOffset(days=7))
]
else:
raise ValueError("Invalid task class name")
return history_series, future_series
def get_background(self, sensor_data):
freeway_dir = sensor_data["Fwy"].iloc[0]
district = sensor_data["District"].iloc[0]
county = sensor_data["County"].iloc[0]
abs_pm = sensor_data["Abs PM"].iloc[0]
if self.background_length == "short":
return SHORT_BACKGROUND.format(freeway_dir=freeway_dir)
elif self.background_length == "medium":
return MEDIUM_BACKGROUND.format(
freeway_dir=freeway_dir, district=ordinal(district), county=county
)
elif self.background_length == "long":
return LONG_BACKGROUND.format(
freeway_dir=freeway_dir,
district=ordinal(district),
county=county,
abs_pm=abs_pm,
)
def get_scenario(self, lane_closure):
"""
Get the scenario of the task.
"""
expected_start_date = pd.to_datetime(lane_closure["Start Date"])
expected_end_date = pd.to_datetime(lane_closure["End Date"])
expected_duration = str(lane_closure["Planned Duration"]) + " minutes"
closure_lanes = lane_closure["Closure Lanes"]
total_lanes = lane_closure["Total Lanes"]
return (
f"Lane closure from {expected_start_date} to {expected_end_date} with a planned duration of {expected_duration}."
f"The number of lanes closed is {closure_lanes} out of {total_lanes} total lanes."
)
def get_prediction_length(self, window):
# Calculate the number of hours between the end of the window and the start of the lane closure day
lane_closure_end = self.lane_closure_end
end_of_closure_day = pd.to_datetime(lane_closure_end).normalize()
end_of_closure_day_extended = pd.to_datetime(
end_of_closure_day
).normalize() + pd.DateOffset(days=2)
# The prediction length is the number of hours from the start of the closure day to the end of the window
prediction_length = (
window.index[-1] - end_of_closure_day_extended
).total_seconds() / 3600
return int(prediction_length)
@property
def seasonal_period(self) -> int:
"""
This returns the period which should be used by statistical models for this task.
If negative, this means that the data either has no period, or the history is shorter than the period.
"""
return 24
class LaneClosureBeforeShortBackgroundTask(AbstractLaneClosureTask):
"""
Default traffic task, randomly sampled lane closure with all windows available.
"""
_context_sources = UnivariateCRPSTask._context_sources + ["c_i", "c_f"]
_skills = UnivariateCRPSTask._skills + ["reasoning: deduction"]
__version__ = "0.0.2" # Modification will trigger re-caching
lane_closure_placement = "before"
history_length = "default"
background_length = "short"
def __init__(
self,
fixed_config: dict = None,
seed: int = None,
target: str = "Speed (mph)", # or 'Occupancy (%)'
):
super().__init__(seed=seed, fixed_config=fixed_config, target=target)
class LaneClosureBeforeMediumBackgroundTask(AbstractLaneClosureTask):
"""
Default traffic task, randomly sampled lane closure with all windows available.
"""
_context_sources = UnivariateCRPSTask._context_sources + ["c_i", "c_f"]
_skills = UnivariateCRPSTask._skills + ["reasoning: deduction"]
__version__ = "0.0.2" # Modification will trigger re-caching
lane_closure_placement = "before"
history_length = "default"
background_length = "medium"
def __init__(
self,
fixed_config: dict = None,
seed: int = None,
target: str = "Speed (mph)", # or 'Occupancy (%)'
):
super().__init__(seed=seed, fixed_config=fixed_config, target=target)
class LaneClosureBeforeLongBackgroundTask(AbstractLaneClosureTask):
"""
Default traffic task, randomly sampled lane closure with all windows available.
"""
_context_sources = UnivariateCRPSTask._context_sources + ["c_i", "c_f"]
_skills = UnivariateCRPSTask._skills + ["reasoning: deduction"]
__version__ = "0.0.2" # Modification will trigger re-caching
lane_closure_placement = "before"
history_length = "default"
background_length = "long"
def __init__(
self,
fixed_config: dict = None,
seed: int = None,
target: str = "Speed (mph)", # or 'Occupancy (%)'
):
super().__init__(seed=seed, fixed_config=fixed_config, target=target)
class LaneClosureDuringShortBackgroundTask(AbstractLaneClosureTask):
"""
Default traffic task, randomly sampled lane closure with all windows available.
"""
_context_sources = UnivariateCRPSTask._context_sources + ["c_i", "c_f"]
_skills = UnivariateCRPSTask._skills + ["reasoning: deduction"]
__version__ = "0.0.2" # Modification will trigger re-caching
lane_closure_placement = "during"
history_length = "default"
background_length = "short"
def __init__(
self,
fixed_config: dict = None,
seed: int = None,
target: str = "Speed (mph)", # or 'Occupancy (%)'
):
super().__init__(seed=seed, fixed_config=fixed_config, target=target)
class LaneClosureDuringMediumBackgroundTask(AbstractLaneClosureTask):
"""
Default traffic task, randomly sampled lane closure with all windows available.
"""
_context_sources = UnivariateCRPSTask._context_sources + ["c_i", "c_f"]
_skills = UnivariateCRPSTask._skills + ["reasoning: deduction"]
__version__ = "0.0.2" # Modification will trigger re-caching
lane_closure_placement = "during"
history_length = "default"
background_length = "medium"
def __init__(
self,
fixed_config: dict = None,
seed: int = None,
target: str = "Speed (mph)", # or 'Occupancy (%)'
):
super().__init__(seed=seed, fixed_config=fixed_config, target=target)
class LaneClosureDuringLongBackgroundTask(AbstractLaneClosureTask):
"""
Default traffic task, randomly sampled lane closure with all windows available.
"""
_context_sources = UnivariateCRPSTask._context_sources + ["c_i", "c_f"]
_skills = UnivariateCRPSTask._skills + ["reasoning: deduction"]
__version__ = "0.0.2" # Modification will trigger re-caching
lane_closure_placement = "during"
history_length = "default"
background_length = "long"
def __init__(
self,
fixed_config: dict = None,
seed: int = None,
target: str = "Speed (mph)", # or 'Occupancy (%)'
):
super().__init__(seed=seed, fixed_config=fixed_config, target=target)
class LaneClosureAfterShortBackgroundTask(AbstractLaneClosureTask):
"""
Default traffic task, randomly sampled lane closure with all windows available.
"""
_context_sources = UnivariateCRPSTask._context_sources + ["c_i", "c_f"]
_skills = UnivariateCRPSTask._skills + ["reasoning: deduction"]
__version__ = "0.0.2" # Modification will trigger re-caching
lane_closure_placement = "after"
history_length = "default"
background_length = "short"
def __init__(
self,
fixed_config: dict = None,
seed: int = None,
target: str = "Speed (mph)", # or 'Occupancy (%)'
):
super().__init__(seed=seed, fixed_config=fixed_config, target=target)
class LaneClosureAfterMediumBackgroundTask(AbstractLaneClosureTask):
"""
Default traffic task, randomly sampled lane closure with all windows available.
"""
_context_sources = UnivariateCRPSTask._context_sources + ["c_i", "c_f"]
_skills = UnivariateCRPSTask._skills + ["reasoning: deduction"]
__version__ = "0.0.2" # Modification will trigger re-caching
lane_closure_placement = "after"
history_length = "default"
background_length = "medium"
def __init__(
self,
fixed_config: dict = None,
seed: int = None,
target: str = "Speed (mph)", # or 'Occupancy (%)'
):
super().__init__(seed=seed, fixed_config=fixed_config, target=target)
class LaneClosureAfterLongBackgroundTask(AbstractLaneClosureTask):
"""
Default traffic task, randomly sampled lane closure with all windows available.
"""
_context_sources = UnivariateCRPSTask._context_sources + ["c_i", "c_f"]
_skills = UnivariateCRPSTask._skills + ["reasoning: deduction"]
__version__ = "0.0.2" # Modification will trigger re-caching
lane_closure_placement = "after"
history_length = "default"
background_length = "long"
def __init__(
self,
fixed_config: dict = None,
seed: int = None,
target: str = "Speed (mph)", # or 'Occupancy (%)'
):
super().__init__(seed=seed, fixed_config=fixed_config, target=target)
class LaneClosureBeforeShortHistoryShortBackgroundTask(AbstractLaneClosureTask):
"""
Default traffic task, randomly sampled lane closure with all windows available.
"""
_context_sources = UnivariateCRPSTask._context_sources + ["c_i", "c_f"]
_skills = UnivariateCRPSTask._skills + ["reasoning: deduction"]
__version__ = "0.0.2" # Modification will trigger re-caching
lane_closure_placement = "before"
history_length = "short"
background_length = "short"
def __init__(
self,
fixed_config: dict = None,
seed: int = None,
target: str = "Speed (mph)", # or 'Occupancy (%)'
):
super().__init__(seed=seed, fixed_config=fixed_config, target=target)
class LaneClosureBeforeShortHistoryMediumBackgroundTask(AbstractLaneClosureTask):
"""
Default traffic task, randomly sampled lane closure with all windows available.
"""
_context_sources = UnivariateCRPSTask._context_sources + ["c_i", "c_f"]
_skills = UnivariateCRPSTask._skills + ["reasoning: deduction"]
__version__ = "0.0.2" # Modification will trigger re-caching
lane_closure_placement = "before"
history_length = "short"
background_length = "medium"
def __init__(
self,
fixed_config: dict = None,
seed: int = None,
target: str = "Speed (mph)", # or 'Occupancy (%)'
):
super().__init__(seed=seed, fixed_config=fixed_config, target=target)
class LaneClosureBeforeShortHistoryLongBackgroundTask(AbstractLaneClosureTask):
"""
Default traffic task, randomly sampled lane closure with all windows available.
"""
_context_sources = UnivariateCRPSTask._context_sources + ["c_i", "c_f"]
_skills = UnivariateCRPSTask._skills + ["reasoning: deduction"]
__version__ = "0.0.2" # Modification will trigger re-caching
lane_closure_placement = "before"
history_length = "short"
background_length = "long"
def __init__(
self,
fixed_config: dict = None,
seed: int = None,
target: str = "Speed (mph)", # or 'Occupancy (%)'
):
super().__init__(seed=seed, fixed_config=fixed_config, target=target)
class LaneClosureDuringShortHistoryShortBackgroundTask(AbstractLaneClosureTask):
"""
Default traffic task, randomly sampled lane closure with all windows available.
"""
_context_sources = UnivariateCRPSTask._context_sources + ["c_i", "c_f"]
_skills = UnivariateCRPSTask._skills + ["reasoning: deduction"]
__version__ = "0.0.2" # Modification will trigger re-caching
lane_closure_placement = "during"
history_length = "short"
background_length = "short"
def __init__(
self,
fixed_config: dict = None,
seed: int = None,
target: str = "Speed (mph)", # or 'Occupancy (%)'
):
super().__init__(seed=seed, fixed_config=fixed_config, target=target)
class LaneClosureDuringShortHistoryMediumBackgroundTask(AbstractLaneClosureTask):
"""
Default traffic task, randomly sampled lane closure with all windows available.
"""
_context_sources = UnivariateCRPSTask._context_sources + ["c_i", "c_f"]
_skills = UnivariateCRPSTask._skills + ["reasoning: deduction"]
__version__ = "0.0.2" # Modification will trigger re-caching
lane_closure_placement = "during"
history_length = "short"
background_length = "medium"
def __init__(
self,
fixed_config: dict = None,
seed: int = None,
target: str = "Speed (mph)", # or 'Occupancy (%)'
):
super().__init__(seed=seed, fixed_config=fixed_config, target=target)
class LaneClosureDuringShortHistoryLongBackgroundTask(AbstractLaneClosureTask):
"""
Default traffic task, randomly sampled lane closure with all windows available.
"""
_context_sources = UnivariateCRPSTask._context_sources + ["c_i", "c_f"]
_skills = UnivariateCRPSTask._skills + ["reasoning: deduction"]
__version__ = "0.0.2" # Modification will trigger re-caching
lane_closure_placement = "during"
history_length = "short"
background_length = "long"
def __init__(
self,
fixed_config: dict = None,
seed: int = None,
target: str = "Speed (mph)", # or 'Occupancy (%)'
):
super().__init__(seed=seed, fixed_config=fixed_config, target=target)
class LaneClosureAfterShortHistoryShortBackgroundTask(AbstractLaneClosureTask):
"""
Default traffic task, randomly sampled lane closure with all windows available.
"""
_context_sources = UnivariateCRPSTask._context_sources + ["c_i", "c_f"]
_skills = UnivariateCRPSTask._skills + ["reasoning: deduction"]
__version__ = "0.0.2" # Modification will trigger re-caching
lane_closure_placement = "after"
history_length = "short"
background_length = "short"
def __init__(
self,
fixed_config: dict = None,
seed: int = None,
target: str = "Speed (mph)", # or 'Occupancy (%)'
):
super().__init__(seed=seed, fixed_config=fixed_config, target=target)
class LaneClosureAfterShortHistoryMediumBackgroundTask(AbstractLaneClosureTask):
"""
Default traffic task, randomly sampled lane closure with all windows available.
"""
_context_sources = UnivariateCRPSTask._context_sources + ["c_i", "c_f"]
_skills = UnivariateCRPSTask._skills + ["reasoning: deduction"]
__version__ = "0.0.2" # Modification will trigger re-caching
lane_closure_placement = "after"
history_length = "short"
background_length = "medium"
def __init__(
self,
fixed_config: dict = None,
seed: int = None,
target: str = "Speed (mph)", # or 'Occupancy (%)'
):
super().__init__(seed=seed, fixed_config=fixed_config, target=target)
class LaneClosureAfterShortHistoryLongBackgroundTask(AbstractLaneClosureTask):
"""
Default traffic task, randomly sampled lane closure with all windows available.
"""
_context_sources = UnivariateCRPSTask._context_sources + ["c_i", "c_f"]
_skills = UnivariateCRPSTask._skills + ["reasoning: deduction"]
__version__ = "0.0.2" # Modification will trigger re-caching
lane_closure_placement = "after"
history_length = "short"
background_length = "long"
def __init__(
self,
fixed_config: dict = None,
seed: int = None,
target: str = "Speed (mph)", # or 'Occupancy (%)'
):
super().__init__(seed=seed, fixed_config=fixed_config, target=target)
__TASKS__ = [
LaneClosureBeforeShortBackgroundTask,
LaneClosureBeforeMediumBackgroundTask,
LaneClosureBeforeLongBackgroundTask,
LaneClosureDuringShortBackgroundTask,
LaneClosureDuringMediumBackgroundTask,
LaneClosureDuringLongBackgroundTask,
LaneClosureAfterShortBackgroundTask,
LaneClosureAfterMediumBackgroundTask,
LaneClosureAfterLongBackgroundTask,
LaneClosureBeforeShortHistoryShortBackgroundTask,
LaneClosureBeforeShortHistoryMediumBackgroundTask,
LaneClosureBeforeShortHistoryLongBackgroundTask,
LaneClosureDuringShortHistoryShortBackgroundTask,
LaneClosureDuringShortHistoryMediumBackgroundTask,
LaneClosureDuringShortHistoryLongBackgroundTask,
LaneClosureAfterShortHistoryShortBackgroundTask,
LaneClosureAfterShortHistoryMediumBackgroundTask,
LaneClosureAfterShortHistoryLongBackgroundTask,
]
__CLUSTERS__ = [
WeightCluster(
weight=1,
tasks=__TASKS__,
),
]