amber / tests /test_format.py
amongglue's picture
Corpus index: 104 datasets, 5,735 h
c56d466 verified
Raw History Blame Contribute Delete
10.2 kB
import sys, os, json, math, tempfile
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import numpy as np
import eegx
from eegx.format import Writer, Recording, make_channel, make_event, EEGXError, validate_header
rng = np.random.default_rng(0)
FAILS = []
def check(name, cond, extra=""):
print(("PASS " if cond else "FAIL ") + name + (f" {extra}" if extra and not cond else ""))
if not cond: FAILS.append(name)
def hdr(nch, n, dtype="int16", sfreq=256.0, codec="zstd", scale=0.1):
return dict(eegx_version=1, id=f"t/{nch}x{n}", dataset="t", subject="s1",
session=None, run=None, part=None, sfreq=sfreq, n_channels=nch,
n_samples=n, dtype=dtype, layout="channel_major", codec={"name": codec},
channels=[make_channel(f"C{i}", "eeg", "uV", scale, 0.0) for i in range(nch)],
events=[make_event(1.5, 0.5, "x")], meta={}, provenance={"lossless": True})
d = tempfile.mkdtemp()
# --- 1. exact int roundtrip, zstd+delta, streamed in odd-sized blocks
nch, n = 23, 100_000
data = (np.cumsum(rng.integers(-40, 40, size=(nch, n)), axis=1) % 30000 - 15000).astype(np.int16)
p = f"{d}/a.eegx"
with Writer(p, hdr(nch, n)) as w:
i = 0
for b in [1, 7, 4095, 60000, 1, 999]:
if i >= n: break
w.append(data[:, i:i+b]); i += b
w.append(data[:, i:])
r = Recording(p)
check("roundtrip exact (zstd+delta)", np.array_equal(r.read(physical=False), data))
check("n_samples correct", r.n_samples == n, f"{r.n_samples}")
check("physical scaling", np.allclose(r.read(0, 100), data[:, :100].astype(np.float32)*0.1, atol=1e-4))
check("duration", abs(r.duration - n/256.0) < 1e-9)
# --- 2. random access equals full read on every chunk boundary
cs = r.header["codec"]["chunk_samples"]
oks = True
for s in [0, 1, cs-1, cs, cs+1, 2*cs-5, n-10, n-1]:
e = min(n, s+3000)
oks &= np.array_equal(r.read(s, e, physical=False), data[:, s:e])
check("random access on chunk boundaries", oks)
check("slice sugar", np.allclose(r[:, 10:20], data[:, 10:20]*0.1, atol=1e-4))
check("picks(eeg)", list(r.picks("eeg")) == list(range(nch)))
check("read past end clamps", r.read(n-5, n+500, physical=False).shape == (nch, 5))
check("empty range", r.read(50, 50).shape == (nch, 0))
r.close()
# --- 2b. the writer must not alias a caller's reused scratch buffer
pbuf = f"{d}/reuse.eegx"
scratch = np.empty((nch, 4096), dtype=np.int16)
with Writer(pbuf, hdr(nch, 40960)) as w:
for k in range(10):
scratch[:] = data[:, k*4096:(k+1)*4096] # same array every iteration
w.append(scratch)
with Recording(pbuf) as rb:
check("writer copies reused caller buffer",
np.array_equal(rb.read(physical=False), data[:, :40960]))
# --- 3. uncompressed is mmap-able and identical
p2 = f"{d}/b.eegx"
h = hdr(nch, n, codec="none")
eegx.write(p2, data, h)
r2 = Recording(p2)
check("codec=none roundtrip", np.array_equal(r2.read(physical=False), data))
check("codec=none random access", np.array_equal(r2.read(70000, 70123, physical=False), data[:, 70000:70123]))
check("codec=none exact file size", os.path.getsize(p2) == r2._data_off + nch*n*2)
r2.close()
# --- 4. compression actually helps on realistic (smooth) EEG
t = np.arange(n) / 256.0
sig = np.zeros((nch, n))
for i in range(nch):
for f_, a_ in ((10, 30), (5, 15), (2.5, 20), (25, 5)):
sig[i] += a_*np.sin(2*np.pi*f_*t + rng.random()*6.28)
sig[i] += rng.normal(0, 3, n)
q = np.clip(np.rint(sig/0.1), -32768, 32767).astype(np.int16)
sizes = {}
for name, kw in (("zstd+delta", {}), ("zstd", {"filters": ()}), ("none", None)):
pp = f"{d}/c_{name}.eegx"
if kw is None:
eegx.write(pp, q, hdr(nch, n, codec="none"))
else:
eegx.write(pp, q, hdr(nch, n), **kw)
sizes[name] = os.path.getsize(pp)
raw = nch*n*2
print(" sizes:", {k: f"{v/raw:.3f}x" for k, v in sizes.items()})
check("delta filter beats plain zstd", sizes["zstd+delta"] < sizes["zstd"])
check("zstd beats raw", sizes["zstd+delta"] < sizes["none"]*0.8)
# --- 5. dtypes
for dt, arr in (("int32", rng.integers(-2**30, 2**30, (4, 5000)).astype(np.int32)),
("float32", rng.normal(0, 50, (4, 5000)).astype(np.float32))):
# float32 payloads must silently drop the integer-only delta filter
pp = f"{d}/d_{dt}.eegx"
hh = hdr(4, 5000, dtype=dt, scale=1.0)
eegx.write(pp, arr, hh)
with Recording(pp) as rr:
check(f"{dt} roundtrip", np.array_equal(rr.read(physical=False), arr))
# --- 6. header-rewrite path (reserved header too small)
pp = f"{d}/e2.eegx"
big = rng.integers(-100, 100, (2, 300_000)).astype(np.int16)
wr = Writer(pp, hdr(2, 300_000), chunk_samples=1024) # 293 chunks -> big index
wr.append(big); wr.close()
with Recording(pp) as rr:
check("many-chunk file roundtrip", np.array_equal(rr.read(physical=False), big))
check("chunk_offsets length", len(rr.header["codec"]["chunk_offsets"]) ==
math.ceil(300_000/1024)+1)
# --- 7. zero-length and single-sample
for n_ in (0, 1):
pp = f"{d}/z{n_}.eegx"
a = np.zeros((3, n_), dtype=np.int16)
eegx.write(pp, a, hdr(3, n_))
with Recording(pp) as rr:
check(f"n_samples={n_} roundtrip", rr.read(physical=False).shape == (3, n_))
# --- 8. validation rejects malformed headers
def rejects(name, mut):
h = hdr(2, 10); mut(h)
try:
validate_header(h); check("reject "+name, False)
except EEGXError: check("reject "+name, True)
rejects("bad dtype", lambda h: h.__setitem__("dtype", "float64"))
rejects("bad version", lambda h: h.__setitem__("eegx_version", 2))
rejects("nch mismatch", lambda h: h.__setitem__("n_channels", 3))
rejects("dup channel names", lambda h: h["channels"].__setitem__(1, dict(h["channels"][0])))
rejects("type outside vocab", lambda h: h["channels"][0].__setitem__("type", "brainwaves"))
rejects("negative sfreq", lambda h: h.__setitem__("sfreq", -1))
rejects("nan onset", lambda h: h.__setitem__("events", [{"onset": float("nan"), "value": "x"}]))
rejects("missing key", lambda h: h.pop("meta"))
rejects("bad layout", lambda h: h.__setitem__("layout", "time_major"))
# --- 9. not-an-eegx-file
pp = f"{d}/bad.bin"; __import__("pathlib").Path(pp).write_bytes(b"NOTEEGX" + b"\0"*100)
try:
Recording(pp); check("reject bad magic", False)
except EEGXError: check("reject bad magic", True)
# --- 10. corpus catalog + window index
import shutil
root = f"{d}/corpus"; os.makedirs(root+"/t", exist_ok=True)
for k in range(3):
hh = hdr(8, 30000); hh["id"] = f"t/r{k}"; hh["subject"] = f"s{k}"
eegx.write(f"{root}/t/r{k}.eegx", data[:8, :30000], hh)
rows = eegx.build_catalog(root)
check("catalog rows", len(rows) == 3)
st = eegx.corpus_stats(rows)
check("stats hours", abs(st["total_hours"] - 3*30000/256/3600) < 1e-3, str(st["total_hours"]))
wi = eegx.WindowIndex(root, window_s=10.0, hop_s=10.0)
exp = 3 * ((30000 - 2560)//2560 + 1)
check("window count", len(wi) == exp, f"{len(wi)} vs {exp}")
x, m = wi[5]
check("window shape", x.shape == (8, 2560), str(x.shape))
m_ = int(round(m['t0']*256))
check("window content", np.allclose(x, data[:8, m_:m_+2560]*0.1, atol=1e-4))
wi.close()
# --- 11. to_mne
with Recording(f"{root}/t/r0.eegx") as rr:
raw = rr.to_mne()
check("to_mne shape", raw.get_data().shape == (8, 30000))
check("to_mne volts", np.allclose(raw.get_data()[:, :50], data[:8, :50]*0.1*1e-6, atol=1e-12))
check("to_mne annots", len(raw.annotations) == 1)
# --- 12. picks by channel type and name
# Regression: picks went straight to np.asarray(dtype=int64), so every
# documented example selecting by channel type (`read(picks=['eeg'])`) raised
# ValueError -- including the ones printed on the published dataset cards.
pk = f"{d}/picks.eegx"
_h = hdr(3, 50, sfreq=100.0)
_h["channels"] = [make_channel("Cz", "eeg", "uV", 0.1, 0.0),
make_channel("EOGl", "eog", "uV", 0.1, 0.0),
make_channel("C3", "eeg", "uV", 0.1, 0.0)]
with Writer(pk, _h) as _w:
_w.append(np.arange(150, dtype=np.int16).reshape(3, 50))
with Recording(pk) as rp:
check("picks by type", rp.read(picks=["eeg"]).shape == (2, 50))
check("picks single type", rp.read(picks=["eog"]).shape == (1, 50))
check("picks two types", rp.read(picks=["eeg", "eog"]).shape == (3, 50))
check("picks by name", rp.read(picks=["Cz"]).shape == (1, 50))
check("picks name case-insensitive", rp.read(picks=["cz"]).shape == (1, 50))
check("picks by index", rp.read(picks=[0, 2]).shape == (2, 50))
check("picks mixed type+index", rp.read(picks=["eeg", 1]).shape == (3, 50))
check("picks absent type is empty", rp.read(picks=["ecg"]).shape == (0, 50))
check("picks dedupe", rp.read(picks=["eeg", "Cz"]).shape == (2, 50))
check("picks preserve requested order",
np.array_equal(rp.read(picks=["C3", "Cz"], physical=False),
rp.read(picks=[2, 0], physical=False)))
try:
rp.read(picks=["nonsense"]); check("bad pick raises", False)
except EEGXError:
check("bad pick raises", True)
try:
rp.read(picks=[99]); check("out-of-range index raises", False)
except EEGXError:
check("out-of-range index raises", True)
# --- atomic publication: a .eegx only appears once it is complete, so a
# concurrent uploader can never pick up a half-written file.
ap = f"{d}/atomic.eegx"
w = Writer(ap, hdr(4, 0))
w.append(np.zeros((4, 1000), dtype=np.int16))
check("no .eegx while writing", not os.path.exists(ap))
check(".part exists while writing", os.path.exists(ap + ".part"))
w.close()
check(".eegx exists after close", os.path.exists(ap))
check("no .part left after close", not os.path.exists(ap + ".part"))
# A conversion that raises leaves nothing behind at all.
fp = f"{d}/failed.eegx"
try:
with Writer(fp, hdr(4, 0)) as w:
w.append(np.zeros((4, 1000), dtype=np.int16))
raise RuntimeError("simulated conversion failure")
except RuntimeError:
pass
check("failed write leaves no .eegx", not os.path.exists(fp))
check("failed write leaves no .part", not os.path.exists(fp + ".part"))
shutil.rmtree(d)
print("\n" + ("ALL PASS" if not FAILS else f"{len(FAILS)} FAILURES: {FAILS}"))
sys.exit(1 if FAILS else 0)