"""Rule-based engine for ski station predictions. Evaluates physical and operational constraints for a given station and weather observation. Rules always take priority over ML predictions when conditions are deterministic (e.g. extreme wind, insufficient snow depth). All thresholds are loaded from config/stations.yaml. No station-specific values are hardcoded in this module. """ import logging from pathlib import Path from typing import Any import yaml logger = logging.getLogger(__name__) # Path relative to repository root _CONFIG_PATH = Path(__file__).parent.parent / "config" / "stations.yaml" # Fresh snowfall (cm in 24 h) considered "heavy" _HEAVY_FRESH_SNOW_THRESHOLD_CM = 20.0 # Wind gust (km/h) considered "moderate" when combined with heavy snow _MODERATE_WIND_THRESHOLD_KMH = 40.0 # Warm rain quickly degrades skiable terrain even when opening remains possible. _WARM_RAIN_TEMP_THRESHOLD_C = 10.0 _WARM_RAIN_PRECIP_THRESHOLD_MM = 1.0 _WARM_RAIN_KM_FACTOR = 0.6 def _load_station_configs() -> dict[str, Any]: """Load all station configurations from stations.yaml. Returns: A dict mapping station IDs to their configuration dicts. Raises: FileNotFoundError: If stations.yaml cannot be found. KeyError: If the 'stations' key is absent from the file. """ if not _CONFIG_PATH.exists(): raise FileNotFoundError(f"Station config not found: {_CONFIG_PATH}") with _CONFIG_PATH.open("r", encoding="utf-8") as fh: raw = yaml.safe_load(fh) if "stations" not in raw: raise KeyError(f"'stations' key missing in {_CONFIG_PATH}") logger.debug("Loaded station configs for: %s", list(raw["stations"].keys())) return raw["stations"] class RulesEngine: """Evaluates operational rule constraints for a ski station. Rules are deterministic: when a rule fires, the outcome is certain regardless of what the ML model predicts. Rules are derived exclusively from the station configuration file so they remain configurable without code changes. Usage:: engine = RulesEngine() result = engine.evaluate("pajares", weather_data) Args: config_path: Optional override for the path to stations.yaml. Defaults to config/stations.yaml in the repository root. """ def __init__(self, config_path: Path | None = None) -> None: effective_path = config_path or _CONFIG_PATH if config_path: # Re-read from custom path with Path(effective_path).open("r", encoding="utf-8") as fh: raw = yaml.safe_load(fh) self._stations = raw.get("stations", {}) else: self._stations = _load_station_configs() logger.info( "RulesEngine initialised with %d station(s): %s", len(self._stations), list(self._stations.keys()), ) # ------------------------------------------------------------------ # Public API # ------------------------------------------------------------------ def evaluate(self, station_id: str, weather_data: dict[str, Any]) -> dict[str, Any]: """Evaluate rule-based constraints for a station and weather snapshot. Args: station_id: Key identifying the station in stations.yaml (e.g. ``"pajares"``). weather_data: Dict of weather variables for the prediction day. Expected keys (all optional; missing keys are skipped): - ``wind_gusts_10m_max`` (float, km/h) - ``snow_depth`` (float, cm) - ``snowfall_sum`` (float, cm in last 24 h) - ``temperature_2m_max`` (float, °C) - ``precipitation_sum`` (float, mm) - ``is_weekend`` (bool or int 0/1) - ``is_holiday`` (bool or int 0/1) Returns: A dict with the following keys: - ``force_closed`` (bool): Rule mandates the station is closed. - ``force_open`` (bool): Rule mandates the station is open (reserved for future use; currently always False). - ``confidence`` (float 0–1): How certain the rule engine is about its assessment. 1.0 when a force_closed or force_open rule fires; lower when only soft rules apply. - ``reasons`` (list[str]): Human-readable explanations for each rule that fired. - ``estimated_km_factor`` (float 0–1): Multiplier to apply to the maximum skiable km. 1.0 = all slopes available, 0.0 = none. Raises: ValueError: If station_id is not present in the configuration. """ if station_id not in self._stations: raise ValueError( f"Unknown station '{station_id}'. " f"Known stations: {list(self._stations.keys())}" ) config = self._stations[station_id] station_name = config.get("name", station_id) logger.debug( "Evaluating rules for '%s' with weather_data keys: %s", station_name, list(weather_data.keys()), ) force_closed = False force_open = False reasons: list[str] = [] km_factor = 1.0 # ---- Rule 1: Extreme wind gust -> force close -------------------- wind_gust = weather_data.get("wind_gusts_10m_max") wind_threshold = config["wind_closure_threshold"] if wind_gust is not None: if wind_gust >= wind_threshold: force_closed = True reasons.append( f"Rachas de viento de {wind_gust:.1f} km/h superan el umbral de cierre de " f"{wind_threshold} km/h." ) logger.info( "[%s] Rule 1 fired: wind gust %.1f > %.1f km/h -> force_closed", station_name, wind_gust, wind_threshold, ) # ---- Rule 2: Snow depth below minimum -> force close ------------- snow_depth = weather_data.get("snow_depth") min_snow = config["minimum_snow_depth"] if snow_depth is not None: if snow_depth < min_snow: force_closed = True km_factor = 0.0 reasons.append( f"El espesor de nieve ({snow_depth:.1f} cm) está por debajo del mínimo " f"requerido ({min_snow} cm)." ) logger.info( "[%s] Rule 2 fired: snow depth %.1f < %.1f cm -> force_closed", station_name, snow_depth, min_snow, ) # ---- Rule 3: Heavy fresh snow + moderate wind -> likely open ----- snowfall_24h = weather_data.get("snowfall_sum") wind_speed = weather_data.get("wind_gusts_10m_max", 0.0) if ( snowfall_24h is not None and snowfall_24h >= _HEAVY_FRESH_SNOW_THRESHOLD_CM and wind_speed is not None and wind_speed <= _MODERATE_WIND_THRESHOLD_KMH and not force_closed ): force_open = True reasons.append( f"Nevada intensa ({snowfall_24h:.1f} cm en 24 h) con viento moderado " f"({wind_speed:.1f} km/h); es muy probable que la estación abra y esté concurrida." ) logger.info( "[%s] Rule 3 fired: heavy snow %.1f cm + wind %.1f km/h -> force_open", station_name, snowfall_24h, wind_speed, ) # ---- Rule 4: Weekday + no fresh snow -> low crowd ---------------- is_weekend = bool(weather_data.get("is_weekend", False)) is_holiday = bool(weather_data.get("is_holiday", False)) is_busy_day = is_weekend or is_holiday no_fresh_snow = (snowfall_24h is None or snowfall_24h < 5.0) if not is_busy_day and no_fresh_snow and not force_closed: reasons.append( "Día laborable sin nevadas significativas; se espera un nivel de afluencia bajo." ) logger.debug("[%s] Rule 4 fired: weekday + no fresh snow -> low crowd", station_name) # ---- Rule 5: Weekend/holiday + fresh snow -> high crowd ---------- if is_busy_day and snowfall_24h is not None and snowfall_24h >= 5.0 and not force_closed: reasons.append( f"Fin de semana o festivo con {snowfall_24h:.1f} cm de nieve fresca; " "se espera un nivel de afluencia alto." ) logger.debug( "[%s] Rule 5 fired: busy day + fresh snow %.1f cm -> high crowd", station_name, snowfall_24h, ) # ---- Rule 6: Warm rain reduces skiable terrain ------------------- max_temperature = weather_data.get("temperature_2m_max") precipitation = weather_data.get("precipitation_sum") if ( max_temperature is not None and max_temperature > _WARM_RAIN_TEMP_THRESHOLD_C and precipitation is not None and precipitation >= _WARM_RAIN_PRECIP_THRESHOLD_MM and not force_closed ): km_factor = min(km_factor, _WARM_RAIN_KM_FACTOR) reasons.append( f"Lluvia ({precipitation:.1f} mm) con temperatura alta " f"({max_temperature:.1f} C); se reduce el km esquiable estimado." ) logger.info( "[%s] Rule 6 fired: warm rain %.1f C / %.1f mm -> km_factor %.2f", station_name, max_temperature, precipitation, km_factor, ) # ---- Derive confidence ------------------------------------------- if force_closed or force_open: confidence = 1.0 elif reasons: # Soft rules fired but no deterministic outcome confidence = 0.6 else: # No rules fired; rules engine is inconclusive confidence = 0.0 result = { "force_closed": force_closed, "force_open": force_open, "confidence": confidence, "reasons": reasons, "estimated_km_factor": km_factor, } logger.debug("[%s] Rules result: %s", station_name, result) return result