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,7 @@
|
||||
"""Predictor package for ski predictor.
|
||||
|
||||
Modules:
|
||||
rules: Rule-based engine that enforces physical and operational constraints.
|
||||
ml_predictor: Loads trained ML models and generates probabilistic predictions.
|
||||
hybrid_predictor: Combines rules engine and ML predictions into a final decision.
|
||||
"""
|
||||
@@ -0,0 +1,452 @@
|
||||
"""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
|
||||
@@ -0,0 +1,293 @@
|
||||
"""ML-based predictor for ski station conditions.
|
||||
|
||||
Loads pre-trained models from the ml/models/ directory and generates
|
||||
probabilistic predictions for station opening, skiable kilometres, and
|
||||
crowd level. When models are absent the predictor degrades gracefully
|
||||
and returns None so callers can fall back to rule-based logic.
|
||||
|
||||
Expected model files under ml/models/:
|
||||
- open_model.joblib : binary classifier -> open_probability
|
||||
- km_model.joblib : regressor -> km_open_prediction
|
||||
- crowd_model.joblib : multiclass classifier -> crowd_level
|
||||
"""
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import joblib
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_MODELS_DIR = Path(__file__).parent.parent / "ml" / "models"
|
||||
|
||||
_CROWD_LABELS: list[str] = ["low", "medium", "high"]
|
||||
|
||||
# Filename constants make it easy to swap model artefacts without touching logic
|
||||
_OPEN_MODEL_FILE = "station_open_model.joblib"
|
||||
_KM_MODEL_FILE = "km_open_model.joblib"
|
||||
_CROWD_MODEL_FILE = "crowd_level_model.joblib"
|
||||
_CROWD_ENCODER_FILE = "crowd_level_label_encoder.joblib"
|
||||
|
||||
|
||||
def _load_model(path: Path) -> Any | None:
|
||||
"""Load a joblib model artefact from disk.
|
||||
|
||||
Args:
|
||||
path: Absolute path to the ``.joblib`` file.
|
||||
|
||||
Returns:
|
||||
The deserialised model object, or None if the file does not exist
|
||||
or cannot be loaded.
|
||||
"""
|
||||
if not path.exists():
|
||||
logger.warning("Model file not found: %s", path)
|
||||
return None
|
||||
|
||||
try:
|
||||
model = joblib.load(path)
|
||||
logger.info("Loaded model from %s", path)
|
||||
return model
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
logger.error("Failed to load model %s: %s", path, exc)
|
||||
return None
|
||||
|
||||
|
||||
class MLPredictor:
|
||||
"""Generates ML-based predictions for ski station conditions.
|
||||
|
||||
Models are loaded lazily from ``ml/models/`` the first time
|
||||
:meth:`predict` is called, or eagerly if ``eager_load=True`` is passed
|
||||
to the constructor.
|
||||
|
||||
When a required model file is missing the corresponding output field
|
||||
is omitted from the returned dict and a warning is logged. The caller
|
||||
(typically :class:`~predictor.hybrid_predictor.HybridPredictor`) must
|
||||
handle a ``None`` return gracefully.
|
||||
|
||||
Usage::
|
||||
|
||||
predictor = MLPredictor()
|
||||
result = predictor.predict(features_df)
|
||||
if result is None:
|
||||
# No models available; fall back to rules only
|
||||
...
|
||||
|
||||
Args:
|
||||
models_dir: Optional override for the directory containing model
|
||||
artefacts. Defaults to ``ml/models/`` in the repository
|
||||
root.
|
||||
eager_load: If True, models are loaded during ``__init__``.
|
||||
Defaults to False.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
models_dir: Path | None = None,
|
||||
eager_load: bool = False,
|
||||
) -> None:
|
||||
self._models_dir = Path(models_dir) if models_dir else _MODELS_DIR
|
||||
self._open_model: Any | None = None
|
||||
self._km_model: Any | None = None
|
||||
self._crowd_model: Any | None = None
|
||||
self._crowd_encoder: Any | None = None
|
||||
self._loaded = False
|
||||
|
||||
if eager_load:
|
||||
self._load_all_models()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Private helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _load_all_models(self) -> None:
|
||||
"""Load all model artefacts from disk."""
|
||||
self._open_model = _load_model(self._models_dir / _OPEN_MODEL_FILE)
|
||||
self._km_model = _load_model(self._models_dir / _KM_MODEL_FILE)
|
||||
self._crowd_model = _load_model(self._models_dir / _CROWD_MODEL_FILE)
|
||||
self._crowd_encoder = _load_model(self._models_dir / _CROWD_ENCODER_FILE)
|
||||
self._loaded = True
|
||||
|
||||
available = [
|
||||
name
|
||||
for name, mdl in [
|
||||
("open_model", self._open_model),
|
||||
("km_model", self._km_model),
|
||||
("crowd_model", self._crowd_model),
|
||||
]
|
||||
if mdl is not None
|
||||
]
|
||||
logger.info(
|
||||
"MLPredictor loaded %d/%d model(s): %s",
|
||||
len(available),
|
||||
3,
|
||||
available,
|
||||
)
|
||||
|
||||
def _ensure_loaded(self) -> None:
|
||||
"""Lazy-load models on first prediction call."""
|
||||
if not self._loaded:
|
||||
self._load_all_models()
|
||||
|
||||
def _prepare_features(self, df: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Select and align features to match the trained model inputs.
|
||||
|
||||
Drops non-feature columns (date, station_id, target variables) and
|
||||
fills any missing feature columns with 0.0 so the model always
|
||||
receives the expected input shape.
|
||||
"""
|
||||
# Determine expected features from the first available model
|
||||
ref_model = self._open_model or self._km_model or self._crowd_model
|
||||
if ref_model is None:
|
||||
return df
|
||||
|
||||
try:
|
||||
expected = list(ref_model.feature_names_in_)
|
||||
except AttributeError:
|
||||
# Fallback: drop known non-feature columns
|
||||
drop_cols = {
|
||||
"date", "station_id", "station_open", "open_status",
|
||||
"km_open", "crowd_level", "snow_quality", "season",
|
||||
}
|
||||
expected = [c for c in df.columns if c not in drop_cols]
|
||||
|
||||
# Select only expected columns, adding missing ones as 0
|
||||
result = pd.DataFrame(index=df.index)
|
||||
for col in expected:
|
||||
if col in df.columns:
|
||||
result[col] = pd.to_numeric(df[col], errors="coerce").fillna(0.0)
|
||||
else:
|
||||
result[col] = 0.0
|
||||
logger.debug("Feature '%s' missing in input; filled with 0.0.", col)
|
||||
|
||||
return result
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public API
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def predict(self, features_df: pd.DataFrame) -> dict[str, Any] | None:
|
||||
"""Generate predictions from a feature row.
|
||||
|
||||
Args:
|
||||
features_df: A ``pandas.DataFrame`` with exactly one row
|
||||
containing the engineered features for the prediction day.
|
||||
Column names must match those expected by the trained models
|
||||
(as defined in ``config/features.yaml``).
|
||||
|
||||
Returns:
|
||||
A dict with the following keys, or ``None`` if no models are
|
||||
available at all:
|
||||
|
||||
- ``open_probability`` (float 0–1): Probability the station opens.
|
||||
- ``km_open_prediction`` (float): Predicted km of open slopes.
|
||||
- ``crowd_level`` (str): Most likely crowd level
|
||||
(``"low"``, ``"medium"``, or ``"high"``).
|
||||
- ``crowd_probabilities`` (dict): Probability for each crowd
|
||||
level, e.g. ``{"low": 0.1, "medium": 0.4, "high": 0.5}``.
|
||||
|
||||
Any key whose model is missing is omitted from the dict.
|
||||
|
||||
Raises:
|
||||
ValueError: If ``features_df`` is empty or has more than one row.
|
||||
"""
|
||||
if features_df is None or features_df.empty:
|
||||
raise ValueError("features_df must be a non-empty DataFrame.")
|
||||
if len(features_df) != 1:
|
||||
raise ValueError(
|
||||
f"features_df must contain exactly one row; got {len(features_df)}."
|
||||
)
|
||||
|
||||
self._ensure_loaded()
|
||||
|
||||
any_model_available = any(
|
||||
m is not None
|
||||
for m in [self._open_model, self._km_model, self._crowd_model]
|
||||
)
|
||||
if not any_model_available:
|
||||
logger.warning(
|
||||
"No ML models are available in %s. "
|
||||
"Returning None; hybrid predictor will rely on rules only.",
|
||||
self._models_dir,
|
||||
)
|
||||
return None
|
||||
|
||||
# Select only the features the models were trained on, dropping
|
||||
# non-feature columns (date, station_id, target variables, etc.).
|
||||
features_df = self._prepare_features(features_df)
|
||||
|
||||
result: dict[str, Any] = {}
|
||||
|
||||
# ---- Open probability -------------------------------------------
|
||||
if self._open_model is not None:
|
||||
try:
|
||||
proba = self._open_model.predict_proba(features_df)
|
||||
# scikit-learn convention: class order matches model.classes_
|
||||
classes = list(self._open_model.classes_)
|
||||
open_idx = classes.index(1) if 1 in classes else -1
|
||||
open_prob = float(proba[0][open_idx]) if open_idx >= 0 else float(proba[0][1])
|
||||
result["open_probability"] = float(np.clip(open_prob, 0.0, 1.0))
|
||||
logger.debug("open_probability: %.3f", result["open_probability"])
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
logger.error("open_model prediction failed: %s", exc)
|
||||
else:
|
||||
logger.warning("open_model not loaded; 'open_probability' will be absent.")
|
||||
|
||||
# ---- km open prediction -----------------------------------------
|
||||
if self._km_model is not None:
|
||||
try:
|
||||
km_pred = float(self._km_model.predict(features_df)[0])
|
||||
result["km_open_prediction"] = max(0.0, km_pred)
|
||||
logger.debug("km_open_prediction: %.2f", result["km_open_prediction"])
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
logger.error("km_model prediction failed: %s", exc)
|
||||
else:
|
||||
logger.warning("km_model not loaded; 'km_open_prediction' will be absent.")
|
||||
|
||||
# ---- Crowd level -------------------------------------------------
|
||||
if self._crowd_model is not None:
|
||||
try:
|
||||
crowd_proba = self._crowd_model.predict_proba(features_df)[0]
|
||||
predicted_encoded = int(np.argmax(crowd_proba))
|
||||
|
||||
# Decode numeric class back to string label
|
||||
if self._crowd_encoder is not None:
|
||||
encoded_classes = list(self._crowd_model.classes_)
|
||||
decoded_classes = list(
|
||||
self._crowd_encoder.inverse_transform(encoded_classes)
|
||||
)
|
||||
predicted_crowd = str(
|
||||
self._crowd_encoder.inverse_transform(
|
||||
[encoded_classes[predicted_encoded]]
|
||||
)[0]
|
||||
)
|
||||
else:
|
||||
# Fallback: assume classes map directly to _CROWD_LABELS
|
||||
decoded_classes = _CROWD_LABELS[: len(self._crowd_model.classes_)]
|
||||
predicted_crowd = decoded_classes[predicted_encoded]
|
||||
|
||||
# Build probability dict aligned to canonical label order
|
||||
crowd_prob_dict: dict[str, float] = {}
|
||||
for i, label in enumerate(decoded_classes):
|
||||
crowd_prob_dict[label] = float(crowd_proba[i])
|
||||
# Ensure all canonical labels present
|
||||
for label in _CROWD_LABELS:
|
||||
if label not in crowd_prob_dict:
|
||||
crowd_prob_dict[label] = 0.0
|
||||
|
||||
result["crowd_level"] = predicted_crowd
|
||||
result["crowd_probabilities"] = crowd_prob_dict
|
||||
logger.debug(
|
||||
"crowd_level: %s | probabilities: %s",
|
||||
result["crowd_level"],
|
||||
crowd_prob_dict,
|
||||
)
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
logger.error("crowd_model prediction failed: %s", exc)
|
||||
else:
|
||||
logger.warning("crowd_model not loaded; crowd fields will be absent.")
|
||||
|
||||
logger.info("MLPredictor result keys: %s", list(result.keys()))
|
||||
return result if result else None
|
||||
@@ -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