"""Read CODE IONEX files and compute geomagnetic-band mean VTEC, as note 002's Methods describe. Pure Python (no numpy on this machine). Downloads are read as data only: .Z files are unpacked with `gzip -dc` (gzip reads Unix-compress LZW), .gz with Python's gzip. """ import gzip import math import subprocess import datetime as dt # ---------------------------------------------------------------- IONEX reading def read_bytes(path): if path.endswith(".Z"): p = subprocess.run(["gzip", "-dc", path], capture_output=True) if p.returncode != 0: raise IOError("gzip failed on %s: %s" % (path, p.stderr[:200])) return p.stdout if path.endswith(".gz"): with gzip.open(path, "rb") as f: return f.read() with open(path, "rb") as f: return f.read() def parse_ionex(path): """Return dict with lats, lons, exponent, maps: list of (datetime, grid) where grid[i][j] is VTEC in TECU (None for 9999) at lats[i], lons[j]. TEC maps only.""" text = read_bytes(path).decode("ascii", errors="replace") lines = text.splitlines() hdr = {} i = 0 while i < len(lines): ln = lines[i] label = ln[60:].strip() if label == "END OF HEADER": i += 1 break if label == "EXPONENT": hdr["exponent"] = int(ln[:6]) elif label == "LAT1 / LAT2 / DLAT": a = ln[:60].split() hdr["lat"] = tuple(float(x) for x in a[:3]) elif label == "LON1 / LON2 / DLON": a = ln[:60].split() hdr["lon"] = tuple(float(x) for x in a[:3]) elif label == "INTERVAL": hdr["interval"] = int(float(ln[:6])) elif label == "# OF MAPS IN FILE": hdr["nmaps"] = int(ln[:6]) elif label == "EPOCH OF FIRST MAP": hdr["first"] = [int(x) for x in ln[:60].split()[:6]] i += 1 exp = hdr.get("exponent", -1) scale = 10.0 ** exp lat1, lat2, dlat = hdr["lat"] lon1, lon2, dlon = hdr["lon"] nlat = int(round((lat2 - lat1) / dlat)) + 1 nlon = int(round((lon2 - lon1) / dlon)) + 1 lats = [lat1 + k * dlat for k in range(nlat)] lons = [lon1 + k * dlon for k in range(nlon)] maps = [] in_tec = False epoch = None grid = None row = None vals = [] while i < len(lines): ln = lines[i] label = ln[60:].strip() if label == "START OF TEC MAP": in_tec = True grid = [[None] * nlon for _ in range(nlat)] row = None elif label.startswith("START OF RMS MAP") or label.startswith("START OF HEIGHT MAP"): in_tec = False elif in_tec and label == "EPOCH OF CURRENT MAP": y, mo, d, h, mi, s = [int(x) for x in ln[:60].split()[:6]] epoch = dt.datetime(y, mo, d) + dt.timedelta(hours=h, minutes=mi, seconds=s) elif in_tec and label == "LAT/LON1/LON2/DLON/H": # flush previous row if row is not None: grid[row] = [None if v == 9999 else v * scale for v in vals[:nlon]] lat = float(ln[2:8]) row = int(round((lat - lat1) / dlat)) vals = [] elif in_tec and label == "END OF TEC MAP": if row is not None: grid[row] = [None if v == 9999 else v * scale for v in vals[:nlon]] maps.append((epoch, grid)) in_tec = False row = None elif in_tec and row is not None: s = ln.rstrip() # values are I5, up to 16 per line for k in range(0, len(s), 5): chunk = s[k:k + 5].strip() if chunk: vals.append(int(chunk)) elif label == "END OF FILE": break i += 1 return {"lats": lats, "lons": lons, "exponent": exp, "maps": maps, "hdr": hdr} # ---------------------------------------------------------------- IGRF-14 dipole def load_igrf_dipole(path): """Return (epochs, g10, g11, h11, sv) from igrf14coeffs.txt.""" epochs = None rows = {} with open(path, encoding="utf-8") as f: for ln in f: if ln.startswith("g/h"): parts = ln.split() epochs = [float(x) for x in parts[3:-1]] parts = ln.split() if len(parts) > 4 and parts[0] in ("g", "h") and parts[1] == "1": key = parts[0] + parts[1] + parts[2] rows[key] = [float(x) for x in parts[3:]] return epochs, rows def dipole_coeffs(year_frac, igrf): epochs, rows = igrf out = {} for key in ("g10", "g11", "h11"): vals = rows[key] main, sv = vals[:-1], vals[-1] if year_frac >= epochs[-1]: out[key] = main[-1] + sv * (year_frac - epochs[-1]) else: k = max(i for i in range(len(epochs)) if epochs[i] <= year_frac) f = (year_frac - epochs[k]) / (epochs[k + 1] - epochs[k]) out[key] = main[k] + f * (main[k + 1] - main[k]) return out def dipole_pole(year_frac, igrf): c = dipole_coeffs(year_frac, igrf) g10, g11, h11 = c["g10"], c["g11"], c["h11"] b0 = math.sqrt(g10 * g10 + g11 * g11 + h11 * h11) theta = math.acos(-g10 / b0) # colatitude of the boreal geomagnetic pole phi = math.atan2(-h11, -g11) # its east longitude return 90.0 - math.degrees(theta), math.degrees(phi) def mag_lat(lat, lon, pole_lat, pole_lon): a = math.radians(lat) pl = math.radians(pole_lat) s = math.sin(a) * math.sin(pl) + math.cos(a) * math.cos(pl) * math.cos(math.radians(lon - pole_lon)) return math.degrees(math.asin(max(-1.0, min(1.0, s)))) def year_fraction(t): y0 = dt.datetime(t.year, 1, 1) y1 = dt.datetime(t.year + 1, 1, 1) return t.year + (t - y0).total_seconds() / (y1 - y0).total_seconds() # ---------------------------------------------------------------- bands BANDS = (30, 50, 70) def band_masks(lats, lons, pole_lat, pole_lon, half_width=2.5, drop_lon_dup=True): """For each band key ('N50', 'S50', ...) list of (i, j, weight).""" jmax = len(lons) if drop_lon_dup and abs((lons[-1] - lons[0]) - 360.0) < 1e-6: jmax -= 1 # -180 and +180 are the same meridian masks = {} for c in BANDS: for hemi, sign in (("N", 1), ("S", -1)): pts = [] for i, la in enumerate(lats): w = math.cos(math.radians(la)) for j in range(jmax): m = mag_lat(la, lons[j], pole_lat, pole_lon) if abs(m - sign * c) <= half_width: pts.append((i, j, w)) masks["%s%d" % (hemi, c)] = pts return masks def band_means(grid, masks): out = {} for key, pts in masks.items(): sw = 0.0 sv = 0.0 for i, j, w in pts: v = grid[i][j] if v is None: continue sw += w sv += w * v out[key] = sv / sw if sw > 0 else None for c in BANDS: n, s = out.get("N%d" % c), out.get("S%d" % c) out["NS%d" % c] = None if (n is None or s is None) else 0.5 * (n + s) return out def bilinear(grid, lats, lons, lat, lon): """Bilinear interpolation of a grid value at (lat, lon), as IONEX recommends for a site.""" dlat = lats[1] - lats[0] dlon = lons[1] - lons[0] fi = (lat - lats[0]) / dlat fj = (lon - lons[0]) / dlon i0 = int(math.floor(fi)) j0 = int(math.floor(fj)) p = fi - i0 q = fj - j0 v = [] for di, dj in ((0, 0), (1, 0), (0, 1), (1, 1)): x = grid[i0 + di][j0 + dj] if x is None: return None v.append(x) return (1 - p) * (1 - q) * v[0] + p * (1 - q) * v[1] + (1 - p) * q * v[2] + p * q * v[3]