mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 15:26:15 +00:00
feat(rules): refactor rules to be deterministic and add validation script
This commit is contained in:
1 parent
d2f543f19c
commit
49580ec010
2 files changed
+83
-59
No files matched your search
+10
-59
@@ -149,11 +149,11 @@ class RulesEngine:
|
||||
if wind_gust >= wind_threshold:
|
||||
force_closed = True
|
||||
reasons.append(
|
||||
f"Rachas de viento de {wind_gust:.1f} km/h superan el umbral de cierre de "
|
||||
f"{wind_threshold} km/h."
|
||||
f"Cierre forzoso por viento extremo: {wind_gust:.1f} km/h "
|
||||
f"(umbral histórico de seguridad: {wind_threshold} km/h)."
|
||||
)
|
||||
logger.info(
|
||||
"[%s] Rule 1 fired: wind gust %.1f > %.1f km/h -> force_closed",
|
||||
"[%s] Deterministic Rule: wind gust %.1f >= %.1f km/h -> force_closed",
|
||||
station_name,
|
||||
wind_gust,
|
||||
wind_threshold,
|
||||
@@ -168,76 +168,27 @@ class RulesEngine:
|
||||
force_closed = True
|
||||
km_factor = 0.0
|
||||
reasons.append(
|
||||
f"El espesor de nieve ({snow_depth:.1f} cm) está por debajo del mínimo "
|
||||
f"requerido ({min_snow} cm)."
|
||||
f"Espesor de nieve insuficiente ({snow_depth:.1f} cm) "
|
||||
f"para la apertura de pistas (mínimo requerido: {min_snow} cm)."
|
||||
)
|
||||
logger.info(
|
||||
"[%s] Rule 2 fired: snow depth %.1f < %.1f cm -> force_closed",
|
||||
"[%s] Deterministic Rule: snow depth %.1f < %.1f cm -> force_closed",
|
||||
station_name,
|
||||
snow_depth,
|
||||
min_snow,
|
||||
)
|
||||
|
||||
# ---- Rule 3: Heavy fresh snow + moderate wind -> likely open -----
|
||||
snowfall_24h = weather_data.get("snowfall_sum")
|
||||
wind_speed = weather_data.get("wind_gusts_10m_max", 0.0)
|
||||
|
||||
if (
|
||||
snowfall_24h is not None
|
||||
and snowfall_24h >= _HEAVY_FRESH_SNOW_THRESHOLD_CM
|
||||
and wind_speed is not None
|
||||
and wind_speed <= _MODERATE_WIND_THRESHOLD_KMH
|
||||
and not force_closed
|
||||
):
|
||||
force_open = True
|
||||
reasons.append(
|
||||
f"Nevada intensa ({snowfall_24h:.1f} cm en 24 h) con viento moderado "
|
||||
f"({wind_speed:.1f} km/h); es muy probable que la estación abra y esté concurrida."
|
||||
)
|
||||
logger.info(
|
||||
"[%s] Rule 3 fired: heavy snow %.1f cm + wind %.1f km/h -> force_open",
|
||||
station_name,
|
||||
snowfall_24h,
|
||||
wind_speed,
|
||||
)
|
||||
|
||||
# ---- Rule 4: Weekday + no fresh snow -> low crowd ----------------
|
||||
is_weekend = bool(weather_data.get("is_weekend", False))
|
||||
is_holiday = bool(weather_data.get("is_holiday", False))
|
||||
is_busy_day = is_weekend or is_holiday
|
||||
no_fresh_snow = (snowfall_24h is None or snowfall_24h < 5.0)
|
||||
|
||||
if not is_busy_day and no_fresh_snow and not force_closed:
|
||||
reasons.append(
|
||||
"Día laborable sin nevadas significativas; se espera un nivel de afluencia bajo."
|
||||
)
|
||||
logger.debug("[%s] Rule 4 fired: weekday + no fresh snow -> low crowd", station_name)
|
||||
|
||||
# ---- Rule 5: Weekend/holiday + fresh snow -> high crowd ----------
|
||||
if is_busy_day and snowfall_24h is not None and snowfall_24h >= 5.0 and not force_closed:
|
||||
reasons.append(
|
||||
f"Fin de semana o festivo con {snowfall_24h:.1f} cm de nieve fresca; "
|
||||
"se espera un nivel de afluencia alto."
|
||||
)
|
||||
logger.debug(
|
||||
"[%s] Rule 5 fired: busy day + fresh snow %.1f cm -> high crowd",
|
||||
station_name,
|
||||
snowfall_24h,
|
||||
)
|
||||
|
||||
# ---- Derive confidence -------------------------------------------
|
||||
if force_closed or force_open:
|
||||
# Confidence is 1.0 only if a deterministic closure rule fired.
|
||||
# Otherwise, confidence is 0.0, delegating all responsibility to ML.
|
||||
if force_closed:
|
||||
confidence = 1.0
|
||||
elif reasons:
|
||||
# Soft rules fired but no deterministic outcome
|
||||
confidence = 0.6
|
||||
else:
|
||||
# No rules fired; rules engine is inconclusive
|
||||
confidence = 0.0
|
||||
|
||||
result = {
|
||||
"force_closed": force_closed,
|
||||
"force_open": force_open,
|
||||
"force_open": False, # No force_open rules in this version
|
||||
"confidence": confidence,
|
||||
"reasons": reasons,
|
||||
"estimated_km_factor": km_factor,
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Analysis script to validate and derive deterministic operational rules from historical data.
|
||||
|
||||
This script scans the historical dataset to find categorical thresholds (e.g., wind speed,
|
||||
snow depth) where the station's open status is 100% predictable. These values
|
||||
should be used as 'hard rules' in config/stations.yaml.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import pandas as pd
|
||||
from storage import SQLiteStore, HISTORICAL_FEATURED_TABLE
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def analyze_station_thresholds(station_id: str, df: pd.DataFrame):
|
||||
"""Find the highest wind speed where the station ever opened and the minimum snow depth."""
|
||||
station_df = df[df["station_id"] == station_id].copy()
|
||||
if station_df.empty:
|
||||
logger.warning(f"No data for {station_id}")
|
||||
return
|
||||
|
||||
# 1. Wind Threshold Analysis
|
||||
# Find the maximum wind gust ever recorded while the station was OPEN (open_status=1)
|
||||
open_days = station_df[station_df["open_status"] == 1]
|
||||
if not open_days.empty:
|
||||
# Use wind_gusts_10m_max if available, fallback to wind_speed_10m_max
|
||||
wind_col = "wind_gusts_10m_max" if "wind_gusts_10m_max" in station_df.columns else "wind_speed_10m_max"
|
||||
max_wind_when_open = open_days[wind_col].max()
|
||||
logger.info(f"[{station_id}] Max wind recorded while OPEN: {max_wind_when_open:.1f} km/h")
|
||||
|
||||
# Find 100% closure zone: starting from max_wind_when_open, find the next threshold
|
||||
# where we have enough samples and ZERO are open.
|
||||
for w in range(int(max_wind_when_open), 130, 2):
|
||||
total_days = len(station_df[station_df[wind_col] >= w])
|
||||
if total_days >= 5: # Statistical significance
|
||||
open_at_w = len(station_df[(station_df[wind_col] >= w) & (station_df["open_status"] == 1)])
|
||||
if open_at_w == 0:
|
||||
logger.info(f"[{station_id}] SUGGESTED WIND THRESHOLD: {w} km/h (Deterministic closure)")
|
||||
break
|
||||
|
||||
# 2. Snow Depth Analysis
|
||||
if not open_days.empty:
|
||||
min_snow_when_open = open_days["snow_depth"].min()
|
||||
logger.info(f"[{station_id}] Min snow depth while OPEN: {min_snow_when_open:.1f} cm")
|
||||
|
||||
# Find 100% closure zone for snow (below threshold)
|
||||
for s in range(int(min_snow_when_open), 0, -2):
|
||||
total_days = len(station_df[station_df["snow_depth"] <= s])
|
||||
if total_days >= 5:
|
||||
open_at_s = len(station_df[(station_df["snow_depth"] <= s) & (station_df["open_status"] == 1)])
|
||||
if open_at_s == 0:
|
||||
logger.info(f"[{station_id}] SUGGESTED MIN SNOW: {s} cm (Deterministic closure)")
|
||||
break
|
||||
|
||||
def main():
|
||||
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
||||
store = SQLiteStore()
|
||||
|
||||
# Check multiple tables to find best available historical data
|
||||
df = store.read_dataframe(HISTORICAL_FEATURED_TABLE)
|
||||
if df.empty:
|
||||
from storage import HISTORICAL_MERGED_TABLE
|
||||
df = store.read_dataframe(HISTORICAL_MERGED_TABLE)
|
||||
|
||||
if df.empty:
|
||||
logger.error("No historical data found in SQLite. Run historical collection scripts first.")
|
||||
return
|
||||
|
||||
logger.info("--- Data-Driven Rule Validation ---\n")
|
||||
for station_id in df["station_id"].unique():
|
||||
analyze_station_thresholds(station_id, df)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user