#!/usr/bin/env python3 """Stages 1 and 2 of swarma_rules.txt: the structure of SwarmA-MagSet.zip and what its labels mark. Reads the zip as data (no extraction). Writes out/swarma_structure.json and out/swarma_samples.csv. Run: python3 -I swarma_structure.py """ import csv import io import json import math import statistics import sys import zipfile from pathlib import Path sys.stdout.reconfigure(encoding="utf-8", errors="replace") LEN = 1573 POLE = (80.37, -72.62) 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)) PU = unit(*POLE) def mlat(lat, lon): u = unit(lat, lon) return math.degrees(math.asin(max(-1.0, min(1.0, PU[0] * u[0] + PU[1] * u[1] + PU[2] * u[2])))) def read_csv(zf, name): with zf.open(name) as raw: text = io.TextIOWrapper(raw, encoding="utf-8", newline="") r = csv.reader(text) header = next(r) cols = [[] for _ in header] bad = 0 n = 0 for row in r: n += 1 if len(row) != len(header): bad += 1 continue for c, v in zip(cols, row): try: c.append(float(v)) except ValueError: bad += 1 c.append(float("nan")) return header, dict(zip(header, cols)), n, bad def rms(v): return math.sqrt(sum(x * x for x in v) / len(v)) def describe_samples(d, setname, n_samples): out = [] for s in range(n_samples): a, b = s * LEN, (s + 1) * LEN lat = d["Latitude"][a:b] lon = d["Longitude"][a:b] steps = [lat[i + 1] - lat[i] for i in range(LEN - 1)] lonsteps = [((lon[i + 1] - lon[i] + 180) % 360) - 180 for i in range(LEN - 1)] rad = d["Radius"][a:b] dst = d["Dst"][a:b] kp = sorted(set(d["Kp"][a:b])) out.append( { "set": setname, "sample": s, "lat_first": lat[0], "lat_last": lat[-1], "direction": "asc" if lat[-1] > lat[0] else "desc", "lat_step_min": min(steps), "lat_step_max": max(steps), "monotonic": all(x > 0 for x in steps) or all(x < 0 for x in steps), "lon_first": lon[0], "lon_last": lon[-1], "lon_step_max": max(abs(x) for x in lonsteps), "radius_first": rad[0], "radius_last": rad[-1], "radius_mean": statistics.fmean(rad), "dst_first": dst[0], "dst_last": dst[-1], "dst_min": min(dst), "dst_max": max(dst), "kp_values": "|".join(f"{x:.3f}" for x in kp), "flags_b": "|".join(str(int(x)) for x in sorted(set(d["Flags_B"][a:b]))), "flags_f": "|".join(str(int(x)) for x in sorted(set(d["Flags_F"][a:b]))), "rms_diff_BX": rms(d["diff_res_BX"][a + 1 : b]), "rms_diff_BY": rms(d["diff_res_BY"][a + 1 : b]), "rms_diff_BZ": rms(d["diff_res_BZ"][a + 1 : b]), "rms_diff_F": rms(d["diff_res_F"][a + 1 : b]), "rms_res_BY": rms(d["res_BY"][a:b]), "max_abs_res_F": max(abs(x) for x in d["res_F"][a:b]), } ) return out def diff_check(d, n_samples): worst = {} first = {} for ch in ("BX", "BY", "BZ", "F"): r = d["res_" + ch] f = d["diff_res_" + ch] w = 0.0 ff = [] for s in range(n_samples): a, b = s * LEN, (s + 1) * LEN ff.append(f[a]) for i in range(a + 1, b): w = max(w, abs(f[i] - (r[i] - r[i - 1]))) worst[ch] = w first[ch] = {"first_row_diff_median_abs": statistics.median(abs(x) for x in ff)} return worst, first def runs(flags): out = [] i = 0 n = len(flags) while i < n: if flags[i]: j = i while j < n and flags[j]: j += 1 out.append((i, j)) i = j else: i += 1 return out def binned(vals, flags, edges): res = [] for lo, hi in zip(edges[:-1], edges[1:]): n = pos = 0 for v, f in zip(vals, flags): if lo <= v < hi: n += 1 pos += f res.append({"bin": f"{lo} to {hi}", "points": n, "labelled": pos, "share": round(pos / n, 4) if n else None}) return res def main(): zpath, outdir = sys.argv[1], Path(sys.argv[2]) outdir.mkdir(parents=True, exist_ok=True) out = {} with zipfile.ZipFile(zpath) as zf: out["zip_members"] = [{"name": i.filename, "bytes": i.file_size} for i in zf.infolist()] hdr_tr, tr, n_tr, bad_tr = read_csv(zf, "SwarmA-MagSet/train.csv") hdr_te, te, n_te, bad_te = read_csv(zf, "SwarmA-MagSet/test.csv") hdr_la, la, n_la, bad_la = read_csv(zf, "SwarmA-MagSet/label.csv") print("rows", n_tr, n_te, n_la, "bad", bad_tr, bad_te, bad_la) print("header", hdr_tr) out["rows"] = {"train": n_tr, "test": n_te, "label": n_la, "bad_fields": [bad_tr, bad_te, bad_la]} out["header"] = hdr_tr out["header_same"] = hdr_tr == hdr_te out["samples"] = {"train": n_tr / LEN, "test": n_te / LEN} ntr, nte = n_tr // LEN, n_te // LEN # Column ranges. out["ranges"] = {} for name, d in (("train", tr), ("test", te)): out["ranges"][name] = {c: [min(d[c]), max(d[c])] for c in hdr_tr} st = describe_samples(tr, "train", ntr) + describe_samples(te, "test", nte) labels = la["Label"] out["label_values"] = sorted(set(labels)) p = sum(labels) / len(labels) out["label_share"] = p print("label share", p, "values", out["label_values"]) # Samples. per = [] all_runs = [] for s in range(nte): f = [int(x) for x in labels[s * LEN : (s + 1) * LEN]] r = runs(f) per.append({"sample": s, "labelled": sum(f), "runs": len(r), "lengths": [b - a for a, b in r], "starts": [a for a, b in r]}) all_runs += [(s, a, b) for a, b in r] st_te = st[ntr:] for row, q in zip(st_te, per): row["labelled_points"] = q["labelled"] row["label_runs"] = q["runs"] row["run_lengths"] = "|".join(str(x) for x in q["lengths"]) row["run_starts"] = "|".join(str(x) for x in q["starts"]) lens = [b - a for s, a, b in all_runs] out["labels"] = { "points": len(labels), "labelled": int(sum(labels)), "share": p, "samples_with_none": sum(1 for q in per if q["labelled"] == 0), "samples_with_some": sum(1 for q in per if q["labelled"] > 0), "runs_total": len(all_runs), "runs_per_sample": sorted({q["runs"] for q in per}), "run_length_min_median_max": [min(lens), statistics.median(lens), max(lens)] if lens else None, "runs_touching_first_row": sum(1 for s, a, b in all_runs if a == 0), "runs_touching_last_row": sum(1 for s, a, b in all_runs if b == LEN), } print(json.dumps(out["labels"], indent=1)) print("run length histogram:") hist = {} for x in lens: hist[x] = hist.get(x, 0) + 1 print(sorted(hist.items())[:60]) out["run_length_hist"] = sorted(hist.items()) # Where. lat = te["Latitude"] lon = te["Longitude"] ml = [mlat(a, b) for a, b in zip(lat, lon)] fl = [int(x) for x in labels] edges = list(range(-60, 61, 10)) out["by_latitude"] = binned(lat, fl, list(range(-50, 51, 10))) out["by_mlat"] = binned(ml, fl, edges) pos = [i % LEN for i in range(len(lat))] out["by_position"] = binned(pos, fl, [int(LEN * k / 10) for k in range(11)]) dirs = [st_te[i // LEN]["direction"] == "asc" for i in range(len(lat))] out["by_direction"] = { "ascending": {"points": sum(dirs), "labelled": sum(f for f, d in zip(fl, dirs) if d)}, "descending": {"points": len(dirs) - sum(dirs), "labelled": sum(f for f, d in zip(fl, dirs) if not d)}, } # Consistency. w_tr, f_tr = diff_check(tr, ntr) w_te, f_te = diff_check(te, nte) out["diff_is_res_difference_worst_abs_error"] = {"train": w_tr, "test": w_te} out["first_row_diff"] = {"train": f_tr, "test": f_te} # Summary of blocks. out["blocks"] = {} for name, rows in (("train", st[:ntr]), ("test", st[ntr:])): out["blocks"][name] = { "n": len(rows), "all_monotonic": all(r["monotonic"] for r in rows), "asc": sum(r["direction"] == "asc" for r in rows), "desc": sum(r["direction"] == "desc" for r in rows), "lat_first_range": [min(r["lat_first"] for r in rows), max(r["lat_first"] for r in rows)], "lat_last_range": [min(r["lat_last"] for r in rows), max(r["lat_last"] for r in rows)], "abs_lat_step_range": [min(min(abs(r["lat_step_min"]), abs(r["lat_step_max"])) for r in rows), max(max(abs(r["lat_step_min"]), abs(r["lat_step_max"])) for r in rows)], "lon_step_max": max(r["lon_step_max"] for r in rows), "radius_mean_range": [min(r["radius_mean"] for r in rows), max(r["radius_mean"] for r in rows)], "dst_range": [min(r["dst_min"] for r in rows), max(r["dst_max"] for r in rows)], "kp_values": sorted({float(x) for r in rows for x in r["kp_values"].split("|")}), "flags_b": sorted({r["flags_b"] for r in rows}), "flags_f": sorted({r["flags_f"] for r in rows}), "rms_diff_BY_median": statistics.median(r["rms_diff_BY"] for r in rows), "rms_diff_BY_range": [min(r["rms_diff_BY"] for r in rows), max(r["rms_diff_BY"] for r in rows)], } print(json.dumps(out["blocks"], indent=1)) print(json.dumps(out["by_latitude"])) print(json.dumps(out["by_mlat"])) print(json.dumps(out["by_position"])) print(json.dumps(out["by_direction"])) print(json.dumps(out["diff_is_res_difference_worst_abs_error"])) with open(outdir / "swarma_structure.json", "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, ensure_ascii=False, indent=1) fields = list(st_te[0].keys()) with open(outdir / "swarma_samples.csv", "w", encoding="utf-8", newline="\n") as f: w = csv.DictWriter(f, fieldnames=fields, lineterminator="\n", extrasaction="ignore") w.writeheader() for row in st: w.writerow(row) if __name__ == "__main__": main()