mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 15:26:15 +00:00
401 lines
15 KiB
Python
401 lines
15 KiB
Python
"""Build the full historical dataset by merging station data with weather.
|
|
|
|
Steps:
|
|
1. Load historical station data from SQLite or download it from infonieve.es
|
|
2. Map infonieve columns to the project schema
|
|
3. Fetch historical weather from Open-Meteo for 2009-2026 when SQLite has no cache
|
|
4. Merge weather + station data on (date, station_id)
|
|
5. Run feature engineering
|
|
6. Save the merged and featured datasets to SQLite
|
|
7. Train ML models
|
|
|
|
Column mapping from infonieve schema to project schema:
|
|
closedflag / idestado -> open_status (1=open, 0=closed)
|
|
kmopen -> km_open
|
|
pistasopen -> lifts_open (actually slopes, but matches schema)
|
|
espesormax -> snow_depth
|
|
calidadnieve -> snow_quality
|
|
pistasopen/pistastotal ratio -> crowd_level (low/medium/high)
|
|
open_status + km_open -> station_open (ML target alias)
|
|
"""
|
|
|
|
import logging
|
|
import sys
|
|
from datetime import date, timedelta
|
|
from pathlib import Path
|
|
|
|
import pandas as pd
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Path setup - add repo root to sys.path so project modules are importable
|
|
# ---------------------------------------------------------------------------
|
|
REPO_ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(REPO_ROOT))
|
|
|
|
from data_sources.weather_api import WeatherCollector
|
|
from data_sources.infonieve_historical import download_all_history
|
|
from pipeline.feature_engineering import FeatureEngineer
|
|
from ml.train_model import ModelTrainer
|
|
from storage import (
|
|
HISTORICAL_FEATURED_TABLE,
|
|
HISTORICAL_MERGED_TABLE,
|
|
HISTORICAL_STATION_TABLE,
|
|
HISTORICAL_WEATHER_TABLE,
|
|
SQLiteStore,
|
|
)
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Logging
|
|
# ---------------------------------------------------------------------------
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
|
)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Constants
|
|
# ---------------------------------------------------------------------------
|
|
# Weather fetch range - driven by what is in the station data
|
|
WEATHER_START_YEAR = 2009
|
|
WEATHER_END_YEAR = 2026 # inclusive
|
|
|
|
# Crowd level thresholds based on pistas open / pistas total ratio
|
|
CROWD_LOW_THRESHOLD = 0.33
|
|
CROWD_HIGH_THRESHOLD = 0.67
|
|
|
|
# Station coordinates from config/stations.yaml
|
|
STATIONS = {
|
|
"fuentes": {"latitude": 43.0833, "longitude": -5.9333},
|
|
"pajares": {"latitude": 43.0500, "longitude": -5.7700},
|
|
"sanisidro": {"latitude": 43.0700, "longitude": -5.3700},
|
|
}
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Step 1: Load and map station data
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def load_station_data(store: SQLiteStore) -> pd.DataFrame:
|
|
"""Load historical station raw data from SQLite and map it to project schema."""
|
|
df = store.load_historical_station_raw()
|
|
if df.empty:
|
|
logger.info("No historical station data found in SQLite. Downloading fresh history.")
|
|
df = download_all_history(store=store)
|
|
else:
|
|
logger.info("Loaded %d historical station rows from SQLite.", len(df))
|
|
|
|
# Parse dates with mixed formats (ISO and day-first variants)
|
|
df["date"] = pd.to_datetime(df["date"], format="mixed", dayfirst=True)
|
|
|
|
# ---------- open_status ----------
|
|
# idestado=1: open (normal operation)
|
|
# idestado=4: open (special/summer operation, some km data present)
|
|
# idestado=0: closed (no operation that day)
|
|
# idestado=2: off-season (not yet / no longer open)
|
|
# idestado=3: temporarily closed (weather/maintenance)
|
|
# Best signal: station is open if kmopen > 0, else use idestado
|
|
df["open_status"] = 0
|
|
has_km_data = df["kmopen"].notna() & (df["kmopen"] > 0)
|
|
df.loc[has_km_data, "open_status"] = 1
|
|
# Also mark idestado=1 rows where kmopen may be missing as open
|
|
df.loc[(df["idestado"] == 1.0) & ~has_km_data, "open_status"] = 1
|
|
|
|
# station_open is the ML binary classification target (same as open_status)
|
|
df["station_open"] = df["open_status"]
|
|
|
|
# ---------- km_open ----------
|
|
df["km_open"] = pd.to_numeric(df["kmopen"], errors="coerce")
|
|
|
|
# ---------- lifts_open (slopes in this dataset) ----------
|
|
df["lifts_open"] = pd.to_numeric(df["pistasopen"], errors="coerce")
|
|
|
|
# ---------- snow_depth ----------
|
|
df["snow_depth"] = pd.to_numeric(df["espesormax"], errors="coerce")
|
|
|
|
# ---------- snow_quality ----------
|
|
df["snow_quality"] = df["calidadnieve"].astype(str)
|
|
df.loc[df["snow_quality"] == "nan", "snow_quality"] = None
|
|
|
|
# ---------- crowd_level ----------
|
|
# Derived from fraction of slopes open vs total available
|
|
pistastotal = pd.to_numeric(df["pistastotal"], errors="coerce")
|
|
pistasopen = pd.to_numeric(df["pistasopen"], errors="coerce")
|
|
ratio = pistasopen / pistastotal.replace(0, float("nan"))
|
|
|
|
crowd = pd.Series(index=df.index, dtype="object")
|
|
crowd[ratio < CROWD_LOW_THRESHOLD] = "low"
|
|
crowd[(ratio >= CROWD_LOW_THRESHOLD) & (ratio < CROWD_HIGH_THRESHOLD)] = "medium"
|
|
crowd[ratio >= CROWD_HIGH_THRESHOLD] = "high"
|
|
# Only assign crowd_level when the station is open
|
|
df["crowd_level"] = None
|
|
df.loc[df["open_status"] == 1, "crowd_level"] = crowd[df["open_status"] == 1]
|
|
|
|
# Keep only the columns needed for merging
|
|
keep = [
|
|
"date", "station_id",
|
|
"open_status", "station_open",
|
|
"km_open", "lifts_open",
|
|
"snow_depth", "snow_quality",
|
|
"crowd_level",
|
|
]
|
|
result = df[keep].copy()
|
|
result = result.sort_values(["station_id", "date"]).reset_index(drop=True)
|
|
|
|
logger.info(
|
|
"Station data mapped. Open rows: %d / %d",
|
|
(result["open_status"] == 1).sum(),
|
|
len(result),
|
|
)
|
|
logger.info(
|
|
"crowd_level distribution:\n%s",
|
|
result["crowd_level"].value_counts(),
|
|
)
|
|
return result
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Step 2: Fetch historical weather
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def fetch_weather_all_stations(store: SQLiteStore) -> pd.DataFrame:
|
|
"""Load cached historical weather from SQLite or fetch it from Open-Meteo."""
|
|
cached = store.read_dataframe(HISTORICAL_WEATHER_TABLE, parse_dates=("date",))
|
|
yesterday = pd.Timestamp(date.today() - timedelta(days=1))
|
|
if not cached.empty and cached["date"].max() >= yesterday:
|
|
logger.info(
|
|
"Loaded %d historical weather rows from SQLite table %s.",
|
|
len(cached),
|
|
HISTORICAL_WEATHER_TABLE,
|
|
)
|
|
return cached
|
|
|
|
logger.info("Historical weather cache missing or stale. Fetching from Open-Meteo.")
|
|
collector = WeatherCollector()
|
|
all_frames: list[pd.DataFrame] = []
|
|
|
|
today = date.today()
|
|
end_year = min(WEATHER_END_YEAR, today.year)
|
|
|
|
for station_id, coords in STATIONS.items():
|
|
lat = coords["latitude"]
|
|
lon = coords["longitude"]
|
|
station_frames: list[pd.DataFrame] = []
|
|
|
|
for year in range(WEATHER_START_YEAR, end_year + 1):
|
|
start_date = f"{year}-01-01"
|
|
end_date = (
|
|
(today - timedelta(days=1)).strftime("%Y-%m-%d")
|
|
if year == today.year
|
|
else f"{year}-12-31"
|
|
)
|
|
logger.info(
|
|
"Fetching weather for station=%s year=%d (%s to %s)",
|
|
station_id,
|
|
year,
|
|
start_date,
|
|
end_date,
|
|
)
|
|
|
|
try:
|
|
df = collector.get_historical(
|
|
station_id=station_id,
|
|
lat=lat,
|
|
lon=lon,
|
|
start_date=start_date,
|
|
end_date=end_date,
|
|
)
|
|
if not df.empty:
|
|
df["date"] = pd.to_datetime(df["date"])
|
|
station_frames.append(df)
|
|
except RuntimeError as exc:
|
|
logger.error(
|
|
"Weather fetch failed for station=%s year=%d: %s",
|
|
station_id,
|
|
year,
|
|
exc,
|
|
)
|
|
|
|
if station_frames:
|
|
combined = pd.concat(station_frames, ignore_index=True)
|
|
combined["date"] = pd.to_datetime(combined["date"])
|
|
combined.drop_duplicates(subset=["date", "station_id"], inplace=True)
|
|
combined.sort_values("date", inplace=True)
|
|
all_frames.append(combined)
|
|
logger.info("Total weather rows for %s: %d", station_id, len(combined))
|
|
|
|
if not all_frames:
|
|
raise RuntimeError("No weather data fetched for any station.")
|
|
|
|
weather = pd.concat(all_frames, ignore_index=True)
|
|
weather["date"] = pd.to_datetime(weather["date"])
|
|
store.save_weather_snapshot(weather, table_name=HISTORICAL_WEATHER_TABLE)
|
|
logger.info("Total weather rows across all stations: %d", len(weather))
|
|
return weather
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Step 3: Merge weather + station data
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def merge_datasets(
|
|
weather_df: pd.DataFrame,
|
|
station_df: pd.DataFrame,
|
|
) -> pd.DataFrame:
|
|
"""Outer-merge weather and station frames on (date, station_id)."""
|
|
logger.info(
|
|
"Merging weather (%d rows) with station (%d rows).",
|
|
len(weather_df), len(station_df),
|
|
)
|
|
|
|
# Normalise date type for both frames before merging
|
|
weather_df = weather_df.copy()
|
|
station_df = station_df.copy()
|
|
weather_df["date"] = pd.to_datetime(weather_df["date"])
|
|
station_df["date"] = pd.to_datetime(station_df["date"])
|
|
|
|
merged = pd.merge(
|
|
weather_df,
|
|
station_df,
|
|
on=["date", "station_id"],
|
|
how="outer",
|
|
)
|
|
merged = merged.sort_values(["station_id", "date"]).reset_index(drop=True)
|
|
logger.info("Merged dataset shape: %s", merged.shape)
|
|
return merged
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Step 4: Feature engineering
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def run_feature_engineering(df: pd.DataFrame) -> pd.DataFrame:
|
|
"""Apply the standard feature engineering pipeline."""
|
|
logger.info("Running feature engineering on %d rows.", len(df))
|
|
engineer = FeatureEngineer()
|
|
featured = engineer.transform(df)
|
|
logger.info(
|
|
"Feature engineering complete. Output shape: %s", featured.shape
|
|
)
|
|
return featured
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Step 5: Save
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def save_dataset(store: SQLiteStore, merged_df: pd.DataFrame, featured_df: pd.DataFrame) -> None:
|
|
"""Persist merged and featured datasets to SQLite."""
|
|
store.replace_dataframe(HISTORICAL_MERGED_TABLE, merged_df)
|
|
store.replace_dataframe(HISTORICAL_FEATURED_TABLE, featured_df)
|
|
logger.info(
|
|
"Historical datasets saved to SQLite tables %s and %s.",
|
|
HISTORICAL_MERGED_TABLE,
|
|
HISTORICAL_FEATURED_TABLE,
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Step 6: Summary statistics
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def print_summary(df: pd.DataFrame) -> None:
|
|
"""Print summary statistics about the final dataset."""
|
|
print("\n" + "=" * 60)
|
|
print("DATASET SUMMARY")
|
|
print("=" * 60)
|
|
print(f"Total rows: {len(df):,}")
|
|
print(f"Total columns: {len(df.columns)}")
|
|
print(f"Date range: {df['date'].min().date()} to {df['date'].max().date()}")
|
|
print(f"Stations: {sorted(df['station_id'].unique())}")
|
|
print()
|
|
print("Rows per station:")
|
|
for sid, count in df.groupby("station_id").size().items():
|
|
print(f" {sid}: {count:,}")
|
|
print()
|
|
|
|
if "station_open" in df.columns:
|
|
open_rows = df["station_open"].notna()
|
|
total_labeled = open_rows.sum()
|
|
open_count = (df.loc[open_rows, "station_open"] == 1).sum()
|
|
closed_count = (df.loc[open_rows, "station_open"] == 0).sum()
|
|
print(f"station_open labels: {total_labeled:,} total")
|
|
print(f" open: {open_count:,} ({100*open_count/total_labeled:.1f}%)")
|
|
print(f" closed: {closed_count:,} ({100*closed_count/total_labeled:.1f}%)")
|
|
print()
|
|
|
|
if "crowd_level" in df.columns:
|
|
crowd_dist = df["crowd_level"].value_counts()
|
|
print("crowd_level distribution:")
|
|
for level, cnt in crowd_dist.items():
|
|
print(f" {level}: {cnt:,}")
|
|
print()
|
|
|
|
if "km_open" in df.columns:
|
|
km = df["km_open"].dropna()
|
|
print(f"km_open stats (non-null, n={len(km):,}):")
|
|
print(f" mean={km.mean():.2f} median={km.median():.2f} "
|
|
f"min={km.min():.2f} max={km.max():.2f}")
|
|
print()
|
|
|
|
if "snow_depth" in df.columns:
|
|
sd = df["snow_depth"].dropna()
|
|
print(f"snow_depth stats (non-null, n={len(sd):,}):")
|
|
print(f" mean={sd.mean():.1f}cm max={sd.max():.1f}cm")
|
|
print()
|
|
|
|
missing_pct = 100 * df.isnull().sum() / len(df)
|
|
high_missing = missing_pct[missing_pct > 20].sort_values(ascending=False)
|
|
if not high_missing.empty:
|
|
print("Columns with >20% missing values:")
|
|
for col, pct in high_missing.items():
|
|
print(f" {col}: {pct:.1f}%")
|
|
else:
|
|
print("No columns with >20% missing values.")
|
|
print("=" * 60 + "\n")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Main
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def main() -> None:
|
|
logger.info("Starting full dataset build pipeline.")
|
|
store = SQLiteStore()
|
|
|
|
# Step 1: Load and map station data
|
|
station_df = load_station_data(store)
|
|
|
|
# Step 2: Fetch historical weather
|
|
weather_df = fetch_weather_all_stations(store)
|
|
|
|
# Step 3: Merge
|
|
merged = merge_datasets(weather_df, station_df)
|
|
|
|
# Step 4: Feature engineering
|
|
featured = run_feature_engineering(merged)
|
|
|
|
# Step 5: Save
|
|
save_dataset(store, merged, featured)
|
|
|
|
# Step 6: Summary
|
|
print_summary(featured)
|
|
|
|
# Step 7: Train models
|
|
logger.info("Starting model training on the full dataset.")
|
|
trainer = ModelTrainer(store=store, dataset_table=HISTORICAL_FEATURED_TABLE)
|
|
cv_results = trainer.train_all()
|
|
|
|
print("\nCROSS-VALIDATION RESULTS")
|
|
print("=" * 60)
|
|
for target, scores in cv_results.items():
|
|
print(f"\n {target}:")
|
|
for metric, value in scores.items():
|
|
print(f" {metric}: {value:.4f}")
|
|
print("=" * 60)
|
|
|
|
logger.info("Pipeline complete.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|