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

+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)