"""Reanalyses against station records; the note's station trends. Usage: py -3.12 -I stations.py [products...] Follows RULES_stations.txt. Reads READER text files, Eureka's NOAA ISD yearly files and the station-point caches written by extract_fields.py. """ import gzip import glob import json import os import re import sys from collections import defaultdict import numpy as np sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import ppt_lib as L # noqa: E402 READER = {s: f"{s}.All.station_level_pressure.txt" for s in ["Amundsen_Scott", "Vostok", "Mirny", "Casey", "Davis", "Mawson", "Syowa", "Novolazarevskaya", "Dumont_Durville", "McMurdo", "Orcadas", "Esperanza", "Bellingshausen"]} READER["Faraday"] = "Faraday.All.msl_pressure.txt" BAD_Q = set("2367") def read_reader(path): ym, vals = [], [] for line in open(path, encoding="utf-8", errors="replace"): f = line.split() if len(f) == 13 and re.fullmatch(r"\d{4}", f[0]): for m in range(12): tok = f[m + 1] v = float(tok) if re.fullmatch(r"-?\d+(\.\d+)?", tok) else np.nan ym.append((int(f[0]), m + 1)) vals.append(v) ym = np.array(ym) return ym[:, 0], ym[:, 1], np.array(vals) def read_isd(files, min_hours): """Monthly means of station pressure (MA1) and SLP from ISD yearly files.""" hourly = {"stp": defaultdict(list), "slp": defaultdict(list)} nobs = 0 for fn in files: with gzip.open(fn, "rt", encoding="latin-1") as fh: for line in fh: nobs += 1 date, hh = line[15:23], line[23:25] key = (date, hh) slp, q = line[99:104], line[104] if slp != "99999" and q not in BAD_Q: hourly["slp"][key].append(int(slp) / 10.0) m = re.search(r"MA1(\d{5})(.)(\d{5})(.)", line[105:]) if m and m.group(3) != "99999" and m.group(4) not in BAD_Q: hourly["stp"][key].append(int(m.group(3)) / 10.0) out = {} for var, h in hourly.items(): days = defaultdict(list) for (date, hh), v in h.items(): days[date].append(np.mean(v)) months = defaultdict(list) for date, hv in days.items(): if len(hv) >= min_hours: months[(int(date[:4]), int(date[4:6]))].append(np.mean(hv)) ym = sorted(k for k, v in months.items() if len(v) >= 20) out[var] = (np.array([k[0] for k in ym]), np.array([k[1] for k in ym]), np.array([np.mean(months[k]) for k in ym])) return out, nobs def annual(years, months, vals): ok = ~np.isnan(vals) return L.annual_means(years[ok], months[ok], vals[ok]) def spans(yrs): return {"full": (int(yrs.min()), int(yrs.max())), "pre1979": (int(yrs.min()), 1978), "since1979": (1979, int(yrs.max()))} def compare(sy, sv, ry, rv): common = np.intersect1d(sy, ry) S = np.array([sv[list(sy).index(y)] for y in common]) R = np.array([rv[list(ry).index(y)] for y in common]) res = {"n_overlap": int(len(common))} if len(common) < 10: return res res["years"] = [int(common[0]), int(common[-1])] for name, (a, b) in spans(common).items(): sel = (common >= a) & (common <= b) if sel.sum() < 10: res[name] = {"n": int(sel.sum())} continue y, s, r = common[sel], S[sel], R[sel] k = s.mean() / r.mean() d = k * (r - r.mean()) - (s - s.mean()) res[name] = {"n": int(sel.sum()), "first": int(y[0]), "last": int(y[-1]), "k": float(k), "corr": float(np.corrcoef(s, r)[0, 1]), "station": L.trend(y, s), "reanalysis": L.trend(y, r), "reanalysis_scaled": L.trend(y, k * r), "drift": L.trend(y, d)} return res def main(downloads, out, products): res = {"rules": "RULES_stations.txt", "stations": {}, "note_numbers": {}} series = {} for st, fn in READER.items(): yy, mm, vv = read_reader(os.path.join(downloads, "reader", fn)) series[st] = annual(yy, mm, vv) files = sorted(glob.glob(os.path.join(downloads, "noaa-isd", "eureka", "*.gz"))) isd4, nobs = read_isd(files, 4) isd1, _ = read_isd(files, 1) series["Eureka"] = annual(*isd4["stp"]) eureka_extra = {"stp_min1hour": annual(*isd1["stp"]), "slp_min4hours": annual(*isd4["slp"])} res["eureka_isd"] = {"files": len(files), "observations": nobs} for st, (yrs, ann) in series.items(): with open(os.path.join(out, f"station_annual_{st}.csv"), "w", newline="\n") as fh: fh.write("year,annual_mean_hPa\n") for y, v in zip(yrs, ann): fh.write(f"{y},{v:.3f}\n") caches = {p: dict(np.load(os.path.join(out, "cache", p + ".npz"))) for p in products} drift_rows = [] for st, (yrs, ann) in series.items(): entry = {"valid_years": int(len(yrs)), "span": [int(yrs.min()), int(yrs.max())] if len(yrs) else None, "trend_all_years": L.trend(yrs, ann) if len(yrs) > 3 else None, "products": {}} for p, c in caches.items(): names = [str(x) for x in c["stations"]] j = names.index(st) ry, rv = L.annual_means(c["years"], c["months"], c["points"][:, j]) cmpr = compare(yrs, ann, ry, rv) entry["products"][p] = cmpr for sp in ("full", "pre1979", "since1979"): d = cmpr.get(sp, {}) if "drift" in d: drift_rows.append((st, p, sp, d["n"], d["first"], d["last"], d["station"]["slope"], d["reanalysis_scaled"]["slope"], d["drift"]["slope"], d["drift"]["lo"], d["drift"]["hi"], d["corr"])) res["stations"][st] = entry # pre-registered reading for question (a) reading = {} for p in products: for sp in ("pre1979", "since1979"): rows = [r for r in drift_rows if r[1] == p and r[2] == sp and r[0] != "Eureka"] if not rows: continue dr = np.array([r[8] for r in rows]) det = [r for r in rows if r[9] > 0 or r[10] < 0] reading[f"{p}_{sp}"] = {"stations": len(rows), "median_drift": float(np.median(dr)), "detected": len(det), "detected_negative": sum(1 for r in det if r[8] < 0), "artificial_trend_by_rule": bool(np.median(dr) < 0 and len(det) > len(rows) / 2)} res["reading"] = reading # the note's station numbers (question b) for st, spans_note in (("Eureka", [(1951, 2024), (1979, 2024)]), ("Amundsen_Scott", [(1957, 2025), (1979, 2025)])): yrs, ann = series[st] res["note_numbers"][st] = {f"{a}-{b}": L.trend_window(yrs, ann, a, b, "M1") for a, b in spans_note} for a, b in spans_note: sel = (yrs >= a) & (yrs <= b) res["note_numbers"][st][f"{a}-{b}"]["valid_years"] = int(sel.sum()) for k, (yrs, ann) in eureka_extra.items(): res["note_numbers"]["Eureka_" + k] = {f"{a}-{b}": L.trend_window(yrs, ann, a, b, "M1") for a, b in ((1951, 2024), (1979, 2024))} for a, b in ((1951, 2024), (1979, 2024)): res["note_numbers"]["Eureka_" + k][f"{a}-{b}"]["valid_years"] = int(((yrs >= a) & (yrs <= b)).sum()) with open(os.path.join(out, "station_drifts.csv"), "w", newline="\n") as fh: fh.write("station,product,span,n,first,last,station_trend,reanalysis_trend_scaled," "drift,drift_lo,drift_hi,corr\n") for r in drift_rows: fh.write(",".join([r[0], r[1], r[2], str(r[3]), str(r[4]), str(r[5])] + [f"{x:.4f}" for x in r[6:]]) + "\n") with open(os.path.join(out, "stations.json"), "w", newline="\n") as fh: json.dump(res, fh, indent=1) print(json.dumps(res["reading"], indent=1)) for k, v in res["note_numbers"].items(): print(k, {s: (round(t["slope"], 3), round(t["lo"], 3), round(t["hi"], 3), t["valid_years"]) for s, t in v.items()}) print("station,product,span,n,first,last,station,reanalysis(scaled),drift[lo,hi],corr") for r in drift_rows: print(f"{r[0]:16s} {r[1]:6s} {r[2]:9s} n={r[3]:3d} {r[4]}-{r[5]} st={r[6]:+.3f} " f"re={r[7]:+.3f} drift={r[8]:+.3f} [{r[9]:+.3f},{r[10]:+.3f}] r={r[11]:.2f}") if __name__ == "__main__": main(sys.argv[1], sys.argv[2], sys.argv[3:])