feat(storage): migrate project to sqlite

This commit is contained in:
dasemu committed 2026-03-13 06:50:18 +01:00
1 parent 1bc1e58781
commit 9c8ba03574
17 files changed
+1204 -688

No files matched your search

+61 -91
View File
@@ -1,12 +1,12 @@
"""Build the full historical dataset by merging station data with weather.
Steps:
1. Load historical station CSV from infonieve.es (data/raw/station_historical_all.csv)
1. Load historical station data from SQLite or download it from infonieve.es
2. Map infonieve columns to the project schema
3. Fetch historical weather from Open-Meteo for 2009-2026 in 1-year chunks
3. Fetch historical weather from Open-Meteo for 2009-2026 when SQLite has no cache
4. Merge weather + station data on (date, station_id)
5. Run feature engineering
6. Save to data/processed/dataset_featured.csv
6. Save the merged and featured datasets to SQLite
7. Train ML models
Column mapping from infonieve schema to project schema:
@@ -21,8 +21,7 @@ Column mapping from infonieve schema to project schema:
import logging
import sys
import time
from datetime import date
from datetime import date, timedelta
from pathlib import Path
import pandas as pd
@@ -34,8 +33,16 @@ REPO_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO_ROOT))
from data_sources.weather_api import WeatherCollector
from data_sources.infonieve_historical import download_all_history
from pipeline.feature_engineering import FeatureEngineer
from ml.train_model import ModelTrainer
from storage import (
HISTORICAL_FEATURED_TABLE,
HISTORICAL_MERGED_TABLE,
HISTORICAL_STATION_TABLE,
HISTORICAL_WEATHER_TABLE,
SQLiteStore,
)
# ---------------------------------------------------------------------------
# Logging
@@ -49,10 +56,6 @@ logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
STATION_CSV = REPO_ROOT / "data" / "raw" / "station_historical_all.csv"
OUTPUT_DIR = REPO_ROOT / "data" / "processed"
OUTPUT_PATH = OUTPUT_DIR / "dataset_featured.csv"
# Weather fetch range - driven by what is in the station data
WEATHER_START_YEAR = 2009
WEATHER_END_YEAR = 2026 # inclusive
@@ -68,25 +71,18 @@ STATIONS = {
"sanisidro": {"latitude": 43.0700, "longitude": -5.3700},
}
# Delay between API calls to avoid rate-limiting (seconds)
API_CALL_DELAY = 3.0
# Extra pause between stations (seconds)
INTER_STATION_DELAY = 10.0
# Local cache directory for per-year weather chunks
WEATHER_CACHE_DIR = REPO_ROOT / "data" / "raw" / "weather_cache"
# ---------------------------------------------------------------------------
# Step 1: Load and map station data
# ---------------------------------------------------------------------------
def load_station_data() -> pd.DataFrame:
"""Load the infonieve historical CSV and map columns to project schema."""
logger.info("Loading station data from %s", STATION_CSV)
df = pd.read_csv(STATION_CSV)
logger.info("Loaded %d rows, %d columns", len(df), len(df.columns))
def load_station_data(store: SQLiteStore) -> pd.DataFrame:
"""Load historical station raw data from SQLite and map it to project schema."""
df = store.load_historical_station_raw()
if df.empty:
logger.info("No historical station data found in SQLite. Downloading fresh history.")
df = download_all_history(store=store)
else:
logger.info("Loaded %d historical station rows from SQLite.", len(df))
# Parse dates with mixed formats (ISO and day-first variants)
df["date"] = pd.to_datetime(df["date"], format="mixed", dayfirst=True)
@@ -158,25 +154,22 @@ def load_station_data() -> pd.DataFrame:
# ---------------------------------------------------------------------------
# Step 2: Fetch historical weather in 1-year chunks
# Step 2: Fetch historical weather
# ---------------------------------------------------------------------------
def _cache_path(station_id: str, year: int) -> Path:
"""Return the local cache file path for a (station, year) chunk."""
return WEATHER_CACHE_DIR / f"weather_{station_id}_{year}.csv"
def fetch_weather_all_stations(store: SQLiteStore) -> pd.DataFrame:
"""Load cached historical weather from SQLite or fetch it from Open-Meteo."""
cached = store.read_dataframe(HISTORICAL_WEATHER_TABLE, parse_dates=("date",))
yesterday = pd.Timestamp(date.today() - timedelta(days=1))
if not cached.empty and cached["date"].max() >= yesterday:
logger.info(
"Loaded %d historical weather rows from SQLite table %s.",
len(cached),
HISTORICAL_WEATHER_TABLE,
)
return cached
def fetch_weather_all_stations() -> pd.DataFrame:
"""Fetch full historical weather for all stations in annual chunks.
Each (station, year) chunk is cached to
``data/raw/weather_cache/weather_{station_id}_{year}.csv``.
If the cache file already exists the API call is skipped, making
reruns fast and avoiding rate-limit exhaustion.
The current year's cache is always refreshed (partial year grows daily).
"""
WEATHER_CACHE_DIR.mkdir(parents=True, exist_ok=True)
logger.info("Historical weather cache missing or stale. Fetching from Open-Meteo.")
collector = WeatherCollector()
all_frames: list[pd.DataFrame] = []
@@ -187,36 +180,21 @@ def fetch_weather_all_stations() -> pd.DataFrame:
lat = coords["latitude"]
lon = coords["longitude"]
station_frames: list[pd.DataFrame] = []
needs_api_call = False
for year in range(WEATHER_START_YEAR, end_year + 1):
cache_file = _cache_path(station_id, year)
start_date = f"{year}-01-01"
# For the current partial year always refresh the cache
is_current_year = year == today.year
if cache_file.exists() and not is_current_year:
logger.info(
"Cache hit: %s (skipping API call)", cache_file.name
)
df = pd.read_csv(cache_file)
df["date"] = pd.to_datetime(df["date"])
station_frames.append(df)
continue
# For the current year, only fetch up to yesterday
if is_current_year:
from datetime import timedelta
yesterday = today - timedelta(days=1)
end_date = yesterday.strftime("%Y-%m-%d")
else:
end_date = f"{year}-12-31"
end_date = (
(today - timedelta(days=1)).strftime("%Y-%m-%d")
if year == today.year
else f"{year}-12-31"
)
logger.info(
"Fetching weather for station=%s year=%d (%s to %s)",
station_id, year, start_date, end_date,
station_id,
year,
start_date,
end_date,
)
needs_api_call = True
try:
df = collector.get_historical(
@@ -228,42 +206,29 @@ def fetch_weather_all_stations() -> pd.DataFrame:
)
if not df.empty:
df["date"] = pd.to_datetime(df["date"])
# Save to per-year cache (not the rolling weather_X_today.csv)
df.to_csv(cache_file, index=False)
logger.info(
" -> Got %d rows; cached to %s",
len(df), cache_file.name,
)
station_frames.append(df)
except RuntimeError as exc:
logger.error(
"Weather fetch failed for station=%s year=%d: %s",
station_id, year, exc,
station_id,
year,
exc,
)
# Be polite to the API between calls
time.sleep(API_CALL_DELAY)
if station_frames:
combined = pd.concat(station_frames, ignore_index=True)
combined["date"] = pd.to_datetime(combined["date"])
combined.drop_duplicates(subset=["date", "station_id"], inplace=True)
combined.sort_values("date", inplace=True)
all_frames.append(combined)
logger.info(
"Total weather rows for %s: %d", station_id, len(combined)
)
if needs_api_call:
# Only pause if we actually made API calls for this station
logger.info("Pausing %ds before next station.", INTER_STATION_DELAY)
time.sleep(INTER_STATION_DELAY)
logger.info("Total weather rows for %s: %d", station_id, len(combined))
if not all_frames:
raise RuntimeError("No weather data fetched for any station.")
weather = pd.concat(all_frames, ignore_index=True)
weather["date"] = pd.to_datetime(weather["date"])
store.save_weather_snapshot(weather, table_name=HISTORICAL_WEATHER_TABLE)
logger.info("Total weather rows across all stations: %d", len(weather))
return weather
@@ -318,11 +283,15 @@ def run_feature_engineering(df: pd.DataFrame) -> pd.DataFrame:
# Step 5: Save
# ---------------------------------------------------------------------------
def save_dataset(df: pd.DataFrame) -> None:
"""Persist the featured dataset to disk."""
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
df.to_csv(OUTPUT_PATH, index=False)
logger.info("Featured dataset saved to %s (%d rows)", OUTPUT_PATH, len(df))
def save_dataset(store: SQLiteStore, merged_df: pd.DataFrame, featured_df: pd.DataFrame) -> None:
"""Persist merged and featured datasets to SQLite."""
store.replace_dataframe(HISTORICAL_MERGED_TABLE, merged_df)
store.replace_dataframe(HISTORICAL_FEATURED_TABLE, featured_df)
logger.info(
"Historical datasets saved to SQLite tables %s and %s.",
HISTORICAL_MERGED_TABLE,
HISTORICAL_FEATURED_TABLE,
)
# ---------------------------------------------------------------------------
@@ -391,12 +360,13 @@ def print_summary(df: pd.DataFrame) -> None:
def main() -> None:
logger.info("Starting full dataset build pipeline.")
store = SQLiteStore()
# Step 1: Load and map station data
station_df = load_station_data()
station_df = load_station_data(store)
# Step 2: Fetch historical weather
weather_df = fetch_weather_all_stations()
weather_df = fetch_weather_all_stations(store)
# Step 3: Merge
merged = merge_datasets(weather_df, station_df)
@@ -405,14 +375,14 @@ def main() -> None:
featured = run_feature_engineering(merged)
# Step 5: Save
save_dataset(featured)
save_dataset(store, merged, featured)
# Step 6: Summary
print_summary(featured)
# Step 7: Train models
logger.info("Starting model training on the full dataset.")
trainer = ModelTrainer(dataset_path=OUTPUT_PATH)
trainer = ModelTrainer(store=store, dataset_table=HISTORICAL_FEATURED_TABLE)
cv_results = trainer.train_all()
print("\nCROSS-VALIDATION RESULTS")