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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
from scipy.ndimage import gaussian_filter1d
|
| 4 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
from torch.utils.data import Dataset, DataLoader
|
| 8 |
+
import random
|
| 9 |
+
import matplotlib.pyplot as plt
|
| 10 |
+
from torch.utils.data import DataLoader, TensorDataset
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
import matplotlib.dates as mdates
|
| 13 |
+
|
| 14 |
+
# --- Utility Functions ---
|
| 15 |
+
def set_seed(seed):
|
| 16 |
+
random.seed(seed)
|
| 17 |
+
np.random.seed(seed)
|
| 18 |
+
torch.manual_seed(seed)
|
| 19 |
+
if torch.cuda.is_available():
|
| 20 |
+
torch.cuda.manual_seed(seed)
|
| 21 |
+
torch.cuda.manual_seed_all(seed)
|
| 22 |
+
torch.backends.cudnn.deterministic = True
|
| 23 |
+
torch.backends.cudnn.benchmark = False
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# --- Data Loading and Initial Processing (from original) ---
|
| 27 |
+
def get_data_building_weather_weekly():
|
| 28 |
+
# path = "C:\\Software\\Probabilistic_Forecasting\\Data\\ashrae-energy-prediction"
|
| 29 |
+
# df_train = pd.read_csv(path + "\\train.csv")
|
| 30 |
+
# df_weather = pd.read_csv(path + "\\weather_train.csv")
|
| 31 |
+
# df_meta = pd.read_csv(path + "\\building_metadata.csv")
|
| 32 |
+
|
| 33 |
+
df_train = pd.read_csv("/Users/muhaoguo/Documents/study/Paper_Projects/PESGM/data/ashrae-energy-prediction/train.csv")
|
| 34 |
+
df_weather = pd.read_csv("/Users/muhaoguo/Documents/study/Paper_Projects/PESGM/data/ashrae-energy-prediction/weather_train.csv")
|
| 35 |
+
df_meta = pd.read_csv("/Users/muhaoguo/Documents/study/Paper_Projects/PESGM/data/ashrae-energy-prediction/building_metadata.csv")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
df = df_train.merge(df_meta, on='building_id').merge(df_weather, on=['site_id', 'timestamp'])
|
| 39 |
+
df['timestamp'] = pd.to_datetime(df['timestamp'])
|
| 40 |
+
# Filter for a specific building, meter, and a reduced date range for faster processing if needed
|
| 41 |
+
df = df[(df['building_id'] == 2) & (df['meter'] == 0)]
|
| 42 |
+
df = df[(df['timestamp'] >= '2016-01-04') & (df['timestamp'] < '2017-01-04')] # Ensure enough data for ~50 weeks
|
| 43 |
+
df['Date'] = df['timestamp'].dt.date
|
| 44 |
+
df['day_of_week'] = df['timestamp'].dt.dayofweek # Monday=0, Sunday=6
|
| 45 |
+
|
| 46 |
+
def get_season(month):
|
| 47 |
+
return {12: 0, 1: 0, 2: 0, 3: 1, 4: 1, 5: 1, 6: 2, 7: 2, 8: 2, 9: 3, 10: 3, 11: 3}[month]
|
| 48 |
+
|
| 49 |
+
# Ensure 'meter_reading' and 'air_temperature' are present and numeric
|
| 50 |
+
df['meter_reading'] = pd.to_numeric(df['meter_reading'], errors='coerce').fillna(0)
|
| 51 |
+
df['air_temperature'] = pd.to_numeric(df['air_temperature'], errors='coerce').fillna(method='ffill').fillna(
|
| 52 |
+
method='bfill').fillna(15)
|
| 53 |
+
|
| 54 |
+
measurement_columns = ['meter_reading', 'air_temperature', 'Date', 'timestamp']
|
| 55 |
+
# Ensure columns exist, add placeholders if not
|
| 56 |
+
for col in measurement_columns:
|
| 57 |
+
if col not in df.columns and col not in ['Date']: # Date is derived
|
| 58 |
+
df[col] = 0 if col != 'timestamp' else pd.NaT
|
| 59 |
+
|
| 60 |
+
grouped = df.groupby('Date')[measurement_columns + ['day_of_week']]
|
| 61 |
+
|
| 62 |
+
array_3d, labels_3d, seasons_3d = [], [], []
|
| 63 |
+
dates = sorted(grouped.groups.keys())
|
| 64 |
+
if not dates:
|
| 65 |
+
print("Warning: No data after filtering in get_data_building_weather_weekly.")
|
| 66 |
+
# Return empty arrays with expected dimensions to avoid downstream errors immediately
|
| 67 |
+
return np.array([]), np.array([]), np.array([]), np.array([]), np.array([])
|
| 68 |
+
|
| 69 |
+
for date_val in dates:
|
| 70 |
+
group_df = grouped.get_group(date_val)
|
| 71 |
+
if group_df.empty or len(group_df) != 24: # Assuming hourly data, fill if not
|
| 72 |
+
# Create a full day template
|
| 73 |
+
full_day_timestamps = pd.to_datetime([f"{date_val} {h:02d}:00:00" for h in range(24)])
|
| 74 |
+
template_df = pd.DataFrame({'timestamp': full_day_timestamps})
|
| 75 |
+
group_df = pd.merge(template_df, group_df, on='timestamp', how='left')
|
| 76 |
+
group_df['Date'] = group_df['timestamp'].dt.date
|
| 77 |
+
group_df['day_of_week'] = group_df['timestamp'].dt.dayofweek
|
| 78 |
+
for col in ['meter_reading', 'air_temperature']:
|
| 79 |
+
group_df[col] = group_df[col].interpolate(method='linear').fillna(method='ffill').fillna(method='bfill')
|
| 80 |
+
group_df = group_df.fillna({'meter_reading': 0, 'air_temperature': 15}) # final fallback
|
| 81 |
+
|
| 82 |
+
arr = group_df[measurement_columns].values
|
| 83 |
+
label = 0 if group_df['day_of_week'].iloc[0] < 5 else 1 # Weekday/Weekend
|
| 84 |
+
season = get_season(group_df['timestamp'].iloc[0].month)
|
| 85 |
+
array_3d.append(arr)
|
| 86 |
+
labels_3d.append(np.full(len(arr), label))
|
| 87 |
+
seasons_3d.append(np.full(len(arr), season))
|
| 88 |
+
|
| 89 |
+
n_full_weeks = len(array_3d) // 7
|
| 90 |
+
if n_full_weeks == 0:
|
| 91 |
+
print("Warning: Not enough daily data to form even one full week.")
|
| 92 |
+
return np.array([]), np.array([]), np.array([]), np.array([]), np.array([])
|
| 93 |
+
|
| 94 |
+
energy, temp, times, workday, season_feat = [], [], [], [], []
|
| 95 |
+
for w in range(n_full_weeks):
|
| 96 |
+
wk = slice(w * 7, (w + 1) * 7)
|
| 97 |
+
week_data = array_3d[wk]
|
| 98 |
+
week_labels = labels_3d[wk]
|
| 99 |
+
week_seasons = seasons_3d[wk]
|
| 100 |
+
|
| 101 |
+
e = np.concatenate([np.asarray(d[:, 0], dtype=float) for d in week_data])
|
| 102 |
+
t = np.concatenate([np.asarray(d[:, 1], dtype=float) for d in week_data])
|
| 103 |
+
ts = np.concatenate([np.asarray(d[:, 3]) for d in week_data]) # timestamp objects
|
| 104 |
+
wl = np.concatenate([np.asarray(lbl, dtype=int) for lbl in week_labels])
|
| 105 |
+
sl = np.concatenate([np.asarray(seas, dtype=int) for seas in week_seasons])
|
| 106 |
+
|
| 107 |
+
if e.shape[0] != 168: # Skip incomplete weeks silently or handle
|
| 108 |
+
# print(f"Skipping week {w} due to incomplete data: {e.shape[0]} points")
|
| 109 |
+
continue
|
| 110 |
+
|
| 111 |
+
e = gaussian_filter1d(e, sigma=1)
|
| 112 |
+
t = gaussian_filter1d(t, sigma=1)
|
| 113 |
+
|
| 114 |
+
energy.append(e)
|
| 115 |
+
temp.append(t)
|
| 116 |
+
times.append(ts)
|
| 117 |
+
workday.append(wl)
|
| 118 |
+
season_feat.append(sl)
|
| 119 |
+
|
| 120 |
+
return np.array(times, dtype=object), np.array(energy), np.array(temp), np.array(workday), np.array(season_feat)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def gaussian_nll_loss(mu, logvar, target):
|
| 124 |
+
# mu, logvar, target → same shape [B, L+1, output_len, output_dim]
|
| 125 |
+
nll = 0.5 * (logvar + np.log(2 * np.pi) + ((target - mu) ** 2) / logvar.exp())
|
| 126 |
+
return nll.mean() # average over all elements
|
| 127 |
+
|
| 128 |
+
def kl_loss(mu_z, logvar_z):
|
| 129 |
+
return -0.5 * torch.mean(1 + logvar_z - mu_z.pow(2) - logvar_z.exp())
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def process_seq2seq_data(
|
| 134 |
+
feature_dict,
|
| 135 |
+
*,
|
| 136 |
+
train_ratio = 0.7,
|
| 137 |
+
norm_features = ('load', 'temp'),
|
| 138 |
+
output_len = 24, # how many steps each decoder step predicts
|
| 139 |
+
encoder_len_weeks = 1,
|
| 140 |
+
decoder_len_weeks = 1,
|
| 141 |
+
num_in_week = 168, # ← NEW: default parameter
|
| 142 |
+
device = None):
|
| 143 |
+
|
| 144 |
+
# ----------------------------------------------------------
|
| 145 |
+
# 1. flatten, scale, keep 1‑D per feature
|
| 146 |
+
# ----------------------------------------------------------
|
| 147 |
+
processed, scalers = {}, {}
|
| 148 |
+
for k, arr in feature_dict.items():
|
| 149 |
+
if arr.size == 0:
|
| 150 |
+
raise ValueError(f"feature '{k}' is empty.")
|
| 151 |
+
vec = arr.astype(float).flatten() # weeks → long vector
|
| 152 |
+
if k in norm_features:
|
| 153 |
+
sc = MinMaxScaler()
|
| 154 |
+
processed[k] = sc.fit_transform(vec.reshape(-1, 1)).flatten()
|
| 155 |
+
scalers[k] = sc
|
| 156 |
+
else:
|
| 157 |
+
processed[k] = vec
|
| 158 |
+
scalers[k] = None
|
| 159 |
+
|
| 160 |
+
n_weeks = feature_dict['load'].shape[0]
|
| 161 |
+
need_weeks = encoder_len_weeks + decoder_len_weeks
|
| 162 |
+
if n_weeks < need_weeks:
|
| 163 |
+
raise ValueError(f"Need ≥{need_weeks} consecutive weeks, found {n_weeks}.")
|
| 164 |
+
|
| 165 |
+
enc_seq_len = encoder_len_weeks * num_in_week
|
| 166 |
+
dec_seq_len = decoder_len_weeks * num_in_week
|
| 167 |
+
L = dec_seq_len - output_len
|
| 168 |
+
if L <= 0:
|
| 169 |
+
raise ValueError("`output_len` must be smaller than decoder sequence length.")
|
| 170 |
+
|
| 171 |
+
# ----------------------------------------------------------
|
| 172 |
+
# 2. build samples (stride = 1 week)
|
| 173 |
+
# ----------------------------------------------------------
|
| 174 |
+
X_enc_l, X_enc_t, X_enc_w, X_enc_s = [], [], [], []
|
| 175 |
+
X_dec_in_l, X_dec_in_t, X_dec_in_w, X_dec_in_s = [], [], [], []
|
| 176 |
+
Y_dec_target_l = []
|
| 177 |
+
|
| 178 |
+
last_start = n_weeks - need_weeks # inclusive
|
| 179 |
+
for w in range(last_start + 1):
|
| 180 |
+
enc_start = w * num_in_week
|
| 181 |
+
enc_end = (w + encoder_len_weeks) * num_in_week
|
| 182 |
+
dec_start = enc_end
|
| 183 |
+
dec_end = dec_start + dec_seq_len # exclusive
|
| 184 |
+
|
| 185 |
+
# -- encoder --
|
| 186 |
+
X_enc_l.append(processed['load' ][enc_start:enc_end])
|
| 187 |
+
X_enc_t.append(processed['temp' ][enc_start:enc_end])
|
| 188 |
+
X_enc_w.append(processed['workday'][enc_start:enc_end])
|
| 189 |
+
X_enc_s.append(processed['season' ][enc_start:enc_end])
|
| 190 |
+
|
| 191 |
+
# -- decoder input (teacher forcing) --
|
| 192 |
+
X_dec_in_l.append(processed['load' ][dec_start : dec_start + L])
|
| 193 |
+
X_dec_in_t.append(processed['temp' ][dec_start : dec_start + L])
|
| 194 |
+
X_dec_in_w.append(processed['workday'][dec_start : dec_start + L])
|
| 195 |
+
X_dec_in_s.append(processed['season' ][dec_start : dec_start + L])
|
| 196 |
+
|
| 197 |
+
# -- decoder targets (sliding output_len window) --
|
| 198 |
+
load_dec_full = processed['load'][dec_start: dec_end]
|
| 199 |
+
targets = np.stack([
|
| 200 |
+
load_dec_full[i: i + output_len] for i in range(L+1)],
|
| 201 |
+
axis=0)
|
| 202 |
+
Y_dec_target_l.append(targets)
|
| 203 |
+
|
| 204 |
+
# ----------------------------------------------------------
|
| 205 |
+
# 3. pack → tensors
|
| 206 |
+
# ----------------------------------------------------------
|
| 207 |
+
to_tensor = lambda lst: torch.tensor(lst, dtype=torch.float32).unsqueeze(-1).to(device)
|
| 208 |
+
|
| 209 |
+
data_tensors = {
|
| 210 |
+
'X_enc_l' : to_tensor(X_enc_l), # [B, enc_seq_len, 1]
|
| 211 |
+
'X_enc_t' : to_tensor(X_enc_t),
|
| 212 |
+
'X_enc_w' : to_tensor(X_enc_w),
|
| 213 |
+
'X_enc_s' : to_tensor(X_enc_s),
|
| 214 |
+
|
| 215 |
+
'X_dec_in_l' : to_tensor(X_dec_in_l), # [B, L, 1]
|
| 216 |
+
'X_dec_in_t' : to_tensor(X_dec_in_t),
|
| 217 |
+
'X_dec_in_w' : to_tensor(X_dec_in_w),
|
| 218 |
+
'X_dec_in_s' : to_tensor(X_dec_in_s),
|
| 219 |
+
|
| 220 |
+
'Y_dec_target_l': torch.tensor(
|
| 221 |
+
Y_dec_target_l, dtype=torch.float32).unsqueeze(-1).to(device) # [B, L, output_len, 1]
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
# quick check
|
| 225 |
+
for k, v in data_tensors.items():
|
| 226 |
+
print(f"{k:15s} {tuple(v.shape)}")
|
| 227 |
+
|
| 228 |
+
# ----------------------------------------------------------
|
| 229 |
+
# 4. train / test split
|
| 230 |
+
# ----------------------------------------------------------
|
| 231 |
+
B = data_tensors['X_enc_l'].shape[0]
|
| 232 |
+
split = int(train_ratio * B)
|
| 233 |
+
train_dict = {k: v[:split] for k, v in data_tensors.items()}
|
| 234 |
+
test_dict = {k: v[split:] for k, v in data_tensors.items()}
|
| 235 |
+
|
| 236 |
+
return train_dict, test_dict, scalers
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def visualise_one_sample(data_dict, sample_idx=0):
|
| 241 |
+
"""Draw a single figure with three subplots:
|
| 242 |
+
1) encoder load, 2) decoder load, 3) heat‑map of Y_dec_target_l."""
|
| 243 |
+
enc = data_dict['X_enc_t'][sample_idx].cpu().numpy().squeeze(-1)
|
| 244 |
+
dec = data_dict['X_dec_in_t'][sample_idx].cpu().numpy().squeeze(-1)
|
| 245 |
+
tgt = data_dict['Y_dec_target_l'][sample_idx].cpu().numpy().squeeze(-1) # [L, output_len]
|
| 246 |
+
|
| 247 |
+
fig, axes = plt.subplots(3, 1, figsize=(14, 10), constrained_layout=True)
|
| 248 |
+
|
| 249 |
+
axes[0].plot(enc)
|
| 250 |
+
axes[0].set_title("Encoder input")
|
| 251 |
+
axes[0].set_xlabel("Time step"); axes[0].set_ylabel("scaled")
|
| 252 |
+
|
| 253 |
+
axes[1].plot(dec)
|
| 254 |
+
axes[1].set_title("Decoder input")
|
| 255 |
+
axes[1].set_xlabel("Time step")
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
axes[2].plot(tgt[0])
|
| 259 |
+
axes[2].plot(tgt[1])
|
| 260 |
+
axes[2].plot(tgt[2])
|
| 261 |
+
axes[2].set_title("Decoder target")
|
| 262 |
+
axes[2].set_xlabel("Time step")
|
| 263 |
+
|
| 264 |
+
plt.show()
|
| 265 |
+
|
| 266 |
+
def make_loader(data_dict, batch_size, shuffle=True):
|
| 267 |
+
"""
|
| 268 |
+
Returns: batch =
|
| 269 |
+
(enc_l, enc_t, enc_w, enc_s,
|
| 270 |
+
dec_l, dec_t, dec_w, dec_s,
|
| 271 |
+
tgt)
|
| 272 |
+
Shapes:
|
| 273 |
+
enc_* : [B, enc_seq, 1]
|
| 274 |
+
dec_* : [B, L, 1]
|
| 275 |
+
tgt : [B, L+1, output_len, 1]
|
| 276 |
+
"""
|
| 277 |
+
tensors = (
|
| 278 |
+
data_dict['X_enc_l'], data_dict['X_enc_t'],
|
| 279 |
+
data_dict['X_enc_w'], data_dict['X_enc_s'],
|
| 280 |
+
data_dict['X_dec_in_l'], data_dict['X_dec_in_t'],
|
| 281 |
+
data_dict['X_dec_in_w'], data_dict['X_dec_in_s'],
|
| 282 |
+
data_dict['Y_dec_target_l']
|
| 283 |
+
)
|
| 284 |
+
ds = TensorDataset(*tensors)
|
| 285 |
+
return DataLoader(ds, batch_size=batch_size, shuffle=shuffle)
|
| 286 |
+
|
| 287 |
+
def reconstruct_sequence(pred_seq):
|
| 288 |
+
"""
|
| 289 |
+
Averages overlapping predictions from [L+1, output_len] into [L+output_len]
|
| 290 |
+
Args:
|
| 291 |
+
pred_seq: [L+1, output_len] – single sample prediction
|
| 292 |
+
Returns:
|
| 293 |
+
avg_pred: [L+output_len] – averaged sequence
|
| 294 |
+
"""
|
| 295 |
+
L_plus_1, output_len = pred_seq.shape
|
| 296 |
+
total_len = L_plus_1 + output_len - 1
|
| 297 |
+
sum_seq = torch.zeros(total_len, device=pred_seq.device)
|
| 298 |
+
count_seq = torch.zeros(total_len, device=pred_seq.device)
|
| 299 |
+
|
| 300 |
+
for t in range(L_plus_1):
|
| 301 |
+
sum_seq[t:t+output_len] += pred_seq[t]
|
| 302 |
+
count_seq[t:t+output_len] += 1
|
| 303 |
+
|
| 304 |
+
return sum_seq / count_seq # [L+output_len]
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def get_load_temperature_spanish():
|
| 309 |
+
'''
|
| 310 |
+
https://www.kaggle.com/datasets/nicholasjhana/energy-consumption-generation-prices-and-weather
|
| 311 |
+
'''
|
| 312 |
+
# Load the energy dataset and weather features
|
| 313 |
+
energy_df = pd.read_csv('/Users/muhaoguo/Documents/study/Paper_Projects/PESGM/data/kaggle/energy_dataset.csv')
|
| 314 |
+
weather_df = pd.read_csv('/Users/muhaoguo/Documents/study/Paper_Projects/PESGM/data/kaggle/weather_features.csv')
|
| 315 |
+
|
| 316 |
+
# Convert timestamp columns to datetime format for easier merging and plotting
|
| 317 |
+
energy_df['time'] = pd.to_datetime(energy_df['time'])
|
| 318 |
+
weather_df['time'] = pd.to_datetime(weather_df['dt_iso'])
|
| 319 |
+
|
| 320 |
+
# Merge datasets on the 'timestamp' column
|
| 321 |
+
merged_df = pd.merge(energy_df, weather_df, on='time', how='inner')
|
| 322 |
+
merged_df = merged_df[['time', 'temp', 'total load actual']].dropna()
|
| 323 |
+
merged_df = merged_df[::5]
|
| 324 |
+
|
| 325 |
+
time = merged_df["time"].values
|
| 326 |
+
print(time)
|
| 327 |
+
exit()
|
| 328 |
+
temperature = (merged_df["temp"] - 273.15).values # from Kelvin (K) to degrees Celsius (°C),
|
| 329 |
+
load = merged_df["total load actual"].values/1000 # from MW to (×10³ MW)
|
| 330 |
+
|
| 331 |
+
temperature = gaussian_filter1d(temperature, sigma=2)
|
| 332 |
+
load = gaussian_filter1d(load, sigma=2)
|
| 333 |
+
|
| 334 |
+
# Plotting temperature and load on the same figure
|
| 335 |
+
fig, ax1 = plt.subplots(figsize=(14, 6))
|
| 336 |
+
# Plot temperature with left y-axis
|
| 337 |
+
ax1.plot(time, temperature, label='Temperature', color='orange', linewidth=2)
|
| 338 |
+
ax1.set_ylabel('Temperature (°C)', color='orange', fontsize=20)
|
| 339 |
+
ax1.tick_params(axis='y', labelcolor='orange', labelsize=20)
|
| 340 |
+
ax1.tick_params(axis='x', labelsize=20)
|
| 341 |
+
# Create a second y-axis for load
|
| 342 |
+
ax2 = ax1.twinx()
|
| 343 |
+
ax2.plot(time, load, label='Power Load', color='darkblue', linewidth=2)
|
| 344 |
+
ax2.set_ylabel('Power Load (×10³ MW)', color='darkblue', fontsize=20)
|
| 345 |
+
ax2.tick_params(axis='y', labelcolor='darkblue', labelsize=20)
|
| 346 |
+
ax2.tick_params(axis='x', labelsize=20)
|
| 347 |
+
# Title and layout adjustments
|
| 348 |
+
fig.suptitle('Temperature and Power Load Over Time', fontsize=20)
|
| 349 |
+
fig.autofmt_xdate(rotation=45)
|
| 350 |
+
plt.tight_layout()
|
| 351 |
+
# plt.savefig("./results/raw_load_temp_spanish.pdf")
|
| 352 |
+
plt.show()
|
| 353 |
+
print(time.shape, load.shape, temperature.shape)
|
| 354 |
+
return time, load, temperature
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def get_data_spanish_weekly():
|
| 358 |
+
"""
|
| 359 |
+
Weekly load-temperature slices for Spain
|
| 360 |
+
—————————————————————————————————————————————————
|
| 361 |
+
Returns
|
| 362 |
+
-------
|
| 363 |
+
times : np.ndarray, dtype=object, shape (n_weeks,)
|
| 364 |
+
energy : np.ndarray, shape (n_weeks, 168)
|
| 365 |
+
temp : np.ndarray, shape (n_weeks, 168)
|
| 366 |
+
workday : np.ndarray, shape (n_weeks, 168)
|
| 367 |
+
season_feat : np.ndarray, shape (n_weeks, 168)
|
| 368 |
+
"""
|
| 369 |
+
# ---------- raw files --------------------------------------------------
|
| 370 |
+
p_energy = "/Users/muhaoguo/Documents/study/Paper_Projects/PESGM/data/kaggle/energy_dataset.csv"
|
| 371 |
+
p_weather = "/Users/muhaoguo/Documents/study/Paper_Projects/PESGM/data/kaggle/weather_features.csv"
|
| 372 |
+
|
| 373 |
+
# ---------- pre-processing & merge ------------------------------------
|
| 374 |
+
energy_df = pd.read_csv(p_energy)
|
| 375 |
+
weather_df = pd.read_csv(p_weather)
|
| 376 |
+
|
| 377 |
+
energy_df["time"] = pd.to_datetime(energy_df["time"], utc=True)
|
| 378 |
+
weather_df["time"] = pd.to_datetime(weather_df["dt_iso"], utc=True)
|
| 379 |
+
df = pd.merge(energy_df, weather_df, on="time", how="inner")
|
| 380 |
+
df = df[::5]
|
| 381 |
+
df = df[1:]
|
| 382 |
+
|
| 383 |
+
df["time"] = df["time"].dt.tz_convert(None) # or .dt.tz_localize(None)
|
| 384 |
+
df = df[["time", "temp", "total load actual"]].dropna()
|
| 385 |
+
df["Date"] = df["time"].dt.date # now works
|
| 386 |
+
df["day_of_week"] = df["time"].dt.dayofweek
|
| 387 |
+
df["air_temperature"] = (df["temp"] - 273.15).astype(float)
|
| 388 |
+
df["meter_reading"] = (df["total load actual"] / 1000).astype(float)
|
| 389 |
+
|
| 390 |
+
# ---------- season helper ---------------------------------------------
|
| 391 |
+
def get_season(month: int) -> int:
|
| 392 |
+
return {12: 0, 1: 0, 2: 0, 3: 1, 4: 1, 5: 1,
|
| 393 |
+
6: 2, 7: 2, 8: 2, 9: 3, 10: 3, 11: 3}[month]
|
| 394 |
+
|
| 395 |
+
# ---------- daily grouping (24 samples each) ---------------------------
|
| 396 |
+
meas_cols = ["meter_reading", "air_temperature", "Date", "time"]
|
| 397 |
+
grouped = df.groupby("Date")[meas_cols + ["day_of_week"]]
|
| 398 |
+
|
| 399 |
+
array_3d, labels_3d, seasons_3d = [], [], []
|
| 400 |
+
for date_val in sorted(grouped.groups.keys()):
|
| 401 |
+
gdf = grouped.get_group(date_val)
|
| 402 |
+
|
| 403 |
+
# make sure we have *exactly* 24 hourly rows
|
| 404 |
+
if len(gdf) != 24:
|
| 405 |
+
full_hours = pd.date_range(start=f"{date_val} 00:00:00",
|
| 406 |
+
end=f"{date_val} 23:00:00",
|
| 407 |
+
freq="H")
|
| 408 |
+
tmpl = pd.DataFrame({"time": full_hours})
|
| 409 |
+
gdf = pd.merge(tmpl, gdf, on="time", how="left")
|
| 410 |
+
gdf["Date"] = gdf["time"].dt.date
|
| 411 |
+
gdf["day_of_week"] = gdf["time"].dt.dayofweek
|
| 412 |
+
for c in ["meter_reading", "air_temperature"]:
|
| 413 |
+
gdf[c] = (gdf[c]
|
| 414 |
+
.interpolate("linear")
|
| 415 |
+
.ffill()
|
| 416 |
+
.bfill()
|
| 417 |
+
)
|
| 418 |
+
gdf.fillna({"meter_reading": 0, "air_temperature": 15}, inplace=True)
|
| 419 |
+
|
| 420 |
+
arr = gdf[meas_cols].values
|
| 421 |
+
w_label = 0 if gdf["day_of_week"].iloc[0] < 5 else 1
|
| 422 |
+
season = get_season(gdf["time"].iloc[0].month)
|
| 423 |
+
|
| 424 |
+
array_3d.append(arr)
|
| 425 |
+
labels_3d.append(np.full(len(arr), w_label))
|
| 426 |
+
seasons_3d.append(np.full(len(arr), season))
|
| 427 |
+
|
| 428 |
+
# ---------- pack consecutive days into full weeks ---------------------
|
| 429 |
+
n_full_weeks = len(array_3d) // 7
|
| 430 |
+
if n_full_weeks == 0:
|
| 431 |
+
return (np.array([]),) * 5
|
| 432 |
+
|
| 433 |
+
energy, temp, times, workday, season_feat = [], [], [], [], []
|
| 434 |
+
for w in range(n_full_weeks):
|
| 435 |
+
wk = slice(w * 7, (w + 1) * 7)
|
| 436 |
+
week_d = array_3d[wk]
|
| 437 |
+
w_lbls = labels_3d[wk]
|
| 438 |
+
w_seas = seasons_3d[wk]
|
| 439 |
+
|
| 440 |
+
e = np.concatenate([d[:, 0].astype(float) for d in week_d])
|
| 441 |
+
t = np.concatenate([d[:, 1].astype(float) for d in week_d])
|
| 442 |
+
ts = np.concatenate([d[:, 3] for d in week_d]) # timestamps
|
| 443 |
+
wl = np.concatenate([lbl.astype(int) for lbl in w_lbls])
|
| 444 |
+
sl = np.concatenate([s.astype(int) for s in w_seas])
|
| 445 |
+
|
| 446 |
+
if e.size != 168: # incomplete week – skip
|
| 447 |
+
continue
|
| 448 |
+
|
| 449 |
+
energy.append(gaussian_filter1d(e, sigma=1))
|
| 450 |
+
temp.append(gaussian_filter1d(t, sigma=1))
|
| 451 |
+
times.append(ts)
|
| 452 |
+
workday.append(wl)
|
| 453 |
+
season_feat.append(sl)
|
| 454 |
+
|
| 455 |
+
return (np.array(times, dtype=object),
|
| 456 |
+
np.array(energy),
|
| 457 |
+
np.array(temp),
|
| 458 |
+
np.array(workday),
|
| 459 |
+
np.array(season_feat))
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def get_data_power_consumption():
|
| 464 |
+
"""
|
| 465 |
+
https://www.kaggle.com/datasets/fedesoriano/electric-power-consumption
|
| 466 |
+
Loads a CSV containing at least:
|
| 467 |
+
['Date Time', 'Temperature', 'Zone 1 Power Consumption']
|
| 468 |
+
and does a simple time-series plot of Zone 1 vs. Temperature.
|
| 469 |
+
"""
|
| 470 |
+
# 1) Load data
|
| 471 |
+
file_path = "/Users/muhaoguo/Documents/study/Paper_Projects/PESGM/data/powerconsumption/powerconsumption.csv" # <-- Adjust to your actual CSV
|
| 472 |
+
df = pd.read_csv(file_path)
|
| 473 |
+
|
| 474 |
+
# 2) Parse datetime and sort
|
| 475 |
+
# We assume a combined 'Date Time' column, like '2020-01-01 00:10:00'
|
| 476 |
+
df['Date Time'] = pd.to_datetime(df['Datetime'])
|
| 477 |
+
df.sort_values(by='Date Time', inplace=True)
|
| 478 |
+
|
| 479 |
+
# 3) Select only needed columns
|
| 480 |
+
# We pick 'Zone 1 Power Consumption' & 'Temperature'
|
| 481 |
+
df_filtered = df[['Date Time', 'Temperature', 'PowerConsumption_Zone1']].copy()
|
| 482 |
+
|
| 483 |
+
# 4) Convert to numeric (in case CSV has strings)
|
| 484 |
+
# Coerce errors => NaN
|
| 485 |
+
df_filtered['Temperature'] = pd.to_numeric(df_filtered['Temperature'], errors='coerce')
|
| 486 |
+
df_filtered['Zone 1 Power Consumption'] = pd.to_numeric(df_filtered['PowerConsumption_Zone1'], errors='coerce')
|
| 487 |
+
|
| 488 |
+
# 5) Drop rows with missing values if needed
|
| 489 |
+
df_filtered.dropna(subset=['Temperature', 'Zone 1 Power Consumption'], inplace=True)
|
| 490 |
+
scaler = MinMaxScaler()
|
| 491 |
+
df_filtered[['Temperature', 'Zone 1 Power Consumption']] = scaler.fit_transform(
|
| 492 |
+
df_filtered[['Temperature', 'Zone 1 Power Consumption']]
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
# 6) Simple Plot: Time series of Zone1 and Temperature
|
| 496 |
+
fig, ax1 = plt.subplots(figsize=(10, 5))
|
| 497 |
+
# Plot Zone 1 Power on ax1
|
| 498 |
+
color1 = 'tab:blue'
|
| 499 |
+
ax1.set_xlabel('Date Time')
|
| 500 |
+
ax1.set_ylabel('Zone 1 Power Consumption', color=color1)
|
| 501 |
+
ax1.plot(df_filtered['Date Time'], df_filtered['Zone 1 Power Consumption'], color=color1, label='Zone1 Power')
|
| 502 |
+
ax1.tick_params(axis='y', labelcolor=color1)
|
| 503 |
+
|
| 504 |
+
# Create a second y-axis for Temperature
|
| 505 |
+
ax2 = ax1.twinx() # shares x-axis
|
| 506 |
+
color2 = 'tab:red'
|
| 507 |
+
ax2.set_ylabel('Temperature', color=color2)
|
| 508 |
+
ax2.plot(df_filtered['Date Time'], df_filtered['Temperature'], color=color2, label='Temperature')
|
| 509 |
+
ax2.tick_params(axis='y', labelcolor=color2)
|
| 510 |
+
plt.title('Zone 1 Power Consumption and Temperature Over Time')
|
| 511 |
+
fig.tight_layout()
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
# --------------------------------------------------------
|
| 515 |
+
# 7) Reshape the data: separate by date
|
| 516 |
+
# => new shape: [#dates, #values_in_one_day]
|
| 517 |
+
# --------------------------------------------------------
|
| 518 |
+
# Extract the date and the time of day (as a string HH:MM:SS)
|
| 519 |
+
df_filtered['Date'] = df_filtered['Date Time'].dt.date
|
| 520 |
+
df_filtered['TimeOfDay'] = df_filtered['Date Time'].dt.strftime('%H:%M:%S')
|
| 521 |
+
|
| 522 |
+
# Pivot so each row is one date, each column is a time of day
|
| 523 |
+
pivot_time = df_filtered.pivot(index='Date', columns='TimeOfDay', values='Date Time')
|
| 524 |
+
pivot_power = df_filtered.pivot(index='Date', columns='TimeOfDay', values='Zone 1 Power Consumption')
|
| 525 |
+
pivot_temp = df_filtered.pivot(index='Date', columns='TimeOfDay', values='Temperature')
|
| 526 |
+
|
| 527 |
+
# Sort the columns so time-of-day is in ascending order (00:00:00 < 00:10:00 < ...)
|
| 528 |
+
pivot_time = pivot_time.reindex(sorted(pivot_time.columns), axis=1)
|
| 529 |
+
pivot_power = pivot_power.reindex(sorted(pivot_power.columns), axis=1)
|
| 530 |
+
pivot_temp = pivot_temp.reindex(sorted(pivot_temp.columns), axis=1)
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
# 9) Create workday/weekend label
|
| 534 |
+
workday_label = np.array([
|
| 535 |
+
[1 if pd.Timestamp(date).weekday() >= 5 else 0] * pivot_power.shape[1]
|
| 536 |
+
for date in pivot_power.index
|
| 537 |
+
])
|
| 538 |
+
|
| 539 |
+
# --------------------------------------------------------
|
| 540 |
+
# 8) Plot daily profiles (one line per date)
|
| 541 |
+
# --------------------------------------------------------
|
| 542 |
+
# Plot Zone 1 Power
|
| 543 |
+
plt.figure(figsize=(10,4))
|
| 544 |
+
for date_idx in pivot_power.index:
|
| 545 |
+
plt.plot(pivot_power.columns, pivot_power.loc[date_idx, :], label=str(date_idx), alpha=0.4, color="gray")
|
| 546 |
+
plt.title("Daily Profile of Zone 1 Power Consumption")
|
| 547 |
+
plt.xlabel("Time of Day (HH:MM:SS)")
|
| 548 |
+
plt.ylabel("Scaled Power Consumption")
|
| 549 |
+
# Uncomment to show legend with all dates
|
| 550 |
+
# plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
|
| 551 |
+
plt.tight_layout()
|
| 552 |
+
|
| 553 |
+
# Plot Temperature
|
| 554 |
+
plt.figure(figsize=(10,4))
|
| 555 |
+
for date_idx in pivot_temp.index:
|
| 556 |
+
plt.plot(pivot_temp.columns, pivot_temp.loc[date_idx, :], label=str(date_idx), alpha=0.4, color="green")
|
| 557 |
+
plt.title("Daily Profile of Temperature")
|
| 558 |
+
plt.xlabel("Time of Day (HH:MM:SS)")
|
| 559 |
+
plt.ylabel("Scaled Temperature")
|
| 560 |
+
# plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
|
| 561 |
+
plt.tight_layout()
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
# 10) Visualize one week of Power, Temperature, and Workday Label
|
| 565 |
+
week_index = 0 # Change this to shift the week (e.g., 7 for second week)
|
| 566 |
+
days_to_plot = 7
|
| 567 |
+
power_week = pivot_power.iloc[week_index:week_index+days_to_plot, :].to_numpy().flatten()
|
| 568 |
+
temp_week = pivot_temp.iloc[week_index:week_index+days_to_plot, :].to_numpy().flatten()
|
| 569 |
+
label_week = workday_label[week_index:week_index+days_to_plot, :].flatten()
|
| 570 |
+
|
| 571 |
+
time_axis = np.arange(len(power_week)) # X-axis for plotting
|
| 572 |
+
plt.figure(figsize=(12, 4))
|
| 573 |
+
plt.plot(time_axis, power_week, label='Power', linewidth=1)
|
| 574 |
+
plt.plot(time_axis, temp_week, label='Temperature', linewidth=1)
|
| 575 |
+
plt.plot(time_axis, label_week, label='Workday Label', linewidth=2, linestyle='--')
|
| 576 |
+
plt.title("One Week of Power, Temperature, and Workday Labels")
|
| 577 |
+
plt.xlabel("10-minute Intervals over 7 Days")
|
| 578 |
+
plt.ylabel("Normalized Value")
|
| 579 |
+
plt.legend()
|
| 580 |
+
plt.grid(True)
|
| 581 |
+
plt.tight_layout()
|
| 582 |
+
# plt.savefig("results/one_week_data.pdf")
|
| 583 |
+
plt.show()
|
| 584 |
+
|
| 585 |
+
return np.array(pivot_time), np.array(pivot_power), np.array(pivot_temp)
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
def plot_data(times, energy, temp, workday, season_feat,
|
| 589 |
+
alpha=0.5, lw=1.0, cmap="viridis"):
|
| 590 |
+
"""
|
| 591 |
+
Overlay *all* weeks in four side-by-side sub-figures.
|
| 592 |
+
|
| 593 |
+
Parameters
|
| 594 |
+
----------
|
| 595 |
+
times, energy, temp, workday, season_feat : list/ndarray
|
| 596 |
+
Output from your get_data_…_weekly routine.
|
| 597 |
+
alpha : float
|
| 598 |
+
Per-curve transparency (≤1). Lower → less clutter.
|
| 599 |
+
lw : float
|
| 600 |
+
Line width.
|
| 601 |
+
cmap : str or matplotlib Colormap
|
| 602 |
+
Used to give each week a slightly different colour.
|
| 603 |
+
"""
|
| 604 |
+
n_weeks = len(times)
|
| 605 |
+
if n_weeks == 0:
|
| 606 |
+
print("Nothing to plot.")
|
| 607 |
+
return
|
| 608 |
+
|
| 609 |
+
# colour map to distinguish weeks (wraps if >256)
|
| 610 |
+
colours = plt.cm.get_cmap(cmap, n_weeks)
|
| 611 |
+
|
| 612 |
+
fig, axes = plt.subplots(
|
| 613 |
+
nrows=1, ncols=4, figsize=(22, 4),
|
| 614 |
+
sharex=False, sharey=False,
|
| 615 |
+
gridspec_kw={"wspace": 0.25})
|
| 616 |
+
|
| 617 |
+
date_fmt = mdates.DateFormatter("%b\n%d")
|
| 618 |
+
|
| 619 |
+
# -------------------------------------------------------------
|
| 620 |
+
# iterate once, plotting the same week on all four axes
|
| 621 |
+
# -------------------------------------------------------------
|
| 622 |
+
for w in range(n_weeks):
|
| 623 |
+
c = colours(w)
|
| 624 |
+
|
| 625 |
+
axes[0].plot(times[w], energy[w], color=c, alpha=alpha, lw=lw)
|
| 626 |
+
axes[1].plot(times[w], temp[w], color=c, alpha=alpha, lw=lw)
|
| 627 |
+
axes[2].step(times[w], workday[w], where="mid",
|
| 628 |
+
color=c, alpha=alpha, lw=lw)
|
| 629 |
+
axes[3].step(times[w], season_feat[w], where="mid",
|
| 630 |
+
color=c, alpha=alpha, lw=lw)
|
| 631 |
+
|
| 632 |
+
# -------------------------------------------------------------
|
| 633 |
+
# cosmetics
|
| 634 |
+
# -------------------------------------------------------------
|
| 635 |
+
axes[0].set_title("Energy (norm.)")
|
| 636 |
+
axes[0].set_ylabel("0–1")
|
| 637 |
+
axes[1].set_title("Temperature (norm.)")
|
| 638 |
+
axes[2].set_title("Weekend flag")
|
| 639 |
+
axes[2].set_ylim(-0.1, 1.1)
|
| 640 |
+
axes[3].set_title("Season (0–3)")
|
| 641 |
+
axes[3].set_ylim(-0.2, 3.2)
|
| 642 |
+
|
| 643 |
+
for ax in axes:
|
| 644 |
+
ax.xaxis.set_major_formatter(date_fmt)
|
| 645 |
+
ax.tick_params(axis="x", rotation=45, labelsize=8)
|
| 646 |
+
|
| 647 |
+
fig.suptitle(f"Overlay of {n_weeks} weeks", fontsize=15, y=1.02)
|
| 648 |
+
plt.tight_layout()
|
| 649 |
+
plt.show()
|
| 650 |
+
|
| 651 |
+
##
|
| 652 |
+
fig, axes = plt.subplots( nrows=1, ncols=4, figsize=(22, 4), sharex=False, sharey=False, gridspec_kw={"wspace": 0.25})
|
| 653 |
+
date_fmt = mdates.DateFormatter("%b\n%d")
|
| 654 |
+
# -------------------------------------------------------------
|
| 655 |
+
# iterate once, plotting the same week on all four axes
|
| 656 |
+
# -------------------------------------------------------------
|
| 657 |
+
for w in range(n_weeks):
|
| 658 |
+
c = colours(w)
|
| 659 |
+
axes[0].plot(energy[w], color=c, alpha=alpha, lw=lw)
|
| 660 |
+
axes[1].plot(temp[w], color=c, alpha=alpha, lw=lw)
|
| 661 |
+
axes[2].plot(workday[w], color=c, alpha=alpha, lw=lw)
|
| 662 |
+
axes[3].plot(season_feat[w], color=c, alpha=alpha, lw=lw)
|
| 663 |
+
|
| 664 |
+
# -------------------------------------------------------------
|
| 665 |
+
# cosmetics
|
| 666 |
+
# -------------------------------------------------------------
|
| 667 |
+
axes[0].set_title("Energy (norm.)")
|
| 668 |
+
axes[0].set_ylabel("0–1")
|
| 669 |
+
axes[1].set_title("Temperature (norm.)")
|
| 670 |
+
axes[2].set_title("Weekend flag")
|
| 671 |
+
axes[2].set_ylim(-0.1, 1.1)
|
| 672 |
+
axes[3].set_title("Season (0–3)")
|
| 673 |
+
axes[3].set_ylim(-0.2, 3.2)
|
| 674 |
+
|
| 675 |
+
for ax in axes:
|
| 676 |
+
ax.xaxis.set_major_formatter(date_fmt)
|
| 677 |
+
ax.tick_params(axis="x", rotation=45, labelsize=8)
|
| 678 |
+
|
| 679 |
+
fig.suptitle(f"Overlay of {n_weeks} weeks", fontsize=15, y=1.02)
|
| 680 |
+
plt.tight_layout()
|
| 681 |
+
plt.show()
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
def get_data_power_consumption_weekly():
|
| 687 |
+
"""
|
| 688 |
+
Weekly load-temperature slices (Zone-1 household data)
|
| 689 |
+
------------------------------------------------------
|
| 690 |
+
Returns
|
| 691 |
+
-------
|
| 692 |
+
times : ndarray[object] – n_weeks, each element len = points_per_day*7
|
| 693 |
+
energy : ndarray[float] – n_weeks × (points_per_day*7)
|
| 694 |
+
temp : ndarray[float] – idem
|
| 695 |
+
workday : ndarray[int] – idem (0 weekday, 1 weekend)
|
| 696 |
+
season_feat : ndarray[int] – idem (0-winter … 3-autumn)
|
| 697 |
+
"""
|
| 698 |
+
csv_path = Path("/Users/muhaoguo/Documents/study/Paper_Projects/PESGM/data/powerconsumption/powerconsumption.csv")
|
| 699 |
+
|
| 700 |
+
# ── 1. Read & basic cleaning ──────────────────────────────────────────
|
| 701 |
+
df = pd.read_csv(csv_path)
|
| 702 |
+
# column names vary slightly across versions → be defensive
|
| 703 |
+
time_col = next(c for c in df.columns if c.lower().startswith(("date time", "datetime")))
|
| 704 |
+
temp_col = next(c for c in df.columns if "temp" in c.lower())
|
| 705 |
+
power_col= next(c for c in df.columns if "zone1" in c.lower())
|
| 706 |
+
|
| 707 |
+
df["time"] = pd.to_datetime(df[time_col])
|
| 708 |
+
df["air_temperature"] = pd.to_numeric(df[temp_col], errors="coerce")
|
| 709 |
+
df["meter_reading"] = pd.to_numeric(df[power_col], errors="coerce")
|
| 710 |
+
df = df[["time", "air_temperature", "meter_reading"]].dropna()
|
| 711 |
+
df = df[::6]
|
| 712 |
+
# print(df)
|
| 713 |
+
df.sort_values("time", inplace=True)
|
| 714 |
+
|
| 715 |
+
for c in ["air_temperature", "meter_reading"]:
|
| 716 |
+
col_min, col_max = df[c].min(), df[c].max()
|
| 717 |
+
df[c] = (df[c] - col_min) / (col_max - col_min)
|
| 718 |
+
|
| 719 |
+
# ── 2. Identify full days & points-per-day ────────────────────────────
|
| 720 |
+
df["date"] = df["time"].dt.date
|
| 721 |
+
day_counts = df.groupby("date").size()
|
| 722 |
+
points_per_day = int(day_counts.mode().iloc[0]) # most common daily length
|
| 723 |
+
|
| 724 |
+
full_dates = day_counts[day_counts == points_per_day].index
|
| 725 |
+
df = df[df["date"].isin(full_dates)].copy()
|
| 726 |
+
|
| 727 |
+
# ── 3. Season & weekday helpers ───────────────────────────────────────
|
| 728 |
+
def get_season(month):
|
| 729 |
+
return {12:0,1:0,2:0,3:1,4:1,5:1,6:2,7:2,8:2,9:3,10:3,11:3}[month]
|
| 730 |
+
|
| 731 |
+
# ── 4. Daily arrays (guaranteed length = points_per_day) ──────────────
|
| 732 |
+
meas_cols = ["meter_reading", "air_temperature", "date", "time"]
|
| 733 |
+
grouped = df.groupby("date")[meas_cols]
|
| 734 |
+
|
| 735 |
+
array_3d, labels_3d, seasons_3d = [], [], []
|
| 736 |
+
for d in sorted(grouped.groups.keys()):
|
| 737 |
+
g = grouped.get_group(d).sort_values("time")
|
| 738 |
+
# (No need to re-index; we already filtered to full days.)
|
| 739 |
+
arr = g[meas_cols].values
|
| 740 |
+
w_label = 0 if g["time"].dt.dayofweek.iloc[0] < 5 else 1
|
| 741 |
+
season = get_season(g["time"].iloc[0].month)
|
| 742 |
+
|
| 743 |
+
array_3d.append(arr)
|
| 744 |
+
labels_3d.append(np.full(points_per_day, w_label))
|
| 745 |
+
seasons_3d.append(np.full(points_per_day, season))
|
| 746 |
+
|
| 747 |
+
# ── 5. Pack into complete weeks (7 consecutive full days) ─────────────
|
| 748 |
+
n_full_weeks = len(array_3d) // 7
|
| 749 |
+
if n_full_weeks == 0:
|
| 750 |
+
return (np.array([]),) * 5
|
| 751 |
+
|
| 752 |
+
sigma = max(1, points_per_day // 24) # ≈ 1-hour smoothing
|
| 753 |
+
energy, temp, times, workday, season_feat = [], [], [], [], []
|
| 754 |
+
|
| 755 |
+
for w in range(n_full_weeks):
|
| 756 |
+
|
| 757 |
+
wk = slice(w*7, (w+1)*7)
|
| 758 |
+
week_d, w_lbls, w_seas = array_3d[wk], labels_3d[wk], seasons_3d[wk]
|
| 759 |
+
|
| 760 |
+
e = np.asarray(np.concatenate([d[:, 0] for d in week_d]), dtype=float)
|
| 761 |
+
t = np.asarray(np.concatenate([d[:, 1] for d in week_d]), dtype=float)
|
| 762 |
+
ts = np.concatenate([d[:,3] for d in week_d])
|
| 763 |
+
wl = np.concatenate(w_lbls)
|
| 764 |
+
sl = np.concatenate(w_seas)
|
| 765 |
+
|
| 766 |
+
energy.append(gaussian_filter1d(e, sigma=sigma))
|
| 767 |
+
temp.append(gaussian_filter1d(t, sigma=sigma))
|
| 768 |
+
times.append(ts)
|
| 769 |
+
workday.append(wl)
|
| 770 |
+
season_feat.append(sl)
|
| 771 |
+
|
| 772 |
+
# plot_data(times, energy, temp, workday, season_feat)
|
| 773 |
+
|
| 774 |
+
return (np.array(times, dtype=object),
|
| 775 |
+
np.array(energy),
|
| 776 |
+
np.array(temp),
|
| 777 |
+
np.array(workday),
|
| 778 |
+
np.array(season_feat))
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
|
| 782 |
+
|
| 783 |
+
def get_data_kaggle_2():
|
| 784 |
+
"""
|
| 785 |
+
https://www.kaggle.com/datasets/srinuti/residential-power-usage-3years-data-timeseries
|
| 786 |
+
Loads the 'power_usage_2016_to_2020.csv' and 'weather_2016_2020_daily.csv' datasets,
|
| 787 |
+
merges them by date, creates daily profiles, and plots a single week of data
|
| 788 |
+
(Power, Temperature, Workday Label) in a flattened time series.
|
| 789 |
+
"""
|
| 790 |
+
load_file = "/Users/muhaoguo/Documents/study/Paper_Projects/PESGM/data/Kaggle_2/power_usage_2016_to_2020.csv"
|
| 791 |
+
df_load = pd.read_csv(load_file)
|
| 792 |
+
df_load['DateTime'] = pd.to_datetime(df_load['StartDate'])
|
| 793 |
+
df_load['Date'] = df_load['DateTime'].dt.date
|
| 794 |
+
df_load.rename(columns={'Value (kWh)': 'Power'}, inplace=True)
|
| 795 |
+
|
| 796 |
+
weather_file = "/Users/muhaoguo/Documents/study/Paper_Projects/PESGM/data/Kaggle_2/weather_2016_2020_daily.csv"
|
| 797 |
+
df_weather = pd.read_csv(weather_file)
|
| 798 |
+
|
| 799 |
+
df_weather['Date'] = pd.to_datetime(df_weather['Date']).dt.date
|
| 800 |
+
df_weather.rename(columns={'Temp_avg': 'Temperature'}, inplace=True)
|
| 801 |
+
df_weather = df_weather[['Date', 'Temperature']]
|
| 802 |
+
|
| 803 |
+
|
| 804 |
+
df_merged = pd.merge(df_load, df_weather, on='Date', how='left')
|
| 805 |
+
|
| 806 |
+
df_merged.sort_values(by='DateTime', inplace=True)
|
| 807 |
+
df_merged.dropna(subset=['Power', 'Temperature'], inplace=True)
|
| 808 |
+
|
| 809 |
+
scaler = MinMaxScaler()
|
| 810 |
+
df_merged[['Power', 'Temperature']] = scaler.fit_transform(df_merged[['Power', 'Temperature']])
|
| 811 |
+
df_merged['TimeOfDay'] = df_merged['DateTime'].dt.strftime('%H:%M:%S')
|
| 812 |
+
|
| 813 |
+
pivot_power = df_merged.pivot(index='Date', columns='TimeOfDay', values='Power')
|
| 814 |
+
pivot_temp = df_merged.pivot(index='Date', columns='TimeOfDay', values='Temperature')
|
| 815 |
+
pivot_time = df_merged.pivot(index='Date', columns='TimeOfDay', values='DateTime')
|
| 816 |
+
|
| 817 |
+
# Sort columns so time-of-day is in ascending order
|
| 818 |
+
pivot_power = pivot_power.reindex(sorted(pivot_power.columns), axis=1)
|
| 819 |
+
pivot_temp = pivot_temp.reindex(sorted(pivot_temp.columns), axis=1)
|
| 820 |
+
pivot_time = pivot_time.reindex(sorted(pivot_time.columns), axis=1)
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
pivot_dates = pivot_power.index # these are datetime.date objects
|
| 824 |
+
|
| 825 |
+
df_day = df_load.groupby('Date')['day_of_week'].first().reindex(pivot_dates)
|
| 826 |
+
weekend_indicator = df_day.isin([5, 6]).astype(int).values # 1 if day_of_week in [6,7], else 0
|
| 827 |
+
|
| 828 |
+
workday_label_2D = np.array([
|
| 829 |
+
[weekend_indicator[i]] * pivot_power.shape[1]
|
| 830 |
+
for i in range(len(pivot_dates))
|
| 831 |
+
])
|
| 832 |
+
print(workday_label_2D)
|
| 833 |
+
plt.figure(figsize=(10, 4))
|
| 834 |
+
for date_idx in pivot_power.index:
|
| 835 |
+
plt.plot(
|
| 836 |
+
pivot_power.columns,
|
| 837 |
+
pivot_power.loc[date_idx, :],
|
| 838 |
+
label=str(date_idx), alpha=0.4, color="gray"
|
| 839 |
+
)
|
| 840 |
+
plt.title("Daily Profile of Power")
|
| 841 |
+
plt.xlabel("Time of Day")
|
| 842 |
+
plt.ylabel("Scaled Power")
|
| 843 |
+
plt.tight_layout()
|
| 844 |
+
plt.show()
|
| 845 |
+
|
| 846 |
+
# 7b) Plot daily temperature profiles
|
| 847 |
+
plt.figure(figsize=(10, 4))
|
| 848 |
+
for date_idx in pivot_temp.index:
|
| 849 |
+
plt.plot(
|
| 850 |
+
pivot_temp.columns,
|
| 851 |
+
pivot_temp.loc[date_idx, :],
|
| 852 |
+
label=str(date_idx), alpha=0.4, color="blue"
|
| 853 |
+
)
|
| 854 |
+
plt.title("Daily Profile of Temperature")
|
| 855 |
+
plt.xlabel("Time of Day")
|
| 856 |
+
plt.ylabel("Scaled Temperature")
|
| 857 |
+
# plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
|
| 858 |
+
plt.tight_layout()
|
| 859 |
+
plt.show()
|
| 860 |
+
|
| 861 |
+
# ------------------------------------------------
|
| 862 |
+
# 8) Select ONE WEEK of data and flatten it into a single time-series
|
| 863 |
+
# ------------------------------------------------
|
| 864 |
+
# Let's say we pick the first 7 days in the pivot:
|
| 865 |
+
week_index = 10 # which chunk of 7 days to pick
|
| 866 |
+
days_to_plot = 7
|
| 867 |
+
chosen_dates = pivot_power.index[week_index:week_index + days_to_plot]
|
| 868 |
+
|
| 869 |
+
power_week = pivot_power.loc[chosen_dates, :].to_numpy().flatten()
|
| 870 |
+
temp_week = pivot_temp.loc[chosen_dates, :].to_numpy().flatten()
|
| 871 |
+
label_week = workday_label_2D[week_index:week_index + days_to_plot, :].flatten()
|
| 872 |
+
|
| 873 |
+
# The X-axis will be one point per hour (or half-hour, etc.) times 7 days
|
| 874 |
+
time_axis = np.arange(len(power_week))
|
| 875 |
+
|
| 876 |
+
# ------------------------------------------------
|
| 877 |
+
# 9) Plot one-week time series of Power, Temperature, Workday
|
| 878 |
+
# ------------------------------------------------
|
| 879 |
+
plt.figure(figsize=(12, 4))
|
| 880 |
+
plt.plot(time_axis, power_week, label='Power', linewidth=1)
|
| 881 |
+
plt.plot(time_axis, temp_week, label='Temperature', linewidth=1)
|
| 882 |
+
plt.plot(time_axis, label_week, label='Workday Label',
|
| 883 |
+
linewidth=2, linestyle='--')
|
| 884 |
+
|
| 885 |
+
print(list(power_week))
|
| 886 |
+
|
| 887 |
+
plt.title("One Week of Power, Temperature, and Workday Labels")
|
| 888 |
+
plt.xlabel("Hourly Points over 7 Days")
|
| 889 |
+
plt.ylabel("Scaled Value / Label")
|
| 890 |
+
plt.legend()
|
| 891 |
+
plt.grid(True)
|
| 892 |
+
plt.tight_layout()
|
| 893 |
+
plt.show()
|
| 894 |
+
|
| 895 |
+
return pivot_power, pivot_temp, workday_label_2D
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
|
| 899 |
+
def get_data_residential_weekly():
|
| 900 |
+
"""
|
| 901 |
+
Residential power-usage data (2016-2020) → weekly slices.
|
| 902 |
+
|
| 903 |
+
Returns
|
| 904 |
+
-------
|
| 905 |
+
times : np.ndarray (dtype=object) – shape (n_weeks,)
|
| 906 |
+
each element is a 1-D array of datetime stamps
|
| 907 |
+
energy : np.ndarray, shape (n_weeks, points_per_day*7)
|
| 908 |
+
temp : np.ndarray, same shape
|
| 909 |
+
workday : np.ndarray, same shape, int {0,1}
|
| 910 |
+
season_feat : np.ndarray, same shape, int {0,1,2,3}
|
| 911 |
+
"""
|
| 912 |
+
|
| 913 |
+
# ── paths ──────────────────────────────────────────────────────────────
|
| 914 |
+
p_load = Path("/Users/muhaoguo/Documents/study/Paper_Projects/PESGM/data/Kaggle_2/power_usage_2016_to_2020.csv")
|
| 915 |
+
p_weather = Path("/Users/muhaoguo/Documents/study/Paper_Projects/PESGM/data/Kaggle_2/weather_2016_2020_daily.csv")
|
| 916 |
+
|
| 917 |
+
# ── 1. read & basic merge (load = hourly, weather = daily) ───────────
|
| 918 |
+
df_load = pd.read_csv(p_load)
|
| 919 |
+
df_load["time"] = pd.to_datetime(df_load["StartDate"])
|
| 920 |
+
df_load["date"] = df_load["time"].dt.date
|
| 921 |
+
df_load.rename(columns={"Value (kWh)": "meter_reading"}, inplace=True)
|
| 922 |
+
|
| 923 |
+
df_weather = pd.read_csv(p_weather)
|
| 924 |
+
df_weather["date"] = pd.to_datetime(df_weather["Date"]).dt.date
|
| 925 |
+
df_weather.rename(columns={"Temp_avg": "air_temperature"}, inplace=True)
|
| 926 |
+
|
| 927 |
+
df = pd.merge(df_load[["time", "date", "meter_reading", "day_of_week"]],
|
| 928 |
+
df_weather[["date", "air_temperature"]],
|
| 929 |
+
on="date", how="left")
|
| 930 |
+
|
| 931 |
+
# ── 2. keep numeric & drop NaN ─────────────────────────────────────────
|
| 932 |
+
df["meter_reading"] = pd.to_numeric(df["meter_reading"], errors="coerce")
|
| 933 |
+
df["air_temperature"] = pd.to_numeric(df["air_temperature"], errors="coerce")
|
| 934 |
+
df.dropna(subset=["meter_reading", "air_temperature"], inplace=True)
|
| 935 |
+
df.sort_values("time", inplace=True)
|
| 936 |
+
|
| 937 |
+
# min-max normalise both variables globally
|
| 938 |
+
for c in ["meter_reading", "air_temperature"]:
|
| 939 |
+
v_min, v_max = df[c].min(), df[c].max()
|
| 940 |
+
df[c] = (df[c] - v_min) / (v_max - v_min)
|
| 941 |
+
|
| 942 |
+
# ── 3. ensure full-day rows & discover points_per_day ─────────────────
|
| 943 |
+
day_counts = df.groupby("date").size()
|
| 944 |
+
points_per_day = int(day_counts.mode().iloc[0]) # most common length
|
| 945 |
+
full_dates = day_counts[day_counts == points_per_day].index
|
| 946 |
+
df = df[df["date"].isin(full_dates)].copy()
|
| 947 |
+
|
| 948 |
+
|
| 949 |
+
# ── 4. helpers ─────────────────────────────────────────────────────────
|
| 950 |
+
def get_season(m): # 0=winter … 3=autumn
|
| 951 |
+
return {12:0,1:0,2:0,3:1,4:1,5:1,6:2,7:2,8:2,9:3,10:3,11:3}[m]
|
| 952 |
+
|
| 953 |
+
meas_cols = ["meter_reading", "air_temperature", "date", "time"]
|
| 954 |
+
grouped = df.groupby("date")[meas_cols]
|
| 955 |
+
|
| 956 |
+
# ── 5. daily arrays (guaranteed identical length) ─────────────────────
|
| 957 |
+
daily, d_labels, d_seasons = [], [], []
|
| 958 |
+
for d in sorted(grouped.groups.keys()):
|
| 959 |
+
g = grouped.get_group(d).sort_values("time")
|
| 960 |
+
arr = g[meas_cols].values
|
| 961 |
+
weekend = 1 if g["time"].dt.dayofweek.iloc[0] >= 5 else 0
|
| 962 |
+
season = get_season(g["time"].iloc[0].month)
|
| 963 |
+
|
| 964 |
+
daily.append(arr)
|
| 965 |
+
d_labels.append(np.full(points_per_day, weekend, dtype=int))
|
| 966 |
+
d_seasons.append(np.full(points_per_day, season, dtype=int))
|
| 967 |
+
|
| 968 |
+
# ── 6. build consecutive 7-day blocks starting at 00:00 ───────────────
|
| 969 |
+
n_full_weeks = len(daily) // 7
|
| 970 |
+
if n_full_weeks == 0:
|
| 971 |
+
return (np.array([]),) * 5
|
| 972 |
+
|
| 973 |
+
# sigma = max(1, points_per_day // 24) # ≈ 1-hour smoothing
|
| 974 |
+
energy, temp, times, workday, season_feat = [], [], [], [], []
|
| 975 |
+
|
| 976 |
+
for w in range(n_full_weeks):
|
| 977 |
+
sl = slice(w*7, (w+1)*7)
|
| 978 |
+
week_d, w_lbl, w_sea = daily[sl], d_labels[sl], d_seasons[sl]
|
| 979 |
+
|
| 980 |
+
e = np.asarray(np.concatenate([d[:,0] for d in week_d]), dtype=float)
|
| 981 |
+
t = np.asarray(np.concatenate([d[:,1] for d in week_d]), dtype=float)
|
| 982 |
+
ts = np.concatenate([d[:,3] for d in week_d])
|
| 983 |
+
wl = np.concatenate(w_lbl)
|
| 984 |
+
sf = np.concatenate(w_sea)
|
| 985 |
+
|
| 986 |
+
energy.append(gaussian_filter1d(e, sigma=1))
|
| 987 |
+
temp.append(gaussian_filter1d(t, sigma=1))
|
| 988 |
+
times.append(ts)
|
| 989 |
+
workday.append(wl)
|
| 990 |
+
season_feat.append(sf)
|
| 991 |
+
|
| 992 |
+
# plot_data(times, energy, temp, workday, season_feat)
|
| 993 |
+
|
| 994 |
+
return (np.array(times, dtype=object),
|
| 995 |
+
np.array(energy),
|
| 996 |
+
np.array(temp),
|
| 997 |
+
np.array(workday),
|
| 998 |
+
np.array(season_feat))
|
| 999 |
+
|
| 1000 |
+
|
| 1001 |
+
|
| 1002 |
+
def get_data_solar_weather_weekly():
|
| 1003 |
+
"""
|
| 1004 |
+
Returns
|
| 1005 |
+
-------
|
| 1006 |
+
times : np.ndarray (dtype=object) shape (n_weeks,)
|
| 1007 |
+
energy : np.ndarray shape (n_weeks, points_per_day*7)
|
| 1008 |
+
temp : np.ndarray same shape
|
| 1009 |
+
workday : np.ndarray same shape, int {0,1}
|
| 1010 |
+
season_feat : np.ndarray same shape, int {0,1,2,3}
|
| 1011 |
+
"""
|
| 1012 |
+
|
| 1013 |
+
# ── 1. read & basic cleaning ─────────────────────────────────────────
|
| 1014 |
+
p_csv = Path("/Users/muhaoguo/Documents/study/Paper_Projects/PESGM/data/solar_weather.csv")
|
| 1015 |
+
df = pd.read_csv(p_csv, parse_dates=["Time"])
|
| 1016 |
+
|
| 1017 |
+
# you sampled 1000:10000 in the draft – keep that if desired
|
| 1018 |
+
# df = df.iloc[1000:10000].copy()
|
| 1019 |
+
df = df.iloc[::4].copy()
|
| 1020 |
+
|
| 1021 |
+
# keep two numeric columns & drop NaN
|
| 1022 |
+
df = df[["Time", "Energy delta[Wh]", "temp"]].rename(
|
| 1023 |
+
columns={"Energy delta[Wh]": "meter_reading",
|
| 1024 |
+
"temp": "air_temperature"})
|
| 1025 |
+
df["meter_reading"] = pd.to_numeric(df["meter_reading"], errors="coerce")
|
| 1026 |
+
df["air_temperature"] = pd.to_numeric(df["air_temperature"], errors="coerce")
|
| 1027 |
+
df.dropna(inplace=True)
|
| 1028 |
+
df.sort_values("Time", inplace=True)
|
| 1029 |
+
# print(df)
|
| 1030 |
+
|
| 1031 |
+
# ── 2. global min-max normalisation ─────────────────────────────────
|
| 1032 |
+
for c in ["meter_reading", "air_temperature"]:
|
| 1033 |
+
vmin, vmax = df[c].min(), df[c].max()
|
| 1034 |
+
df[c] = (df[c] - vmin) / (vmax - vmin)
|
| 1035 |
+
|
| 1036 |
+
# ── 3. identify full days / sample rate ─────────────────────────────
|
| 1037 |
+
df["date"] = df["Time"].dt.date
|
| 1038 |
+
day_counts = df.groupby("date").size()
|
| 1039 |
+
pts_per_day = int(day_counts.mode().iloc[0]) # modal length
|
| 1040 |
+
full_dates = day_counts[day_counts == pts_per_day].index
|
| 1041 |
+
df = df[df["date"].isin(full_dates)].copy()
|
| 1042 |
+
|
| 1043 |
+
# ── 4. helpers ──────────────────────────────────────────────────────
|
| 1044 |
+
def get_season(m): # 0=winter,1=spring,2=summer,3=autumn
|
| 1045 |
+
return {12:0,1:0,2:0,3:1,4:1,5:1,6:2,7:2,8:2,9:3,10:3,11:3}[m]
|
| 1046 |
+
|
| 1047 |
+
meas_cols = ["meter_reading", "air_temperature", "date", "Time"]
|
| 1048 |
+
grouped = df.groupby("date")[meas_cols]
|
| 1049 |
+
|
| 1050 |
+
daily, d_wd, d_sea = [], [], []
|
| 1051 |
+
for d in sorted(grouped.groups.keys()):
|
| 1052 |
+
g = grouped.get_group(d).sort_values("Time")
|
| 1053 |
+
arr = g[meas_cols].values
|
| 1054 |
+
|
| 1055 |
+
wd_flag = 1 if g["Time"].dt.dayofweek.iloc[0] >= 5 else 0
|
| 1056 |
+
season = get_season(g["Time"].iloc[0].month)
|
| 1057 |
+
|
| 1058 |
+
daily.append(arr)
|
| 1059 |
+
d_wd.append(np.full(pts_per_day, wd_flag, dtype=int))
|
| 1060 |
+
d_sea.append(np.full(pts_per_day, season, dtype=int))
|
| 1061 |
+
|
| 1062 |
+
# ── 5. consecutive 7-day blocks, starting at 00:00 ──────────────────
|
| 1063 |
+
n_full_weeks = len(daily) // 7
|
| 1064 |
+
if n_full_weeks == 0:
|
| 1065 |
+
return (np.array([]),)*5
|
| 1066 |
+
|
| 1067 |
+
sigma = max(1, pts_per_day // 24) # ≈ one-hour smoothing
|
| 1068 |
+
energy, temp, times, workday, season_feat = [], [], [], [], []
|
| 1069 |
+
|
| 1070 |
+
for w in range(n_full_weeks):
|
| 1071 |
+
sl = slice(w*7, (w+1)*7)
|
| 1072 |
+
wk_d, wk_wd, wk_sea = daily[sl], d_wd[sl], d_sea[sl]
|
| 1073 |
+
|
| 1074 |
+
e = np.asarray(np.concatenate([d[:,0] for d in wk_d]), dtype=float)
|
| 1075 |
+
t = np.asarray(np.concatenate([d[:,1] for d in wk_d]), dtype=float)
|
| 1076 |
+
ts = np.concatenate([d[:,3] for d in wk_d])
|
| 1077 |
+
wl = np.concatenate(wk_wd)
|
| 1078 |
+
sf = np.concatenate(wk_sea)
|
| 1079 |
+
|
| 1080 |
+
energy.append(gaussian_filter1d(e, sigma=sigma))
|
| 1081 |
+
temp.append(gaussian_filter1d(t, sigma=sigma))
|
| 1082 |
+
times.append(ts)
|
| 1083 |
+
workday.append(wl)
|
| 1084 |
+
season_feat.append(sf)
|
| 1085 |
+
|
| 1086 |
+
# plot_data(times, energy, temp, workday, season_feat)
|
| 1087 |
+
|
| 1088 |
+
return (np.array(times, dtype=object),
|
| 1089 |
+
np.array(energy),
|
| 1090 |
+
np.array(temp),
|
| 1091 |
+
np.array(workday),
|
| 1092 |
+
np.array(season_feat))
|
| 1093 |
+
|
| 1094 |
+
|
| 1095 |
+
if __name__ == "__main__":
|
| 1096 |
+
times, energy, temp, workday, season_feat = get_data_building_weather_weekly()
|
| 1097 |
+
print(times.shape, energy.shape, temp.shape, workday.shape, season_feat.shape)
|
| 1098 |
+
|
| 1099 |
+
times, energy, temp, workday, season_feat = get_data_spanish_weekly()
|
| 1100 |
+
print(times.shape, energy.shape, temp.shape, workday.shape, season_feat.shape)
|
| 1101 |
+
|
| 1102 |
+
times, energy, temp, workday, season_feat = get_data_power_consumption_weekly()
|
| 1103 |
+
print(times.shape, energy.shape, temp.shape, workday.shape, season_feat.shape)
|
| 1104 |
+
|
| 1105 |
+
times, energy, temp, workday, season_feat = get_data_residential_weekly()
|
| 1106 |
+
print(times.shape, energy.shape, temp.shape, workday.shape, season_feat.shape)
|
| 1107 |
+
|
| 1108 |
+
times, energy, temp, workday, season_feat = get_data_solar_weather_weekly()
|
| 1109 |
+
print(times.shape, energy.shape, temp.shape, workday.shape, season_feat.shape)
|
| 1110 |
+
|
| 1111 |
+
|
| 1112 |
+
|
| 1113 |
+
|
main_variational.py
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
from scipy.ndimage import gaussian_filter1d
|
| 4 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
from torch.utils.data import Dataset, DataLoader
|
| 8 |
+
import random
|
| 9 |
+
from data_utils import *
|
| 10 |
+
from model import *
|
| 11 |
+
import numpy as np, random, torch, torch.nn as nn
|
| 12 |
+
from torch.utils.data import DataLoader, TensorDataset
|
| 13 |
+
import matplotlib.pyplot as plt
|
| 14 |
+
import torch
|
| 15 |
+
import matplotlib.pyplot as plt
|
| 16 |
+
from torch.distributions.normal import Normal
|
| 17 |
+
import math
|
| 18 |
+
|
| 19 |
+
# ---------------------------------------------------------------------------
|
| 20 |
+
# Seed
|
| 21 |
+
# ---------------------------------------------------------------------------
|
| 22 |
+
def set_seed(seed: int = 42):
|
| 23 |
+
random.seed(seed)
|
| 24 |
+
np.random.seed(seed)
|
| 25 |
+
torch.manual_seed(seed)
|
| 26 |
+
torch.cuda.manual_seed_all(seed)
|
| 27 |
+
torch.backends.cudnn.deterministic = True
|
| 28 |
+
torch.backends.cudnn.benchmark = False
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# ---------------------------------------------------------------------------
|
| 33 |
+
# Train
|
| 34 |
+
# ---------------------------------------------------------------------------
|
| 35 |
+
def train_model(model, train_loader, epochs, lr, device, save_path="best_model.pt"):
|
| 36 |
+
loss_fn = nn.MSELoss()
|
| 37 |
+
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
|
| 38 |
+
|
| 39 |
+
best_train_loss = float("inf")
|
| 40 |
+
best_epoch = -1
|
| 41 |
+
|
| 42 |
+
for ep in range(1, epochs + 1):
|
| 43 |
+
model.train()
|
| 44 |
+
running_train_loss = 0.0
|
| 45 |
+
|
| 46 |
+
for batch in train_loader:
|
| 47 |
+
(enc_l, enc_t, enc_w, enc_s,
|
| 48 |
+
dec_l, dec_t, dec_w, dec_s,
|
| 49 |
+
tgt) = [t.to(device) for t in batch]
|
| 50 |
+
|
| 51 |
+
optimizer.zero_grad()
|
| 52 |
+
|
| 53 |
+
mu_preds, logvar_preds, mu_z, logvar_z = model(enc_l, enc_t, enc_w, enc_s,
|
| 54 |
+
dec_l, dec_t, dec_w, dec_s,
|
| 55 |
+
epoch=ep,
|
| 56 |
+
top_k=top_k, warmup_epochs=10)
|
| 57 |
+
|
| 58 |
+
nll = gaussian_nll_loss(mu_preds, logvar_preds, tgt)
|
| 59 |
+
kl = kl_loss(mu_z, logvar_z)
|
| 60 |
+
|
| 61 |
+
loss = nll + 0.01 * kl
|
| 62 |
+
|
| 63 |
+
# reconstruction_loss = nn.functional.mse_loss(preds, tgt, reduction='mean')
|
| 64 |
+
# kl_loss = -0.5 * torch.mean(1 + logvar - mu.pow(2) - logvar.exp())
|
| 65 |
+
# loss = reconstruction_loss + kl_weight * kl_loss # KL weight is tunable
|
| 66 |
+
|
| 67 |
+
loss.backward()
|
| 68 |
+
optimizer.step()
|
| 69 |
+
|
| 70 |
+
running_train_loss += loss.item() * enc_l.size(0)
|
| 71 |
+
|
| 72 |
+
avg_train_loss = running_train_loss / len(train_loader.dataset)
|
| 73 |
+
|
| 74 |
+
if avg_train_loss < best_train_loss:
|
| 75 |
+
best_train_loss = avg_train_loss
|
| 76 |
+
best_epoch = ep
|
| 77 |
+
torch.save(model.state_dict(), save_path)
|
| 78 |
+
print(f"✅ Saved best model at epoch {ep} with loss {best_train_loss:.6f}")
|
| 79 |
+
|
| 80 |
+
if ep == 1 or ep % 5 == 0 or ep == epochs:
|
| 81 |
+
print(f"Epoch {ep:3d}/{epochs} | Train MSE: {avg_train_loss:.6f} | Best MSE: {best_train_loss:.6f} (epoch {best_epoch})")
|
| 82 |
+
|
| 83 |
+
print(f"\n🏁 Training completed. Best model saved from epoch {best_epoch} with MSE: {best_train_loss:.6f}")
|
| 84 |
+
return model
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def crps_gaussian(mu, logvar, target):
|
| 89 |
+
"""
|
| 90 |
+
Compute CRPS for Gaussian predictive distribution.
|
| 91 |
+
Args:
|
| 92 |
+
mu: [B, T] predicted mean
|
| 93 |
+
logvar: [B, T] predicted log-variance
|
| 94 |
+
target: [B, T] true target values
|
| 95 |
+
Returns:
|
| 96 |
+
crps: scalar (mean CRPS over all points)
|
| 97 |
+
"""
|
| 98 |
+
std = (0.5 * logvar).exp() # [B, T]
|
| 99 |
+
z = (target - mu) / std # [B, T]
|
| 100 |
+
|
| 101 |
+
normal = Normal(torch.zeros_like(z), torch.ones_like(z))
|
| 102 |
+
phi = torch.exp(normal.log_prob(z)) # PDF φ(z)
|
| 103 |
+
Phi = normal.cdf(z) # CDF Φ(z)
|
| 104 |
+
|
| 105 |
+
crps = std * (z * (2 * Phi - 1) + 2 * phi - 1 / math.sqrt(math.pi))
|
| 106 |
+
return crps.mean()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@torch.no_grad()
|
| 110 |
+
def evaluate_model(model, test_loader, loss_fn, device,
|
| 111 |
+
model_path="model.pt", reduce="first", visualize=True):
|
| 112 |
+
print("Loading model from:", model_path)
|
| 113 |
+
model.load_state_dict(torch.load(model_path, map_location=device))
|
| 114 |
+
model.to(device)
|
| 115 |
+
model.eval()
|
| 116 |
+
|
| 117 |
+
all_preds = []
|
| 118 |
+
all_targets = []
|
| 119 |
+
running_mse = 0.0
|
| 120 |
+
running_nll = 0.0
|
| 121 |
+
running_crps = 0.0
|
| 122 |
+
|
| 123 |
+
for batch in test_loader:
|
| 124 |
+
(enc_l, enc_t, enc_w, enc_s,
|
| 125 |
+
dec_l, dec_t, dec_w, dec_s,
|
| 126 |
+
tgt) = [t.to(device) for t in batch]
|
| 127 |
+
|
| 128 |
+
B = enc_l.size(0)
|
| 129 |
+
|
| 130 |
+
mu_preds, logvar_preds, _, _ = model(enc_l, enc_t, enc_w, enc_s,
|
| 131 |
+
dec_l, dec_t, dec_w, dec_s)
|
| 132 |
+
mu_preds = mu_preds.squeeze(-1) # [B, L+1, output_len]
|
| 133 |
+
logvar_preds = logvar_preds.squeeze(-1) # [B, L+1, output_len]
|
| 134 |
+
tgt = tgt.squeeze(-1) # [B, L+1, output_len]
|
| 135 |
+
|
| 136 |
+
if reduce == "mean":
|
| 137 |
+
for b in range(B):
|
| 138 |
+
pred_avg = reconstruct_sequence(mu_preds[b]) # [L+output_len]
|
| 139 |
+
tgt_avg = reconstruct_sequence(tgt[b])
|
| 140 |
+
all_preds.append(pred_avg.cpu())
|
| 141 |
+
all_targets.append(tgt_avg.cpu())
|
| 142 |
+
running_mse += loss_fn(pred_avg, tgt_avg).item()
|
| 143 |
+
|
| 144 |
+
elif reduce == "first":
|
| 145 |
+
mu_first = mu_preds[:, :, 0] # [B, L+1]
|
| 146 |
+
logvar_first = logvar_preds[:, :, 0] # [B, L+1]
|
| 147 |
+
tgt_first = tgt[:, :, 0] # [B, L+1]
|
| 148 |
+
|
| 149 |
+
all_preds.extend(mu_first.cpu())
|
| 150 |
+
all_targets.extend(tgt_first.cpu())
|
| 151 |
+
running_mse += loss_fn(mu_first, tgt_first).item() * B
|
| 152 |
+
|
| 153 |
+
# NLL
|
| 154 |
+
nll = 0.5 * (
|
| 155 |
+
logvar_first +
|
| 156 |
+
torch.log(torch.tensor(2 * np.pi, device=logvar_first.device)) +
|
| 157 |
+
(tgt_first - mu_first) ** 2 / logvar_first.exp()
|
| 158 |
+
) # [B, L+1]
|
| 159 |
+
running_nll += nll.sum().item()
|
| 160 |
+
|
| 161 |
+
# CRPS
|
| 162 |
+
crps = crps_gaussian(mu_first, logvar_first, tgt_first)
|
| 163 |
+
running_crps += crps.item() * B
|
| 164 |
+
|
| 165 |
+
# Visualization
|
| 166 |
+
if visualize:
|
| 167 |
+
for i in range(min(5, mu_first.size(0))):
|
| 168 |
+
std_pred = logvar_first[i].exp().sqrt().cpu()
|
| 169 |
+
plt.figure(figsize=(4, 2))
|
| 170 |
+
plt.plot(tgt_first[i].cpu(), label='True', linestyle='--', color='red')
|
| 171 |
+
plt.plot(mu_first[i].cpu(), label='Mean Predicted', alpha=0.6, color='blue',)
|
| 172 |
+
plt.fill_between(np.arange(mu_first.size(1)),
|
| 173 |
+
mu_first[i].cpu() - std_pred,
|
| 174 |
+
mu_first[i].cpu() + std_pred,
|
| 175 |
+
color='blue', alpha=0.1, label='±1 Std Predicted')
|
| 176 |
+
# plt.title(f"Prediction + Uncertainty (Sample {i})")
|
| 177 |
+
# plt.legend()
|
| 178 |
+
plt.ylim(0, 1)
|
| 179 |
+
plt.yticks([0, 0.5, 1], fontsize=14)
|
| 180 |
+
plt.xticks(fontsize=14)
|
| 181 |
+
plt.tight_layout()
|
| 182 |
+
plt.savefig(f"./result/{data_name}_{model_name}_sample_{i}.pdf")
|
| 183 |
+
|
| 184 |
+
# handles, labels = plt.gca().get_legend_handles_labels()
|
| 185 |
+
# plt.legend(handles, labels,
|
| 186 |
+
# ncol=len(labels), # one long row
|
| 187 |
+
# loc='upper center', # put it where you like
|
| 188 |
+
# bbox_to_anchor=(0.5, 1.05),# and nudge it above the axes
|
| 189 |
+
# framealpha=1,
|
| 190 |
+
# fontsize= 14
|
| 191 |
+
# )
|
| 192 |
+
plt.show()
|
| 193 |
+
|
| 194 |
+
# Global visualization
|
| 195 |
+
plt.figure(figsize=(12, 6))
|
| 196 |
+
for i in range(mu_first.size(0)):
|
| 197 |
+
std_pred = logvar_first[i].exp().sqrt().cpu()
|
| 198 |
+
plt.plot(tgt_first[i].cpu(), color='gray', linestyle='--', linewidth=0.8, alpha=0.5)
|
| 199 |
+
plt.plot(mu_first[i].cpu(), linewidth=2.0, label='Mean Pred' if i == 0 else None)
|
| 200 |
+
plt.fill_between(np.arange(mu_first.size(1)),
|
| 201 |
+
mu_first[i].cpu() - std_pred,
|
| 202 |
+
mu_first[i].cpu() + std_pred,
|
| 203 |
+
alpha=0.2, color='red')
|
| 204 |
+
plt.title("All Forecasts: Mean + Predicted Variance")
|
| 205 |
+
plt.xlabel("Time step")
|
| 206 |
+
plt.ylabel("Forecasted value")
|
| 207 |
+
plt.legend(loc='upper right')
|
| 208 |
+
plt.tight_layout()
|
| 209 |
+
visualize = False
|
| 210 |
+
# plt.show()
|
| 211 |
+
else:
|
| 212 |
+
raise ValueError("reduce must be 'mean' or 'first'")
|
| 213 |
+
|
| 214 |
+
test_mse = running_mse / len(test_loader.dataset)
|
| 215 |
+
test_nll = running_nll / (len(test_loader.dataset) * mu_first.size(1)) if reduce == "first" else None
|
| 216 |
+
test_crps = running_crps / len(test_loader.dataset) if reduce == "first" else None
|
| 217 |
+
|
| 218 |
+
print(f"🧪 Test MSE: {test_mse:.6f}")
|
| 219 |
+
# print(f"🧪 Test NLL : {test_nll:.6f}")
|
| 220 |
+
print(f"🧪 Test CRPS: {test_crps:.6f}")
|
| 221 |
+
|
| 222 |
+
return test_mse, test_nll, test_crps
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
# ---------------------------------------------------------------------------
|
| 226 |
+
# Main script
|
| 227 |
+
# ---------------------------------------------------------------------------
|
| 228 |
+
if __name__ == "__main__":
|
| 229 |
+
seed = 42
|
| 230 |
+
set_seed(seed)
|
| 231 |
+
batch_size = 16
|
| 232 |
+
epochs = 300
|
| 233 |
+
lr = 1e-3
|
| 234 |
+
kl_weight = 0.01
|
| 235 |
+
xprime_dim = 40
|
| 236 |
+
hidden_dim = 64
|
| 237 |
+
latent_dim = 32
|
| 238 |
+
num_layers = 4
|
| 239 |
+
output_len = 3 # make sure this matches process_seq2seq_data
|
| 240 |
+
num_experts = 3 # temp, workday, season
|
| 241 |
+
top_k = 2
|
| 242 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 243 |
+
|
| 244 |
+
data_name = "Solar" # Spanish Consumption Residential Solar
|
| 245 |
+
model_name = "M2OE2"
|
| 246 |
+
model_path = f"{data_name}_{model_name}_best_model.pt"
|
| 247 |
+
print(f"Using device: {device}")
|
| 248 |
+
|
| 249 |
+
# (A) Load & prepare data ------------------------------------------------
|
| 250 |
+
if data_name == "Building":
|
| 251 |
+
times, load, temp, workday, season = get_data_building_weather_weekly()
|
| 252 |
+
elif data_name == "Spanish":
|
| 253 |
+
times, load, temp, workday, season = get_data_spanish_weekly()
|
| 254 |
+
elif data_name == "Consumption":
|
| 255 |
+
times, load, temp, workday, season = get_data_power_consumption_weekly()
|
| 256 |
+
elif data_name == "Residential":
|
| 257 |
+
times, load, temp, workday, season = get_data_residential_weekly()
|
| 258 |
+
elif data_name == "Solar":
|
| 259 |
+
times, load, temp, workday, season= get_data_solar_weather_weekly()
|
| 260 |
+
|
| 261 |
+
input_dim = 1
|
| 262 |
+
output_dim = 1 # predict one-dimensional load
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
feature_dict = dict(load = load,
|
| 266 |
+
temp = temp,
|
| 267 |
+
workday = workday,
|
| 268 |
+
season = season)
|
| 269 |
+
|
| 270 |
+
train_data, test_data, _ = process_seq2seq_data(
|
| 271 |
+
feature_dict = feature_dict,
|
| 272 |
+
train_ratio = 0.7,
|
| 273 |
+
output_len = output_len,
|
| 274 |
+
device = device)
|
| 275 |
+
|
| 276 |
+
train_loader = make_loader(train_data, batch_size, shuffle=True)
|
| 277 |
+
test_loader = make_loader(test_data, batch_size, shuffle=False)
|
| 278 |
+
|
| 279 |
+
model = VariationalSeq2Seq_meta(
|
| 280 |
+
xprime_dim=xprime_dim,
|
| 281 |
+
input_dim=input_dim,
|
| 282 |
+
hidden_size=hidden_dim,
|
| 283 |
+
latent_size=latent_dim,
|
| 284 |
+
output_len=output_len,
|
| 285 |
+
output_dim=output_dim,
|
| 286 |
+
num_layers=num_layers,
|
| 287 |
+
dropout=0.1,
|
| 288 |
+
num_experts=num_experts
|
| 289 |
+
).to(device)
|
| 290 |
+
|
| 291 |
+
import os
|
| 292 |
+
if not os.path.isfile(model_path):
|
| 293 |
+
print(f"[x] Not Found '{model_path}', training.")
|
| 294 |
+
train_model(model, train_loader, epochs=epochs, lr=lr, device=device, save_path=model_path)
|
| 295 |
+
|
| 296 |
+
# Re-initialize the model with same architecture
|
| 297 |
+
model = VariationalSeq2Seq_meta(
|
| 298 |
+
xprime_dim=xprime_dim,
|
| 299 |
+
input_dim=input_dim,
|
| 300 |
+
hidden_size=hidden_dim,
|
| 301 |
+
latent_size=latent_dim,
|
| 302 |
+
output_len=output_len,
|
| 303 |
+
output_dim=output_dim,
|
| 304 |
+
num_layers=num_layers,
|
| 305 |
+
dropout=0.1,
|
| 306 |
+
num_experts=num_experts
|
| 307 |
+
).to(device)
|
| 308 |
+
|
| 309 |
+
# Then evaluate
|
| 310 |
+
evaluate_model(model, test_loader, nn.MSELoss(), device, model_path=model_path)
|
model.py
ADDED
|
@@ -0,0 +1,514 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
# ---------------- Meta Components ----------------
|
| 6 |
+
class MetaNet(nn.Module):
|
| 7 |
+
def __init__(self, input_dim, xprime_dim):
|
| 8 |
+
super().__init__()
|
| 9 |
+
self.layer1 = nn.Linear(1, input_dim * xprime_dim)
|
| 10 |
+
self.layer2 = nn.Linear(input_dim * xprime_dim, input_dim * xprime_dim)
|
| 11 |
+
self.input_dim = input_dim
|
| 12 |
+
self.xprime_dim = xprime_dim
|
| 13 |
+
|
| 14 |
+
def forward(self, x_feat): # x_feat: [B, 1]
|
| 15 |
+
B = x_feat.size(0)
|
| 16 |
+
out = torch.tanh(self.layer1(x_feat)) # [B, 32]
|
| 17 |
+
out = torch.tanh(self.layer2(out)) # [B, input_dim * xprime_dim]
|
| 18 |
+
return out.view(B, self.input_dim, self.xprime_dim) # [B, input_dim, xprime_dim]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class GatingNet(nn.Module):
|
| 23 |
+
def __init__(self, hidden_size, num_experts=3):
|
| 24 |
+
super().__init__()
|
| 25 |
+
self.layer1 = nn.Linear(hidden_size, hidden_size)
|
| 26 |
+
self.layer2 = nn.Linear(hidden_size, num_experts)
|
| 27 |
+
|
| 28 |
+
def forward(self, h, epoch=None, top_k=None, warmup_epochs=0):
|
| 29 |
+
logits = self.layer2(torch.tanh(self.layer1(h))) # [B, num_experts]
|
| 30 |
+
|
| 31 |
+
if (epoch is None) or (top_k is None) or (epoch < warmup_epochs):
|
| 32 |
+
return torch.softmax(logits, dim=-1)
|
| 33 |
+
|
| 34 |
+
topk_vals, topk_idx = torch.topk(logits, k=top_k, dim=-1)
|
| 35 |
+
mask = torch.zeros_like(logits).scatter(1, topk_idx, 1.0)
|
| 36 |
+
masked_logits = logits.masked_fill(mask == 0, float('-inf'))
|
| 37 |
+
return torch.softmax(masked_logits, dim=-1)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class MetaTransformBlock(nn.Module):
|
| 41 |
+
def __init__(self, xprime_dim, num_experts=3, input_dim=1, hidden_size=64):
|
| 42 |
+
super().__init__()
|
| 43 |
+
self.meta_temp = MetaNet(input_dim, xprime_dim)
|
| 44 |
+
self.meta_work = MetaNet(input_dim, xprime_dim)
|
| 45 |
+
self.meta_season = MetaNet(input_dim, xprime_dim)
|
| 46 |
+
self.gating = GatingNet(hidden_size, num_experts) # Use hidden_size here
|
| 47 |
+
self.ln = nn.LayerNorm([input_dim, xprime_dim])
|
| 48 |
+
self.theta0 = nn.Parameter(torch.zeros(1, input_dim, xprime_dim))
|
| 49 |
+
|
| 50 |
+
def forward(self, h_prev_rnn, x_l, x_t, x_w, x_s, epoch=None, top_k=None, warmup_epochs=0):
|
| 51 |
+
w_temp = self.ln(self.meta_temp(x_t)) # [B, input_dim, xprime_dim]
|
| 52 |
+
w_work = self.ln(self.meta_work(x_w)) # [B, input_dim, xprime_dim]
|
| 53 |
+
w_seas = self.ln(self.meta_season(x_s)) # [B, input_dim, xprime_dim]
|
| 54 |
+
|
| 55 |
+
gates = self.gating(h_prev_rnn, epoch=epoch, top_k=top_k, warmup_epochs=warmup_epochs) # [B, num_experts]
|
| 56 |
+
W_experts = torch.stack([w_temp, w_work, w_seas], dim=1) # [B, num_experts, input_dim, xprime_dim]
|
| 57 |
+
gates_expanded = gates.view(gates.size(0), gates.size(1), 1, 1) # [B, num_experts, 1, 1]
|
| 58 |
+
theta_dynamic = (W_experts * gates_expanded).sum(dim=1) # [B, input_dim, xprime_dim]
|
| 59 |
+
theta = theta_dynamic + self.theta0 # [B, input_dim, xprime_dim]
|
| 60 |
+
|
| 61 |
+
x_prime = torch.bmm(x_l.unsqueeze(1), theta).squeeze(1) # [B, xprime_dim]
|
| 62 |
+
return x_prime, theta
|
| 63 |
+
|
| 64 |
+
# ---------------- Encoder ----------------
|
| 65 |
+
class Encoder_meta(nn.Module):
|
| 66 |
+
def __init__(self, xprime_dim, hidden_size, num_layers=1, dropout=0.1):
|
| 67 |
+
super().__init__()
|
| 68 |
+
self.hidden_size = hidden_size
|
| 69 |
+
self.num_layers = num_layers
|
| 70 |
+
self.rnn = nn.GRU(xprime_dim, hidden_size, num_layers,
|
| 71 |
+
batch_first=True,
|
| 72 |
+
dropout=dropout if num_layers > 1 else 0)
|
| 73 |
+
|
| 74 |
+
def forward(self, x_l_seq, x_t_seq, x_w_seq, x_s_seq,
|
| 75 |
+
transform_block, h_init=None, epoch=None, top_k=None, warmup_epochs=0):
|
| 76 |
+
B, T, _ = x_l_seq.shape
|
| 77 |
+
h_rnn = torch.zeros(self.num_layers, B, self.hidden_size, device=x_l_seq.device) if h_init is None else h_init
|
| 78 |
+
|
| 79 |
+
for t in range(T):
|
| 80 |
+
h_for_meta = h_rnn[-1]
|
| 81 |
+
x_prime, _ = transform_block(h_for_meta,
|
| 82 |
+
x_l_seq[:, t], x_t_seq[:, t],
|
| 83 |
+
x_w_seq[:, t], x_s_seq[:, t],
|
| 84 |
+
epoch=epoch, top_k=top_k, warmup_epochs=warmup_epochs)
|
| 85 |
+
x_prime = x_prime.unsqueeze(1)
|
| 86 |
+
_, h_rnn = self.rnn(x_prime, h_rnn)
|
| 87 |
+
|
| 88 |
+
return h_rnn # [num_layers, B, hidden_size]
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# ---------------- Decoder ----------------
|
| 92 |
+
class Decoder_meta(nn.Module):
|
| 93 |
+
def __init__(self, xprime_dim, latent_size, output_len, output_dim=1,
|
| 94 |
+
num_layers=1, dropout=0.1, hidden_size=None):
|
| 95 |
+
super().__init__()
|
| 96 |
+
self.latent_size = latent_size
|
| 97 |
+
self.output_len = output_len
|
| 98 |
+
self.output_dim = output_dim
|
| 99 |
+
self.num_layers = num_layers
|
| 100 |
+
|
| 101 |
+
self.rnn = nn.GRU(xprime_dim, latent_size, num_layers,
|
| 102 |
+
batch_first=True,
|
| 103 |
+
dropout=dropout if num_layers > 1 else 0)
|
| 104 |
+
|
| 105 |
+
self.head = nn.Linear(latent_size, output_len * output_dim)
|
| 106 |
+
|
| 107 |
+
# Layer-wise projection from encoder hidden_size → decoder latent_size
|
| 108 |
+
assert hidden_size is not None, "You must provide hidden_size for projection."
|
| 109 |
+
self.project = nn.ModuleList([
|
| 110 |
+
nn.Linear(hidden_size, latent_size) for _ in range(num_layers)
|
| 111 |
+
])
|
| 112 |
+
|
| 113 |
+
def forward(self, x_l_seq, x_t_seq, x_w_seq, x_s_seq,
|
| 114 |
+
h_init, transform_block,
|
| 115 |
+
epoch=None, top_k=None, warmup_epochs=0):
|
| 116 |
+
B, L, _ = x_l_seq.shape
|
| 117 |
+
|
| 118 |
+
# Project each layer of encoder hidden state to latent size
|
| 119 |
+
h_rnn = torch.stack([
|
| 120 |
+
self.project[i](h_init[i]) for i in range(self.num_layers)
|
| 121 |
+
], dim=0) # [num_layers, B, latent_size]
|
| 122 |
+
|
| 123 |
+
preds = []
|
| 124 |
+
|
| 125 |
+
# Step 0
|
| 126 |
+
h_last = h_rnn[-1] # [B, latent_size]
|
| 127 |
+
pred_0 = self.head(h_last).view(B, self.output_len, self.output_dim)
|
| 128 |
+
preds.append(pred_0.unsqueeze(1)) # [B, 1, output_len, output_dim]
|
| 129 |
+
|
| 130 |
+
# Steps 1 to L
|
| 131 |
+
for t in range(L):
|
| 132 |
+
h_for_meta = h_rnn[-1]
|
| 133 |
+
x_prime, _ = transform_block(h_for_meta,
|
| 134 |
+
x_l_seq[:, t], x_t_seq[:, t],
|
| 135 |
+
x_w_seq[:, t], x_s_seq[:, t],
|
| 136 |
+
epoch=epoch, top_k=top_k, warmup_epochs=warmup_epochs)
|
| 137 |
+
x_prime = x_prime.unsqueeze(1)
|
| 138 |
+
out_t, h_rnn = self.rnn(x_prime, h_rnn)
|
| 139 |
+
pred_t = self.head(out_t.squeeze(1)).view(B, self.output_len, self.output_dim)
|
| 140 |
+
preds.append(pred_t.unsqueeze(1))
|
| 141 |
+
|
| 142 |
+
preds = torch.cat(preds, dim=1) # [B, L+1, output_len, output_dim]
|
| 143 |
+
return preds
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
# ---------------- Full Seq2Seq Model ----------------
|
| 147 |
+
class Seq2Seq_meta(nn.Module):
|
| 148 |
+
def __init__(self, xprime_dim, input_dim, hidden_size, latent_size,
|
| 149 |
+
output_len, output_dim=1, num_layers=1, dropout=0.1, num_experts=3):
|
| 150 |
+
super().__init__()
|
| 151 |
+
|
| 152 |
+
self.transform_enc = MetaTransformBlock(
|
| 153 |
+
xprime_dim=xprime_dim,
|
| 154 |
+
num_experts=num_experts,
|
| 155 |
+
input_dim=input_dim,
|
| 156 |
+
hidden_size=hidden_size # encoder hidden_size
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
self.transform_dec = MetaTransformBlock(
|
| 160 |
+
xprime_dim=xprime_dim,
|
| 161 |
+
num_experts=num_experts,
|
| 162 |
+
input_dim=input_dim,
|
| 163 |
+
hidden_size=latent_size # decoder latent_size
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
self.encoder = Encoder_meta(
|
| 167 |
+
xprime_dim=xprime_dim,
|
| 168 |
+
hidden_size=hidden_size,
|
| 169 |
+
num_layers=num_layers,
|
| 170 |
+
dropout=dropout)
|
| 171 |
+
|
| 172 |
+
self.decoder = Decoder_meta(
|
| 173 |
+
xprime_dim=xprime_dim,
|
| 174 |
+
latent_size=latent_size,
|
| 175 |
+
output_len=output_len,
|
| 176 |
+
output_dim=output_dim,
|
| 177 |
+
num_layers=num_layers,
|
| 178 |
+
dropout=dropout,
|
| 179 |
+
hidden_size=hidden_size # for projection from encoder hidden
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
def forward(self,
|
| 183 |
+
enc_l, enc_t, enc_w, enc_s,
|
| 184 |
+
dec_l, dec_t, dec_w, dec_s,
|
| 185 |
+
epoch=None, top_k=None, warmup_epochs=0):
|
| 186 |
+
|
| 187 |
+
h_enc = self.encoder(enc_l, enc_t, enc_w, enc_s,
|
| 188 |
+
transform_block=self.transform_enc,
|
| 189 |
+
epoch=epoch, top_k=top_k, warmup_epochs=warmup_epochs)
|
| 190 |
+
|
| 191 |
+
preds = self.decoder(dec_l, dec_t, dec_w, dec_s,
|
| 192 |
+
h_init=h_enc,
|
| 193 |
+
transform_block=self.transform_dec,
|
| 194 |
+
epoch=epoch, top_k=top_k, warmup_epochs=warmup_epochs)
|
| 195 |
+
return preds
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
# ---------------- Encoder ----------------
|
| 200 |
+
class VariationalEncoder_meta(nn.Module):
|
| 201 |
+
def __init__(self, xprime_dim, hidden_size, latent_size, num_layers=1, dropout=0.1):
|
| 202 |
+
super().__init__()
|
| 203 |
+
self.hidden_size = hidden_size
|
| 204 |
+
self.latent_size = latent_size
|
| 205 |
+
self.num_layers = num_layers
|
| 206 |
+
|
| 207 |
+
self.rnn = nn.GRU(xprime_dim, hidden_size, num_layers,
|
| 208 |
+
batch_first=True,
|
| 209 |
+
dropout=dropout if num_layers > 1 else 0)
|
| 210 |
+
|
| 211 |
+
self.mu_layer = nn.Linear(hidden_size, latent_size)
|
| 212 |
+
self.logvar_layer = nn.Linear(hidden_size, latent_size)
|
| 213 |
+
|
| 214 |
+
def forward(self, x_l_seq, x_t_seq, x_w_seq, x_s_seq,
|
| 215 |
+
transform_block, h_init=None, epoch=None, top_k=None, warmup_epochs=0):
|
| 216 |
+
|
| 217 |
+
B, T, _ = x_l_seq.shape
|
| 218 |
+
h_rnn = torch.zeros(self.num_layers, B, self.hidden_size, device=x_l_seq.device) if h_init is None else h_init
|
| 219 |
+
|
| 220 |
+
for t in range(T):
|
| 221 |
+
h_for_meta = h_rnn[-1]
|
| 222 |
+
x_prime, _ = transform_block(h_for_meta,
|
| 223 |
+
x_l_seq[:, t], x_t_seq[:, t],
|
| 224 |
+
x_w_seq[:, t], x_s_seq[:, t],
|
| 225 |
+
epoch=epoch, top_k=top_k, warmup_epochs=warmup_epochs)
|
| 226 |
+
x_prime = x_prime.unsqueeze(1)
|
| 227 |
+
_, h_rnn = self.rnn(x_prime, h_rnn)
|
| 228 |
+
|
| 229 |
+
h_last = h_rnn[-1] # [B, hidden_size]
|
| 230 |
+
mu = self.mu_layer(h_last)
|
| 231 |
+
logvar = self.logvar_layer(h_last)
|
| 232 |
+
|
| 233 |
+
return mu, logvar
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
class VariationalDecoder_meta_predvar(nn.Module):
|
| 238 |
+
def __init__(self, xprime_dim, latent_size, output_len, output_dim=1,
|
| 239 |
+
num_layers=1, dropout=0.1):
|
| 240 |
+
super().__init__()
|
| 241 |
+
self.latent_size = latent_size
|
| 242 |
+
self.output_len = output_len
|
| 243 |
+
self.output_dim = output_dim
|
| 244 |
+
self.num_layers = num_layers
|
| 245 |
+
|
| 246 |
+
self.rnn = nn.GRU(xprime_dim, latent_size, num_layers,
|
| 247 |
+
batch_first=True,
|
| 248 |
+
dropout=dropout if num_layers > 1 else 0)
|
| 249 |
+
|
| 250 |
+
# Separate heads for mean and log-variance
|
| 251 |
+
self.head_mu = nn.Linear(latent_size, output_len * output_dim)
|
| 252 |
+
self.head_logvar = nn.Linear(latent_size, output_len * output_dim)
|
| 253 |
+
|
| 254 |
+
def forward(self, x_l_seq, x_t_seq, x_w_seq, x_s_seq,
|
| 255 |
+
z_latent, transform_block,
|
| 256 |
+
epoch=None, top_k=None, warmup_epochs=0):
|
| 257 |
+
B, L, _ = x_l_seq.shape
|
| 258 |
+
|
| 259 |
+
h_rnn = z_latent.unsqueeze(0).repeat(self.num_layers, 1, 1) # [num_layers, B, latent_size]
|
| 260 |
+
|
| 261 |
+
mu_preds = []
|
| 262 |
+
logvar_preds = []
|
| 263 |
+
|
| 264 |
+
# Step 0
|
| 265 |
+
h_last = h_rnn[-1]
|
| 266 |
+
mu_0 = self.head_mu(h_last).view(B, self.output_len, self.output_dim)
|
| 267 |
+
logvar_0 = self.head_logvar(h_last).view(B, self.output_len, self.output_dim)
|
| 268 |
+
mu_preds.append(mu_0.unsqueeze(1)) # [B, 1, output_len, output_dim]
|
| 269 |
+
logvar_preds.append(logvar_0.unsqueeze(1)) # same shape
|
| 270 |
+
|
| 271 |
+
# Steps 1 to L
|
| 272 |
+
for t in range(L):
|
| 273 |
+
h_for_meta = h_rnn[-1]
|
| 274 |
+
x_prime, _ = transform_block(h_for_meta,
|
| 275 |
+
x_l_seq[:, t], x_t_seq[:, t],
|
| 276 |
+
x_w_seq[:, t], x_s_seq[:, t],
|
| 277 |
+
epoch=epoch, top_k=top_k, warmup_epochs=warmup_epochs)
|
| 278 |
+
x_prime = x_prime.unsqueeze(1)
|
| 279 |
+
out_t, h_rnn = self.rnn(x_prime, h_rnn)
|
| 280 |
+
|
| 281 |
+
mu_t = self.head_mu(out_t.squeeze(1)).view(B, self.output_len, self.output_dim)
|
| 282 |
+
logvar_t = self.head_logvar(out_t.squeeze(1)).view(B, self.output_len, self.output_dim)
|
| 283 |
+
|
| 284 |
+
mu_preds.append(mu_t.unsqueeze(1))
|
| 285 |
+
logvar_preds.append(logvar_t.unsqueeze(1))
|
| 286 |
+
|
| 287 |
+
# Stack across time
|
| 288 |
+
mu_preds = torch.cat(mu_preds, dim=1) # [B, L+1, output_len, output_dim]
|
| 289 |
+
logvar_preds = torch.cat(logvar_preds, dim=1) # same shape
|
| 290 |
+
|
| 291 |
+
return mu_preds, logvar_preds
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
# ---------------- Full Seq2Seq Model ----------------
|
| 295 |
+
class VariationalSeq2Seq_meta(nn.Module):
|
| 296 |
+
def __init__(self, xprime_dim, input_dim, hidden_size, latent_size,
|
| 297 |
+
output_len, output_dim=1, num_layers=1, dropout=0.1, num_experts=3):
|
| 298 |
+
super().__init__()
|
| 299 |
+
|
| 300 |
+
self.transform_enc = MetaTransformBlock(
|
| 301 |
+
xprime_dim=xprime_dim,
|
| 302 |
+
num_experts=num_experts,
|
| 303 |
+
input_dim=input_dim,
|
| 304 |
+
hidden_size=hidden_size # encoder hidden size
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
self.transform_dec = MetaTransformBlock(
|
| 308 |
+
xprime_dim=xprime_dim,
|
| 309 |
+
num_experts=num_experts,
|
| 310 |
+
input_dim=input_dim,
|
| 311 |
+
hidden_size=latent_size # decoder latent size
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
self.encoder = VariationalEncoder_meta(
|
| 315 |
+
xprime_dim=xprime_dim,
|
| 316 |
+
hidden_size=hidden_size,
|
| 317 |
+
latent_size=latent_size,
|
| 318 |
+
num_layers=num_layers,
|
| 319 |
+
dropout=dropout
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
# self.decoder = VariationalDecoder_meta_fixvar(
|
| 323 |
+
# xprime_dim=xprime_dim,
|
| 324 |
+
# latent_size=latent_size,
|
| 325 |
+
# output_len=output_len,
|
| 326 |
+
# output_dim=output_dim,
|
| 327 |
+
# num_layers=num_layers,
|
| 328 |
+
# dropout=dropout
|
| 329 |
+
# )
|
| 330 |
+
|
| 331 |
+
self.decoder = VariationalDecoder_meta_predvar(
|
| 332 |
+
xprime_dim=xprime_dim,
|
| 333 |
+
latent_size=latent_size,
|
| 334 |
+
output_len=output_len,
|
| 335 |
+
output_dim=output_dim,
|
| 336 |
+
num_layers=num_layers,
|
| 337 |
+
dropout=dropout
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
def reparameterize(self, mu, logvar):
|
| 341 |
+
std = torch.exp(0.5 * logvar)
|
| 342 |
+
eps = torch.randn_like(std)
|
| 343 |
+
return mu + eps * std
|
| 344 |
+
|
| 345 |
+
def forward(self,
|
| 346 |
+
enc_l, enc_t, enc_w, enc_s,
|
| 347 |
+
dec_l, dec_t, dec_w, dec_s,
|
| 348 |
+
epoch=None, top_k=None, warmup_epochs=0):
|
| 349 |
+
|
| 350 |
+
mu, logvar = self.encoder(enc_l, enc_t, enc_w, enc_s,
|
| 351 |
+
transform_block=self.transform_enc,
|
| 352 |
+
epoch=epoch, top_k=top_k, warmup_epochs=warmup_epochs)
|
| 353 |
+
|
| 354 |
+
z = self.reparameterize(mu, logvar) # [B, latent_size]
|
| 355 |
+
|
| 356 |
+
mu_preds, logvar_preds = self.decoder(dec_l, dec_t, dec_w, dec_s,
|
| 357 |
+
z_latent=z,
|
| 358 |
+
transform_block=self.transform_dec,
|
| 359 |
+
epoch=epoch, top_k=top_k, warmup_epochs=warmup_epochs)
|
| 360 |
+
|
| 361 |
+
return mu_preds, logvar_preds, mu, logvar
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
# # ---------------- Decoder v1: fixed variance ----------------
|
| 369 |
+
# class VariationalDecoder_meta_fixvar(nn.Module):
|
| 370 |
+
# def __init__(self, xprime_dim, latent_size, output_len, output_dim=1,
|
| 371 |
+
# num_layers=1, dropout=0.1, fixed_var_value=0.01):
|
| 372 |
+
# super().__init__()
|
| 373 |
+
# self.latent_size = latent_size
|
| 374 |
+
# self.output_len = output_len
|
| 375 |
+
# self.output_dim = output_dim
|
| 376 |
+
# self.num_layers = num_layers
|
| 377 |
+
#
|
| 378 |
+
# self.rnn = nn.GRU(xprime_dim, latent_size, num_layers,
|
| 379 |
+
# batch_first=True,
|
| 380 |
+
# dropout=dropout if num_layers > 1 else 0)
|
| 381 |
+
#
|
| 382 |
+
# self.head = nn.Linear(latent_size, output_len * output_dim)
|
| 383 |
+
#
|
| 384 |
+
# # Fixed log-variance (scalar)
|
| 385 |
+
# self.fixed_logvar = torch.tensor(np.log(fixed_var_value), dtype=torch.float32)
|
| 386 |
+
#
|
| 387 |
+
# def forward(self, x_l_seq, x_t_seq, x_w_seq, x_s_seq,
|
| 388 |
+
# z_latent, transform_block,
|
| 389 |
+
# epoch=None, top_k=None, warmup_epochs=0):
|
| 390 |
+
# B, L, _ = x_l_seq.shape
|
| 391 |
+
#
|
| 392 |
+
# h_rnn = z_latent.unsqueeze(0).repeat(self.num_layers, 1, 1) # [num_layers, B, latent_size]
|
| 393 |
+
#
|
| 394 |
+
# mu_preds = []
|
| 395 |
+
#
|
| 396 |
+
# # Step 0
|
| 397 |
+
# h_last = h_rnn[-1]
|
| 398 |
+
# mu_0 = self.head(h_last).view(B, self.output_len, self.output_dim)
|
| 399 |
+
# mu_preds.append(mu_0.unsqueeze(1)) # [B, 1, output_len, output_dim]
|
| 400 |
+
#
|
| 401 |
+
# # Steps 1 to L
|
| 402 |
+
# for t in range(L):
|
| 403 |
+
# h_for_meta = h_rnn[-1]
|
| 404 |
+
# x_prime, _ = transform_block(h_for_meta,
|
| 405 |
+
# x_l_seq[:, t], x_t_seq[:, t],
|
| 406 |
+
# x_w_seq[:, t], x_s_seq[:, t],
|
| 407 |
+
# epoch=epoch, top_k=top_k, warmup_epochs=warmup_epochs)
|
| 408 |
+
# x_prime = x_prime.unsqueeze(1)
|
| 409 |
+
# out_t, h_rnn = self.rnn(x_prime, h_rnn)
|
| 410 |
+
#
|
| 411 |
+
# mu_t = self.head(out_t.squeeze(1)).view(B, self.output_len, self.output_dim)
|
| 412 |
+
# mu_preds.append(mu_t.unsqueeze(1))
|
| 413 |
+
#
|
| 414 |
+
# mu_preds = torch.cat(mu_preds, dim=1) # [B, L+1, output_len, output_dim]
|
| 415 |
+
#
|
| 416 |
+
# # Now create logvar_preds: same shape, filled with fixed_logvar
|
| 417 |
+
# logvar_preds = self.fixed_logvar.expand_as(mu_preds).to(mu_preds.device)
|
| 418 |
+
#
|
| 419 |
+
# return mu_preds, logvar_preds
|
| 420 |
+
#
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
# ---------------- Decoder v2: predicted variance ----------------
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
#
|
| 427 |
+
# ## LSTM
|
| 428 |
+
# import torch, torch.nn as nn
|
| 429 |
+
# import torch.nn.functional as F
|
| 430 |
+
#
|
| 431 |
+
# class LSTM_Baseline(nn.Module):
|
| 432 |
+
# """
|
| 433 |
+
# Simple encoder‑decoder LSTM baseline.
|
| 434 |
+
# • All four modal inputs (load, temp, workday, season) are concatenated along feature dim
|
| 435 |
+
# so the external information is still available, but the model is otherwise “plain”.
|
| 436 |
+
# • The forward signature (extra **kwargs) lets the old training loop pass epoch/top_k/warmup
|
| 437 |
+
# without breaking anything.
|
| 438 |
+
# """
|
| 439 |
+
# def __init__(
|
| 440 |
+
# self,
|
| 441 |
+
# input_dim: int, # 1 → only the scalar value of each channel
|
| 442 |
+
# hidden_size: int, # e.g. 64
|
| 443 |
+
# output_len: int, # prediction horizon (3)
|
| 444 |
+
# output_dim: int = 1, # scalar prediction
|
| 445 |
+
# num_layers: int = 2,
|
| 446 |
+
# dropout: float = 0.1,
|
| 447 |
+
# ):
|
| 448 |
+
# super().__init__()
|
| 449 |
+
# self.hidden_size = hidden_size
|
| 450 |
+
# self.output_len = output_len
|
| 451 |
+
# self.output_dim = output_dim
|
| 452 |
+
# self.num_layers = num_layers
|
| 453 |
+
#
|
| 454 |
+
# # encoder & decoder
|
| 455 |
+
# self.encoder = nn.LSTM(
|
| 456 |
+
# input_size = input_dim * 4, # four channels concatenated
|
| 457 |
+
# hidden_size = hidden_size,
|
| 458 |
+
# num_layers = num_layers,
|
| 459 |
+
# batch_first = True,
|
| 460 |
+
# dropout = dropout if num_layers > 1 else 0.0,
|
| 461 |
+
# )
|
| 462 |
+
# self.decoder = nn.LSTM(
|
| 463 |
+
# input_size = input_dim * 4,
|
| 464 |
+
# hidden_size = hidden_size,
|
| 465 |
+
# num_layers = num_layers,
|
| 466 |
+
# batch_first = True,
|
| 467 |
+
# dropout = dropout if num_layers > 1 else 0.0,
|
| 468 |
+
# )
|
| 469 |
+
#
|
| 470 |
+
# self.out_layer = nn.Linear(hidden_size, output_dim)
|
| 471 |
+
#
|
| 472 |
+
# def forward(
|
| 473 |
+
# self,
|
| 474 |
+
# enc_l, enc_t, enc_w, enc_s,
|
| 475 |
+
# dec_l, dec_t, dec_w, dec_s,
|
| 476 |
+
# *unused, **unused_kw,
|
| 477 |
+
# ):
|
| 478 |
+
# """
|
| 479 |
+
# enc_* : [B, Lenc, 1] (load / temp / workday / season)
|
| 480 |
+
# dec_* : [B, Ldec, 1]
|
| 481 |
+
# return: [B, Lenc+1, output_len, 1] (to keep your downstream code intact)
|
| 482 |
+
# """
|
| 483 |
+
# B, Lenc, _ = enc_l.shape
|
| 484 |
+
#
|
| 485 |
+
# # 1) ---------- Encode ----------
|
| 486 |
+
# enc_in = torch.cat([enc_l, enc_t, enc_w, enc_s], dim=-1) # [B, Lenc, 4]
|
| 487 |
+
# _, (h_n, c_n) = self.encoder(enc_in) # carry hidden to decoder
|
| 488 |
+
#
|
| 489 |
+
# # 2) ---------- Decode ----------
|
| 490 |
+
# Ldec = dec_l.size(1) # usually 1 step (the teacher‑force token)
|
| 491 |
+
# dec_in = torch.cat([dec_l, dec_t, dec_w, dec_s], dim=-1) # [B, Ldec, 4]
|
| 492 |
+
# dec_out, _ = self.decoder(dec_in, (h_n, c_n)) # [B, Ldec, H]
|
| 493 |
+
# y0 = self.out_layer(dec_out[:, -1]) # last step → [B, output_dim]
|
| 494 |
+
#
|
| 495 |
+
# # 3) ---------- Autoregressive forecast ----------
|
| 496 |
+
# preds = []
|
| 497 |
+
# ht, ct = h_n, c_n
|
| 498 |
+
# xt = dec_in[:, -1] # start token
|
| 499 |
+
# for _ in range(self.output_len):
|
| 500 |
+
# xt = xt.unsqueeze(1) # [B,1,4]
|
| 501 |
+
# out, (ht, ct) = self.decoder(xt, (ht, ct)) # [B,1,H]
|
| 502 |
+
# yt = self.out_layer(out.squeeze(1)) # [B, output_dim]
|
| 503 |
+
# preds.append(yt)
|
| 504 |
+
# # next decoder input = last prediction repeated over 4 channels
|
| 505 |
+
# xt = torch.cat([yt]*4, dim=-1)
|
| 506 |
+
#
|
| 507 |
+
# # 3) ---------- Autoregressive forecast ----------
|
| 508 |
+
# preds = torch.stack(preds, dim=1) # [B, H, 1]
|
| 509 |
+
#
|
| 510 |
+
# # 4) ---------- match original return shape ----------
|
| 511 |
+
# seq_len_y = enc_l.size(1) - self.output_len + 1 # <-- NEW: 168‑>166
|
| 512 |
+
# preds = preds.unsqueeze(1).repeat(1, seq_len_y, 1, 1)
|
| 513 |
+
# return preds # [B, 166, 3, 1]
|
| 514 |
+
#
|