🧠 Adaptive Model Selection β€” Architecture Plan

Self-learning weather model picker: use the best model for each location, time horizon, and weather parameter β€’ Aug 2026

1. The Vision

Core idea: Instead of always using "Best match" or a fixed model, the system continuously learns which model performs best for each specific location/parameter/time-horizon combination, and automatically selects it.

Example: ECMWF might be best for temperature in Budapest at 3-day range, but ICON wins for precipitation in Miskolc at 1-day range. The system figures this out automatically from accumulated accuracy data.

2. Storage Strategy β€” Start Simple, Scale Later

Approach: Start with JSON files (extend current system), migrate to SQLite when complexity demands it.

PhaseStorageWhenWhy
Now JSON files (current + extended) Immediate No migration needed, works today, keeps things moving
Later SQLite (single file DB) When JSON gets painful (~6+ months of data, complex queries needed) Better aggregations, proper joins, still zero infrastructure
Probably never PostgreSQL / MySQL Multi-user concurrent access Overkill for this project

JSON file structure for Phase 1:

data/
β”œβ”€β”€ forecasts/                    # existing: daily snapshots per city
β”‚   β”œβ”€β”€ 2026-08-07_inarcs.json
β”‚   β”œβ”€β”€ 2026-08-07_budapest.json
β”‚   └── ...
β”œβ”€β”€ scores.json                   # existing: evaluation results
β”œβ”€β”€ stations.json                 # NEW: tracked locations (fixed + route-discovered)
β”œβ”€β”€ model-rankings.json           # NEW: best model per station/param/horizon
└── route-logs/                   # NEW: route request logs for feedback loop
    β”œβ”€β”€ 2026-08-08_route_001.json
    β”œβ”€β”€ 2026-08-08_route_002.json
    └── ...

stations.json structure:

{
  "stations": [
    {
      "id": "inarcs",
      "lat": 47.2492,
      "lon": 19.3192,
      "name": "Inarcs",
      "source": "fixed"        // shown in reports + home page
    },
    {
      "id": "budapest",
      "lat": 47.4979,
      "lon": 19.0402,
      "name": "Budapest",
      "source": "fixed"
    },
    {
      "id": "hatvan_area",
      "lat": 47.6714,
      "lon": 19.6783,
      "name": "Hatvan",
      "source": "route",       // only used for model selection, not in reports
      "discovered": "2026-08-08"
    }
  ]
}

model-rankings.json structure:

{
  "updated": "2026-08-08T07:00:00",
  "rankings": {
    "inarcs": {
      "temp": {
        "short": { "model": "ICON", "avg_error": 1.2, "samples": 28, "confidence": 0.85 },
        "medium": { "model": "ECMWF", "avg_error": 2.1, "samples": 25, "confidence": 0.72 },
        "long": { "model": "GFS", "avg_error": 3.4, "samples": 22, "confidence": 0.55 }
      },
      "precip": { ... },
      "wind": { ... }
    },
    "budapest": { ... },
    "hatvan_area": { ... }
  }
}

route-logs/2026-08-08_route_001.json:

{
  "request_id": "a1b2c3d4",
  "requested_at": "2026-08-08T16:30:00",
  "waypoints": [
    {
      "lat": 47.4979, "lon": 19.0402,
      "city": "Budapest",
      "target_time": "2026-08-08T16:30:00",
      "forecasts": {
        "ECMWF": { "temp": 32.1, "precip": 0, "wind": 12, "cloud": 25 },
        "GFS":   { "temp": 31.5, "precip": 0, "wind": 14, "cloud": 30 },
        "ICON":  { "temp": 32.4, "precip": 0, "wind": 11, "cloud": 20 },
        "AROME": { "temp": 32.8, "precip": 0, "wind": 13, "cloud": 22 }
      },
      "evaluated": false
    },
    { ... }
  ]
}

When to migrate to SQLite:

Migration is straightforward when the time comes: read all JSON β†’ INSERT into SQLite tables β†’ done in one script.

⚠️ CRITICAL GAP: Browser β†’ Server data pipeline

