-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutils.py
More file actions
1362 lines (1145 loc) · 44.2 KB
/
Copy pathutils.py
File metadata and controls
1362 lines (1145 loc) · 44.2 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
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 pandas as pd
import numpy as np
from pathlib import Path
import json
import importlib.util
import os
import shutil
import lightgbm as lgb
import re
import torch
from tsfeatures import tsfeatures
from datasetsforecast.losses import (
mae, mape, rmse, smape,
)
from typing import Sequence, TypeVar
from matplotlib.ticker import FuncFormatter
# Type definitions for array-like inputs
ArrayLike = TypeVar('ArrayLike', np.ndarray, Sequence[float], Sequence[int])
def cleanup_lightning_artifacts() -> None:
"""
Remove the ``lightning_logs`` and ``checkpoints`` folders that
PyTorch Lightning (used by GluonTS' DeepAR / TFT) writes to the working
directory. Safe to call even when neither folder exists.
"""
for folder in ("lightning_logs", "checkpoints"):
path = Path.cwd() / folder
if path.exists():
shutil.rmtree(path, ignore_errors=True)
col_order = ["series_id", "date", "fcst", "runtime", "model"]
def _nullify_partial_rows(df: pd.DataFrame) -> pd.DataFrame:
"""
Replace every numeric cell of any row with at least one NaN with NaN,
so partial-NaN rows read as fully unavailable.
Parameters
----------
df : pd.DataFrame
Input DataFrame whose numeric columns may contain sporadic NaN values.
Returns
-------
pd.DataFrame
Copy of ``df`` where every numeric cell in a row that contained at
least one NaN is set to NaN.
"""
out = df.copy()
numeric = out.select_dtypes(include=[np.number])
if numeric.empty:
return out
not_run = numeric.isna().any(axis=1)
if not_run.any():
out.loc[not_run, numeric.columns] = np.nan
return out
_PERIOD_TO_OFFSET_FREQ = {"M": "MS", "Q": "QS", "Y": "AS-JAN", "A": "AS-JAN"}
def to_period_freq(freq: str) -> str:
"""
Convert a pandas DateOffset-style frequency string to a Period-style one.
Parameters
----------
freq : str
A pandas DateOffset frequency alias (e.g., ``"MS"``, ``"QS"``,
``"YS-JAN"``).
Returns
-------
str
The equivalent Period frequency alias (e.g., ``"M"``, ``"Q"``,
``"A"``). Returned unchanged when no mapping exists.
"""
return {
"MS": "M",
"QS": "Q",
"AS-JAN": "A",
"AS": "A",
"YS-JAN": "A",
"YS": "A",
"Y": "A",
}.get(freq, freq)
def to_offset_freq(freq: str) -> str:
"""
Convert a pandas Period-style frequency string to a DateOffset-style one.
Inverse of ``to_period_freq``.
Parameters
----------
freq : str
A pandas Period frequency alias (e.g., ``"M"``, ``"Q"``, ``"Y"``).
Returns
-------
str
The equivalent DateOffset frequency alias (e.g., ``"MS"``, ``"QS"``,
``"AS-JAN"``). Returned unchanged when no mapping exists.
"""
return _PERIOD_TO_OFFSET_FREQ.get(freq, freq)
def to_statsforecast_frames(
train: pd.DataFrame,
test: pd.DataFrame,
features: list = None,
) -> tuple:
"""
Reshape HyperTrees DataFrames into the statsforecast schema.
Converts ``(series_id, date, value [, features])`` columns into the
``(unique_id, ds, y)`` schema required by statsforecast.
Parameters
----------
train : pd.DataFrame
Training DataFrame with at least ``series_id``, ``date``, ``value``
columns.
test : pd.DataFrame
Test DataFrame with the same column structure as ``train``.
features : list, optional
Names of exogenous feature columns to carry through. When ``None``,
no exogenous frame is built for the test set.
Returns
-------
tuple
``(ts_train, ts_test_X)`` where ``ts_train`` has the statsforecast
``(unique_id, ds, y)`` schema and ``ts_test_X`` is a DataFrame of
exogenous features (or ``None`` when ``features`` is not provided).
"""
keep = ["series_id", "date", "value"] + (list(features) if features else [])
ts_train = train[keep].rename(
columns={"series_id": "unique_id", "date": "ds", "value": "y"}
).copy()
ts_train["ds"] = pd.to_datetime(ts_train["ds"])
if features:
ts_test_X = test[["series_id", "date"] + list(features)].rename(
columns={"series_id": "unique_id", "date": "ds"}
).copy()
ts_test_X["ds"] = pd.to_datetime(ts_test_X["ds"])
else:
ts_test_X = None
return ts_train, ts_test_X
def to_statsforecast_output(
raw: pd.DataFrame,
test: pd.DataFrame,
model_label: str,
runtime: float,
col_order: list,
) -> pd.DataFrame:
"""
Transform a statsforecast forecast DataFrame into the HyperTrees output schema.
The forecast column is detected as the only non-metadata column (ignoring
``unique_id``, ``ds``, ``cutoff``, ``index``, ``level_0``).
The ``date`` column is taken from ``test`` via a positional merge on
``series_id`` + within-series row index; both sides are assumed to be
(series_id, date)-ascending within each series. ``series_id`` is cast to
``str`` on both sides so int-vs-str mismatches don't break the merge.
Parameters
----------
raw : pd.DataFrame
Raw output from ``statsforecast.forecast()``.
test : pd.DataFrame
Test DataFrame containing the authoritative ``date`` column used to
align forecast rows to calendar dates.
model_label : str
Label written into the ``model`` column of the result.
runtime : float
Elapsed training time in seconds, written into the ``runtime`` column.
col_order : list
Column ordering for the returned DataFrame.
Returns
-------
pd.DataFrame
Forecast DataFrame with columns matching ``col_order``.
"""
if "unique_id" not in raw.columns:
raw = raw.reset_index()
meta = {"unique_id", "ds", "cutoff", "index", "level_0"}
model_cols = [c for c in raw.columns if c not in meta]
if not model_cols:
raise ValueError(
f"No forecast column in statsforecast output: {raw.columns.tolist()}"
)
fcst_col = model_cols[0]
out = raw[["unique_id", "ds", fcst_col]].rename(
columns={"unique_id": "series_id", "ds": "date", fcst_col: "fcst"}
)
out["series_id"] = out["series_id"].astype(str)
# Positional merge on series_id + within-series row index. Relies on both
# sides being (series_id, date)-ascending within each series.
out["_t"] = out.groupby("series_id", sort=False).cumcount()
test_dates = test[["series_id", "date"]].copy()
test_dates["series_id"] = test_dates["series_id"].astype(str)
test_dates["_t"] = test_dates.groupby("series_id", sort=False).cumcount()
out = (
out.drop(columns=["date"])
.merge(test_dates, on=["series_id", "_t"], how="left")
.drop(columns=["_t"])
)
if out["date"].isna().any():
raise ValueError(
"Positional merge with test grid produced missing dates; check "
"that `test` has every (series_id, forecast-step) row expected."
)
out["model"] = model_label
out["runtime"] = runtime
return out[col_order]
def create_lag_features(
df: pd.DataFrame,
lags: list,
features: list,
) -> pd.DataFrame:
"""
Add lag columns per series via groupby + shift.
Creates ``lag{N}`` columns (one per entry in ``lags``) sorted by
``series_id, date``. The first ``max(lags)`` rows per series are dropped
because their lag values are undefined.
Parameters
----------
df : pd.DataFrame
DataFrame with at least ``series_id``, ``date``, and ``value``
columns.
lags : list
Positive integers specifying which lags to create (e.g.,
``[1, 2, 3]``).
features : list
Names of additional columns (beyond ``series_id``, ``date``,
``value``) to carry through.
Returns
-------
pd.DataFrame
DataFrame with the original columns plus ``lag{N}`` columns, rows
with incomplete lags removed.
"""
out = df[["series_id", "date", "value"] + features].sort_values(
["series_id", "date"]
).reset_index(drop=True).copy()
grouped = out.groupby("series_id", sort=False)["value"]
lag_cols = []
for lag in lags:
col = f"lag{lag}"
out[col] = grouped.shift(lag)
lag_cols.append(col)
return out.dropna(subset=lag_cols).reset_index(drop=True)
def fill_missing_dates(
df_missing: pd.DataFrame,
date_column='date',
series_id_column='series_id',
freq="D"
) -> pd.DataFrame:
"""
Reindex a DataFrame so every (series_id, date) pair in the full date range exists.
Missing values are filled with 0.
Parameters
----------
df_missing : pd.DataFrame
DataFrame that may have gaps in its date index.
date_column : str, optional
Name of the date column (default ``'date'``).
series_id_column : str, optional
Name of the series identifier column (default ``'series_id'``).
freq : str, optional
Pandas frequency alias used to build the complete date range
(default ``"D"``).
Returns
-------
pd.DataFrame
DataFrame reindexed to the full Cartesian product of series IDs and
the complete date range, with missing numeric values filled with 0.
"""
# Get the min and max dates across all series
min_date = df_missing[date_column].min()
max_date = df_missing[date_column].max()
# Create a complete date range
full_date_range = pd.date_range(start=min_date, end=max_date, freq=freq)
# Get unique series IDs
series_ids = df_missing[series_id_column].unique()
# Create a MultiIndex with all combinations of series_id and dates
multi_idx = pd.MultiIndex.from_product(
[series_ids, full_date_range],
names=[series_id_column, date_column]
)
# Reindex the DataFrame using the MultiIndex
df_filled = (df_missing
.set_index([series_id_column, date_column])
.reindex(multi_idx)
.fillna(0)
.reset_index()
)
return df_filled
def load_experiments_specs(
dataset: str,
train_type: str,
) -> dict:
"""
Load train, test, metadata, and per-model config for a dataset.
The ``_ets`` entries in the returned dict are populated only when a
padded ETS variant exists for the dataset.
Parameters
----------
dataset : str
Directory name of the dataset under ``experiments/datasets/``
(e.g., ``"airpassengers"``).
train_type : str
Training scope; one of ``"local"`` or ``"global"``.
Returns
-------
dict
Dictionary with keys ``train``, ``test``, ``train_ets``,
``test_ets``, ``meta``, ``meta_ets``, ``config``.
"""
base_path = (Path(__file__).parent / "datasets").resolve()
# Load configuration with Hyper-Parameters for each model
if train_type == "local":
config_path = Path(base_path) / dataset / "config_local.py"
elif train_type == "global":
config_path = Path(base_path) / dataset / "config_global.py"
torch.set_float32_matmul_precision('medium')
spec = importlib.util.spec_from_file_location("config_module", str(config_path))
config_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(config_module)
config = config_module.config
# Load datasets and metadata
dataset_path = base_path / dataset
# Non Padded datasets
train: pd.DataFrame = pd.read_parquet(dataset_path / "train.parquet")
test: pd.DataFrame = pd.read_parquet(dataset_path / "test.parquet")
with open(dataset_path / "meta.json", "r") as f:
meta: dict = json.load(f)
# Padded datasets (only used for global ETS models for specific datasets)
if train_type == "global" and dataset in ["auselectricity", "m3_yearly", "tourism_monthly"]:
train_pad: pd.DataFrame = pd.read_parquet(dataset_path / "train_padded.parquet")
test_pad: pd.DataFrame = pd.read_parquet(dataset_path / "test_padded.parquet")
with open(dataset_path / "meta_ets.json", "r") as f:
meta_pad: dict = json.load(f)
else:
train_pad = None
test_pad = None
meta_pad = None
return {
"train": train,
"test": test,
"train_ets": train_pad,
"test_ets": test_pad,
"meta": meta,
"meta_ets": meta_pad,
"config": config
}
def wape(
true: ArrayLike,
fcst: ArrayLike
) -> float:
"""
Weighted Absolute Percentage Error: ``(Σ|true - fcst| / Σ|true|) * 100``.
Raises ``ValueError`` on shape mismatch or when ``Σ|true| == 0``.
Parameters
----------
true : ArrayLike
Array of actual values.
fcst : ArrayLike
Array of forecast values; must have the same shape as ``true``.
Returns
-------
float
WAPE expressed as a percentage.
"""
# Convert inputs to numpy arrays if they aren't already
true_array = np.asarray(true)
fcst_array = np.asarray(fcst)
# Check for shape mismatch
if true_array.shape != fcst_array.shape:
raise ValueError(f"Input shapes must match. Got true: {true_array.shape}, fcst: {fcst_array.shape}")
# Calculate sum of absolute true values
sum_abs_true = np.sum(np.abs(true_array))
# Check for division by zero
if sum_abs_true == 0:
raise ValueError(
"Sum of absolute true values is zero, which would cause division by zero in WAPE calculation.")
# Calculate WAPE
return (np.sum(np.abs(true_array - fcst_array)) / sum_abs_true) * 100
def calculate_error_metrics(df: pd.DataFrame,
round_digit: int = 5,
) -> pd.Series:
"""
Compute MAPE, sMAPE, WAPE, RMSE, and MAE from actual and forecast columns.
Formulas match the AWS Forecast definitions; sMAPE is implemented locally
to avoid a ``datasetsforecast.losses.smape`` bug on newer numpy versions.
Parameters
----------
df : pd.DataFrame
DataFrame containing ``value`` (actual) and ``fcst`` (forecast)
columns.
round_digit : int, optional
Number of decimal places to round each metric to (default ``5``).
Returns
-------
pd.Series
Series indexed by metric name (``MAPE``, ``sMAPE``, ``WAPE``,
``RMSE``, ``MAE``).
"""
true = df["value"].to_numpy().reshape(-1, 1)
fcst = df["fcst"].to_numpy().reshape(-1, 1)
# Local sMAPE implementation
denom = np.abs(true) + np.abs(fcst)
smape_val = np.mean(np.where(denom == 0, 0.0, 200.0 * np.abs(true - fcst) / denom))
metrics = {
"MAPE": mape(true, fcst).round(round_digit),
"sMAPE": round(float(smape_val), round_digit),
"WAPE": wape(true, fcst).round(round_digit),
"RMSE": rmse(true, fcst).round(round_digit),
"MAE": mae(true, fcst).round(round_digit),
}
return pd.Series(metrics)
def create_tsfeatures(
train: pd.DataFrame,
freq: str = "D"
) -> tuple:
"""
Extract Nixtla ``tsfeatures`` from a training DataFrame.
Missing dates are filled for the Rossmann dataset before feature
extraction.
Parameters
----------
train : pd.DataFrame
Training DataFrame with at least ``date``, ``series_id``, ``value``,
and ``dataset`` columns.
freq : str, optional
Pandas frequency alias used when filling missing dates
(default ``"D"``).
Returns
-------
tuple
``(ts_feat_df, ts_feats)`` where ``ts_feat_df`` is a DataFrame of
extracted features indexed by ``series_id`` and ``ts_feats`` is a
list of the feature column names.
"""
# Define the frequency dictionary for tsfeatures
dict_freqs = {
"D": 7,
"W": 52,
"MS": 12,
"QS": 4,
"AS-JAN": 1,
"YS-JAN": 1,
}
# Fill missing dates
if train["dataset"].unique()[0] == "Rossmann Store Sales":
ts_feat_df = fill_missing_dates(
df_missing=train[["date", "series_id", "value"]],
date_column="date",
series_id_column="series_id",
freq=freq
).rename(columns={"series_id": "unique_id", "date": "ds", "value": "y"}).copy()
else:
ts_feat_df = train[["date", "series_id", "value"]].rename(columns={"series_id": "unique_id", "date": "ds", "value": "y"}).copy()
# Add time features
ts_feat_df = tsfeatures(ts_feat_df, dict_freqs=dict_freqs).rename(columns={"unique_id": "series_id"}).fillna(0)
ts_feats = ts_feat_df.columns.tolist()[1:]
return ts_feat_df, ts_feats
def evaluate_forecasts(
results_dir: str,
train_type: str,
round_decimals: int = 3,
) -> pd.DataFrame:
"""
Load forecast CSVs and compute averaged error metrics per (dataset, model).
Reads all ``*fcsts.csv`` files from ``{results_dir}/{train_type}/``,
computes per-series error metrics, averages across series, and returns
a summary DataFrame. MASE is computed relative to AutoETS (which is
dropped from the output when ``train_type='global'``).
Parameters
----------
results_dir : str
Root directory containing ``global/`` and ``local/`` subdirectories
with forecast CSV files.
train_type : str
Training scope; one of ``"local"`` or ``"global"``.
round_decimals : int, optional
Number of decimal places to round metrics to (default ``3``).
Returns
-------
pd.DataFrame
DataFrame indexed by ``(dataset, model)`` with columns MAPE, sMAPE,
WAPE, RMSE, MAE, MASE (and ``runtime`` for global).
"""
# Load and concatenate all forecast files
fcsts_dir = os.path.join(results_dir, train_type)
fcst_files = [f for f in os.listdir(fcsts_dir) if f.endswith('fcsts.csv')]
if not fcst_files:
raise FileNotFoundError(f"No forecast CSV files found in {fcsts_dir}")
results_df_list = pd.concat(
[pd.read_csv(os.path.join(fcsts_dir, f)) for f in fcst_files],
axis=0, ignore_index=True
)
# Remove model specification from model names (e.g., "Hyper-Tree-AR(12)" -> "Hyper-Tree-AR")
results_df_list["model"] = results_df_list['model'].str.replace(r'\(.*?\)', '', regex=True)
# Extract runtimes (one value per dataset/model)
runtimes_df = (
results_df_list.groupby(["dataset", "model"])["runtime"]
.mean()
.reset_index()
)
# Calculate error metrics per dataset, series, model
fcsts_df = results_df_list.drop(columns=["runtime"])
dta_sets = fcsts_df["dataset"].unique()
err_df_list = []
for dta_set in dta_sets:
fcsts_df_sub = fcsts_df[fcsts_df["dataset"] == dta_set]
err_df_series = fcsts_df_sub.groupby(["dataset", "series_id", "model"]).apply(
calculate_error_metrics
).reset_index()
err_df_series["series_id"] = err_df_series["series_id"].astype(str)
# Compute MASE relative to AutoETS (global only)
if train_type == "global":
autoets_mae = err_df_series[err_df_series['model'] == 'AutoETS'].groupby(["series_id"])['MAE'].first()
err_df_series['MASE'] = err_df_series['MAE'] / err_df_series['series_id'].map(autoets_mae)
err_df_series = err_df_series[err_df_series['model'] != 'AutoETS'].reset_index(drop=True)
# Average across series
numeric_columns = err_df_series.select_dtypes(include=[np.number]).columns
err_df_list.append(err_df_series.groupby(["dataset", "model"])[numeric_columns].mean())
err_df = pd.concat(err_df_list, axis=0, ignore_index=False)
# Merge error metrics with runtimes
eval_df = (
err_df.reset_index()
.merge(runtimes_df, on=["dataset", "model"], how="left")
.set_index(["dataset", "model"])
.round(round_decimals)
)
if train_type == "local":
eval_df.drop(columns="runtime", inplace=True)
return _nullify_partial_rows(eval_df)
# Per-dataset AutoETS source rule used by the ablation evaluators.
# Datasets not listed here default to ``"global"``.
AUTOETS_SOURCE_BY_DATASET = {
# Keys are the display names stored in the forecast CSVs' ``dataset`` column.
"Air Passengers": "local",
}
AUTOETS_DEFAULT_SOURCE = "global"
def _autoets_source_for(dataset: str) -> str:
"""
Return the required AutoETS source for a given dataset.
Parameters
----------
dataset : str
Display name of the dataset (as stored in the forecast CSV's
``dataset`` column).
Returns
-------
str
``"global"`` or ``"local"``, looked up from
``AUTOETS_SOURCE_BY_DATASET`` (default ``"global"``).
"""
return AUTOETS_SOURCE_BY_DATASET.get(dataset, AUTOETS_DEFAULT_SOURCE)
def _load_autoets_mae(results_dir: str) -> pd.Series:
"""
Load AutoETS forecasts and return per-series MAE.
Reads AutoETS forecast CSVs from the global and local result directories,
selects the appropriate source per dataset according to
``AUTOETS_SOURCE_BY_DATASET``, and computes per-series MAE.
Parameters
----------
results_dir : str
Root directory containing ``global/`` and ``local/`` subdirectories
with forecast CSV files.
Returns
-------
pd.Series
MAE values indexed by ``(dataset, series_id)``.
"""
autoets_rows = []
for source in ("global", "local"):
source_dir = os.path.join(results_dir, source)
if not os.path.isdir(source_dir):
continue
for f in os.listdir(source_dir):
if not f.endswith("_fcsts.csv"):
continue
df = pd.read_csv(os.path.join(source_dir, f))
ae_df = df[df["model"].str.startswith("AutoETS")]
if not ae_df.empty:
ae_df = ae_df.assign(source=source)
autoets_rows.append(ae_df)
if not autoets_rows:
raise FileNotFoundError(
f"AutoETS forecasts not found in {results_dir}/global or {results_dir}/local. "
"Run the global and/or local stages first; the ablation evaluators "
"rely on those AutoETS forecasts to compute MASE."
)
autoets_df = pd.concat(autoets_rows, ignore_index=True)
autoets_df["model"] = "AutoETS"
autoets_df["series_id"] = autoets_df["series_id"].astype(str)
# Keep only the row whose `source` matches the required source for its
# dataset; see AUTOETS_SOURCE_BY_DATASET above.
required = autoets_df["dataset"].map(_autoets_source_for)
autoets_df = (
autoets_df[autoets_df["source"] == required]
.drop(columns=["source"])
.reset_index(drop=True)
)
err = (
autoets_df.groupby(["dataset", "series_id", "model"])
.apply(calculate_error_metrics)
.reset_index()
)
return err.set_index(["dataset", "series_id"])["MAE"]
def evaluate_ablation_rossmann(
results_dir: str = "results/",
round_decimals: int = 3,
) -> pd.DataFrame:
"""
Evaluate Rossmann ablation forecasts (Base, A1-A11).
MASE is computed relative to the AutoETS forecasts in the global
Rossmann run.
Parameters
----------
results_dir : str, optional
Root results directory (default ``"results/"``).
round_decimals : int, optional
Number of decimal places to round metrics to (default ``3``).
Returns
-------
pd.DataFrame
DataFrame indexed by ``(dataset, model, ablation)`` with columns
MAPE, sMAPE, WAPE, RMSE, MAE, MASE.
"""
fcsts_dir = os.path.join(results_dir, "ablation", "rossmann")
fcst_files = [f for f in os.listdir(fcsts_dir) if f.endswith("fcsts.csv")]
if not fcst_files:
raise FileNotFoundError(f"No forecast CSV files found in {fcsts_dir}")
df = pd.concat(
[pd.read_csv(os.path.join(fcsts_dir, f)) for f in fcst_files],
axis=0, ignore_index=True,
)
# Strip model specification suffixes (e.g., "Hyper-Tree-AR(21)" -> "Hyper-Tree-AR")
df["model"] = df["model"].str.replace(r"\(.*?\)", "", regex=True)
# "Base" row = unablated metrics taken from the global Rossmann run.
# Paper (Table 4) reports each A1-A11 variant alongside the Base model
# whose metrics come from the global run (Table 3).
base_path = os.path.join(results_dir, "global", "rossmann_hypertrees_fcsts.csv")
base_df = pd.read_csv(base_path)
base_df["model"] = base_df["model"].str.replace(r"\(.*?\)", "", regex=True)
base_df = base_df[base_df["model"].isin(["Hyper-Tree-AR", "Hyper-TreeNet-AR"])].copy()
base_df["ablation"] = "Base"
df = pd.concat([df, base_df[df.columns]], axis=0, ignore_index=True)
# Error metrics per (dataset, model, ablation, series)
err_df = df.groupby(["dataset", "model", "ablation", "series_id"]).apply(
calculate_error_metrics
).reset_index()
err_df["series_id"] = err_df["series_id"].astype(str)
# Order ablations: Base first, then A1, A2, ..., A11 (not lexicographic).
ablation_order = ["Base"] + sorted(
[a for a in err_df["ablation"].unique() if a != "Base"],
key=lambda s: int(str(s).lstrip("A")),
)
err_df["ablation"] = pd.Categorical(
err_df["ablation"], categories=ablation_order, ordered=True
)
# MASE = MAE / AutoETS-MAE per series, looked up from the global Rossmann run.
# The `dataset` column in the CSVs uses the display name ("Rossmann Store
# Sales") rather than the directory name, so read it from the ablation
# CSVs themselves and slice on that.
rossmann_dataset_name = df["dataset"].iloc[0]
autoets_mae = _load_autoets_mae(results_dir).xs(rossmann_dataset_name, level="dataset")
err_df["MASE"] = err_df.apply(
lambda row: row["MAE"] / autoets_mae[row["series_id"]]
if row["series_id"] in autoets_mae.index else np.nan,
axis=1,
)
# Average across series per (dataset, model, ablation)
numeric_columns = err_df.select_dtypes(include=[np.number]).columns
eval_df = (
err_df.groupby(["dataset", "model", "ablation"], observed=True)[numeric_columns]
.mean()
.round(round_decimals)
.sort_index()
)
return _nullify_partial_rows(eval_df)
def evaluate_ablation_embeddings(
results_dir: str = "results/",
round_decimals: int = 3,
) -> pd.DataFrame:
"""
Evaluate embedding-dimension ablation forecasts.
MASE is computed relative to AutoETS per (dataset, series_id).
Parameters
----------
results_dir : str, optional
Root results directory (default ``"results/"``).
round_decimals : int, optional
Number of decimal places to round metrics to (default ``3``).
Returns
-------
pd.DataFrame
DataFrame indexed by ``(dataset, model, embedding_dim)`` with
columns MAPE, sMAPE, WAPE, RMSE, MAE, MASE, and ``runtime``.
"""
fcsts_dir = os.path.join(results_dir, "ablation", "embedding_evaluation")
fcst_files = [f for f in os.listdir(fcsts_dir) if f.endswith("fcsts.csv")]
if not fcst_files:
raise FileNotFoundError(f"No forecast CSV files found in {fcsts_dir}")
df = pd.concat(
[pd.read_csv(os.path.join(fcsts_dir, f)) for f in fcst_files],
axis=0, ignore_index=True,
)
# Strip model specification suffixes
df["model"] = df["model"].str.replace(r"\(.*?\)", "", regex=True)
# Drop any AutoETS rows in the ablation CSVs; AutoETS is pulled from the
# global/local stages for the MASE denominator.
df = df[df["model"] != "AutoETS"].reset_index(drop=True)
# embedding_dim=1 baseline: pull Hyper-TreeNet-AR results from the
# global/local hypertrees runs (default config uses embedding_dimension=1).
# airpassengers runs locally; all other datasets run globally.
base_frames = []
for subdir, pattern in [("global", "_hypertrees_fcsts.csv"), ("local", "airpassengers_hypertrees_fcsts.csv")]:
ht_dir = os.path.join(results_dir, subdir)
if not os.path.isdir(ht_dir):
continue
for f in os.listdir(ht_dir):
if subdir == "local" and f != pattern:
continue
if not f.endswith("_hypertrees_fcsts.csv"):
continue
base_df = pd.read_csv(os.path.join(ht_dir, f))
base_df["model"] = base_df["model"].str.replace(r"\(.*?\)", "", regex=True)
base_df = base_df[base_df["model"] == "Hyper-TreeNet-AR"].copy()
base_df["embedding_dim"] = 1
base_frames.append(base_df)
if base_frames:
base_all = pd.concat(base_frames, axis=0, ignore_index=True)
df = pd.concat([df, base_all[df.columns]], axis=0, ignore_index=True)
# Extract runtimes (one value per dataset/model/embedding_dim)
runtimes_df = (
df.groupby(["dataset", "model", "embedding_dim"])["runtime"]
.mean()
.reset_index()
)
runtimes_df["embedding_dim"] = pd.to_numeric(runtimes_df["embedding_dim"])
df = df.drop(columns=["runtime"])
# Error metrics per (dataset, model, embedding_dim, series)
err_df = df.groupby(["dataset", "model", "embedding_dim", "series_id"]).apply(
calculate_error_metrics
).reset_index()
err_df["series_id"] = err_df["series_id"].astype(str)
# Ensure embedding_dim sorts numerically (1, 3, 5, 10) rather than
err_df["embedding_dim"] = pd.to_numeric(err_df["embedding_dim"])
# MASE = MAE / AutoETS-MAE per (dataset, series_id); AutoETS is loaded
# from the global (and local, for AirPassengers) result directories.
autoets_mae = _load_autoets_mae(results_dir)
err_df["MASE"] = err_df.apply(
lambda row: row["MAE"] / autoets_mae[(row["dataset"], row["series_id"])]
if (row["dataset"], row["series_id"]) in autoets_mae.index else np.nan,
axis=1,
)
# Average across series per (dataset, model, embedding_dim).
groupby_keys = ["dataset", "model", "embedding_dim"]
numeric_columns = [
c for c in err_df.select_dtypes(include=[np.number]).columns
if c not in groupby_keys
]
eval_df = (
err_df.groupby(groupby_keys)[numeric_columns]
.mean()
.sort_index()
)
eval_df = (
eval_df.reset_index()
.merge(runtimes_df, on=groupby_keys, how="left")
.set_index(groupby_keys)
.round(round_decimals)
)
return _nullify_partial_rows(eval_df)
def thousand_separator(x, pos):
"""
Matplotlib tick formatter that adds thousand separators.
Parameters
----------
x : float
Tick value.
pos : int
Tick position (required by the Matplotlib formatter interface,
unused).
Returns
-------
str
``x`` formatted with comma thousand separators and no decimal
places.
"""
return f'{x:,.0f}'
formatter = FuncFormatter(thousand_separator)
def custom_format(value, is_min=False):
"""
Format a float for LaTeX tables, bolding the value if it is the row minimum.
Parameters
----------
value : float
Numeric value to format.
is_min : bool, optional
When ``True``, wrap the formatted string in ``\\textbf{}``
(default ``False``).
Returns
-------
str
LaTeX-ready string; empty string for NaN values.
"""
if pd.isna(value):
return ''
if abs(value) >= 1000:
formatted = f"{value:,.1f}"
else:
formatted = f"{value:.3f}"
if is_min:
return r'\textbf{' + formatted + '}'
return formatted
def latex_table_to_dataframe(latex_content):
"""
Parse a LaTeX tabular environment into a pandas DataFrame.
Parameters
----------
latex_content : str
Raw LaTeX string containing a ``\\begin{tabular}...\\end{tabular}``
block.
Returns
-------
pd.DataFrame
DataFrame whose columns are the table headers and whose rows are
the data between ``\\midrule`` and ``\\bottomrule``. Numeric
columns are converted automatically.
"""
# Remove newlines and extra spaces
latex_content = re.sub(r'\s+', ' ', latex_content.strip())
# Extract the table content
table_pattern = re.compile(r'\\begin{tabular}.*?\\end{tabular}')
table_match = table_pattern.search(latex_content)
if not table_match:
raise ValueError("Could not find a tabular environment in the LaTeX content")
latex_table = table_match.group(0)
# Extract column names
header_match = re.search(r'\\begin{tabular}{.*?}(.*?)\\\\', latex_table)
if header_match:
headers = [h.strip() for h in header_match.group(1).split('&')]
else:
raise ValueError("Could not find table headers")
# Extract data rows
data_pattern = re.compile(r'\\midrule(.*?)\\bottomrule', re.DOTALL)
data_match = data_pattern.search(latex_table)
if data_match:
data_rows = data_match.group(1).strip().split('\\\\')
data = [row.strip().split('&') for row in data_rows if row.strip()]
else:
raise ValueError("Could not find table data")
# Create DataFrame
df = pd.DataFrame(data, columns=headers)