#!/usr/bin/env python3 """Fetch CHAIN's public ISMR files for the windows in RULES_before_running.txt, by URL, with curl. Usage: python3 -I fetch_chain.py RAW_DIR --quiet-list quiet-files-read.txt the files our run read: 13 storm windows, 9-11 April python3 -I fetch_chain.py RAW_DIR what the rules first named: 13 storm windows, 9-15 April Options: --quiet-list FILE fetch only the quiet-week files named in FILE (one file name per line) --budget SECONDS exit cleanly after the batch in progress once this time has passed; run again to go on --batch N files per curl call (default 20) --stations a,b,c this run only, these three-letter stations, for when the link is slow It uses a plain client name, one connection at a time and at most about 100 requests a minute, and stops at the first 403 or 429. It writes RAW_DIR/fetch_log.tsv (url, http code, bytes, UT time) and resumes from it. About 4,400 files, 257 MB, over an hour or more. CHAIN's terms bar redistribution of its data without written agreement, so keep what this fetches to yourself: http://chain.physics.unb.ca/chain/pages/rules """ import argparse import datetime as dt import os import subprocess import sys import time UA = "factchecked-research/1.0" BASE = "http://chain.physics.unb.ca/data/gps/ismr" STATIONS = "arc arv chu daw edm eur fsi fsm gjo kug mcm rab ran rep sac".split() ANCHORS = ["2015-03-17 22", "2015-06-23 04", "2015-12-20 22", "2018-08-26 07", "2023-03-24 02", "2023-04-24 05", "2023-11-05 19", "2024-05-11 02", "2024-08-12 16", "2024-10-11 01", "2025-01-01 15", "2025-11-12 04", "2026-01-20 16"] QUIET_TAG = "quiet_2024-04-09_15" def hours(): """Yield (window tag, datetime of the hour): May 2024 first, then the other storms, then the quiet week.""" order = ["2024-05-11 02"] + [a for a in ANCHORS if a != "2024-05-11 02"] for a in order: t0 = dt.datetime.strptime(a, "%Y-%m-%d %H") - dt.timedelta(hours=10) tag = "storm_" + a[:10] for i in range(24): yield tag, t0 + dt.timedelta(hours=i) d0 = dt.datetime(2024, 4, 9) for i in range(7 * 8): yield QUIET_TAG, d0 + dt.timedelta(hours=3 * i) def url_and_path(raw, tag, t, st): doy = t.timetuple().tm_yday name = f"{st}c{t:%y}{doy:03d}{chr(97 + t.hour)}.ismr.gz" return f"{BASE}/{t:%Y}/{doy:03d}/{t:%H}/{name}", os.path.join(raw, tag, name), name def main(): ap = argparse.ArgumentParser(description="Fetch CHAIN's public ISMR files by URL.") ap.add_argument("raw") ap.add_argument("--quiet-list") ap.add_argument("--budget", type=float) ap.add_argument("--batch", type=int, default=20) ap.add_argument("--stations") a = ap.parse_args() raw = a.raw started = time.time() only = set(a.stations.split(",")) if a.stations else None quiet_names = None if a.quiet_list: with open(a.quiet_list, encoding="utf-8") as f: quiet_names = {line.strip() for line in f if line.strip()} os.makedirs(raw, exist_ok=True) log = os.path.join(raw, "fetch_log.tsv") done = {} if os.path.exists(log): for line in open(log, encoding="utf-8"): p = line.rstrip("\n").split("\t") if len(p) >= 2: done[p[0]] = p[1] jobs = [] for tag, t in hours(): for st in STATIONS: if only and st not in only: continue u, p, name = url_and_path(raw, tag, t, st) if tag == QUIET_TAG and quiet_names is not None and name not in quiet_names: continue if done.get(u) in ("200", "404"): continue jobs.append((u, p)) print(len(jobs), "files to try", flush=True) cfg = os.path.join(raw, "_batch.cfg") trouble = 0 size = a.batch for k in range(0, len(jobs), size): batch = jobs[k:k + size] with open(cfg, "w", encoding="utf-8", newline="\n") as f: for u, p in batch: os.makedirs(os.path.dirname(p), exist_ok=True) f.write('url = "%s"\noutput = "%s"\n' % (u, p.replace(chr(92), "/"))) r = subprocess.run(["curl", "-L", "-sS", "-f", "-A", UA, "--rate", "100/m", "--max-time", "120", "-K", cfg, "-w", "%{http_code}\t%{size_download}\t%{url_effective}\n"], capture_output=True, text=True) stamp = f"{dt.datetime.now(dt.timezone.utc):%Y-%m-%d %H:%M:%S}" codes = [] with open(log, "a", encoding="utf-8", newline="\n") as f: for line in r.stdout.splitlines(): p = line.split("\t") if len(p) == 3: f.write(f"{p[2]}\t{p[0]}\t{p[1]}\t{stamp}\n") codes.append(p[0]) print(stamp, k + len(batch), "of", len(jobs), {c: codes.count(c) for c in set(codes)}, flush=True) if "403" in codes or "429" in codes: print("REFUSED: stopping, as the rules say", flush=True) sys.exit(3) bad = sum(c not in ("200", "404") for c in codes) + (len(batch) - len(codes)) trouble = trouble + 1 if bad > size // 2 else 0 if trouble >= 3: print("Too many failures in a row: stopping", flush=True) sys.exit(4) if a.budget is not None and time.time() - started > a.budget and k + size < len(jobs): print("budget used; run again to go on", flush=True) return print("finished", flush=True) if __name__ == "__main__": main()