The route feedback loop has a missing link: the route planner runs client-side in the user's browser, but the evaluation pipeline runs server-side on cron. Data must travel from browser β†’ server file system.

StatusComponentWhere
βœ… DoneRoute planner fetches all models, stores predictionsBrowser (localStorage)
βœ… Doneevaluate-routes.py scores route logs against actualsServer (cron)
❌ MissingGetting route logs FROM browser TO serverThe gap

Resolution (pick one when web hosting is active):

Until this gap is closed, the fixed 4 cities learn normally (server-side pipeline is complete), but route-discovered stations won't accumulate.

3. Architecture Overview

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ DAILY CRON (07:00) β”‚ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ save-forecast│───▢│ JSON files │◀───│ evaluate (compare forecast β”‚ β”‚ β”‚ β”‚ (snapshot) β”‚ β”‚ β”‚ β”‚ vs actual measured data) β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β€’ forecasts/ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β€’ scores.jsonβ”‚ β”‚ β”‚ β”‚ β€’ stations β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ β€’ rankings │───▢│ model-selector β”‚ β”‚ β”‚ β”‚ β€’ route-logs/β”‚ β”‚ (pick best per location/ β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ param/horizon) β”‚ β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β–Ό β–Ό β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ HTML reports β”‚ β”‚ weather-forecast.py β”‚ β”‚ β”‚ β”‚ (rankings, β”‚ β”‚ (uses selected model per β”‚ β”‚ β”‚ β”‚ history) β”‚ β”‚ location for display) β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ route-weather.js (client-side) β”‚ β”‚ Reads model-rankings.json β”‚ β”‚ Logs route points for feedback β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

4. Data Schema (JSON β€” Phase 1)

The JSON structures from section 2 are the working schema. For reference, here's how the data logically relates β€” this same structure maps 1:1 to SQLite tables when the time comes to migrate:

# Logical entities (implemented as JSON files now, SQLite tables later):

forecasts/YYYY-MM-DD_city.json    β†’  forecasts table
  β€’ city, model, issued_date, target_time
  β€’ temp_c, precip_mm, cloud_pct, wind_kmh, pressure, humidity

scores.json                        β†’  scores table
  β€’ city (or station_id), model, issued_date, target_date
  β€’ horizon_days, param, error

stations.json                      β†’  stations table
  β€’ id, lat, lon, name, source ('fixed'|'route'), discovered date

model-rankings.json                β†’  model_rankings table
  β€’ station_id, param, horizon, model, avg_error, sample_size, rank

route-logs/YYYY-MM-DD_NNN.json    β†’  route_points + route_forecasts tables
  β€’ request_id, waypoints[], each with forecasts per model
  β€’ evaluated flag for feedback loop

Future SQLite schema (kept here for reference β€” use when migrating):

