mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 15:26:15 +00:00
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
453 lines
17 KiB
Python
453 lines
17 KiB
Python
"""Hybrid predictor combining rule-based and ML predictions.
|
||
|
||
Implements the three-stage prediction pipeline defined in AGENTS.md:
|
||
|
||
Stage 1 – Evaluate the rules engine.
|
||
Stage 2 – Compute ML prediction (when rules are inconclusive).
|
||
Stage 3 – Merge both outputs into a single final prediction.
|
||
|
||
Rules always have priority over the ML model when a physical or safety
|
||
constraint makes the outcome deterministic. The ML model is used for
|
||
probabilistic refinement when rules do not resolve the outcome.
|
||
"""
|
||
|
||
import logging
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
import pandas as pd
|
||
import yaml
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
_CONFIG_PATH = Path(__file__).parent.parent / "config" / "stations.yaml"
|
||
|
||
# When rules are inconclusive the ML crowd prediction is used as-is.
|
||
# These defaults are applied only when neither source provides a crowd level.
|
||
_DEFAULT_CROWD_LEVEL = "medium"
|
||
_DEFAULT_OPEN_PROBABILITY = 0.5
|
||
_DEFAULT_KM_FACTOR = 1.0
|
||
|
||
|
||
def _load_station_name(station_id: str, config_path: Path) -> str:
|
||
"""Return the human-readable station name from configuration.
|
||
|
||
Args:
|
||
station_id: Key identifying the station (e.g. ``"pajares"``).
|
||
config_path: Path to ``stations.yaml``.
|
||
|
||
Returns:
|
||
The ``name`` field from the station config, or ``station_id`` if
|
||
the file or key cannot be read.
|
||
"""
|
||
try:
|
||
with config_path.open("r", encoding="utf-8") as fh:
|
||
raw = yaml.safe_load(fh)
|
||
return raw["stations"][station_id]["name"]
|
||
except Exception as exc: # pylint: disable=broad-except
|
||
logger.warning(
|
||
"Could not read station name for '%s' from %s: %s",
|
||
station_id,
|
||
config_path,
|
||
exc,
|
||
)
|
||
return station_id
|
||
|
||
|
||
def _build_weather_summary(weather_data: dict[str, Any]) -> str:
|
||
"""Compose a concise human-readable summary of relevant weather conditions.
|
||
|
||
Args:
|
||
weather_data: The same dict passed to :meth:`HybridPredictor.predict`.
|
||
|
||
Returns:
|
||
A single-line string summarising the most operationally relevant
|
||
weather factors present in the data.
|
||
"""
|
||
parts: list[str] = []
|
||
|
||
temp_max = weather_data.get("temperature_2m_max")
|
||
temp_min = weather_data.get("temperature_2m_min")
|
||
if temp_max is not None and temp_min is not None:
|
||
parts.append(f"Temp {temp_min:.0f}–{temp_max:.0f} °C")
|
||
elif temp_max is not None:
|
||
parts.append(f"Temp max {temp_max:.0f} °C")
|
||
|
||
snowfall = weather_data.get("snowfall_sum")
|
||
if snowfall is not None and snowfall > 0:
|
||
parts.append(f"Snow {snowfall:.0f} cm")
|
||
|
||
snow_depth = weather_data.get("snow_depth")
|
||
if snow_depth is not None:
|
||
parts.append(f"Depth {snow_depth:.0f} cm")
|
||
|
||
precip = weather_data.get("precipitation_sum")
|
||
if precip is not None and precip > 0:
|
||
parts.append(f"Rain {precip:.1f} mm")
|
||
|
||
wind_gust = weather_data.get("wind_gusts_10m_max")
|
||
if wind_gust is not None:
|
||
parts.append(f"Gusts {wind_gust:.0f} km/h")
|
||
|
||
return " | ".join(parts) if parts else "No weather data available."
|
||
|
||
|
||
class HybridPredictor:
|
||
"""Combines the rule engine and ML predictor into a single interface.
|
||
|
||
The prediction logic follows a strict priority order:
|
||
|
||
1. If the rules engine marks the station as ``force_closed`` the
|
||
outcome is ``open_probability=0.0`` and ``km_open=0.0``, regardless
|
||
of what the ML model says.
|
||
2. If the rules engine marks the station as ``force_open`` the
|
||
``open_probability`` is set to 1.0, and the ML km prediction (if
|
||
available) is used for slope coverage.
|
||
3. Otherwise the ML prediction is used and the ``estimated_km_factor``
|
||
from the rules engine is applied as a multiplier to the km estimate.
|
||
4. When neither source can determine the crowd level a default of
|
||
``"medium"`` is used.
|
||
|
||
Usage::
|
||
|
||
from predictor.rules import RulesEngine
|
||
from predictor.ml_predictor import MLPredictor
|
||
from predictor.hybrid_predictor import HybridPredictor
|
||
|
||
predictor = HybridPredictor()
|
||
result = predictor.predict("pajares", weather_data, features_df)
|
||
|
||
Args:
|
||
rules_engine: A :class:`~predictor.rules.RulesEngine` instance.
|
||
If None, one is created with default settings.
|
||
ml_predictor: A :class:`~predictor.ml_predictor.MLPredictor` instance.
|
||
If None, one is created with default settings.
|
||
config_path: Optional override for the path to ``stations.yaml``.
|
||
"""
|
||
|
||
def __init__(
|
||
self,
|
||
rules_engine: Any | None = None,
|
||
ml_predictor: Any | None = None,
|
||
config_path: Path | None = None,
|
||
) -> None:
|
||
# Import here to avoid circular imports at module level
|
||
from predictor.rules import RulesEngine
|
||
from predictor.ml_predictor import MLPredictor
|
||
|
||
self._rules = rules_engine if rules_engine is not None else RulesEngine()
|
||
self._ml = ml_predictor if ml_predictor is not None else MLPredictor()
|
||
self._config_path = config_path or _CONFIG_PATH
|
||
|
||
logger.info("HybridPredictor initialised.")
|
||
|
||
# ------------------------------------------------------------------
|
||
# Public API
|
||
# ------------------------------------------------------------------
|
||
|
||
def predict(
|
||
self,
|
||
station_id: str,
|
||
weather_data: dict[str, Any],
|
||
features_df: pd.DataFrame | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Generate a combined prediction for tomorrow's station conditions.
|
||
|
||
Args:
|
||
station_id: Key identifying the station in ``stations.yaml``
|
||
(e.g. ``"pajares"``).
|
||
weather_data: Dict of weather variables for the prediction day.
|
||
See :meth:`~predictor.rules.RulesEngine.evaluate` for the
|
||
full list of expected keys.
|
||
features_df: A single-row ``pandas.DataFrame`` with the
|
||
engineered ML features. May be ``None`` if no trained models
|
||
exist yet; in that case only the rules engine is used.
|
||
|
||
Returns:
|
||
A dict with the following keys:
|
||
|
||
- ``station_name`` (str): Human-readable station name.
|
||
- ``open_probability`` (float): Probability the station opens
|
||
(0–1).
|
||
- ``km_open`` (float): Estimated km of open slopes.
|
||
- ``crowd_level`` (str): Expected crowd level
|
||
(``"low"``, ``"medium"``, or ``"high"``).
|
||
- ``weather_summary`` (str): Brief weather description.
|
||
- ``rule_overrides`` (list[str]): Reasons from the rules
|
||
engine that influenced the prediction.
|
||
- ``prediction_source`` (str): One of ``"rules"``, ``"ml"``,
|
||
or ``"hybrid"`` indicating which source drove the result.
|
||
|
||
Raises:
|
||
ValueError: If station_id is not found in the configuration.
|
||
"""
|
||
station_name = _load_station_name(station_id, self._config_path)
|
||
weather_summary = _build_weather_summary(weather_data)
|
||
|
||
logger.info("HybridPredictor.predict called for station '%s'.", station_name)
|
||
|
||
# Stage 1: Rules engine ------------------------------------------
|
||
rules_result = self._rules.evaluate(station_id, weather_data)
|
||
force_closed = rules_result["force_closed"]
|
||
force_open = rules_result["force_open"]
|
||
km_factor = rules_result.get("estimated_km_factor", _DEFAULT_KM_FACTOR)
|
||
rule_reasons = rules_result.get("reasons", [])
|
||
|
||
logger.debug(
|
||
"Rules result for '%s': force_closed=%s, force_open=%s, km_factor=%.2f",
|
||
station_name,
|
||
force_closed,
|
||
force_open,
|
||
km_factor,
|
||
)
|
||
|
||
# Stage 2: ML prediction (skipped when rules are deterministic) ---
|
||
ml_result: dict[str, Any] | None = None
|
||
|
||
if not force_closed and features_df is not None:
|
||
try:
|
||
ml_result = self._ml.predict(features_df)
|
||
if ml_result is not None:
|
||
logger.debug("ML result for '%s': %s", station_name, ml_result)
|
||
else:
|
||
logger.info(
|
||
"ML predictor returned None for '%s'; using rules only.",
|
||
station_name,
|
||
)
|
||
except Exception as exc: # pylint: disable=broad-except
|
||
logger.error(
|
||
"ML prediction failed for '%s': %s. Falling back to rules.",
|
||
station_name,
|
||
exc,
|
||
)
|
||
|
||
# Stage 3: Merge -------------------------------------------------
|
||
open_probability, km_open, crowd_level, prediction_source = self._merge(
|
||
station_id=station_id,
|
||
station_name=station_name,
|
||
force_closed=force_closed,
|
||
force_open=force_open,
|
||
km_factor=km_factor,
|
||
rules_result=rules_result,
|
||
ml_result=ml_result,
|
||
weather_data=weather_data,
|
||
)
|
||
|
||
result = {
|
||
"station_name": station_name,
|
||
"open_probability": round(open_probability, 4),
|
||
"km_open": round(km_open, 2),
|
||
"crowd_level": crowd_level,
|
||
"weather_summary": weather_summary,
|
||
"rule_overrides": rule_reasons,
|
||
"prediction_source": prediction_source,
|
||
}
|
||
|
||
logger.info(
|
||
"Final prediction for '%s': open_prob=%.2f, km_open=%.1f, "
|
||
"crowd=%s, source=%s",
|
||
station_name,
|
||
result["open_probability"],
|
||
result["km_open"],
|
||
result["crowd_level"],
|
||
result["prediction_source"],
|
||
)
|
||
|
||
return result
|
||
|
||
# ------------------------------------------------------------------
|
||
# Private helpers
|
||
# ------------------------------------------------------------------
|
||
|
||
def _merge(
|
||
self,
|
||
station_id: str,
|
||
station_name: str,
|
||
force_closed: bool,
|
||
force_open: bool,
|
||
km_factor: float,
|
||
rules_result: dict[str, Any],
|
||
ml_result: dict[str, Any] | None,
|
||
weather_data: dict[str, Any],
|
||
) -> tuple[float, float, str, str]:
|
||
"""Apply the merge strategy and return the four core prediction values.
|
||
|
||
Args:
|
||
station_id: Station key used to retrieve max_km_skiable.
|
||
station_name: Human-readable name for logging.
|
||
force_closed: Whether the rules engine mandates closure.
|
||
force_open: Whether the rules engine mandates opening.
|
||
km_factor: Rules engine multiplier for km estimate (0–1).
|
||
rules_result: Full dict returned by the rules engine.
|
||
ml_result: Full dict returned by the ML predictor, or None.
|
||
weather_data: Raw weather variables (used for crowd inference).
|
||
|
||
Returns:
|
||
Tuple of (open_probability, km_open, crowd_level, prediction_source).
|
||
"""
|
||
# Load max km for this station to bound km_open
|
||
max_km = self._get_max_km(station_id)
|
||
|
||
# ---- Deterministic closure --------------------------------------
|
||
if force_closed:
|
||
crowd_level = self._resolve_crowd(
|
||
rules_result=rules_result,
|
||
ml_result=None, # crowd is irrelevant when closed
|
||
weather_data=weather_data,
|
||
is_open=False,
|
||
)
|
||
return 0.0, 0.0, crowd_level, "rules"
|
||
|
||
# ---- Deterministic opening (e.g. heavy fresh snow) --------------
|
||
if force_open:
|
||
km_open = self._apply_km_factor(
|
||
ml_km=ml_result.get("km_open_prediction") if ml_result else None,
|
||
km_factor=km_factor,
|
||
max_km=max_km,
|
||
)
|
||
crowd_level = self._resolve_crowd(
|
||
rules_result=rules_result,
|
||
ml_result=ml_result,
|
||
weather_data=weather_data,
|
||
is_open=True,
|
||
)
|
||
source = "hybrid" if ml_result else "rules"
|
||
return 1.0, km_open, crowd_level, source
|
||
|
||
# ---- ML-driven prediction (rules inconclusive) ------------------
|
||
if ml_result is not None:
|
||
open_prob = ml_result.get("open_probability", _DEFAULT_OPEN_PROBABILITY)
|
||
raw_km = ml_result.get("km_open_prediction")
|
||
km_open = self._apply_km_factor(
|
||
ml_km=raw_km,
|
||
km_factor=km_factor,
|
||
max_km=max_km,
|
||
)
|
||
crowd_level = self._resolve_crowd(
|
||
rules_result=rules_result,
|
||
ml_result=ml_result,
|
||
weather_data=weather_data,
|
||
is_open=open_prob >= 0.5,
|
||
)
|
||
|
||
# km_factor < 1.0 means a soft rule also contributed
|
||
source = "hybrid" if km_factor < 1.0 else "ml"
|
||
return float(open_prob), km_open, crowd_level, source
|
||
|
||
# ---- Rules-only fallback (no ML models and no deterministic rule)
|
||
logger.info(
|
||
"[%s] No ML result and no deterministic rule; "
|
||
"using rules confidence=%.2f as open_probability.",
|
||
station_name,
|
||
rules_result.get("confidence", 0.0),
|
||
)
|
||
open_prob = rules_result.get("confidence", _DEFAULT_OPEN_PROBABILITY)
|
||
km_open = max_km * km_factor
|
||
crowd_level = self._resolve_crowd(
|
||
rules_result=rules_result,
|
||
ml_result=None,
|
||
weather_data=weather_data,
|
||
is_open=open_prob >= 0.5,
|
||
)
|
||
return float(open_prob), km_open, crowd_level, "rules"
|
||
|
||
def _apply_km_factor(
|
||
self,
|
||
ml_km: float | None,
|
||
km_factor: float,
|
||
max_km: float,
|
||
) -> float:
|
||
"""Return km_open bounded by max_km and adjusted by km_factor.
|
||
|
||
Args:
|
||
ml_km: Raw km prediction from the ML model. If None, max_km
|
||
is used as a ceiling reference.
|
||
km_factor: Multiplier from the rules engine (0–1).
|
||
max_km: Maximum skiable km for the station.
|
||
|
||
Returns:
|
||
Adjusted km value, clamped to [0, max_km].
|
||
"""
|
||
base = ml_km if ml_km is not None else max_km
|
||
adjusted = base * km_factor
|
||
clamped = max(0.0, min(adjusted, max_km))
|
||
logger.debug(
|
||
"km calculation: base=%.2f * factor=%.2f = %.2f (max=%.2f)",
|
||
base,
|
||
km_factor,
|
||
adjusted,
|
||
max_km,
|
||
)
|
||
return clamped
|
||
|
||
def _resolve_crowd(
|
||
self,
|
||
rules_result: dict[str, Any],
|
||
ml_result: dict[str, Any] | None,
|
||
weather_data: dict[str, Any],
|
||
is_open: bool,
|
||
) -> str:
|
||
"""Determine the crowd level from available sources.
|
||
|
||
Priority:
|
||
1. If station is closed -> "low" (no visitors).
|
||
2. If the rules engine fired a crowd-related reason, infer
|
||
from that reason.
|
||
3. ML crowd_level if available.
|
||
4. Calendar-based heuristic (weekend/holiday vs. weekday).
|
||
5. Default: "medium".
|
||
|
||
Args:
|
||
rules_result: Full rules engine output.
|
||
ml_result: Full ML predictor output, or None.
|
||
weather_data: Raw weather dict (for calendar features).
|
||
is_open: Whether the station is predicted to open.
|
||
|
||
Returns:
|
||
A crowd level string: ``"low"``, ``"medium"``, or ``"high"``.
|
||
"""
|
||
if not is_open:
|
||
return "low"
|
||
|
||
reasons = rules_result.get("reasons", [])
|
||
reasons_text = " ".join(reasons).lower()
|
||
|
||
# Infer crowd from rule reasons text
|
||
if "high crowd" in reasons_text or "busy" in reasons_text:
|
||
return "high"
|
||
if "low crowd" in reasons_text:
|
||
return "low"
|
||
|
||
# Use ML prediction if available
|
||
if ml_result and "crowd_level" in ml_result:
|
||
return str(ml_result["crowd_level"])
|
||
|
||
# Calendar heuristic
|
||
is_weekend = bool(weather_data.get("is_weekend", False))
|
||
is_holiday = bool(weather_data.get("is_holiday", False))
|
||
if is_weekend or is_holiday:
|
||
return "medium"
|
||
|
||
return _DEFAULT_CROWD_LEVEL
|
||
|
||
def _get_max_km(self, station_id: str) -> float:
|
||
"""Return max_km_skiable for the given station from config.
|
||
|
||
Args:
|
||
station_id: Station key in ``stations.yaml``.
|
||
|
||
Returns:
|
||
The configured maximum skiable km, or 10.0 if it cannot be read.
|
||
"""
|
||
try:
|
||
with self._config_path.open("r", encoding="utf-8") as fh:
|
||
raw = yaml.safe_load(fh)
|
||
return float(raw["stations"][station_id]["max_km_skiable"])
|
||
except Exception as exc: # pylint: disable=broad-except
|
||
logger.warning(
|
||
"Could not read max_km_skiable for '%s': %s. Defaulting to 10.0.",
|
||
station_id,
|
||
exc,
|
||
)
|
||
return 10.0
|