mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 15:26:15 +00:00
307 lines
11 KiB
Python
307 lines
11 KiB
Python
"""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",
|
||
]
|
||
|
||
# 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",
|
||
]
|
||
|
||
|
||
class DatasetBuilder:
|
||
"""Merges raw weather and station data into a single processed dataset.
|
||
|
||
The builder reads the latest forecast snapshot and latest station status
|
||
snapshot from SQLite, merges them on ``(date, station_id)``, and persists
|
||
the processed result into another SQLite table.
|
||
"""
|
||
|
||
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 and station snapshots from SQLite, merges
|
||
them, fills missing values, and saves the result to the configured
|
||
dataset table.
|
||
|
||
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()
|
||
|
||
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)
|
||
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,
|
||
) -> pd.DataFrame:
|
||
"""Append a single day's data to the existing processed dataset.
|
||
|
||
Useful for daily cron-driven updates without reprocessing the full
|
||
history.
|
||
|
||
Parameters
|
||
----------
|
||
weather_data:
|
||
Either a ``dict`` (single record) or a one-row ``DataFrame``
|
||
containing weather measurements for the day.
|
||
station_data:
|
||
Either a ``dict`` (single record) or a one-row ``DataFrame``
|
||
containing station operational data for the day.
|
||
|
||
Returns
|
||
-------
|
||
pd.DataFrame
|
||
The updated full dataset (existing rows + new row).
|
||
"""
|
||
weather_row = self._to_dataframe(weather_data)
|
||
station_row = self._to_dataframe(station_data)
|
||
|
||
new_row = self._merge(weather_row, station_row)
|
||
new_row = self._handle_missing(new_row)
|
||
|
||
existing = self._load_existing_dataset()
|
||
|
||
# Normalize date columns to pd.Timestamp before concat to avoid
|
||
# mixed-type sort errors (datetime.date vs Timestamp).
|
||
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)
|
||
|
||
# Ensure date column is uniform Timestamp after concat
|
||
combined["date"] = pd.to_datetime(combined["date"], format="mixed")
|
||
|
||
# Drop duplicate (date, station_id) pairs, keeping the latest entry.
|
||
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_existing_dataset(self) -> pd.DataFrame:
|
||
"""Return the persisted processed dataset, or an empty DataFrame."""
|
||
df = self.store.read_dataframe(self.dataset_table, parse_dates=("date",))
|
||
if not df.empty:
|
||
logger.debug(
|
||
"Loaded existing dataset from table %s with %d rows.",
|
||
self.dataset_table,
|
||
len(df),
|
||
)
|
||
return df
|
||
|
||
# ------------------------------------------------------------------
|
||
# 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])
|