"""Build the full historical dataset by merging station data with weather. Steps: 1. Load historical station CSV from infonieve.es (data/raw/station_historical_all.csv) 2. Map infonieve columns to the project schema 3. Fetch historical weather from Open-Meteo for 2009-2026 in 1-year chunks 4. Merge weather + station data on (date, station_id) 5. Run feature engineering 6. Save to data/processed/dataset_featured.csv 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 import time from datetime import date 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 pipeline.feature_engineering import FeatureEngineer from ml.train_model import ModelTrainer # --------------------------------------------------------------------------- # Logging # --------------------------------------------------------------------------- logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", ) logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- # Constants # --------------------------------------------------------------------------- STATION_CSV = REPO_ROOT / "data" / "raw" / "station_historical_all.csv" OUTPUT_DIR = REPO_ROOT / "data" / "processed" OUTPUT_PATH = OUTPUT_DIR / "dataset_featured.csv" # 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}, } # Delay between API calls to avoid rate-limiting (seconds) API_CALL_DELAY = 3.0 # Extra pause between stations (seconds) INTER_STATION_DELAY = 10.0 # Local cache directory for per-year weather chunks WEATHER_CACHE_DIR = REPO_ROOT / "data" / "raw" / "weather_cache" # --------------------------------------------------------------------------- # Step 1: Load and map station data # --------------------------------------------------------------------------- def load_station_data() -> pd.DataFrame: """Load the infonieve historical CSV and map columns to project schema.""" logger.info("Loading station data from %s", STATION_CSV) df = pd.read_csv(STATION_CSV) logger.info("Loaded %d rows, %d columns", len(df), len(df.columns)) # 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 in 1-year chunks # --------------------------------------------------------------------------- def _cache_path(station_id: str, year: int) -> Path: """Return the local cache file path for a (station, year) chunk.""" return WEATHER_CACHE_DIR / f"weather_{station_id}_{year}.csv" def fetch_weather_all_stations() -> pd.DataFrame: """Fetch full historical weather for all stations in annual chunks. Each (station, year) chunk is cached to ``data/raw/weather_cache/weather_{station_id}_{year}.csv``. If the cache file already exists the API call is skipped, making reruns fast and avoiding rate-limit exhaustion. The current year's cache is always refreshed (partial year grows daily). """ WEATHER_CACHE_DIR.mkdir(parents=True, exist_ok=True) 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] = [] needs_api_call = False for year in range(WEATHER_START_YEAR, end_year + 1): cache_file = _cache_path(station_id, year) start_date = f"{year}-01-01" # For the current partial year always refresh the cache is_current_year = year == today.year if cache_file.exists() and not is_current_year: logger.info( "Cache hit: %s (skipping API call)", cache_file.name ) df = pd.read_csv(cache_file) df["date"] = pd.to_datetime(df["date"]) station_frames.append(df) continue # For the current year, only fetch up to yesterday if is_current_year: from datetime import timedelta yesterday = today - timedelta(days=1) end_date = yesterday.strftime("%Y-%m-%d") else: end_date = f"{year}-12-31" logger.info( "Fetching weather for station=%s year=%d (%s to %s)", station_id, year, start_date, end_date, ) needs_api_call = True 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"]) # Save to per-year cache (not the rolling weather_X_today.csv) df.to_csv(cache_file, index=False) logger.info( " -> Got %d rows; cached to %s", len(df), cache_file.name, ) station_frames.append(df) except RuntimeError as exc: logger.error( "Weather fetch failed for station=%s year=%d: %s", station_id, year, exc, ) # Be polite to the API between calls time.sleep(API_CALL_DELAY) 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 needs_api_call: # Only pause if we actually made API calls for this station logger.info("Pausing %ds before next station.", INTER_STATION_DELAY) time.sleep(INTER_STATION_DELAY) 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"]) 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(df: pd.DataFrame) -> None: """Persist the featured dataset to disk.""" OUTPUT_DIR.mkdir(parents=True, exist_ok=True) df.to_csv(OUTPUT_PATH, index=False) logger.info("Featured dataset saved to %s (%d rows)", OUTPUT_PATH, len(df)) # --------------------------------------------------------------------------- # 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.") # Step 1: Load and map station data station_df = load_station_data() # Step 2: Fetch historical weather weather_df = fetch_weather_all_stations() # Step 3: Merge merged = merge_datasets(weather_df, station_df) # Step 4: Feature engineering featured = run_feature_engineering(merged) # Step 5: Save save_dataset(featured) # Step 6: Summary print_summary(featured) # Step 7: Train models logger.info("Starting model training on the full dataset.") trainer = ModelTrainer(dataset_path=OUTPUT_PATH) 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()