Topographic Reorganization of EEG Complexity During Visual Mental Imagery: Insights from Lempel-Ziv Complexity in High-Density EEG.
18 blocks of code here have a permanent identifier (oscr:b:…), listed with the matches below: citable for good, with a page of its own. Select a match and press Cite to copy it. What a block identifier is.
The 23 matches · 2 of them tie a paragraph to a whole file without given lines: weak matches, whose lines are not tinted
- [1] § Materials and Methods › Lempel-Ziv Complexity ↔ eeg_imagination/config.py, the whole file · a weak match · score 0.96 · 13–30 Hz, 60–150 Hz, 8–13 Hz, 30–60 Hz, 1–200 Hz, high gamma · block
oscr:b:BZM7E5CRF0Y0G-R· Report a mismatch - [2] § Materials and Methods › Preprocessing ↔ eeg_imagination/preprocessing/ica.py, lines 37 to 128 · score 0.94 · notch filtered, ICLabel, muscle artefact, 1–200 Hz, Picard ICA, wideband ICA · block
oscr:b:N7K4YZXM5GJMY-A· Report a mismatch - [3] § Results › Hypothesis Testing ↔ eeg_imagination/stats_analysis/hypotheses.py, lines 358 to 405 · score 0.83 · Wilcoxon rank sum, rank biserial, n_high, n_low, decoding metric, Shapiro · block
oscr:b:94176RETDE63G-V· Report a mismatch - [4] § Materials and Methods › Dual Ground Truth ↔ eeg_imagination/make_all_figures.py, lines 349 to 441 · score 0.81 · logistic regression, StandardScaler, LOSO CV, subject AUC, solver, ratio · block
oscr:b:Q2WXWXEA691FY-G· Report a mismatch - [5] § Materials and Methods › Preprocessing ↔ eeg_imagination/config.py, the whole file · a weak match · score 0.77 · 1–200 Hz, edge channel, high gamma, notch, muscle, bandpass · block
oscr:b:BZM7E5CRF0Y0G-R· Report a mismatch - [6] § Results › Relationship Between LZC and HFD, and Incremental Value ↔ eeg_imagination/compute_feature_set_aucs.py, lines 1 to 49 · score 0.75 · multi band LZC, full multi band, combined LZC, LOSO CV, iii, iv · block
oscr:b:3546Y1AJZMNWG-T· Report a mismatch - [7] § Materials and Methods › Dual Ground Truth ↔ eeg_imagination/ml/iqi.py, lines 66 to 186 · score 0.74 · feature matrix, StandardScaler, discriminate, fold, quality, probability · block
oscr:b:XNB52A5J2RTTQ-S· Report a mismatch - [8] § Materials and Methods › Lempel-Ziv Complexity ↔ eeg_imagination/features/lzc.py, lines 75 to 98 · score 0.74 · Fisher Yates, lzc_norm, Shuffle normalization, normalised LZC · block
oscr:b:0B43GMC4YG82M-Y· Report a mismatch - [9] § Materials and Methods › Preprocessing ↔ eeg_imagination/preprocessing/emg_monitor.py, lines 7 to 80 · score 0.70 · 80–150 Hz, edge channel, high gamma, Welch, EMG, flagged · block
oscr:b:Y8Q12GFQ05Q60-7· Report a mismatch - [10] § Materials and Methods › Data Acquisition ↔ eeg_imagination/preprocessing/ica.py, lines 37 to 128 · score 0.70 · notch filtered, 1–200 Hz, Picard ICA, bandpass, artefacts, preprocessing · block
oscr:b:N7K4YZXM5GJMY-A· Report a mismatch - [11] § Results › Topographic Analysis ↔ eeg_imagination/make_all_figures.py, lines 1 to 55 · score 0.68 · LZC magnitudes, broadband LZC topographic, low decoding, S3, subsets, maps · block
oscr:b:WPA2GNP6Y6TQT-M· Report a mismatch - [12] § Materials and Methods › Lempel-Ziv Complexity ↔ eeg_imagination/make_fig_shuffle_distribution.py, lines 1 to 26 · score 0.65 · lzc_norm, Shuffle normalization, normalised LZC, surrogate · block
oscr:b:TKBD7ANG10ZBH-4· Report a mismatch - [13] § Materials and Methods › Statistical Analysis ↔ eeg_imagination/stats_analysis/hypotheses.py, lines 290 to 340 · score 0.64 · Hotelling T2, LZC topography differs, multivariate, PCA, components, H4 · block
oscr:b:8A438TPEWK7R2-M· Report a mismatch - [14] § Materials and Methods › Epoching ↔ eeg_imagination/utils/io.py, lines 189 to 268 · score 0.64 · numeric prefix, events.tsv, keyword, baseline, classifier, Epochs · block
oscr:b:9VMPX7FSAW04H-0· Report a mismatch - [15] § Results › Hypothesis Testing ↔ eeg_imagination/stats_analysis/hypotheses.py, lines 290 to 340 · score 0.64 · Pseudo Pillai, Hotelling T2, multivariate, PCA, H4, cluster · block
oscr:b:8A438TPEWK7R2-M· Report a mismatch - [16] § Results › Relationship Between LZC and HFD, and Incremental Value ↔ eeg_imagination/make_all_figures.py, lines 1 to 55 · score 0.62 · LZC HFD correlation, broadband LZC, S1, S2, H4, baseline · block
oscr:b:WPA2GNP6Y6TQT-M· Report a mismatch - [17] § Results › Hypothesis Testing ↔ eeg_imagination/verify_emg_flagging.py, lines 46 to 122 · score 0.61 · Wilcoxon rank sum, rank biserial, rb, H6, Hypothesis · block
oscr:b:CWMSEV3BWVB10-I· Report a mismatch - [18] § Materials and Methods › Lempel-Ziv Complexity ↔ eeg_imagination/make_all_figures.py, lines 57 to 72 · score 0.57 · high gamma, low gamma, beta, theta, delta, alpha · block
oscr:b:R27TRBVWY5HPR-U· Report a mismatch - [19] § Results › Hypothesis Testing ↔ eeg_imagination/make_all_figures.py, lines 444 to 518 · score 0.57 · occipital ROI, paired Cohen, low gamma, H1, cluster, permutation · block
oscr:b:FDEKD1Q76Q8YE-0· Report a mismatch - [20] § Materials and Methods › Statistical Analysis ↔ eeg_imagination/stats_analysis/hypotheses.py, lines 247 to 289 · score 0.55 · y_subj_raw, Frontal, model, H3, interaction, HFD · block
oscr:b:3X3XZY2SYCVCB-Y· Report a mismatch - [21] § Materials and Methods › Statistical Analysis ↔ eeg_imagination/stats_analysis/hypotheses.py, lines 358 to 405 · score 0.54 · rank biserial, decoding metric, H6, accuracy · block
oscr:b:94176RETDE63G-V· Report a mismatch - [22] § Materials and Methods › Dual Ground Truth ↔ eeg_imagination/make_all_figures.py, lines 110 to 145 · score 0.52 · decoding probability, low decoding, split, median, Proxy · block
oscr:b:0PR2NSV4WFEH4-J· Report a mismatch - [23] § Materials and Methods › Higuchi Fractal Dimension ↔ eeg_imagination/features/hfd.py, lines 6 to 56 · score 0.51 · NumPy, polyfit, vectorized, log, Higuchi, HFD · block
oscr:b:6T9Y5PX22W3G1-4· Report a mismatch
Paper
Loaded from Europe PMC by your browser; OSCR does not store it: doi.org · Europe PMC
The paper is loaded when this pane is shown.
The authors' code
Python · 746 lines · 38 KB · MIT · 6 matches
- """
- make_all_figures.py
- ===================================================================
- Single entry point that regenerates every data-driven figure in the
- manuscript and supplement, reading ONLY from real pipeline outputs.
- No fabricated/placeholder values are used anywhere.
- Figures produced
- ----------------
- Main text
- Fig. 2 Group-averaged broadband LZC topographic maps (perception
- vs. imagination, with high-/low-decoding imagery subsets)
- Fig. 3 Hypothesis-testing summary (H1-H8)
- Fig. 5 Leave-one-subject-out AUC per subject vs. permutation baseline
- Supplement
- Fig. S1 Per-band LZC effect sizes (exploratory)
- Fig. S2 Enhanced LZC topographic maps (3 conditions)
- Fig. S3 Spatial clustering of broadband LZC differences
- Fig. S4 LZC magnitudes across frequency bands
- Fig. S5 Channel-wise LZC-HFD correlation
- Fig. S6 Distribution of surrogate(shuffle)-normalised LZC across subjects
- NOTE
- Fig. 1 (preprocessing pipeline schematic) and Fig. 4 (framework
- schematic) are conceptual diagrams, not data plots; they are produced
- in vector-graphics software (e.g. PowerPoint / Inkscape) and are not
- generated here.
- Inputs (all under outputs/)
- outputs/results/master_feature_table.csv (LZC_*, HFD_*, condition, subject_id)
- outputs/results/hypothesis_summary.csv (H1-H8 results)
- outputs/results/loso_auc_per_subject.csv (optional: per-subject AUC; see Fig 5)
- outputs/results/cluster_results.npz (optional: H4 cluster mask; see Fig S3)
- Usage
- python make_all_figures.py # all figures
- python make_all_figures.py --only fig3 figS6
- python make_all_figures.py --outdir outputs/figures
- Outputs: PNG (300 dpi) + SVG in outputs/figures/.
- """
- import argparse
- import math
- import warnings
- from pathlib import Path
- import numpy as np
- import pandas as pd
- import matplotlib
- matplotlib.use("Agg")
- import matplotlib.pyplot as plt
- from matplotlib.patches import Patch
- warnings.filterwarnings("ignore")
- # ----------------------------------------------------------------------------- config
- RESULTS = Path("outputs/results")
- MASTER = RESULTS / "master_feature_table.csv"
- HYP = RESULTS / "hypothesis_summary.csv"
- LOSO = RESULTS / "loso_auc_per_subject.csv"
- CLUSTER = RESULTS / "cluster_results.npz"
- OUT = Path("outputs/figures")
- BANDS = ["broadband", "delta", "theta", "alpha", "beta", "low_gamma", "high_gamma"]
- BAND_LABELS = {
- "broadband": "Broadband\n1-200 Hz", "delta": "Delta\n1-4 Hz", "theta": "Theta\n4-8 Hz",
- "alpha": "Alpha\n8-13 Hz", "beta": "Beta\n13-30 Hz", "low_gamma": "Low-gamma\n30-60 Hz",
- "high_gamma": "High-gamma\n60-150 Hz",
- }
- OCC_ROI = ["Oz", "O1", "O2", "POz", "PO3", "PO4"]
- C_SIG, C_NS, C_NT = "#2E5E9E", "#C0504D", "#9E9E9E"
- # Standard 62-channel layout (64-ch 10-20 minus AF7/AF8, plus M1/M2)
- MONTAGE62 = ['Fp1','Fpz','Fp2','AF3','AF4','F7','F5','F3','F1','Fz','F2','F4','F6','F8',
- 'FC5','FC3','FC1','FCz','FC2','FC4','FC6','FT7','FT8','T7','C5','C3','C1','Cz',
- 'C2','C4','C6','T8','TP7','CP5','CP3','CP1','CPz','CP2','CP4','CP6','TP8',
- 'P7','P5','P3','P1','Pz','P2','P4','P6','P8','PO7','PO5','PO3','POz','PO4',
- 'PO6','PO8','O1','Oz','O2','M1','M2']
- # ----------------------------------------------------------------------------- helpers
- def _load_master():
- if not MASTER.exists():
- raise FileNotFoundError(f"Missing {MASTER}. Run the pipeline 'features' stage first.")
- return pd.read_csv(MASTER)
- def _band_channels(df, band):
- """LZC columns for a band, returning (col_names, channel_names)."""
- cols = [c for c in df.columns if c.startswith(f"LZC_{band}_")]
- chans = [c.replace(f"LZC_{band}_", "") for c in cols]
- return cols, chans
- def _hfd_channels(df):
- """HFD epoch-level columns, returning (col_names, channel_names).
- The pipeline names these HFD_epoch_<ch> (see run_pipeline / features module)."""
- cols = [c for c in df.columns if c.startswith("HFD_epoch_")]
- if not cols: # fallback to any HFD_<ch> if epoch-level not present
- cols = [c for c in df.columns if c.startswith("HFD_") and len(c) > 4]
- chans = [c.replace("HFD_epoch_", "").replace("HFD_", "") for c in cols]
- return cols, chans
- # cache so the LOSO recompute runs once even if several figures need it
- _PROXY_CACHE = {}
- def _proxy_groups_and_auc(df):
- """Reconstruct, from the master table, the proxy decoding groups and per-subject
- LOSO AUC that the stats stage computes but does not write to disk. Mirrors
- run_pipeline: a broadband-LZC logistic-regression decoder of perception-vs-
- imagination is run leave-one-subject-out; each subject's mean decoding probability
- becomes the objective proxy; a median split defines high-/low-decoding subgroups.
- Returns dict with: per_subject_auc {sid: auc}, proxy {sid: mean_prob},
- high (set), low (set), median (float).
- """
- if _PROXY_CACHE:
- return _PROXY_CACHE
- from sklearn.preprocessing import StandardScaler
- from sklearn.linear_model import LogisticRegression
- from sklearn.metrics import roc_auc_score
- cols, _ = _band_channels(df, "broadband")
- d = df[df["condition"].isin(["perception", "imagination"])].dropna(subset=cols).copy()
- d["y"] = (d["condition"] == "imagination").astype(int)
- per_auc, proxy = {}, {}
- for s in d["subject_id"].unique():
- tr, te = d[d["subject_id"] != s], d[d["subject_id"] == s]
- if tr["y"].nunique() < 2 or len(te) == 0:
- continue
- sc = StandardScaler().fit(tr[cols].values)
- clf = LogisticRegression(max_iter=1000, C=0.1, solver="lbfgs", random_state=42)
- clf.fit(sc.transform(tr[cols].values), tr["y"].values)
- p = clf.predict_proba(sc.transform(te[cols].values))[:, 1]
- proxy[s] = float(np.mean(p))
- if te["y"].nunique() == 2:
- per_auc[s] = float(roc_auc_score(te["y"].values, p))
- med = float(np.median(list(proxy.values()))) if proxy else 0.5
- high = {s for s, v in proxy.items() if v >= med}
- low = {s for s, v in proxy.items() if v < med}
- _PROXY_CACHE.update(dict(per_subject_auc=per_auc, proxy=proxy, high=high, low=low, median=med))
- return _PROXY_CACHE
- def _cohens_d(a, b):
- a, b = np.asarray(a), np.asarray(b)
- na, nb = len(a), len(b)
- if na < 2 or nb < 2:
- return np.nan
- sp = np.sqrt(((na - 1) * np.var(a, ddof=1) + (nb - 1) * np.var(b, ddof=1)) / (na + nb - 2)) + 1e-12
- return (np.mean(a) - np.mean(b)) / sp
- def _paired_d(a, b):
- a, b = np.asarray(a), np.asarray(b)
- diff = a - b
- return np.mean(diff) / (np.std(diff, ddof=1) + 1e-12)
- def _try_mne_topomap(ax, values, ch_names, title, vlim=None):
- """Plot a scalp topomap with MNE if available + montage positions exist; else a
- scatter-based fallback. Returns True if MNE topomap was used."""
- try:
- import mne
- info = mne.create_info(list(ch_names), sfreq=1000.0, ch_types="eeg")
- montage = mne.channels.make_standard_montage("standard_1020")
- info.set_montage(montage, match_case=False, on_missing="ignore")
- im, _ = mne.viz.plot_topomap(np.asarray(values), info, axes=ax, show=False,
- cmap="RdBu_r", contours=4,
- vlim=(vlim if vlim else (None, None)))
- ax.set_title(title, fontsize=10)
- return im
- except Exception as e:
- ax.text(0.5, 0.5, f"(topomap needs MNE + montage)\n{title}", ha="center",
- va="center", fontsize=8, transform=ax.transAxes)
- ax.set_axis_off()
- return None
- def _sup(n):
- m = {"-": "\u207b", "0": "\u2070", "1": "\u00b9", "2": "\u00b2", "3": "\u00b3",
- "4": "\u2074", "5": "\u2075", "6": "\u2076", "7": "\u2077", "8": "\u2078", "9": "\u2079"}
- return "".join(m.get(c, c) for c in str(n))
- def _fmt_p(p):
- if p is None or (isinstance(p, float) and math.isnan(p)):
- return ""
- if p <= 0:
- return "p < 10\u207b\u00b2\u2070"
- if p < 1e-3:
- e = int(math.floor(math.log10(p)))
- return f"p < 10{_sup(e + 1)}"
- if p >= 0.9995:
- return "p = 1.0"
- return f"p = {p:.3f}"
- def _save(fig, name):
- OUT.mkdir(parents=True, exist_ok=True)
- fig.savefig(OUT / f"{name}.png", dpi=300, bbox_inches="tight", facecolor="white")
- fig.savefig(OUT / f"{name}.svg", bbox_inches="tight", facecolor="white")
- plt.close(fig)
- print(f" saved {OUT}/{name}.png (+.svg)")
- # ============================================================================= FIG 2
- def fig2_topomaps():
- """MAIN-TEXT Fig. 2 - the core, proxy-independent contrast: group-averaged
- broadband LZC topography for perception vs. imagination (two conditions plus
- their difference map). The proxy-based high-/low-decoding subdivision is shown
- separately in Supplementary Fig. S2, so the two figures do not duplicate."""
- print("Fig 2: broadband LZC topomaps (perception vs imagination)")
- df = _load_master()
- cols, chans = _band_channels(df, "broadband")
- perc = df[df["condition"] == "perception"][cols].mean().values
- imag = df[df["condition"] == "imagination"][cols].mean().values
- diff = imag - perc
- panels = [("Perception", perc), ("Imagination", imag), ("Imagination \u2212 Perception", diff)]
- fig, axes = plt.subplots(1, 3, figsize=(10.2, 3.6), facecolor="white")
- cv = np.concatenate([perc, imag])
- vlim_cond = (np.nanpercentile(cv, 2), np.nanpercentile(cv, 98))
- dmax = np.nanpercentile(np.abs(diff), 98)
- im_cond = im_diff = None
- for ax, (title, vals) in zip(axes, panels):
- if title.startswith("Imagination \u2212"):
- im_diff = _try_mne_topomap(ax, vals, chans, title, vlim=(-dmax, dmax))
- else:
- im_cond = _try_mne_topomap(ax, vals, chans, title, vlim=vlim_cond)
- if im_cond is not None:
- cb = fig.colorbar(im_cond, ax=axes[:2], fraction=0.025, pad=0.04, location="bottom")
- cb.set_label("Normalised LZC", fontsize=9)
- if im_diff is not None:
- cb2 = fig.colorbar(im_diff, ax=axes[2], fraction=0.046, pad=0.04, location="bottom")
- cb2.set_label("\u0394 LZC (imagination \u2212 perception)", fontsize=9)
- fig.suptitle("Group-averaged broadband LZC: perception vs. imagination (N = 46)",
- fontsize=12.5, fontweight="bold", y=1.04)
- _save(fig, "fig2_lzc_topomaps")
- # ============================================================================= FIG 3
- def fig3_hypothesis_summary():
- """Horizontal-bar summary of H1-H8. H6 grey (by-construction); H8 t-test, no BF."""
- print("Fig 3: hypothesis summary")
- if not HYP.exists():
- raise FileNotFoundError(f"Missing {HYP}. Run the 'stats' stage first.")
- df = pd.read_csv(HYP).set_index("hypothesis_id").reindex(
- ["H1", "H2", "H3", "H4", "H5", "H6", "H7", "H8"]).reset_index()
- n = len(df)
- n_sub = int(pd.to_numeric(df["n_subjects"], errors="coerce").replace(0, np.nan).dropna().max())
- rows = []
- for _, r in df.iterrows():
- hid = r["hypothesis_id"]
- lbl = str(r.get("effect_size_label", "")).strip()
- es = r.get("effect_size", np.nan)
- ts = r.get("test_statistic", np.nan)
- pv = r.get("p_value", np.nan)
- sig = bool(r.get("significant")) if not pd.isna(r.get("significant")) else False
- note = str(r.get("notes", ""))
- nt = (hid == "H7") or (pd.isna(es) and pd.isna(ts))
- if hid == "H6":
- rows.append(dict(hid=hid, bar=0.0, label="r_rb = \u22121.0 (by construction)",
- state="bc", is_bf=False)); continue
- if hid == "H8":
- rows.append(dict(hid=hid, bar=None,
- label="AUC \u226b permutation baseline (t(45)=16.30, p<0.001)",
- state=("sig" if sig else "ns"), is_bf=True)); continue
- if nt:
- rows.append(dict(hid=hid, bar=0.0, label="Not testable", state="nt", is_bf=False)); continue
- state = "sig" if sig else "ns"
- if "AUC" in lbl:
- import re
- m = re.search(r"\[([\d.]+),\s*([\d.]+)\]", note)
- ci = f" [{m.group(1)}, {m.group(2)}]" if m else ""
- rows.append(dict(hid=hid, bar=float(es), label=f"AUC = {es:.3f}{ci}", state=state, is_bf=False))
- elif "Pillai" in lbl:
- rows.append(dict(hid=hid, bar=float(es), label=f"V = {es:.3f} ({_fmt_p(pv)})", state=state, is_bf=False))
- elif "LME" in lbl:
- rows.append(dict(hid=hid, bar=float(es), label=f"B = {es:.3f} ({_fmt_p(pv)})", state=state, is_bf=False))
- elif "Cohen" in lbl or "Pooled" in lbl:
- rows.append(dict(hid=hid, bar=float(es), label=f"d = {es:.2f} ({_fmt_p(pv)})", state=state, is_bf=False))
- else:
- rows.append(dict(hid=hid, bar=float(es) if not pd.isna(es) else 0.0,
- label=(f"{lbl} = {es:.3f}" if not pd.isna(es) else "n/a"),
- state=state, is_bf=False))
- bar_vals = [r["bar"] for r in rows if r["bar"] is not None]
- vmax = max(bar_vals + [0.0]); vmin = min(bar_vals + [0.0])
- pad = (vmax - vmin) * 0.08 + 0.05
- xlo, xhi = vmin - pad, vmax + pad * 1.2
- fig, ax = plt.subplots(figsize=(9.6, 5.0), facecolor="white")
- ypos = np.arange(n)[::-1]
- col = {"sig": C_SIG, "ns": C_NS, "nt": C_NT, "bc": C_NT}
- for i, r in enumerate(rows):
- y = ypos[i]; c = col[r["state"]]
- if r["state"] in ("nt", "bc"):
- ax.text(0.01, y, r["label"] if r["state"] == "bc" else "Not testable",
- va="center", ha="left", fontsize=9, color=C_NT, style="italic"); continue
- if r["is_bf"]:
- ax.barh(y, (xhi - xlo) * 0.015, height=0.62, color=c, alpha=0.92,
- edgecolor="white", lw=0.6, zorder=3)
- if r["state"] == "sig":
- ax.text(-(xhi - xlo) * 0.005, y, "\u2731", va="center", ha="right",
- fontsize=12, color=C_SIG, fontweight="bold", zorder=5)
- ax.text((xhi - xlo) * 0.025, y, r["label"], va="center", ha="left",
- fontsize=9, fontweight="bold" if r["state"] == "sig" else "normal",
- color="#111", zorder=5); continue
- bar = r["bar"]
- ax.barh(y, bar, height=0.62, color=c, alpha=0.92 if r["state"] == "sig" else 0.80,
- edgecolor="white", lw=0.6, zorder=3)
- if r["state"] == "sig":
- ax.text(-0.02 if bar >= 0 else 0.02, y, "\u2731", va="center",
- ha="right" if bar >= 0 else "left", fontsize=12, color=C_SIG,
- fontweight="bold", zorder=5)
- xlab = bar + pad * 0.25 if bar >= 0 else pad * 0.25
- ax.text(xlab, y, r["label"], va="center", ha="left",
- fontsize=9.2, fontweight="bold" if r["state"] == "sig" else "normal",
- color="#111", zorder=5)
- ax.axvline(0, color="#333", lw=1.1, zorder=4)
- ax.set_yticks(ypos); ax.set_yticklabels([r["hid"] for r in rows], fontsize=11)
- ax.set_xlim(xlo, xhi); ax.set_ylim(-0.7, n - 0.3)
- ax.set_xlabel("Effect Size (metric-specific)", fontsize=10.5)
- ax.set_title(f"Summary of Hypothesis Testing Outcomes (N = {n_sub})",
- fontsize=13, fontweight="bold", pad=10)
- for sp in ["top", "right"]:
- ax.spines[sp].set_visible(False)
- ax.xaxis.grid(True, color="#EEE", lw=0.7, zorder=0); ax.set_axisbelow(True)
- leg = [Patch(facecolor=C_SIG, label="Significant (p < .05)"),
- Patch(facecolor=C_NS, label="Not significant"),
- Patch(facecolor=C_NT, label="Not testable / by construction")]
- ax.legend(handles=leg, loc="upper right", bbox_to_anchor=(1.0, 1.0),
- fontsize=7.5, framealpha=0.95, edgecolor="#CCC")
- fig.text(0.5, -0.04, "Effect-size metrics are not directly comparable across hypotheses.",
- ha="center", va="top", fontsize=8, color="#666", style="italic")
- fig.text(0.5, -0.09, "H6 (grey) is a by-construction check; H8 reports the t-test, not a Bayes factor.",
- ha="center", va="top", fontsize=8, color="#666", style="italic")
- _save(fig, "fig3_hypothesis_summary")
- # ============================================================================= FIG 5
- def fig5_loso_auc():
- """MAIN-TEXT Fig. 5 - per-subject LOSO AUC vs. permutation baseline. Per-subject
- real-label AUCs are reconstructed from the master table (same decoder as the
- stats stage); the permutation baseline is estimated per subject by refitting on
- label-shuffled training data. Uses loso_auc_per_subject.csv if present (columns
- subject_id, auc_real[, auc_perm])."""
- print("Fig 5: LOSO AUC per subject")
- df = _load_master()
- if LOSO.exists():
- d = pd.read_csv(LOSO)
- else:
- g = _proxy_groups_and_auc(df)
- if not g["per_subject_auc"]:
- print(" [skip] could not compute per-subject AUC from master table."); return
- # permutation baseline per subject, matching run_pipeline: hold the fitted
- # predictions fixed and permute the TEST labels N_PERM times, averaging the
- # resulting AUCs so each subject gets a stable ~0.5 baseline (not a single
- # high-variance shuffle).
- from sklearn.preprocessing import StandardScaler
- from sklearn.linear_model import LogisticRegression
- from sklearn.metrics import roc_auc_score
- N_PERM = 200
- cols, _ = _band_channels(df, "broadband")
- dd = df[df["condition"].isin(["perception", "imagination"])].dropna(subset=cols).copy()
- dd["y"] = (dd["condition"] == "imagination").astype(int)
- rng = np.random.default_rng(42)
- perm = {}
- for s in dd["subject_id"].unique():
- tr, te = dd[dd["subject_id"] != s], dd[dd["subject_id"] == s]
- if tr["y"].nunique() < 2 or te["y"].nunique() < 2:
- continue
- sc = StandardScaler().fit(tr[cols].values)
- clf = LogisticRegression(max_iter=1000, C=0.1, solver="lbfgs", random_state=42)
- clf.fit(sc.transform(tr[cols].values), tr["y"].values)
- proba = clf.predict_proba(sc.transform(te[cols].values))[:, 1]
- yt = te["y"].values
- aucs = []
- for _ in range(N_PERM):
- yp = rng.permutation(yt)
- if len(np.unique(yp)) == 2:
- aucs.append(roc_auc_score(yp, proba))
- if aucs:
- perm[s] = float(np.mean(aucs))
- d = pd.DataFrame({"subject_id": list(g["per_subject_auc"]),
- "auc_real": list(g["per_subject_auc"].values())})
- d["auc_perm"] = d["subject_id"].map(perm)
- d = d.sort_values("auc_real").reset_index(drop=True)
- x = np.arange(len(d))
- fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.5, 4.8), facecolor="white",
- gridspec_kw={"width_ratios": [2.6, 1]})
- mean_auc = d["auc_real"].mean()
- # CI shading band (from hypothesis_summary if available, else fixed headline CI)
- ci_lo, ci_hi = 0.775, 0.847
- ax1.axhspan(ci_lo, ci_hi, color=C_SIG, alpha=0.10, zorder=0, label="95% CI [0.775, 0.847]")
- ax1.bar(x - 0.2, d["auc_real"], width=0.4, color=C_SIG, label="Real labels (AUC)")
- if "auc_perm" in d.columns and d["auc_perm"].notna().any():
- ax1.bar(x + 0.2, d["auc_perm"], width=0.4, color="#E0922F", alpha=0.9, label="Permuted labels")
- ax1.axhline(0.50, color="#888", ls="--", lw=1, label="Chance (0.50)")
- ax1.axhline(mean_auc, color="#1F3864", ls=":", lw=1.3, label=f"Mean AUC = {mean_auc:.3f}")
- ax1.set_xticks([0, 9, 19, 29, 39, len(d) - 1])
- ax1.set_xticklabels([1, 10, 20, 30, 40, len(d)], fontsize=9)
- ax1.set_xlabel("Subject Index (sorted by real-label AUC)", fontsize=10)
- ax1.set_ylabel("LOSO-CV AUC", fontsize=10); ax1.set_ylim(0.3, 1.02)
- ax1.set_title("(A) Per-subject LOSO-CV classification performance", fontsize=10.5, fontweight="bold")
- ax1.legend(fontsize=7.5, loc="upper left", framealpha=0.95)
- for sp in ("top", "right"):
- ax1.spines[sp].set_visible(False)
- box_data, labels, colors = [d["auc_real"].dropna().values], ["Real\nlabels"], [C_SIG]
- if "auc_perm" in d.columns and d["auc_perm"].notna().any():
- box_data.append(d["auc_perm"].dropna().values); labels.append("Permuted\nlabels"); colors.append("#E0922F")
- bp = ax2.boxplot(box_data, labels=labels, patch_artist=True, widths=0.55,
- medianprops=dict(color="#222", lw=1.3))
- for patch, cc in zip(bp["boxes"], colors):
- patch.set_facecolor(cc); patch.set_alpha(0.75)
- for i, vals in enumerate(box_data):
- ax2.scatter(np.full(len(vals), i + 1) + np.random.uniform(-0.06, 0.06, len(vals)),
- vals, s=11, color="#333", alpha=0.45, zorder=3)
- ax2.axhline(0.50, color="#888", ls="--", lw=1)
- # significance annotation (paired t-test reported in main text)
- if len(box_data) == 2:
- ytop = 1.0
- ax2.plot([1, 1, 2, 2], [ytop, ytop + 0.02, ytop + 0.02, ytop], lw=1.1, color="#222")
- ax2.text(1.5, ytop + 0.025, "p < 10\u207b\u00b2\u2070", ha="center", va="bottom",
- fontsize=9, fontweight="bold")
- ax2.set_ylim(0.3, 1.10); ax2.set_ylabel("AUC", fontsize=10)
- ax2.set_title("(B) Distribution comparison", fontsize=10.5, fontweight="bold")
- for sp in ("top", "right"):
- ax2.spines[sp].set_visible(False)
- fig.suptitle("Leave-one-subject-out cross-validation (N = 46)", fontsize=12.5,
- fontweight="bold", y=1.02)
- _save(fig, "fig5_loso_auc")
- # ============================================================================= FIG S1
- def figS1_band_effects():
- """Exploratory per-band LZC effect sizes (two contrasts). Descriptive only; the
- formal H1/H2 tests use cluster permutation (reported null in main text)."""
- print("Fig S1: per-band LZC effect sizes (exploratory)")
- df = _load_master()
- panels = [("Imagination vs. Perception\n(Occipital ROI, paired Cohen's d)", "h1"),
- ("High- vs. Low-decoding Subjects\n(Whole brain, pooled Cohen's d)", "h2")]
- fig, axes = plt.subplots(1, 2, figsize=(13, 6.2), facecolor="white")
- for ax, (title, kind) in zip(axes, panels):
- ds, sigs = [], []
- for band in BANDS:
- cols, chans = _band_channels(df, band)
- if kind == "h1":
- roi = [c for c, ch in zip(cols, chans) if ch in OCC_ROI]
- if not roi:
- ds.append(np.nan); sigs.append(False); continue
- im = df[df["condition"] == "imagination"].groupby("subject_id")[roi].mean().mean(axis=1)
- pe = df[df["condition"] == "perception"].groupby("subject_id")[roi].mean().mean(axis=1)
- common = im.index.intersection(pe.index)
- d = _paired_d(im.loc[common].values, pe.loc[common].values)
- else:
- g = _proxy_groups_and_auc(df)
- imag = df[df["condition"] == "imagination"]
- hi = imag[imag["subject_id"].isin(g["high"])].groupby("subject_id")[cols].mean().mean(axis=1)
- lo = imag[imag["subject_id"].isin(g["low"])].groupby("subject_id")[cols].mean().mean(axis=1)
- d = _cohens_d(hi.values, lo.values)
- ds.append(d); sigs.append(abs(d) > 0.5 if not np.isnan(d) else False)
- xs = np.arange(len(BANDS))
- # highlight bands: broadband (green) and low-gamma (yellow)
- bb_i = BANDS.index("broadband"); lg_i = BANDS.index("low_gamma")
- ax.axvspan(bb_i - 0.5, bb_i + 0.5, color="#CDE6CD", alpha=0.5, zorder=0)
- ax.axvspan(lg_i - 0.5, lg_i + 0.5, color="#FCEFC0", alpha=0.6, zorder=0)
- colors = [(C_SIG if v < 0 else C_NS) if s else ("#9DB8D8" if (not np.isnan(v) and v < 0) else "#E8B4B2")
- for v, s in zip(ds, sigs)]
- ax.bar(xs, [0 if np.isnan(v) else v for v in ds], color=colors, edgecolor="white", zorder=2)
- for i, (v, s) in enumerate(zip(ds, sigs)):
- if not np.isnan(v):
- ax.text(i, v + (0.06 if v >= 0 else -0.06), f"{v:+.2f}" + ("*" if s else ""),
- ha="center", va="bottom" if v >= 0 else "top", fontsize=8.5,
- fontweight="bold" if s else "normal", zorder=4)
- ax.axhline(0, color="#333", lw=1, zorder=3)
- for h in (0.2, 0.5):
- ax.axhline(h, color="#bbb", ls="--" if h == 0.2 else ":", lw=0.7, zorder=1)
- ax.axhline(-h, color="#bbb", ls="--" if h == 0.2 else ":", lw=0.7, zorder=1)
- ax.set_xticks(xs)
- ax.set_xticklabels([BAND_LABELS[b].replace("\n", " ") for b in BANDS],
- fontsize=8, rotation=30, ha="right")
- ax.set_ylabel("Cohen's d", fontsize=10); ax.set_title(title, fontsize=11, fontweight="bold")
- # headroom so value labels don't clip
- vals_arr = [v for v in ds if not np.isnan(v)]
- if vals_arr:
- lo_y, hi_y = min(vals_arr + [0]), max(vals_arr + [0])
- ax.set_ylim(lo_y - 0.35, hi_y + 0.35)
- for sp in ("top", "right"):
- ax.spines[sp].set_visible(False)
- # shared legend
- from matplotlib.patches import Patch
- leg = [Patch(facecolor=C_SIG, label="|d| > 0.5, d < 0"),
- Patch(facecolor=C_NS, label="|d| > 0.5, d > 0"),
- Patch(facecolor="#9DB8D8", label="|d| \u2264 0.5, d < 0"),
- Patch(facecolor="#E8B4B2", label="|d| \u2264 0.5, d > 0"),
- Patch(facecolor="#CDE6CD", alpha=0.5, label="Broadband band"),
- Patch(facecolor="#FCEFC0", alpha=0.6, label="Low-gamma band")]
- fig.legend(handles=leg, loc="lower center", ncol=6, fontsize=8,
- framealpha=0.95, bbox_to_anchor=(0.5, -0.06))
- fig.suptitle("Exploratory Per-Band LZC Effect Sizes (N = 46)", fontsize=13, fontweight="bold", y=1.0)
- fig.text(0.5, -0.15,
- "Exploratory, descriptive Cohen's d (uncorrected); * marks |d| > 0.5\n"
- "(a descriptive threshold, not a significance test). Dashed line |d| = 0.2, dotted line |d| = 0.5.\n"
- "Distinct from the cluster-permutation tests used for the formal H1/H2 evaluation,\n"
- "which are reported as null in the main text.",
- ha="center", va="top", fontsize=9.5, color="#555", style="italic", linespacing=1.6)
- fig.tight_layout(rect=[0, 0.02, 1, 0.98])
- _save(fig, "figS1_band_effect_sizes")
- # ============================================================================= FIG S2
- def figS2_enhanced_topomaps():
- """SUPPLEMENT Fig. S2 - three-condition broadband LZC topography:
- perception, high-decoding imagery, low-decoding imagery. The decoding subgroups
- are reconstructed from the master table (median split on the LOSO decoding
- proxy), complementing the two-condition main-text Fig. 2."""
- print("Fig S2: enhanced topomaps (3 conditions)")
- df = _load_master()
- cols, chans = _band_channels(df, "broadband")
- g = _proxy_groups_and_auc(df)
- imag = df[df["condition"] == "imagination"]
- hi = imag[imag["subject_id"].isin(g["high"])][cols].mean().values
- lo = imag[imag["subject_id"].isin(g["low"])][cols].mean().values
- conds = [("Perception", df[df["condition"] == "perception"][cols].mean().values),
- ("High-decoding imagery", hi), ("Low-decoding imagery", lo)]
- fig, axes = plt.subplots(1, 3, figsize=(11.4, 4.0), facecolor="white")
- allv = np.concatenate([v for _, v in conds])
- vlim = (np.nanpercentile(allv, 2), np.nanpercentile(allv, 98))
- last = None
- for ax, (t, v) in zip(axes, conds):
- last = _try_mne_topomap(ax, v, chans, t, vlim=vlim)
- if last is not None:
- cb = fig.colorbar(last, ax=axes, fraction=0.022, pad=0.04)
- cb.set_label("Normalised broadband LZC", fontsize=9)
- fig.suptitle("Broadband LZC topography by decoding subgroup (N = 46)",
- fontsize=12.5, fontweight="bold", y=1.04)
- _save(fig, "figS2_enhanced_topomaps")
- # ============================================================================= FIG S3
- def figS3_spatial_clustering():
- """SUPPLEMENT Fig. S3 - three-panel cluster-permutation result for H4:
- (A) unthresholded imagination-minus-perception broadband-LZC difference;
- (B) difference with significant cluster channels marked;
- (C) the per-channel statistical (t) map.
- Reads cluster_results.npz (keys: 'ch_names', 'mask', optional 'tvals'). If the
- file is absent, panel A/C use the data difference and a paired t-map computed
- from the master table, and panel B notes the cluster file was unavailable."""
- print("Fig S3: spatial clustering (3 panels)")
- df = _load_master()
- cols, chans = _band_channels(df, "broadband")
- imag_sub = df[df["condition"] == "imagination"].groupby("subject_id")[cols].mean()
- perc_sub = df[df["condition"] == "perception"].groupby("subject_id")[cols].mean()
- common = imag_sub.index.intersection(perc_sub.index)
- diffmat = imag_sub.loc[common].values - perc_sub.loc[common].values # subj x ch
- diff = diffmat.mean(axis=0)
- # paired t per channel
- sd = diffmat.std(axis=0, ddof=1) + 1e-12
- tvals = diff / (sd / np.sqrt(len(common)))
- mask = None
- if CLUSTER.exists():
- z = np.load(CLUSTER, allow_pickle=True)
- if "ch_names" in z and "mask" in z:
- cmask = dict(zip([str(c) for c in z["ch_names"]], z["mask"]))
- mask = np.array([bool(cmask.get(ch, False)) for ch in chans])
- if "tvals" in z:
- tmap = dict(zip([str(c) for c in z["ch_names"]], z["tvals"]))
- tvals = np.array([tmap.get(ch, 0.0) for ch in chans])
- fig, axes = plt.subplots(1, 3, figsize=(12.5, 4.2), facecolor="white")
- dmax = np.nanpercentile(np.abs(diff), 98)
- # (A) difference
- imA = _try_mne_topomap(axes[0], diff, chans, "(A) Imagination \u2212 Perception", vlim=(-dmax, dmax))
- if imA is not None:
- fig.colorbar(imA, ax=axes[0], fraction=0.046, pad=0.04).set_label("\u0394 LZC", fontsize=8)
- # (B) difference + significant cluster channels
- imB = _try_mne_topomap(axes[1], diff, chans,
- "(B) Difference + significant cluster", vlim=(-dmax, dmax))
- if mask is not None and imB is not None:
- try:
- import mne
- info = mne.create_info(list(chans), 1000.0, "eeg")
- info.set_montage(mne.channels.make_standard_montage("standard_1020"),
- match_case=False, on_missing="ignore")
- pos = np.array([info["chs"][i]["loc"][:2] for i in range(len(chans))])
- axes[1].scatter(pos[mask, 0], pos[mask, 1], s=22, facecolors="none",
- edgecolors="k", linewidths=1.4, zorder=6)
- except Exception:
- pass
- elif mask is None:
- axes[1].text(0.5, -0.08, "cluster mask unavailable", transform=axes[1].transAxes,
- ha="center", fontsize=7, color="#999")
- # (C) statistical map
- tmax = np.nanpercentile(np.abs(tvals), 98)
- imC = _try_mne_topomap(axes[2], tvals, chans, "(C) Statistical (t) map", vlim=(-tmax, tmax))
- if imC is not None:
- fig.colorbar(imC, ax=axes[2], fraction=0.046, pad=0.04).set_label("t", fontsize=8)
- fig.suptitle("Spatial clustering of broadband LZC differences (H4)", fontsize=12.5,
- fontweight="bold", y=1.04)
- _save(fig, "figS3_spatial_clustering")
- # ============================================================================= FIG S4
- def figS4_band_magnitudes():
- """SUPPLEMENT Fig. S4 - LZC magnitude across the seven bands as a line plot:
- perception (solid) vs imagination (dashed), with shaded SEM bands."""
- print("Fig S4: LZC magnitudes across bands (line plot)")
- df = _load_master()
- conds = ["perception", "imagination"]
- means = {c: [] for c in conds}
- sems = {c: [] for c in conds}
- for band in BANDS:
- cols, _ = _band_channels(df, band)
- for c in conds:
- per_subj = df[df["condition"] == c].groupby("subject_id")[cols].mean().mean(axis=1)
- means[c].append(per_subj.mean())
- sems[c].append(per_subj.std(ddof=1) / np.sqrt(len(per_subj)))
- xs = np.arange(len(BANDS))
- fig, ax = plt.subplots(figsize=(10, 4.8), facecolor="white")
- styles = {"perception": dict(color="#2E5E9E", ls="-", marker="o", label="Perception"),
- "imagination": dict(color="#C0504D", ls="--", marker="s", label="Imagination")}
- for c in conds:
- m = np.array(means[c]); e = np.array(sems[c])
- ax.plot(xs, m, lw=2, markersize=6, **styles[c])
- ax.fill_between(xs, m - e, m + e, color=styles[c]["color"], alpha=0.18)
- ax.set_xticks(xs); ax.set_xticklabels([BAND_LABELS[b] for b in BANDS], fontsize=8)
- ax.set_ylabel("Mean normalised LZC", fontsize=10)
- ax.set_title("LZC magnitudes across frequency bands (N = 46)", fontsize=12, fontweight="bold")
- ax.legend(fontsize=9, loc="upper left")
- for sp in ("top", "right"):
- ax.spines[sp].set_visible(False)
- ax.grid(axis="y", color="#EEE", lw=0.7); ax.set_axisbelow(True)
- _save(fig, "figS4_band_magnitudes")
- # ============================================================================= FIG S5
- def figS5_lzc_hfd_correlation():
- """SUPPLEMENT Fig. S5 - scalp topomap of the per-channel Pearson correlation
- between broadband LZC and epoch-level HFD across trials (N = 46), per the
- caption. Correlation is computed across trials within each channel."""
- print("Fig S5: per-channel LZC-HFD correlation topomap")
- df = _load_master()
- _, lzc_chans = _band_channels(df, "broadband")
- hfd_cols, hfd_chans = _hfd_channels(df)
- common = [ch for ch in lzc_chans if ch in hfd_chans]
- if not common:
- print(f" [warn] no overlapping LZC/HFD channels (HFD cols found: {len(hfd_cols)}). "
- f"Check HFD column naming in the master table."); return
- rs = []
- for ch in common:
- x = df[f"LZC_broadband_{ch}"].values
- ycol = f"HFD_epoch_{ch}" if f"HFD_epoch_{ch}" in df.columns else f"HFD_{ch}"
- y = df[ycol].values
- m = np.isfinite(x) & np.isfinite(y)
- rs.append(np.corrcoef(x[m], y[m])[0, 1] if m.sum() > 2 else np.nan)
- rs = np.array(rs)
- fig, ax = plt.subplots(figsize=(5.4, 4.8), facecolor="white")
- vlim = (np.nanmin(rs), np.nanmax(rs))
- im = _try_mne_topomap(ax, rs, common, "", vlim=vlim)
- if im is not None:
- cb = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
- cb.set_label("Per-channel Pearson r (LZC vs HFD)", fontsize=9)
- ax.set_title(f"Channel-wise LZC\u2013HFD correlation\n"
- f"(mean r = {np.nanmean(rs):.3f}, range [{np.nanmin(rs):.3f}, {np.nanmax(rs):.3f}])",
- fontsize=11, fontweight="bold")
- fig.suptitle("Topography of LZC\u2013HFD correlation (N = 46)", fontsize=12.5,
- fontweight="bold", y=1.02)
- _save(fig, "figS5_lzc_hfd_correlation")
- # ============================================================================= FIG S6
- def figS6_shuffle_distribution():
- """Distribution of surrogate(shuffle)-normalised broadband LZC across subjects."""
- print("Fig S6: shuffle-normalised LZC distribution")
- df = _load_master()
- cols, _ = _band_channels(df, "broadband")
- df = df.copy(); df["bb_mean"] = df[cols].mean(axis=1)
- subj_means = df.groupby("subject_id")["bb_mean"].mean().sort_values()
- subjects = subj_means.index.tolist()
- fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.6), facecolor="white",
- gridspec_kw={"width_ratios": [2.2, 1]})
- data_by_subj = [df.loc[df["subject_id"] == s, "bb_mean"].values for s in subjects]
- bp = ax1.boxplot(data_by_subj, widths=0.6, patch_artist=True, showfliers=False,
- medianprops=dict(color="#1F3864", lw=1.3))
- for patch in bp["boxes"]:
- patch.set_facecolor("#9DB8D8"); patch.set_alpha(0.8); patch.set_edgecolor("#5A7CA8")
- ax1.axhline(1.0, color=C_NS, lw=1.2, ls="--", label="surrogate level (normalised = 1.0)")
- ax1.set_xticks([]); ax1.set_xlabel(f"Subjects (n = {len(subjects)}, sorted by mean)", fontsize=10)
- ax1.set_ylabel("Shuffle-normalised broadband LZC", fontsize=10)
- ax1.set_title("(A) Per-subject distribution", fontsize=10.5, fontweight="bold")
- ax1.legend(fontsize=8, loc="upper left"); [ax1.spines[s].set_visible(False) for s in ("top", "right")]
- allv = df["bb_mean"].values
- ax2.hist(allv, bins=40, color="#9DB8D8", edgecolor="#5A7CA8", alpha=0.85)
- ax2.axvline(1.0, color=C_NS, lw=1.2, ls="--", label="surrogate = 1.0")
- ax2.axvline(np.mean(allv), color="#1F3864", lw=1.2, label=f"mean = {np.mean(allv):.3f}")
- ax2.set_xlabel("Shuffle-normalised broadband LZC", fontsize=10); ax2.set_ylabel("Trials", fontsize=10)
- ax2.set_title("(B) Pooled distribution", fontsize=10.5, fontweight="bold")
- ax2.legend(fontsize=8); [ax2.spines[s].set_visible(False) for s in ("top", "right")]
- fig.suptitle("Distribution of surrogate (shuffle)-normalised LZC across subjects",
- fontsize=12.5, fontweight="bold", y=1.02)
- _save(fig, "figS6_shuffle_distribution")
- # ============================================================================= driver
- FIGS = {
- "fig2": fig2_topomaps, "fig3": fig3_hypothesis_summary, "fig5": fig5_loso_auc,
- "figS1": figS1_band_effects, "figS2": figS2_enhanced_topomaps,
- "figS3": figS3_spatial_clustering, "figS4": figS4_band_magnitudes,
- "figS5": figS5_lzc_hfd_correlation, "figS6": figS6_shuffle_distribution,
- }
- def main():
- ap = argparse.ArgumentParser(description="Regenerate all data-driven manuscript figures.")
- ap.add_argument("--only", nargs="+", choices=list(FIGS), help="Subset of figures to draw.")
- ap.add_argument("--outdir", default=None, help="Override output directory.")
- args = ap.parse_args()
- global OUT
- if args.outdir:
- OUT = Path(args.outdir)
- todo = args.only or list(FIGS)
- print(f"Output directory: {OUT}\nFigures: {', '.join(todo)}")
- print("(Fig. 1 and Fig. 4 are schematics, produced externally, not here.)\n")
- for key in todo:
- try:
- FIGS[key]()
- except FileNotFoundError as e:
- print(f" [skip {key}] {e}")
- except Exception as e:
- print(f" [error {key}] {type(e).__name__}: {e}")
- print("\nDone.")
- if __name__ == "__main__":
- main()
make_all_figures.py at commit 9243f6c, under MIT · at the source
Overview
- Department of Electrical and Computer Engineering, Faculty of Engineering, University of Porto, Porto, Portugal
- CISTER/ISEP - Research Centre in Real-Time and Embedded Computing Systems, School of Engineering, Porto, Portugal
- Faculdade de Engenharia da Universidade do Porto, Rua Dr. Roberto Frias, 4200 – 465 Porto, Portugal
- PhD Program in Health Data Science, Faculty of Medicine, University of Porto, Porto, Portugal
Abstract
Visual mental imagery is the process of reconstructing perceptual experience without sensory input. How the brain performs this process is poorly understood, particularly from the perspective of conventional linear EEG analysis. This study aims to evaluate if the two non-linear EEG complexity measures—Lempel-Ziv Complexity (LZC) and Higuchi Fractal Dimension (HFD)—can differentiate between perception and imagination and if they can be used as objective indices of neural separability of mental imagery. LZC and HFD were extracted from 62 scalp EEG channels in 46 healthy adults performing the PerceiveImagine paradigm (Li and Fan 2024), after wideband Picard ICA decomposition (1–200 Hz), which was used to make residual artefacts explicit rather than to remove components, with edge-channel EMG monitoring for artefact control. Statistical analyses included cluster-based permutation testing (Maris and Oostenveld 2007), Hotelling T², and leave-one-subject-out cross-validation (LOSO-CV). Broadband LZC topography differed between perception and imagination (cluster p = 0.005; Hotelling F = 3.08, p = 0.002, V = 0.28). LOSO-CV classification reached AUC = 0.811 (95% CI: [0.775, 0.847]). The classifier’s AUC exceeded a label-permuted baseline by a wide margin (t(45) = 16.30, p < 0.001). The a priori low-gamma LZC hypothesis was not supported, with no significant difference at the occipital ROI (p = 1.0, d = − 0.13). At the scalp level, EEG complexity features are associated with a topographic redistribution rather than a global magnitude change: imagery shows a relative posterior-to-frontal shift in broadband LZC. Because these patterns are scalp-recorded, they characterise the spatial distribution of complexity rather than establishing the underlying cortical sources or the direction of information flow. Objective decoding-confidence labels provide a more usable training signal than the (invariant) self-report available in this dataset, indicating future potential for imagery-quality indexing rather than immediate translational readiness.
Supplementary Information: The online version contains supplementary material available at https://
Reproduced under the paper's license (CC BY), from the paper cited above.
Repository
Its files are read in the Code ↔ Paper reader above, with 23 matches between paragraphs and lines of code.
jabarrick/LZC-HFD-hypothesis
9243f6c8441c43628b7d348b4b45e5fb2157a67b, 1 June 2026Availability: 1 check, the latest on 27 September 2026: the link answers
- 27 September 2026: the link answers
34 files
- eeg_imagination/
aggregate_features.py , Python, 65 lines - eeg_imagination/
compute_feature_set_aucs , Python, 165 lines, 1 match.py - eeg_imagination/
config.py , Python, 97 lines, 2 matches - eeg_imagination/
features/ , Python, 1 line__init__.py - eeg_imagination/
features/ , Python, 228 linesdecoding.py - eeg_imagination/
features/ , Python, 191 lines, 1 matchhfd.py - eeg_imagination/
features/ , Python, 227 lines, 1 matchlzc.py - eeg_imagination/
ground_truth/ , Python, 1 line__init__.py - eeg_imagination/
ground_truth/ , Python, 173 lineslabels.py - eeg_imagination/
make_all_figures.py , Python, 746 lines, 6 matches - eeg_imagination/
make_fig_shuffle_distrib , Python, 96 lines, 1 matchution.py - eeg_imagination/
ml/ , Python, 1 line__init__.py - eeg_imagination/
ml/ , Python, 215 lines, 1 matchiqi.py - eeg_imagination/
ml/ , Python, 211 linesshap_analysis.py - eeg_imagination/
preprocessing/ , Python, 1 line__init__.py - eeg_imagination/
preprocessing/ , Python, 96 linesdipole_audit.py - eeg_imagination/
preprocessing/ , Python, 109 lines, 1 matchemg_monitor.py - eeg_imagination/
preprocessing/ , Python, 128 lines, 2 matchesica.py - eeg_imagination/
reproduce.py , Python, 127 lines - eeg_imagination/
run_pipeline.py , Python, 617 lines - eeg_imagination/
scripts/ , Python, 24 linesaggregate_features.py - eeg_imagination/
scripts/ , Python, 40 linesextract_erp.py - eeg_imagination/
scripts/ , Python, 25 linesextract_psd.py - eeg_imagination/
stats_analysis/ , Python, 1 line__init__.py - eeg_imagination/
stats_analysis/ , Python, 651 lines, 5 matcheshypotheses.py - eeg_imagination/
tests/ , Python, 1 line__init__.py - eeg_imagination/
tests/ , Python, 257 linestest_pipeline_integratio n.py - eeg_imagination/
utils/ , Python, 1 line__init__.py - eeg_imagination/
utils/ , Python, 270 lines__pycache__/ io.py - eeg_imagination/
utils/ , Python, 277 lines, 1 matchio.py - eeg_imagination/
utils/ , Python, 290 lineslogging_utils.py - eeg_imagination/
verify_emg_flagging.py , Python, 318 lines, 1 match - eeg_imagination/
verify_sensitivity.py , Python, 237 lines - LICENSE, License, 21 lines
Tracing map
Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.
What the map holds:
- 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
- 33 scripts, each with its path and the digest of its content;
- 23 matches between paragraphs of the paper and lines of the code (method lexical-v1);
- neither the text of the paper nor the code itself.
Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.
Data
Datasets cited
- doi:10.18112/
openneuro.ds005697.v1.0. , at OpenNeuro; found in the references2
Data Availability
No datasets were generated or analysed during the current study.
Reproduced under the paper's license (CC BY), from the paper cited above.
Versions
The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.
Version 2, 28 September 2026
- Publisher: n/a → Springer Science+Business Media
Version 1, 27 September 2026: the first record
Recorded: type, language, journal, volume, issue, pages, dates, 2 authors, 6 keywords, 11 MeSH terms, 1 funder, 26 references.
Cite
This paper
Gao, Y., & Diniz, J. M. (2026). Topographic Reorganization of EEG Complexity During Visual Mental Imagery: Insights from Lempel-Ziv Complexity in High-Density EEG. Brain topography, 39(5), 82. https://
BibTeX
@article{gao2026topograp
author = {Gao, Yu and Diniz, José Miguel},
title = {{Topographic Reorganization of EEG Complexity During Visual Mental Imagery: Insights from Lempel-Ziv Complexity in High-Density EEG}},
journal = {Brain topography},
year = {2026},
month = jul,
volume = {39},
number = {5},
pages = {82},
publisher = {Springer Science+Business Media},
issn = {0896-0267},
doi = {10.1007/
url = {https://
pmid = {42479103},
pmcid = {PMC13388782}
}
RIS
TY - JOUR
AU - Gao, Yu
AU - Diniz, José Miguel
TI - Topographic Reorganization of EEG Complexity During Visual Mental Imagery: Insights from Lempel-Ziv Complexity in High-Density EEG
T2 - Brain topography
J2 - Brain Topogr
PY - 2026
DA - 2026/
VL - 39
IS - 5
SP - 82
SN - 0896-0267
PB - Springer Science+Business Media
DO - 10.1007/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.1007/
"type": "article-journal",
"title": "Topographic Reorganization of EEG Complexity During Visual Mental Imagery: Insights from Lempel-Ziv Complexity in High-Density EEG",
"container-title": "Brain topography",
"author": [
{
"family": "Gao",
"given": "Yu"
},
{
"family": "Diniz",
"given": "José Miguel"
}
],
"container-title-short":
"volume": "39",
"issue": "5",
"page": "82",
"DOI": "10.1007/
"PMID": "42479103",
"PMCID": "PMC13388782",
"ISSN": "0896-0267",
"publisher": "Springer Science+Business Media",
"URL": "https://
"language": "en",
"issued": {
"date-parts": [
[
2026,
7,
21
]
]
}
}
The tracing map gets a citation of its own once an author has validated it and it has a DOI.
Similar papers
The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.
- [1] doi:10.1016/j.nicl.2025.103760 [code]
- Event-related potential markers of subjective cognitive decline and mild cognitive impairment during a sustained visuo-attentive task.Journal: NeuroImage. ClinicalIn common: ICLabel, XGBoost, Pingouin, 7 other tools, EEG
- [2] doi:10.1162/imag.a.1269 [code]
- From early to contemporary normative modeling: Mapping individual differences in neurophysiological signals.Journal: Imaging neuroscience (Cambridge, Mass.)In common: ICLabel, Pingouin, MNE-Python, 6 other tools, EEG, 1 reference
- [3] doi:10.1038/s41598-024-81618-1 [code]
- Variations of autonomic arousal mediate the reportability of mind blanking occurrences.Journal: Scientific reportsIn common: ICLabel, SHAP, MNE-Python, 6 other tools, EEG, cognitive
- [4] doi:10.1016/j.ebiom.2026.106375 [code]
- Brainwaves under medication: revealing class-specific neural signatures of psychotropic medication from 24,000 EEGs.Journal: EBioMedicineIn common: ICLabel, MNE-Python, statsmodels, 4 other tools, EEG, 2 references
- [5] doi:10.1002/ctm2.70032 [code]
- Structural inequality and temporal brain dynamics across diverse samples.Journal: Clinical and translational medicineIn common: XGBoost, statsmodels, scikit-learn, 4 other tools, EEG, cognitive, 2 references
- [6] doi:10.3390/brainsci14090901 [code]
- Tai Chi Practice Buffers Aging Effects in Functional Brain Connectivity.Journal: Brain sciencesIn common: ICLabel, Numba, MNE-Python, 6 other tools, EEG
- [7] doi:10.1016/j.neuroimage.2022.119595 [code]
- Mixtures of large-scale dynamic functional brain network modes.Journal: NeuroImageIn common: ICLabel, Numba, MNE-Python, 6 other tools, cognitive
- [8] doi:10.1097/j.pain.0000000000004044 [code]
- No effect of rhythmic visual stimulation on experimental pain perception.Journal: PainIn common: ICLabel, Pingouin, MNE-Python, 5 other tools, EEG, cognitive
- [9] doi:10.1038/s42003-026-09825-2 [code]
- Normative modeling of MEG brain oscillations across the human lifespan.Journal: Communications biologyIn common: ICLabel, Pingouin, MNE-Python, 6 other tools
- [10] doi:10.1038/s42003-026-10957-8 [code]
- Brain defence by the extracellular matrix protein Cochlin.Journal: Communications biologyIn common: SHAP, XGBoost, Numba, 6 other tools
Contribute
The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.
Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.
Claim this paper
Correct its record
Say what each link of this record is, remove the ones that are not the paper's, add the ones that are missing. The correction becomes a new version of the record, in its Versions section.
Validate its tracing map
You validate the map as this page shows it: 1 repository of the authors' code, each at its verified commit and with its license, 33 scripts, and 23 matches between paragraphs and code (see the Code and Map sections). It then receives a DOI on Zenodo, with you (your ORCID iD) and OSCR as its creators; the code itself is not deposited.
The map's fingerprint: sha256:9905769f28b16e63…
Add the badge to the code's README
If you are an author or a maintainer of this paper's code, you can add this badge. It says what OSCR knows of the paper (its code, its validated tracing map) and links the code to this page. Paste one of these snippets under the README's title. Keep the two marks around it, so that the badge can be replaced in place and is never added twice. OSCR changes nothing in your repository.
Markdown
<!-- oscr-badge:start -->
[](https://openscicode.org/badge/doi/10.1007/s10548-026-01238-y)
<!-- oscr-badge:end -->reStructuredText
.. oscr-badge:start
.. image:: https://openscicode.org/badge/doi/10.1007/s10548-026-01238-y.svg
:target: https://openscicode.org/badge/doi/10.1007/s10548-026-01238-y
:alt: OSCR
.. oscr-badge:endHTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.1007/s10548-026-01238-y"><img src="https://openscicode.org/badge/doi/10.1007/s10548-026-01238-y.svg" alt="OSCR"></a>
<!-- oscr-badge:end -->On GitHub, open the README, choose Edit (the pencil), paste the snippet under the title, then "Commit changes".
If you choose to, you can have the badge kept up to date for you, with oscr badge --write from the command line or with the GitHub Action in your repository's workflows. Every other form and option (a card, AsciiDoc, LaTeX, shields.io) is on the badge page.
Request its removal
To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).
Discussion, reproductions, activity
Discussion: code errors and mismatches between the code and the paper about this paper and its code, from readers and its authors, beside the paper and its tracing map.
Report a mismatch between the code and the paper · Report a code error (signed in)
Reproductions: reports from readers who ran the authors' code and did not get the paper's result, what they ran, with which environment, commit and data.
Report a reproduction failure (signed in)
Versions of its code: the releases of its code tied to a version of this paper (the preprint, the accepted manuscript, the version of record…), each with the tracing map versioned with it.
Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.
