OSCR

Topographic Reorganization of EEG Complexity During Visual Mental Imagery: Insights from Lempel-Ziv Complexity in High-Density EEG.

Code ↔ Paper

23 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 23 matches · 2 of them tie a paragraph to a whole file, not to given lines: weak matches, whose lines are not tinted
  1. [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
  2. [2] § Materials and Methods › Preprocessing ↔ eeg_imagination/preprocessing/ica.py, lines 37–128 · score 0.94 · notch filtered, ICLabel, muscle artefact, 1–200 Hz, Picard ICA, wideband ICA
  3. [3] § Results › Hypothesis Testing ↔ eeg_imagination/stats_analysis/hypotheses.py, lines 358–405 · score 0.83 · Wilcoxon rank sum, rank biserial, n_high, n_low, decoding metric, Shapiro
  4. [4] § Materials and Methods › Dual Ground Truth ↔ eeg_imagination/make_all_figures.py, lines 349–441 · score 0.81 · logistic regression, StandardScaler, LOSO CV, subject AUC, solver, ratio
  5. [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
  6. [6] § Results › Relationship Between LZC and HFD, and Incremental Value ↔ eeg_imagination/compute_feature_set_aucs.py, lines 1–49 · score 0.75 · multi band LZC, full multi band, combined LZC, LOSO CV, iii, iv
  7. [7] § Materials and Methods › Dual Ground Truth ↔ eeg_imagination/ml/iqi.py, lines 66–186 · score 0.74 · feature matrix, StandardScaler, discriminate, fold, quality, probability
  8. [8] § Materials and Methods › Lempel-Ziv Complexity ↔ eeg_imagination/features/lzc.py, lines 75–98 · score 0.74 · Fisher Yates, lzc_norm, Shuffle normalization, normalised LZC
  9. [9] § Materials and Methods › Preprocessing ↔ eeg_imagination/preprocessing/emg_monitor.py, lines 7–80 · score 0.70 · 80–150 Hz, edge channel, high gamma, Welch, EMG, flagged
  10. [10] § Materials and Methods › Data Acquisition ↔ eeg_imagination/preprocessing/ica.py, lines 37–128 · score 0.70 · notch filtered, 1–200 Hz, Picard ICA, bandpass, artefacts, preprocessing
  11. [11] § Results › Topographic Analysis ↔ eeg_imagination/make_all_figures.py, lines 1–55 · score 0.68 · LZC magnitudes, broadband LZC topographic, low decoding, S3, subsets, maps
  12. [12] § Materials and Methods › Lempel-Ziv Complexity ↔ eeg_imagination/make_fig_shuffle_distribution.py, lines 1–26 · score 0.65 · lzc_norm, Shuffle normalization, normalised LZC, surrogate
  13. [13] § Materials and Methods › Statistical Analysis ↔ eeg_imagination/stats_analysis/hypotheses.py, lines 290–340 · score 0.64 · Hotelling T2, LZC topography differs, multivariate, PCA, components, H4
  14. [14] § Materials and Methods › Epoching ↔ eeg_imagination/utils/io.py, lines 189–268 · score 0.64 · numeric prefix, events.tsv, keyword, baseline, classifier, Epochs
  15. [15] § Results › Hypothesis Testing ↔ eeg_imagination/stats_analysis/hypotheses.py, lines 290–340 · score 0.64 · Pseudo Pillai, Hotelling T2, multivariate, PCA, H4, cluster
  16. [16] § Results › Relationship Between LZC and HFD, and Incremental Value ↔ eeg_imagination/make_all_figures.py, lines 1–55 · score 0.62 · LZC HFD correlation, broadband LZC, S1, S2, H4, baseline
  17. [17] § Results › Hypothesis Testing ↔ eeg_imagination/verify_emg_flagging.py, lines 46–122 · score 0.61 · Wilcoxon rank sum, rank biserial, rb, H6, Hypothesis
  18. [18] § Materials and Methods › Lempel-Ziv Complexity ↔ eeg_imagination/make_all_figures.py, lines 57–72 · score 0.57 · high gamma, low gamma, beta, theta, delta, alpha
  19. [19] § Results › Hypothesis Testing ↔ eeg_imagination/make_all_figures.py, lines 444–518 · score 0.57 · occipital ROI, paired Cohen, low gamma, H1, cluster, permutation
  20. [20] § Materials and Methods › Statistical Analysis ↔ eeg_imagination/stats_analysis/hypotheses.py, lines 247–289 · score 0.55 · y_subj_raw, Frontal, model, H3, interaction, HFD
  21. [21] § Materials and Methods › Statistical Analysis ↔ eeg_imagination/stats_analysis/hypotheses.py, lines 358–405 · score 0.54 · rank biserial, decoding metric, H6, accuracy
  22. [22] § Materials and Methods › Dual Ground Truth ↔ eeg_imagination/make_all_figures.py, lines 110–145 · score 0.52 · decoding probability, low decoding, split, median, Proxy
  23. [23] § Materials and Methods › Higuchi Fractal Dimension ↔ eeg_imagination/features/hfd.py, lines 6–56 · score 0.51 · NumPy, polyfit, vectorized, log, Higuchi, HFD

Paper

Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Python · 746 lines · 38 KB · MIT · 6 matches

  1. """
  2. make_all_figures.py
  3. ===================================================================
  4. Single entry point that regenerates every data-driven figure in the
  5. manuscript and supplement, reading ONLY from real pipeline outputs.
  6. No fabricated/placeholder values are used anywhere.
  7. Figures produced
  8. ----------------
  9. Main text
  10. Fig. 2 Group-averaged broadband LZC topographic maps (perception
  11. vs. imagination, with high-/low-decoding imagery subsets)
  12. Fig. 3 Hypothesis-testing summary (H1-H8)
  13. Fig. 5 Leave-one-subject-out AUC per subject vs. permutation baseline
  14. Supplement
  15. Fig. S1 Per-band LZC effect sizes (exploratory)
  16. Fig. S2 Enhanced LZC topographic maps (3 conditions)
  17. Fig. S3 Spatial clustering of broadband LZC differences
  18. Fig. S4 LZC magnitudes across frequency bands
  19. Fig. S5 Channel-wise LZC-HFD correlation
  20. Fig. S6 Distribution of surrogate(shuffle)-normalised LZC across subjects
  21. NOTE
  22. Fig. 1 (preprocessing pipeline schematic) and Fig. 4 (framework
  23. schematic) are conceptual diagrams, not data plots; they are produced
  24. in vector-graphics software (e.g. PowerPoint / Inkscape) and are not
  25. generated here.
  26. Inputs (all under outputs/)
  27. outputs/results/master_feature_table.csv (LZC_*, HFD_*, condition, subject_id)
  28. outputs/results/hypothesis_summary.csv (H1-H8 results)
  29. outputs/results/loso_auc_per_subject.csv (optional: per-subject AUC; see Fig 5)
  30. outputs/results/cluster_results.npz (optional: H4 cluster mask; see Fig S3)
  31. Usage
  32. python make_all_figures.py # all figures
  33. python make_all_figures.py --only fig3 figS6
  34. python make_all_figures.py --outdir outputs/figures
  35. Outputs: PNG (300 dpi) + SVG in outputs/figures/.
  36. """
  37. import argparse
  38. import math
  39. import warnings
  40. from pathlib import Path
  41. import numpy as np
  42. import pandas as pd
  43. import matplotlib
  44. matplotlib.use("Agg")
  45. import matplotlib.pyplot as plt
  46. from matplotlib.patches import Patch
  47. warnings.filterwarnings("ignore")
  48. # ----------------------------------------------------------------------------- config
  49. RESULTS = Path("outputs/results")
  50. MASTER = RESULTS / "master_feature_table.csv"
  51. HYP = RESULTS / "hypothesis_summary.csv"
  52. LOSO = RESULTS / "loso_auc_per_subject.csv"
  53. CLUSTER = RESULTS / "cluster_results.npz"
  54. OUT = Path("outputs/figures")
  55. BANDS = ["broadband", "delta", "theta", "alpha", "beta", "low_gamma", "high_gamma"]
  56. BAND_LABELS = {
  57. "broadband": "Broadband\n1-200 Hz", "delta": "Delta\n1-4 Hz", "theta": "Theta\n4-8 Hz",
  58. "alpha": "Alpha\n8-13 Hz", "beta": "Beta\n13-30 Hz", "low_gamma": "Low-gamma\n30-60 Hz",
  59. "high_gamma": "High-gamma\n60-150 Hz",
  60. }
  61. OCC_ROI = ["Oz", "O1", "O2", "POz", "PO3", "PO4"]
  62. C_SIG, C_NS, C_NT = "#2E5E9E", "#C0504D", "#9E9E9E"
  63. # Standard 62-channel layout (64-ch 10-20 minus AF7/AF8, plus M1/M2)
  64. MONTAGE62 = ['Fp1','Fpz','Fp2','AF3','AF4','F7','F5','F3','F1','Fz','F2','F4','F6','F8',
  65. 'FC5','FC3','FC1','FCz','FC2','FC4','FC6','FT7','FT8','T7','C5','C3','C1','Cz',
  66. 'C2','C4','C6','T8','TP7','CP5','CP3','CP1','CPz','CP2','CP4','CP6','TP8',
  67. 'P7','P5','P3','P1','Pz','P2','P4','P6','P8','PO7','PO5','PO3','POz','PO4',
  68. 'PO6','PO8','O1','Oz','O2','M1','M2']
  69. # ----------------------------------------------------------------------------- helpers
  70. def _load_master():
  71. if not MASTER.exists():
  72. raise FileNotFoundError(f"Missing {MASTER}. Run the pipeline 'features' stage first.")
  73. return pd.read_csv(MASTER)
  74. def _band_channels(df, band):
  75. """LZC columns for a band, returning (col_names, channel_names)."""
  76. cols = [c for c in df.columns if c.startswith(f"LZC_{band}_")]
  77. chans = [c.replace(f"LZC_{band}_", "") for c in cols]
  78. return cols, chans
  79. def _hfd_channels(df):
  80. """HFD epoch-level columns, returning (col_names, channel_names).
  81. The pipeline names these HFD_epoch_<ch> (see run_pipeline / features module)."""
  82. cols = [c for c in df.columns if c.startswith("HFD_epoch_")]
  83. if not cols: # fallback to any HFD_<ch> if epoch-level not present
  84. cols = [c for c in df.columns if c.startswith("HFD_") and len(c) > 4]
  85. chans = [c.replace("HFD_epoch_", "").replace("HFD_", "") for c in cols]
  86. return cols, chans
  87. # cache so the LOSO recompute runs once even if several figures need it
  88. _PROXY_CACHE = {}
  89. def _proxy_groups_and_auc(df):
  90. """Reconstruct, from the master table, the proxy decoding groups and per-subject
  91. LOSO AUC that the stats stage computes but does not write to disk. Mirrors
  92. run_pipeline: a broadband-LZC logistic-regression decoder of perception-vs-
  93. imagination is run leave-one-subject-out; each subject's mean decoding probability
  94. becomes the objective proxy; a median split defines high-/low-decoding subgroups.
  95. Returns dict with: per_subject_auc {sid: auc}, proxy {sid: mean_prob},
  96. high (set), low (set), median (float).
  97. """
  98. if _PROXY_CACHE:
  99. return _PROXY_CACHE
  100. from sklearn.preprocessing import StandardScaler
  101. from sklearn.linear_model import LogisticRegression
  102. from sklearn.metrics import roc_auc_score
  103. cols, _ = _band_channels(df, "broadband")
  104. d = df[df["condition"].isin(["perception", "imagination"])].dropna(subset=cols).copy()
  105. d["y"] = (d["condition"] == "imagination").astype(int)
  106. per_auc, proxy = {}, {}
  107. for s in d["subject_id"].unique():
  108. tr, te = d[d["subject_id"] != s], d[d["subject_id"] == s]
  109. if tr["y"].nunique() < 2 or len(te) == 0:
  110. continue
  111. sc = StandardScaler().fit(tr[cols].values)
  112. clf = LogisticRegression(max_iter=1000, C=0.1, solver="lbfgs", random_state=42)
  113. clf.fit(sc.transform(tr[cols].values), tr["y"].values)
  114. p = clf.predict_proba(sc.transform(te[cols].values))[:, 1]
  115. proxy[s] = float(np.mean(p))
  116. if te["y"].nunique() == 2:
  117. per_auc[s] = float(roc_auc_score(te["y"].values, p))
  118. med = float(np.median(list(proxy.values()))) if proxy else 0.5
  119. high = {s for s, v in proxy.items() if v >= med}
  120. low = {s for s, v in proxy.items() if v < med}
  121. _PROXY_CACHE.update(dict(per_subject_auc=per_auc, proxy=proxy, high=high, low=low, median=med))
  122. return _PROXY_CACHE
  123. def _cohens_d(a, b):
  124. a, b = np.asarray(a), np.asarray(b)
  125. na, nb = len(a), len(b)
  126. if na < 2 or nb < 2:
  127. return np.nan
  128. sp = np.sqrt(((na - 1) * np.var(a, ddof=1) + (nb - 1) * np.var(b, ddof=1)) / (na + nb - 2)) + 1e-12
  129. return (np.mean(a) - np.mean(b)) / sp
  130. def _paired_d(a, b):
  131. a, b = np.asarray(a), np.asarray(b)
  132. diff = a - b
  133. return np.mean(diff) / (np.std(diff, ddof=1) + 1e-12)
  134. def _try_mne_topomap(ax, values, ch_names, title, vlim=None):
  135. """Plot a scalp topomap with MNE if available + montage positions exist; else a
  136. scatter-based fallback. Returns True if MNE topomap was used."""
  137. try:
  138. import mne
  139. info = mne.create_info(list(ch_names), sfreq=1000.0, ch_types="eeg")
  140. montage = mne.channels.make_standard_montage("standard_1020")
  141. info.set_montage(montage, match_case=False, on_missing="ignore")
  142. im, _ = mne.viz.plot_topomap(np.asarray(values), info, axes=ax, show=False,
  143. cmap="RdBu_r", contours=4,
  144. vlim=(vlim if vlim else (None, None)))
  145. ax.set_title(title, fontsize=10)
  146. return im
  147. except Exception as e:
  148. ax.text(0.5, 0.5, f"(topomap needs MNE + montage)\n{title}", ha="center",
  149. va="center", fontsize=8, transform=ax.transAxes)
  150. ax.set_axis_off()
  151. return None
  152. def _sup(n):
  153. m = {"-": "\u207b", "0": "\u2070", "1": "\u00b9", "2": "\u00b2", "3": "\u00b3",
  154. "4": "\u2074", "5": "\u2075", "6": "\u2076", "7": "\u2077", "8": "\u2078", "9": "\u2079"}
  155. return "".join(m.get(c, c) for c in str(n))
  156. def _fmt_p(p):
  157. if p is None or (isinstance(p, float) and math.isnan(p)):
  158. return ""
  159. if p <= 0:
  160. return "p < 10\u207b\u00b2\u2070"
  161. if p < 1e-3:
  162. e = int(math.floor(math.log10(p)))
  163. return f"p < 10{_sup(e + 1)}"
  164. if p >= 0.9995:
  165. return "p = 1.0"
  166. return f"p = {p:.3f}"
  167. def _save(fig, name):
  168. OUT.mkdir(parents=True, exist_ok=True)
  169. fig.savefig(OUT / f"{name}.png", dpi=300, bbox_inches="tight", facecolor="white")
  170. fig.savefig(OUT / f"{name}.svg", bbox_inches="tight", facecolor="white")
  171. plt.close(fig)
  172. print(f" saved {OUT}/{name}.png (+.svg)")
  173. # ============================================================================= FIG 2
  174. def fig2_topomaps():
  175. """MAIN-TEXT Fig. 2 - the core, proxy-independent contrast: group-averaged
  176. broadband LZC topography for perception vs. imagination (two conditions plus
  177. their difference map). The proxy-based high-/low-decoding subdivision is shown
  178. separately in Supplementary Fig. S2, so the two figures do not duplicate."""
  179. print("Fig 2: broadband LZC topomaps (perception vs imagination)")
  180. df = _load_master()
  181. cols, chans = _band_channels(df, "broadband")
  182. perc = df[df["condition"] == "perception"][cols].mean().values
  183. imag = df[df["condition"] == "imagination"][cols].mean().values
  184. diff = imag - perc
  185. panels = [("Perception", perc), ("Imagination", imag), ("Imagination \u2212 Perception", diff)]
  186. fig, axes = plt.subplots(1, 3, figsize=(10.2, 3.6), facecolor="white")
  187. cv = np.concatenate([perc, imag])
  188. vlim_cond = (np.nanpercentile(cv, 2), np.nanpercentile(cv, 98))
  189. dmax = np.nanpercentile(np.abs(diff), 98)
  190. im_cond = im_diff = None
  191. for ax, (title, vals) in zip(axes, panels):
  192. if title.startswith("Imagination \u2212"):
  193. im_diff = _try_mne_topomap(ax, vals, chans, title, vlim=(-dmax, dmax))
  194. else:
  195. im_cond = _try_mne_topomap(ax, vals, chans, title, vlim=vlim_cond)
  196. if im_cond is not None:
  197. cb = fig.colorbar(im_cond, ax=axes[:2], fraction=0.025, pad=0.04, location="bottom")
  198. cb.set_label("Normalised LZC", fontsize=9)
  199. if im_diff is not None:
  200. cb2 = fig.colorbar(im_diff, ax=axes[2], fraction=0.046, pad=0.04, location="bottom")
  201. cb2.set_label("\u0394 LZC (imagination \u2212 perception)", fontsize=9)
  202. fig.suptitle("Group-averaged broadband LZC: perception vs. imagination (N = 46)",
  203. fontsize=12.5, fontweight="bold", y=1.04)
  204. _save(fig, "fig2_lzc_topomaps")
  205. # ============================================================================= FIG 3
  206. def fig3_hypothesis_summary():
  207. """Horizontal-bar summary of H1-H8. H6 grey (by-construction); H8 t-test, no BF."""
  208. print("Fig 3: hypothesis summary")
  209. if not HYP.exists():
  210. raise FileNotFoundError(f"Missing {HYP}. Run the 'stats' stage first.")
  211. df = pd.read_csv(HYP).set_index("hypothesis_id").reindex(
  212. ["H1", "H2", "H3", "H4", "H5", "H6", "H7", "H8"]).reset_index()
  213. n = len(df)
  214. n_sub = int(pd.to_numeric(df["n_subjects"], errors="coerce").replace(0, np.nan).dropna().max())
  215. rows = []
  216. for _, r in df.iterrows():
  217. hid = r["hypothesis_id"]
  218. lbl = str(r.get("effect_size_label", "")).strip()
  219. es = r.get("effect_size", np.nan)
  220. ts = r.get("test_statistic", np.nan)
  221. pv = r.get("p_value", np.nan)
  222. sig = bool(r.get("significant")) if not pd.isna(r.get("significant")) else False
  223. note = str(r.get("notes", ""))
  224. nt = (hid == "H7") or (pd.isna(es) and pd.isna(ts))
  225. if hid == "H6":
  226. rows.append(dict(hid=hid, bar=0.0, label="r_rb = \u22121.0 (by construction)",
  227. state="bc", is_bf=False)); continue
  228. if hid == "H8":
  229. rows.append(dict(hid=hid, bar=None,
  230. label="AUC \u226b permutation baseline (t(45)=16.30, p<0.001)",
  231. state=("sig" if sig else "ns"), is_bf=True)); continue
  232. if nt:
  233. rows.append(dict(hid=hid, bar=0.0, label="Not testable", state="nt", is_bf=False)); continue
  234. state = "sig" if sig else "ns"
  235. if "AUC" in lbl:
  236. import re
  237. m = re.search(r"\[([\d.]+),\s*([\d.]+)\]", note)
  238. ci = f" [{m.group(1)}, {m.group(2)}]" if m else ""
  239. rows.append(dict(hid=hid, bar=float(es), label=f"AUC = {es:.3f}{ci}", state=state, is_bf=False))
  240. elif "Pillai" in lbl:
  241. rows.append(dict(hid=hid, bar=float(es), label=f"V = {es:.3f} ({_fmt_p(pv)})", state=state, is_bf=False))
  242. elif "LME" in lbl:
  243. rows.append(dict(hid=hid, bar=float(es), label=f"B = {es:.3f} ({_fmt_p(pv)})", state=state, is_bf=False))
  244. elif "Cohen" in lbl or "Pooled" in lbl:
  245. rows.append(dict(hid=hid, bar=float(es), label=f"d = {es:.2f} ({_fmt_p(pv)})", state=state, is_bf=False))
  246. else:
  247. rows.append(dict(hid=hid, bar=float(es) if not pd.isna(es) else 0.0,
  248. label=(f"{lbl} = {es:.3f}" if not pd.isna(es) else "n/a"),
  249. state=state, is_bf=False))
  250. bar_vals = [r["bar"] for r in rows if r["bar"] is not None]
  251. vmax = max(bar_vals + [0.0]); vmin = min(bar_vals + [0.0])
  252. pad = (vmax - vmin) * 0.08 + 0.05
  253. xlo, xhi = vmin - pad, vmax + pad * 1.2
  254. fig, ax = plt.subplots(figsize=(9.6, 5.0), facecolor="white")
  255. ypos = np.arange(n)[::-1]
  256. col = {"sig": C_SIG, "ns": C_NS, "nt": C_NT, "bc": C_NT}
  257. for i, r in enumerate(rows):
  258. y = ypos[i]; c = col[r["state"]]
  259. if r["state"] in ("nt", "bc"):
  260. ax.text(0.01, y, r["label"] if r["state"] == "bc" else "Not testable",
  261. va="center", ha="left", fontsize=9, color=C_NT, style="italic"); continue
  262. if r["is_bf"]:
  263. ax.barh(y, (xhi - xlo) * 0.015, height=0.62, color=c, alpha=0.92,
  264. edgecolor="white", lw=0.6, zorder=3)
  265. if r["state"] == "sig":
  266. ax.text(-(xhi - xlo) * 0.005, y, "\u2731", va="center", ha="right",
  267. fontsize=12, color=C_SIG, fontweight="bold", zorder=5)
  268. ax.text((xhi - xlo) * 0.025, y, r["label"], va="center", ha="left",
  269. fontsize=9, fontweight="bold" if r["state"] == "sig" else "normal",
  270. color="#111", zorder=5); continue
  271. bar = r["bar"]
  272. ax.barh(y, bar, height=0.62, color=c, alpha=0.92 if r["state"] == "sig" else 0.80,
  273. edgecolor="white", lw=0.6, zorder=3)
  274. if r["state"] == "sig":
  275. ax.text(-0.02 if bar >= 0 else 0.02, y, "\u2731", va="center",
  276. ha="right" if bar >= 0 else "left", fontsize=12, color=C_SIG,
  277. fontweight="bold", zorder=5)
  278. xlab = bar + pad * 0.25 if bar >= 0 else pad * 0.25
  279. ax.text(xlab, y, r["label"], va="center", ha="left",
  280. fontsize=9.2, fontweight="bold" if r["state"] == "sig" else "normal",
  281. color="#111", zorder=5)
  282. ax.axvline(0, color="#333", lw=1.1, zorder=4)
  283. ax.set_yticks(ypos); ax.set_yticklabels([r["hid"] for r in rows], fontsize=11)
  284. ax.set_xlim(xlo, xhi); ax.set_ylim(-0.7, n - 0.3)
  285. ax.set_xlabel("Effect Size (metric-specific)", fontsize=10.5)
  286. ax.set_title(f"Summary of Hypothesis Testing Outcomes (N = {n_sub})",
  287. fontsize=13, fontweight="bold", pad=10)
  288. for sp in ["top", "right"]:
  289. ax.spines[sp].set_visible(False)
  290. ax.xaxis.grid(True, color="#EEE", lw=0.7, zorder=0); ax.set_axisbelow(True)
  291. leg = [Patch(facecolor=C_SIG, label="Significant (p < .05)"),
  292. Patch(facecolor=C_NS, label="Not significant"),
  293. Patch(facecolor=C_NT, label="Not testable / by construction")]
  294. ax.legend(handles=leg, loc="upper right", bbox_to_anchor=(1.0, 1.0),
  295. fontsize=7.5, framealpha=0.95, edgecolor="#CCC")
  296. fig.text(0.5, -0.04, "Effect-size metrics are not directly comparable across hypotheses.",
  297. ha="center", va="top", fontsize=8, color="#666", style="italic")
  298. fig.text(0.5, -0.09, "H6 (grey) is a by-construction check; H8 reports the t-test, not a Bayes factor.",
  299. ha="center", va="top", fontsize=8, color="#666", style="italic")
  300. _save(fig, "fig3_hypothesis_summary")
  301. # ============================================================================= FIG 5
  302. def fig5_loso_auc():
  303. """MAIN-TEXT Fig. 5 - per-subject LOSO AUC vs. permutation baseline. Per-subject
  304. real-label AUCs are reconstructed from the master table (same decoder as the
  305. stats stage); the permutation baseline is estimated per subject by refitting on
  306. label-shuffled training data. Uses loso_auc_per_subject.csv if present (columns
  307. subject_id, auc_real[, auc_perm])."""
  308. print("Fig 5: LOSO AUC per subject")
  309. df = _load_master()
  310. if LOSO.exists():
  311. d = pd.read_csv(LOSO)
  312. else:
  313. g = _proxy_groups_and_auc(df)
  314. if not g["per_subject_auc"]:
  315. print(" [skip] could not compute per-subject AUC from master table."); return
  316. # permutation baseline per subject, matching run_pipeline: hold the fitted
  317. # predictions fixed and permute the TEST labels N_PERM times, averaging the
  318. # resulting AUCs so each subject gets a stable ~0.5 baseline (not a single
  319. # high-variance shuffle).
  320. from sklearn.preprocessing import StandardScaler
  321. from sklearn.linear_model import LogisticRegression
  322. from sklearn.metrics import roc_auc_score
  323. N_PERM = 200
  324. cols, _ = _band_channels(df, "broadband")
  325. dd = df[df["condition"].isin(["perception", "imagination"])].dropna(subset=cols).copy()
  326. dd["y"] = (dd["condition"] == "imagination").astype(int)
  327. rng = np.random.default_rng(42)
  328. perm = {}
  329. for s in dd["subject_id"].unique():
  330. tr, te = dd[dd["subject_id"] != s], dd[dd["subject_id"] == s]
  331. if tr["y"].nunique() < 2 or te["y"].nunique() < 2:
  332. continue
  333. sc = StandardScaler().fit(tr[cols].values)
  334. clf = LogisticRegression(max_iter=1000, C=0.1, solver="lbfgs", random_state=42)
  335. clf.fit(sc.transform(tr[cols].values), tr["y"].values)
  336. proba = clf.predict_proba(sc.transform(te[cols].values))[:, 1]
  337. yt = te["y"].values
  338. aucs = []
  339. for _ in range(N_PERM):
  340. yp = rng.permutation(yt)
  341. if len(np.unique(yp)) == 2:
  342. aucs.append(roc_auc_score(yp, proba))
  343. if aucs:
  344. perm[s] = float(np.mean(aucs))
  345. d = pd.DataFrame({"subject_id": list(g["per_subject_auc"]),
  346. "auc_real": list(g["per_subject_auc"].values())})
  347. d["auc_perm"] = d["subject_id"].map(perm)
  348. d = d.sort_values("auc_real").reset_index(drop=True)
  349. x = np.arange(len(d))
  350. fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.5, 4.8), facecolor="white",
  351. gridspec_kw={"width_ratios": [2.6, 1]})
  352. mean_auc = d["auc_real"].mean()
  353. # CI shading band (from hypothesis_summary if available, else fixed headline CI)
  354. ci_lo, ci_hi = 0.775, 0.847
  355. ax1.axhspan(ci_lo, ci_hi, color=C_SIG, alpha=0.10, zorder=0, label="95% CI [0.775, 0.847]")
  356. ax1.bar(x - 0.2, d["auc_real"], width=0.4, color=C_SIG, label="Real labels (AUC)")
  357. if "auc_perm" in d.columns and d["auc_perm"].notna().any():
  358. ax1.bar(x + 0.2, d["auc_perm"], width=0.4, color="#E0922F", alpha=0.9, label="Permuted labels")
  359. ax1.axhline(0.50, color="#888", ls="--", lw=1, label="Chance (0.50)")
  360. ax1.axhline(mean_auc, color="#1F3864", ls=":", lw=1.3, label=f"Mean AUC = {mean_auc:.3f}")
  361. ax1.set_xticks([0, 9, 19, 29, 39, len(d) - 1])
  362. ax1.set_xticklabels([1, 10, 20, 30, 40, len(d)], fontsize=9)
  363. ax1.set_xlabel("Subject Index (sorted by real-label AUC)", fontsize=10)
  364. ax1.set_ylabel("LOSO-CV AUC", fontsize=10); ax1.set_ylim(0.3, 1.02)
  365. ax1.set_title("(A) Per-subject LOSO-CV classification performance", fontsize=10.5, fontweight="bold")
  366. ax1.legend(fontsize=7.5, loc="upper left", framealpha=0.95)
  367. for sp in ("top", "right"):
  368. ax1.spines[sp].set_visible(False)
  369. box_data, labels, colors = [d["auc_real"].dropna().values], ["Real\nlabels"], [C_SIG]
  370. if "auc_perm" in d.columns and d["auc_perm"].notna().any():
  371. box_data.append(d["auc_perm"].dropna().values); labels.append("Permuted\nlabels"); colors.append("#E0922F")
  372. bp = ax2.boxplot(box_data, labels=labels, patch_artist=True, widths=0.55,
  373. medianprops=dict(color="#222", lw=1.3))
  374. for patch, cc in zip(bp["boxes"], colors):
  375. patch.set_facecolor(cc); patch.set_alpha(0.75)
  376. for i, vals in enumerate(box_data):
  377. ax2.scatter(np.full(len(vals), i + 1) + np.random.uniform(-0.06, 0.06, len(vals)),
  378. vals, s=11, color="#333", alpha=0.45, zorder=3)
  379. ax2.axhline(0.50, color="#888", ls="--", lw=1)
  380. # significance annotation (paired t-test reported in main text)
  381. if len(box_data) == 2:
  382. ytop = 1.0
  383. ax2.plot([1, 1, 2, 2], [ytop, ytop + 0.02, ytop + 0.02, ytop], lw=1.1, color="#222")
  384. ax2.text(1.5, ytop + 0.025, "p < 10\u207b\u00b2\u2070", ha="center", va="bottom",
  385. fontsize=9, fontweight="bold")
  386. ax2.set_ylim(0.3, 1.10); ax2.set_ylabel("AUC", fontsize=10)
  387. ax2.set_title("(B) Distribution comparison", fontsize=10.5, fontweight="bold")
  388. for sp in ("top", "right"):
  389. ax2.spines[sp].set_visible(False)
  390. fig.suptitle("Leave-one-subject-out cross-validation (N = 46)", fontsize=12.5,
  391. fontweight="bold", y=1.02)
  392. _save(fig, "fig5_loso_auc")
  393. # ============================================================================= FIG S1
  394. def figS1_band_effects():
  395. """Exploratory per-band LZC effect sizes (two contrasts). Descriptive only; the
  396. formal H1/H2 tests use cluster permutation (reported null in main text)."""
  397. print("Fig S1: per-band LZC effect sizes (exploratory)")
  398. df = _load_master()
  399. panels = [("Imagination vs. Perception\n(Occipital ROI, paired Cohen's d)", "h1"),
  400. ("High- vs. Low-decoding Subjects\n(Whole brain, pooled Cohen's d)", "h2")]
  401. fig, axes = plt.subplots(1, 2, figsize=(13, 6.2), facecolor="white")
  402. for ax, (title, kind) in zip(axes, panels):
  403. ds, sigs = [], []
  404. for band in BANDS:
  405. cols, chans = _band_channels(df, band)
  406. if kind == "h1":
  407. roi = [c for c, ch in zip(cols, chans) if ch in OCC_ROI]
  408. if not roi:
  409. ds.append(np.nan); sigs.append(False); continue
  410. im = df[df["condition"] == "imagination"].groupby("subject_id")[roi].mean().mean(axis=1)
  411. pe = df[df["condition"] == "perception"].groupby("subject_id")[roi].mean().mean(axis=1)
  412. common = im.index.intersection(pe.index)
  413. d = _paired_d(im.loc[common].values, pe.loc[common].values)
  414. else:
  415. g = _proxy_groups_and_auc(df)
  416. imag = df[df["condition"] == "imagination"]
  417. hi = imag[imag["subject_id"].isin(g["high"])].groupby("subject_id")[cols].mean().mean(axis=1)
  418. lo = imag[imag["subject_id"].isin(g["low"])].groupby("subject_id")[cols].mean().mean(axis=1)
  419. d = _cohens_d(hi.values, lo.values)
  420. ds.append(d); sigs.append(abs(d) > 0.5 if not np.isnan(d) else False)
  421. xs = np.arange(len(BANDS))
  422. # highlight bands: broadband (green) and low-gamma (yellow)
  423. bb_i = BANDS.index("broadband"); lg_i = BANDS.index("low_gamma")
  424. ax.axvspan(bb_i - 0.5, bb_i + 0.5, color="#CDE6CD", alpha=0.5, zorder=0)
  425. ax.axvspan(lg_i - 0.5, lg_i + 0.5, color="#FCEFC0", alpha=0.6, zorder=0)
  426. colors = [(C_SIG if v < 0 else C_NS) if s else ("#9DB8D8" if (not np.isnan(v) and v < 0) else "#E8B4B2")
  427. for v, s in zip(ds, sigs)]
  428. ax.bar(xs, [0 if np.isnan(v) else v for v in ds], color=colors, edgecolor="white", zorder=2)
  429. for i, (v, s) in enumerate(zip(ds, sigs)):
  430. if not np.isnan(v):
  431. ax.text(i, v + (0.06 if v >= 0 else -0.06), f"{v:+.2f}" + ("*" if s else ""),
  432. ha="center", va="bottom" if v >= 0 else "top", fontsize=8.5,
  433. fontweight="bold" if s else "normal", zorder=4)
  434. ax.axhline(0, color="#333", lw=1, zorder=3)
  435. for h in (0.2, 0.5):
  436. ax.axhline(h, color="#bbb", ls="--" if h == 0.2 else ":", lw=0.7, zorder=1)
  437. ax.axhline(-h, color="#bbb", ls="--" if h == 0.2 else ":", lw=0.7, zorder=1)
  438. ax.set_xticks(xs)
  439. ax.set_xticklabels([BAND_LABELS[b].replace("\n", " ") for b in BANDS],
  440. fontsize=8, rotation=30, ha="right")
  441. ax.set_ylabel("Cohen's d", fontsize=10); ax.set_title(title, fontsize=11, fontweight="bold")
  442. # headroom so value labels don't clip
  443. vals_arr = [v for v in ds if not np.isnan(v)]
  444. if vals_arr:
  445. lo_y, hi_y = min(vals_arr + [0]), max(vals_arr + [0])
  446. ax.set_ylim(lo_y - 0.35, hi_y + 0.35)
  447. for sp in ("top", "right"):
  448. ax.spines[sp].set_visible(False)
  449. # shared legend
  450. from matplotlib.patches import Patch
  451. leg = [Patch(facecolor=C_SIG, label="|d| > 0.5, d < 0"),
  452. Patch(facecolor=C_NS, label="|d| > 0.5, d > 0"),
  453. Patch(facecolor="#9DB8D8", label="|d| \u2264 0.5, d < 0"),
  454. Patch(facecolor="#E8B4B2", label="|d| \u2264 0.5, d > 0"),
  455. Patch(facecolor="#CDE6CD", alpha=0.5, label="Broadband band"),
  456. Patch(facecolor="#FCEFC0", alpha=0.6, label="Low-gamma band")]
  457. fig.legend(handles=leg, loc="lower center", ncol=6, fontsize=8,
  458. framealpha=0.95, bbox_to_anchor=(0.5, -0.06))
  459. fig.suptitle("Exploratory Per-Band LZC Effect Sizes (N = 46)", fontsize=13, fontweight="bold", y=1.0)
  460. fig.text(0.5, -0.15,
  461. "Exploratory, descriptive Cohen's d (uncorrected); * marks |d| > 0.5\n"
  462. "(a descriptive threshold, not a significance test). Dashed line |d| = 0.2, dotted line |d| = 0.5.\n"
  463. "Distinct from the cluster-permutation tests used for the formal H1/H2 evaluation,\n"
  464. "which are reported as null in the main text.",
  465. ha="center", va="top", fontsize=9.5, color="#555", style="italic", linespacing=1.6)
  466. fig.tight_layout(rect=[0, 0.02, 1, 0.98])
  467. _save(fig, "figS1_band_effect_sizes")
  468. # ============================================================================= FIG S2
  469. def figS2_enhanced_topomaps():
  470. """SUPPLEMENT Fig. S2 - three-condition broadband LZC topography:
  471. perception, high-decoding imagery, low-decoding imagery. The decoding subgroups
  472. are reconstructed from the master table (median split on the LOSO decoding
  473. proxy), complementing the two-condition main-text Fig. 2."""
  474. print("Fig S2: enhanced topomaps (3 conditions)")
  475. df = _load_master()
  476. cols, chans = _band_channels(df, "broadband")
  477. g = _proxy_groups_and_auc(df)
  478. imag = df[df["condition"] == "imagination"]
  479. hi = imag[imag["subject_id"].isin(g["high"])][cols].mean().values
  480. lo = imag[imag["subject_id"].isin(g["low"])][cols].mean().values
  481. conds = [("Perception", df[df["condition"] == "perception"][cols].mean().values),
  482. ("High-decoding imagery", hi), ("Low-decoding imagery", lo)]
  483. fig, axes = plt.subplots(1, 3, figsize=(11.4, 4.0), facecolor="white")
  484. allv = np.concatenate([v for _, v in conds])
  485. vlim = (np.nanpercentile(allv, 2), np.nanpercentile(allv, 98))
  486. last = None
  487. for ax, (t, v) in zip(axes, conds):
  488. last = _try_mne_topomap(ax, v, chans, t, vlim=vlim)
  489. if last is not None:
  490. cb = fig.colorbar(last, ax=axes, fraction=0.022, pad=0.04)
  491. cb.set_label("Normalised broadband LZC", fontsize=9)
  492. fig.suptitle("Broadband LZC topography by decoding subgroup (N = 46)",
  493. fontsize=12.5, fontweight="bold", y=1.04)
  494. _save(fig, "figS2_enhanced_topomaps")
  495. # ============================================================================= FIG S3
  496. def figS3_spatial_clustering():
  497. """SUPPLEMENT Fig. S3 - three-panel cluster-permutation result for H4:
  498. (A) unthresholded imagination-minus-perception broadband-LZC difference;
  499. (B) difference with significant cluster channels marked;
  500. (C) the per-channel statistical (t) map.
  501. Reads cluster_results.npz (keys: 'ch_names', 'mask', optional 'tvals'). If the
  502. file is absent, panel A/C use the data difference and a paired t-map computed
  503. from the master table, and panel B notes the cluster file was unavailable."""
  504. print("Fig S3: spatial clustering (3 panels)")
  505. df = _load_master()
  506. cols, chans = _band_channels(df, "broadband")
  507. imag_sub = df[df["condition"] == "imagination"].groupby("subject_id")[cols].mean()
  508. perc_sub = df[df["condition"] == "perception"].groupby("subject_id")[cols].mean()
  509. common = imag_sub.index.intersection(perc_sub.index)
  510. diffmat = imag_sub.loc[common].values - perc_sub.loc[common].values # subj x ch
  511. diff = diffmat.mean(axis=0)
  512. # paired t per channel
  513. sd = diffmat.std(axis=0, ddof=1) + 1e-12
  514. tvals = diff / (sd / np.sqrt(len(common)))
  515. mask = None
  516. if CLUSTER.exists():
  517. z = np.load(CLUSTER, allow_pickle=True)
  518. if "ch_names" in z and "mask" in z:
  519. cmask = dict(zip([str(c) for c in z["ch_names"]], z["mask"]))
  520. mask = np.array([bool(cmask.get(ch, False)) for ch in chans])
  521. if "tvals" in z:
  522. tmap = dict(zip([str(c) for c in z["ch_names"]], z["tvals"]))
  523. tvals = np.array([tmap.get(ch, 0.0) for ch in chans])
  524. fig, axes = plt.subplots(1, 3, figsize=(12.5, 4.2), facecolor="white")
  525. dmax = np.nanpercentile(np.abs(diff), 98)
  526. # (A) difference
  527. imA = _try_mne_topomap(axes[0], diff, chans, "(A) Imagination \u2212 Perception", vlim=(-dmax, dmax))
  528. if imA is not None:
  529. fig.colorbar(imA, ax=axes[0], fraction=0.046, pad=0.04).set_label("\u0394 LZC", fontsize=8)
  530. # (B) difference + significant cluster channels
  531. imB = _try_mne_topomap(axes[1], diff, chans,
  532. "(B) Difference + significant cluster", vlim=(-dmax, dmax))
  533. if mask is not None and imB is not None:
  534. try:
  535. import mne
  536. info = mne.create_info(list(chans), 1000.0, "eeg")
  537. info.set_montage(mne.channels.make_standard_montage("standard_1020"),
  538. match_case=False, on_missing="ignore")
  539. pos = np.array([info["chs"][i]["loc"][:2] for i in range(len(chans))])
  540. axes[1].scatter(pos[mask, 0], pos[mask, 1], s=22, facecolors="none",
  541. edgecolors="k", linewidths=1.4, zorder=6)
  542. except Exception:
  543. pass
  544. elif mask is None:
  545. axes[1].text(0.5, -0.08, "cluster mask unavailable", transform=axes[1].transAxes,
  546. ha="center", fontsize=7, color="#999")
  547. # (C) statistical map
  548. tmax = np.nanpercentile(np.abs(tvals), 98)
  549. imC = _try_mne_topomap(axes[2], tvals, chans, "(C) Statistical (t) map", vlim=(-tmax, tmax))
  550. if imC is not None:
  551. fig.colorbar(imC, ax=axes[2], fraction=0.046, pad=0.04).set_label("t", fontsize=8)
  552. fig.suptitle("Spatial clustering of broadband LZC differences (H4)", fontsize=12.5,
  553. fontweight="bold", y=1.04)
  554. _save(fig, "figS3_spatial_clustering")
  555. # ============================================================================= FIG S4
  556. def figS4_band_magnitudes():
  557. """SUPPLEMENT Fig. S4 - LZC magnitude across the seven bands as a line plot:
  558. perception (solid) vs imagination (dashed), with shaded SEM bands."""
  559. print("Fig S4: LZC magnitudes across bands (line plot)")
  560. df = _load_master()
  561. conds = ["perception", "imagination"]
  562. means = {c: [] for c in conds}
  563. sems = {c: [] for c in conds}
  564. for band in BANDS:
  565. cols, _ = _band_channels(df, band)
  566. for c in conds:
  567. per_subj = df[df["condition"] == c].groupby("subject_id")[cols].mean().mean(axis=1)
  568. means[c].append(per_subj.mean())
  569. sems[c].append(per_subj.std(ddof=1) / np.sqrt(len(per_subj)))
  570. xs = np.arange(len(BANDS))
  571. fig, ax = plt.subplots(figsize=(10, 4.8), facecolor="white")
  572. styles = {"perception": dict(color="#2E5E9E", ls="-", marker="o", label="Perception"),
  573. "imagination": dict(color="#C0504D", ls="--", marker="s", label="Imagination")}
  574. for c in conds:
  575. m = np.array(means[c]); e = np.array(sems[c])
  576. ax.plot(xs, m, lw=2, markersize=6, **styles[c])
  577. ax.fill_between(xs, m - e, m + e, color=styles[c]["color"], alpha=0.18)
  578. ax.set_xticks(xs); ax.set_xticklabels([BAND_LABELS[b] for b in BANDS], fontsize=8)
  579. ax.set_ylabel("Mean normalised LZC", fontsize=10)
  580. ax.set_title("LZC magnitudes across frequency bands (N = 46)", fontsize=12, fontweight="bold")
  581. ax.legend(fontsize=9, loc="upper left")
  582. for sp in ("top", "right"):
  583. ax.spines[sp].set_visible(False)
  584. ax.grid(axis="y", color="#EEE", lw=0.7); ax.set_axisbelow(True)
  585. _save(fig, "figS4_band_magnitudes")
  586. # ============================================================================= FIG S5
  587. def figS5_lzc_hfd_correlation():
  588. """SUPPLEMENT Fig. S5 - scalp topomap of the per-channel Pearson correlation
  589. between broadband LZC and epoch-level HFD across trials (N = 46), per the
  590. caption. Correlation is computed across trials within each channel."""
  591. print("Fig S5: per-channel LZC-HFD correlation topomap")
  592. df = _load_master()
  593. _, lzc_chans = _band_channels(df, "broadband")
  594. hfd_cols, hfd_chans = _hfd_channels(df)
  595. common = [ch for ch in lzc_chans if ch in hfd_chans]
  596. if not common:
  597. print(f" [warn] no overlapping LZC/HFD channels (HFD cols found: {len(hfd_cols)}). "
  598. f"Check HFD column naming in the master table."); return
  599. rs = []
  600. for ch in common:
  601. x = df[f"LZC_broadband_{ch}"].values
  602. ycol = f"HFD_epoch_{ch}" if f"HFD_epoch_{ch}" in df.columns else f"HFD_{ch}"
  603. y = df[ycol].values
  604. m = np.isfinite(x) & np.isfinite(y)
  605. rs.append(np.corrcoef(x[m], y[m])[0, 1] if m.sum() > 2 else np.nan)
  606. rs = np.array(rs)
  607. fig, ax = plt.subplots(figsize=(5.4, 4.8), facecolor="white")
  608. vlim = (np.nanmin(rs), np.nanmax(rs))
  609. im = _try_mne_topomap(ax, rs, common, "", vlim=vlim)
  610. if im is not None:
  611. cb = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
  612. cb.set_label("Per-channel Pearson r (LZC vs HFD)", fontsize=9)
  613. ax.set_title(f"Channel-wise LZC\u2013HFD correlation\n"
  614. f"(mean r = {np.nanmean(rs):.3f}, range [{np.nanmin(rs):.3f}, {np.nanmax(rs):.3f}])",
  615. fontsize=11, fontweight="bold")
  616. fig.suptitle("Topography of LZC\u2013HFD correlation (N = 46)", fontsize=12.5,
  617. fontweight="bold", y=1.02)
  618. _save(fig, "figS5_lzc_hfd_correlation")
  619. # ============================================================================= FIG S6
  620. def figS6_shuffle_distribution():
  621. """Distribution of surrogate(shuffle)-normalised broadband LZC across subjects."""
  622. print("Fig S6: shuffle-normalised LZC distribution")
  623. df = _load_master()
  624. cols, _ = _band_channels(df, "broadband")
  625. df = df.copy(); df["bb_mean"] = df[cols].mean(axis=1)
  626. subj_means = df.groupby("subject_id")["bb_mean"].mean().sort_values()
  627. subjects = subj_means.index.tolist()
  628. fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.6), facecolor="white",
  629. gridspec_kw={"width_ratios": [2.2, 1]})
  630. data_by_subj = [df.loc[df["subject_id"] == s, "bb_mean"].values for s in subjects]
  631. bp = ax1.boxplot(data_by_subj, widths=0.6, patch_artist=True, showfliers=False,
  632. medianprops=dict(color="#1F3864", lw=1.3))
  633. for patch in bp["boxes"]:
  634. patch.set_facecolor("#9DB8D8"); patch.set_alpha(0.8); patch.set_edgecolor("#5A7CA8")
  635. ax1.axhline(1.0, color=C_NS, lw=1.2, ls="--", label="surrogate level (normalised = 1.0)")
  636. ax1.set_xticks([]); ax1.set_xlabel(f"Subjects (n = {len(subjects)}, sorted by mean)", fontsize=10)
  637. ax1.set_ylabel("Shuffle-normalised broadband LZC", fontsize=10)
  638. ax1.set_title("(A) Per-subject distribution", fontsize=10.5, fontweight="bold")
  639. ax1.legend(fontsize=8, loc="upper left"); [ax1.spines[s].set_visible(False) for s in ("top", "right")]
  640. allv = df["bb_mean"].values
  641. ax2.hist(allv, bins=40, color="#9DB8D8", edgecolor="#5A7CA8", alpha=0.85)
  642. ax2.axvline(1.0, color=C_NS, lw=1.2, ls="--", label="surrogate = 1.0")
  643. ax2.axvline(np.mean(allv), color="#1F3864", lw=1.2, label=f"mean = {np.mean(allv):.3f}")
  644. ax2.set_xlabel("Shuffle-normalised broadband LZC", fontsize=10); ax2.set_ylabel("Trials", fontsize=10)
  645. ax2.set_title("(B) Pooled distribution", fontsize=10.5, fontweight="bold")
  646. ax2.legend(fontsize=8); [ax2.spines[s].set_visible(False) for s in ("top", "right")]
  647. fig.suptitle("Distribution of surrogate (shuffle)-normalised LZC across subjects",
  648. fontsize=12.5, fontweight="bold", y=1.02)
  649. _save(fig, "figS6_shuffle_distribution")
  650. # ============================================================================= driver
  651. FIGS = {
  652. "fig2": fig2_topomaps, "fig3": fig3_hypothesis_summary, "fig5": fig5_loso_auc,
  653. "figS1": figS1_band_effects, "figS2": figS2_enhanced_topomaps,
  654. "figS3": figS3_spatial_clustering, "figS4": figS4_band_magnitudes,
  655. "figS5": figS5_lzc_hfd_correlation, "figS6": figS6_shuffle_distribution,
  656. }
  657. def main():
  658. ap = argparse.ArgumentParser(description="Regenerate all data-driven manuscript figures.")
  659. ap.add_argument("--only", nargs="+", choices=list(FIGS), help="Subset of figures to draw.")
  660. ap.add_argument("--outdir", default=None, help="Override output directory.")
  661. args = ap.parse_args()
  662. global OUT
  663. if args.outdir:
  664. OUT = Path(args.outdir)
  665. todo = args.only or list(FIGS)
  666. print(f"Output directory: {OUT}\nFigures: {', '.join(todo)}")
  667. print("(Fig. 1 and Fig. 4 are schematics, produced externally, not here.)\n")
  668. for key in todo:
  669. try:
  670. FIGS[key]()
  671. except FileNotFoundError as e:
  672. print(f" [skip {key}] {e}")
  673. except Exception as e:
  674. print(f" [error {key}] {type(e).__name__}: {e}")
  675. print("\nDone.")
  676. if __name__ == "__main__":
  677. main()

