Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ This repository contains a diverse collection of Dash applications that showcase
- **[Montreal Metro Incidents](./montreal-metro-incidents/)** - Transit incident data analysis and visualization
- **[Montreal Events](./montreal-events/)** - Event tracking and analytics dashboard
- **[Coffee Flavours](./coffee-flavours/)** - Coffee data visualization and analysis
- **[Wind Energy Demo](./wind-energy-demo/)** - Power flows between U.S. grid operators and hub-height wind during winter storms Uri and Elliott, on real EIA-930 and ERA5 data

### 📰 Content & News
- **[Dash News](./dash-news/)** - Modern, responsive news dashboard template
Expand Down
4 changes: 4 additions & 0 deletions wind-energy-demo/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
__pycache__/
.venv/
.DS_Store
data_raw/
1 change: 1 addition & 0 deletions wind-energy-demo/.python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.13
1 change: 1 addition & 0 deletions wind-energy-demo/Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: gunicorn app:server --workers 2 --timeout 120 --preload
78 changes: 78 additions & 0 deletions wind-energy-demo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Wind Energy Demo

![Screenshot of app](assets/screenshot.png)

A two-page Dash app for a **post-event grid review**: during a stress event, where was power flowing between U.S. grid operators, and what was the wind doing? Everything runs on real public data: EIA-930, EIA-860, ERA5 reanalysis and the USGS Wind Turbine Database. It covers three events: Winter Storm Uri (Feb 2021), Winter Storm Elliott (Dec 2022), and the Lower-48 peak-demand week of 2026, which is chosen from the data.

| Page | Path | Plotly feature it shows off |
|---|---|---|
| **Grid Flows** | `/` | A MapLibre map (`go.Scattermap`) played back hour by hour with `dash.Patch`. Particles flow along each interchange arc in the direction power moved. Clicking a grid operator opens its fuel mix, where the unified tooltip ranks fuels by output with **`layout.hoversort`** (Plotly.js 3.6). |
| **Wind Field** | `/wind-field` | The new **`go.Quiver`** trace (Plotly.js 4.0) draws 775 ERA5 grid cells of 100 m wind as arrows colored by speed. A side chart uses **`layout.clickanywhere`** (Plotly.js 3.5), so clicking anywhere on it moves the map to that hour. |

**Stack:** Dash 4.5.1, Plotly 7.2.0 (Plotly.js 4.1.1), Dash Mantine Components 3.0.0 (React 19), pandas and numpy.

## Run

```bash
python3 -m venv .venv
.venv/bin/pip install -r requirements.txt
.venv/bin/python app.py # http://127.0.0.1:8062 (PORT=… to change, DASH_DEBUG=0 to hide dev tools)
# production (what the Procfile runs): gunicorn app:server --workers 2 --timeout 120 --preload
```

