-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
200 lines (165 loc) · 8.1 KB
/
Copy pathapp.py
File metadata and controls
200 lines (165 loc) · 8.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
"""GreenGrid UK — when is Britain's electricity greenest?
Streamlit app serving the GreenBlend model (climatology + LightGBM, see src/train.py).
Live grid data comes from the official Carbon Intensity API; if it is unreachable the
app degrades gracefully to climatology-only forecasts instead of crashing.
"""
from datetime import datetime, timezone
from pathlib import Path
import joblib
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import streamlit as st
from src.features import FEATURE_COLS, calendar_features, lag_features
from src.live import fetch_current, fetch_history
from src.train import predict_climatology
st.set_page_config(page_title="GreenGrid UK", page_icon="🔌", layout="wide")
HORIZON = 96 # forecast 48h ahead, half-hourly
UK_TZ = "Europe/London"
APPLIANCES = {
"EV charge (40 kWh)": (40.0, 8), # kWh, typical duration in half-hours
"Washing machine (1.0 kWh)": (1.0, 3),
"Tumble dryer (2.5 kWh)": (2.5, 3),
"Dishwasher (1.2 kWh)": (1.2, 3),
"Oven for dinner (1.5 kWh)": (1.5, 2),
"Custom": (1.0, 2),
}
@st.cache_resource
def load_models():
models_dir = Path(__file__).parent / "models"
return (
joblib.load(models_dir / "lgbm.joblib"),
joblib.load(models_dir / "climatology.joblib"),
)
@st.cache_data(ttl=600, show_spinner=False)
def get_live_data():
"""(history_df, current_dict) or (None, None) when the live API is down."""
try:
return fetch_history(), fetch_current()
except Exception:
return None, None
def forecast(lgbm, clim, history: pd.DataFrame | None) -> tuple[pd.Series, bool]:
"""Predict the next 48h. Returns (predictions, live_mode)."""
if history is not None and len(history) >= 340:
last = history.index.max()
future = pd.date_range(last + pd.Timedelta("30min"), periods=HORIZON, freq="30min")
# lag features need one continuous series spanning history + future
ci = pd.concat([history["CARBON_INTENSITY"], pd.Series(np.nan, index=future)])
wind = pd.concat([history["wind_share"], pd.Series(np.nan, index=future)])
solar = pd.concat([history["solar_share"], pd.Series(np.nan, index=future)])
X = calendar_features(future).join(lag_features(ci, wind, solar).loc[future])
if not X[FEATURE_COLS].isna().any().any():
lgbm_pred = pd.Series(lgbm.predict(X[FEATURE_COLS]), index=future)
clim_pred = predict_climatology(clim["table"], future)
alpha = clim["alpha"]
return alpha * clim_pred + (1 - alpha) * lgbm_pred, True
# fallback: seasonal average only — app stays useful even with no live data
now = pd.Timestamp.now(tz="UTC").tz_localize(None).floor("30min")
future = pd.date_range(now + pd.Timedelta("30min"), periods=HORIZON, freq="30min")
return predict_climatology(clim["table"], future), False
def best_window(pred: pd.Series, duration_periods: int, within_hours: int) -> pd.Timestamp:
"""End timestamp of the cleanest contiguous run that finishes within the horizon."""
horizon = pred.iloc[: within_hours * 2]
return horizon.rolling(duration_periods).mean().idxmin()
def badge(value: float) -> str:
if value < 100:
return "🟢 green"
if value < 200:
return "🟠 amber"
return "🔴 red"
def to_uk(idx):
return idx.tz_localize("UTC").tz_convert(UK_TZ).tz_localize(None)
# --------------------------------------------------------------------------- #
st.title("🔌 GreenGrid UK")
st.markdown(
"**When is Britain's electricity greenest?** The same kWh can cost 5× more CO₂ at "
"the wrong time of day. Pick an appliance, tell us how flexible you are, and the "
"model finds the cleanest slot in the next 48 hours."
)
lgbm, clim = load_models()
history, current = get_live_data()
pred, live_mode = forecast(lgbm, clim, history)
if not live_mode:
st.warning(
"Live grid data is currently unavailable — showing seasonal-average forecasts. "
"Recommendations are still sensible, but less sharp than usual.", icon="⚠️"
)
with st.sidebar:
st.header("What do you want to run?")
appliance = st.selectbox("Appliance", list(APPLIANCES.keys()))
kwh_default, dur_default = APPLIANCES[appliance]
kwh = st.number_input("Energy used (kWh)", 0.1, 100.0, kwh_default, step=0.1)
duration_h = st.slider("How long does it run? (hours)", 0.5, 8.0, dur_default / 2, 0.5)
within = st.slider("I can wait up to... (hours)", 3, 48, 24)
st.caption(
"Forecasts by GreenBlend — a climatology + LightGBM model trained on 17 years "
"of NESO grid data. See the repo for the full evaluation."
)
duration_periods = max(1, int(duration_h * 2))
end = best_window(pred, duration_periods, within)
start = end - pd.Timedelta(minutes=30 * (duration_periods - 1))
window_ci = pred.loc[start:end].mean()
now_ci = pred.iloc[:duration_periods].mean() # "plug in right now" comparison
saving_g = (now_ci - window_ci) * kwh
c1, c2, c3, c4 = st.columns(4)
if current:
c1.metric("Grid right now", f"{current['intensity']} gCO₂/kWh",
current["index"], delta_color="off")
else:
c1.metric("Grid right now", "n/a")
c2.metric("Best slot starts", f"{to_uk(pd.DatetimeIndex([start]))[0]:%a %H:%M}",
f"{badge(window_ci).split()[1]} · {window_ci:.0f} gCO₂/kWh", delta_color="off")
c3.metric("If you start now", f"{now_ci:.0f} gCO₂/kWh", badge(now_ci).split()[1],
delta_color="off")
c4.metric("CO₂ saved by waiting", f"{saving_g:.0f} g",
f"≈ {saving_g / 1000:.2f} kg per run", delta_color="off")
# ---- forecast chart -------------------------------------------------------- #
plot_idx = to_uk(pred.index)
fig = go.Figure()
fig.add_hrect(y0=0, y1=100, fillcolor="green", opacity=0.07, line_width=0)
fig.add_hrect(y0=100, y1=200, fillcolor="orange", opacity=0.06, line_width=0)
fig.add_hrect(y0=200, y1=max(320, float(pred.max()) + 20),
fillcolor="red", opacity=0.05, line_width=0)
fig.add_trace(go.Scatter(x=plot_idx, y=pred.values, mode="lines",
name="predicted carbon intensity",
line=dict(color="#1a7f37", width=2.5)))
ws, we = to_uk(pd.DatetimeIndex([start]))[0], to_uk(pd.DatetimeIndex([end]))[0]
fig.add_vrect(x0=ws, x1=we, fillcolor="#1a7f37", opacity=0.25, line_width=0,
annotation_text="your green slot", annotation_position="top left")
fig.update_layout(
title=f"Predicted GB grid carbon intensity — next 48h (times in UK local)",
yaxis_title="gCO₂/kWh", height=420, margin=dict(t=50, b=10),
showlegend=False,
)
st.plotly_chart(fig, width="stretch")
# ---- context row ----------------------------------------------------------- #
left, right = st.columns([1, 1])
with left:
st.subheader("What's powering the grid right now?")
if current:
mix = dict(sorted(current["mix"].items(), key=lambda kv: -kv[1]))
fig2 = go.Figure(go.Pie(labels=[k.title() for k in mix], values=list(mix.values()),
hole=0.45))
fig2.update_layout(height=330, margin=dict(t=10, b=10))
st.plotly_chart(fig2, width="stretch")
else:
st.info("Live generation mix unavailable.")
with right:
st.subheader("Why this matters")
st.markdown(
f"""
- The GB grid's carbon intensity swings **hour to hour** with wind, solar and demand —
the model found a median within-day spread of **~90 gCO₂/kWh** in recent years.
- Time-shifting one **EV charge** to the cleanest window saves **kilograms** of CO₂ —
scaled to the UK's ~1.5M EVs, that's a meaningful national lever that costs nothing.
- Smart tariffs (Octopus Agile, Intelligent Go) already reward exactly this behaviour,
so the green slot is usually the **cheap** slot too.
*Data: National Energy System Operator (NESO) historic generation mix, 2009–present;
live conditions from the official GB Carbon Intensity API. Predictions are for the
national grid — your local mix may differ.*
"""
)
st.caption(
f"GreenBlend model · MAE ≈ 51 gCO₂/kWh on held-out 2026 data · last refreshed "
f"{datetime.now(timezone.utc):%Y-%m-%d %H:%M} UTC · not affiliated with NESO"
)