Files
skipredictor/pipeline/feature_engineering.py
T
dasemu 5e2a22340f refactor(crowd_analysis): simplify table + upgrade YOLO + add regional holidays
- Remove internal YOLO counts (cars/people/buses/total_vehicles) from crowd_analysis table
- Keep only crowd_density and confidence_scores for persistence (no ML training impact)
- Upgrade from YOLOv8n to YOLOv11m for better person detection (fewer false positives)
- Add regional holidays: Día de Castilla y León (4/23), Santiago Apóstol (7/25, shared with Galicia)
- Add Easter Monday (moveable, 2018-2035) for Castilla y León and Galicia
- Update all tests to match simplified crowd_analysis schema

Tests: all 38 SQLite/crowd_analyzer tests + 13 feature tests passing.
2026-03-13 18:03:15 +01:00

415 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Feature engineering for the ski predictor pipeline.
Derives temporal, rolling, and calendar features from a merged weather +
station DataFrame to produce an ML-ready feature set.
"""
import logging
from pathlib import Path
from typing import Optional
import numpy as np
import pandas as pd
import yaml
logger = logging.getLogger(__name__)
_REPO_ROOT = Path(__file__).resolve().parents[1]
_DEFAULT_FEATURES_CONFIG = _REPO_ROOT / "config" / "features.yaml"
# Spanish national public holidays (month, day). Regional holidays for
# Asturias (where all three target stations are located) are also included.
_SPANISH_HOLIDAYS: set[tuple[int, int]] = {
# National
(1, 1), # New Year's Day
(1, 6), # Epiphany
(5, 1), # Labour Day
(7, 25), # Santiago Apóstol (National + Día de Galicia)
(8, 15), # Assumption of Mary
(10, 12), # National Day of Spain
(11, 1), # All Saints' Day
(12, 6), # Constitution Day
(12, 8), # Immaculate Conception
(12, 25), # Christmas Day
# Asturian regional
(9, 8), # Day of Asturias
# Castilla y León regional
(4, 23), # Día de Castilla y León
}
# Approximate Good Friday dates for years 2018-2035 (moveable feast).
# Keyed by year, value is (month, day).
_GOOD_FRIDAY: dict[int, tuple[int, int]] = {
2018: (3, 30),
2019: (4, 19),
2020: (4, 10),
2021: (4, 2),
2022: (4, 15),
2023: (4, 7),
2024: (3, 29),
2025: (4, 18),
2026: (4, 3),
2027: (3, 26),
2028: (4, 14),
2029: (3, 30),
2030: (4, 19),
2031: (4, 11),
2032: (3, 26),
2033: (4, 15),
2034: (4, 7),
2035: (3, 23),
}
# Easter Monday dates for years 2018-2035 (Good Friday + 3 days).
# Regional holiday in Castilla y León and Galicia.
_EASTER_MONDAY: dict[int, tuple[int, int]] = {
2018: (4, 2), 2019: (4, 22), 2020: (4, 13), 2021: (4, 5),
2022: (4, 18), 2023: (4, 10), 2024: (4, 1), 2025: (4, 21),
2026: (4, 6), 2027: (3, 29), 2028: (4, 17), 2029: (4, 2),
2030: (4, 22), 2031: (4, 14), 2032: (3, 29), 2033: (4, 18),
2034: (4, 10), 2035: (3, 26),
}
def _build_holiday_set(years: Optional[list[int]] = None) -> set[pd.Timestamp]:
"""Return a set of Timestamps for every known holiday across the given years.
Parameters
----------
years:
Calendar years to include. Defaults to 2018-2035.
"""
if years is None:
years = list(range(2018, 2036))
holidays: set[pd.Timestamp] = set()
for year in years:
for month, day in _SPANISH_HOLIDAYS:
try:
holidays.add(pd.Timestamp(year=year, month=month, day=day))
except ValueError:
pass
gf = _GOOD_FRIDAY.get(year)
if gf:
holidays.add(pd.Timestamp(year=year, month=gf[0], day=gf[1]))
em = _EASTER_MONDAY.get(year)
if em:
holidays.add(pd.Timestamp(year=year, month=em[0], day=em[1]))
return holidays
class FeatureEngineer:
"""Derives engineered features from a merged weather + station DataFrame.
All features defined in ``config/features.yaml`` under
``engineered_features`` are computed. Columns required by each feature
must be present in the input DataFrame; missing source columns are logged
as warnings and the corresponding feature is set to NaN.
Parameters
----------
config_path:
Path to the ``features.yaml`` configuration file. Defaults to
``<repo_root>/config/features.yaml``.
"""
def __init__(self, config_path: Optional[Path] = None) -> None:
self.config_path = (
Path(config_path) if config_path else _DEFAULT_FEATURES_CONFIG
)
self._config = self._load_config()
self._holidays = _build_holiday_set()
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def transform(self, df: pd.DataFrame) -> pd.DataFrame:
"""Add all engineered features to *df* and return the result.
The input DataFrame must contain at minimum:
- ``date`` (datetime-like)
- ``station_id`` (str or int)
- ``snowfall_sum`` (float) – daily snowfall in cm
- ``temperature_2m_mean`` (float) – mean temperature in degrees C
- ``wind_gusts_10m_max`` (float) – maximum wind gust in km/h
- ``surface_pressure_mean`` (float) – mean surface pressure in hPa
Parameters
----------
df:
Merged weather + station DataFrame, one row per (date, station_id).
Returns
-------
pd.DataFrame
Original DataFrame with additional feature columns appended.
"""
if df.empty:
logger.warning("Input DataFrame is empty; returning as-is.")
return df
result = df.copy()
result["date"] = pd.to_datetime(result["date"])
result = result.sort_values(["station_id", "date"]).reset_index(drop=True)
enabled = set(self._config.get("engineered_features", []))
result = self._add_rolling_snow(result, enabled)
result = self._add_rolling_temperature(result, enabled)
result = self._add_max_wind_gust(result, enabled)
result = self._add_calendar_features(result, enabled)
result = self._add_days_since_last_snowfall(result, enabled)
result = self._add_temperature_trend(result, enabled)
result = self._add_pressure_trend(result, enabled)
computed = [c for c in result.columns if c not in df.columns]
logger.info("Feature engineering complete. Added columns: %s", computed)
return result
# ------------------------------------------------------------------
# Private feature methods
# ------------------------------------------------------------------
def _add_rolling_snow(
self, df: pd.DataFrame, enabled: set
) -> pd.DataFrame:
"""Compute rolling snowfall sums over 3 and 7 days.
Features produced:
- ``snow_last_3_days``: sum of snowfall_sum over the 3 preceding days
(exclusive of the current day).
- ``snow_last_7_days``: sum of snowfall_sum over the 7 preceding days
(exclusive of the current day).
The shift-by-one before rolling ensures these features capture
antecedent conditions, which is the meaningful signal for a
next-day opening-probability model.
"""
source = "snowfall_sum"
if not self._check_source(df, source):
for feat in ("snow_last_3_days", "snow_last_7_days"):
if feat in enabled:
df[feat] = np.nan
return df
grp = df.groupby("station_id")[source]
if "snow_last_3_days" in enabled:
shifted = grp.shift(1)
df["snow_last_3_days"] = (
shifted.groupby(df["station_id"])
.transform(lambda s: s.rolling(window=3, min_periods=1).sum())
)
if "snow_last_7_days" in enabled:
shifted = grp.shift(1)
df["snow_last_7_days"] = (
shifted.groupby(df["station_id"])
.transform(lambda s: s.rolling(window=7, min_periods=1).sum())
)
return df
def _add_rolling_temperature(
self, df: pd.DataFrame, enabled: set
) -> pd.DataFrame:
"""Compute 3-day rolling mean temperature.
Feature produced:
- ``avg_temperature_3_days``: mean of temperature_2m_mean over the
3 preceding days (exclusive of the current day).
"""
feat = "avg_temperature_3_days"
if feat not in enabled:
return df
source = "temperature_2m_mean"
if not self._check_source(df, source):
df[feat] = np.nan
return df
shifted = df.groupby("station_id")[source].shift(1)
df[feat] = (
shifted.groupby(df["station_id"])
.transform(lambda s: s.rolling(window=3, min_periods=1).mean())
)
return df
def _add_max_wind_gust(
self, df: pd.DataFrame, enabled: set
) -> pd.DataFrame:
"""Alias the daily maximum wind gust into a consistently named feature.
Feature produced:
- ``max_wind_gust``: maximum wind gust (km/h) for the current day,
sourced directly from ``wind_gusts_10m_max``.
The raw column already represents the 24-hour maximum, so no rolling
aggregation is required.
"""
feat = "max_wind_gust"
if feat not in enabled:
return df
source = "wind_gusts_10m_max"
if not self._check_source(df, source):
df[feat] = np.nan
else:
df[feat] = df[source]
return df
def _add_calendar_features(
self, df: pd.DataFrame, enabled: set
) -> pd.DataFrame:
"""Add calendar-derived features.
Features produced:
- ``is_weekend``: 1 if the date falls on Saturday (5) or Sunday (6).
- ``is_holiday``: 1 if the date is a Spanish or Asturian public holiday.
- ``month_of_year``: integer month 1-12.
- ``day_of_week``: integer weekday 0 (Monday) through 6 (Sunday).
"""
dates = df["date"]
if "is_weekend" in enabled:
df["is_weekend"] = dates.dt.dayofweek.isin([5, 6]).astype(int)
if "is_holiday" in enabled:
df["is_holiday"] = dates.isin(self._holidays).astype(int)
if "month_of_year" in enabled:
df["month_of_year"] = dates.dt.month
if "day_of_week" in enabled:
df["day_of_week"] = dates.dt.dayofweek
return df
def _add_days_since_last_snowfall(
self, df: pd.DataFrame, enabled: set
) -> pd.DataFrame:
"""Compute days elapsed since the most recent snowfall event.
A snowfall event is defined as ``snowfall_sum > 0``.
Feature produced:
- ``days_since_last_snowfall``: integer count of days since the last
day with non-zero snowfall. 0 means it snowed today. NaN is used
for rows where no prior snowfall is present in the history window.
"""
feat = "days_since_last_snowfall"
if feat not in enabled:
return df
source = "snowfall_sum"
if not self._check_source(df, source):
df[feat] = np.nan
return df
def _days_since_for_group(group: pd.Series) -> pd.Series:
"""Vectorised computation for a single station's snowfall series."""
snow = group.values
result = np.full(len(snow), np.nan)
last_snow_idx: Optional[int] = None
for i, val in enumerate(snow):
if val > 0:
last_snow_idx = i
if last_snow_idx is not None:
result[i] = float(i - last_snow_idx)
return pd.Series(result, index=group.index)
df[feat] = (
df.groupby("station_id")[source]
.transform(_days_since_for_group)
)
return df
def _add_temperature_trend(
self, df: pd.DataFrame, enabled: set
) -> pd.DataFrame:
"""Compute temperature change over the last 3 days.
Feature produced:
- ``temperature_trend_3_days``: difference between today's mean
temperature and the mean temperature 3 days ago. A positive value
indicates warming; a negative value indicates cooling.
"""
feat = "temperature_trend_3_days"
if feat not in enabled:
return df
source = "temperature_2m_mean"
if not self._check_source(df, source):
df[feat] = np.nan
return df
df[feat] = (
df[source]
- df.groupby("station_id")[source].transform(lambda s: s.shift(3))
)
return df
def _add_pressure_trend(
self, df: pd.DataFrame, enabled: set
) -> pd.DataFrame:
"""Compute surface pressure change over the last 3 days.
Feature produced:
- ``pressure_trend_3_days``: difference between today's mean surface
pressure and the value 3 days ago. A positive value indicates a
rising pressure (improving conditions); a negative value indicates
a falling pressure (approaching precipitation).
"""
feat = "pressure_trend_3_days"
if feat not in enabled:
return df
source = "surface_pressure_mean"
if not self._check_source(df, source):
df[feat] = np.nan
return df
df[feat] = (
df[source]
- df.groupby("station_id")[source].transform(lambda s: s.shift(3))
)
return df
# ------------------------------------------------------------------
# Private helpers
# ------------------------------------------------------------------
def _load_config(self) -> dict:
"""Load and return the features YAML configuration."""
if not self.config_path.exists():
logger.warning(
"Features config not found at %s. All features enabled by default.",
self.config_path,
)
return {}
with open(self.config_path, "r", encoding="utf-8") as fh:
config = yaml.safe_load(fh)
logger.debug("Loaded features config from %s.", self.config_path)
return config or {}
@staticmethod
def _check_source(df: pd.DataFrame, column: str) -> bool:
"""Return True if *column* exists in *df*, otherwise log a warning."""
if column not in df.columns:
logger.warning(
"Source column '%s' not found in DataFrame. "
"Dependent feature(s) will be set to NaN.",
column,
)
return False
return True