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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import os
|
| 3 |
+
import traceback
|
| 4 |
+
|
| 5 |
+
st.set_page_config(page_title="Renewable Energy AI", layout="wide", page_icon="⚡")
|
| 6 |
+
|
| 7 |
+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 8 |
+
|
| 9 |
+
MODELS = {
|
| 10 |
+
"2025-26 Model": "2025_26_model",
|
| 11 |
+
"2024 Model": "2024_model",
|
| 12 |
+
"2023 Model": "2023_model",
|
| 13 |
+
"2016-17 Model": "2016_17_model"
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def get_folder_path(model_key):
|
| 18 |
+
rel = MODELS[model_key]
|
| 19 |
+
abs_path = os.path.join(BASE_DIR, rel)
|
| 20 |
+
return abs_path if os.path.isdir(abs_path) else os.path.join(os.getcwd(), rel)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@st.cache_resource(max_entries=1)
|
| 24 |
+
def load_assets(folder_path):
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
import torch.nn.functional as F
|
| 28 |
+
import joblib
|
| 29 |
+
import json
|
| 30 |
+
|
| 31 |
+
class TFTBranch(nn.Module):
|
| 32 |
+
def __init__(self, input_dim, hidden_dim, num_horizons):
|
| 33 |
+
super().__init__()
|
| 34 |
+
self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers=2, batch_first=True, dropout=0.2)
|
| 35 |
+
self.attention = nn.MultiheadAttention(embed_dim=hidden_dim, num_heads=4, batch_first=True, dropout=0.2)
|
| 36 |
+
self.dropout = nn.Dropout(0.2)
|
| 37 |
+
self.fc = nn.Linear(hidden_dim, num_horizons)
|
| 38 |
+
|
| 39 |
+
def forward(self, x):
|
| 40 |
+
lstm_out, _ = self.lstm(x)
|
| 41 |
+
lstm_out = self.dropout(lstm_out)
|
| 42 |
+
attn_out, attn_weights = self.attention(lstm_out, lstm_out, lstm_out)
|
| 43 |
+
attn_out = self.dropout(attn_out)
|
| 44 |
+
out = self.fc(attn_out[:, -1, :])
|
| 45 |
+
return out, attn_weights
|
| 46 |
+
|
| 47 |
+
class NBEATSBlock(nn.Module):
|
| 48 |
+
def __init__(self, input_size, theta_size, hidden_size):
|
| 49 |
+
super().__init__()
|
| 50 |
+
self.fc1 = nn.Linear(input_size, hidden_size)
|
| 51 |
+
self.fc2 = nn.Linear(hidden_size, hidden_size)
|
| 52 |
+
self.fc3 = nn.Linear(hidden_size, hidden_size)
|
| 53 |
+
self.fc4 = nn.Linear(hidden_size, hidden_size)
|
| 54 |
+
self.dropout = nn.Dropout(0.2)
|
| 55 |
+
self.theta_layer = nn.Linear(hidden_size, theta_size)
|
| 56 |
+
self.backcast_layer = nn.Linear(theta_size, input_size)
|
| 57 |
+
self.forecast_layer = nn.Linear(theta_size, theta_size)
|
| 58 |
+
|
| 59 |
+
def forward(self, x):
|
| 60 |
+
h = self.dropout(F.relu(self.fc1(x)))
|
| 61 |
+
h = self.dropout(F.relu(self.fc2(h)))
|
| 62 |
+
h = self.dropout(F.relu(self.fc3(h)))
|
| 63 |
+
h = self.dropout(F.relu(self.fc4(h)))
|
| 64 |
+
theta = self.theta_layer(h)
|
| 65 |
+
backcast = self.backcast_layer(theta)
|
| 66 |
+
forecast = self.forecast_layer(theta)
|
| 67 |
+
return backcast, forecast, theta
|
| 68 |
+
|
| 69 |
+
class NBEATSBranch(nn.Module):
|
| 70 |
+
def __init__(self, seq_len, num_horizons, hidden_size=128):
|
| 71 |
+
super().__init__()
|
| 72 |
+
self.trend_block = NBEATSBlock(seq_len, num_horizons, hidden_size)
|
| 73 |
+
self.seasonality_block = NBEATSBlock(seq_len, num_horizons, hidden_size)
|
| 74 |
+
|
| 75 |
+
def forward(self, x):
|
| 76 |
+
x_flat = x[:, :, 0]
|
| 77 |
+
backcast_t, forecast_t, _ = self.trend_block(x_flat)
|
| 78 |
+
x_res = x_flat - backcast_t
|
| 79 |
+
_, forecast_s, _ = self.seasonality_block(x_res)
|
| 80 |
+
return forecast_t + forecast_s, forecast_t, forecast_s
|
| 81 |
+
|
| 82 |
+
class HybridFusionModel(nn.Module):
|
| 83 |
+
def __init__(self, input_dim, seq_len, hidden_dim, num_horizons):
|
| 84 |
+
super().__init__()
|
| 85 |
+
self.tft = TFTBranch(input_dim, hidden_dim, num_horizons)
|
| 86 |
+
self.nbeats = NBEATSBranch(seq_len, num_horizons, hidden_dim)
|
| 87 |
+
self.attention_fusion = nn.Sequential(
|
| 88 |
+
nn.Linear(num_horizons * 2, hidden_dim),
|
| 89 |
+
nn.ReLU(),
|
| 90 |
+
nn.Linear(hidden_dim, 2),
|
| 91 |
+
nn.Softmax(dim=-1)
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
def forward(self, x):
|
| 95 |
+
tft_out, tft_attn = self.tft(x)
|
| 96 |
+
nbeats_out, nbeats_trend, nbeats_season = self.nbeats(x)
|
| 97 |
+
combined = torch.cat([tft_out, nbeats_out], dim=-1)
|
| 98 |
+
weights = self.attention_fusion(combined)
|
| 99 |
+
w_tft = weights[:, 0].unsqueeze(1)
|
| 100 |
+
w_nbeats = weights[:, 1].unsqueeze(1)
|
| 101 |
+
final_out = (tft_out * w_tft) + (nbeats_out * w_nbeats)
|
| 102 |
+
return final_out, tft_attn, nbeats_trend, nbeats_season
|
| 103 |
+
|
| 104 |
+
try:
|
| 105 |
+
config_path = os.path.join(folder_path, "config.json")
|
| 106 |
+
with open(config_path, 'r') as f:
|
| 107 |
+
config = json.load(f)
|
| 108 |
+
|
| 109 |
+
scaler_path = os.path.join(folder_path, "scaler.pkl")
|
| 110 |
+
scaler = joblib.load(scaler_path)
|
| 111 |
+
|
| 112 |
+
model_path = os.path.join(folder_path, "pytorch_model.bin")
|
| 113 |
+
|
| 114 |
+
input_dim = config.get("input_dim", 12)
|
| 115 |
+
seq_len = config.get("seq_len", 144)
|
| 116 |
+
hidden_dim = config.get("hidden_dim", 64)
|
| 117 |
+
num_horizons = config.get("num_horizons", 5)
|
| 118 |
+
|
| 119 |
+
model = HybridFusionModel(input_dim, seq_len, hidden_dim, num_horizons)
|
| 120 |
+
|
| 121 |
+
try:
|
| 122 |
+
state_dict = torch.load(model_path, map_location="cpu", weights_only=True)
|
| 123 |
+
except Exception:
|
| 124 |
+
state_dict = torch.load(model_path, map_location="cpu", weights_only=False)
|
| 125 |
+
|
| 126 |
+
model.load_state_dict(state_dict, strict=False)
|
| 127 |
+
model.eval()
|
| 128 |
+
|
| 129 |
+
return model, scaler, config, None
|
| 130 |
+
|
| 131 |
+
except Exception:
|
| 132 |
+
return None, None, None, traceback.format_exc()
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def read_config_for_sidebar(model_key):
|
| 136 |
+
folder_path = get_folder_path(model_key)
|
| 137 |
+
config_path = os.path.join(folder_path, "config.json")
|
| 138 |
+
try:
|
| 139 |
+
import json
|
| 140 |
+
with open(config_path, 'r') as f:
|
| 141 |
+
cfg = json.load(f)
|
| 142 |
+
input_dim = cfg.get("input_dim", 12)
|
| 143 |
+
feature_names = cfg.get("numeric_cols", [f"Feature_{i}" for i in range(input_dim)])
|
| 144 |
+
return feature_names
|
| 145 |
+
except Exception:
|
| 146 |
+
return [f"Feature_{i}" for i in range(12)]
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def main():
|
| 150 |
+
st.title("Multi-Horizon Renewable Energy Forecaster")
|
| 151 |
+
|
| 152 |
+
with st.sidebar.form("model_control_form"):
|
| 153 |
+
st.markdown("### Control Panel")
|
| 154 |
+
selected_year = st.selectbox("Active Temporal Model", list(MODELS.keys()))
|
| 155 |
+
st.markdown("---")
|
| 156 |
+
st.subheader("Real-time Sensors")
|
| 157 |
+
|
| 158 |
+
feature_names = read_config_for_sidebar(selected_year)
|
| 159 |
+
|
| 160 |
+
user_sensor_data = {}
|
| 161 |
+
for feat in feature_names:
|
| 162 |
+
user_sensor_data[feat] = st.slider(feat, -5.0, 5.0, 0.0)
|
| 163 |
+
|
| 164 |
+
submit_button = st.form_submit_button("Initialize & Predict")
|
| 165 |
+
|
| 166 |
+
if not submit_button:
|
| 167 |
+
st.info("Adjust the sensors in the sidebar and click **Initialize & Predict** to begin.")
|
| 168 |
+
return
|
| 169 |
+
|
| 170 |
+
folder_path = get_folder_path(selected_year)
|
| 171 |
+
|
| 172 |
+
with st.spinner(f"Loading {selected_year} — this may take a moment..."):
|
| 173 |
+
model, scaler, config, error = load_assets(folder_path)
|
| 174 |
+
|
| 175 |
+
if error:
|
| 176 |
+
st.error("Failed to load model assets. Details below:")
|
| 177 |
+
st.code(error)
|
| 178 |
+
st.write("**Debug info:**")
|
| 179 |
+
st.write(f"- Looking in: `{folder_path}`")
|
| 180 |
+
st.write(f"- BASE_DIR: `{BASE_DIR}`")
|
| 181 |
+
st.write(f"- CWD: `{os.getcwd()}`")
|
| 182 |
+
st.write("**Files found in CWD:**")
|
| 183 |
+
try:
|
| 184 |
+
st.write(os.listdir(os.getcwd()))
|
| 185 |
+
except Exception:
|
| 186 |
+
st.write("Could not list directory.")
|
| 187 |
+
return
|
| 188 |
+
|
| 189 |
+
try:
|
| 190 |
+
import torch
|
| 191 |
+
import numpy as np
|
| 192 |
+
import pandas as pd
|
| 193 |
+
import plotly.graph_objects as go
|
| 194 |
+
|
| 195 |
+
seq_len_config = config.get("seq_len", 144)
|
| 196 |
+
|
| 197 |
+
input_df = pd.DataFrame([user_sensor_data])
|
| 198 |
+
scaled_data = scaler.transform(input_df)
|
| 199 |
+
input_seq = np.tile(scaled_data, (seq_len_config, 1))
|
| 200 |
+
input_tensor = torch.tensor(input_seq, dtype=torch.float32).unsqueeze(0)
|
| 201 |
+
|
| 202 |
+
with torch.no_grad():
|
| 203 |
+
preds, _, _, _ = model(input_tensor)
|
| 204 |
+
forecast = preds.detach().cpu().numpy().flatten()
|
| 205 |
+
|
| 206 |
+
st.markdown(f"Analyzing with **{selected_year}** architecture.")
|
| 207 |
+
|
| 208 |
+
m1, m2, m3 = st.columns(3)
|
| 209 |
+
m1.metric("Architecture", "TFT + N-BEATS")
|
| 210 |
+
m2.metric("Input Features", len(feature_names))
|
| 211 |
+
m3.metric("Lookback Window", f"{seq_len_config} Timesteps")
|
| 212 |
+
|
| 213 |
+
st.markdown("---")
|
| 214 |
+
c1, c2 = st.columns([2, 1])
|
| 215 |
+
|
| 216 |
+
with c1:
|
| 217 |
+
st.subheader("Forecasted Energy Trajectory")
|
| 218 |
+
fig = go.Figure()
|
| 219 |
+
fig.add_trace(go.Scatter(
|
| 220 |
+
x=[f"T+{i+1}" for i in range(len(forecast))],
|
| 221 |
+
y=forecast,
|
| 222 |
+
mode="lines+markers",
|
| 223 |
+
name="Predicted Value",
|
| 224 |
+
line=dict(color="#00F5FF", width=4),
|
| 225 |
+
marker=dict(size=10, symbol="diamond")
|
| 226 |
+
))
|
| 227 |
+
fig.update_layout(
|
| 228 |
+
template="plotly_dark",
|
| 229 |
+
hovermode="x unified",
|
| 230 |
+
xaxis_title="Future Timesteps",
|
| 231 |
+
yaxis_title="Normalized Energy Value",
|
| 232 |
+
plot_bgcolor="rgba(0,0,0,0)",
|
| 233 |
+
paper_bgcolor="rgba(0,0,0,0)",
|
| 234 |
+
margin=dict(l=0, r=0, t=30, b=0)
|
| 235 |
+
)
|
| 236 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 237 |
+
|
| 238 |
+
with c2:
|
| 239 |
+
st.subheader("Prediction Table")
|
| 240 |
+
res_df = pd.DataFrame({
|
| 241 |
+
"Horizon": [f"Step {i+1}" for i in range(len(forecast))],
|
| 242 |
+
"Forecast Value": forecast.round(4)
|
| 243 |
+
})
|
| 244 |
+
st.table(res_df)
|
| 245 |
+
with st.expander("Technical Model Configuration"):
|
| 246 |
+
st.json(config)
|
| 247 |
+
|
| 248 |
+
st.markdown("---")
|
| 249 |
+
st.caption("Deployment powered by Hybrid Fusion Model Architecture.")
|
| 250 |
+
|
| 251 |
+
except Exception:
|
| 252 |
+
st.error("Error during inference:")
|
| 253 |
+
st.code(traceback.format_exc())
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
if __name__ == "__main__":
|
| 257 |
+
main()
|