"""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" # 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 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"Cierre forzoso por viento extremo: {wind_gust:.1f} km/h " f"(umbral histórico de seguridad: {wind_threshold} km/h)." ) logger.info( "[%s] Deterministic Rule: 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"Espesor de nieve insuficiente ({snow_depth:.1f} cm) " f"para la apertura de pistas (mínimo requerido: {min_snow} cm)." ) logger.info( "[%s] Deterministic Rule: snow depth %.1f < %.1f cm -> force_closed", station_name, snow_depth, min_snow, ) # ---- Rule 3: 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 ------------------------------------------- # Confidence is 1.0 only if a deterministic closure rule fired. # Otherwise, confidence is 0.0, delegating all responsibility to ML. if force_closed: confidence = 1.0 else: confidence = 0.0 result = { "force_closed": force_closed, "force_open": False, # No force_open rules in this version "confidence": confidence, "reasons": reasons, "estimated_km_factor": km_factor, } logger.debug("[%s] Rules result: %s", station_name, result) return result