fix(pipeline): preserve historical features

This commit is contained in:
dasemu committed 2026-03-12 16:49:46 +01:00
1 parent 4933c61c69
commit e14a9f2d3b
3 files changed
+137 -35

No files matched your search

+130 -27
View File
@@ -6,17 +6,24 @@ This script is designed for cron execution. It runs every day to:
2. Collect current station operational status.
3. Append new rows to the processed dataset.
4. Run feature engineering on the updated dataset.
5. Generate predictions for the next day using the HybridPredictor.
5. Generate predictions for the configured target date using the
HybridPredictor.
6. Save the predictions to data/processed/predictions_latest.json.
Cron example (run daily at 20:00, after stations close):
0 20 * * * /path/to/.venv/bin/python /path/to/scripts/collect_daily_data.py
Ad hoc example for same-day verification without overwriting production:
python scripts/collect_daily_data.py \
--days-ahead 0 \
--output-path data/processed/predictions_today_check.json
Exit codes:
0 - Pipeline completed (partial failures are logged but do not abort).
1 - Fatal error that prevented any useful work.
"""
import argparse
import json
import logging
import sys
@@ -56,8 +63,10 @@ logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
_PROCESSED_DIR = _PROJECT_ROOT / "data" / "processed"
_DATASET_PATH = _PROCESSED_DIR / "dataset.csv"
_FEATURED_PATH = _PROCESSED_DIR / "dataset_featured.csv"
_RUNTIME_DIR = _PROCESSED_DIR / "runtime"
_DATASET_PATH = _RUNTIME_DIR / "dataset.csv"
_FEATURED_PATH = _RUNTIME_DIR / "dataset_featured.csv"
_HISTORICAL_FEATURED_PATH = _PROCESSED_DIR / "dataset_featured.csv"
_PREDICTIONS_PATH = _PROCESSED_DIR / "predictions_latest.json"
@@ -144,44 +153,96 @@ def run_feature_engineering(engineer: FeatureEngineer, df: pd.DataFrame) -> pd.D
return df
featured = engineer.transform(df)
_PROCESSED_DIR.mkdir(parents=True, exist_ok=True)
_FEATURED_PATH.parent.mkdir(parents=True, exist_ok=True)
featured.to_csv(_FEATURED_PATH, index=False)
logger.info("Featured dataset saved: %d rows, %d cols.", len(featured), len(featured.columns))
return featured
def _load_prediction_feature_base(runtime_featured_df: pd.DataFrame) -> pd.DataFrame:
"""Return the best available feature base for inference.
Preference order:
1. Historical `dataset_featured.csv` used for model training, when it
exists and contains more rows than the runtime snapshot.
2. The runtime-engineered dataset generated during this script run.
This prevents the daily pipeline from relying on a tiny runtime snapshot
when rich historical features are available.
"""
historical_df = pd.DataFrame()
if _HISTORICAL_FEATURED_PATH.exists():
try:
historical_df = pd.read_csv(_HISTORICAL_FEATURED_PATH, parse_dates=["date"])
logger.info(
"Loaded historical feature base from %s (%d rows).",
_HISTORICAL_FEATURED_PATH,
len(historical_df),
)
except Exception as exc:
logger.warning(
"Could not load historical feature base from %s: %s",
_HISTORICAL_FEATURED_PATH,
exc,
)
candidates = []
if not historical_df.empty:
candidates.append(("historical", historical_df))
if not runtime_featured_df.empty:
candidates.append(("runtime", runtime_featured_df))
if not candidates:
return runtime_featured_df
source_name, feature_base_df = max(candidates, key=lambda item: len(item[1]))
logger.info(
"Using %s feature base for predictions (%d rows).",
source_name,
len(feature_base_df),
)
return feature_base_df
def generate_predictions(
predictor: HybridPredictor,
weather_by_station: dict[str, pd.DataFrame],
featured_df: pd.DataFrame,
station_records: list[dict],
target_date: date,
output_path: Path,
) -> None:
"""Generate next-day predictions and save to disk."""
logger.info("Step 5/5 - Generating predictions.")
tomorrow = date.today() + timedelta(days=1)
"""Generate predictions for a target date and save them to disk."""
logger.info("Step 5/5 - Generating predictions for %s.", target_date.isoformat())
predictions = {}
station_map = {r["station_id"]: r for r in station_records}
base_date = date.today()
days_ahead = (target_date - base_date).days
feature_base_df = _load_prediction_feature_base(featured_df)
for station_id, weather_df in weather_by_station.items():
# Get tomorrow's forecast row as weather_data dict
tomorrow_rows = weather_df[weather_df["date"] == tomorrow]
if tomorrow_rows.empty:
tomorrow_rows = weather_df.iloc[1:2]
if tomorrow_rows.empty:
logger.warning("No forecast for tomorrow for %s.", station_id)
# Get target-date forecast row as weather_data dict.
target_rows = weather_df[weather_df["date"] == target_date]
if target_rows.empty:
fallback_index = max(0, min(days_ahead, len(weather_df) - 1))
target_rows = weather_df.iloc[fallback_index:fallback_index + 1]
if target_rows.empty:
logger.warning("No forecast for %s for %s.", station_id, target_date.isoformat())
continue
weather_data = tomorrow_rows.iloc[0].to_dict()
weather_data = target_rows.iloc[0].to_dict()
# Build a feature row: tomorrow's weather + today's station data
# (lifts_open, snow_depth are current observations - best proxy for tomorrow)
# Build a feature row: target-date weather + today's station data.
# Current station observations are still the best proxy available for
# same-day or next-day inference.
features_df = None
if not featured_df.empty:
station_featured = featured_df[featured_df["station_id"] == station_id]
if not feature_base_df.empty:
station_featured = feature_base_df[feature_base_df["station_id"] == station_id]
if not station_featured.empty:
# Start from the latest featured row (has rolling features)
features_df = station_featured.tail(1).copy()
# Overlay tomorrow's weather
features_df["date"] = pd.Timestamp(target_date)
# Overlay target-date weather
for col in weather_data:
if col in features_df.columns and col not in ("date", "station_id"):
features_df[col] = weather_data[col]
@@ -212,15 +273,42 @@ def generate_predictions(
logger.error("Prediction failed for %s: %s", station_id, exc)
# Save predictions
_PREDICTIONS_PATH.parent.mkdir(parents=True, exist_ok=True)
output_path.parent.mkdir(parents=True, exist_ok=True)
output = {
"generated_at": datetime.now(timezone.utc).isoformat(),
"prediction_date": tomorrow.isoformat(),
"prediction_date": target_date.isoformat(),
"stations": predictions,
}
with open(_PREDICTIONS_PATH, "w", encoding="utf-8") as fh:
with output_path.open("w", encoding="utf-8") as fh:
json.dump(output, fh, indent=2, ensure_ascii=False, default=str)
logger.info("Predictions saved to %s.", _PREDICTIONS_PATH)
logger.info("Predictions saved to %s.", output_path)
def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse CLI arguments for ad hoc prediction runs."""
parser = argparse.ArgumentParser(
description="Collect station/weather data and generate ski predictions.",
)
parser.add_argument(
"--days-ahead",
type=int,
default=1,
help="Prediction horizon in days relative to today (default: 1). Use 0 for today.",
)
parser.add_argument(
"--output-path",
default=str(_PREDICTIONS_PATH),
help="Path for the generated predictions JSON. Defaults to predictions_latest.json.",
)
return parser.parse_args(argv)
def _resolve_output_path(raw_path: str) -> Path:
"""Resolve an output path against the project root when relative."""
path = Path(raw_path)
if path.is_absolute():
return path
return (_PROJECT_ROOT / path).resolve()
# ---------------------------------------------------------------------------
@@ -228,14 +316,22 @@ def generate_predictions(
# ---------------------------------------------------------------------------
def main() -> int:
def main(argv: list[str] | None = None) -> int:
"""Run the full daily data collection and prediction pipeline."""
logger.info("=== Daily pipeline started ===")
args = _parse_args(argv)
target_date = date.today() + timedelta(days=args.days_ahead)
output_path = _resolve_output_path(args.output_path)
logger.info(
"=== Daily pipeline started (target_date=%s, output_path=%s) ===",
target_date.isoformat(),
output_path,
)
try:
weather_collector = WeatherCollector()
station_scraper = StationScraper()
dataset_builder = DatasetBuilder()
dataset_builder = DatasetBuilder(processed_dir=_RUNTIME_DIR)
feature_engineer = FeatureEngineer()
hybrid_predictor = HybridPredictor()
except Exception as exc:
@@ -257,7 +353,14 @@ def main() -> int:
featured_df = run_feature_engineering(feature_engineer, df)
# Step 5: predictions
generate_predictions(hybrid_predictor, weather_data, featured_df, station_records)
generate_predictions(
hybrid_predictor,
weather_data,
featured_df,
station_records,
target_date=target_date,
output_path=output_path,
)
logger.info("=== Daily pipeline finished ===")
return 0