mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 07:16:15 +00:00
480 lines
17 KiB
Python
480 lines
17 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 (unless --skip-training is passed)
|
|
|
|
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
|
|
crowd_analysis table -> crowd_level (low/medium/high) when available
|
|
open_status + km_open -> station_open (ML target alias)
|
|
"""
|
|
|
|
import argparse
|
|
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
|
|
|
|
VALID_CROWD_LEVELS = {"low", "medium", "high"}
|
|
|
|
# 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},
|
|
}
|
|
|
|
|
|
def _load_webcam_crowd_labels(store: SQLiteStore) -> pd.DataFrame:
|
|
"""Load one historical webcam crowd label per (date, station_id).
|
|
|
|
If multiple webcam analyses exist for the same station-day, keep the latest
|
|
one by ``analyzed_at``.
|
|
"""
|
|
crowd_df = store.load_crowd_analyses()
|
|
if crowd_df.empty:
|
|
logger.info("No rows found in crowd_analysis; crowd labels will be missing.")
|
|
return pd.DataFrame(columns=["date", "station_id", "webcam_crowd_level"])
|
|
|
|
valid = crowd_df[crowd_df["crowd_density"].isin(VALID_CROWD_LEVELS)].copy()
|
|
if valid.empty:
|
|
logger.info(
|
|
"No valid webcam crowd labels found (only unknown/missing values)."
|
|
)
|
|
return pd.DataFrame(columns=["date", "station_id", "webcam_crowd_level"])
|
|
|
|
valid["date"] = pd.to_datetime(valid["analysis_date"], errors="coerce")
|
|
valid["analyzed_at"] = pd.to_datetime(valid["analyzed_at"], errors="coerce")
|
|
valid = valid.dropna(subset=["date", "station_id", "crowd_density"])
|
|
valid = valid.sort_values(["station_id", "date", "analyzed_at"])
|
|
valid = valid.drop_duplicates(subset=["station_id", "date"], keep="last")
|
|
|
|
labels = valid[["date", "station_id", "crowd_density"]].rename(
|
|
columns={"crowd_density": "webcam_crowd_level"}
|
|
)
|
|
logger.info(
|
|
"Loaded %d valid webcam labels across %d station-days.",
|
|
len(valid),
|
|
len(labels),
|
|
)
|
|
return labels
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 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))
|
|
|
|
# Historical station data is stored in SQLite as ISO dates.
|
|
if not pd.api.types.is_datetime64_any_dtype(df["date"]):
|
|
df["date"] = pd.to_datetime(
|
|
df["date"],
|
|
format="%Y-%m-%d",
|
|
errors="raise",
|
|
)
|
|
|
|
# Keep station history aligned with the weather archive, which is fetched
|
|
# only up to the last complete day.
|
|
cutoff_ts = pd.Timestamp(date.today() - timedelta(days=1))
|
|
original_len = len(df)
|
|
df = df[df["date"] <= cutoff_ts].copy()
|
|
dropped = original_len - len(df)
|
|
if dropped > 0:
|
|
logger.info(
|
|
"Dropped %d station rows after %s while building the dataset.",
|
|
dropped,
|
|
cutoff_ts.date().isoformat(),
|
|
)
|
|
|
|
# ---------- 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
|
|
|
|
webcam_labels = _load_webcam_crowd_labels(store)
|
|
if webcam_labels.empty:
|
|
df["webcam_crowd_level"] = None
|
|
else:
|
|
df = df.merge(webcam_labels, on=["date", "station_id"], how="left")
|
|
|
|
# ---------- crowd_level ----------
|
|
# Crowd labels are sourced strictly from webcam analysis.
|
|
# We only keep labels for days where the station is open.
|
|
open_mask = df["open_status"] == 1
|
|
df["crowd_level"] = None
|
|
df["crowd_level_source"] = None
|
|
|
|
webcam_mask = open_mask & df["webcam_crowd_level"].isin(VALID_CROWD_LEVELS)
|
|
df.loc[webcam_mask, "crowd_level"] = df.loc[webcam_mask, "webcam_crowd_level"]
|
|
df.loc[webcam_mask, "crowd_level_source"] = "webcam"
|
|
|
|
# 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",
|
|
"crowd_level_source",
|
|
]
|
|
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(),
|
|
)
|
|
logger.info(
|
|
"crowd_level source distribution:\n%s",
|
|
result["crowd_level_source"].fillna("missing").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(*, skip_training: bool = False) -> 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)
|
|
|
|
if skip_training:
|
|
logger.info("Skipping model training (--skip-training).")
|
|
logger.info("Pipeline complete (dataset only).")
|
|
return
|
|
|
|
# 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.")
|
|
|
|
|
|
def _parse_args() -> argparse.Namespace:
|
|
parser = argparse.ArgumentParser(
|
|
description="Build historical datasets and optionally train ML models.",
|
|
)
|
|
parser.add_argument(
|
|
"--skip-training",
|
|
action="store_true",
|
|
help="Build and store datasets but skip model training.",
|
|
)
|
|
return parser.parse_args()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
args = _parse_args()
|
|
main(skip_training=args.skip_training)
|