#!/usr/bin/env python3 """Rule A13 of swarma_rules.txt: how far does the earthquake comparison reach? Added after a fresh review of the page. The test keeps every test point where it is, labelled or not, and slides USGS's catalogue to other dates. That keeps the geography (labels may fall in more or less active places) and breaks any link in time. The real gap between labelled and unlabelled points is then set against the same gap at 300 other dates. Settings are illustrative, not the paper's, whose earthquake sections could not be read. Standard library only. Observed values: every row, with limits from resampling the 100 test passes (2,000 draws). Other dates: every fifth row, as swarma_catalogue.py does for its point shares. A pass counts as one moment, its middle row: a pass lasts 26 minutes and the windows run to 90 days. Run: python3 -I swarma_shift_test.py Reads swarma_samples_dated.csv from the out folder. Writes swarma_shift_test.json there. """ import bisect import csv import io import json import math import random import statistics import sys import zipfile from datetime import datetime from pathlib import Path sys.stdout.reconfigure(encoding="utf-8", errors="replace") LEN = 1573 RE = 6371.0 SEED = 20261102 REC0 = datetime(2014, 1, 1) NDAY = (datetime(2026, 1, 1) - REC0).days N_DATES = 300 BOOT = 2000 SKETCH = 197 # rows between the sketch points of a pass, about 12.5 degrees SETTINGS = ( ("M >= 5.5, depth < 50 km, due within 30 days", "shallow", 1, 0, 30), ("M >= 5.5, depth < 50 km, due within 60 days", "shallow", 1, 0, 60), ("M >= 5.5, depth < 50 km, due within 90 days", "shallow", 1, 0, 90), ("M >= 5.5, any depth, due within 60 days", "any", 1, 0, 60), ("M >= 5.5, any depth, due within 90 days", "any", 1, 0, 90), ("M >= 5.5, depth < 50 km, twice the radius, due within 90 days", "shallow", 2, 0, 90), ("M >= 5.5, depth < 50 km, within the 90 days just past", "shallow", 1, -90, 0), ) def unit(lat, lon): a, b = math.radians(lat), math.radians(lon) return (math.cos(a) * math.cos(b), math.cos(a) * math.sin(b), math.sin(a)) def read_csv(zf, name, want): with zf.open(name) as raw: r = csv.reader(io.TextIOWrapper(raw, encoding="utf-8", newline="")) h = next(r) ii = [h.index(w) for w in want] cols = [[] for _ in want] for row in r: for c, i in zip(cols, ii): c.append(float(row[i])) return cols def load_events(folder): ev = [] seen = set() for p in sorted(Path(folder).glob("usgs-m5-*.csv")): for r in csv.DictReader(open(p, encoding="utf-8", newline="")): if r["type"] != "earthquake" or r["id"] in seen: continue seen.add(r["id"]) m = float(r["mag"]) if m < 5.5: continue t = datetime.strptime(r["time"][:19], "%Y-%m-%dT%H:%M:%S") rho = 10 ** (0.43 * m) / RE ev.append(((t - REC0).total_seconds() / 86400, float(r["depth"] or 0), unit(float(r["latitude"]), float(r["longitude"])), rho)) ev.sort(key=lambda e: e[0]) return ev class Passes: """The test passes at a given stride, with each event's reach as one integer of bits per pass.""" def __init__(self, units, y, step): self.n = len(y) // LEN self.idx = [[i for i in range(p * LEN, (p + 1) * LEN) if i % step == 0] for p in range(self.n)] self.u = [[units[i] for i in ids] for ids in self.idx] self.lab = [sum(1 << k for k, i in enumerate(ids) if y[i]) for ids in self.idx] self.full = [(1 << len(ids)) - 1 for ids in self.idx] self.sketch = [[units[p * LEN + k] for k in range(SKETCH // 2, LEN, SKETCH)] for p in range(self.n)] self.halfgap = math.radians(SKETCH * 0.0635 / 2 + 0.2) def reach(self, ev): """For one event: [(pass, bits inside the radius, bits inside twice the radius)], for the passes it touches.""" (ex, ey, ez), rho = ev[2], ev[3] c1 = math.cos(min(rho, math.pi)) c2 = math.cos(min(2 * rho, math.pi)) cs = math.cos(min(2 * rho + self.halfgap, math.pi)) out = [] for p in range(self.n): if not any(a * ex + b * ey + c * ez >= cs for a, b, c in self.sketch[p]): continue m1 = m2 = 0 for k, (a, b, c) in enumerate(self.u[p]): d = a * ex + b * ey + c * ez if d >= c2: m2 |= 1 << k if d >= c1: m1 |= 1 << k if m2: out.append((p, m1, m2)) return out def hits(cells, ev_t, ev_dep, tp, setting, offset): """Bits of each pass inside a zone, for the catalogue slid so that the passes sit at tp + offset.""" _, depth, mul, lo, hi = setting t = [x + offset for x in tp] a = bisect.bisect_right(ev_t, min(t) + lo) b = bisect.bisect_right(ev_t, max(t) + hi) out = [0] * len(tp) for e in range(a, b): if depth == "shallow" and ev_dep[e] >= 50: continue te = ev_t[e] for p, m1, m2 in cells[e]: if lo < te - t[p] <= hi: out[p] |= m1 if mul == 1 else m2 return out def shares(hit, pa): a = sum((h & l).bit_count() for h, l in zip(hit, pa.lab)) A = sum(l.bit_count() for l in pa.lab) b = sum((h & (f ^ l)).bit_count() for h, f, l in zip(hit, pa.full, pa.lab)) B = sum((f ^ l).bit_count() for f, l in zip(pa.full, pa.lab)) return a / A, b / B def main(): zpath, usgs, outdir = sys.argv[1], sys.argv[2], Path(sys.argv[3]) with zipfile.ZipFile(zpath) as zf: lat, lon = read_csv(zf, "SwarmA-MagSet/test.csv", ["Latitude", "Longitude"]) y = [int(v) for v in read_csv(zf, "SwarmA-MagSet/label.csv", ["Label"])[0]] units = [unit(a, b) for a, b in zip(lat, lon)] dated = [r for r in csv.DictReader(open(outdir / "swarma_samples_dated.csv", encoding="utf-8", newline="")) if r["set"] == "test"] tp = [(datetime.strptime(r["t_first_row_utc"], "%Y-%m-%dT%H:%M:%S") - REC0).total_seconds() / 86400 + (LEN // 2) / 86400 for r in dated] ev = load_events(usgs) ev_t = [e[0] for e in ev] ev_dep = [e[1] for e in ev] print("M >= 5.5 events, any depth:", len(ev), flush=True) # Every row, at the real dates. every = Passes(units, y, 1) t0, t1 = min(tp), max(tp) near = {e: every.reach(ev[e]) for e in range(bisect.bisect_right(ev_t, t0 - 91), bisect.bisect_right(ev_t, t1 + 91))} cells_all = {e: near.get(e, ()) for e in range(len(ev))} # The labelled runs, split at the joins between samples. runs = [] for p in range(every.n): i = 0 while i < LEN: if y[p * LEN + i]: j = i while j < LEN and y[p * LEN + j]: j += 1 runs.append((p, sum(1 << k for k in range(i, j)))) i = j else: i += 1 out = {"note": "Our analysis, added after a fresh review (rule A13). Illustrative settings, not the paper's.", "labelled_runs": len(runs), "settings": {}} rng = random.Random(SEED) observed = {} for s in SETTINGS: h = hits(cells_all, ev_t, ev_dep, tp, s, 0.0) la, un = shares(h, every) per = [((x & l).bit_count(), l.bit_count(), (x & (f ^ l)).bit_count(), (f ^ l).bit_count()) for x, l, f in zip(h, every.lab, every.full)] gaps = [] for _ in range(BOOT): a = A = b = B = 0 for _ in range(every.n): q = per[rng.randrange(every.n)] a += q[0] A += q[1] b += q[2] B += q[3] gaps.append(a / A - b / B) gaps.sort() touched = sum(1 for p, m in runs if h[p] & m) observed[s[0]] = { "labelled_pct_all_rows": round(100 * la, 2), "unlabelled_pct_all_rows": round(100 * un, 2), "gap_points_all_rows": round(100 * (la - un), 2), "gap_95pct_limits_by_pass": [round(100 * gaps[int(0.025 * BOOT)], 2), round(100 * gaps[int(0.975 * BOOT)], 2)], "labelled_runs_touching_a_zone": touched, } print(s[0], observed[s[0]], flush=True) # Every fifth row, at other dates. fifth = Passes(units, y, 5) cells = {} for e in range(len(ev)): cells[e] = fifth.reach(ev[e]) print("reach of each event worked out", flush=True) margin = 91 + 1 lo_o = -t0 + margin hi_o = NDAY - t1 - margin span = t1 - t0 rng = random.Random(SEED + 13) offs = [] while len(offs) < N_DATES: o = float(rng.randrange(int(lo_o), int(hi_o))) if abs(o) > 2 * margin + span: offs.append(o) for s in SETTINGS: la0, un0 = shares(hits(cells, ev_t, ev_dep, tp, s, 0.0), fifth) gap0 = la0 - un0 vals = [] for o in offs: la, un = shares(hits(cells, ev_t, ev_dep, tp, s, o), fifth) vals.append(la - un) vals_sorted = sorted(vals) unl = [shares(hits(cells, ev_t, ev_dep, tp, s, o), fifth)[1] for o in offs[:50]] res = dict(observed[s[0]]) res.update( { "labelled_pct_every_fifth_row": round(100 * la0, 2), "unlabelled_pct_every_fifth_row": round(100 * un0, 2), "gap_points_every_fifth_row": round(100 * gap0, 2), "other_dates": N_DATES, "other_dates_gap_mean": round(100 * statistics.fmean(vals), 2), "other_dates_gap_sd": round(100 * statistics.pstdev(vals), 2), "other_dates_gap_90th_95th_975th_percentile": [round(100 * vals_sorted[int(q * N_DATES)], 2) for q in (0.90, 0.95, 0.975)], "share_of_other_dates_with_gap_at_least_the_real_one": round(sum(1 for v in vals if v >= gap0) / N_DATES, 3), "share_of_other_dates_with_gap_at_least_the_unlabelled_share": round(sum(1 for v in vals if v >= un0) / N_DATES, 3), "other_dates_unlabelled_pct_mean_of_50": round(100 * statistics.fmean(unl), 2), } ) out["settings"][s[0]] = res print(s[0], json.dumps(res), flush=True) with open(outdir / "swarma_shift_test.json", "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, ensure_ascii=False, indent=1) f.write("\n") if __name__ == "__main__": main()