β–Ά Click to expand SQLite schema (for future migration)
-- Raw forecast snapshots (replaces data/forecasts/*.json)
CREATE TABLE forecasts (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    city        TEXT NOT NULL,           -- 'inarcs', 'budapest', ...
    model       TEXT NOT NULL,           -- 'ECMWF', 'GFS', 'ICON', 'AROME', 'BestMatch'
    issued_date DATE NOT NULL,           -- when forecast was fetched
    target_time DATETIME NOT NULL,       -- what hour it predicts
    temp_c      REAL,
    precip_mm   REAL,
    cloud_pct   REAL,
    wind_kmh    REAL,
    wind_gust   REAL,
    pressure    REAL,
    humidity    REAL,
    weather_code INTEGER,
    UNIQUE(city, model, issued_date, target_time)
);

-- Measured actuals (from Open-Meteo history API)
CREATE TABLE actuals (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    city        TEXT NOT NULL,
    time        DATETIME NOT NULL,
    temp_c      REAL,
    precip_mm   REAL,
    cloud_pct   REAL,
    wind_kmh    REAL,
    wind_gust   REAL,
    pressure    REAL,
    humidity    REAL,
    UNIQUE(city, time)
);

-- Evaluation scores (forecast vs actual)
CREATE TABLE scores (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    city        TEXT NOT NULL,
    model       TEXT NOT NULL,
    issued_date DATE NOT NULL,           -- when forecast was made
    target_date DATE NOT NULL,           -- what day it predicted
    horizon_days INTEGER NOT NULL,       -- target_date - issued_date
    param       TEXT NOT NULL,           -- 'temp', 'precip', 'wind', 'cloud'
    error       REAL NOT NULL,           -- absolute error (MAE for that day)
    scored_at   DATETIME DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(city, model, issued_date, target_date, param)
);

-- Model rankings (aggregated, recalculated daily)
CREATE TABLE model_rankings (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    city        TEXT NOT NULL,
    region      TEXT,                    -- optional: area grouping
    param       TEXT NOT NULL,           -- 'temp', 'precip', 'wind', 'overall'
    horizon     TEXT NOT NULL,           -- 'short' (1-2d), 'medium' (3-4d), 'long' (5-7d)
    model       TEXT NOT NULL,
    avg_error   REAL NOT NULL,
    sample_size INTEGER NOT NULL,
    rank        INTEGER NOT NULL,
    window_days INTEGER DEFAULT 30,     -- rolling window used
    updated_at  DATETIME DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(city, param, horizon, model)
);

-- Indexes for fast lookups
CREATE INDEX idx_forecasts_lookup ON forecasts(city, model, target_time);
CREATE INDEX idx_actuals_lookup ON actuals(city, time);
CREATE INDEX idx_scores_ranking ON scores(city, model, param, horizon_days);
CREATE INDEX idx_rankings_best ON model_rankings(city, param, horizon, rank);

5. The Self-Learning Loop

Step 1: Collect (daily, automated)

Each morning, save-forecast.py saves all model predictions for the next 7 days into data/forecasts/ JSON files. Same as today β€” no change needed.

Step 2: Evaluate (daily, automated)

evaluate.py compares forecasts made N days ago with actual measurements. Calculates error per model/city/parameter/horizon and stores in scores table.

-- "How wrong was ECMWF about temperature in Inarcs 
--  when predicting 2 days ahead, over the last 30 days?"
SELECT model, AVG(ABS(error)) as mae, COUNT(*) as samples
FROM scores
WHERE city = 'inarcs' 
  AND param = 'temp'
  AND horizon_days = 2
  AND scored_at > date('now', '-30 days')
GROUP BY model
ORDER BY mae ASC;

Step 3: Rank (daily, automated)

After scoring, recalculate model_rankings. This is the "learning" β€” with more data, rankings become more confident and shift as models improve/degrade seasonally.

-- Recalculate: best model for temp, short-term, Inarcs
INSERT OR REPLACE INTO model_rankings (city, param, horizon, model, avg_error, sample_size, rank)
SELECT city, param,
       CASE WHEN horizon_days <= 2 THEN 'short'
            WHEN horizon_days <= 4 THEN 'medium'
            ELSE 'long' END as horizon,
       model, AVG(error), COUNT(*),
       RANK() OVER (PARTITION BY city, param ORDER BY AVG(error) ASC)
FROM scores
WHERE city = 'inarcs' AND param = 'temp' AND horizon_days <= 2
  AND scored_at > date('now', '-30 days')
GROUP BY city, param, model;

Step 4: Select (at forecast time)

When generating a forecast for a specific location, the system queries the rankings and picks the best model:

def get_best_model(city: str, param: str, horizon: str) -> str:
    """Return the best-performing model for this combination."""
    row = db.execute("""
        SELECT model FROM model_rankings
        WHERE city = ? AND param = ? AND horizon = ? AND rank = 1
          AND sample_size >= 7  -- minimum confidence threshold
    """, (city, param, horizon)).fetchone()
    
    if row:
        return row[0]
    return "BestMatch"  # fallback when not enough data

6. Route Feedback Loop β€” Crowd-Sourced Learning Points

Key insight: Every time a user requests a route forecast, the waypoints along that route become new "observation points." The system saves all model forecasts for those points, then evaluates them against actuals the next day. The coverage map grows organically with usage.

User requests route Next day (automated) Budapest β†’ Miskolc β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Route calculated β”‚ β”‚ evaluate-route-points.py β”‚ β”‚ Waypoints: β”‚ β”‚ β”‚ β”‚ β€’ Budapest │──── saved to DB ────▢│ For each pending point: β”‚ β”‚ β€’ Hatvan β”‚ (all models, β”‚ 1. Fetch actual weather β”‚ β”‚ β€’ FΓΌzesabony β”‚ all params) β”‚ 2. Compare with stored β”‚ β”‚ β€’ Miskolc β”‚ β”‚ forecasts per model β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ 3. Score β†’ scores table β”‚ β”‚ 4. Recalculate rankings β”‚ β”‚ for these coords β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ model_rankings now has β”‚ β”‚ data for Hatvan & β”‚ β”‚ FΓΌzesabony too! β”‚ β”‚ β”‚ β”‚ Next route through that β”‚ β”‚ area β†’ smarter model pick β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

How it works:

  1. User requests a route β†’ client-side JS fetches weather from ALL models for each waypoint (not just one)
  2. Client sends a "log" request β†’ a tiny POST to a static-friendly endpoint (or: appends to a log file via the daily cron sync)
  3. Daily cron picks up pending route points β†’ fetches actual measured weather for those coords from yesterday
  4. Scores get calculated β†’ same as for the fixed cities, but now for arbitrary coords
  5. Rankings expand β†’ the system now knows which model is best near Hatvan, FΓΌzesabony, etc.

Database additions:

-- Route forecast log: what the user asked for
CREATE TABLE route_points (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    request_id  TEXT NOT NULL,           -- groups points from same route request
    lat         REAL NOT NULL,
    lon         REAL NOT NULL,
    city_name   TEXT,                    -- reverse-geocoded name
    target_time DATETIME NOT NULL,       -- when the user would arrive there
    created_at  DATETIME DEFAULT CURRENT_TIMESTAMP,
    evaluated   BOOLEAN DEFAULT 0        -- flag: has this been scored yet?
);

-- Forecasts stored for route points (all models)
CREATE TABLE route_forecasts (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    route_point_id INTEGER REFERENCES route_points(id),
    model       TEXT NOT NULL,
    temp_c      REAL,
    precip_mm   REAL,
    cloud_pct   REAL,
    wind_kmh    REAL,
    pressure    REAL,
    UNIQUE(route_point_id, model)
);

CREATE INDEX idx_route_points_pending ON route_points(evaluated, target_time);
CREATE INDEX idx_route_points_coords ON route_points(lat, lon);

The coverage grows organically:

DayCoverageHow
Day 14 fixed citiesOriginal setup
Day 24 + 3 route pointsUser drove Budapest→Miskolc
Day 54 + 12 route pointsMore routes requested
Day 304 + 80+ unique areasOrganic growth
Day 90Dense coverage of HungaryRepeated routes build confidence

Same coordinate requested multiple times = higher confidence ranking for that area.

Clustering nearby points:

-- Don't treat points 500m apart as different locations.
-- Cluster within ~5km radius β†’ same "observation station"
def get_or_create_station(lat, lon, city_name):
    """Find existing nearby station or create new one."""
    existing = db.execute("""
        SELECT id, lat, lon, city_name FROM stations
        WHERE ABS(lat - ?) < 0.045 AND ABS(lon - ?) < 0.06  -- ~5km box
        ORDER BY (lat-?)*(lat-?) + (lon-?)*(lon-?) ASC
        LIMIT 1
    """, (lat, lon, lat, lat, lon, lon)).fetchone()
    
    if existing:
        return existing['id']
    
    # New station discovered via route usage
    db.execute("""INSERT INTO stations (lat, lon, city_name, source)
                  VALUES (?, ?, ?, 'route')""", (lat, lon, city_name))
    return db.lastrowid

CREATE TABLE stations (
    id        INTEGER PRIMARY KEY AUTOINCREMENT,
    lat       REAL NOT NULL,
    lon       REAL NOT NULL,
    city_name TEXT,
    source    TEXT DEFAULT 'fixed',  -- 'fixed' (original 4) or 'route' (user-generated)
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

Client-side implementation:

// In route-weather.js β€” after calculating results, log the route points
async function logRouteForLearning(waypoints) {
  const requestId = crypto.randomUUID();
  const points = waypoints.map(wp => ({
    lat: wp.lat, lon: wp.lon,
    city: wp.city,
    target_time: wp.arrivalTime.toISOString(),
    forecasts: wp.allModelData  // all models' predictions stored
  }));
  
  // Option A: POST to a tiny API on the web server
  // Option B: Store in localStorage, sync via daily export
  // Option C: Append to a shared JSON log file (simplest for static hosting)
  
  try {
    await fetch('/api/log-route', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ request_id: requestId, points })
    });
  } catch (e) {
    // Non-critical: learning is best-effort
    console.log('Route logging skipped (offline or no API)');
  }
}

Static hosting limitation: Pure static hosting can't receive POST requests. Solutions:

Option C is cleanest once your tarhely.com hosting supports Python/PHP scripts.

Evaluation pipeline (daily cron addition):

def evaluate_route_points():
    """Score route forecasts from 1+ days ago against actuals."""
    pending = db.execute("""
        SELECT rp.*, rf.model, rf.temp_c, rf.precip_mm, rf.wind_kmh
        FROM route_points rp
        JOIN route_forecasts rf ON rf.route_point_id = rp.id
        WHERE rp.evaluated = 0
          AND rp.target_time < datetime('now', '-1 hour')
    """).fetchall()
    
    for point in pending:
        # Fetch actual weather from Open-Meteo history
        actual = fetch_actual_weather(point['lat'], point['lon'], point['target_time'])
        
        # Score this model's prediction
        station_id = get_or_create_station(point['lat'], point['lon'], point['city_name'])
        
        for param in ['temp', 'precip', 'wind']:
            error = abs(point[f'{param}_forecast'] - actual[param])
            db.execute("""INSERT INTO scores 
                (station_id, model, target_date, param, error, horizon_days)
                VALUES (?, ?, ?, ?, ?, ?)""",
                (station_id, point['model'], point['target_time'][:10], 
                 param, error, 0))  # horizon=0 for same-day route forecasts
    
    # Mark as evaluated
    db.execute("UPDATE route_points SET evaluated = 1 WHERE evaluated = 0 AND target_time < datetime('now', '-1 hour')")
    db.commit()

7. Region-Based Selection (for Route Weather)

Problem (before feedback loop): The route planner passes through areas we don't have accuracy data for.

Solution (with feedback loop): The problem solves itself over time! As users request routes, the coverage map fills in. For new/unvisited areas, fall back to nearest station with data.

Solution: Spatial model selection β€” assign regions to nearby tracked cities.

-- Nearest station with data (combines fixed cities + route-discovered stations)
def get_best_model_for_coords(lat, lon, param, horizon):
    """Find the nearest station we have ranking data for."""
    station = db.execute("""
        SELECT id, city_name,
               (lat-?)*(lat-?) + (lon-?)*(lon-?) as dist_sq
        FROM stations
        WHERE id IN (SELECT DISTINCT station_id FROM scores WHERE sample_size >= 5)
        ORDER BY dist_sq ASC LIMIT 1
    """, (lat, lat, lon, lon)).fetchone()
    
    if station:
        return get_best_model(station['id'], param, horizon)
    return "BestMatch"

Coverage growth path:

  1. Start with 4 fixed stations (Inarcs, Budapest, Ivancsa, Gyal)
  2. Route requests add new stations automatically (clustered within 5km)
  3. After weeks of usage β†’ dozens of stations with real accuracy data
  4. Eventually: dense enough coverage that any point in Hungary has a nearby scored station
  5. Optional: group into regions by county when station density is high enough

8. Future: Migration from JSON to SQLite

FUTURE Only when JSON performance becomes a bottleneck. Keep this section as a reference for when the time comes.

JSON (Phase 1)SQLite (Phase 4)Mapping
data/forecasts/*.jsonforecasts tableOne INSERT per hourly data point
data/scores.jsonscores tableStructured, queryable
data/stations.jsonstations tableDirect mapping
data/model-rankings.jsonmodel_rankings tableDirect mapping
data/route-logs/*.jsonroute_points + route_forecastsNormalized into two tables
# Migration script (one-time, ~20 lines):
import json, sqlite3, glob

db = sqlite3.connect('data/weather.db')
# ... create tables from schema above ...

# Import existing JSON snapshots
for f in glob.glob('data/forecasts/*.json'):
    data = json.loads(open(f).read())
    for model, points in data['models'].items():
        for p in points:
            db.execute("""INSERT OR IGNORE INTO forecasts 
                (city, model, issued_date, target_time, temp_c, precip_mm, ...)
                VALUES (?, ?, ?, ?, ?, ?, ...)""",
                (data['city'], model, data['date'], p['time'], p['temp'], ...))

db.commit()

9. Confidence & Minimum Data

Critical: The system must not blindly trust rankings with insufficient data.

RuleThresholdBehavior when not met
Minimum samples for rankingβ‰₯ 7 scored daysFall back to "BestMatch" / equal weight
Ranking stalenessRecalculated dailyWindow = rolling 30 days (seasonal adaptation)
Significance gapTop model must be β‰₯5% better than #2If models are within 5%, use ensemble average
Seasonal resetOptional: weight recent data more heavilyExponential decay: last 7 days count 2Γ— vs day 30

Confidence score formula:

def model_confidence(sample_size, error_gap_pct):
    """How confident are we that model A is truly better than model B?"""
    size_factor = min(sample_size / 30, 1.0)   # 0..1, full confidence at 30 samples
    gap_factor = min(error_gap_pct / 20, 1.0)  # 0..1, full confidence at 20% gap
    return size_factor * gap_factor

# If confidence < 0.5: use ensemble (average all models)
# If confidence >= 0.5: use the top-ranked model

10. Seasonal Adaptation

Models perform differently in winter vs summer. ICON might nail summer thunderstorms in Hungary but struggle with winter inversions. The rolling 30-day window handles this naturally β€” by December, summer data is gone from the window.

Optional enhancement: Keep a separate "same month last year" ranking for long-term seasonal knowledge.

-- Seasonal query: "How did models perform in August historically?"
SELECT model, AVG(error), COUNT(*)
FROM scores
WHERE city = 'inarcs' AND param = 'temp'
  AND strftime('%m', target_date) = '08'  -- August only
GROUP BY model
ORDER BY AVG(error);

11. File Structure

misc_scripts/
β”œβ”€β”€ data/
β”‚   β”œβ”€β”€ forecasts/              ← existing: daily model snapshots per city
β”‚   β”‚   β”œβ”€β”€ 2026-08-07_inarcs.json
β”‚   β”‚   └── ...
β”‚   β”œβ”€β”€ scores.json             ← existing: evaluation results (extended)
β”‚   β”œβ”€β”€ stations.json           ← NEW: fixed + route-discovered locations
β”‚   β”œβ”€β”€ model-rankings.json     ← NEW: best model per station/param/horizon
β”‚   β”œβ”€β”€ route-logs/             ← NEW: route forecast logs for feedback
β”‚   β”‚   β”œβ”€β”€ 2026-08-08_route_001.json
β”‚   β”‚   └── ...
β”‚   └── headaches.txt           ← keep as-is (human-edited)
β”œβ”€β”€ scripts/
β”‚   β”œβ”€β”€ weather-forecast/
β”‚   β”‚   └── weather-forecast.py ← reads model-rankings.json for best model
β”‚   β”œβ”€β”€ weather-history/
β”‚   β”‚   └── weather-history.py  ← unchanged
β”‚   β”œβ”€β”€ model-validator/
β”‚   β”‚   β”œβ”€β”€ save-forecast.py    ← unchanged (already saves JSON snapshots)
β”‚   β”‚   β”œβ”€β”€ evaluate.py         ← extended: scores β†’ rankings recalculation
β”‚   β”‚   β”œβ”€β”€ evaluate-routes.py  ← NEW: score pending route logs
β”‚   β”‚   └── report.py           ← reads rankings JSON for HTML report
β”‚   └── route-weather/          ← NEW: client-side app
β”œβ”€β”€ shared/
β”‚   β”œβ”€β”€ config.py
β”‚   └── model_selector.py       ← NEW: get_best_model() logic (reads JSON)
└── public_html/
    β”œβ”€β”€ route-weather.html
    β”œβ”€β”€ route-weather.js
    β”œβ”€β”€ model-rankings.json     ← deployed copy for client-side access
    └── ...

12. Route Weather Integration

For the client-side route weather planner to use adaptive model selection, we need a small "API" β€” just a static JSON file regenerated daily:

# Generated daily by evaluate.py β†’ public_html/model-rankings.json
{
  "rankings": {
    "inarcs": {
      "temp": { "short": "ICON", "medium": "ECMWF", "long": "GFS" },
      "precip": { "short": "AROME", "medium": "ICON", "long": "ECMWF" },
      "wind": { "short": "ICON", "medium": "ICON", "long": "GFS" }
    },
    "budapest": { ... },
    "regions": {
      "central_hu": ["inarcs", "budapest", "gyal"],
      "northeast_hu": ["miskolc"]  -- future expansion
    }
  },
  "updated": "2026-08-08T07:00:00"
}

The route-weather.js client reads this JSON, finds the nearest region to each waypoint, and requests weather from the ranked-best model for that parameter + horizon.

13. Implementation Phases

Phase 1 JSON-based Ranking Engine βœ… DONE

Phase 2 Route Feedback Loop βœ… DONE (server endpoint pending)

Phase 3 Adaptive Forecasting βœ… DONE (activates with data)

Phase 4 SQLite Migration (when needed)

Phase 5 Advanced (future)

14. Storage Progression

Phase 1 (now): JSON files

Phase 4 (future): SQLite

Probably never: PostgreSQL / MySQL

15. Data Volume Estimate

Base load (4 fixed cities, no route usage):

TableRows/dayRows/yearSize estimate
forecasts~2,400 (4 cities Γ— 5 models Γ— ~120 hours)~876,000~80 MB
actuals~96 (4 cities Γ— 24 hours)~35,000~3 MB
scores~560 (4 cities Γ— 5 models Γ— 7 horizons Γ— 4 params)~204,000~18 MB
model_rankings~240 (recalculated daily, small)~240 (latest only)~0.1 MB
Base total after 1 year~100 MB

With route feedback loop (assuming ~5 route requests/day, ~6 waypoints each = ~30 new points/day):

TableRows/dayRows/yearSize estimate
route_points~30~11,000~1 MB
route_forecasts~150 (30 points Γ— 5 models)~55,000~5 MB
stations (discovered)~5 new (clustered)~500 unique~0.1 MB
scores (route-sourced)~600 (30 pts Γ— 5 models Γ— 4 params)~219,000~20 MB
Route feedback after 1 year~26 MB

Heavy usage scenario (50 routes/day, popular service):

TableRows/dayRows/yearSize estimate
route_points~300~110,000~10 MB
route_forecasts~1,500~550,000~50 MB
stations~20 new~2,000 unique~0.2 MB
scores (route-sourced)~6,000~2,190,000~200 MB
Heavy route feedback after 1 year~260 MB

Worst case total: ~360 MB after 1 year of heavy usage. SQLite handles this without breaking a sweat β€” it's tested up to terabytes. Queries stay in the millisecond range with proper indexes.

Optional: prune route_forecasts older than 90 days (only aggregated scores matter long-term).

16. Quick Start β€” Minimum Viable Learning

The absolute minimum to get the self-learning loop running:

  1. Create weather.db with the schema above
  2. Modify save-forecast.py: one extra INSERT INTO forecasts call
  3. Modify evaluate.py: score into scores table + recalculate model_rankings
  4. Add 10 lines to weather-forecast.py: query model_rankings before selecting which model's data to display

That's it. The system starts learning from day 1. Confidence builds over 2-4 weeks as data accumulates.