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.
Approach: Start with JSON files (extend current system), migrate to SQLite when complexity demands it.
| Phase | Storage | When | Why |
|---|---|---|---|
| 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 |
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": [
{
"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"
}
]
}
{
"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": { ... }
}
}
{
"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.
| Status | Component | Where |
|---|---|---|
| β Done | Route planner fetches all models, stores predictions | Browser (localStorage) |
| β Done | evaluate-routes.py scores route logs against actuals | Server (cron) |
| β Missing | Getting route logs FROM browser TO server | The gap |
Resolution (pick one when web hosting is active):
data/route-logs/. Simplest once tarhely.com is live.Until this gap is closed, the fixed 4 cities learn normally (server-side pipeline is complete), but route-discovered stations won't accumulate.
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):
-- 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);
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.
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;
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;
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
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.
-- 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);
| Day | Coverage | How |
|---|---|---|
| Day 1 | 4 fixed cities | Original setup |
| Day 2 | 4 + 3 route points | User drove BudapestβMiskolc |
| Day 5 | 4 + 12 route points | More routes requested |
| Day 30 | 4 + 80+ unique areas | Organic growth |
| Day 90 | Dense coverage of Hungary | Repeated routes build confidence |
Same coordinate requested multiple times = higher confidence ranking for that area.
-- 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
);
// 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.
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()
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"
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/*.json | forecasts table | One INSERT per hourly data point |
data/scores.json | scores table | Structured, queryable |
data/stations.json | stations table | Direct mapping |
data/model-rankings.json | model_rankings table | Direct mapping |
data/route-logs/*.json | route_points + route_forecasts | Normalized 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()
Critical: The system must not blindly trust rankings with insufficient data.
| Rule | Threshold | Behavior when not met |
|---|---|---|
| Minimum samples for ranking | β₯ 7 scored days | Fall back to "BestMatch" / equal weight |
| Ranking staleness | Recalculated daily | Window = rolling 30 days (seasonal adaptation) |
| Significance gap | Top model must be β₯5% better than #2 | If models are within 5%, use ensemble average |
| Seasonal reset | Optional: weight recent data more heavily | Exponential decay: last 7 days count 2Γ vs day 30 |
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
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);
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
βββ ...
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.
data/stations.json with the 4 fixed citiesevaluate.py to write scores per model/city/param/horizonshared/model_selector.py β reads scores.json, calculates rankings, writes model-rankings.jsonmodel-rankings.json to public_html for client-side route weatherevaluate-routes.py scores pending route logs against actualsstations.json with source: "route"weather-forecast.py to use get_best_model() β will wire when rankings have data (~Aug 14+)shared/db.py with schema + connection helperPhase 1 (now): JSON files
json module handles everythingPhase 4 (future): SQLite
.db file on diskimport sqlite3) β no new dependenciesProbably never: PostgreSQL / MySQL
Base load (4 fixed cities, no route usage):
| Table | Rows/day | Rows/year | Size 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):
| Table | Rows/day | Rows/year | Size 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):
| Table | Rows/day | Rows/year | Size 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).
The absolute minimum to get the self-learning loop running:
weather.db with the schema abovesave-forecast.py: one extra INSERT INTO forecasts callevaluate.py: score into scores table + recalculate model_rankingsweather-forecast.py: query model_rankings before selecting which model's data to displayThat's it. The system starts learning from day 1. Confidence builds over 2-4 weeks as data accumulates.