""" verify_dataset.py — recompute every number on the dataset card from the CSVs. pip install pandas numpy huggingface_hub python verify_dataset.py ./chb_mit_data # folder with the 24 CSVs python verify_dataset.py --download ./chb_mit_data # download first (~4 GB) Writes verification_report.json and prints a summary. Reads one patient at a time (peak RAM ~ 2-3 GB for chb04). """ import os import re import sys import json import numpy as np import pandas as pd META = ["epoch_id", "window_start", "window_end", "file_source", "target_label"] STD18 = ["FP1-F7", "F7-T7", "T7-P7", "P7-O1", "FP1-F3", "F3-C3", "C3-P3", "P3-O1", "FP2-F4", "F4-C4", "C4-P4", "P4-O2", "FP2-F8", "F8-T8", "T8-P8-0", "P8-O2", "FZ-CZ", "CZ-PZ"] DUMMY = re.compile(r"^(--\d+|\.-\d+)$") def channels(cols): return [c[: -len("_Delta_power")] for c in cols if c.endswith("_Delta_power")] def check_patient(path): df = pd.read_csv(path, low_memory=False) cols = list(df.columns) feats = [c for c in cols if c not in META] chs = channels(cols) num = df[feats].apply(pd.to_numeric, errors="coerce") arr = num.to_numpy(dtype=np.float64) # per-recording channel availability (a channel "exists" if its Delta_power is non-null) per_edf = {} for edf, g in df.groupby("file_source"): present = [ch for ch in chs if g[f"{ch}_Delta_power"].notna().any()] per_edf[edf] = { "rows": int(len(g)), "preictal": int((g["target_label"] == 1).sum()), "std_channels": [c for c in present if c in STD18], "dummy_channels": [c for c in present if DUMMY.match(c)], "other_channels": [c for c in present if c not in STD18 and not DUMMY.match(c)], } std_cols = [c for c in feats if any(c.startswith(s + "_") or c.startswith(s.replace("-", "_") + "_") for s in STD18)] no_std_eeg = int(df[std_cols].isna().all(axis=1).sum()) if std_cols else len(df) coh = [c for c in feats if c.startswith("coh_")] order = list(df["file_source"]) return { "rows": int(len(df)), "label_counts": {str(k): int(v) for k, v in df["target_label"].value_counts().sort_index().items()}, "n_columns": len(cols), "n_features": len(feats), "channels": chs, "n_std_channels_any": sum(c in STD18 for c in chs), "dummy_channels": [c for c in chs if DUMMY.match(c)], "non_standard_channels": [c for c in chs if c not in STD18 and not DUMMY.match(c)], "edf_files": int(df["file_source"].nunique()), "rows_without_any_standard_eeg": no_std_eeg, "preictal_rows_without_any_standard_eeg": int(df.loc[df[std_cols].isna().all(axis=1), "target_label"].eq(1).sum()) if std_cols else None, "n_inf": int(np.isinf(arr).sum()), "n_nan": int(np.isnan(arr).sum()), "always_zero_coherence": [c for c in coh if (num[c].fillna(0) == 0).all()], "duplicate_rows": int(df.duplicated(subset=["file_source", "window_start"]).sum()), "rows_in_file_time_order": bool(order == sorted(order, key=lambda s: [int(t) if t.isdigit() else t for t in re.split(r"(\d+)", s)])), "window_lengths": sorted({round(float(x), 2) for x in (df["window_end"] - df["window_start"]).unique()}), "per_recording": per_edf, } def main(): args = sys.argv[1:] download = "--download" in args args = [a for a in args if a != "--download"] data_dir = args[0] if args else "./chb_mit_data" if download: from huggingface_hub import snapshot_download snapshot_download("JayF14/chb-mit-preprocessed-eeg", repo_type="dataset", local_dir=data_dir) report, tot = {}, {"rows": 0, "pre": 0, "inter": 0, "edf": 0, "no_eeg": 0, "inf": 0} for i in range(1, 25): pid = f"chb{i:02d}" path = os.path.join(data_dir, f"{pid}_labeled_features.csv") r = check_patient(path) r["size_bytes"] = os.path.getsize(path) report[pid] = r lc = r["label_counts"] tot["rows"] += r["rows"]; tot["pre"] += lc.get("1", 0); tot["inter"] += lc.get("0", 0) tot["edf"] += r["edf_files"]; tot["no_eeg"] += r["rows_without_any_standard_eeg"]; tot["inf"] += r["n_inf"] print(f"{pid}: rows={r['rows']:>6} pre={lc.get('1',0):>5} cols={r['n_columns']:>5} " f"std_ch={r['n_std_channels_any']:>2} dummies={len(r['dummy_channels'])} " f"other={r['non_standard_channels']} edf={r['edf_files']} " f"no_eeg_rows={r['rows_without_any_standard_eeg']} inf={r['n_inf']} " f"zero_coh={len(r['always_zero_coherence'])} sorted={r['rows_in_file_time_order']}") tot["pre_pct"] = round(100 * tot["pre"] / tot["rows"], 2) tot["size_gb"] = round(sum(r["size_bytes"] for r in report.values()) / 1e9, 3) zero_all = set.intersection(*[set(r["always_zero_coherence"]) for r in report.values()]) tot["coherence_zero_in_all_patients"] = sorted(zero_all) print("\nTOTAL:", json.dumps({k: v for k, v in tot.items() if k != "coherence_zero_in_all_patients"})) print("Coherence columns that are 0 in every patient:", len(zero_all)) with open("verification_report.json", "w") as f: json.dump({"totals": tot, "patients": report}, f, indent=1) print("Saved verification_report.json") if __name__ == "__main__": main()