Add hourly usage snapshots, analysis layer, scorecard, tooltips & guided tour

- data-pipeline: hourly NDW snapshot job (occupancy + status) + GitHub Action;
  per-gemeente day files, current-status, daily-average rollup.
- webapp: usage-over-day chart in detail panel; fresh per-gemeente status colours;
  national analysis choropleth (LayerSwitcher) + gemeente scorecard with demand
  (peer-model), siting priority, congestion and live/potential net-impact scenario.
- analysis/ (Python): golden dataset (CBS Kerncijfers + chargers) -> derived
  metrics + models (demand, siting, congestion, municipal percentiles).
- UX: InfoTip tooltips throughout, expanded methodology modal, interactive
  guided tour (spotlight + blur) that drives the app to example screens.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Robbert Janssen
2026-06-02 22:01:28 +02:00
co-authored by Claude Opus 4.8
parent 55ecd88b78
commit 800ad823e9
717 changed files with 2839 additions and 54 deletions
+5
View File
@@ -0,0 +1,5 @@
.venv/
.cache/
data/
__pycache__/
*.pyc
+27
View File
@@ -0,0 +1,27 @@
# Laadpalenviewer — analysis (golden dataset)
Python layer that integrates open Dutch datasets into a "golden dataset" and
exports derived map layers consumed by the webapp. Phase 1 works at **gemeente
grain**; buurt/PC4 grain and more sources (BAG/BGT, NDW traffic, grid) follow.
## Sources (open tier)
- **CBS Kerncijfers wijken en buurten** `85984NED` (CC-BY) — demographics, income,
urbanisation, car ownership. Field keys live in `src/ingest/cbs.py`.
- **Charger supply/usage** — our own `webapp/public/data` (municipalities.json,
crop-out GeoJSONs, hourly snapshots).
- **PDOK CBS Gebiedsindelingen** — gemeente polygons for the choropleth.
## Run
```bash
cd analysis
python3 -m venv .venv && ./.venv/bin/pip install -r requirements.txt
./.venv/bin/python -m src.main # uses caches in .cache/
./.venv/bin/python -m src.main --refresh # re-fetch CBS/PDOK
```
Outputs:
- `data/gold_gemeente.{csv,parquet}` — the golden dataset (gitignored).
- `webapp/public/data/derived/gemeente-metrics.geojson` — choropleth layer (committed).
- `webapp/public/data/derived/metrics-meta.json` — metric list for the viewer.
The viewer's **Analyse (per gemeente)** switcher (national view) renders any metric
as a choropleth. Attribution: data © CBS (CC-BY), PDOK, NDW.
+5
View File
@@ -0,0 +1,5 @@
requests>=2.31
pandas>=2.2
pyarrow>=16
numpy>=1.26
scikit-learn>=1.4
View File
+80
View File
@@ -0,0 +1,80 @@
"""Export the golden dataset + models as a viewer choropleth layer + metadata."""
from __future__ import annotations
import json
import math
import pandas as pd
from .ingest.boundaries import fetch_gemeente_geojson
from .paths import DERIVED_DIR
# Choropleth-selectable metrics (order = display order). category groups the switcher.
METRICS = [
{"key": "chargers_per_1000_inw", "label": "Laadpunten per 1.000 inwoners", "unit": "", "decimals": 1, "category": "Aanbod",
"desc": "Aantal OCPI-laadlocaties (NDW) gedeeld door inwoners (CBS) × 1.000. Maat voor dekking."},
{"key": "chargers_per_1000_auto", "label": "Laadpunten per 1.000 auto's", "unit": "", "decimals": 1, "category": "Aanbod",
"desc": "Laadlocaties per 1.000 personenauto's (CBS autobezit). Dekking t.o.v. het wagenpark."},
{"key": "chargers_total", "label": "Laadpunten totaal", "unit": "", "decimals": 0, "category": "Aanbod",
"desc": "Totaal aantal OCPI-laadlocaties (personen + vracht) in de gemeente."},
{"key": "chargers_freight", "label": "Vracht-laadpunten", "unit": "", "decimals": 0, "category": "Aanbod",
"desc": "Laadpunten geclassificeerd als logistiek/vracht (≥350 kW DC, MCS/megawatt of truck-exploitant)."},
{"key": "power_per_1000_inw_kw", "label": "Vermogen per 1.000 inw.", "unit": "kW", "decimals": 0, "category": "Aanbod",
"desc": "Som van gerapporteerd connectorvermogen per 1.000 inwoners. Let op: NDW mist vermogen voor ±90% — onderschatting."},
{"key": "avg_occupancy", "label": "Gem. bezetting (snapshot)", "unit": "%", "decimals": 1, "category": "Gebruik",
"desc": "Gemiddeld aandeel connectoren dat 'laadt' over de geregistreerde snapshot-uren."},
{"key": "demand_per_1000_inw", "label": "Verwachte vraag (peer-model)", "unit": "/1.000 inw", "decimals": 1, "category": "Vraag",
"desc": "Door een random-forest voorspeld 'verwacht' aantal laadpunten o.b.v. demografie, per 1.000 inwoners."},
{"key": "supply_gap", "label": "Tekort/overschot t.o.v. verwacht", "unit": "laadpunten", "decimals": 0, "category": "Vraag",
"desc": "Werkelijk − verwacht aantal laadpunten. Negatief = minder aanbod dan vergelijkbare gemeenten."},
{"key": "siting_priority", "label": "Plaatsingsprioriteit (0-100)", "unit": "", "decimals": 0, "category": "Siting",
"desc": "Prioriteit voor bijplaatsen: combineert relatief + absoluut tekort en huidige bezetting. Hoger = meer behoefte."},
{"key": "load_per_1000_inw_kw", "label": "Gesch. piekbelasting /1.000 inw", "unit": "kW", "decimals": 1, "category": "Congestie",
"desc": "Gemodelleerde potentiële piek (alle EVSE's × ~11 kW × 30%) per 1.000 inwoners. Vermogen aangenomen."},
{"key": "congestion_index", "label": "Congestie-index (relatief)", "unit": "", "decimals": 0, "category": "Congestie",
"desc": "Relatieve percentielrang (0-100) van de piekbelasting per inwoner. NB: geen DSO-capaciteit ingelezen."},
{"key": "autos_per_huishouden", "label": "Auto's per huishouden", "unit": "", "decimals": 2, "category": "Demografie",
"desc": "CBS: personenauto's per huishouden — driver van laadbehoefte."},
{"key": "inkomen_per_inwoner", "label": "Gem. inkomen per inwoner", "unit": "×€1.000", "decimals": 1, "category": "Demografie",
"desc": "CBS gemiddeld inkomen per inwoner (×€1.000)."},
{"key": "stedelijkheid", "label": "Stedelijkheid (1=zeer sterk)", "unit": "", "decimals": 0, "category": "Demografie",
"desc": "CBS stedelijkheidsklasse 1 (zeer sterk stedelijk) t/m 5 (niet stedelijk)."},
]
# Extra fields carried in properties for the gemeente scorecard panel.
SCORECARD_COLS = [
"expected_chargers", "chargers_passenger", "inwoners", "autos_totaal",
"est_peak_load_kw", "potential_peak_load_kw", "live_peak_load_kw",
"evse_total", "charging_now", "occupancy_now",
"megawatt_sites", "supply_pct", "occupancy_pct", "gap_pct",
]
EXPORT_COLS = [m["key"] for m in METRICS] + SCORECARD_COLS
def _clean(v):
if v is None or (isinstance(v, float) and (math.isnan(v) or math.isinf(v))):
return None
return v
def export_layer(gold: pd.DataFrame) -> None:
print("Exporting derived viewer layer...")
fc = fetch_gemeente_geojson()
by_code = {c: gold.loc[c] for c in gold.index}
for feat in fc["features"]:
code = feat["properties"].get("statcode")
props = {"code": code, "gemeente": feat["properties"].get("statnaam")}
row = by_code.get(code)
if row is not None:
props["slug"] = row.get("slug")
for col in EXPORT_COLS:
val = row.get(col)
props[col] = _clean(float(val)) if pd.notna(val) else None
feat["properties"] = props
meta = {"metrics": METRICS, "model": gold.attrs.get("model_metrics", {})}
fc["metadata"] = meta
DERIVED_DIR.mkdir(parents=True, exist_ok=True)
(DERIVED_DIR / "gemeente-metrics.geojson").write_text(json.dumps(fc))
(DERIVED_DIR / "metrics-meta.json").write_text(json.dumps(meta, ensure_ascii=False, indent=2))
n = sum(1 for f in fc["features"] if f["properties"].get("chargers_total") is not None)
print(f" wrote gemeente-metrics.geojson ({n}/{len(fc['features'])} gemeenten with data)")
+38
View File
@@ -0,0 +1,38 @@
"""Assemble the gemeente-grain golden dataset and derived metrics."""
from __future__ import annotations
import pandas as pd
from .ingest.cbs import fetch_cbs_gemeente
from .ingest.chargers import fetch_chargers
from .models import add_models
from .paths import GOLD_DIR
def build_gold(refresh: bool = False) -> pd.DataFrame:
print("Building golden dataset (gemeente grain)...")
chargers = fetch_chargers()
cbs = fetch_cbs_gemeente(refresh=refresh)
df = chargers.join(cbs, how="left")
df["chargers_total"] = df["chargers_passenger"] + df["chargers_freight"]
# Prefer CBS population; fall back to municipalities.json population.
pop = df["inwoners"].fillna(df["population"]).replace(0, pd.NA)
autos = df["autos_totaal"].replace(0, pd.NA)
df["chargers_per_1000_inw"] = (df["chargers_total"] / pop * 1000).round(2)
df["chargers_per_1000_auto"] = (df["chargers_total"] / autos * 1000).round(2)
df["autos_per_charger"] = (autos / df["chargers_total"].replace(0, pd.NA)).round(1)
df["power_per_1000_inw_kw"] = (df["total_power_kw"] / pop * 1000).round(1)
# Phases 2-5 models (demand, siting, congestion/net-impact, municipal).
df = add_models(df)
GOLD_DIR.mkdir(parents=True, exist_ok=True)
df.to_csv(GOLD_DIR / "gold_gemeente.csv")
try:
df.to_parquet(GOLD_DIR / "gold_gemeente.parquet")
except Exception as e: # pyarrow missing -> CSV still written
print(f" (parquet skipped: {e})")
print(f" golden dataset: {len(df)} gemeenten, {df.shape[1]} columns")
return df
View File
+30
View File
@@ -0,0 +1,30 @@
"""Gemeente polygons (PDOK CBS Gebiedsindelingen WFS, GeoJSON, EPSG:4326)."""
from __future__ import annotations
import json
import requests
from ..paths import CACHE_DIR
YEAR = "2025"
WFS = f"https://service.pdok.nl/cbs/gebiedsindelingen/{YEAR}/wfs/v1_0"
def fetch_gemeente_geojson(refresh: bool = False) -> dict:
cache = CACHE_DIR / f"gemeenten_{YEAR}.geojson"
if cache.exists() and not refresh:
return json.loads(cache.read_text())
params = {
"service": "WFS",
"version": "2.0.0",
"request": "GetFeature",
"typeName": "gebiedsindelingen:gemeente_gegeneraliseerd",
"outputFormat": "application/json",
"srsName": "EPSG:4326",
"count": "1000",
"startIndex": "0",
}
r = requests.get(WFS, params=params, headers={"Accept": "application/json"}, timeout=120)
r.raise_for_status()
fc = r.json()
cache.write_text(json.dumps(fc))
print(f" [boundaries] {len(fc.get('features', []))} gemeente polygons")
return fc
+55
View File
@@ -0,0 +1,55 @@
"""Ingest CBS Kerncijfers wijken en buurten (gemeente grain) via OData v3.
Open data, CC-BY 4.0 (attribution: Centraal Bureau voor de Statistiek).
Table 85984NED (2024). Field keys are version-suffixed; kept in one place here.
"""
from __future__ import annotations
import json
import time
from pathlib import Path
import requests
import pandas as pd
from ..paths import CACHE_DIR
TABLE = "85984NED"
BASE = f"https://opendata.cbs.nl/ODataApi/OData/{TABLE}"
# CBS measure key -> our column name (keys confirmed from DataProperties).
FIELDS = {
"AantalInwoners_5": "inwoners",
"HuishoudensTotaal_29": "huishoudens",
"GemiddeldInkomenPerInwoner_78": "inkomen_per_inwoner",
"PersonenautoSTotaal_104": "autos_totaal",
"PersonenautoSPerHuishouden_107": "autos_per_huishouden",
"PersonenautoSOverigeBrandstof_106": "autos_overige_brandstof",
"MateVanStedelijkheid_120": "stedelijkheid",
"Omgevingsadressendichtheid_121": "adresdichtheid",
}
def fetch_cbs_gemeente(refresh: bool = False) -> pd.DataFrame:
cache = CACHE_DIR / f"cbs_{TABLE}_gemeente.json"
if cache.exists() and not refresh:
rows = json.loads(cache.read_text())
else:
select = ",".join(["WijkenEnBuurten", *FIELDS.keys()])
# Gemeente rows only (codes start with 'GM').
url = f"{BASE}/TypedDataSet?$select={select}&$filter=startswith(WijkenEnBuurten,'GM')"
rows = []
while url:
r = requests.get(url, headers={"Accept": "application/json"}, timeout=60)
r.raise_for_status()
payload = r.json()
rows.extend(payload.get("value", []))
url = payload.get("odata.nextLink") or payload.get("@odata.nextLink")
if url:
time.sleep(0.2)
cache.write_text(json.dumps(rows))
df = pd.DataFrame(rows)
df = df.rename(columns={**FIELDS, "WijkenEnBuurten": "code"})
df["code"] = df["code"].str.strip()
for col in FIELDS.values():
df[col] = pd.to_numeric(df[col], errors="coerce")
print(f" [cbs] {len(df)} gemeenten from {TABLE}")
return df.set_index("code")
+83
View File
@@ -0,0 +1,83 @@
"""Charger supply + usage per gemeente, from our own committed artifacts.
- supply: municipalities.json (counts) + crop-out GeoJSONs (power, megawatt)
- usage: latest per-gemeente snapshot day file (avg occupancy %)
"""
from __future__ import annotations
import json
import pandas as pd
from ..paths import MUNICIPALITIES_JSON, GEMEENTEN_DIR, SNAPSHOTS_DIR
def _latest_day(slug: str) -> dict | None:
d = SNAPSHOTS_DIR / slug
if not d.is_dir():
return None
days = sorted(p for p in d.glob("*.json") if p.name != "daily.json")
return json.loads(days[-1].read_text()) if days else None
def _snapshot_metrics(slug: str) -> dict:
"""avg occupancy + live EVSE totals/charging-now from the latest snapshot."""
data = _latest_day(slug)
if not data:
return {"avg_occupancy": None, "evse_total": None, "charging_now": None, "occupancy_now": None}
all_occ: list[float] = []
evse_total = 0
charging_now = 0
for loc in data.get("locations", {}).values():
n = loc.get("n") or 0
occ_arr = [v for v in loc.get("occ", []) if v is not None]
if occ_arr:
all_occ.extend(occ_arr)
latest = occ_arr[-1] # most recent recorded hour
charging_now += round(latest / 100 * n)
evse_total += n
avg = round(sum(all_occ) / len(all_occ), 1) if all_occ else None
occ_now = round(100 * charging_now / evse_total, 1) if evse_total else None
return {"avg_occupancy": avg, "evse_total": evse_total, "charging_now": charging_now, "occupancy_now": occ_now}
def _crop_power(slug: str) -> tuple[float, int]:
"""Sum of max power (kW) and megawatt-location count for a gemeente."""
f = GEMEENTEN_DIR / f"{slug}.geojson"
if not f.exists():
return 0.0, 0
data = json.loads(f.read_text())
power = 0.0
mw = 0
for feat in data.get("features", []):
p = feat.get("properties", {})
if p.get("type") == "charge":
power += p.get("maxPowerKw") or 0
if p.get("isMegawatt"):
mw += 1
return power, mw
def fetch_chargers() -> pd.DataFrame:
munis = json.loads(MUNICIPALITIES_JSON.read_text())
rows = []
for m in munis:
if not m.get("code"): # skip 'nederland'
continue
slug = m["slug"]
power, mw = _crop_power(slug)
snap = _snapshot_metrics(slug)
rows.append({
"code": m["code"],
"name": m["name"],
"slug": slug,
"population": m.get("population") or 0,
"chargers_passenger": m.get("passengerCount") or 0,
"chargers_freight": m.get("freightCount") or 0,
"total_power_kw": round(power),
"megawatt_sites": mw,
"avg_occupancy": snap["avg_occupancy"],
"evse_total": snap["evse_total"],
"charging_now": snap["charging_now"],
"occupancy_now": snap["occupancy_now"],
})
df = pd.DataFrame(rows)
print(f" [chargers] {len(df)} gemeenten from municipalities.json + crop-outs")
return df.set_index("code")
+17
View File
@@ -0,0 +1,17 @@
"""Phase 1 analysis pipeline: golden dataset (gemeente) -> viewer layer."""
from __future__ import annotations
import sys
from .gold import build_gold
from .export import export_layer
def main() -> None:
refresh = "--refresh" in sys.argv
print("\n=== Laadpalenviewer analysis ===\n")
gold = build_gold(refresh=refresh)
export_layer(gold)
print("\n=== Analysis done ===\n")
if __name__ == "__main__":
main()
+84
View File
@@ -0,0 +1,84 @@
"""Phase 2-5 models on the gemeente-grain golden dataset.
All transparent and documented. Where real grid-capacity data is not ingested
(open Capaciteitskaart is viewer-only), congestion is a MODELLED index, flagged.
"""
from __future__ import annotations
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_val_predict, KFold
from sklearn.metrics import r2_score, mean_absolute_error
# Demand model features (socio-demographic drivers of charging demand).
FEATURES = [
"inwoners", "huishoudens", "autos_totaal", "autos_per_huishouden",
"inkomen_per_inwoner", "stedelijkheid", "adresdichtheid",
]
TARGET = "chargers_passenger"
# Load-model constants (documented, tunable).
# NDW omits max_electric_power for ~90% of connectors, so power MUST be assumed.
ASSUMED_EVSE_KW = 11.0 # blended assumed draw per EVSE (mostly AC)
AVG_FREIGHT_KW = 150.0 # typical HPC/truck connector draw
CONCURRENCY = 0.30 # planning concurrency for the potential peak
def _pct_rank(s: pd.Series) -> pd.Series:
return (s.rank(pct=True) * 100).round(0)
def add_models(df: pd.DataFrame) -> pd.DataFrame:
df = df.copy()
# ---- P2: demand (peer benchmark) ----
X = df[FEATURES].apply(lambda c: c.fillna(c.median()), axis=0)
y = df[TARGET].fillna(0).astype(float)
model = RandomForestRegressor(n_estimators=300, min_samples_leaf=3, random_state=42, n_jobs=-1)
cv = KFold(n_splits=5, shuffle=True, random_state=42)
oof = cross_val_predict(model, X, y, cv=cv, n_jobs=-1)
oof = np.clip(oof, 0, None)
df["expected_chargers"] = oof.round(0)
df["supply_gap"] = (y - oof).round(0) # actual - expected; <0 = underserved
pop = df["inwoners"].fillna(df["population"]).replace(0, np.nan)
df["demand_per_1000_inw"] = (df["expected_chargers"] / pop * 1000).round(2)
# fit on all for feature importance + reported metrics
model.fit(X, y)
metrics = {
"r2_oof": round(float(r2_score(y, oof)), 3),
"mae_oof": round(float(mean_absolute_error(y, oof)), 1),
"feature_importance": dict(zip(FEATURES, model.feature_importances_.round(3).tolist())),
}
# ---- P3: optimal siting (gap-driven priority) ----
deficit = (df["expected_chargers"] - y).clip(lower=0) # how many short
rel_deficit = (deficit / df["expected_chargers"].replace(0, np.nan)).fillna(0)
occ = df["avg_occupancy"].fillna(df["avg_occupancy"].median() if df["avg_occupancy"].notna().any() else 0)
occ_norm = occ / 100.0
# priority blends absolute shortfall, relative shortfall, and usage pressure
raw = 0.5 * rel_deficit + 0.3 * (deficit / (deficit.max() or 1)) + 0.2 * occ_norm
df["siting_priority"] = (raw / (raw.max() or 1) * 100).round(0)
# ---- P4: congestion risk + net impact ----
# EVSE count: prefer live snapshot total; fall back to locations if no snapshot.
evse = df["evse_total"].fillna(df["chargers_passenger"].fillna(0) + df["chargers_freight"].fillna(0))
# Potential peak (planning): all EVSEs x assumed kW x concurrency.
df["potential_peak_load_kw"] = (evse * ASSUMED_EVSE_KW * CONCURRENCY).round(0)
# Live peak now (grounded in OCPI status): EVSEs charging now x assumed kW.
df["live_peak_load_kw"] = (df["charging_now"] * ASSUMED_EVSE_KW).round(0)
# Scenario base = potential peak; kept as est_peak_load_kw for the scorecard slider.
df["est_peak_load_kw"] = df["potential_peak_load_kw"]
df["load_per_1000_inw_kw"] = (df["potential_peak_load_kw"] / pop * 1000).round(1)
df["congestion_index"] = _pct_rank(df["load_per_1000_inw_kw"]) # 0-100 relative
# ---- P5: municipal percentiles (for scorecard) ----
df["supply_pct"] = _pct_rank(df["chargers_per_1000_inw"])
df["occupancy_pct"] = _pct_rank(df["avg_occupancy"]) if df["avg_occupancy"].notna().any() else np.nan
df["gap_pct"] = _pct_rank(-df["supply_gap"]) # high = more underserved
df.attrs["model_metrics"] = metrics
print(f" [models] demand OOF R²={metrics['r2_oof']} MAE={metrics['mae_oof']}; "
f"top feature={max(metrics['feature_importance'], key=metrics['feature_importance'].get)}")
return df
+18
View File
@@ -0,0 +1,18 @@
"""Filesystem paths for the analysis layer."""
from pathlib import Path
ANALYSIS_ROOT = Path(__file__).resolve().parent.parent
PROJECT_ROOT = ANALYSIS_ROOT.parent
CACHE_DIR = ANALYSIS_ROOT / ".cache"
GOLD_DIR = ANALYSIS_ROOT / "data" # golden dataset outputs (parquet/csv)
WEBAPP_PUBLIC = PROJECT_ROOT / "webapp" / "public"
DATA_DIR = WEBAPP_PUBLIC / "data"
GEMEENTEN_DIR = DATA_DIR / "gemeenten"
SNAPSHOTS_DIR = DATA_DIR / "snapshots"
DERIVED_DIR = DATA_DIR / "derived"
MUNICIPALITIES_JSON = WEBAPP_PUBLIC / "municipalities.json"
for d in (CACHE_DIR, GOLD_DIR, DERIVED_DIR):
d.mkdir(parents=True, exist_ok=True)