mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 15:26:15 +00:00
feat: initial ski predictor system
Hybrid ML + rules prediction system for 3 Asturian ski stations (Pajares, San Isidro, Fuentes de Invierno). - Weather data from Open-Meteo (historical + forecast) - Station scraping from infonieve.es (live + 16 seasons historical TSV) - Feature engineering: rolling snow, calendar, temperature/pressure trends - ML models: RandomForest (open/close), GradientBoosting (km), LightGBM (crowd) - Rules engine: wind closure, snow depth, rain+heat, heavy snow - YOLOv8 webcam crowd detection (cars, people in parking/lifts) - Telegram bot with /pajares, /sanisidro, /fuentes commands - Daily cron pipeline for automated data collection and predictions - Deployment guide with systemd service and cron setup
This commit is contained in:
commit
1afe2b73e0
34 files changed
+7201
No files matched your search
@@ -0,0 +1,278 @@
|
||||
"""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"
|
||||
|
||||
# Temperature above which rain becomes operationally problematic
|
||||
_RAIN_TEMPERATURE_THRESHOLD_C = 10.0
|
||||
|
||||
# Precipitation threshold (mm) to be considered rain at high temperature
|
||||
_RAIN_PRECIPITATION_THRESHOLD_MM = 2.0
|
||||
|
||||
# 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
|
||||
|
||||
# km_factor reduction applied when warm rain is detected
|
||||
_WARM_RAIN_KM_FACTOR_REDUCTION = 0.4
|
||||
|
||||
|
||||
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"Wind gust {wind_gust:.1f} km/h exceeds closure threshold "
|
||||
f"of {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"Snow depth {snow_depth:.1f} cm is below the minimum "
|
||||
f"required {min_snow} cm."
|
||||
)
|
||||
logger.info(
|
||||
"[%s] Rule 2 fired: snow depth %.1f < %.1f cm -> force_closed",
|
||||
station_name,
|
||||
snow_depth,
|
||||
min_snow,
|
||||
)
|
||||
|
||||
# ---- Rule 3: High temperature + rain -> reduce km_factor ---------
|
||||
temp_max = weather_data.get("temperature_2m_max")
|
||||
precip = weather_data.get("precipitation_sum", 0.0)
|
||||
|
||||
if (
|
||||
temp_max is not None
|
||||
and temp_max > _RAIN_TEMPERATURE_THRESHOLD_C
|
||||
and precip > _RAIN_PRECIPITATION_THRESHOLD_MM
|
||||
):
|
||||
km_factor = max(0.0, km_factor - _WARM_RAIN_KM_FACTOR_REDUCTION)
|
||||
reasons.append(
|
||||
f"Temperature {temp_max:.1f} °C above {_RAIN_TEMPERATURE_THRESHOLD_C} °C "
|
||||
f"with {precip:.1f} mm precipitation; estimated open slopes reduced."
|
||||
)
|
||||
logger.info(
|
||||
"[%s] Rule 3 fired: temp %.1f °C + rain %.1f mm -> km_factor reduced to %.2f",
|
||||
station_name,
|
||||
temp_max,
|
||||
precip,
|
||||
km_factor,
|
||||
)
|
||||
|
||||
# ---- Rule 4: 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"Heavy fresh snow ({snowfall_24h:.1f} cm in 24 h) with manageable "
|
||||
f"wind ({wind_speed:.1f} km/h); station very likely open and busy."
|
||||
)
|
||||
logger.info(
|
||||
"[%s] Rule 4 fired: heavy snow %.1f cm + wind %.1f km/h -> force_open",
|
||||
station_name,
|
||||
snowfall_24h,
|
||||
wind_speed,
|
||||
)
|
||||
|
||||
# ---- Rule 5: 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(
|
||||
"Weekday with no significant fresh snow; crowd level expected to be low."
|
||||
)
|
||||
logger.debug("[%s] Rule 5 fired: weekday + no fresh snow -> low crowd", station_name)
|
||||
|
||||
# ---- Rule 6: 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"Weekend or holiday with {snowfall_24h:.1f} cm of fresh snow; "
|
||||
"crowd level expected to be high."
|
||||
)
|
||||
logger.debug(
|
||||
"[%s] Rule 6 fired: busy day + fresh snow %.1f cm -> high crowd",
|
||||
station_name,
|
||||
snowfall_24h,
|
||||
)
|
||||
|
||||
# ---- 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
|
||||
Reference in new issue
Block a user