#!/usr/bin/env python3 """RULES_D_japan_weather.txt and RULES_F_regional_thunderstorms.txt: METAR screens from the Iowa Environmental Mesonet. Usage: python3 -I df_weather.py IEM_DIR OUT_DIR Standard library only. Reads the IEM CSV files as data. Writes OUT_DIR/D_japan_weather.json and OUT_DIR/F_regional_ts.json. """ import csv import json import math import os import re import sys from collections import defaultdict sys.stdout.reconfigure(encoding="utf-8") IEM, OUT = sys.argv[1], sys.argv[2] BAD_WX = re.compile(r"(RA|DZ|SN|SG|SH|TS|GR|GS|PL|IC|UP|FG|BR|HZ|FU|DU|SA|VA)") def rows(path): with open(path, encoding="utf-8", errors="replace", newline="") as f: lines = [l for l in f if not l.startswith("#")] rd = csv.DictReader(lines) seen = set() for r in rd: key = (r["station"], r["valid"]) if key in seen: continue seen.add(key) yield r def fnum(x): try: return float(x) except (TypeError, ValueError): return None def rh(t, td): if t is None or td is None: return None a, b = 17.625, 243.04 return 100 * math.exp(a * td / (b + td)) / math.exp(a * t / (b + t)) def judge(r): wx = (r.get("wxcodes") or "").strip() wx = "" if wx == "M" else wx metar = r.get("metar") or "" body = metar.split(" RMK")[0] a = not BAD_WX.search(wx) vis_mi = fnum(r.get("vsby")) a2 = vis_mi is not None and vis_mi * 1.609344 >= 2.0 cb = bool(re.search(r"\b(FEW|SCT|BKN|OVC|///)(\d{3}|///)(CB|TCU)\b", body)) low = False lowfewsct = False for i in range(1, 5): c = (r.get(f"skyc{i}") or "").strip() h = fnum(r.get(f"skyl{i}")) if c in ("BKN", "OVC", "VV") and h is not None and h < 5000: low = True if c == "VV": low = True if c in ("FEW", "SCT") and h is not None and h < 5000: lowfewsct = True b = (not cb) and (not low) kt = fnum(r.get("sknt")) c_ok = kt is not None and 1.0 <= kt * 0.5144 <= 8.0 t, td = fnum(r.get("tmpc")), fnum(r.get("dwpc")) return {"a": a, "a2": a2, "b": b, "c": c_ok, "fair": a and a2 and b and c_ok, "cb": cb, "low": low, "lowfewsct": lowfewsct, "rh": rh(t, td), "vis_km": min(10.0, vis_mi * 1.609344) if vis_mi is not None else None, "wind_ms": kt * 0.5144 if kt is not None else None, "wx": wx} # ---------------- D ---------------- D = {} for st in ("RJTF", "RJAH", "RJTY", "RJAK"): p = os.path.join(IEM, "japan", f"{st}_202405.csv") per = defaultdict(list) for r in rows(p): day = r["valid"][:10] per[day].append(judge(r)) out = {} for day in sorted(per): js = per[day] n = len(js) rhs = [j["rh"] for j in js if j["rh"] is not None] vis = [j["vis_km"] for j in js if j["vis_km"] is not None] wnd = [j["wind_ms"] for j in js if j["wind_ms"] is not None] out[day] = {"n": n, "fair": sum(j["fair"] for j in js), "fair_frac": round(sum(j["fair"] for j in js) / n, 3), "fail_wx": sum(not j["a"] for j in js), "fail_vis": sum(not j["a2"] for j in js), "fail_cloud": sum(not j["b"] for j in js), "fail_wind": sum(not j["c"] for j in js), "rh_mean": round(sum(rhs) / len(rhs), 1) if rhs else None, "rh_ge90": sum(1 for x in rhs if x >= 90), "vis_mean_km": round(sum(vis) / len(vis), 1) if vis else None, "wind_max_ms": round(max(wnd), 1) if wnd else None, "low_few_sct": sum(j["lowfewsct"] for j in js), "wx_codes": sorted(set(j["wx"] for j in js if j["wx"]))} D[st] = out dec = {} for site, st in (("CHF", "RJTF"), ("KAK", "RJAH"), ("CHF_secondary", "RJTY"), ("KAK_secondary", "RJAK")): o = D[st] if all(d in o for d in ("2024-05-09", "2024-05-10", "2024-05-11")): f9, f10, f11 = o["2024-05-09"]["fair_frac"], o["2024-05-10"]["fair_frac"], o["2024-05-11"]["fair_frac"] diff = f11 - (f9 + f10) / 2 dec[site] = {"station": st, "f9": f9, "f10": f10, "f11": f11, "f12": o.get("2024-05-12", {}).get("fair_frac"), "diff_11_vs_9_10": round(diff, 3), "decision": "weather differed" if abs(diff) >= 0.25 else "reports do not separate the days"} else: dec[site] = {"station": st, "decision": "missing days"} json.dump({"per_day": D, "decision": dec}, open(os.path.join(OUT, "D_japan_weather.json"), "w", encoding="utf-8", newline="\n"), indent=1) print("D decision:", json.dumps(dec, indent=1)) for st in ("RJTF", "RJAH"): for day in ("2024-05-08", "2024-05-09", "2024-05-10", "2024-05-11", "2024-05-12", "2024-05-13"): print(st, day, D[st].get(day)) # ---------------- F ---------------- F = {"stations": {}, "per_day": {}} STS = ["VECC", "VGHS", "VEDO", "VEJS", "VEAT", "VEKO", "VEDG", "VERC", "VECO", "VGEG", "VEBD", "VEHX", "VEGY", "VELP", "VEBI", "VEGT", "VEPT", "VEBS", "VEKU", "VEJH"] ts_by_day = defaultdict(set) tsrep_by_day = defaultdict(int) hours_11 = defaultdict(set) for st in STS: p = os.path.join(IEM, "india", f"{st}_202404_05.csv") n = 0 for r in rows(p): n += 1 wx = (r.get("wxcodes") or "") day = r["valid"][:10] if "TS" in wx: ts_by_day[day].add(st) tsrep_by_day[day] += 1 if day == "2024-05-11": hours_11[st].add(r["valid"][11:13]) F["stations"][st] = n days = [] import datetime as _dt # noqa: E402 d0 = _dt.date(2024, 4, 1) for i in range(61): d = (d0 + _dt.timedelta(days=i)).isoformat() days.append((d, len(ts_by_day.get(d, ())), tsrep_by_day.get(d, 0))) F["per_day"] = {d: {"ts_stations": n, "ts_reports": k} for d, n, k in days} c11 = F["per_day"]["2024-05-11"]["ts_stations"] better_or_equal = sum(1 for d, n, _ in days if d != "2024-05-11" and n >= c11) rank = 1 + sum(1 for d, n, _ in days if d != "2024-05-11" and n > c11) ref = [F["per_day"][d]["ts_stations"] for d in [f"2024-05-{x:02d}" for x in list(range(3, 10)) + list(range(13, 20))]] F["summary"] = {"ts_stations_11May": c11, "other_days_with_ge": better_or_equal, "rank_11May_of_61": rank, "ref_days_mean": round(sum(ref) / len(ref), 2), "ref_days": ref, "decision": ("within the range of ordinary pre-monsoon days" if better_or_equal >= 5 else ("most thunderous day of the two months" if rank == 1 and better_or_equal == 0 else "among the more thunderous days")), "hours_UT_with_TS_on_11May": {k: sorted(v) for k, v in hours_11.items()}, "stations_with_no_reports": [s for s, n in F["stations"].items() if n == 0]} json.dump(F, open(os.path.join(OUT, "F_regional_ts.json"), "w", encoding="utf-8", newline="\n"), indent=1) print("F summary:", json.dumps(F["summary"], indent=1)) print("3-19 May:", [(d[5:], F["per_day"][d]["ts_stations"], F["per_day"][d]["ts_reports"]) for d in sorted(F["per_day"]) if "2024-05-03" <= d <= "2024-05-19"]) print("all days sorted by ts_stations:", sorted(((v["ts_stations"], d) for d, v in F["per_day"].items()), reverse=True)[:15])