The app reads only `data/`, a compact snapshot of about 3.7 MB. To publish it, upload this folder at [cloud.plotly.com](https://cloud.plotly.com).

## Refresh the data

The scripts need two extra packages, so install `requirements-dev.txt` first:

```bash
.venv/bin/pip install -r requirements-dev.txt
.venv/bin/python -I scripts/fetch_eia930.py # EIA-930 BALANCE + INTERCHANGE six-month files (~570 MB, cached in data_raw/)
.venv/bin/python -I scripts/fetch_plants.py # EIA-860 generators via Catalyst Cooperative PUDL
.venv/bin/python -I scripts/fetch_turbines.py # USGS U.S. Wind Turbine Database
.venv/bin/python -I scripts/fetch_outlines.py # state + Mexico outlines for the Wind Field basemap
curl -o data_raw/EIA930_Reference_Tables.xlsx https://www.eia.gov/electricity/930-content/EIA930_Reference_Tables.xlsx
.venv/bin/python -I scripts/build_snapshot.py # -> data/*.csv.gz, nodes, events.json, …
.venv/bin/python -I scripts/fetch_era5.py # -> data/era5_<event>.npz (reads events.json; ~2.3k Open-Meteo calls)
```

`data_raw/` is gitignored. Delete a file there to force a fresh download. To add an event, edit `FIXED_EVENTS` in `scripts/common.py`.

## Sources (retrieved 2026-11-27)

| Data | Source | License |
|---|---|---|
| Hourly demand, day-ahead demand forecast, net generation by fuel, interchange per balancing authority (BA) | EIA Hourly Electric Grid Monitor (Form EIA-930) six-month files, <https://www.eia.gov/electricity/gridmonitor/> | Public domain |
| BA names, regions, generation-only flags | EIA-930 reference tables | Public domain |
| Power plants: location, BA, capacity, fuel | EIA-860 via Catalyst Cooperative PUDL (`out_eia__yearly_generators`), <https://catalyst.coop/pudl/> | CC-BY-4.0 (PUDL); EIA data public domain |
| Wind at 100 m, hourly | ERA5 reanalysis (Copernicus Climate Change Service / ECMWF) via the Open-Meteo historical API, <https://open-meteo.com/en/docs/historical-weather-api> | CC BY 4.0 |
| Wind projects | USGS U.S. Wind Turbine Database, <https://energy.usgs.gov/uswtdb/> | Public domain |
| Outlines | US states: PublicaMundi `us-states.json`; Mexico: Natural Earth 50m admin-0 | Public domain |

## Numbers checked against the snapshot

| Fact | Value | How |
|---|---|---|
| Lower-48 peak demand hour of 2026 (through 27 Nov) | 753,630 MW at 17:00 CT on 2 Jul 2026 | Sum of EIA-930 adjusted demand over U.S. non-generation-only BAs, hours with ≥95% of BAs reporting |
| ERCOT's largest gap between forecast and served demand during Uri | 28,885 MW at 20:00 CT on 15 Feb 2021 (forecast 73,149 MW, served 44,264 MW) | EIA-930 `Demand Forecast` − `Demand (Adjusted)` |
| Interchange links reported by both sides | 92% of link-hours | `n_reports == 2` in `links_hourly.csv.gz` |
| ERA5 spot check | 10.91 m/s from 32° at 33°N 101°W, 18:00 UTC 14 Feb 2021 | `era5_uri-2021.npz` matches a direct API call |

## Methods and caveats

- **Time.** Every event window is in U.S. Central time. EIA-930 timestamps are hour-ending in UTC, and ERA5 is sampled at the same UTC timestamps.
- **Served vs forecast.** EIA-930 has no load-shed field. Demand served below the day-ahead forecast is how rolling outages show up, but the gap also includes forecast error. The app labels it as a gap against forecast, not as load shed. A node is flagged when served demand is more than 5% below a forecast of at least 1 GW.
- **Fuels.** The data uses 8 fuel groups, so the categorical palette stays colorblind safe. Oil, geothermal, "other", and "unknown" are folded into *Other*. From 2025 EIA-930 splits solar and wind "with/without integrated battery storage"; those are summed back into *Solar* and *Wind*, and battery, other, and unknown storage become *Battery*. Adjusted values are used where EIA publishes them, otherwise raw values.
- **Where nodes are drawn.** Each BA sits at the capacity-weighted centroid of its EIA-860 plants, using the EIA-860 year before the event. Overlapping nodes are nudged apart, with bigger nodes moving less, so positions are schematic. BAs created in 2025–26 are placed at the plants they were formed from: SWPW from WACM and WAUW, BHBA from Black Hills Power, and SIKE from the City of Sikeston. Canadian and Mexican neighbors have no EIA-860 plants, so they are drawn at their main load center (approximate), and CENACE gets one node per border area.
- **Links.** Each BA pair is one link: the average of A's report and the negative of B's. Particles move from the exporting side to the importing side. Their number and speed scale with MW.
- **Wind.** ERA5 is 0.25° reanalysis. It is sampled on a 1° grid over 112–82°W and 25–49°N. "100 m wind at projects" is the capacity-weighted speed at the nearest grid cell to each USWTDB project online by the event year. The 3, 12, and 25 m/s colorbar ticks are typical cut-in, rated, and cut-out speeds, not those of a specific turbine.
- **Colors** were validated with the dataviz skill's `validate_palette.js` on the white chart surface. For the fuels, the worst adjacent colorblind ΔE is 10.7 and the worst normal-vision ΔE is 18.6. Wind speed uses a single-hue charcoal ramp. Net position is a charcoal ↔ slate ↔ peach diverging scale.

## How it's built

- **`figures/flow_map.py`** uses the wildfire app's map pattern. A pure `map_state(event, hour, ba)` feeds the first figure and every hourly `Patch` by trace index, so the 14k plants are sent once. Link width classes and node color classes are separate traces, because MapLibre won't render per-point size *and* color in one Scattermap trace.
- **`assets/js/flow-particles.js`** draws the moving particles and the pulsing stress rings on a transparent `<canvas>` inside the map's canvas container. It places them each frame with `map.project()`, so they follow pan, zoom and pitch. It reads the hour's flows from `layout.meta`, so 60 fps motion never goes through Dash. It doesn't use a MapLibre GeoJSON layer, for this reason: plotly.js resolves map updates only on a render where `map.loaded()` is true. Calling `setData` every frame keeps a source "loading" forever, and `dcc.Graph` then stops applying Patches. The script respects `prefers-reduced-motion`.
- **`assets/js/time.js`** is the only writer of the `{event, hour}` store; this is the wildfire `day.js` pattern. The map and quiver callbacks hold `busy-*` flags, so playback skips ticks instead of queueing them.
- **Both pages stay mounted** and are shown or hidden by URL, so every callback's components always exist.
- **plotly.js 4.1.1 quirk.** On stacked areas, the unified tooltip is built in legend order. With `showlegend=False`, that falls back to the stack's reversed order, which flips `hoversort` ("value descending" shows smallest-first). The fuel-mix chart therefore keeps a visible legend pinned to `traceorder="normal"`.
181 changes: 181 additions & 0 deletions wind-energy-demo/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
"""Wind Energy Demo — a two-page Dash app on real U.S. grid and wind data.

Grid Flows (/) animated MapLibre map of hourly interchange (EIA-930)
Wind Field (/wind-field) ERA5 hub-height wind with Plotly.js 4's quiver trace

Run: .venv/bin/python app.py -> http://127.0.0.1:8062
Data: the snapshot in data/ (rebuild with the scripts in scripts/, see README.md)

Both pages stay mounted and are shown/hidden by URL (pattern from the wildfire app), so
the shared time bar, stores and playback interval always exist and every callback's
components are always in the layout.
"""

import os

from dash import _dash_renderer

_dash_renderer._set_react_version("19.2.4") # Dash Mantine Components 3 needs React 19 (Dash 4.5 bundles it)

import dash_mantine_components as dmc # noqa: E402
from dash import ClientsideFunction, Dash, Input, Output, State, callback, clientside_callback, dcc, html # noqa: E402

import data_store as ds
import theme # noqa: F401 (registers the "griddesk" Plotly template)
from components import NAV_ITEMS, header, time_bar
from figures.charts import local_x
from pages import grid_flows, wind_field
from theme import MANTINE_THEME
from why_plotly import add_why_plotly

app = Dash(
__name__,
title="Wind Energy Demo",
update_title=None, # the default "Updating..." flickers the tab on every playback tick
suppress_callback_exceptions=True,
meta_tags=[{"name": "viewport", "content": "width=device-width, initial-scale=1"}],
)
server = app.server


def time_meta() -> dict:
"""Static per-event data for the clientside time controller."""
out = {}
for ev in ds.EVENT_ORDER:
hrs = ds.hours(ev)
loc = hrs.tz_convert(ds.LOCAL_TZ)
n_days = len({t.date() for t in loc})
step = 1 if n_days <= 8 else 2
marks, seen = [], 0
for k, t in enumerate(loc):
if t.hour == 0 and t.minute == 0:
if seen % step == 0:
marks.append({"value": k, "label": f"{t:%b %-d}"})
seen += 1
out[ev] = {
"n": len(hrs),
"x": local_x(ev),
"labels": [ds.hour_label(ev, k) for k in range(len(hrs))],
"marks": marks,
"featured": ds.featured_hour(ev),
"label": ds.events()[ev]["label"],
}
return out


def serve_layout():
event = ds.EVENT_ORDER[0]
i = ds.featured_hour(event)
return dmc.MantineProvider(
[
dcc.Location(id="url", refresh=False),
dcc.Store(id="selection", data={"event": event, "i": i}),
dcc.Store(id="current-event", data=event),
dcc.Store(id="time-meta", data=time_meta()),
dcc.Store(id="ba-select", data=grid_flows.DEFAULT_BA),
dcc.Store(id="node-curves", data=grid_flows.NODE_CURVES),
dcc.Store(id="jump"),
dcc.Store(id="busy-map", data=False),
dcc.Store(id="busy-wind", data=False),
dcc.Store(id="flow-map-event", data=event),
dcc.Store(id="quiver-event", data=event),
dcc.Interval(id="playback-interval", interval=450, disabled=True),
dmc.AppShell(
[
header(),
dmc.AppShellMain(
html.Div(
[time_bar(), grid_flows.layout(), wind_field.layout()],
className="main-inner",
id="main-inner",
)
),
],
header={"height": 64},
padding=0,
className="app-shell",
),
],
theme=MANTINE_THEME,
forceColorScheme="light",
)


app.layout = serve_layout
add_why_plotly(app, "wind-energy-demo", floating=False) # buttons are rendered in the header (components.header)


# ── Routing: show one page, mark its nav link ─────────────────────────────────
@callback(
Output("page-flows", "style"),
Output("page-wind", "style"),
Output("main-inner", "className"),
*[Output(item["id"], "className") for item in NAV_ITEMS],
Input("url", "pathname"),
)
def route(pathname):
wind = pathname == wind_field.PATH
show, hide = {}, {"display": "none"}
tab = lambda on: "hdr-tab active" if on else "hdr-tab" # noqa: E731
return (hide if wind else show), (show if wind else hide), ("main-inner on-wind" if wind else "main-inner on-flows"), tab(not wind), tab(wind)


# ── Time: clientside single writer + playback ─────────────────────────────────
clientside_callback(
ClientsideFunction(namespace="time", function_name="setTime"),
Output("selection", "data"),
Output("current-event", "data"),
Output("hour-slider", "value"),
Output("hour-slider", "max"),
Output("hour-slider", "marks"),
Output("hour-label", "children"),
Output("playback-interval", "disabled", allow_duplicate=True),
Input("event", "value"),
Input("hour-slider", "value"),
Input("prev-btn", "n_clicks"),
Input("next-btn", "n_clicks"),
Input("play-btn", "n_clicks"),
Input("playback-interval", "n_intervals"),
Input("jump", "data"),
State("selection", "data"),
State("busy-map", "data"),
State("busy-wind", "data"),
State("time-meta", "data"),
prevent_initial_call="initial_duplicate",
)


@callback(
Output("playback-interval", "disabled"),
Input("play-btn", "n_clicks"),
State("playback-interval", "disabled"),
prevent_initial_call=True,
)
def toggle_playback(_n, disabled):
return not disabled


@callback(Output("playback-interval", "interval"), Input("speed", "value"))
def set_speed(ms):
return int(ms)


@callback(
Output("play-btn", "children"),
Output("play-btn", "color"),
Input("playback-interval", "disabled"),
)
def play_ui(disabled):
from dash_iconify import DashIconify

playing = not disabled
return DashIconify(icon="tabler:player-pause-filled" if playing else "tabler:player-play-filled", width=16), ("peach.6" if playing else "charcoal")


@callback(Output("hdr-event", "children"), Input("current-event", "data"))
def header_event(event):
return ds.events()[event or ds.EVENT_ORDER[0]]["label"]


if __name__ == "__main__":
app.run(debug=os.environ.get("DASH_DEBUG", "1") == "1", port=int(os.environ.get("PORT", 8062)))
Loading
Loading