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:
dasemu committed 2026-03-12 14:51:32 +01:00
commit 1afe2b73e0
34 files changed
+7201

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Test suite for the ski predictor project."""
+483
View File
@@ -0,0 +1,483 @@
"""Unit tests for CrowdAnalyzer in data_sources/crowd_analyzer.py.
Tests cover:
- Instantiation without loading the YOLO model.
- Crowd density threshold classification across all boundary conditions.
- analyze_image() with a mocked YOLO model.
- estimate_crowd_level() with mocked WebcamCollector and YOLO.
- analyze_all_stations() integration across all three stations.
- JSON persistence of results.
"""
from __future__ import annotations
import json
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
_STATIONS_CONFIG = {
"stations": {
"pajares": {
"name": "Valgrande-Pajares",
"latitude": 43.05,
"longitude": -5.77,
"altitude": 1500,
"wind_closure_threshold": 80,
"minimum_snow_depth": 30,
"max_km_skiable": 22.0,
"url": "https://www.valgrande-pajares.com",
"telegram_command": "/pajares",
"webcams": {
"primary_webcam_page": "https://www.infonieve.es/estacion-esqui/valgrande-pajares/webcams/",
"snapshots": [
{
"label": "Cuitu Negru - Telecabina",
"static": False,
}
],
},
},
"sanisidro": {
"name": "San Isidro",
"latitude": 43.07,
"longitude": -5.37,
"altitude": 1500,
"wind_closure_threshold": 80,
"minimum_snow_depth": 30,
"max_km_skiable": 31.0,
"url": "https://www.san-isidro.net",
"telegram_command": "/sanisidro",
"webcams": {
"snapshots": [
{
"label": "Cebolledo I",
"url": "https://www.nieveleonsanisidro.com/img/sanisidro/webcam/CebolledoI.jpg",
"static": True,
}
],
},
},
"fuentes": {
"name": "Fuentes de Invierno",
"latitude": 43.0833,
"longitude": -5.9333,
"altitude": 1500,
"wind_closure_threshold": 80,
"minimum_snow_depth": 30,
"max_km_skiable": 8.6,
"url": "https://www.fuentesdeinvierno.com",
"telegram_command": "/fuentes",
"webcams": {
"snapshots": [
{
"label": "Camara 1",
"url": "https://fuentesdeinvierno.com/tmp/camara1.jpg",
"static": True,
"ssl_verify": False,
}
],
},
},
}
}
def _make_analyzer(tmp_path: Path) -> "CrowdAnalyzer":
"""Return a CrowdAnalyzer with config loading and model instantiation bypassed."""
with patch(
"data_sources.crowd_analyzer.CrowdAnalyzer._load_stations",
return_value=_STATIONS_CONFIG["stations"],
):
from data_sources.crowd_analyzer import CrowdAnalyzer
analyzer = CrowdAnalyzer(
config_path=tmp_path / "stations.yaml",
output_dir=tmp_path,
)
return analyzer
def _make_yolo_result(
cls_names: list[str],
confidences: list[float],
) -> list[MagicMock]:
"""Build a fake YOLO results list with the given class names and confidences.
Parameters
----------
cls_names:
List of COCO class name strings for each detected box.
confidences:
Confidence score per detection (same order as cls_names).
"""
result = MagicMock()
result.names = {i: name for i, name in enumerate(set(cls_names))}
# Build a reverse lookup so the mock returns the right cls_id for each box.
name_to_id = {v: k for k, v in result.names.items()}
boxes = []
for name, conf in zip(cls_names, confidences):
box = MagicMock()
box.conf = [conf]
box.cls = [name_to_id[name]]
boxes.append(box)
result.boxes = boxes
return [result]
# ---------------------------------------------------------------------------
# Tests – instantiation
# ---------------------------------------------------------------------------
class TestInstantiation:
"""CrowdAnalyzer must be importable and instantiable without loading YOLO."""
def test_can_be_instantiated(self, tmp_path):
"""CrowdAnalyzer.__init__ must not attempt to load the YOLO model."""
analyzer = _make_analyzer(tmp_path)
# The model must remain un-loaded (lazy) after construction.
assert analyzer._model is None
def test_output_dir_is_created(self, tmp_path):
"""The output directory must exist after initialisation."""
out_dir = tmp_path / "outputs" / "raw"
with patch(
"data_sources.crowd_analyzer.CrowdAnalyzer._load_stations",
return_value=_STATIONS_CONFIG["stations"],
):
from data_sources.crowd_analyzer import CrowdAnalyzer
CrowdAnalyzer(
config_path=tmp_path / "stations.yaml",
output_dir=out_dir,
)
assert out_dir.is_dir()
def test_stations_are_loaded(self, tmp_path):
"""All three stations must be present in self.stations after init."""
analyzer = _make_analyzer(tmp_path)
assert set(analyzer.stations.keys()) == {"pajares", "sanisidro", "fuentes"}
# ---------------------------------------------------------------------------
# Tests – _classify_density thresholds
# ---------------------------------------------------------------------------
class TestClassifyDensity:
"""_classify_density must apply the documented car/person thresholds."""
# Import once so all methods share it.
@pytest.fixture(autouse=True)
def _import(self):
from data_sources.crowd_analyzer import CrowdAnalyzer
self.classify = CrowdAnalyzer._classify_density
# -- Low density --
def test_zero_cars_zero_people_is_low(self):
assert self.classify(0, 0) == "low"
def test_below_car_threshold_is_low(self):
"""19 cars and 0 people must produce 'low'."""
assert self.classify(19, 0) == "low"
def test_below_person_threshold_is_low(self):
"""0 cars and 9 people must produce 'low'."""
assert self.classify(0, 9) == "low"
# -- Medium density --
def test_car_at_low_threshold_is_medium(self):
"""Exactly 20 cars must cross into 'medium'."""
assert self.classify(20, 0) == "medium"
def test_car_at_high_threshold_is_medium(self):
"""Exactly 50 cars must still be 'medium' (not high)."""
assert self.classify(50, 0) == "medium"
def test_person_at_low_threshold_is_medium(self):
"""Exactly 10 people must cross into 'medium'."""
assert self.classify(0, 10) == "medium"
def test_person_at_high_threshold_is_medium(self):
"""Exactly 30 people must still be 'medium'."""
assert self.classify(0, 30) == "medium"
def test_mixed_medium_cars_low_people(self):
"""Medium cars + low people -> 'medium' (max wins)."""
assert self.classify(25, 5) == "medium"
# -- High density --
def test_above_car_threshold_is_high(self):
"""51 cars must produce 'high'."""
assert self.classify(51, 0) == "high"
def test_above_person_threshold_is_high(self):
"""31 people must produce 'high'."""
assert self.classify(0, 31) == "high"
def test_high_people_overrides_low_cars(self):
"""High person count must push density to 'high' even with few cars."""
assert self.classify(5, 35) == "high"
def test_high_cars_overrides_low_people(self):
"""High car count must push density to 'high' even with few people."""
assert self.classify(60, 2) == "high"
# -- Boundary correctness --
def test_boundary_19_cars_is_low(self):
assert self.classify(19, 0) == "low"
def test_boundary_20_cars_is_medium(self):
assert self.classify(20, 0) == "medium"
def test_boundary_50_cars_is_medium(self):
assert self.classify(50, 0) == "medium"
def test_boundary_51_cars_is_high(self):
assert self.classify(51, 0) == "high"
# ---------------------------------------------------------------------------
# Tests – analyze_image with mocked YOLO
# ---------------------------------------------------------------------------
class TestAnalyzeImage:
"""analyze_image must correctly aggregate YOLO detections."""
def _run(self, tmp_path: Path, cls_names: list[str], confidences: list[float]):
"""Helper: run analyze_image with a synthetic YOLO output."""
analyzer = _make_analyzer(tmp_path)
fake_results = _make_yolo_result(cls_names, confidences)
# Create a dummy image file so the path existence check passes.
img_path = tmp_path / "test_frame.jpg"
img_path.write_bytes(b"\xff\xd8\xff" + b"\x00" * 100)
# Mock both _load_model and the YOLO call.
mock_model = MagicMock(return_value=fake_results)
analyzer._model = mock_model
return analyzer.analyze_image(str(img_path))
def test_counts_cars_correctly(self, tmp_path):
"""Three cars in detections must produce cars_detected=3."""
result = self._run(tmp_path, ["car", "car", "car"], [0.9, 0.85, 0.8])
assert result["cars_detected"] == 3
def test_counts_people_correctly(self, tmp_path):
"""Two people detections must produce people_detected=2."""
result = self._run(tmp_path, ["person", "person"], [0.95, 0.88])
assert result["people_detected"] == 2
def test_counts_buses_correctly(self, tmp_path):
"""One bus detection must produce buses_detected=1."""
result = self._run(tmp_path, ["bus"], [0.7])
assert result["buses_detected"] == 1
def test_total_vehicles_excludes_people(self, tmp_path):
"""total_vehicles must count cars + buses + trucks, not people."""
result = self._run(
tmp_path,
["car", "person", "bus", "truck"],
[0.9, 0.9, 0.8, 0.75],
)
assert result["total_vehicles"] == 3 # car + bus + truck
assert result["people_detected"] == 1
def test_confidence_scores_are_included(self, tmp_path):
"""All detection confidence scores must be present in the result."""
result = self._run(tmp_path, ["car", "person"], [0.91, 0.82])
assert len(result["confidence_scores"]) == 2
assert all(0.0 <= s <= 1.0 for s in result["confidence_scores"])
def test_result_has_required_keys(self, tmp_path):
"""analyze_image must return all documented keys."""
result = self._run(tmp_path, [], [])
required = {
"cars_detected",
"people_detected",
"buses_detected",
"total_vehicles",
"crowd_density",
"confidence_scores",
"timestamp",
}
assert required.issubset(result.keys())
def test_crowd_density_is_valid_string(self, tmp_path):
"""crowd_density must be one of the three documented values."""
result = self._run(tmp_path, ["car"] * 5, [0.9] * 5)
assert result["crowd_density"] in {"low", "medium", "high"}
def test_empty_image_gives_low_density(self, tmp_path):
"""An image with no detections must yield density='low'."""
result = self._run(tmp_path, [], [])
assert result["crowd_density"] == "low"
def test_raises_file_not_found(self, tmp_path):
"""FileNotFoundError must be raised when the image path does not exist."""
analyzer = _make_analyzer(tmp_path)
analyzer._model = MagicMock()
with pytest.raises(FileNotFoundError):
analyzer.analyze_image(str(tmp_path / "nonexistent.jpg"))
# ---------------------------------------------------------------------------
# Tests – estimate_crowd_level
# ---------------------------------------------------------------------------
class TestEstimateCrowdLevel:
"""estimate_crowd_level must capture a webcam image and analyse it."""
def _run_with_mocks(
self,
tmp_path: Path,
station_id: str,
captured_paths: list[str],
cls_names: list[str],
confidences: list[float],
):
"""Run estimate_crowd_level with WebcamCollector and YOLO both mocked.
WebcamCollector is imported inside estimate_crowd_level at call-time,
so we patch it at its definition site in ``data_sources.webcam_collector``.
"""
analyzer = _make_analyzer(tmp_path)
# Ensure a real image file exists if the collector is to return a path.
for p in captured_paths:
Path(p).parent.mkdir(parents=True, exist_ok=True)
Path(p).write_bytes(b"\xff\xd8\xff" + b"\x00" * 100)
fake_results = _make_yolo_result(cls_names, confidences)
mock_yolo = MagicMock(return_value=fake_results)
analyzer._model = mock_yolo
# Patch at the definition module so the local import inside
# estimate_crowd_level picks up the mock.
with patch(
"data_sources.webcam_collector.WebcamCollector"
) as MockCollector:
mock_instance = MockCollector.return_value
mock_instance.capture.return_value = captured_paths
result = analyzer.estimate_crowd_level(station_id)
return result
def test_returns_crowd_density_string(self, tmp_path):
"""estimate_crowd_level must return a dict with a crowd_density key."""
img = str(tmp_path / "frame.jpg")
result = self._run_with_mocks(tmp_path, "pajares", [img], ["car"] * 5, [0.9] * 5)
assert "crowd_density" in result
assert result["crowd_density"] in {"low", "medium", "high", "unknown"}
def test_result_includes_station_id(self, tmp_path):
"""The returned dict must carry the station_id."""
img = str(tmp_path / "frame.jpg")
result = self._run_with_mocks(tmp_path, "sanisidro", [img], [], [])
assert result["station_id"] == "sanisidro"
def test_result_includes_image_path(self, tmp_path):
"""The returned dict must carry the image path used for analysis."""
img = str(tmp_path / "frame.jpg")
result = self._run_with_mocks(tmp_path, "fuentes", [img], [], [])
assert result["image_path"] == img
def test_unknown_density_when_no_capture(self, tmp_path):
"""When the webcam collector returns no images, density must be 'unknown'."""
result = self._run_with_mocks(tmp_path, "pajares", [], [], [])
assert result["crowd_density"] == "unknown"
def test_result_is_saved_to_json(self, tmp_path):
"""A JSON file must be written to output_dir after analysis."""
img = str(tmp_path / "frame.jpg")
self._run_with_mocks(tmp_path, "pajares", [img], ["person"] * 3, [0.9] * 3)
from datetime import date
today = date.today().strftime("%Y-%m-%d")
json_file = tmp_path / f"crowd_pajares_{today}.json"
assert json_file.exists()
def test_json_contains_valid_list(self, tmp_path):
"""The saved JSON file must contain a list with at least one result."""
img = str(tmp_path / "frame.jpg")
self._run_with_mocks(tmp_path, "pajares", [img], ["car"], [0.85])
from datetime import date
today = date.today().strftime("%Y-%m-%d")
json_file = tmp_path / f"crowd_pajares_{today}.json"
data = json.loads(json_file.read_text())
assert isinstance(data, list)
assert len(data) >= 1
def test_multiple_calls_append_to_json(self, tmp_path):
"""Successive calls must append results to the same JSON file."""
img = str(tmp_path / "frame.jpg")
self._run_with_mocks(tmp_path, "sanisidro", [img], ["car"], [0.9])
self._run_with_mocks(tmp_path, "sanisidro", [img], ["person"], [0.8])
from datetime import date
today = date.today().strftime("%Y-%m-%d")
json_file = tmp_path / f"crowd_sanisidro_{today}.json"
data = json.loads(json_file.read_text())
assert len(data) == 2
# ---------------------------------------------------------------------------
# Tests – analyze_all_stations
# ---------------------------------------------------------------------------
class TestAnalyzeAllStations:
"""analyze_all_stations must process every configured station."""
def test_returns_all_station_ids(self, tmp_path):
"""The result dict must contain keys for all three stations."""
analyzer = _make_analyzer(tmp_path)
# Patch estimate_crowd_level to avoid real I/O.
def _fake_estimate(station_id):
return {
"station_id": station_id,
"crowd_density": "low",
"cars_detected": 0,
"people_detected": 0,
"buses_detected": 0,
"total_vehicles": 0,
"confidence_scores": [],
"timestamp": "2026-01-01T12:00:00",
"image_path": None,
}
with patch.object(analyzer, "estimate_crowd_level", side_effect=_fake_estimate):
results = analyzer.analyze_all_stations()
assert set(results.keys()) == {"pajares", "sanisidro", "fuentes"}
def test_all_results_have_crowd_density(self, tmp_path):
"""Every station result must contain a crowd_density key."""
analyzer = _make_analyzer(tmp_path)
def _fake_estimate(station_id):
return {"station_id": station_id, "crowd_density": "medium"}
with patch.object(analyzer, "estimate_crowd_level", side_effect=_fake_estimate):
results = analyzer.analyze_all_stations()
for station_id, result in results.items():
assert "crowd_density" in result, f"Missing crowd_density for {station_id}"
+230
View File
@@ -0,0 +1,230 @@
"""Unit tests for the FeatureEngineer in pipeline/feature_engineering.py.
Tests verify that derived features are computed correctly against known
reference DataFrames. Each test class is focused on a single feature group.
"""
import pytest
import pandas as pd
import numpy as np
from datetime import date, timedelta
from unittest.mock import patch
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _next_weekday(weekday: int) -> date:
"""Return the next calendar date whose weekday() equals *weekday*.
Monday=0, Tuesday=1, ..., Saturday=5, Sunday=6.
"""
today = date.today()
days_ahead = (weekday - today.weekday()) % 7
if days_ahead == 0:
days_ahead = 7 # ensure we get a future date to avoid "today" edge case
return today + timedelta(days=days_ahead)
def _make_base_df(
n_days: int = 14,
station_id: str = "pajares",
start_date: date | None = None,
) -> pd.DataFrame:
"""Build a minimal raw dataset for one station spanning n_days."""
if start_date is None:
start_date = date.today() - timedelta(days=n_days - 1)
dates = [start_date + timedelta(days=i) for i in range(n_days)]
return pd.DataFrame(
{
"date": pd.to_datetime(dates),
"station_id": station_id,
"temperature_2m_max": [2.0] * n_days,
"temperature_2m_min": [-4.0] * n_days,
"temperature_2m_mean": [-1.0] * n_days,
"precipitation_sum": [0.0] * n_days,
"snowfall_sum": [0.0] * n_days,
"wind_speed_10m_max": [20.0] * n_days,
"wind_gusts_10m_max": [35.0] * n_days,
"wind_direction_10m_dominant": [270.0] * n_days,
"relative_humidity_2m_mean": [75.0] * n_days,
"surface_pressure_mean": [1013.0] * n_days,
"open_status": [True] * n_days,
"km_open": [15.0] * n_days,
"snow_depth": [60] * n_days,
}
)
# Features config that enables all engineered features
_FEATURES_CONFIG = {
"engineered_features": [
"snow_last_3_days",
"snow_last_7_days",
"avg_temperature_3_days",
"max_wind_gust",
"is_weekend",
"is_holiday",
"month_of_year",
"day_of_week",
"days_since_last_snowfall",
"temperature_trend_3_days",
"pressure_trend_3_days",
]
}
@pytest.fixture()
def feature_engineer():
"""Return a FeatureEngineer instance with config loading bypassed."""
with patch(
"pipeline.feature_engineering.FeatureEngineer._load_config",
return_value=_FEATURES_CONFIG,
):
from pipeline.feature_engineering import FeatureEngineer
engineer = FeatureEngineer()
return engineer
# ---------------------------------------------------------------------------
# Tests – is_weekend
# ---------------------------------------------------------------------------
class TestIsWeekend:
"""is_weekend must be 1 only for Saturday (5) and Sunday (6)."""
def test_saturday_is_weekend(self, feature_engineer):
"""Saturday rows must have is_weekend == 1."""
saturday = _next_weekday(5)
df = _make_base_df(n_days=1, start_date=saturday)
result = feature_engineer.transform(df)
assert result["is_weekend"].iloc[0] == 1
def test_sunday_is_weekend(self, feature_engineer):
"""Sunday rows must have is_weekend == 1."""
sunday = _next_weekday(6)
df = _make_base_df(n_days=1, start_date=sunday)
result = feature_engineer.transform(df)
assert result["is_weekend"].iloc[0] == 1
def test_monday_is_not_weekend(self, feature_engineer):
"""Monday rows must have is_weekend == 0."""
monday = _next_weekday(0)
df = _make_base_df(n_days=1, start_date=monday)
result = feature_engineer.transform(df)
assert result["is_weekend"].iloc[0] == 0
def test_friday_is_not_weekend(self, feature_engineer):
"""Friday rows must have is_weekend == 0."""
friday = _next_weekday(4)
df = _make_base_df(n_days=1, start_date=friday)
result = feature_engineer.transform(df)
assert result["is_weekend"].iloc[0] == 0
# ---------------------------------------------------------------------------
# Tests – snow_last_3_days
# ---------------------------------------------------------------------------
class TestSnowLast3Days:
"""snow_last_3_days is the rolling 3-day sum of previous snowfall."""
def test_correct_rolling_sum(self, feature_engineer):
"""Rolling 3-day snowfall sum must match manual computation."""
df = _make_base_df(n_days=7)
snowfalls = [0.0, 5.0, 3.0, 0.0, 8.0, 2.0, 1.0]
df["snowfall_sum"] = snowfalls
result = feature_engineer.transform(df)
# snow_last_3_days uses shift(1) then rolling(3), so for row 6:
# shifted values at positions 3,4,5 = 0.0, 8.0, 2.0 -> sum = 10.0
expected_last = snowfalls[3] + snowfalls[4] + snowfalls[5]
assert result["snow_last_3_days"].iloc[6] == pytest.approx(expected_last)
def test_zero_snowfall_gives_zero(self, feature_engineer):
"""All-zero snowfall must produce a zero rolling sum."""
df = _make_base_df(n_days=5)
df["snowfall_sum"] = 0.0
result = feature_engineer.transform(df)
assert (result["snow_last_3_days"].fillna(0.0) == 0.0).all()
def test_single_row_nan(self, feature_engineer):
"""With only one row, snow_last_3_days is NaN (no prior data after shift)."""
df = _make_base_df(n_days=1)
df["snowfall_sum"] = 7.0
result = feature_engineer.transform(df)
assert pd.isna(result["snow_last_3_days"].iloc[0])
# ---------------------------------------------------------------------------
# Tests – days_since_last_snowfall
# ---------------------------------------------------------------------------
class TestDaysSinceLastSnowfall:
"""days_since_last_snowfall counts days since the last snow event."""
def test_zero_when_it_snowed_today(self, feature_engineer):
"""If the most recent row has snowfall > 0, days_since must be 0."""
df = _make_base_df(n_days=5)
df["snowfall_sum"] = [0.0, 0.0, 0.0, 0.0, 3.0]
result = feature_engineer.transform(df)
assert result["days_since_last_snowfall"].iloc[4] == 0
def test_increments_correctly(self, feature_engineer):
"""Days-since counter must increment by 1 for each snow-free day."""
df = _make_base_df(n_days=5)
df["snowfall_sum"] = [5.0, 0.0, 0.0, 0.0, 0.0]
result = feature_engineer.transform(df)
assert result["days_since_last_snowfall"].iloc[1] == 1
assert result["days_since_last_snowfall"].iloc[2] == 2
assert result["days_since_last_snowfall"].iloc[3] == 3
assert result["days_since_last_snowfall"].iloc[4] == 4
def test_resets_after_new_snowfall(self, feature_engineer):
"""Counter must reset to 0 when snowfall resumes after a dry spell."""
df = _make_base_df(n_days=6)
df["snowfall_sum"] = [3.0, 0.0, 0.0, 0.0, 5.0, 0.0]
result = feature_engineer.transform(df)
assert result["days_since_last_snowfall"].iloc[4] == 0
assert result["days_since_last_snowfall"].iloc[5] == 1
# ---------------------------------------------------------------------------
# Tests – temperature_trend
# ---------------------------------------------------------------------------
class TestTemperatureTrend:
"""temperature_trend_3_days is the difference between today and 3 days ago."""
def test_positive_trend_when_warming(self, feature_engineer):
"""Increasing temperatures must produce a positive trend value."""
df = _make_base_df(n_days=5)
df["temperature_2m_mean"] = [-5.0, -4.0, -3.0, -2.0, -1.0]
result = feature_engineer.transform(df)
assert result["temperature_trend_3_days"].iloc[3] > 0
def test_negative_trend_when_cooling(self, feature_engineer):
"""Decreasing temperatures must produce a negative trend value."""
df = _make_base_df(n_days=5)
df["temperature_2m_mean"] = [5.0, 4.0, 3.0, 2.0, 1.0]
result = feature_engineer.transform(df)
assert result["temperature_trend_3_days"].iloc[4] < 0
def test_zero_trend_when_stable(self, feature_engineer):
"""Constant temperatures must produce a trend of zero."""
df = _make_base_df(n_days=5)
df["temperature_2m_mean"] = [0.0] * 5
result = feature_engineer.transform(df)
stable_rows = result["temperature_trend_3_days"].dropna()
assert all(v == pytest.approx(0.0) for v in stable_rows)
+165
View File
@@ -0,0 +1,165 @@
"""Unit tests for the RulesEngine in predictor/rules.py.
Tests cover the physical and operational constraints that must override ML
predictions when conditions are deterministic:
- Extreme wind forces the station closed regardless of other conditions.
- Insufficient snow depth forces the station closed.
- Normal conditions produce no forced outcome.
- High temperature combined with rain reduces the estimated_km_factor.
"""
import pytest
from unittest.mock import patch
# ---------------------------------------------------------------------------
# Fixtures – station config
# ---------------------------------------------------------------------------
@pytest.fixture()
def station_config():
"""Minimal station configuration mirroring config/stations.yaml structure."""
return {
"pajares": {
"name": "Valgrande-Pajares",
"wind_closure_threshold": 80, # km/h
"minimum_snow_depth": 30, # cm
"max_km_skiable": 22.0,
}
}
@pytest.fixture()
def rules_engine(station_config):
"""RulesEngine instance with mocked config loading."""
with patch("predictor.rules._load_station_configs", return_value=station_config):
from predictor.rules import RulesEngine
engine = RulesEngine()
return engine
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _weather(
wind_gust: float = 40.0,
snow_depth: int = 60,
temperature: float = 2.0,
precipitation: float = 0.0,
) -> dict:
"""Build a minimal weather observation dict for testing."""
return {
"wind_gusts_10m_max": wind_gust,
"snow_depth": snow_depth,
"temperature_2m_max": temperature,
"precipitation_sum": precipitation,
}
# ---------------------------------------------------------------------------
# Tests – wind closure
# ---------------------------------------------------------------------------
class TestWindClosure:
"""Rules triggered by wind gust exceeding the station threshold."""
def test_wind_above_threshold_forces_closed(self, rules_engine):
"""Wind gust above 80 km/h must set force_closed to True."""
weather = _weather(wind_gust=85.0)
result = rules_engine.evaluate("pajares", weather)
assert result["force_closed"] is True
def test_wind_at_threshold_forces_closed(self, rules_engine):
"""Wind gust exactly at the threshold (80 km/h) must force closure."""
weather = _weather(wind_gust=80.0)
result = rules_engine.evaluate("pajares", weather)
assert result["force_closed"] is True
def test_wind_below_threshold_does_not_force_closed(self, rules_engine):
"""Wind gust below 80 km/h must not set force_closed."""
weather = _weather(wind_gust=75.0)
result = rules_engine.evaluate("pajares", weather)
assert result["force_closed"] is False
# ---------------------------------------------------------------------------
# Tests – snow depth
# ---------------------------------------------------------------------------
class TestSnowDepth:
"""Rules triggered by insufficient snow depth."""
def test_snow_below_minimum_forces_closed(self, rules_engine):
"""Snow depth below 30 cm must set force_closed to True."""
weather = _weather(snow_depth=20)
result = rules_engine.evaluate("pajares", weather)
assert result["force_closed"] is True
def test_snow_at_minimum_does_not_force_closed(self, rules_engine):
"""Snow depth exactly at 30 cm is acceptable and must not force closure."""
weather = _weather(snow_depth=30)
result = rules_engine.evaluate("pajares", weather)
assert result["force_closed"] is False
def test_snow_above_minimum_does_not_force_closed(self, rules_engine):
"""Snow depth well above the minimum must not force closure."""
weather = _weather(snow_depth=80)
result = rules_engine.evaluate("pajares", weather)
assert result["force_closed"] is False
# ---------------------------------------------------------------------------
# Tests – normal conditions
# ---------------------------------------------------------------------------
class TestNormalConditions:
"""No rules should trigger under benign conditions."""
def test_normal_conditions_produce_no_force(self, rules_engine):
"""Standard winter conditions must leave all force flags unset."""
weather = _weather(wind_gust=30.0, snow_depth=60, temperature=-2.0, precipitation=0.0)
result = rules_engine.evaluate("pajares", weather)
assert result["force_closed"] is False
assert result["estimated_km_factor"] == pytest.approx(1.0)
def test_normal_conditions_return_dict(self, rules_engine):
"""evaluate() must always return a dict with the expected keys."""
weather = _weather()
result = rules_engine.evaluate("pajares", weather)
assert isinstance(result, dict)
assert "force_closed" in result
assert "estimated_km_factor" in result
# ---------------------------------------------------------------------------
# Tests – rain + high temperature reduces estimated_km_factor
# ---------------------------------------------------------------------------
class TestRainAndHighTemperature:
"""Rain at positive temperatures should reduce the estimated open km."""
def test_high_temp_and_rain_reduces_km_factor(self, rules_engine):
"""Temperature > 10 C combined with precipitation must reduce estimated_km_factor below 1.0."""
weather = _weather(temperature=12.0, precipitation=8.0)
result = rules_engine.evaluate("pajares", weather)
assert result["estimated_km_factor"] < 1.0
def test_rain_without_high_temp_does_not_reduce_km_factor(self, rules_engine):
"""Rain at sub-zero temperatures must not reduce estimated_km_factor."""
weather = _weather(temperature=-3.0, precipitation=8.0)
result = rules_engine.evaluate("pajares", weather)
assert result["estimated_km_factor"] == pytest.approx(1.0)
def test_high_temp_without_rain_does_not_reduce_km_factor(self, rules_engine):
"""High temperature without precipitation must not reduce estimated_km_factor."""
weather = _weather(temperature=12.0, precipitation=0.0)
result = rules_engine.evaluate("pajares", weather)
assert result["estimated_km_factor"] == pytest.approx(1.0)