Forecast Texas grid demand with temperature and calendar covariates, plan capacity under weather scenarios, and gate the plan on approval.
Capacity planning with covariates
Code available on GitHub. See Time series models for setup, the container image, and the metrics.
Electricity demand in Texas follows the temperature: a hot afternoon in Houston means air conditioning across the coast. This tutorial forecasts hourly demand for the eight ERCOT weather zones with Timestral, conditioned on temperature and the calendar. It then plans next week’s capacity:
- Backtest three covariate configurations on the last eight weeks of data, to measure what each covariate adds.
- Plan next week’s peak demand under weather scenarios taken from the same week of every past year.
- Approve the plan: the run pauses until a planner enters a reserve margin, then publishes the plan as a CSV.
flowchart LR
E[load_ercot<br/>cached] --> B
W["fetch_temperature × 8<br/>cached, backoff"] --> B
W --> P
E --> P
B["backtest_zone × 8"] --> R[report]
P["plan_zone × 8<br/>17 scenarios each"] --> R
R --> A[/planner:<br/>reserve margin %/]
A --> O[capacity_plan.csv]
Run it
python capacity_planning.pyWhen the report is ready, the run pauses on a condition named reserve-margin. Enter a percentage in the UI, or from the CLI with the condition’s action name, which flyte get condition lists:
flyte get condition <run-name>
flyte signal condition <run-name> <action-name> 15.0Enter 0 to reject the plan, which fails the run. To stress-test the plan against hotter weather, shift every scenario up by a few degrees:
flyte run capacity_planning.py capacity_plan --heat_shift_c 3The data
Load comes from ERCOT’s hourly demand per weather zone, 2004 through August 2021. Temperature comes from the Open-Meteo historical weather API, for one representative city per zone.
# Hourly load (MW) for the eight ERCOT weather zones, 2004 to August 2021.
ERCOT_URL = (
"https://huggingface.co/datasets/autogluon/chronos_datasets/resolve/main/"
"ercot/train-00000-of-00001.parquet"
)
# One representative city per weather zone, for hourly temperatures from the
# Open-Meteo historical weather API.
ZONES = {
"COAST": (29.76, -95.37), # Houston
"EAST": (32.35, -95.30), # Tyler
"FAR_WEST": (31.99, -102.08), # Midland
"NORTH": (33.91, -98.49), # Wichita Falls
"NORTH_C": (32.78, -96.80), # Dallas
"SOUTHERN": (27.80, -97.40), # Corpus Christi
"SOUTH_C": (30.27, -97.74), # Austin
"WEST": (32.45, -99.73), # Abilene
}
WEATHER_URL = "https://archive-api.open-meteo.com/v1/archive"
Both downloads are cached tasks. The weather API is rate-limited, so fetch_temperature retries with exponential backoff: 10 seconds, then 20, then 40, capped at two minutes. A burst of 429 responses delays the run instead of failing it, and once a zone’s temperatures are fetched, no later run calls the API for them again.
@env.task(cache="auto", retries=3)
async def load_ercot(url: str = ERCOT_URL) -> flyte.io.File:
local = Path(tempfile.mkdtemp()) / "ercot.parquet"
urllib.request.urlretrieve(url, local)
return await flyte.io.File.from_local(str(local))
# The weather API is rate-limited. Exponential backoff rides out 429s and
# transient errors; the cache means each zone is fetched once, ever.
@env.task(
cache="auto",
retries=flyte.RetryStrategy(
count=5,
backoff=flyte.Backoff(
base=timedelta(seconds=10), factor=2.0, cap=timedelta(minutes=2)
),
),
)
async def fetch_temperature(zone: str, start: str, end: str) -> flyte.io.File:
"""Hourly 2 m temperature (°C) in US Central local time, as Parquet."""
import httpx
import pandas as pd
lat, lon = ZONES[zone]
params = {
"latitude": lat,
"longitude": lon,
"start_date": start,
"end_date": end,
"hourly": "temperature_2m",
"timezone": "America/Chicago",
}
async with httpx.AsyncClient(timeout=120) as client:
response = await client.get(WEATHER_URL, params=params)
response.raise_for_status()
hourly = response.json()["hourly"]
frame = pd.DataFrame(
{"timestamp": pd.to_datetime(hourly["time"]), "temp_c": hourly["temperature_2m"]}
)
out = Path(tempfile.mkdtemp()) / f"temperature_{zone}.parquet"
frame.to_parquet(out)
return await flyte.io.File.from_local(str(out))
Covariates
Timestral takes two kinds of known-future covariates, values known for the history and the horizon alike:
- Categorical, as
categorical_known_covariates: hour of day, day of week, and a US federal holiday flag. The forecaster encodes each category against the target, so the codes can be any numbers. - Numeric, as
known_covariates: hourly temperature.
def calendar_codes(index):
"""Categorical known-future covariates: hour of day, day of week, holiday."""
import numpy as np
import pandas as pd
from pandas.tseries.holiday import USFederalHolidayCalendar
holidays = USFederalHolidayCalendar().holidays(index.min(), index.max())
return np.stack(
[
index.hour.to_numpy(),
index.dayofweek.to_numpy(),
pd.DatetimeIndex(index.normalize()).isin(holidays).astype(int),
]
).astype(
"float32"
) # (3, len(index))
def forecast_with(forecaster, load, temps, codes, horizon: int, config: str):
"""Forecast one or more series under a covariate configuration.
`load` is (B, T); `temps` is (B, T + horizon); `codes` is (3, T + horizon).
"""
import numpy as np
batch = load.shape[0]
kwargs = {}
if config != "target only":
kwargs["categorical_known_covariates"] = np.repeat(codes[None], batch, axis=0)
if config == "+ calendar + temperature":
kwargs["known_covariates"] = temps[:, None, :]
return (
forecaster.forecast(load, prediction_length=horizon, **kwargs).quantiles[:, 0].numpy()
)
Each covariate array spans the history plus the horizon, T + horizon steps. That is how the model sees the temperature during the hours it forecasts.
Measure what the covariates add
backtest_zone forecasts each of the last n_windows weeks three ways: target only, with calendar codes, and with calendar codes and temperature.
@env.task(cache="auto", retries=3)
async def backtest_zone(
ercot: flyte.io.File,
temperature: flyte.io.File,
zone: str,
model: str,
n_windows: int,
context_length: int,
horizon: int,
) -> list[ConfigScore]:
"""Score every covariate configuration on the last `n_windows` weeks of data.
The backtest uses observed temperatures over the horizon, as a stand-in for a
perfect weather forecast. That is an upper bound on what temperature adds.
"""
import numpy as np
frame = await zone_frame(ercot, temperature, zone)
load = frame["load_mw"].to_numpy("float32")
temps = frame["temp_c"].to_numpy("float32")
codes = calendar_codes(frame.index)
forecaster = load_forecaster(TIMESTRAL_MODELS[model], CPUS)
scores = []
for config in CONFIGS:
wql, mase_ = [], []
for k in range(n_windows, 0, -1):
cutoff = len(load) - k * horizon
window = slice(cutoff - context_length, cutoff + horizon)
quantiles = forecast_with(
forecaster,
load[None, cutoff - context_length : cutoff],
temps[None, window],
codes[:, window],
horizon,
config,
)[0]
actual = load[cutoff : cutoff + horizon]
wql.append(weighted_quantile_loss(actual, quantiles))
mase_.append(
mase(actual, quantiles[:, QUANTILE_LEVELS.index(0.5)], load[:cutoff], 168)
)
scores.append(ConfigScore(zone, config, float(np.mean(wql)), float(np.mean(mase_))))
return scores
On three zones with Timestral-28M, over the last eight weeks of summer 2021:
| Zone | Target only | + calendar | + calendar + temperature |
|---|---|---|---|
| COAST | 0.0331 | 0.0335 | 0.0196 |
| NORTH_C | 0.0426 | 0.0431 | 0.0228 |
| FAR_WEST | 0.0184 | 0.0183 | 0.0122 |
The values are weighted quantile loss; lower is better. Temperature cuts the loss by 34% to 47%. Calendar codes alone make little difference, because the model already reads the daily and weekly cycles from the 4,096 hours (about 24 weeks) of history in each context.
The backtest uses the observed temperatures over each horizon, as if the weather forecast were perfect. That’s an upper bound on what temperature adds. With a real weather forecast, the gain shrinks with the forecast’s error.
Plan under weather scenarios
Next week’s temperatures aren’t known, so plan_zone builds one scenario per past year: the same calendar week’s temperatures from that year. History is the same in every scenario, so all the scenarios, 17 with this dataset, go through the model as one batch of series that differ only in their temperature covariate.
@env.task(cache="auto", retries=3)
async def plan_zone(
ercot: flyte.io.File,
temperature: flyte.io.File,
zone: str,
model: str,
context_length: int,
horizon: int,
heat_shift_c: float,
) -> ZonePlan:
"""Forecast the week after the data ends under one weather scenario per past
year, in a single batched forward pass."""
import numpy as np
import pandas as pd
frame = await zone_frame(ercot, temperature, zone)
load = frame["load_mw"].to_numpy("float32")[-context_length:]
future = pd.date_range(frame.index[-1], periods=horizon + 1, freq="h")[1:]
index = frame.index[-context_length:].append(future)
codes = calendar_codes(index)
# Scenario y: the same calendar week's temperatures from year y, plus an
# optional heat-stress shift. History is the same in every scenario.
years = sorted(set(frame.index.year) - {future[0].year})
scenarios = []
for year in years:
analog = frame["temp_c"].reindex(future - pd.DateOffset(years=future[0].year - year))
if analog.notna().all():
scenarios.append((year, analog.to_numpy("float32") + heat_shift_c))
history_temps = frame["temp_c"].to_numpy("float32")[-context_length:]
temps = np.stack([np.concatenate([history_temps, s]) for _, s in scenarios])
forecaster = load_forecaster(TIMESTRAL_MODELS[model], CPUS)
batch_load = np.repeat(load[None], len(scenarios), axis=0)
quantiles = forecast_with(
forecaster, batch_load, temps, codes, horizon, "+ calendar + temperature"
)
median_peaks = quantiles[:, :, QUANTILE_LEVELS.index(0.5)].max(axis=1)
p99_peaks = quantiles[:, :, -1].max(axis=1)
worst = int(np.argmax(p99_peaks))
return ZonePlan(
zone=zone,
median_peak_mw=float(np.median(median_peaks)),
p99_peak_mw=float(p99_peaks[worst]),
worst_year=scenarios[worst][0],
chart=fan_chart_svg(
load[-2 * horizon :],
quantiles[worst],
title=f"{zone}: worst scenario ({scenarios[worst][0]} weather)",
),
)
For each zone, the plan records the median of the scenarios’ peak median forecasts and the worst scenario’s peak 99th-percentile forecast. The worst case drives the capacity plan.
Approve and publish
capacity_plan fans out the downloads, backtests, and scenario forecasts across zones, renders the report, and waits for a planner. render_report passes do_flush=True, so the report is visible in the UI while the run waits on the approval that points to it.
@env.task(report=True)
async def capacity_plan(
zones: list[str] = list(ZONES),
model: str = "209M",
n_windows: int = 8,
context_length: int = 4096,
horizon: int = 168,
heat_shift_c: float = 0.0,
approval_timeout_hours: float = 24.0,
) -> flyte.io.File:
ercot = await load_ercot()
with flyte.group("weather"):
temperatures = await asyncio.gather(
*(fetch_temperature(zone, "2004-01-01", "2021-09-01") for zone in zones)
)
with flyte.group("backtest"):
backtests = await asyncio.gather(
*(
backtest_zone(ercot, temps, zone, model, n_windows, context_length, horizon)
for zone, temps in zip(zones, temperatures)
)
)
with flyte.group("plan"):
plans = await asyncio.gather(
*(
plan_zone(ercot, temps, zone, model, context_length, horizon, heat_shift_c)
for zone, temps in zip(zones, temperatures)
)
)
await render_report([s for scores in backtests for s in scores], plans)
margin = await approve_reserve_margin(plans, approval_timeout_hours)
return await publish_plan(plans, margin)
approve_reserve_margin creates a float condition. The planner reviews the report and enters the reserve margin to apply on top of each zone’s worst-case peak.
async def approve_reserve_margin(plans: list[ZonePlan], timeout_hours: float) -> float:
"""Pause until a planner enters the reserve margin. A margin of 0 or less
rejects the plan; no answer before the timeout fails the run."""
total = sum(p.p99_peak_mw for p in plans)
condition = await flyte.new_condition.aio(
"reserve-margin",
prompt=(
f"Worst-case peak across zones: {total:,.0f} MW (see the report). "
"Enter the reserve margin in percent to publish the plan, or 0 to reject it."
),
data_type=float,
timeout=timedelta(hours=timeout_hours),
)
margin = await condition.wait.aio()
if margin <= 0:
raise flyte.errors.RuntimeUserError(
"PlanRejected", "The planner rejected the capacity plan."
)
return margin
The run waits up to approval_timeout_hours, 24 by default. While it waits, every upstream result is already stored. If the run fails at this point, from a timeout or a rejection, running it again with the same inputs reuses the cached downloads, backtests, and scenario forecasts, and goes straight back to the approval. See External conditions and Caching.
The published plan has one row per zone:
| Column | Meaning |
|---|---|
median_peak_mw |
Median, across scenarios, of the week’s peak median forecast |
p99_peak_mw |
The worst scenario’s peak 99th-percentile forecast |
worst_weather_year |
The year whose weather produced that worst case |
planned_capacity_mw |
p99_peak_mw plus the approved reserve margin |