make_all_figures.py at commit 9243f6c, under MIT · at the source

Overview

Authors: Yu Gao1,2,3, José Miguel Diniz4
  1. Department of Electrical and Computer Engineering, Faculty of Engineering, University of Porto, Porto, Portugal
  2. CISTER/ISEP - Research Centre in Real-Time and Embedded Computing Systems, School of Engineering, Porto, Portugal
  3. Faculdade de Engenharia da Universidade do Porto, Rua Dr. Roberto Frias, 4200 – 465 Porto, Portugal
  4. PhD Program in Health Data Science, Faculty of Medicine, University of Porto, Porto, Portugal
Journal: Brain topography, volume 39, issue 5, article 82
Dates: received 10 April 2026; accepted 15 July 2026; published online 21 July 2026; in print 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1007/s10548-026-01238-y · PMID 42479103 · PMCID PMC13388782 · OpenAlex W7169826764
Open access: hybrid, a free copy (OpenAlex)
Status: code verified
Categories: EEG (modality), human (organism), cognitive (subfield)
Methods: Spectral & time-frequency, Preprocessing, Statistics, Smoothing, state filtering, decompositions, Machine learning, Connectivity, Complexity, fMRI & imaging, Physiology & signal measures
Keywords: EEG, Mental Imagery, Neural Complexity, Lempel-Ziv Complexity, Higuchi Fractal Dimension, Cortical State Decoding
MeSH: Brain*, Brain Mapping*, Electroencephalography*, Imagination*, Visual Perception*, Adult, Female, Humans, Male, Signal Processing, Computer-Assisted, Young Adult (* major topic)
Topic: Functional Brain Connectivity Studies (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Funding: Universidade do Porto
Citations: not cited yet (Europe PMC); 26 references in the paper

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://doi.org/10.1007/s10548-026-01238-y.

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

License: MIT
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: 9243f6c8441c43628b7d348b4b45e5fb2157a67b, 1 June 2026
Languages: Python (33)
Size: 87 files, 33 scripts
Software Heritage: not archived
Found in: the text, “Introduction”
Holds: license file, environment (eeg_imagination/requirements.txt), tests
Not found: README, CITATION.cff, continuous integration, documentation
Tools: NumPy (20 files), pandas (19 files), MNE-Python (16 files), scikit-learn (8 files), SciPy (8 files), Matplotlib (6 files), XGBoost (2 files), ICLabel (1 file), Numba (1 file), Pingouin (1 file), SHAP (1 file), statsmodels (1 file)
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
34 files

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

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://doi.org/10.1007/s10548-026-01238-y

BibTeX

@article{gao2026topographic,
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/s10548-026-01238-y},
url = {https://doi.org/10.1007/s10548-026-01238-y},
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/07/21
VL - 39
IS - 5
SP - 82
SN - 0896-0267
PB - Springer Science+Business Media
DO - 10.1007/s10548-026-01238-y
UR - https://doi.org/10.1007/s10548-026-01238-y
LA - en
ER -

CSL-JSON

{
"id": "10.1007/s10548-026-01238-y",
"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": "Brain Topogr",
"volume": "39",
"issue": "5",
"page": "82",
"DOI": "10.1007/s10548-026-01238-y",
"PMID": "42479103",
"PMCID": "PMC13388782",
"ISSN": "0896-0267",
"publisher": "Springer Science+Business Media",
"URL": "https://doi.org/10.1007/s10548-026-01238-y",
"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.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
[2] doi:10.1016/j.isci.2026.116825 [code]
Social hierarchy shapes behavioral and transcriptional responses to chronic stress and ketamine in male mice.
Journal: iScience
In common: SHAP, XGBoost, Pingouin, 7 other tools
[3] doi:10.3390/s26175327 [code]
Subject Identity Confounds qEEG Emotion Recognition on DEAP and DREAMER.
Journal: Sensors (Basel, Switzerland)
In common: SHAP, XGBoost, 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: EBioMedicine
In common: ICLabel, MNE-Python, statsmodels, 4 other tools, EEG, 2 references
[5] doi:10.1016/j.nicl.2026.104012 [code]
Structural-functional multilayer brain network properties and outcome of combined repetitive transcranial magnetic stimulation and psychotherapy for obsessive-compulsive disorder.
Journal: NeuroImage. Clinical
In common: SHAP, XGBoost, Pingouin, 6 other tools
[6] doi:10.1038/s42003-026-10957-8 [code]
Brain defence by the extracellular matrix protein Cochlin.
Journal: Communications biology
In common: SHAP, XGBoost, Numba, 6 other tools
[7] doi:10.1097/j.pain.0000000000004044 [code]
No effect of rhythmic visual stimulation on experimental pain perception.
Journal: Pain
In common: ICLabel, Pingouin, MNE-Python, 5 other tools, EEG, cognitive
[8] doi:10.21203/rs.3.rs-9914920/v1 [code]
Prediction of cognitive performance by demographics, sleep, and brain morphometry: machine learning findings from ENIGMA-Sleep Working Group
Journal: Research Square (preprint)
In common: SHAP, XGBoost, Pingouin, 6 other tools
[9] doi:10.7554/elife.109717 [code]
Retrosplenial cortex enables context-dependent goal-directed sensorimotor transformation.
Journal: eLife
In common: SHAP, XGBoost, Numba, 6 other tools
[10] doi:10.1162/imag.a.1245 [code]
Towards precision EEG connectomics: Evaluating the benefits of dense sampling.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: ICLabel, Pingouin, MNE-Python, 5 other tools, EEG

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.

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: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.