File size: 48,709 Bytes
a2fecd2 8d1b1b5 a2fecd2 c34c912 a2fecd2 c34c912 a2fecd2 8d1b1b5 a2fecd2 bb6be84 a2fecd2 bb6be84 a2fecd2 c34c912 a2fecd2 8d1b1b5 a2fecd2 c34c912 a2fecd2 c34c912 a2fecd2 8d1b1b5 a2fecd2 c34c912 a2fecd2 8d1b1b5 a2fecd2 8d1b1b5 a2fecd2 47aa70f a2fecd2 8d1b1b5 a2fecd2 8d1b1b5 a2fecd2 8d1b1b5 a2fecd2 8d1b1b5 a2fecd2 8d1b1b5 a2fecd2 8d1b1b5 a2fecd2 c34c912 a2fecd2 c34c912 a2fecd2 c06d939 a2fecd2 c06d939 a2fecd2 8d1b1b5 a2fecd2 c34c912 a2fecd2 8d1b1b5 a2fecd2 c34c912 a2fecd2 8d1b1b5 a2fecd2 8d1b1b5 a2fecd2 8d1b1b5 a2fecd2 8d1b1b5 a2fecd2 8d1b1b5 a2fecd2 8d1b1b5 a2fecd2 8d1b1b5 a2fecd2 8d1b1b5 a2fecd2 8d1b1b5 a2fecd2 8d1b1b5 a2fecd2 | 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 | #!/usr/bin/env python3
"""Re-implement the DECODE paper training pipeline for local I-BLEND data.
The paper pipeline is:
1. Fuse energy, occupancy, calendar, and weather-like environmental features.
2. Align everything to a 10-minute sampling rate.
3. Normalize features with Min-Max scaling.
4. Split chronologically into train/validation/test with a 70:15:15 ratio.
5. Compare LSTM with Linear Regression, Decision Tree, and Random Forest.
This local implementation supports two targets:
- paper_buildings: 7 building-level series matching the paper.
- meters: 9 meter-level series from all_buildings_power.csv.
Weather is optional because the local weather file in this workspace starts in
2018, while the energy data ends in 2017. The script detects this and continues.
"""
from __future__ import annotations
import argparse
import joblib
import os
import json
import math
import sys
import warnings
from dataclasses import dataclass
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_DATA_MINING_ROOT = ROOT if (ROOT / "IIITD_occupancy_dataset").exists() else ROOT.parent
DATA_MINING_ROOT = Path(os.environ.get("IBLEND_DATA_ROOT", DEFAULT_DATA_MINING_ROOT))
DEFAULT_ENERGY_FILE = DATA_MINING_ROOT / "energy_dataset" / "all_buildings_power.csv"
if not DEFAULT_ENERGY_FILE.exists():
nested_energy_file = DATA_MINING_ROOT / "energy_dataset" / "energy_dataset" / "all_buildings_power.csv"
if nested_energy_file.exists():
DEFAULT_ENERGY_FILE = nested_energy_file
ENERGY_FILE = Path(os.environ.get("IBLEND_ENERGY_FILE", DEFAULT_ENERGY_FILE))
OCCUPANCY_DIR = DATA_MINING_ROOT / "IIITD_occupancy_dataset" / "IIITD_occupancy_dataset"
CALENDAR_DIR = DATA_MINING_ROOT / "iiitd_calender_schedule" / "iiitd_calender_schedule"
WEATHER_FILE = DATA_MINING_ROOT / "weather_comparison" / "weather_comparison" / "IIITD_and_airport_data.csv"
OUT_DIR = ROOT / "decode_reimplementation_outputs"
TZ = "Asia/Kolkata"
PAPER_BUILDINGS = {
"Academic": {"meters": ["Academic"], "occupancy": "ACB"},
"Boys_hostel": {"meters": ["Boys_main", "Boys_backup"], "occupancy": "BH"},
"Girls_hostel": {"meters": ["Girls_main", "Girls_backup"], "occupancy": "GH"},
"Library": {"meters": ["Library"], "occupancy": "LB"},
"Lecture": {"meters": ["Lecture"], "occupancy": "LCB"},
"Dining": {"meters": ["Mess"], "occupancy": "DB"},
"Facilities": {"meters": ["Facilities"], "occupancy": "SRB"},
}
PREV_SAME_DAY_TYPE_ENERGY_FEATURES = [
"prev_same_day_type_energy_1",
"prev_same_day_type_energy_2",
"prev_same_day_type_energy_3",
]
LEGACY_PREV_SAME_DAY_TYPE_ENERGY_FEATURES = [
"same_day_type_lag_1",
"same_day_type_lag_2",
"same_day_type_lag_3",
]
METER_TARGETS = {
"Academic": {"meters": ["Academic"], "occupancy": "ACB"},
"Boys_main": {"meters": ["Boys_main"], "occupancy": "BH"},
"Boys_backup": {"meters": ["Boys_backup"], "occupancy": "BH"},
"Facilities": {"meters": ["Facilities"], "occupancy": "SRB"},
"Girls_main": {"meters": ["Girls_main"], "occupancy": "GH"},
"Girls_backup": {"meters": ["Girls_backup"], "occupancy": "GH"},
"Lecture": {"meters": ["Lecture"], "occupancy": "LCB"},
"Library": {"meters": ["Library"], "occupancy": "LB"},
"Mess": {"meters": ["Mess"], "occupancy": "DB"},
}
@dataclass
class SplitData:
x_train: object
x_val: object
x_test: object
y_train: object
y_val: object
y_test: object
feature_names: list[str]
x_all: object
y_all: object
clean_index: object
train_end: int
val_end: int
test_span_steps: int | None = None
def import_stack():
try:
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_absolute_error, r2_score
from sklearn.preprocessing import MinMaxScaler
from sklearn.tree import DecisionTreeRegressor
except ImportError as exc:
missing = str(exc).split("No module named ")[-1].strip("'")
raise SystemExit(
f"Missing dependency: {missing}\n"
"Install the base training stack with:\n"
f" {sys.executable} -m pip install pandas numpy scikit-learn\n"
"Install LSTM support with either PyTorch or TensorFlow:\n"
f" {sys.executable} -m pip install torch\n"
f" {sys.executable} -m pip install tensorflow\n"
) from exc
torch_import_error = None
try:
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
except Exception as exc:
torch = None
nn = None
DataLoader = None
TensorDataset = None
torch_import_error = f"{type(exc).__name__}: {exc}"
lgbm_import_error = None
try:
import lightgbm as lgb
except Exception as exc:
lgb = None
lgbm_import_error = f"{type(exc).__name__}: {exc}"
statsmodels_import_error = None
try:
from statsmodels.tsa.arima.model import ARIMA
except Exception as exc:
ARIMA = None
statsmodels_import_error = f"{type(exc).__name__}: {exc}"
tf = None
keras = None
tf_import_error = None
disable_tf_when_torch_available = os.environ.get("DECODE_DISABLE_TENSORFLOW", "1") == "1"
if disable_tf_when_torch_available and torch is not None:
tf_import_error = "disabled because PyTorch is available"
else:
try:
import tensorflow as tf
from tensorflow import keras
except Exception as exc:
tf = None
keras = None
tf_import_error = f"{type(exc).__name__}: {exc}"
return {
"np": np,
"pd": pd,
"RandomForestRegressor": RandomForestRegressor,
"Ridge": Ridge,
"DecisionTreeRegressor": DecisionTreeRegressor,
"MinMaxScaler": MinMaxScaler,
"mean_absolute_error": mean_absolute_error,
"r2_score": r2_score,
"torch": torch,
"nn": nn,
"DataLoader": DataLoader,
"TensorDataset": TensorDataset,
"torch_import_error": torch_import_error,
"lgb": lgb,
"lgbm_import_error": lgbm_import_error,
"ARIMA": ARIMA,
"statsmodels_import_error": statsmodels_import_error,
"tf": tf,
"keras": keras,
"tf_import_error": tf_import_error,
}
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="DECODE paper re-implementation for I-BLEND data.")
parser.add_argument(
"--mode",
choices=["paper_buildings", "meters"],
default="paper_buildings",
help="paper_buildings trains 7 building-level targets; meters trains 9 meter-level targets.",
)
parser.add_argument(
"--target",
default="all",
help="Target name to train, or 'all'. Names depend on --mode.",
)
parser.add_argument("--freq", default="10min", help="Common sampling frequency. Paper uses 10min.")
parser.add_argument("--lookback", type=int, default=18, help="LSTM lookback steps. 18 at 10min = 3 hours.")
parser.add_argument("--horizon", type=int, default=1, help="Prediction horizon in rows. 1 at 10min = next 10min.")
parser.add_argument("--horizon-days", type=float, default=0, help="Prediction horizon in days. Overrides --horizon when > 0.")
parser.add_argument("--test-span-days", type=float, default=0, help="Evaluate only this many days from the chronological test split.")
parser.add_argument("--epochs", type=int, default=20, help="LSTM epochs. Paper uses 20.")
parser.add_argument("--batch-size", type=int, default=64, help="LSTM batch size. Paper uses 64.")
parser.add_argument("--rf-trees", type=int, default=500, help="Random Forest trees. Paper tuned to 500.")
parser.add_argument(
"--dl-models",
default="lstm,cnn,tcn",
help="Comma-separated deep models: lstm,cnn,tcn,timesnet,none.",
)
parser.add_argument("--include-arima", action="store_true", help="Fit ARIMA(2,1,2). This can be slow on full series.")
parser.add_argument("--arima-max-train", type=int, default=20000, help="Maximum recent train points for ARIMA fitting.")
parser.add_argument("--max-rows", type=int, default=0, help=argparse.SUPPRESS)
parser.add_argument("--include-weather", action="store_true", help="Try to merge local weather data if time ranges overlap.")
parser.add_argument("--skip-lstm", action="store_true", help="Only train baseline ML models.")
parser.add_argument("--output-dir", default=str(OUT_DIR), help="Output directory.")
return parser.parse_args()
def read_energy_10min(pd, freq: str):
if not ENERGY_FILE.exists():
raise FileNotFoundError(f"Missing energy file: {ENERGY_FILE}")
df = pd.read_csv(ENERGY_FILE, na_values=["NA", ""])
df["datetime"] = pd.to_datetime(df["timestamp"], unit="s", utc=True).dt.tz_convert(TZ)
df = df.drop(columns=["timestamp"]).set_index("datetime").sort_index()
# Paper predicts energy in Wh. Original columns are power in W at 1-minute resolution.
# For a 10-minute interval: Wh = mean(W) * 10 / 60.
mean_power_w = df.resample(freq).mean()
interval_minutes = pd.Timedelta(freq).total_seconds() / 60
energy_wh = mean_power_w * interval_minutes / 60
return energy_wh
def read_occupancy_10min(pd, code: str, freq: str):
path = OCCUPANCY_DIR / f"{code}.csv"
if not path.exists():
warnings.warn(f"Missing occupancy file for {code}: {path}")
return None
df = pd.read_csv(path, na_values=["NA", ""])
df["datetime"] = pd.to_datetime(df["timestamp"], unit="s", utc=True).dt.tz_convert(TZ)
df = df.drop(columns=["timestamp"]).set_index("datetime").sort_index()
occ = df.resample(freq).mean()
occ["occupancy_count"] = occ["occupancy_count"].interpolate(method="time").ffill().bfill()
return occ
def read_calendar(pd):
frames = []
for path in sorted(CALENDAR_DIR.glob("calender_year_*.csv")):
frames.append(pd.read_csv(path))
if not frames:
warnings.warn(f"No calendar files found in {CALENDAR_DIR}")
return None
cal = pd.concat(frames, ignore_index=True)
cal["date"] = pd.to_datetime(cal["Date"]).dt.date
cal = cal[["date", "working_day", "activity"]].drop_duplicates("date")
cal["working_day"] = pd.to_numeric(cal["working_day"], errors="coerce").fillna(0).astype(int)
cal["activity"] = cal["activity"].fillna("unknown").astype(str)
cal["activity_code"] = cal["activity"].astype("category").cat.codes
return cal
def read_weather_10min(pd, freq: str):
if not WEATHER_FILE.exists():
warnings.warn(f"Missing weather file: {WEATHER_FILE}")
return None
df = pd.read_csv(WEATHER_FILE, na_values=["NA", ""])
first_col = df.columns[0]
df = df.rename(columns={first_col: "datetime"})
df["datetime"] = pd.to_datetime(df["datetime"], errors="coerce")
df = df.dropna(subset=["datetime"]).set_index("datetime").sort_index()
if df.index.tz is None:
df.index = df.index.tz_localize(TZ)
weather = df.resample(freq).mean().interpolate(method="time").ffill().bfill()
return weather
def horizon_steps_from_args(pd, args) -> int:
if args.horizon_days and args.horizon_days > 0:
freq_delta = pd.Timedelta(args.freq)
steps = int(round(pd.Timedelta(days=args.horizon_days) / freq_delta))
return max(1, steps)
return max(1, args.horizon)
def test_span_steps_from_args(pd, args) -> int | None:
if args.test_span_days and args.test_span_days > 0:
freq_delta = pd.Timedelta(args.freq)
steps = int(round(pd.Timedelta(days=args.test_span_days) / freq_delta))
return max(1, steps)
return None
def describe_steps(pd, steps: int, freq: str) -> str:
delta = pd.Timedelta(freq) * steps
total_minutes = delta.total_seconds() / 60
if total_minutes % 1440 == 0:
return f"{int(total_minutes // 1440)} day(s)"
if total_minutes % 60 == 0:
return f"{int(total_minutes // 60)} hour(s)"
return f"{total_minutes:g} minute(s)"
def add_time_features(pd, df):
out = df.copy()
idx = out.index
out["hour"] = idx.hour
out["day_of_week"] = idx.dayofweek
out["month"] = idx.month
out["time_slot"] = idx.hour * 60 + idx.minute
out["hour_sin"] = (2 * math.pi * out["hour"] / 24).map(math.sin)
out["hour_cos"] = (2 * math.pi * out["hour"] / 24).map(math.cos)
out["dow_sin"] = (2 * math.pi * out["day_of_week"] / 7).map(math.sin)
out["dow_cos"] = (2 * math.pi * out["day_of_week"] / 7).map(math.cos)
out["month_sin"] = (2 * math.pi * out["month"] / 12).map(math.sin)
out["month_cos"] = (2 * math.pi * out["month"] / 12).map(math.cos)
return out
def add_historical_features(df):
out = df.copy()
out["energy_lag_1"] = out["energy_wh"].shift(1)
out["energy_lag_6"] = out["energy_wh"].shift(6)
out["energy_lag_144"] = out["energy_wh"].shift(144)
out["energy_lag_1008"] = out["energy_wh"].shift(1008)
out["rolling_mean_6"] = out["energy_wh"].shift(1).rolling(6).mean()
out["rolling_mean_144"] = out["energy_wh"].shift(1).rolling(144).mean()
out["rolling_std_144"] = out["energy_wh"].shift(1).rolling(144).std()
# DECODE paper feature: for each timestamp, use energy from the previous
# three days that have the same working/non-working class and same time slot.
same_type_groups = out.sort_index().groupby(["working_day", "time_slot"], sort=False)["energy_wh"]
for lag_number, column in enumerate(PREV_SAME_DAY_TYPE_ENERGY_FEATURES, start=1):
out[column] = same_type_groups.shift(lag_number).reindex(out.index)
return out
def choose_feature_names(pd, data) -> list[str]:
non_features = {"target", "date", "activity", *LEGACY_PREV_SAME_DAY_TYPE_ENERGY_FEATURES}
feature_names = [
c for c in data.columns
if c not in non_features and pd.api.types.is_numeric_dtype(data[c])
]
missing_same_type_features = [
c for c in PREV_SAME_DAY_TYPE_ENERGY_FEATURES
if c not in feature_names
]
if missing_same_type_features:
raise ValueError(
"Missing DECODE same-working-day-class energy features: "
f"{missing_same_type_features}"
)
return feature_names
def build_target_frame(pd, energy_10min, calendar, target_name: str, target_spec: dict, freq: str, include_weather: bool):
missing_meters = [m for m in target_spec["meters"] if m not in energy_10min.columns]
if missing_meters:
raise KeyError(f"{target_name} references missing meter columns: {missing_meters}")
df = pd.DataFrame(index=energy_10min.index)
df["energy_wh"] = energy_10min[target_spec["meters"]].sum(axis=1, min_count=1)
occ = read_occupancy_10min(pd, target_spec["occupancy"], freq)
if occ is not None:
df = df.join(occ[["occupancy_count"]], how="left")
else:
df["occupancy_count"] = math.nan
df["date"] = df.index.date
if calendar is not None:
df = df.reset_index().merge(calendar, on="date", how="left").set_index("datetime").sort_index()
else:
df["working_day"] = (df.index.dayofweek < 5).astype(int)
df["activity"] = "unknown"
df["activity_code"] = 0
if include_weather:
weather = read_weather_10min(pd, freq)
if weather is not None:
before = len(df)
df = df.join(weather, how="inner")
if df.empty:
warnings.warn(
"Weather data has no overlap with this target after joining. "
"Continuing without weather features."
)
df = pd.DataFrame(index=energy_10min.index)
df["energy_wh"] = energy_10min[target_spec["meters"]].sum(axis=1, min_count=1)
occ = read_occupancy_10min(pd, target_spec["occupancy"], freq)
if occ is not None:
df = df.join(occ[["occupancy_count"]], how="left")
df["date"] = df.index.date
df = df.reset_index().merge(calendar, on="date", how="left").set_index("datetime").sort_index()
elif len(df) < before:
warnings.warn(f"Weather join reduced rows from {before} to {len(df)}.")
df["occupancy_count"] = df["occupancy_count"].interpolate(method="time").ffill().bfill()
fallback_working_day = pd.Series((df.index.dayofweek < 5).astype(int), index=df.index)
df["working_day"] = df["working_day"].fillna(fallback_working_day).astype(int)
df["activity"] = df["activity"].fillna("unknown").astype(str)
df["activity_code"] = df["activity_code"].fillna(0).astype(int)
df = add_time_features(pd, df)
df = add_historical_features(df)
return df
def make_ml_split(
np,
pd,
MinMaxScaler,
df,
horizon: int,
max_rows: int,
test_span_steps: int | None = None,
global_scalers: tuple[object, object] | None = None,
) -> tuple[SplitData, object, object]:
data = df.copy()
data["target"] = data["energy_wh"].shift(-horizon)
feature_names = choose_feature_names(pd, data)
clean = data[feature_names + ["target"]].replace([np.inf, -np.inf], np.nan).dropna()
if max_rows and len(clean) > max_rows:
clean = clean.tail(max_rows)
n = len(clean)
if n < 100:
raise ValueError(f"Not enough clean rows after preprocessing: {n}")
train_end = int(n * 0.70)
val_end = int(n * 0.85)
x_raw = clean[feature_names]
y_raw = clean[["target"]]
if global_scalers is None:
x_scaler, y_scaler = MinMaxScaler(), MinMaxScaler()
x_scaler.fit(x_raw.iloc[:train_end])
y_scaler.fit(y_raw.iloc[:train_end])
else:
x_scaler, y_scaler = global_scalers
x_all = x_scaler.transform(x_raw)
y_all = y_scaler.transform(y_raw).ravel()
x_train, x_val, x_test = x_all[:train_end], x_all[train_end:val_end], x_all[val_end:]
y_train, y_val, y_test = y_all[:train_end], y_all[train_end:val_end], y_all[val_end:]
if test_span_steps is not None:
x_test = x_test[:test_span_steps]
y_test = y_test[:test_span_steps]
split = SplitData(
x_train=x_train,
x_val=x_val,
x_test=x_test,
y_train=y_train,
y_val=y_val,
y_test=y_test,
feature_names=feature_names,
x_all=x_all,
y_all=y_all,
clean_index=clean.index,
train_end=train_end,
val_end=val_end,
test_span_steps=test_span_steps,
)
return split, y_scaler, clean
def make_lstm_sequences(np, split: SplitData, lookback: int):
x_all = np.vstack([split.x_train, split.x_val, split.x_test])
y_all = np.concatenate([split.y_train, split.y_val, split.y_test])
n_train = len(split.y_train)
n_val = len(split.y_val)
xs, ys, end_indices = [], [], []
for end in range(lookback - 1, len(y_all)):
# Use the sequence ending at row `end` to predict that row's target.
# The target was already shifted by --horizon during feature engineering,
# so excluding row `end` here would make sequence models forecast one
# extra step farther than the baseline models.
xs.append(x_all[end - lookback + 1:end + 1])
ys.append(y_all[end])
end_indices.append(end)
xs = np.asarray(xs)
ys = np.asarray(ys)
end_indices = np.asarray(end_indices)
train_mask = end_indices < n_train
val_mask = (end_indices >= n_train) & (end_indices < n_train + n_val)
test_mask = end_indices >= n_train + n_val
return (
xs[train_mask],
xs[val_mask],
xs[test_mask],
ys[train_mask],
ys[val_mask],
ys[test_mask],
)
def inverse_metric(np, y_scaler, y_true_scaled, y_pred_scaled, mean_absolute_error, r2_score):
y_true = y_scaler.inverse_transform(np.asarray(y_true_scaled).reshape(-1, 1)).ravel()
y_pred = y_scaler.inverse_transform(np.asarray(y_pred_scaled).reshape(-1, 1)).ravel()
return {
"mae_normalized": float(mean_absolute_error(y_true_scaled, y_pred_scaled)),
"mae_wh": float(mean_absolute_error(y_true, y_pred)),
"r2": float(r2_score(y_true, y_pred)),
}
def fit_global_scalers(stack, frames, horizon, max_rows=0):
np, pd = stack["np"], stack["pd"]
x_parts, y_parts, expected = [], [], None
for name, frame in frames.items():
data = frame.copy()
data["target"] = data["energy_wh"].shift(-horizon)
features = choose_feature_names(pd, data)
expected = features if expected is None else expected
if features != expected:
raise ValueError(f"Feature mismatch for global scaling: {name}")
clean = data[features + ["target"]].replace([np.inf, -np.inf], np.nan).dropna()
if max_rows and len(clean) > max_rows:
clean = clean.tail(max_rows)
end = int(len(clean) * .70)
x_parts.append(clean[features].iloc[:end])
y_parts.append(clean[["target"]].iloc[:end])
xs, ys = stack["MinMaxScaler"](), stack["MinMaxScaler"]()
xs.fit(pd.concat(x_parts)); ys.fit(pd.concat(y_parts))
return xs, ys
def save_predictions(pd, np, out_dir, target, model_name, split, y_scaler, pred_scaled, start=0):
pred_scaled = np.asarray(pred_scaled).ravel()
actual_scaled = split.y_all[start:start + len(pred_scaled)]
positions = np.arange(start, start + len(pred_scaled))
table = pd.DataFrame({
"datetime": split.clean_index[start:start + len(pred_scaled)],
"partition": np.where(positions < split.train_end, "train", np.where(positions < split.val_end, "validation", "test")),
"actual_normalized": actual_scaled,
"prediction_normalized": pred_scaled,
"actual_wh": y_scaler.inverse_transform(actual_scaled.reshape(-1, 1)).ravel(),
"prediction_wh": y_scaler.inverse_transform(pred_scaled.reshape(-1, 1)).ravel(),
})
path = out_dir / "predictions" / target / f"{model_name}_full.csv"
path.parent.mkdir(parents=True, exist_ok=True)
table.to_csv(path, index=False)
return path
def save_feature_importance(pd, out_dir: Path, target_name: str, model_name: str, feature_names: list[str], importances):
importance_dir = out_dir / "feature_importance"
importance_dir.mkdir(parents=True, exist_ok=True)
table = pd.DataFrame({"feature": feature_names, "importance": importances})
table = table.sort_values("importance", ascending=False)
table.to_csv(importance_dir / f"{target_name}_{model_name}_feature_importance.csv", index=False)
def train_baselines(stack, split: SplitData, x_scaler, y_scaler, args, out_dir: Path, target_name: str):
np = stack["np"]
pd = stack["pd"]
models = {
"ridge_regression": stack["Ridge"](alpha=1.0),
"decision_tree": stack["DecisionTreeRegressor"](max_depth=14, min_samples_split=20, random_state=42),
"random_forest": stack["RandomForestRegressor"](
n_estimators=args.rf_trees,
random_state=42,
n_jobs=-1,
min_samples_split=2,
),
}
if stack["lgb"] is not None:
models["lightgbm"] = stack["lgb"].LGBMRegressor(
n_estimators=500,
learning_rate=0.03,
num_leaves=31,
subsample=0.9,
colsample_bytree=0.9,
random_state=42,
n_jobs=-1,
verbose=-1,
)
rows = []
for name, model in models.items():
model.fit(split.x_train, split.y_train)
pred = model.predict(split.x_test)
full_pred = model.predict(split.x_all)
metrics = inverse_metric(
np,
y_scaler,
split.y_test,
pred,
stack["mean_absolute_error"],
stack["r2_score"],
)
model_path = out_dir / "models" / target_name / f"{name}.joblib"
model_path.parent.mkdir(parents=True, exist_ok=True)
joblib.dump({"model": model, "x_scaler": x_scaler, "y_scaler": y_scaler,
"feature_names": split.feature_names}, model_path)
metrics["model_path"] = str(model_path)
metrics["prediction_path"] = str(save_predictions(
pd, np, out_dir, target_name, name, split, y_scaler, full_pred))
if name == "lightgbm" and hasattr(model, "feature_importances_"):
save_feature_importance(pd, out_dir, target_name, name, split.feature_names, model.feature_importances_)
metrics["feature_importance_path"] = str(
out_dir / "feature_importance" / f"{target_name}_{name}_feature_importance.csv"
)
rows.append({"model": name, **metrics})
if stack["lgb"] is None:
rows.append({
"model": "lightgbm",
"mae_normalized": math.nan,
"mae_wh": math.nan,
"r2": math.nan,
"note": f"lightgbm_missing: {stack.get('lgbm_import_error')}",
})
return rows
def train_sequence_torch(stack, split: SplitData, y_scaler, args, model_kind: str):
np = stack["np"]
torch = stack["torch"]
nn = stack["nn"]
DataLoader = stack["DataLoader"]
TensorDataset = stack["TensorDataset"]
torch.manual_seed(42)
np.random.seed(42)
x_train, x_val, x_test, y_train, y_val, y_test = make_lstm_sequences(np, split, args.lookback)
if len(x_train) < 100 or len(x_val) < 10 or len(x_test) < 10:
return [{"model": model_kind, "mae_wh": math.nan, "r2": math.nan, "note": "not_enough_sequences", "backend": "torch"}]
class DecodeLSTM(nn.Module):
def __init__(self, input_size: int):
super().__init__()
self.lstm = nn.LSTM(input_size=input_size, hidden_size=32, batch_first=True)
self.head = nn.Sequential(
nn.Linear(32, 5),
nn.ReLU(),
nn.Linear(5, 5),
nn.ReLU(),
nn.Linear(5, 1),
)
def forward(self, x):
output, _ = self.lstm(x)
return self.head(output[:, -1, :]).squeeze(-1)
class DecodeCNN1D(nn.Module):
def __init__(self, input_size: int):
super().__init__()
self.net = nn.Sequential(
nn.Conv1d(input_size, 32, kernel_size=3, padding=1),
nn.ReLU(),
nn.Conv1d(32, 32, kernel_size=3, padding=1),
nn.ReLU(),
nn.AdaptiveAvgPool1d(1),
)
self.head = nn.Sequential(
nn.Flatten(),
nn.Linear(32, 16),
nn.ReLU(),
nn.Linear(16, 1),
)
def forward(self, x):
x = x.transpose(1, 2)
return self.head(self.net(x)).squeeze(-1)
class Chomp1d(nn.Module):
def __init__(self, chomp_size: int):
super().__init__()
self.chomp_size = chomp_size
def forward(self, x):
return x[:, :, :-self.chomp_size].contiguous() if self.chomp_size else x
class DecodeTCN(nn.Module):
def __init__(self, input_size: int):
super().__init__()
self.net = nn.Sequential(
nn.Conv1d(input_size, 32, kernel_size=3, padding=2, dilation=1),
Chomp1d(2),
nn.ReLU(),
nn.Conv1d(32, 32, kernel_size=3, padding=4, dilation=2),
Chomp1d(4),
nn.ReLU(),
)
self.head = nn.Sequential(
nn.Linear(32, 16),
nn.ReLU(),
nn.Linear(16, 1),
)
def forward(self, x):
x = x.transpose(1, 2)
output = self.net(x).transpose(1, 2)
return self.head(output[:, -1, :]).squeeze(-1)
class Inception2DBlock(nn.Module):
def __init__(self, channels: int):
super().__init__()
self.branches = nn.ModuleList(
[
nn.Conv2d(channels, channels, kernel_size=1, padding=0),
nn.Conv2d(channels, channels, kernel_size=3, padding=1),
nn.Conv2d(channels, channels, kernel_size=5, padding=2),
]
)
self.activation = nn.GELU()
def forward(self, x):
outputs = [branch(x) for branch in self.branches]
return self.activation(torch.stack(outputs, dim=0).mean(dim=0))
class TimesBlock(nn.Module):
def __init__(self, d_model: int, top_k: int = 3):
super().__init__()
self.top_k = top_k
self.inception = nn.Sequential(
Inception2DBlock(d_model),
Inception2DBlock(d_model),
)
def forward(self, x):
batch_size, seq_len, d_model = x.shape
fft = torch.fft.rfft(x, dim=1)
amplitudes = fft.abs().mean(dim=0).mean(dim=-1)
if len(amplitudes) <= 1:
return x
amplitudes = amplitudes.clone()
amplitudes[0] = 0
k = min(self.top_k, len(amplitudes) - 1)
period_weights, frequency_indices = torch.topk(amplitudes, k=k)
periods = torch.div(seq_len, frequency_indices, rounding_mode="floor").clamp(min=1)
period_outputs = []
for period in periods.tolist():
padded_len = math.ceil(seq_len / period) * period
if padded_len > seq_len:
padding = x.new_zeros(batch_size, padded_len - seq_len, d_model)
period_input = torch.cat([x, padding], dim=1)
else:
period_input = x
rows = padded_len // period
period_input = period_input.reshape(batch_size, rows, period, d_model).permute(0, 3, 1, 2)
period_output = self.inception(period_input)
period_output = period_output.permute(0, 2, 3, 1).reshape(batch_size, padded_len, d_model)
period_outputs.append(period_output[:, :seq_len, :])
weights = torch.softmax(period_weights, dim=0).view(1, 1, 1, -1)
stacked = torch.stack(period_outputs, dim=-1)
return (stacked * weights).sum(dim=-1) + x
class DecodeTimesNet(nn.Module):
def __init__(self, input_size: int):
super().__init__()
d_model = 32
self.embedding = nn.Linear(input_size, d_model)
self.blocks = nn.ModuleList([TimesBlock(d_model=d_model, top_k=3) for _ in range(2)])
self.norm = nn.LayerNorm(d_model)
self.head = nn.Sequential(
nn.Linear(d_model, 16),
nn.GELU(),
nn.Linear(16, 1),
)
def forward(self, x):
x = self.embedding(x)
for block in self.blocks:
x = self.norm(block(x))
return self.head(x[:, -1, :]).squeeze(-1)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model_classes = {
"lstm": DecodeLSTM,
"cnn1d": DecodeCNN1D,
"tcn": DecodeTCN,
"timesnet": DecodeTimesNet,
}
model = model_classes[model_kind](input_size=x_train.shape[2]).to(device)
criterion = nn.L1Loss()
optimizer = torch.optim.RMSprop(model.parameters(), lr=1e-3)
train_ds = TensorDataset(
torch.tensor(x_train, dtype=torch.float32),
torch.tensor(y_train, dtype=torch.float32),
)
val_x = torch.tensor(x_val, dtype=torch.float32).to(device)
val_y = torch.tensor(y_val, dtype=torch.float32).to(device)
train_loader = DataLoader(train_ds, batch_size=args.batch_size, shuffle=True)
best_state = None
best_val_loss = math.inf
patience = 4
patience_left = patience
epochs_run = 0
for epoch in range(args.epochs):
model.train()
train_loss = 0.0
seen = 0
for batch_x, batch_y in train_loader:
batch_x = batch_x.to(device)
batch_y = batch_y.to(device)
optimizer.zero_grad()
pred = model(batch_x)
loss = criterion(pred, batch_y)
loss.backward()
optimizer.step()
train_loss += loss.item() * len(batch_y)
seen += len(batch_y)
model.eval()
with torch.no_grad():
val_pred = model(val_x)
val_loss = criterion(val_pred, val_y).item()
epochs_run = epoch + 1
print(f"Epoch {epochs_run}/{args.epochs} - loss: {train_loss / max(seen, 1):.6f} - val_loss: {val_loss:.6f}")
if val_loss < best_val_loss:
best_val_loss = val_loss
best_state = {key: value.detach().cpu().clone() for key, value in model.state_dict().items()}
patience_left = patience
else:
patience_left -= 1
if patience_left <= 0:
break
if best_state is not None:
model.load_state_dict(best_state)
model.eval()
test_loader = DataLoader(
TensorDataset(torch.tensor(x_test, dtype=torch.float32), torch.tensor(y_test, dtype=torch.float32)),
batch_size=args.batch_size,
shuffle=False,
)
preds = []
with torch.no_grad():
for batch_x, _ in test_loader:
preds.append(model(batch_x.to(device)).detach().cpu().numpy())
pred = np.concatenate(preds)
metrics = inverse_metric(
np,
y_scaler,
y_test,
pred,
stack["mean_absolute_error"],
stack["r2_score"],
)
metrics["epochs_run"] = epochs_run
metrics["backend"] = "torch"
metrics["device"] = str(device)
model_dir = Path(args.output_dir) / "models" / getattr(args, "current_target", "unknown")
model_dir.mkdir(parents=True, exist_ok=True)
model_path = model_dir / f"{model_kind}.pt"
torch.save({"state_dict": model.state_dict(), "model_kind": model_kind,
"input_size": split.x_all.shape[1], "lookback": args.lookback,
"feature_names": split.feature_names}, model_path)
joblib.dump({"y_scaler": y_scaler, "feature_names": split.feature_names},
model_dir / f"{model_kind}_scaler.joblib")
full_x = np.asarray([split.x_all[i - args.lookback + 1:i + 1]
for i in range(args.lookback - 1, len(split.x_all))])
full_pred_parts = []
with torch.no_grad():
for begin in range(0, len(full_x), args.batch_size):
batch = torch.tensor(full_x[begin:begin + args.batch_size], dtype=torch.float32).to(device)
full_pred_parts.append(model(batch).detach().cpu().numpy())
full_pred = np.concatenate(full_pred_parts)
pred_path = save_predictions(stack["pd"], np, Path(args.output_dir), getattr(args, "current_target", "unknown"),
model_kind, split, y_scaler, full_pred, args.lookback - 1)
metrics["model_path"] = str(model_path)
metrics["prediction_path"] = str(pred_path)
return [{"model": model_kind, **metrics}]
def train_lstm_torch(stack, split: SplitData, y_scaler, args):
return train_sequence_torch(stack, split, y_scaler, args, "lstm")
def train_cnn1d_torch(stack, split: SplitData, y_scaler, args):
return train_sequence_torch(stack, split, y_scaler, args, "cnn1d")
def train_tcn_torch(stack, split: SplitData, y_scaler, args):
return train_sequence_torch(stack, split, y_scaler, args, "tcn")
def train_timesnet_torch(stack, split: SplitData, y_scaler, args):
return train_sequence_torch(stack, split, y_scaler, args, "timesnet")
def train_lstm_keras(stack, split: SplitData, y_scaler, args):
np = stack["np"]
keras = stack["keras"]
tf = stack["tf"]
tf.random.set_seed(42)
np.random.seed(42)
x_train, x_val, x_test, y_train, y_val, y_test = make_lstm_sequences(np, split, args.lookback)
if len(x_train) < 100 or len(x_val) < 10 or len(x_test) < 10:
return [{"model": "lstm", "mae_wh": math.nan, "r2": math.nan, "note": "not_enough_sequences", "backend": "tensorflow"}]
model = keras.Sequential(
[
keras.layers.Input(shape=(x_train.shape[1], x_train.shape[2])),
keras.layers.LSTM(32),
keras.layers.Dense(5, activation="relu"),
keras.layers.Dense(5, activation="relu"),
keras.layers.Dense(1),
]
)
model.compile(optimizer=keras.optimizers.RMSprop(), loss="mae")
early_stop = keras.callbacks.EarlyStopping(monitor="val_loss", patience=4, restore_best_weights=True)
history = model.fit(
x_train,
y_train,
validation_data=(x_val, y_val),
epochs=args.epochs,
batch_size=args.batch_size,
verbose=1,
callbacks=[early_stop],
)
pred = model.predict(x_test, verbose=0).ravel()
metrics = inverse_metric(
np,
y_scaler,
y_test,
pred,
stack["mean_absolute_error"],
stack["r2_score"],
)
metrics["epochs_run"] = len(history.history["loss"])
metrics["backend"] = "tensorflow"
model_dir = Path(args.output_dir) / "models" / getattr(args, "current_target", "unknown")
model_dir.mkdir(parents=True, exist_ok=True)
model_path = model_dir / "lstm.keras"
model.save(model_path)
full_x = np.asarray([split.x_all[i - args.lookback + 1:i + 1]
for i in range(args.lookback - 1, len(split.x_all))])
full_pred = model.predict(full_x, batch_size=args.batch_size, verbose=0).ravel()
metrics["model_path"] = str(model_path)
metrics["prediction_path"] = str(save_predictions(
stack["pd"], np, Path(args.output_dir), getattr(args, "current_target", "unknown"),
"lstm", split, y_scaler, full_pred, args.lookback - 1))
return [{"model": "lstm", **metrics}]
def train_lstm(stack, split: SplitData, y_scaler, args):
if args.skip_lstm:
return [{"model": "lstm", "mae_wh": math.nan, "r2": math.nan, "note": "skipped_by_flag"}]
if stack["torch"] is not None:
return train_lstm_torch(stack, split, y_scaler, args)
if stack["keras"] is not None:
return train_lstm_keras(stack, split, y_scaler, args)
note = (
"lstm_backend_missing: "
f"torch={stack.get('torch_import_error')}; "
f"tensorflow={stack.get('tf_import_error')}"
)
return [{"model": "lstm", "mae_wh": math.nan, "r2": math.nan, "note": note}]
def train_deep_models(stack, split: SplitData, y_scaler, args):
requested = {item.strip().lower() for item in args.dl_models.split(",") if item.strip()}
if "none" in requested or args.skip_lstm:
return [{"model": "deep_models", "mae_wh": math.nan, "r2": math.nan, "note": "skipped_by_flag"}]
rows = []
if "lstm" in requested:
rows.extend(train_lstm(stack, split, y_scaler, args))
torch_missing_note = f"torch_missing: {stack.get('torch_import_error')}"
if "cnn" in requested:
requested.add("cnn1d")
if "cnn1d" in requested:
if stack["torch"] is not None:
rows.extend(train_cnn1d_torch(stack, split, y_scaler, args))
else:
rows.append({"model": "cnn1d", "mae_wh": math.nan, "r2": math.nan, "note": torch_missing_note})
if "tcn" in requested:
if stack["torch"] is not None:
rows.extend(train_tcn_torch(stack, split, y_scaler, args))
else:
rows.append({"model": "tcn", "mae_wh": math.nan, "r2": math.nan, "note": torch_missing_note})
if "times" in requested:
requested.add("timesnet")
if "timesnet" in requested:
if stack["torch"] is not None:
rows.extend(train_timesnet_torch(stack, split, y_scaler, args))
else:
rows.append({"model": "timesnet", "mae_wh": math.nan, "r2": math.nan, "note": torch_missing_note})
return rows
def train_arima(stack, clean, args):
if not args.include_arima:
return [{"model": "arima", "mae_wh": math.nan, "r2": math.nan, "note": "skipped_enable_with_include_arima"}]
if stack["ARIMA"] is None:
return [{
"model": "arima",
"mae_wh": math.nan,
"r2": math.nan,
"note": f"statsmodels_missing: {stack.get('statsmodels_import_error')}",
}]
n = len(clean)
train_end = int(n * 0.70)
val_end = int(n * 0.85)
history = clean["energy_wh"].iloc[:val_end].dropna()
if args.arima_max_train and len(history) > args.arima_max_train:
history = history.iloc[-args.arima_max_train:]
y_true = clean["target"].iloc[val_end:].dropna()
test_span_steps = test_span_steps_from_args(stack["pd"], args)
if test_span_steps is not None:
y_true = y_true.iloc[:test_span_steps]
if len(history) < 50 or len(y_true) < 10:
return [{"model": "arima", "mae_wh": math.nan, "r2": math.nan, "note": "not_enough_points"}]
try:
model = stack["ARIMA"](history, order=(2, 1, 2))
fitted = model.fit()
forecast = fitted.forecast(steps=len(y_true))
metrics = {
"mae_wh": float(stack["mean_absolute_error"](y_true, forecast)),
"r2": float(stack["r2_score"](y_true, forecast)),
"note": f"order=(2,1,2); train_points={len(history)}",
}
return [{"model": "arima", **metrics}]
except Exception as exc:
return [{"model": "arima", "mae_wh": math.nan, "r2": math.nan, "note": f"arima_failed: {type(exc).__name__}: {exc}"}]
def save_dataset(pd, clean, out_dir: Path, target_name: str):
out_path = out_dir / "processed" / f"{target_name}_train_ready.csv"
out_path.parent.mkdir(parents=True, exist_ok=True)
clean.to_csv(out_path)
return out_path
def run_target(stack, args, target_name: str, df, out_dir: Path, global_scalers):
pd = stack["pd"]
np = stack["np"]
horizon_steps = horizon_steps_from_args(pd, args)
test_span_steps = test_span_steps_from_args(pd, args)
print(f"\n=== Target: {target_name} ===")
args.current_target = target_name
print(f"Horizon: {horizon_steps} step(s) = {describe_steps(pd, horizon_steps, args.freq)}")
print(f"Lookback: {args.lookback} step(s) = {describe_steps(pd, args.lookback, args.freq)}")
if test_span_steps is not None:
print(f"Test span: {test_span_steps} step(s) = {describe_steps(pd, test_span_steps, args.freq)}")
split, y_scaler, clean = make_ml_split(
np,
pd,
stack["MinMaxScaler"],
df,
horizon=horizon_steps,
max_rows=args.max_rows,
test_span_steps=test_span_steps,
global_scalers=global_scalers,
)
x_scaler = global_scalers[0]
dataset_path = save_dataset(pd, clean, out_dir, target_name)
print(f"Rows after feature engineering: {len(clean):,}")
print(f"Train/val/test: {len(split.y_train):,}/{len(split.y_val):,}/{len(split.y_test):,}")
print(f"Saved train-ready table: {dataset_path}")
rows = []
rows.extend(train_baselines(stack, split, x_scaler, y_scaler, args, out_dir, target_name))
rows.extend(train_deep_models(stack, split, y_scaler, args))
rows.extend(train_arima(stack, clean, args))
for row in rows:
row["target"] = target_name
row["rows"] = len(clean)
row["features"] = len(split.feature_names)
row["horizon_steps"] = horizon_steps
row["horizon"] = describe_steps(pd, horizon_steps, args.freq)
row["lookback_steps"] = args.lookback
row["lookback"] = describe_steps(pd, args.lookback, args.freq)
row["test_span_steps"] = test_span_steps if test_span_steps is not None else len(split.y_test)
row["test_span"] = describe_steps(pd, row["test_span_steps"], args.freq)
return rows
def main() -> int:
args = parse_args()
stack = import_stack()
pd = stack["pd"]
out_dir = Path(args.output_dir)
out_dir.mkdir(parents=True, exist_ok=True)
(out_dir / "processed").mkdir(exist_ok=True)
full_config = PAPER_BUILDINGS if args.mode == "paper_buildings" else METER_TARGETS
config = full_config
if args.target != "all":
if args.target not in config:
raise SystemExit(f"Unknown target {args.target!r}. Available: {', '.join(config)}")
config = {args.target: config[args.target]}
print("DECODE re-implementation")
print(f"Mode: {args.mode}")
print(f"Frequency: {args.freq}")
print(f"Python executable: {sys.executable}")
print(f"PyTorch available: {stack['torch'] is not None}")
if stack["torch"] is None:
print(f"PyTorch import error: {stack.get('torch_import_error')}")
print(f"TensorFlow available: {stack['keras'] is not None}")
if stack["keras"] is None:
print(f"TensorFlow import error: {stack.get('tf_import_error')}")
print(f"LightGBM available: {stack['lgb'] is not None}")
if stack["lgb"] is None:
print(f"LightGBM import error: {stack.get('lgbm_import_error')}")
print(f"Statsmodels ARIMA available: {stack['ARIMA'] is not None}")
if stack["ARIMA"] is None:
print(f"Statsmodels import error: {stack.get('statsmodels_import_error')}")
if not args.skip_lstm:
if stack["torch"] is not None:
print("LSTM backend: PyTorch")
elif stack["keras"] is not None:
print("LSTM backend: TensorFlow/Keras")
else:
print("LSTM backend: unavailable")
energy_10min = read_energy_10min(pd, args.freq)
calendar = read_calendar(pd)
# Build every target first so one leakage-safe scaler can be fitted on the
# concatenated 70% training partitions of all buildings/meters.
all_frames = {
name: build_target_frame(pd, energy_10min, calendar, name, spec, args.freq, args.include_weather)
for name, spec in full_config.items()
}
global_scalers = fit_global_scalers(
stack, all_frames, horizon_steps_from_args(pd, args), args.max_rows)
scaler_path = out_dir / f"global_scalers_{args.mode}.joblib"
joblib.dump({"x_scaler": global_scalers[0], "y_scaler": global_scalers[1],
"scope": list(full_config)}, scaler_path)
print(f"Global MinMax scaler fitted on training partitions: {scaler_path}")
all_rows = []
for target_name in config:
rows = run_target(stack, args, target_name, all_frames[target_name], out_dir, global_scalers)
all_rows.extend(rows)
results = pd.DataFrame(all_rows)
effective_horizon = horizon_steps_from_args(pd, args)
effective_test_span = test_span_steps_from_args(pd, args)
result_suffix = f"h{effective_horizon}"
if effective_test_span is not None:
result_suffix += f"_ts{effective_test_span}"
result_path = out_dir / f"results_{args.mode}_{result_suffix}.csv"
results.to_csv(result_path, index=False)
metadata = {
"mode": args.mode,
"target": args.target,
"freq": args.freq,
"lookback": args.lookback,
"horizon": args.horizon,
"horizon_days": args.horizon_days,
"horizon_steps_effective": horizon_steps_from_args(pd, args),
"test_span_days": args.test_span_days,
"test_span_steps_effective": test_span_steps_from_args(pd, args),
"epochs": args.epochs,
"batch_size": args.batch_size,
"rf_trees": args.rf_trees,
"dl_models": args.dl_models,
"include_arima": args.include_arima,
"include_weather": args.include_weather,
"scaling": "global_train_partitions_all_targets",
"global_scaler_path": str(scaler_path),
"pytorch_available": stack["torch"] is not None,
"torch_import_error": stack.get("torch_import_error"),
"lightgbm_available": stack["lgb"] is not None,
"lightgbm_import_error": stack.get("lgbm_import_error"),
"statsmodels_available": stack["ARIMA"] is not None,
"statsmodels_import_error": stack.get("statsmodels_import_error"),
"tensorflow_available": stack["keras"] is not None,
"tensorflow_import_error": stack.get("tf_import_error"),
"energy_file": str(ENERGY_FILE),
"occupancy_dir": str(OCCUPANCY_DIR),
"calendar_dir": str(CALENDAR_DIR),
"weather_file": str(WEATHER_FILE),
}
(out_dir / f"run_config_{args.mode}.json").write_text(json.dumps(metadata, indent=2), encoding="utf-8")
print("\n=== Results ===")
print(results.sort_values(["target", "mae_normalized"]).to_string(index=False))
print(f"\nSaved results: {result_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
|