"""Accuracy measurement for ski station predictions. Compares past predictions against actual station data to compute divergence metrics. Used for daily admin reports and accumulated accuracy tracking. """ import logging from datetime import date, timedelta from typing import Any from storage import SQLiteStore logger = logging.getLogger(__name__) def compute_daily_accuracy( target_date: date, store: SQLiteStore | None = None, ) -> dict[str, Any]: """Compare yesterday's prediction for target_date against actual data. Divergence metrics per station: - open_status_match: bool - Did we predict open/closed correctly? - open_prob_error: float - |predicted_probability - actual_status| - km_error: float|None - |predicted_km - actual_km| (None if station closed) - km_error_pct: float|None - Percentage error for km Returns dict with: - date: target date ISO string - stations: dict[station_id, metrics] - summary: overall accuracy metrics """ store = store or SQLiteStore() # Get the prediction made the day before (run_hour=20) for target_date # This is in past_forecasts since it was archived past_rows = store.load_past_forecasts( date_from=target_date.isoformat(), date_to=target_date.isoformat(), limit=100, ) # Filter to the 20:00 run from the day before yesterday = (target_date - timedelta(days=1)).isoformat() relevant_predictions = [ r for r in past_rows if r.get("run_hour") == 20 and r.get("generated_at", "").startswith(yesterday[:10]) ] # If no 20:00 predictions, try any prediction for that date if not relevant_predictions: relevant_predictions = [ r for r in past_rows if r.get("generated_at", "").startswith(yesterday[:10]) ] if not relevant_predictions: # Fallback: use any past forecast for target_date relevant_predictions = past_rows # Get actual data for target_date from historical_actuals with store.connect() as conn: actuals = conn.execute( "SELECT * FROM historical_actuals WHERE date = ?", (target_date.isoformat(),), ).fetchall() actual_map = {row["station_id"]: dict(row) for row in actuals} pred_map = {r["station_id"]: r for r in relevant_predictions} station_metrics = {} total_open_correct = 0 total_stations = 0 total_km_error = 0.0 km_count = 0 for station_id in ["pajares", "sanisidro", "fuentes"]: pred = pred_map.get(station_id) actual = actual_map.get(station_id) if pred is None or actual is None: station_metrics[station_id] = {"available": False} continue total_stations += 1 pred_prob = float(pred.get("open_probability") or 0) pred_open = pred_prob >= 0.5 actual_open = bool(actual.get("open_status")) open_match = pred_open == actual_open if open_match: total_open_correct += 1 open_prob_error = abs(pred_prob - (1.0 if actual_open else 0.0)) pred_km = float(pred.get("km_open") or 0) actual_km = float(actual.get("km_open") or 0) km_error = abs(pred_km - actual_km) if actual_open else None km_error_pct = None if actual_open and actual_km > 0: km_error_pct = (abs(pred_km - actual_km) / actual_km) * 100 station_metrics[station_id] = { "available": True, "open_status_match": open_match, "predicted_open": pred_open, "predicted_probability": pred_prob, "actual_open": actual_open, "open_prob_error": round(open_prob_error, 4), "predicted_km": pred_km, "actual_km": actual_km, "km_error": round(km_error, 2) if km_error is not None else None, "km_error_pct": round(km_error_pct, 1) if km_error_pct is not None else None, } if km_error is not None: total_km_error += km_error km_count += 1 open_accuracy = (total_open_correct / total_stations * 100) if total_stations > 0 else None avg_km_error = (total_km_error / km_count) if km_count > 0 else None return { "date": target_date.isoformat(), "stations": station_metrics, "summary": { "stations_evaluated": total_stations, "open_accuracy_pct": round(open_accuracy, 1) if open_accuracy is not None else None, "avg_km_error": round(avg_km_error, 2) if avg_km_error is not None else None, }, } def compute_accumulated_accuracy( days: int = 30, store: SQLiteStore | None = None, ) -> dict[str, Any]: """Compute accumulated accuracy over the last N days. Returns: - period_days: number of days evaluated - open_accuracy_pct: overall open/closed prediction accuracy - avg_km_error: average km prediction error - days_evaluated: actual number of days with data """ store = store or SQLiteStore() today = date.today() total_open_correct = 0 total_stations = 0 total_km_error = 0.0 km_count = 0 days_with_data = 0 for i in range(days): target = today - timedelta(days=i) try: daily = compute_daily_accuracy(target, store=store) except Exception: continue if daily["summary"]["stations_evaluated"] == 0: continue days_with_data += 1 for station_id, metrics in daily["stations"].items(): if not metrics.get("available"): continue total_stations += 1 if metrics["open_status_match"]: total_open_correct += 1 if metrics.get("km_error") is not None: total_km_error += metrics["km_error"] km_count += 1 open_accuracy = (total_open_correct / total_stations * 100) if total_stations > 0 else None avg_km_error = (total_km_error / km_count) if km_count > 0 else None return { "period_days": days, "days_evaluated": days_with_data, "total_station_predictions": total_stations, "open_accuracy_pct": round(open_accuracy, 1) if open_accuracy is not None else None, "avg_km_error": round(avg_km_error, 2) if avg_km_error is not None else None, } def format_accuracy_report( daily: dict[str, Any], accumulated: dict[str, Any], ) -> str: """Format accuracy data into an HTML message for Telegram. Args: daily: Output of compute_daily_accuracy() accumulated: Output of compute_accumulated_accuracy() Returns: HTML-formatted string ready for Telegram. """ lines = [f"📊 Informe de precisión - {daily['date']}\n"] # Station names for display station_names = { "pajares": "Valgrande-Pajares", "sanisidro": "San Isidro", "fuentes": "Fuentes de Invierno", } for station_id in ["pajares", "sanisidro", "fuentes"]: metrics = daily["stations"].get(station_id, {}) name = station_names.get(station_id, station_id) if not metrics.get("available"): lines.append(f"\n{name}: Sin datos") continue status_icon = "✅" if metrics["open_status_match"] else "❌" pred_status = "Abierta" if metrics["predicted_open"] else "Cerrada" actual_status = "Abierta" if metrics["actual_open"] else "Cerrada" lines.append(f"\n{name}") lines.append( f" {status_icon} Estado: predicho {pred_status} / real {actual_status}" f" (prob: {metrics['predicted_probability']:.0%})" ) if metrics.get("km_error") is not None: lines.append( f" Km: predicho {metrics['predicted_km']:.1f} / " f"real {metrics['actual_km']:.1f} " f"(error: {metrics['km_error']:.1f} km" + (f", {metrics['km_error_pct']:.0f}%" if metrics.get("km_error_pct") is not None else "") + ")" ) # Summary summary = daily["summary"] lines.append(f"\nResumen del día:") if summary["open_accuracy_pct"] is not None: lines.append(f" Acierto apertura: {summary['open_accuracy_pct']:.0f}%") if summary["avg_km_error"] is not None: lines.append(f" Error medio km: {summary['avg_km_error']:.1f} km") # Accumulated lines.append(f"\nAcumulado ({accumulated['period_days']} días):") lines.append(f" Días con datos: {accumulated['days_evaluated']}") if accumulated["open_accuracy_pct"] is not None: lines.append(f" Acierto apertura: {accumulated['open_accuracy_pct']:.0f}%") if accumulated["avg_km_error"] is not None: lines.append(f" Error medio km: {accumulated['avg_km_error']:.1f} km") return "\n".join(lines)