From cbd4531574a69045397bfed6841903fe6fa6294c Mon Sep 17 00:00:00 2001 From: robbertjanssen85 <91183957+robbertjanssen85@users.noreply.github.com> Date: Tue, 7 Jul 2026 01:08:27 +0200 Subject: [PATCH] Rework freight classification and fix analysis/webapp derivations Freight classification v2: two-tier freightKind ('dedicated' via truck operator, truck-named location (forklifts excluded), MCS, logistics depot >=150 kW DC, or curated hub; 'hpc' for power-only >=350 kW DC) with freightReason carried through to the map and detail panel. Connector power is now derived from V x A when max_electric_power is missing or implausible (caps out NDW garbage like 7.36 MW on a 22 kW AC post), eliminating all zero-kW points. Adds Milence Waddinxveen to curated hubs and a nearest-gemeente fallback so coastal/industrial sites get detail bundles. Tariff matching now honors one-sided time windows. Analysis: peak load finally uses the 150 kW freight constant (was priced at 11 kW), crop stats split by layer so freight no longer skews supply/price metrics, occupancy is EVSE-weighted, charging_now samples one common hour, and a new Logistiek metric group exports chargers_freight/freight_dedicated/ freight_power_kw. Relabels peer-model outputs as modelled supply. Webapp: freight markers colored by kind with status ring, dedicated-only filter, filter counts respect the power filter, status tallies scoped to passenger, national-view detail panel can jump into the point's gemeente, connector kW display mirrors the pipeline derivation. Co-Authored-By: Claude Fable 5 --- analysis/src/export.py | 22 +++--- analysis/src/ingest/chargers.py | 72 +++++++++++++----- analysis/src/models.py | 17 ++++- data-pipeline/data/curated-hubs.json | 12 +++ data-pipeline/src/assignGemeente.ts | 31 ++++++++ data-pipeline/src/classifyFreight.ts | 92 ++++++++++++++++++----- data-pipeline/src/index.ts | 10 ++- data-pipeline/src/sources/curated.ts | 2 + data-pipeline/src/sources/merge.ts | 7 ++ data-pipeline/src/tariff.ts | 12 ++- data-pipeline/src/types.ts | 13 ++++ data-pipeline/src/writeOutputs.ts | 16 ++-- webapp/app/page.tsx | 39 +++++++++- webapp/components/AboutModal.tsx | 9 ++- webapp/components/FilterPanel.tsx | 24 +++++- webapp/components/LocationDetailPanel.tsx | 37 ++++++++- webapp/components/MapDeck.tsx | 47 +++++++++--- webapp/components/StatsPanel.tsx | 26 +++++-- webapp/lib/colors.ts | 9 ++- webapp/lib/pointInGemeente.ts | 40 ++++++++++ webapp/types/charging.ts | 9 +++ 21 files changed, 452 insertions(+), 94 deletions(-) create mode 100644 webapp/lib/pointInGemeente.ts diff --git a/analysis/src/export.py b/analysis/src/export.py index 9f38261143..10dfdb7638 100644 --- a/analysis/src/export.py +++ b/analysis/src/export.py @@ -14,22 +14,26 @@ METRICS = [ "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."}, + "desc": "Som van het max. connectorvermogen per 1.000 inwoners (personen + vracht). Vermogen afgeleid uit spanning × stroomsterkte waar NDW het niet rapporteert."}, + {"key": "chargers_freight", "label": "Truck-laadlocaties", "unit": "", "decimals": 0, "category": "Logistiek", + "desc": "Locaties voor truckladen: dedicated voorzieningen (truck-operator, 'truck' in naam, MCS, logistiek depot) plus truck-capable snelladers (≥350 kW DC)."}, + {"key": "freight_dedicated", "label": "Dedicated truck-locaties", "unit": "", "decimals": 0, "category": "Logistiek", + "desc": "Locaties met een expliciet trucksignaal: exploitant (Milence/WattHub), 'truck' in de naam, MCS-aansluiting, logistiek depot met ≥150 kW DC, of gecureerde hub. Exclusief locaties die alleen op vermogen kwalificeren."}, + {"key": "freight_power_kw", "label": "Truck-laadvermogen", "unit": "kW", "decimals": 0, "category": "Logistiek", + "desc": "Som van het max. connectorvermogen van truck-laadlocaties in de gemeente. Indicatie van logistieke laadcapaciteit (bays per site niet meegenomen)."}, {"key": "avg_occupancy", "label": "Gem. bezetting (snapshot)", "unit": "%", "decimals": 1, "category": "Gebruik", "desc": "Gemiddeld aandeel connectoren dat 'laadt' over de geregistreerde snapshot-uren."}, {"key": "price_kwh_median", "label": "Mediaan tarief (€/kWh)", "unit": "€/kWh", "decimals": 3, "category": "Prijs", "desc": "Mediaan van het actuele energietarief (€/kWh) uit de OCPI-tarieven (NDW) over laadlocaties met een gepubliceerde prijs. ±50% van de connectoren publiceert geen tarief; momentopname uit de laatste data-update."}, - {"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": "demand_per_1000_inw", "label": "Verwacht aanbod (peer-model)", "unit": "/1.000 inw", "decimals": 1, "category": "Vraag", + "desc": "Door een random-forest voorspeld aantal laadpunten o.b.v. demografie, per 1.000 inwoners. Peer-benchmark van het aanbod, geen gemeten vraag."}, + {"key": "supply_gap", "label": "Afwijking t.o.v. peers", "unit": "laadpunten", "decimals": 0, "category": "Vraag", + "desc": "Werkelijk − verwacht (peer-model) aantal laadpunten. Negatief = minder aanbod dan demografisch vergelijkbare gemeenten. Gemodelleerd; NDW-dekkingsgaten (bijv. Amsterdam) kleuren dit beeld."}, {"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."}, + "desc": "Gemodelleerde potentiële piek ((personen-EVSE's × ~11 kW + truck-locaties × ~150 kW) × 30%) per 1.000 inwoners. Vermogens 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", @@ -46,7 +50,7 @@ SCORECARD_COLS = [ "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", - "price_kwh_mean", "price_kwh_n", "price_pct", + "price_kwh_mean", "price_kwh_n", "price_pct", "freight_pct", ] EXPORT_COLS = [m["key"] for m in METRICS] + SCORECARD_COLS diff --git a/analysis/src/ingest/chargers.py b/analysis/src/ingest/chargers.py index 1f21fbcbbf..2babf66e56 100644 --- a/analysis/src/ingest/chargers.py +++ b/analysis/src/ingest/chargers.py @@ -19,48 +19,83 @@ def _latest_day(slug: str) -> dict | None: def _snapshot_metrics(slug: str) -> dict: - """avg occupancy + live EVSE totals/charging-now from the latest snapshot.""" + """avg occupancy + live EVSE totals/charging-now from the latest snapshot. + + - avg_occupancy is EVSE-weighted (a 147-connector hub weighs more than a + 1-connector post), not a flat mean over location-hours. + - charging_now samples every location at the SAME hour (the latest hour with + any data), so the "now" figure is a real instant, not a blend of each + location's own last non-null hour. + """ data = _latest_day(slug) if not data: return {"avg_occupancy": None, "evse_total": None, "charging_now": None, "occupancy_now": None} - all_occ: list[float] = [] + locations = data.get("locations", {}).values() evse_total = 0 - charging_now = 0 - for loc in data.get("locations", {}).values(): + w_sum = 0.0 + w_total = 0.0 + last_idx = -1 + for loc in locations: 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 + occ = loc.get("occ", []) + for i, v in enumerate(occ): + if v is not None: + w_sum += v * n + w_total += n + if i > last_idx: + last_idx = i + charging_now = 0 + evse_now = 0 + if last_idx >= 0: + for loc in locations: + n = loc.get("n") or 0 + occ = loc.get("occ", []) + v = occ[last_idx] if last_idx < len(occ) else None + if v is not None: + charging_now += round(v / 100 * n) + evse_now += n + avg = round(w_sum / w_total, 1) if w_total else None + occ_now = round(100 * charging_now / evse_now, 1) if evse_now else None return {"avg_occupancy": avg, "evse_total": evse_total, "charging_now": charging_now, "occupancy_now": occ_now} def _crop_stats(slug: str) -> dict: - """Per-gemeente supply stats from the crop-out: summed power, megawatt count, - and the €/kWh price distribution (median/mean) over locations that publish one.""" + """Per-gemeente supply stats from the crop-out, split by layer: summed power + (passenger vs freight), megawatt + dedicated-truck counts, and the €/kWh + price distribution over PASSENGER locations that publish one (freight HPC + tariffs would skew the general-public median).""" f = GEMEENTEN_DIR / f"{slug}.geojson" if not f.exists(): - return {"power": 0.0, "mw": 0, "price_median": None, "price_mean": None, "price_n": 0} + return {"power": 0.0, "freight_power": 0.0, "mw": 0, "freight_dedicated": 0, + "price_median": None, "price_mean": None, "price_n": 0} data = json.loads(f.read_text()) power = 0.0 + freight_power = 0.0 mw = 0 + freight_dedicated = 0 prices: list[float] = [] for feat in data.get("features", []): p = feat.get("properties", {}) - if p.get("type") == "charge": - power += p.get("maxPowerKw") or 0 + if p.get("type") != "charge": + continue + kw = p.get("maxPowerKw") or 0 + if p.get("layer") == "freight": + freight_power += kw if p.get("isMegawatt"): mw += 1 + if p.get("freightKind") == "dedicated": + freight_dedicated += 1 + else: + power += kw price = p.get("priceKwh") if isinstance(price, (int, float)): prices.append(float(price)) return { "power": power, + "freight_power": freight_power, "mw": mw, + "freight_dedicated": freight_dedicated, "price_median": round(statistics.median(prices), 3) if prices else None, "price_mean": round(statistics.fmean(prices), 3) if prices else None, "price_n": len(prices), @@ -83,7 +118,10 @@ def fetch_chargers() -> pd.DataFrame: "population": m.get("population") or 0, "chargers_passenger": m.get("passengerCount") or 0, "chargers_freight": m.get("freightCount") or 0, - "total_power_kw": round(crop["power"]), + "total_power_kw": round(crop["power"] + crop["freight_power"]), + "passenger_power_kw": round(crop["power"]), + "freight_power_kw": round(crop["freight_power"]), + "freight_dedicated": crop["freight_dedicated"], "megawatt_sites": crop["mw"], "price_kwh_median": crop["price_median"], "price_kwh_mean": crop["price_mean"], diff --git a/analysis/src/models.py b/analysis/src/models.py index 0b5c06bdd4..c0d9a3b77f 100644 --- a/analysis/src/models.py +++ b/analysis/src/models.py @@ -62,10 +62,19 @@ def add_models(df: pd.DataFrame) -> pd.DataFrame: 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 count: prefer live snapshot total (EVSE grain); the fallback is + # LOCATION grain (~2-10 EVSEs per location) and only fires for gemeenten + # without any snapshot — treat those rows as underestimates. 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) + # Potential peak (planning): passenger EVSEs at ~11 kW plus freight/truck + # locations at ~150 kW each, x concurrency. Freight sites are counted per + # location (crop-outs don't carry per-site bay counts) — conservative for + # multi-bay hubs, but far closer than pricing an MCS hub as one AC post. + freight_locs = df["chargers_freight"].fillna(0) + passenger_evse = (evse - freight_locs).clip(lower=0) + df["potential_peak_load_kw"] = ( + (passenger_evse * ASSUMED_EVSE_KW + freight_locs * AVG_FREIGHT_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. @@ -79,6 +88,8 @@ def add_models(df: pd.DataFrame) -> pd.DataFrame: df["gap_pct"] = _pct_rank(-df["supply_gap"]) # high = more underserved # Price percentile: high = relatively expensive vs other gemeenten. df["price_pct"] = _pct_rank(df["price_kwh_median"]) if df["price_kwh_median"].notna().any() else np.nan + # Freight/logistics percentile: rank on installed truck-charging power. + df["freight_pct"] = _pct_rank(df["freight_power_kw"]) if df["freight_power_kw"].notna().any() else np.nan df.attrs["model_metrics"] = metrics print(f" [models] demand OOF R²={metrics['r2_oof']} MAE={metrics['mae_oof']}; " diff --git a/data-pipeline/data/curated-hubs.json b/data-pipeline/data/curated-hubs.json index fd2917d2f5..899efa6a94 100644 --- a/data-pipeline/data/curated-hubs.json +++ b/data-pipeline/data/curated-hubs.json @@ -25,6 +25,18 @@ "isMegawatt": true, "sourceUrl": "https://milence.com" }, + { + "id": "milence-waddinxveen", + "name": "Milence Charging Hub Waddinxveen", + "operatorName": "Milence", + "city": "Waddinxveen", + "address": "Distripark Doelwijk (A12), Waddinxveen", + "lat": 52.0177, + "lng": 4.6199, + "maxPowerKw": 400, + "isMegawatt": false, + "sourceUrl": "https://milence.com/nl/press-release/milence-breidt-nederlands-netwerk-uit-in-het-hart-van-de-randstad-met-nieuwe-laadhub-in-waddinxveen/" + }, { "id": "watthub-geldermalsen", "name": "WattHub Geldermalsen", diff --git a/data-pipeline/src/assignGemeente.ts b/data-pipeline/src/assignGemeente.ts index 4d364ad6cc..cb2c5b4767 100644 --- a/data-pipeline/src/assignGemeente.ts +++ b/data-pipeline/src/assignGemeente.ts @@ -31,4 +31,35 @@ export class GemeenteAssigner { } return null; } + + // Like assign(), but falls back to the nearest gemeente (by bbox distance) for + // points that miss every generalized polygon — reclaimed/industrial land such as + // the Maasvlakte sits outside the simplified coastline. Returns null beyond ~15 km. + assignWithFallback(item: Assignable): { code: string; fallback: boolean } | null { + const exact = this.assign(item); + if (exact) return { code: exact, fallback: false }; + const { lat, lng } = item; + const cosLat = Math.cos((lat * Math.PI) / 180); + let best: string | null = null; + let bestD = Infinity; + for (const g of this.gemeenten) { + const b = this.bboxes.get(g.properties.statcode); + if (!b) continue; + const dx = (lng < b[0] ? b[0] - lng : lng > b[2] ? lng - b[2] : 0) * cosLat; + const dy = lat < b[1] ? b[1] - lat : lat > b[3] ? lat - b[3] : 0; + let d = Math.hypot(dx, dy); + if (d === 0) { + // Inside the bbox but outside the polygon: rank by distance to bbox centre, + // scaled down so any bbox hit beats a near-miss on a neighbouring bbox. + const cx = ((b[0] + b[2]) / 2 - lng) * cosLat; + const cy = (b[1] + b[3]) / 2 - lat; + d = Math.hypot(cx, cy) * 0.01; + } + if (d < bestD) { + bestD = d; + best = g.properties.statcode; + } + } + return best && bestD <= 0.15 ? { code: best, fallback: true } : null; + } } diff --git a/data-pipeline/src/classifyFreight.ts b/data-pipeline/src/classifyFreight.ts index 5da72b4305..9515bc2a52 100644 --- a/data-pipeline/src/classifyFreight.ts +++ b/data-pipeline/src/classifyFreight.ts @@ -1,7 +1,11 @@ -// Classify an OCPI location as passenger vs freight (heavy-duty / megawatt) charging. -// Heuristics combine connector power, connector standard, parking_type and operator name. +// Classify an OCPI location as passenger vs freight (heavy-duty / truck) charging. +// Signals, in decreasing precision: dedicated truck operator, explicit truck naming, +// logistics-depot naming + serious DC power, MCS standard, parking_type, raw DC power. +// Locations that only qualify on raw DC power are marked freightKind 'hpc' +// (truck-capable high-power charging, e.g. 400 kW Fastned/IONITY lanes that a tractor- +// trailer may not physically fit); everything else is 'dedicated'. -import type { OCPILocation, ClassificationMeta, AggregateStatus } from './types.js'; +import type { OCPILocation, OCPIConnector, ClassificationMeta, AggregateStatus } from './types.js'; // Aggregate EVSE statuses into one availability value (fleetsim priority: // AVAILABLE > CHARGING > any other status -> UNAVAILABLE; no EVSEs -> UNKNOWN). @@ -14,15 +18,20 @@ export function aggregateStatus(loc: OCPILocation): AggregateStatus { } export const THRESHOLDS = { - // Watts. A DC connector at/above this marks a location as freight/logistics. - // Set above the practical passenger-car CCS ceiling (~350 kW) so ordinary - // ultra-fast passenger chargers (Fastned/Ionity 150-350 kW) are NOT counted; - // ~>=350 kW high-power and MCS sites are truck/bus oriented. + // Watts. A DC connector at/above this makes a location truck-capable ('hpc'). + // 350 kW+ is above the CCS power most passenger cars can take, but several + // passenger networks (Fastned/IONITY) run 400 kW lanes, so power alone is only + // a 'truck-capable' signal, never a 'dedicated truck facility' signal. FREIGHT_DC_WATTS: 350_000, // Watts. Megawatt Charging System territory. MEGAWATT_WATTS: 1_000_000, - // Watts. Minimum DC power for a freight parking_type to count (motorway HPC). + // Watts. Minimum DC power for a logistics-named depot / motorway parking to count. + DEPOT_MIN_DC_WATTS: 150_000, PARKING_MIN_DC_WATTS: 350_000, + // Plausibility caps for declared connector power. NDW carries garbage like + // 7,360,000 W on a 230 V / 32 A AC post; above the cap we fall back to V×A. + MAX_PLAUSIBLE_WATTS: 1_500_000, + MAX_PLAUSIBLE_MCS_WATTS: 4_000_000, } as const; // Operators whose sites are dedicated heavy-duty / truck hubs. @@ -34,6 +43,20 @@ const FREIGHT_OPERATOR_PATTERNS = [ 'heliox truck', ]; +// Explicit truck naming on the location itself ("Truck only", "Truckpoint", +// "E-Truck", "vrachtwagen", ...). High precision in the NDW feed, but "heftruck"/ +// "vorkheftruck" (forklift) and "pallettruck" must not match. +const TRUCK_NAME_RE = /truck|vracht|zwaar vervoer/i; +const FORKLIFT_RE = /(hef|vorkhef|pallet|steek)truck/gi; + +function nameMentionsTruck(name: string): boolean { + return TRUCK_NAME_RE.test(name.replace(FORKLIFT_RE, '')); +} + +// Logistics-depot naming; only counts as freight when paired with serious DC power, +// so a 22 kW AC post at a transport company's visitor parking stays passenger. +const DEPOT_NAME_RE = /logisti|distributiecentr|transport/i; + // parking_type values that hint at freight/truck use. const FREIGHT_PARKING_TYPES = new Set([ 'ALONG_MOTORWAY', @@ -52,22 +75,41 @@ function normalize(s: string | undefined): string { return (s ?? '').toLowerCase().trim(); } +// Best-effort connector power in watts. Prefers the declared max_electric_power +// when plausible; otherwise derives from V×A (×3 for three-phase AC), which +// recovers power for the ~50% of NDW connectors that omit max_electric_power +// and neutralizes implausible declared values. +export function connectorPowerW(c: OCPIConnector): number { + const declared = c.max_electric_power ?? 0; + const cap = isMcsStandard(c.standard) + ? THRESHOLDS.MAX_PLAUSIBLE_MCS_WATTS + : THRESHOLDS.MAX_PLAUSIBLE_WATTS; + if (declared > 0 && declared <= cap) return declared; + const v = c.max_voltage ?? 0; + const a = c.max_amperage ?? 0; + if (v <= 0 || a <= 0) return 0; + const phases = (c.power_type ?? '').toUpperCase() === 'AC_3_PHASE' ? 3 : 1; + return v * a * phases; +} + export function classifyLocation(loc: OCPILocation): ClassificationMeta { let maxPowerW = 0; + let maxDcPowerW = 0; let hasCCS = false; let hasMCS = false; let dcCount = 0; - let dcAtFreightPower = false; for (const evse of loc.evses ?? []) { for (const c of evse.connectors ?? []) { - const power = c.max_electric_power ?? 0; + const power = connectorPowerW(c); if (power > maxPowerW) maxPowerW = power; const isDc = (c.power_type ?? '').toUpperCase() === 'DC'; - if (isDc) dcCount++; + if (isDc) { + dcCount++; + if (power > maxDcPowerW) maxDcPowerW = power; + } if (CCS_STANDARDS.has(c.standard)) hasCCS = true; if (isMcsStandard(c.standard)) hasMCS = true; - if (isDc && power >= THRESHOLDS.FREIGHT_DC_WATTS) dcAtFreightPower = true; } } @@ -77,17 +119,28 @@ export function classifyLocation(loc: OCPILocation): ClassificationMeta { const operator = normalize(loc.operator?.name); const operatorIsFreight = FREIGHT_OPERATOR_PATTERNS.some((p) => operator.includes(p)); + const name = loc.name ?? ''; + const nameIsTruck = nameMentionsTruck(name); + const nameIsDepot = DEPOT_NAME_RE.test(name) && maxDcPowerW >= THRESHOLDS.DEPOT_MIN_DC_WATTS; + const parkingIsFreight = !!loc.parking_type && FREIGHT_PARKING_TYPES.has(loc.parking_type) && - maxPowerW >= THRESHOLDS.PARKING_MIN_DC_WATTS; + maxDcPowerW >= THRESHOLDS.PARKING_MIN_DC_WATTS; - const isFreight = - operatorIsFreight || - hasMCS || - isMegawatt || - dcAtFreightPower || - parkingIsFreight; + // Dedicated truck facility: an explicit signal beyond raw power. + let freightReason: ClassificationMeta['freightReason']; + if (operatorIsFreight) freightReason = 'operator'; + else if (nameIsTruck) freightReason = 'truck-name'; + else if (hasMCS) freightReason = 'mcs'; + else if (nameIsDepot) freightReason = 'depot-name'; + else if (parkingIsFreight) freightReason = 'motorway'; + + const isDedicated = freightReason !== undefined; + const isTruckCapableHpc = !isDedicated && maxDcPowerW >= THRESHOLDS.FREIGHT_DC_WATTS; + if (isTruckCapableHpc) freightReason = 'power'; + + const isFreight = isDedicated || isTruckCapableHpc; return { category: isFreight ? 'freight' : 'passenger', @@ -96,5 +149,6 @@ export function classifyLocation(loc: OCPILocation): ClassificationMeta { hasMCS, isMegawatt, dcCount, + ...(isFreight ? { freightKind: isDedicated ? 'dedicated' : 'hpc', freightReason } : {}), }; } diff --git a/data-pipeline/src/index.ts b/data-pipeline/src/index.ts index 476358de9c..a13afa5686 100644 --- a/data-pipeline/src/index.ts +++ b/data-pipeline/src/index.ts @@ -1,6 +1,6 @@ // Orchestrator: NDW OCPI + external freight + PDOK boundaries -> static files. import { fetchNdw } from './fetchNdw.js'; -import { classifyLocation, aggregateStatus } from './classifyFreight.js'; +import { classifyLocation, aggregateStatus, connectorPowerW } from './classifyFreight.js'; import { fetchBoundaries } from './fetchBoundaries.js'; import { writeOutputs } from './writeOutputs.js'; import { sanitizeId } from './slugify.js'; @@ -46,13 +46,15 @@ function enrich( lastUpdated: loc.last_updated, layer: meta.category, maxPowerKw: meta.maxPowerKw, + freightKind: meta.freightKind, + freightReason: meta.freightReason, evses: (loc.evses ?? []).map((evse) => ({ ...evse, connectors: (evse.connectors ?? []).map((c) => { const tariffs = (c.tariff_ids ?? []) .map((id) => tariffMap.get(id)) .filter((t): t is OCPITariff => Boolean(t)); - const powerKw = c.max_electric_power ? c.max_electric_power / 1000 : 0; + const powerKw = connectorPowerW(c) / 1000; const resolved = resolveConnectorPrice(tariffs, powerKw, now); return { ...c, @@ -133,6 +135,8 @@ async function main() { isMegawatt: meta.isMegawatt, status, priceKwh, + freightKind: meta.freightKind, + freightReason: meta.freightReason, }); } } @@ -169,6 +173,8 @@ async function main() { source: f.source, sourceUrl: f.sourceUrl, priceKwh: f.priceKwh, + freightKind: f.freightKind ?? 'dedicated', + freightReason: f.freightReason ?? 'curated', })); // 5. Boundaries. diff --git a/data-pipeline/src/sources/curated.ts b/data-pipeline/src/sources/curated.ts index 2fe3380fea..2562209e91 100644 --- a/data-pipeline/src/sources/curated.ts +++ b/data-pipeline/src/sources/curated.ts @@ -35,6 +35,8 @@ export const curatedSource: FreightSource = { maxPowerKw: h.maxPowerKw ?? 0, isMegawatt: h.isMegawatt ?? false, sourceUrl: h.sourceUrl, + freightKind: 'dedicated', + freightReason: 'curated', })); }, }; diff --git a/data-pipeline/src/sources/merge.ts b/data-pipeline/src/sources/merge.ts index a9a3bfa806..dd6b00a57b 100644 --- a/data-pipeline/src/sources/merge.ts +++ b/data-pipeline/src/sources/merge.ts @@ -38,6 +38,7 @@ export function mergeFreight( const other = winner === loc ? existing : loc; const pickStatus = winner.status && winner.status !== 'UNKNOWN' ? winner.status : other.status ?? winner.status; + const dedicated = winner.freightKind === 'dedicated' || other.freightKind === 'dedicated'; byCoord.set(k, { ...winner, maxPowerKw: Math.max(winner.maxPowerKw, other.maxPowerKw), @@ -48,6 +49,12 @@ export function mergeFreight( status: pickStatus, sourceUrl: winner.sourceUrl || other.sourceUrl, priceKwh: winner.priceKwh ?? other.priceKwh, + freightKind: dedicated ? 'dedicated' : winner.freightKind ?? other.freightKind, + freightReason: + (winner.freightKind === 'dedicated' ? winner.freightReason : undefined) ?? + (other.freightKind === 'dedicated' ? other.freightReason : undefined) ?? + winner.freightReason ?? + other.freightReason, }); } } diff --git a/data-pipeline/src/tariff.ts b/data-pipeline/src/tariff.ts index 788d1c2f9b..22c6c170d4 100644 --- a/data-pipeline/src/tariff.ts +++ b/data-pipeline/src/tariff.ts @@ -59,11 +59,17 @@ function matchesRestrictions(r: OCPITariffRestrictions | undefined, powerKw: num if (r.start_date && t.date < r.start_date) return false; if (r.end_date && t.date > r.end_date) return false; - // Time-of-day window (supports overnight ranges where start > end). - if (r.start_time && r.end_time) { - const { start_time: s, end_time: e } = r; + // Time-of-day window (supports overnight ranges where start > end, and + // one-sided windows where only one bound is given). + const s = r.start_time ?? null; + const e = r.end_time ?? null; + if (s && e) { const within = s <= e ? t.hhmm >= s && t.hhmm <= e : t.hhmm >= s || t.hhmm <= e; if (!within) return false; + } else if (s) { + if (t.hhmm < s) return false; + } else if (e) { + if (t.hhmm > e) return false; } return true; } diff --git a/data-pipeline/src/types.ts b/data-pipeline/src/types.ts index c9dbb1a76e..12aa7225bc 100644 --- a/data-pipeline/src/types.ts +++ b/data-pipeline/src/types.ts @@ -102,6 +102,11 @@ export interface OCPITariff { export type ChargeCategory = 'passenger' | 'freight'; +// 'dedicated' = explicit truck facility (operator/name/MCS/curated); +// 'hpc' = only qualifies on raw DC power >= 350 kW (truck-capable, not necessarily truck-accessible). +export type FreightKind = 'dedicated' | 'hpc'; +export type FreightReason = 'operator' | 'truck-name' | 'mcs' | 'depot-name' | 'motorway' | 'power' | 'curated'; + // Classification metadata derived from a location's connectors. export interface ClassificationMeta { category: ChargeCategory; @@ -110,6 +115,8 @@ export interface ClassificationMeta { hasMCS: boolean; isMegawatt: boolean; dcCount: number; + freightKind?: FreightKind; + freightReason?: FreightReason; } // Aggregate availability derived from a location's EVSE statuses (fleetsim-style). @@ -132,6 +139,8 @@ export interface LightLocation { source: string; // 'ndw' | 'curated' | 'eafo' | 'ocm' sourceUrl?: string; priceKwh?: number; // cheapest currently-applicable €/kWh across this location's connectors + freightKind?: FreightKind; + freightReason?: FreightReason; } // Normalized external freight location (from sources/*). @@ -149,6 +158,8 @@ export interface NormalizedFreightLocation { status?: AggregateStatus; sourceUrl?: string; priceKwh?: number; + freightKind?: FreightKind; + freightReason?: FreightReason; } // Full enriched location detail ("with details"), stored in per-gemeente bundles. @@ -178,5 +189,7 @@ export interface EnrichedLocation { lastUpdated: string; layer: ChargeCategory; maxPowerKw: number; + freightKind?: FreightKind; + freightReason?: FreightReason; evses: EnrichedEVSE[]; } diff --git a/data-pipeline/src/writeOutputs.ts b/data-pipeline/src/writeOutputs.ts index 3b59be1621..4eac263193 100644 --- a/data-pipeline/src/writeOutputs.ts +++ b/data-pipeline/src/writeOutputs.ts @@ -40,6 +40,8 @@ function pointFeature(l: LightLocation) { status: l.status, source: l.source, ...(l.priceKwh != null ? { priceKwh: l.priceKwh } : {}), + ...(l.freightKind ? { freightKind: l.freightKind } : {}), + ...(l.freightReason ? { freightReason: l.freightReason } : {}), }, }; } @@ -68,17 +70,21 @@ export async function writeOutputs(input: WriteInput): Promise { // Group lights by gemeente code. const byGemeente = new Map(); let unassigned = 0; + let viaFallback = 0; for (const l of [...passengerLights, ...freightLights]) { - const code = assigner.assign(l); - if (!code) { + const res = assigner.assignWithFallback(l); + if (!res) { unassigned++; continue; } - let arr = byGemeente.get(code); - if (!arr) byGemeente.set(code, (arr = [])); + if (res.fallback) viaFallback++; + let arr = byGemeente.get(res.code); + if (!arr) byGemeente.set(res.code, (arr = [])); arr.push(l); } - console.log(` assigned points; ${unassigned} unassigned (kept in national files only)`); + console.log( + ` assigned points; ${viaFallback} via nearest-gemeente fallback, ${unassigned} unassigned (kept in national files only)`, + ); // Per-gemeente crop-out + detail bundle. const municipalities: Array = []; diff --git a/webapp/app/page.tsx b/webapp/app/page.tsx index 7762b979a2..85fb7907a3 100644 --- a/webapp/app/page.tsx +++ b/webapp/app/page.tsx @@ -13,6 +13,7 @@ import AboutModal from "@/components/AboutModal"; import ShareModal from "@/components/ShareModal"; import GuidedTour, { type TourStep } from "@/components/GuidedTour"; import type { ChoroplethData, AreaProps } from "@/types/analysis"; +import { findGemeenteSlug } from "@/lib/pointInGemeente"; import { Municipality, CropoutData, @@ -222,6 +223,10 @@ export default function Home() { window.history.replaceState({}, "", url.toString()); }, [selectedMunicipality, municipalities, isNational]); + // A locationId to re-select once the next gemeente load finishes (used by the + // "jump to gemeente" action in the detail panel from the national view). + const pendingSelectRef = useRef(null); + // Load data when municipality changes. useEffect(() => { if (!selectedMunicipality) return; @@ -269,6 +274,11 @@ export default function Home() { setBounds(crop.metadata.bounds ?? null); setDetails(bundle); setGemeenteName(crop.metadata.gemeente ?? selectedMunicipality); + if (pendingSelectRef.current) { + const again = charges.find((f) => f.properties.locationId === pendingSelectRef.current); + pendingSelectRef.current = null; + if (again) setSelected(again); + } } }; @@ -281,18 +291,38 @@ export default function Home() { }; }, [selectedMunicipality]); + // Counts shown in the filter panel: same power/kind filtering as the map layers, + // so "the counts reflect the current view" actually holds. const { passengerCount, freightCount } = useMemo(() => { let p = 0; let f = 0; for (const feat of chargeFeatures) { - if (feat.properties.layer === "freight") f++; - else p++; + if (feat.properties.maxPowerKw < filters.minPowerKw) continue; + if (feat.properties.layer === "freight") { + if (filters.dedicatedFreightOnly && feat.properties.freightKind === "hpc") continue; + f++; + } else p++; } return { passengerCount: p, freightCount: f }; - }, [chargeFeatures]); + }, [chargeFeatures, filters.minPowerKw, filters.dedicatedFreightOnly]); const selectedDetail = selected ? details[selected.properties.locationId] ?? null : null; + // From the national view, jump into the gemeente containing the selected point + // (found via the choropleth polygons) and re-open its detail panel there. + const jumpToGemeente = useMemo(() => { + if (!selected || selectedDetail || !isNational) return undefined; + const [lng, lat] = selected.geometry.coordinates; + const slug = findGemeenteSlug(choropleth, lng, lat); + if (!slug) return undefined; + const locationId = selected.properties.locationId; + return () => { + pendingSelectRef.current = locationId; + setAnalysisMetric(null); + setSelectedMunicipality(slug); + }; + }, [selected, selectedDetail, isNational, choropleth]); + const handleAddressSelected = (slug: string) => { setSelectedMunicipality(slug); setMobileSidebarOpen(false); @@ -416,9 +446,10 @@ export default function Home() { setSelected(null)} + onJumpToGemeente={jumpToGemeente} /> {/* Mobile filter button */} diff --git a/webapp/components/AboutModal.tsx b/webapp/components/AboutModal.tsx index 0167eefb4b..8771208c88 100644 --- a/webapp/components/AboutModal.tsx +++ b/webapp/components/AboutModal.tsx @@ -79,9 +79,12 @@ export default function AboutModal({ isOpen, onClose, onStartTutorial }: Props)

