"""Dataset builder for the ski predictor pipeline. Loads weather and station snapshots from SQLite, merges them on date and station_id, imputes missing values, and persists the processed dataset back to SQLite. """ import logging from typing import Optional import pandas as pd from storage import ( LATEST_STATION_STATUS_TABLE, LATEST_WEATHER_TABLE, RUNTIME_DATASET_TABLE, SQLiteStore, ) logger = logging.getLogger(__name__) # Numeric weather columns that can be safely interpolated when values are # missing in the middle of a time series. Columns not listed here are filled # with forward-fill only (e.g. station metadata). _INTERPOLATABLE_WEATHER_COLS = [ "temperature_2m_max", "temperature_2m_min", "temperature_2m_mean", "precipitation_sum", "snowfall_sum", "wind_speed_10m_max", "wind_gusts_10m_max", "wind_direction_10m_dominant", "relative_humidity_2m_mean", "surface_pressure_mean", "weather_code", ] # Station operational columns are TARGET variables for ML and must NEVER # be forward-filled or interpolated. Missing values mean we have no # observation for that date and should remain as NaN. _STATION_TARGET_COLS = [ "open_status", "km_open", "lifts_open", "snow_depth", "snow_quality", "crowd_density", ] class DatasetBuilder: """Merges raw weather, station, and crowd data into a single processed dataset. The builder reads the latest forecast snapshot, latest station status snapshot, and crowd analysis records from SQLite, merges them on ``(date, station_id)``, and persists the processed result. """ def __init__( self, store: Optional[SQLiteStore] = None, weather_table: str = LATEST_WEATHER_TABLE, station_table: str = LATEST_STATION_STATUS_TABLE, dataset_table: str = RUNTIME_DATASET_TABLE, ) -> None: self.store = store if store is not None else SQLiteStore() self.weather_table = weather_table self.station_table = station_table self.dataset_table = dataset_table # ------------------------------------------------------------------ # Public API # ------------------------------------------------------------------ def build(self) -> pd.DataFrame: """Run the full build pipeline and persist the result. Reads the latest weather, station, and crowd snapshots from SQLite, merges them, fills missing values, and saves the result. Returns ------- pd.DataFrame The fully merged and cleaned dataset. """ logger.info("Starting full dataset build.") weather_df = self._load_weather_snapshot() station_df = self._load_station_snapshot() crowd_df = self._load_crowd_density_snapshot() if weather_df.empty and station_df.empty: logger.warning("No raw data found. Returning empty dataset.") return pd.DataFrame() merged = self._merge(weather_df, station_df) # Merge crowd data if available if not crowd_df.empty: merged["date"] = pd.to_datetime(merged["date"]) crowd_df["date"] = pd.to_datetime(crowd_df["date"]) merged = pd.merge( merged, crowd_df, on=["date", "station_id"], how="left" ) logger.debug("Merged crowd data. New shape: %s", merged.shape) merged = self._handle_missing(merged) self._save(merged) logger.info("Dataset build complete. Rows: %d", len(merged)) return merged def append_daily( self, weather_data: dict | pd.DataFrame, station_data: dict | pd.DataFrame, crowd_data: dict | pd.DataFrame | None = None, ) -> pd.DataFrame: """Append a single day's data to the existing processed dataset. Parameters ---------- weather_data: Weather measurements for the day. station_data: Station operational data for the day. crowd_data: Optional crowd analysis data for the day. """ weather_row = self._to_dataframe(weather_data) station_row = self._to_dataframe(station_data) new_row = self._merge(weather_row, station_row) if crowd_data is not None: crowd_row = self._to_dataframe(crowd_data) # Ensure date columns are compatible for merge new_row["date"] = pd.to_datetime(new_row["date"]) crowd_row["date"] = pd.to_datetime(crowd_row["date"]) new_row = pd.merge(new_row, crowd_row, on=["date", "station_id"], how="left") new_row = self._handle_missing(new_row) existing = self._load_existing_dataset() # Normalize date columns new_row["date"] = pd.to_datetime(new_row["date"]) if not existing.empty: existing["date"] = pd.to_datetime(existing["date"], format="mixed") combined = pd.concat([existing, new_row], ignore_index=True) combined["date"] = pd.to_datetime(combined["date"], format="mixed") combined = combined.drop_duplicates( subset=["date", "station_id"], keep="last" ) combined = combined.sort_values(["station_id", "date"]).reset_index(drop=True) self._save(combined) logger.info("Appended daily data. Total rows: %d", len(combined)) return combined # ------------------------------------------------------------------ # Private helpers – loading # ------------------------------------------------------------------ def _load_weather_snapshot(self) -> pd.DataFrame: """Load the latest persisted weather forecast snapshot.""" df = self.store.load_weather_snapshot(self.weather_table) if df.empty: logger.warning("No weather snapshot found in table %s.", self.weather_table) return df logger.info("Loaded %d weather rows from table %s.", len(df), self.weather_table) return df def _load_station_snapshot(self) -> pd.DataFrame: """Load the latest persisted station status snapshot.""" df = self.store.read_dataframe(self.station_table, parse_dates=("date",)) if df.empty: logger.warning("No station snapshot found in table %s.", self.station_table) return df logger.info("Loaded %d station rows from table %s.", len(df), self.station_table) return df def _load_crowd_density_snapshot(self) -> pd.DataFrame: """Load and aggregate daily crowd density levels.""" df = self.store.load_crowd_analyses() if df.empty: logger.info("No crowd analysis records found.") return pd.DataFrame() # Map density labels to numeric ranks for aggregation (max wins) rank_map = {"low": 0, "medium": 1, "high": 2} inv_map = {v: k for k, v in rank_map.items()} df["date"] = pd.to_datetime(df["analysis_date"]).dt.date df["density_rank"] = df["crowd_density"].map(rank_map).fillna(-1) # Aggregate by taking the highest density detected in any image that day daily = ( df.groupby(["date", "station_id"])["density_rank"] .max() .reset_index() ) daily["crowd_density"] = daily["density_rank"].map(inv_map) logger.info("Loaded crowd density for %d (date, station) pairs.", len(daily)) return daily[["date", "station_id", "crowd_density"]] # ------------------------------------------------------------------ # Private helpers – merging and cleaning # ------------------------------------------------------------------ def _merge( self, weather_df: pd.DataFrame, station_df: pd.DataFrame ) -> pd.DataFrame: """Outer-merge weather and station frames on (date, station_id). An outer merge is used so that rows present in only one source are still retained (with NaN in the missing columns). This allows the missing-data handler to fill or interpolate the gaps. """ if weather_df.empty and station_df.empty: return pd.DataFrame() if weather_df.empty: logger.warning( "Weather data is empty; returning station data only." ) return station_df.copy() if station_df.empty: logger.warning( "Station data is empty; returning weather data only." ) return weather_df.copy() 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.debug("Merged dataset shape: %s", merged.shape) return merged def _handle_missing(self, df: pd.DataFrame) -> pd.DataFrame: """Fill or interpolate missing values. Strategy per column type: - Interpolatable numeric weather columns: linear interpolation, then forward-fill for leading/trailing NaNs. - All other numeric columns: forward-fill then backward-fill. - Non-numeric columns: forward-fill within each station group. """ if df.empty: return df result = df.copy() # Interpolate known numeric weather variables within each station group. weather_cols_present = [ c for c in _INTERPOLATABLE_WEATHER_COLS if c in result.columns ] if weather_cols_present: result[weather_cols_present] = ( result.groupby("station_id", group_keys=False)[weather_cols_present] .apply( lambda g: g.interpolate(method="linear", limit_direction="both") ) ) # Forward-fill / backward-fill remaining numeric columns, # but NEVER fill station target columns (those are real observations). numeric_cols = result.select_dtypes(include="number").columns.tolist() remaining_numeric = [ c for c in numeric_cols if c not in weather_cols_present and c not in _STATION_TARGET_COLS ] if remaining_numeric: result[remaining_numeric] = ( result.groupby("station_id", group_keys=False)[remaining_numeric] .apply(lambda g: g.ffill().bfill()) ) # Forward-fill non-numeric columns (e.g. station name, categorical fields), # but NEVER fill station target columns. non_numeric_cols = result.select_dtypes(exclude="number").columns.tolist() skip_cols = {"date"} | set(_STATION_TARGET_COLS) fill_non_numeric = [ c for c in non_numeric_cols if c not in skip_cols ] if fill_non_numeric: result[fill_non_numeric] = ( result.groupby("station_id", group_keys=False)[fill_non_numeric] .apply(lambda g: g.ffill()) ) missing_after = result.isnull().sum().sum() if missing_after > 0: logger.warning( "%d missing values remain after imputation.", missing_after ) return result # ------------------------------------------------------------------ # Private helpers – persistence # ------------------------------------------------------------------ def _save(self, df: pd.DataFrame) -> None: """Write the processed dataset to SQLite.""" self.store.replace_dataframe(self.dataset_table, df) logger.info("Dataset saved to table %s.", self.dataset_table) # ------------------------------------------------------------------ # Private helpers – type coercion # ------------------------------------------------------------------ @staticmethod def _to_dataframe(data: dict | pd.DataFrame) -> pd.DataFrame: """Coerce a dict or DataFrame to a one-row DataFrame.""" if isinstance(data, pd.DataFrame): return data.copy() return pd.DataFrame([data])