File size: 3,587 Bytes
5edd575 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | """The ONE place the 18 model inputs are built (used by notebooks, Streamlit, HF Space, FastAPI)."""
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
import numpy as np
import pandas as pd
from src.config import COUNTRIES, FEATURES, MONTH_OFFSET, DAY_OFFSET, RANGES
def time_features_from_utc(ts_utc: datetime) -> dict:
"""Engineered time features from a timezone-aware UTC datetime (same formulas as training)."""
h, m, d, dow = (
ts_utc.hour,
ts_utc.month,
ts_utc.timetuple().tm_yday,
ts_utc.weekday(),
)
return {
"hour": h,
"day_of_week": dow,
"month": m,
"day_of_year": d,
"is_weekend": int(dow >= 5),
"hour_sin": np.sin(2 * np.pi * h / 24),
"hour_cos": np.cos(2 * np.pi * h / 24),
"month_sin": np.sin(2 * np.pi * (m - MONTH_OFFSET) / 12),
"month_cos": np.cos(2 * np.pi * (m - MONTH_OFFSET) / 12),
"day_year_sin": np.sin(2 * np.pi * (d - DAY_OFFSET) / 365.25),
"day_year_cos": np.cos(2 * np.pi * (d - DAY_OFFSET) / 365.25),
}
def local_to_utc(country: str, local_dt: datetime) -> datetime:
"""Convert a local date-time in the country's time zone to UTC (naive input = local time)."""
if local_dt.tzinfo is None:
local_dt = local_dt.replace(tzinfo=ZoneInfo(COUNTRIES[country]["tz"]))
return local_dt.astimezone(timezone.utc)
def validate_inputs(country: str, **weather) -> None:
if country not in COUNTRIES:
raise ValueError("Country not supported. Choose from the list.")
for name, (lo, hi) in RANGES.items():
v = weather.get(name)
if v is None or not (lo <= float(v) <= hi):
raise ValueError(f"{name} must be between {lo} and {hi}.")
def make_features(
country: str,
local_dt: datetime,
temperature_2m: float,
relative_humidity_2m: float,
cloud_cover: float,
wind_speed_10m: float,
surface_pressure: float,
shortwave_radiation: float,
) -> pd.DataFrame:
"""One-row DataFrame with the 18 input columns. local_dt is local time in the country (naive or aware)."""
weather = dict(
temperature_2m=temperature_2m,
relative_humidity_2m=relative_humidity_2m,
cloud_cover=cloud_cover,
wind_speed_10m=wind_speed_10m,
surface_pressure=surface_pressure,
shortwave_radiation=shortwave_radiation,
)
validate_inputs(country, **weather)
ts_utc = local_to_utc(country, local_dt) # the model uses the UTC hour (fix F10)
row = {**weather, "country": country, **time_features_from_utc(ts_utc)}
return pd.DataFrame([row])[FEATURES]
def add_time_features(df: pd.DataFrame, ts_col: str = "timestamp") -> pd.DataFrame:
"""Vectorised version used when building the dataset. Same formulas as time_features_from_utc()."""
out = df.copy()
ts = pd.to_datetime(out[ts_col], utc=True)
out["hour"] = ts.dt.hour
out["day_of_week"] = ts.dt.dayofweek
out["month"] = ts.dt.month
out["day_of_year"] = ts.dt.dayofyear
out["is_weekend"] = (out["day_of_week"] >= 5).astype(int)
out["hour_sin"] = np.sin(2 * np.pi * out["hour"] / 24)
out["hour_cos"] = np.cos(2 * np.pi * out["hour"] / 24)
out["month_sin"] = np.sin(2 * np.pi * (out["month"] - MONTH_OFFSET) / 12)
out["month_cos"] = np.cos(2 * np.pi * (out["month"] - MONTH_OFFSET) / 12)
out["day_year_sin"] = np.sin(2 * np.pi * (out["day_of_year"] - DAY_OFFSET) / 365.25)
out["day_year_cos"] = np.cos(2 * np.pi * (out["day_of_year"] - DAY_OFFSET) / 365.25)
return out
|