- Een laadpunt is vracht bij: een truck-exploitant (Milence/WattHub…), de MCS/megawatt-standaard, - of een DC-connector ≥ 350 kW. Daardoor blijven gewone snelladers (150–350 kW) in de personenauto-laag. - Megawatt-locaties (≥ 1 MW) krijgen een aparte kleur. + Een laadpunt is dedicated truck bij een expliciet signaal: een truck-exploitant + (Milence/WattHub…), “truck” of “vrachtwagen” in de naam, de MCS/megawatt-standaard, of een logistiek + depot met ≥ 150 kW DC. Locaties die alléén op vermogen kwalificeren (DC ≥ 350 kW, zoals 400 kW-lanen + van personenauto-netwerken) heten truck-capable en krijgen een lichtere kleur — niet + elke locatie daarvan is fysiek toegankelijk voor een trekker-oplegger. Megawatt-locaties (≥ 1 MW of + MCS) krijgen een aparte kleur. Connectorvermogen wordt waar nodig afgeleid uit spanning × stroomsterkte.

diff --git a/webapp/components/FilterPanel.tsx b/webapp/components/FilterPanel.tsx index 9383cf010b..4c6db07d77 100644 --- a/webapp/components/FilterPanel.tsx +++ b/webapp/components/FilterPanel.tsx @@ -56,6 +56,25 @@ export default function FilterPanel({ filters, onChange, passengerCount, freight {freightCount.toLocaleString("nl-NL")} + {filters.showFreight && ( + + )} +