Source code for energy_methods.strata_impact

"""STRATA output sampling and explicitly hypothetical energy screening.

SCREAM units and cube layout follow NVIDIA's released STRATA writer. These
functions do not run inference, diagnose wind height, or predict asset failures.
"""

from __future__ import annotations

from dataclasses import dataclass
from math import hypot, isfinite

import numpy as np
import pandas as pd
import xarray as xr

REFERENCE_IDS = ("nvidia_strata_2026",)
_SPATIAL = ("face", "x", "y")
_FIELDS = {
    "temperature_c": ("T_2m", {"K", "kelvin"}),
    "precipitation_mm_h": ("precip_liq_surf_mass_flux", {"m/s", "m s-1", "m s^-1"}),
    "eastward_wind_ms": ("U", {"m/s", "m s-1", "m s^-1"}),
    "northward_wind_ms": ("V", {"m/s", "m s-1", "m s^-1"}),
}


[docs] @dataclass(frozen=True) class StormExposure: """One asset's exposure and illustrative production multiplier.""" asset: str wind_speed_ms: float precipitation_mm_h: float temperature_c: float wind_alert: bool precipitation_alert: bool illustrative_availability: float
[docs] def screen_asset( asset: str, *, eastward_wind_ms: float, northward_wind_ms: float, precipitation_mm_h: float, temperature_c: float, wind_threshold_ms: float = 20.0, rain_threshold_mm_h: float = 15.0, ) -> StormExposure: """Apply hypothetical 15% wind / 5% rain power reductions, additive. The legacy ``illustrative_availability`` name is a scenario power multiplier, not technical availability, failure probability, or an observed loss. """ if not all( isfinite(v) for v in ( eastward_wind_ms, northward_wind_ms, precipitation_mm_h, temperature_c, wind_threshold_ms, rain_threshold_mm_h, ) ): raise ValueError("Weather and thresholds must be finite") if wind_threshold_ms <= 0 or rain_threshold_mm_h <= 0: raise ValueError("Thresholds must be positive") if precipitation_mm_h < 0: raise ValueError("Precipitation cannot be negative") wind = hypot(eastward_wind_ms, northward_wind_ms) wind_alert = wind >= wind_threshold_ms rain_alert = precipitation_mm_h >= rain_threshold_mm_h return StormExposure( asset, wind, precipitation_mm_h, temperature_c, wind_alert, rain_alert, 1.0 - 0.15 * wind_alert - 0.05 * rain_alert, )
[docs] def precipitation_flux_to_mm_h(flux_m_s: float) -> float: """Convert SCREAM liquid-water-equivalent m/s to mm/h (not kg/m²/s).""" if not isfinite(flux_m_s) or flux_m_s < 0: raise ValueError("Precipitation flux must be finite and nonnegative") return flux_m_s * 3_600_000.0
[docs] @dataclass(frozen=True) class GridCell: """Positional cube indices and great-circle distance to a requested site.""" face: int x: int y: int latitude: float longitude: float distance_km: float
[docs] def nearest_strata_cell( dataset: xr.Dataset, *, latitude: float, longitude: float, max_distance_km: float = 25.0, rows_per_chunk: int = 64, ) -> GridCell: """Find a cell on a sphere without loading the global weather fields. Scan latitude/longitude in bounded face-row chunks. Longitudes in either -180..180 or 0..360 work across the dateline. Invalid cells are ignored; missing coverage or a cell farther than the explicit limit raises an error. This is nearest-cell sampling, without interpolation or terrain correction. """ if not isfinite(latitude) or not -90 <= latitude <= 90 or not isfinite(longitude): raise ValueError("Site latitude/longitude must be finite; latitude must be -90..90") if not isfinite(max_distance_km) or max_distance_km <= 0 or rows_per_chunk < 1: raise ValueError("Distance limit and rows_per_chunk must be positive") for name in ("lat", "lon"): if name not in dataset or set(dataset[name].dims) != set(_SPATIAL): raise ValueError(f"{name} must have dimensions face, x, y") best: GridCell | None = None for face in range(dataset.sizes["face"]): for start in range(0, dataset.sizes["x"], rows_per_chunk): selection = {"face": face, "x": slice(start, start + rows_per_chunk)} lat = np.asarray(dataset["lat"].isel(selection).transpose("x", "y").values) lon = np.asarray(dataset["lon"].isel(selection).transpose("x", "y").values) valid = np.isfinite(lat) & np.isfinite(lon) & (np.abs(lat) <= 90) # Mask before trigonometry to avoid propagating invalid-coordinate warnings. lat = np.where(valid, lat, 0.0) lon = np.where(valid, lon, 0.0) dlon = np.deg2rad((lon - longitude + 180) % 360 - 180) a = ( np.sin(np.deg2rad(lat - latitude) / 2) ** 2 + np.cos(np.deg2rad(latitude)) * np.cos(np.deg2rad(lat)) * np.sin(dlon / 2) ** 2 ) distance = 6371.0088 * 2 * np.arcsin(np.sqrt(np.clip(a, 0, 1))) distance = np.where(valid, distance, np.inf) row, col = np.unravel_index(np.argmin(distance), distance.shape) km = float(distance[row, col]) if np.isfinite(km) and (best is None or km < best.distance_km): best = GridCell( face, start + int(row), int(col), float(lat[row, col]), float((lon[row, col] + 180) % 360 - 180), km, ) if best is None or best.distance_km > max_distance_km: raise ValueError("No finite STRATA cell within max_distance_km of the asset") return best
def _weather_fields(dataset: xr.Dataset) -> xr.Dataset: for key, (name, units) in _FIELDS.items(): if name not in dataset: raise ValueError(f"Missing STRATA field {name} ({key})") # Upstream writer does not attach units to weather variables. Missing # metadata means the documented native SCREAM units, never a guessed conversion. declared = dataset[name].attrs.get("units") if declared is not None and declared not in units: raise ValueError(f"{name} has unsupported units {declared!r}; expected {sorted(units)}") expected = {"time", "step", *_SPATIAL} if name in {"U", "V"}: expected.add("level") if set(dataset[name].dims) != expected: raise ValueError(f"{name} must have dimensions {sorted(expected)}") return dataset[[value[0] for value in _FIELDS.values()]] def _converted(values: xr.Dataset) -> dict[str, np.ndarray]: arrays = { key: np.asarray(values[name].values, dtype=float) for key, (name, _) in _FIELDS.items() } if not all(np.isfinite(a).all() for a in arrays.values()): raise ValueError("Selected STRATA weather contains nonfinite values") if np.any(arrays["precipitation_mm_h"] < 0): raise ValueError("Precipitation flux cannot be negative; inspect model diagnostics") arrays["temperature_c"] = arrays["temperature_c"] - 273.15 arrays["precipitation_mm_h"] = arrays["precipitation_mm_h"] * 3_600_000 return arrays
[docs] def sample_strata_output( dataset: xr.Dataset, *, face: int, x: int, y: int, step: int = 0, time: int = 0, wind_level: int | None = None, ) -> dict[str, float]: """Sample a single cell using positional indices (legacy interface). ``wind_level`` is a positional index here. Prefer ``extract_strata_timeseries`` for label-based model-level selection and explicit valid timestamps. """ if wind_level is None: raise ValueError("Specify wind_level for level-dependent U/V fields") selected = ( _weather_fields(dataset) .isel( time=time, step=step, face=face, x=x, y=y, level=wind_level, ) .load() ) return {key: float(value.item()) for key, value in _converted(selected).items()}
[docs] def extract_strata_timeseries( dataset: xr.Dataset, *, cell: GridCell, wind_level: int, time_index: int = 0, ) -> pd.DataFrame: """Extract all lead times for one cell and one initialization. ``wind_level`` is a coordinate label, e.g. 30, NOT position 30 or a height. Native timedeltas and explicitly second-valued numeric ``step`` coordinates are supported. Valid time = initialization + lead. ``interval_hours`` spans the previous saved lead (zero for the start); rates are endpoint samples, so multiplying by this duration is only rectangular quadrature. """ fields = _weather_fields(dataset) if "level" not in fields.coords or wind_level not in fields["level"].values: raise ValueError(f"Requested model-level label {wind_level} is not in the output") if not 0 <= time_index < fields.sizes["time"]: raise ValueError("time_index is outside available initializations") initial = np.asarray(fields["time"].values)[time_index] if not np.issubdtype(np.asarray(initial).dtype, np.datetime64) or np.isnat(initial): raise ValueError("time must contain decoded, finite datetime initializations") step = fields["step"] raw = np.asarray(step.values) if np.issubdtype(raw.dtype, np.timedelta64): lead = raw / np.timedelta64(1, "s") elif np.issubdtype(raw.dtype, np.number) and step.attrs.get("units") in {"s", "seconds"}: lead = raw.astype(float) else: raise ValueError("step must be timedeltas or numeric seconds with explicit units") if len(lead) == 0 or not np.isfinite(lead).all() or lead[0] <= 0 or np.any(np.diff(lead) <= 0): raise ValueError("Lead times must be finite, positive and strictly increasing") selected = ( fields.sel(level=wind_level) .isel( time=time_index, face=cell.face, x=cell.x, y=cell.y, ) .transpose("step") .load() ) table = pd.DataFrame(_converted(selected)) table.insert(0, "valid_time", pd.Timestamp(initial) + pd.to_timedelta(lead, unit="s")) table.insert(0, "lead_hours", lead / 3600) table["interval_hours"] = np.diff(np.r_[0, lead]) / 3600 table["wind_speed_ms"] = np.hypot(table.eastward_wind_ms, table.northward_wind_ms) table["wind_model_level"] = wind_level return table
[docs] def paired_error_metrics(predicted: pd.Series, reference: pd.Series) -> dict[str, float | int]: """MAE, RMSE and signed bias on exact paired timestamps, with no silent drop. The caller supplies SCREAM simulation truth at the same sites, model level and valid times. Historical STRATA simulation dates cannot be validated against observed weather on those calendar dates. """ if not predicted.index.equals(reference.index) or not predicted.index.is_unique: raise ValueError("Prediction and reference require identical, unique indices") a, b = np.asarray(predicted, dtype=float), np.asarray(reference, dtype=float) if not len(a) or not np.isfinite(a).all() or not np.isfinite(b).all(): raise ValueError("Metrics require nonempty finite paired values") error = a - b return { "n": len(a), "mae": float(np.abs(error).mean()), "rmse": float(np.sqrt(np.square(error).mean())), "bias": float(error.mean()), }
[docs] def energy_scenario( weather: pd.DataFrame, baseline_mw: np.ndarray, *, wind_threshold_ms: float, rain_threshold_mm_h: float = 15.0, wind_reduction: float = 0.15, rain_reduction: float = 0.05, price_eur_mwh: float = 60.0, ) -> pd.DataFrame: """Apply explicit scenario reductions to external baseline interval-mean MW. Wind at a model level is only a sensitivity proxy. No turbine power curve, hub-height extrapolation, PV irradiance or failure probabilities are inferred. EUR values are gross energy value, excluding contracts and mitigation costs. """ values = weather[["wind_speed_ms", "precipitation_mm_h", "interval_hours"]].to_numpy(float) baseline = np.asarray(baseline_mw, dtype=float) parameters = [ wind_threshold_ms, rain_threshold_mm_h, wind_reduction, rain_reduction, price_eur_mwh, ] if not np.isfinite(parameters).all() or min(wind_threshold_ms, rain_threshold_mm_h) <= 0: raise ValueError("Scenario parameters must be finite and thresholds positive") if not 0 <= wind_reduction <= 1 or not 0 <= rain_reduction <= 1: raise ValueError("Reduction fractions must be in [0, 1]") if baseline.shape != (len(weather),) or not np.isfinite(baseline).all() or (baseline < 0).any(): raise ValueError("Provide one finite nonnegative baseline MW value per weather row") if ( not len(weather) or not np.isfinite(values).all() or (values < 0).any() or (values[:, 2] <= 0).any() ): raise ValueError("Weather must be finite and nonnegative with positive intervals") result = weather.copy() result["wind_alert"] = result.wind_speed_ms >= wind_threshold_ms result["rain_alert"] = result.precipitation_mm_h >= rain_threshold_mm_h result["power_multiplier"] = np.maximum( 0, 1 - wind_reduction * result.wind_alert - rain_reduction * result.rain_alert, ) result["baseline_mwh"] = baseline * result.interval_hours result["scenario_mwh"] = result.baseline_mwh * result.power_multiplier result["energy_at_risk_mwh"] = result.baseline_mwh - result.scenario_mwh result["gross_value_at_risk_eur"] = result.energy_at_risk_mwh * price_eur_mwh return result