covcollab-eve-detection / covcollab_eve_loader.py
ashen-navigator's picture
Add covert-collaboration Eve-detection dataset (data + minimal generator source)
b96185c verified
Raw
History Blame
3.28 kB
"""Standalone loader for the Covert-Collaboration Eve-Detection Dataset.
Zero dependency on the ``covcollab`` package -- only ``numpy`` and ``pyarrow``.
Reconstructs the complex received blocks ``Y`` and (optionally) the model input
features ``x = [Re(Y), Im(Y), |Y|^2]``.
from covcollab_eve_loader import load_split, complex_Y, features_from_Y
d = load_split(".", "train") # d["Y"]: (N, 4, 320) complex64 + metadata columns
x = features_from_Y(d["Y"][:64]) # (64, 4, 3, 320) float32
"""
from __future__ import annotations
import json
import os
import numpy as np
def _split_files(out_dir: str, split: str) -> list[str]:
with open(os.path.join(out_dir, "manifest.json")) as f:
man = json.load(f)
files = [os.path.join(out_dir, r["file"]) for r in man["files"] if r["split"] == split]
if not files:
raise ValueError(f"no files for split {split!r}; splits: "
f"{sorted({r['split'] for r in man['files']})}")
return sorted(files)
def load_split(out_dir: str, split: str) -> dict:
"""Load one split's parquet shards into a dict of numpy arrays.
Returns ``Y`` (N, R, T) complex64 plus every metadata column as a numpy array.
``split`` is one of: train, val, test_iid, test_ood.
"""
import pyarrow.parquet as pq
tbl = pq.ParquetDataset(_split_files(out_dir, split)).read()
d = tbl.to_pydict()
n = len(d["label"])
r = int(d["n_rx_eve"][0])
t = int(d["n_samples_t"][0])
yr = np.asarray(d.pop("y_real"), dtype=np.float32).reshape(n, r, t)
yi = np.asarray(d.pop("y_imag"), dtype=np.float32).reshape(n, r, t)
out = {"Y": (yr + 1j * yi).astype(np.complex64)}
for k, v in d.items():
out[k] = np.asarray(v)
return out
def complex_Y(y_real, y_imag, n_rx_eve: int = 4, n_samples_t: int = 320) -> np.ndarray:
"""Reconstruct a single (R, T) complex block from its stored flat lists."""
yr = np.asarray(y_real, dtype=np.float32).reshape(n_rx_eve, n_samples_t)
yi = np.asarray(y_imag, dtype=np.float32).reshape(n_rx_eve, n_samples_t)
return (yr + 1j * yi).astype(np.complex64)
def features_from_Y(Y: np.ndarray) -> np.ndarray:
"""Model input x = [Re(Y), Im(Y), |Y|^2] from Y (..., R, T) complex.
Uses a single global energy scale over the passed array (mirrors the training
pipeline's per-minibatch scale); pass a whole minibatch to reproduce exactly.
Returns float32 with a new channel axis before T: (..., R, 3, T).
"""
Y = np.asarray(Y)
if not np.iscomplexobj(Y):
Y = Y.astype(np.complex64)
s = float(np.sqrt(np.mean(np.abs(Y) ** 2)).clip(1e-12))
feat = np.stack([Y.real / s, Y.imag / s, (np.abs(Y) ** 2) / (s * s)], axis=-2)
return feat.astype(np.float32)
if __name__ == "__main__":
import sys
d = sys.argv[1] if len(sys.argv) > 1 else "."
for sp in ("train", "val", "test_iid", "test_ood"):
try:
s = load_split(d, sp)
print(f"{sp:10s} Y={s['Y'].shape} {s['Y'].dtype} "
f"H1={int((s['label']==1).sum())}/{len(s['label'])} "
f"formats={len(np.unique(s['format']))} arms={sorted(np.unique(s['policy_arm']))}")
except Exception as e:
print(f"{sp:10s} <{e}>")