| """ |
| ====================================================== |
| Riemannian Artifact Rejection as a Pre-processing Step |
| ====================================================== |
| |
| Electroencephalography (EEG) signal cleaning has long been a critical |
| challenge in the research community. The presence of artifacts can |
| significantly degrade EEG data quality, complicating analysis and |
| potentially leading to erroneous interpretations. These artifacts are |
| broadly categorized as either endogenous (biological: ocular, myogenic, |
| cardiac) or exogenous (environmental, instrumental). As noted in [3]_, |
| manual annotation of artifacts is time-consuming, subjective, and |
| impractical for large-scale EEG studies. |
| |
| Riemannian geometry provides an elegant framework for automatic artifact |
| detection. The key feature of interest is the **covariance matrix** derived |
| from EEG epochs. Each epoch of :math:`N` channels and :math:`T` time |
| samples yields a covariance matrix :math:`\\Sigma = \\frac{1}{T-1} X X^\\top` |
| that lies on the manifold of Symmetric Positive Definite (SPD) matrices |
| :math:`\\mathcal{M}_N`. The affine-invariant Riemannian distance between |
| two SPD matrices is: |
| |
| .. math:: |
| |
| \\delta_R(\\Sigma_1, \\Sigma_2) = \\left\\| \\log\\left( |
| \\Sigma_1^{-1/2} \\Sigma_2 \\Sigma_1^{-1/2} \\right) |
| \\right\\|_F = \\sqrt{\\sum_{n=1}^{N} \\log^2(\\lambda_n)} |
| |
| where :math:`\\lambda_n` are the eigenvalues of |
| :math:`\\Sigma_1^{-1} \\Sigma_2`. |
| |
| This tutorial introduces three progressively more powerful Riemannian |
| artifact rejection methods and demonstrates how to integrate them |
| into a MOABB pre-processing pipeline using **pipeline surgery**: |
| |
| 1. **Riemannian Potato (RP)** [1]_ — a single-potato detector based on |
| Riemannian distance to the geometric mean (barycenter). |
| 2. **Riemannian Potato Field (RPF)** [2]_ — multiple potatoes, each |
| targeting specific artifact types via channel subsets and frequency |
| bands, combined using Fisher's method. |
| 3. **Improved RPF (iRPF)** [3]_ — enhanced RPF with GFRMS amplitude |
| pre-filtering to remove severely corrupted epochs, per-potato distance |
| metrics, and both Fisher's and Stouffer's (Liptak) combination functions |
| for a more sensitive rejection criterion. |
| |
| We apply these methods to the BNCI2014-009 P300 dataset and design a |
| potato field following the principles described in [3]_. |
| |
| References |
| ---------- |
| .. [1] Barachant, A., Andreev, A., & Congedo, M. (2013). The Riemannian |
| Potato: an automatic and adaptive artifact detection method for |
| online experiments using Riemannian geometry. In TOBI Workshop IV |
| (pp. 19-20). |
| |
| .. [2] Barthelemy, Q., Mayaud, L., Ojeda, D., & Congedo, M. (2019). |
| The Riemannian Potato Field: a tool for online signal quality index |
| of EEG. IEEE Transactions on Neural Systems and Rehabilitation |
| Engineering, 27(2), 244-255. |
| |
| .. [3] Hajhassani, D., Barthelemy, Q., Mattout, J., & Congedo, M. (2026). |
| Improved Riemannian potato field: an Automatic Artifact Rejection |
| Method for EEG. Biomedical Signal Processing and Control, 112, |
| 108505. https://doi.org/10.1016/j.bspc.2025.108505 |
| """ |
|
|
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| import warnings |
|
|
| import matplotlib.pyplot as plt |
| import numpy as np |
| import pandas as pd |
| from pyriemann.classification import MDM |
| from pyriemann.clustering import Potato, PotatoField |
| from pyriemann.estimation import Covariances, ERPCovariances |
| from pyriemann.utils.covariance import normalize |
| from scipy.stats import combine_pvalues, norm |
| from sklearn.pipeline import make_pipeline |
| from sklearn.preprocessing import FunctionTransformer |
|
|
| import moabb |
| from moabb.datasets import BNCI2014_009 |
| from moabb.datasets.bids_interface import StepType |
| from moabb.evaluations import WithinSessionEvaluation |
| from moabb.paradigms import P300 |
|
|
|
|
| |
| |
| warnings.filterwarnings("ignore", category=FutureWarning, module="sklearn") |
| warnings.filterwarnings("ignore", category=RuntimeWarning, module="pyriemann") |
|
|
| moabb.set_log_level("info") |
|
|
|
|
| def predict_clean_mask(model, covariances): |
| """Return clean-epoch mask across pyRiemann label encodings.""" |
| labels = np.asarray(model.predict(covariances)) |
| if np.issubdtype(labels.dtype, np.number) and np.any(labels < 0): |
| return labels > 0 |
| return labels.astype(bool) |
|
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| dataset = BNCI2014_009() |
| |
| |
| dataset.subject_list = dataset.subject_list[:2] |
|
|
| paradigm = P300(resample=128, scorer={"roc_auc": "roc_auc", "f1": "f1"}) |
|
|
| |
| dataset_viz = BNCI2014_009() |
| dataset_viz.subject_list = dataset.subject_list[:1] |
| epochs, labels, meta = paradigm.get_data(dataset_viz, return_epochs=True) |
| print(f"Loaded {len(epochs)} epochs, {len(epochs.ch_names)} channels") |
| print(f"Channels: {epochs.ch_names}") |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| data = epochs.get_data() |
| covs = Covariances(estimator="lwf").transform(data) |
|
|
| |
| |
| |
| |
| |
| potato = Potato(metric={"mean": "riemann", "distance": "riemann"}, threshold=3) |
| potato.fit(covs) |
| z_scores = potato.transform(covs) |
| is_clean = predict_clean_mask(potato, covs) |
|
|
| print(f"RP detected {(~is_clean).sum()}/{len(covs)} artifact epochs") |
|
|
| |
| |
| fig, axes = plt.subplots(1, 5, figsize=(15, 3), facecolor="white") |
|
|
| |
| barycenter = potato.covmean_ |
| im = axes[0].imshow(barycenter, cmap="RdBu_r", aspect="equal") |
| axes[0].set_title("Barycenter\n(geometric mean)", fontsize=9) |
|
|
| |
| sorted_idx = np.argsort(np.abs(z_scores)) |
| for j, idx in enumerate(sorted_idx[:2]): |
| axes[1 + j].imshow(covs[idx], cmap="RdBu_r", aspect="equal") |
| axes[1 + j].set_title(f"Clean epoch\nz = {z_scores[idx]:.2f}", fontsize=9) |
|
|
| |
| for j, idx in enumerate(sorted_idx[-2:]): |
| axes[3 + j].imshow(covs[idx], cmap="RdBu_r", aspect="equal") |
| axes[3 + j].set_title(f"Outlier epoch\nz = {z_scores[idx]:.2f}", fontsize=9) |
|
|
| for ax in axes: |
| ax.set_xticks([]) |
| ax.set_yticks([]) |
|
|
| fig.suptitle( |
| "Covariance matrices: barycenter vs clean vs outlier epochs", |
| fontsize=11, |
| fontweight="bold", |
| ) |
| plt.tight_layout() |
| plt.show() |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| ch_name_x = "Oz" |
| ch_name_y = "C4" |
| ch_idx_x = epochs.ch_names.index(ch_name_x) |
| ch_idx_y = epochs.ch_names.index(ch_name_y) |
| covs_2d = covs[:, [ch_idx_x, ch_idx_y], :][:, :, [ch_idx_x, ch_idx_y]] |
|
|
| |
| n_calib_2d = min(40, len(covs_2d)) |
| z_threshold_2d = 3.0 |
| potato_2d = Potato( |
| metric={"mean": "riemann", "distance": "riemann"}, threshold=z_threshold_2d |
| ) |
| potato_2d.fit(covs_2d[:n_calib_2d]) |
| z_2d = potato_2d.transform(covs_2d) |
| is_clean_2d = predict_clean_mask(potato_2d, covs_2d) |
| barycenter_2d = potato_2d.covmean_ |
|
|
| |
| |
| cov_scale = 1e12 |
| x_vals = covs_2d[:, 0, 0] * cov_scale |
| y_vals = covs_2d[:, 1, 1] * cov_scale |
|
|
| |
| potato_2d_euclid = Potato( |
| metric={"mean": "euclid", "distance": "euclid"}, threshold=z_threshold_2d |
| ) |
| potato_2d_euclid.fit(covs_2d[:n_calib_2d]) |
|
|
| calib_x = x_vals[:n_calib_2d] |
| calib_y = y_vals[:n_calib_2d] |
| x_p01, x_p99 = np.percentile(calib_x, [1, 99]) |
| y_p01, y_p99 = np.percentile(calib_y, [1, 99]) |
| x_pad = 0.35 * max(x_p99 - x_p01, 1e-12) |
| y_pad = 0.35 * max(y_p99 - y_p01, 1e-12) |
| x_grid = np.linspace(x_p01 - x_pad, x_p99 + x_pad, 140) |
| y_grid = np.linspace(y_p01 - y_pad, y_p99 + y_pad, 140) |
| xx, yy = np.meshgrid(x_grid, y_grid) |
|
|
|
|
| def make_z_map(model): |
| """Compute z-score map on a diagonal covariance grid.""" |
| off_diag = model.covmean_[0, 1] |
| grid_covs = np.zeros((len(x_grid) * len(y_grid), 2, 2)) |
| grid_covs[:, 0, 0] = xx.ravel() / cov_scale |
| grid_covs[:, 1, 1] = yy.ravel() / cov_scale |
| grid_covs[:, 0, 1] = off_diag |
| grid_covs[:, 1, 0] = off_diag |
|
|
| det = grid_covs[:, 0, 0] * grid_covs[:, 1, 1] - off_diag**2 |
| valid = det > 0 |
| z_grid = np.full(len(grid_covs), np.nan) |
| if valid.sum() > 0: |
| z_grid[valid] = model.transform(grid_covs[valid]) |
| return np.ma.masked_invalid(z_grid.reshape(xx.shape)) |
|
|
|
|
| z_map_riemann = make_z_map(potato_2d) |
| z_map_euclid = make_z_map(potato_2d_euclid) |
| z_abs_max = np.nanmax( |
| np.abs( |
| np.hstack( |
| [z_map_riemann.compressed(), z_map_euclid.compressed(), [z_threshold_2d]] |
| ) |
| ) |
| ) |
| z_levels = np.linspace(-z_abs_max, z_abs_max, 18) |
|
|
| fig, axes = plt.subplots(1, 2, figsize=(13, 5), facecolor="white") |
| plot_specs = [ |
| (axes[0], potato_2d, z_map_riemann, "Riemannian", "Z-score of Riemannian distance"), |
| ( |
| axes[1], |
| potato_2d_euclid, |
| z_map_euclid, |
| "Euclidean", |
| "Z-score of Euclidean distance", |
| ), |
| ] |
|
|
| for ax, model, z_map, title_name, cbar_label in plot_specs: |
| contour = ax.contourf(xx, yy, z_map, levels=z_levels, cmap="RdYlBu_r", alpha=0.55) |
| ax.contour(xx, yy, z_map, levels=[z_threshold_2d], colors=["black"], linewidths=1.8) |
|
|
| |
| |
| off_diag = model.covmean_[0, 1] |
| covs_2d_projected = covs_2d.copy() |
| covs_2d_projected[:, 0, 1] = off_diag |
| covs_2d_projected[:, 1, 0] = off_diag |
| det_points = covs_2d_projected[:, 0, 0] * covs_2d_projected[:, 1, 1] - off_diag**2 |
| valid_points = det_points > 0 |
| is_clean_full = np.zeros(len(covs_2d_projected), dtype=bool) |
| if valid_points.sum() > 0: |
| is_clean_full[valid_points] = predict_clean_mask( |
| model, covs_2d_projected[valid_points] |
| ) |
| is_calib = np.zeros(len(covs_2d), dtype=bool) |
| is_calib[:n_calib_2d] = True |
| is_clean_calib = is_calib & is_clean_full |
| is_artifact_calib = is_calib & ~is_clean_full |
| is_artifact_eval = ~is_calib & ~is_clean_full |
|
|
| ax.scatter( |
| x_vals[is_clean_calib], |
| y_vals[is_clean_calib], |
| c="blue", |
| s=34, |
| label="Calibration clean", |
| zorder=4, |
| ) |
| ax.scatter( |
| x_vals[is_artifact_calib], |
| y_vals[is_artifact_calib], |
| c="red", |
| s=48, |
| label="Calibration artifact", |
| zorder=5, |
| ) |
| ax.scatter( |
| x_vals[is_artifact_eval], |
| y_vals[is_artifact_eval], |
| c="red", |
| s=24, |
| alpha=0.65, |
| marker="x", |
| linewidths=1.2, |
| label="Artifact (outside calibration)", |
| zorder=5, |
| ) |
| ax.scatter( |
| model.covmean_[0, 0] * cov_scale, |
| model.covmean_[1, 1] * cov_scale, |
| c="black", |
| s=120, |
| marker="o", |
| label="Barycenter", |
| zorder=5, |
| ) |
|
|
| ax.set_title(f"2D projection of {title_name} potato") |
| ax.set_xlabel(f"Cov({ch_name_x},{ch_name_x}) [uV^2]") |
| ax.set_ylabel(f"Cov({ch_name_y},{ch_name_y}) [uV^2]") |
| ax.set_xlim(x_grid.min(), x_grid.max()) |
| ax.set_ylim(y_grid.min(), y_grid.max()) |
| ax.grid(alpha=0.2, linestyle=":") |
| ax.legend(loc="upper right") |
| plt.colorbar(contour, ax=ax, label=cbar_label) |
|
|
| fig.suptitle(f"Offline calibration of potatoes (first {n_calib_2d} epochs)", fontsize=18) |
| plt.tight_layout() |
| plt.show() |
|
|
| |
| |
| |
| |
|
|
| fig, axes = plt.subplots(1, 2, figsize=(12, 4), facecolor="white") |
|
|
| |
| axes[0].hist(z_scores[is_clean], bins=30, alpha=0.7, label="Clean", color="#4C72B0") |
| axes[0].hist(z_scores[~is_clean], bins=10, alpha=0.7, label="Artifact", color="#C44E52") |
| axes[0].axvline(3, color="k", linestyle="--", linewidth=1.5, label="Threshold (z=3)") |
| axes[0].set_xlabel("Geometric z-score") |
| axes[0].set_ylabel("Count") |
| axes[0].set_title("RP: Z-score distribution") |
| axes[0].legend() |
|
|
| |
| p_values = 1 - norm.cdf(z_scores) |
| sorted_p = np.sort(p_values) |
| axes[1].plot(sorted_p, ".-", markersize=2, color="#4C72B0") |
| axes[1].set_xlabel("Epoch index (sorted)") |
| axes[1].set_ylabel("p-value") |
| axes[1].set_title("RP: Sorted p-values (Signal Quality Index)") |
| axes[1].set_yscale("log") |
| axes[1].axhline( |
| 1 - norm.cdf(3), |
| color="k", |
| linestyle="--", |
| linewidth=1.5, |
| label=f"Threshold (p={1 - norm.cdf(3):.4f})", |
| ) |
| axes[1].legend() |
|
|
| plt.tight_layout() |
| plt.show() |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| POTATO_FIELD_CONFIG = [ |
| { |
| "channels": ["F3", "Fz", "F4"], |
| "low_freq": 1.0, |
| "high_freq": 7.0, |
| "metric": "euclid", |
| "normalization": None, |
| "target": "Ocular (low-freq)", |
| }, |
| { |
| "channels": ["F3", "Fz", "F4"], |
| "low_freq": 1.0, |
| "high_freq": 7.0, |
| "metric": "riemann", |
| "normalization": None, |
| "target": "Ocular (blinks)", |
| }, |
| { |
| "channels": ["PO7", "PO8", "P3", "P4"], |
| "low_freq": 16.0, |
| "high_freq": 24.0, |
| "metric": "riemann", |
| "normalization": "trace", |
| "target": "Myogenic lateral", |
| }, |
| { |
| "channels": ["C3", "Cz", "C4"], |
| "low_freq": 16.0, |
| "high_freq": 24.0, |
| "metric": "riemann", |
| "normalization": "trace", |
| "target": "Myogenic central", |
| }, |
| { |
| "channels": ["CP3", "CPz", "CP4", "Pz"], |
| "low_freq": 1.0, |
| "high_freq": 24.0, |
| "metric": "riemann", |
| "normalization": None, |
| "target": "General parietal", |
| }, |
| { |
| "channels": None, |
| "low_freq": 1.0, |
| "high_freq": 24.0, |
| "metric": "riemann", |
| "normalization": None, |
| "target": "General (all channels)", |
| }, |
| ] |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
|
|
| def compute_potato_covariances(epochs, config): |
| """Compute covariance matrices for each potato in the field. |
| |
| For each potato configuration, this function: |
| 1. Resolves channel selection (``None`` means all channels) |
| 2. Copies and picks the relevant channel subset |
| 3. Applies bandpass filtering for the target frequency band. |
| The paradigm already applies a broadband filter (e.g., 1-24 Hz |
| for P300); per-potato filtering further narrows within that band. |
| 4. Computes covariance matrices using Ledoit-Wolf shrinkage |
| 5. Optionally normalizes the covariances |
| |
| Parameters |
| ---------- |
| epochs : mne.Epochs |
| The input epochs. |
| config : list of dict |
| Potato field configuration. Each dict must contain: |
| ``channels`` (list of str or None for all channels), |
| ``low_freq``, ``high_freq``, ``metric``, ``normalization``, |
| and ``target``. |
| |
| Returns |
| ------- |
| cov_list : list of ndarray |
| List of covariance matrices arrays, one per potato. |
| """ |
| cov_list = [] |
| for potato_cfg in config: |
| channels = potato_cfg["channels"] |
| if channels is None: |
| channels = epochs.ch_names |
| ep = epochs.copy().pick(channels) |
| |
| |
| ep.filter( |
| l_freq=potato_cfg["low_freq"], |
| h_freq=potato_cfg["high_freq"], |
| method="iir", |
| verbose=False, |
| ) |
| covs = Covariances(estimator="lwf").transform(ep.get_data()) |
| if potato_cfg.get("normalization") is not None: |
| covs = normalize(covs, potato_cfg["normalization"]) |
| cov_list.append(covs) |
| return cov_list |
|
|
|
|
| def min_fisher_stouffer(probas, axis=0): |
| """Combine p-values as min(Fisher, Stouffer).""" |
| _, fisher_p = combine_pvalues(probas, method="fisher", axis=axis) |
| _, stouffer_p = combine_pvalues(probas, method="stouffer", axis=axis) |
| return np.minimum(fisher_p, stouffer_p) |
|
|
|
|
| |
| cov_list = compute_potato_covariances(epochs, POTATO_FIELD_CONFIG) |
|
|
| |
| rpf_vis = PotatoField( |
| n_potatoes=len(POTATO_FIELD_CONFIG), |
| metric={"mean": "riemann", "distance": "riemann"}, |
| z_threshold=3, |
| p_threshold=0.01, |
| ) |
| rpf_vis.fit(cov_list) |
| z_matrix = rpf_vis.transform(cov_list) |
| potato_z_scores = [z_matrix[:, i] for i in range(z_matrix.shape[1])] |
| potato_p_values = [1 - norm.cdf(z) for z in potato_z_scores] |
|
|
| for i, (z, cfg) in enumerate(zip(potato_z_scores, POTATO_FIELD_CONFIG)): |
| n_outliers = (z > 3).sum() |
| ch_list = cfg["channels"] if cfg["channels"] is not None else epochs.ch_names |
| ch_display = f"ch={ch_list[:3]}{'...' if len(ch_list) > 3 else ''}" |
| print( |
| f"Potato {i + 1} ({cfg['target']}): " |
| f"{n_outliers}/{len(z)} outliers, " |
| f"{ch_display}, " |
| f"freq={cfg['low_freq']}-{cfg['high_freq']} Hz" |
| ) |
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| fig, axes = plt.subplots(2, 3, figsize=(14, 7), facecolor="white") |
| axes = axes.ravel() |
|
|
| for i, (z, cfg) in enumerate(zip(potato_z_scores, POTATO_FIELD_CONFIG)): |
| ax = axes[i] |
| ax.hist(z, bins=40, alpha=0.7, color="#4C72B0", edgecolor="white") |
| ax.axvline(3, color="#C44E52", linestyle="--", linewidth=1.5, label="z=3") |
| n_out = (z > 3).sum() |
| ax.set_title( |
| f"Potato {i + 1}: {cfg['target']}\n" |
| f"({cfg['metric']}, {cfg['low_freq']:.0f}-{cfg['high_freq']:.0f} Hz, " |
| f"{n_out} outliers)", |
| fontsize=9, |
| ) |
| ax.set_xlabel("z-score") |
| ax.set_ylabel("Count") |
| ax.legend(fontsize=8) |
|
|
| fig.suptitle( |
| "Per-potato z-score distributions across the Potato Field", |
| fontsize=12, |
| fontweight="bold", |
| ) |
| plt.tight_layout() |
| plt.show() |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| n_potatoes = len(POTATO_FIELD_CONFIG) |
| combined_p = rpf_vis.predict_proba(cov_list) |
|
|
| sorted_p = np.sort(combined_p) |
|
|
| fig, axes = plt.subplots(1, 2, figsize=(12, 4), facecolor="white") |
|
|
| |
| axes[0].plot(sorted_p, ".-", markersize=2, color="#4C72B0") |
| axes[0].set_xlabel("Epoch index (sorted by SQI)") |
| axes[0].set_ylabel("Combined p-value (SQI)") |
| axes[0].set_title("RPF: Sorted Signal Quality Index\n(Fisher's combination)") |
| axes[0].set_yscale("log") |
| axes[0].axhline(0.01, color="#C44E52", linestyle="--", label="p = 0.01 threshold") |
| n_rejected = (combined_p < 0.01).sum() |
| axes[0].legend() |
| axes[0].annotate( |
| f"{n_rejected} epochs\nbelow threshold", |
| xy=(n_rejected // 2, 0.01), |
| xytext=(n_rejected + 50, 0.001), |
| fontsize=9, |
| arrowprops={"arrowstyle": "->", "color": "gray"}, |
| ) |
|
|
| |
| |
| sorted_idx = np.argsort(combined_p) |
| p_matrix_viz = np.array(potato_p_values) |
| p_sorted = p_matrix_viz[:, sorted_idx] |
| im = axes[1].imshow( |
| np.log10(p_sorted), aspect="auto", cmap="RdYlBu", interpolation="nearest" |
| ) |
| axes[1].set_xlabel("Epoch index (sorted by SQI)") |
| axes[1].set_ylabel("Potato index") |
| axes[1].set_yticks(range(n_potatoes)) |
| axes[1].set_yticklabels( |
| [f"P{i + 1}: {cfg['target']}" for i, cfg in enumerate(POTATO_FIELD_CONFIG)], |
| fontsize=8, |
| ) |
| axes[1].set_title("Per-potato log10(p-values)\n(sorted by combined SQI)") |
| plt.colorbar(im, ax=axes[1], label="log10(p-value)") |
|
|
| plt.tight_layout() |
| plt.show() |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
|
|
| def riemannian_potato_rejection(epochs): |
| """Reject artifacts using a single Riemannian Potato. |
| |
| Computes covariance matrices for all channels, fits a Potato, |
| and drops epochs whose geometric z-score exceeds the threshold. |
| |
| Note: The Potato is fit and evaluated on the same data. In a rigorous |
| benchmark you would fit only on training folds to avoid information |
| leakage. Here the Potato is an unsupervised outlier detector, so the |
| leakage is minimal and acceptable for tutorial purposes. |
| """ |
| data = epochs.get_data() |
| n_before = len(data) |
|
|
| covs = Covariances(estimator="lwf").transform(data) |
| potato = Potato(metric={"mean": "riemann", "distance": "riemann"}, threshold=3) |
| potato.fit(covs) |
| is_clean = predict_clean_mask(potato, covs) |
|
|
| n_rejected = n_before - is_clean.sum() |
| print(f" RP: rejected {n_rejected}/{n_before} epochs") |
|
|
| if is_clean.sum() == 0: |
| raise ValueError( |
| f"All {n_before} epochs rejected by Riemannian Potato — " |
| "consider raising the threshold or checking data quality." |
| ) |
| return epochs[is_clean] |
|
|
|
|
| def riemannian_potato_field_rejection(epochs): |
| """Reject artifacts using a Riemannian Potato Field. |
| |
| Uses pyriemann's ``PotatoField`` [2]_ with a single Riemannian metric |
| for all potatoes. Per-potato covariance matrices are computed on the |
| relevant channel subsets and frequency bands. The ``PotatoField`` |
| internally combines per-potato p-values using Fisher's method and |
| rejects epochs below the significance threshold. |
| |
| Note: The PotatoField is fit and evaluated on the same data. In a |
| rigorous benchmark you would fit only on training folds to avoid |
| information leakage. Here the potatoes are unsupervised outlier |
| detectors, so the leakage is minimal and acceptable for tutorial |
| purposes. |
| """ |
| n_before = len(epochs) |
| available_chs = set(epochs.ch_names) |
|
|
| |
| |
| valid_config = [ |
| cfg |
| for cfg in POTATO_FIELD_CONFIG |
| if cfg["channels"] is None or all(ch in available_chs for ch in cfg["channels"]) |
| ] |
| if not valid_config: |
| return epochs |
|
|
| cov_list = compute_potato_covariances(epochs, valid_config) |
|
|
| |
| rpf = PotatoField( |
| n_potatoes=len(valid_config), |
| metric={"mean": "riemann", "distance": "riemann"}, |
| z_threshold=3, |
| p_threshold=0.01, |
| ) |
| rpf.fit(cov_list) |
| is_clean = predict_clean_mask(rpf, cov_list) |
|
|
| n_rejected = n_before - is_clean.sum() |
| print(f" RPF: rejected {n_rejected}/{n_before} epochs") |
|
|
| if is_clean.sum() == 0: |
| raise ValueError( |
| f"All {n_before} epochs rejected by Riemannian Potato Field — " |
| "consider raising the threshold or checking data quality." |
| ) |
| return epochs[is_clean] |
|
|
|
|
| def compute_gfrms(data): |
| """Compute log-GFRMS (Global Field Root Mean Square) per sample per epoch. |
| |
| As described in [3]_, the GFRMS measures the instantaneous amplitude |
| across all channels at each time sample. The log transform compresses |
| the dynamic range and makes the distribution more symmetric. |
| |
| Parameters |
| ---------- |
| data : ndarray, shape (n_epochs, n_channels, n_samples) |
| The EEG data. |
| |
| Returns |
| ------- |
| gfrms : ndarray, shape (n_epochs, n_samples) |
| Log-GFRMS values per sample per epoch. |
| """ |
| |
| gfrms = np.sqrt(np.mean(data**2, axis=1)) |
| |
| gfrms = np.log(np.maximum(gfrms, 1e-30)) |
| return gfrms |
|
|
|
|
| def gfrms_amplitude_rejection(epochs, config, upper_limit=1.618): |
| """Pre-reject epochs using adaptive GFRMS amplitude thresholding. |
| |
| Implements the amplitude pre-rejection from [3]_ (Section 2.4.1). |
| Severely corrupted epochs are removed before the Riemannian potato |
| field analysis, preventing them from distorting the barycenter. |
| |
| The adaptive thresholds are derived from the GFRMS distribution: |
| |
| - ``lower``: 10th smallest GFRMS value (robust floor) |
| - ``m``: mean of GFRMS values in a window around the median |
| - ``upper``: ``m + (m - lower) * upper_limit`` |
| |
| The default ``upper_limit`` is the golden ratio (1.618), following |
| the Julia RAR implementation. |
| |
| Parameters |
| ---------- |
| epochs : mne.Epochs |
| The input epochs. |
| config : list of dict |
| Potato field configuration (used to determine the union frequency |
| band for filtering). |
| upper_limit : float |
| Multiplier for the upper threshold. Default is the golden ratio. |
| |
| Returns |
| ------- |
| is_clean : ndarray of bool, shape (n_epochs,) |
| True for epochs that pass amplitude thresholding. |
| gfrms : ndarray, shape (n_epochs, n_samples) |
| Log-GFRMS values for visualization. |
| lower : float |
| Lower adaptive threshold. |
| upper : float |
| Upper adaptive threshold. |
| m : float |
| Mean of the median window. |
| """ |
| |
| all_lows = [cfg["low_freq"] for cfg in config] |
| all_highs = [cfg["high_freq"] for cfg in config] |
| union_low = min(all_lows) |
| union_high = max(all_highs) |
|
|
| ep = epochs.copy().filter( |
| l_freq=union_low, h_freq=union_high, method="iir", verbose=False |
| ) |
| data = ep.get_data() |
|
|
| |
| gfrms = compute_gfrms(data) |
|
|
| |
| all_values = gfrms.ravel() |
| sorted_values = np.sort(all_values) |
| ns = len(sorted_values) |
| n_samples = gfrms.shape[1] |
|
|
| |
| mid = ns // 2 |
| half_w = min(n_samples, mid) |
| m = np.mean(sorted_values[mid - half_w : mid + half_w]) |
|
|
| |
| lower = sorted_values[min(9, ns - 1)] |
|
|
| |
| upper = m + (m - lower) * upper_limit |
|
|
| |
| epoch_min = np.min(gfrms, axis=1) |
| epoch_max = np.max(gfrms, axis=1) |
| is_clean = (epoch_min >= lower) & (epoch_max <= upper) |
|
|
| return is_clean, gfrms, lower, upper, m |
|
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| is_clean_gfrms, gfrms_values, gfrms_lower, gfrms_upper, gfrms_m = ( |
| gfrms_amplitude_rejection(epochs, POTATO_FIELD_CONFIG) |
| ) |
| n_gfrms_rejected = (~is_clean_gfrms).sum() |
| print(f"GFRMS pre-rejection: {n_gfrms_rejected}/{len(epochs)} epochs rejected") |
|
|
| fig, axes = plt.subplots(1, 2, figsize=(14, 5), facecolor="white") |
|
|
| |
| all_gfrms_sorted = np.sort(gfrms_values.ravel()) |
| axes[0].plot(all_gfrms_sorted, linewidth=0.5, color="#4C72B0") |
| axes[0].axhline( |
| gfrms_lower, |
| color="#55A868", |
| linestyle="--", |
| linewidth=1.5, |
| label=f"Lower = {gfrms_lower:.2f}", |
| ) |
| axes[0].axhline( |
| gfrms_upper, |
| color="#C44E52", |
| linestyle="--", |
| linewidth=1.5, |
| label=f"Upper = {gfrms_upper:.2f}", |
| ) |
| axes[0].axhline( |
| gfrms_m, |
| color="#DD8452", |
| linestyle=":", |
| linewidth=1.5, |
| label=f"m (median window mean) = {gfrms_m:.2f}", |
| ) |
| axes[0].set_xlabel("Sample index (sorted)") |
| axes[0].set_ylabel("log-GFRMS") |
| axes[0].set_title("Sorted log-GFRMS with adaptive thresholds\n(from iRPF [3])") |
| axes[0].legend(fontsize=8) |
|
|
| |
| epoch_max_gfrms = np.max(gfrms_values, axis=1) |
| colors_gfrms = np.where(is_clean_gfrms, "#4C72B0", "#C44E52") |
| axes[1].scatter( |
| range(len(epoch_max_gfrms)), epoch_max_gfrms, c=colors_gfrms, s=5, alpha=0.5 |
| ) |
| axes[1].axhline( |
| gfrms_upper, color="#C44E52", linestyle="--", linewidth=1.5, label="Upper threshold" |
| ) |
| axes[1].axhline( |
| gfrms_lower, color="#55A868", linestyle="--", linewidth=1.5, label="Lower threshold" |
| ) |
| axes[1].set_xlabel("Epoch index") |
| axes[1].set_ylabel("Max log-GFRMS per epoch") |
| axes[1].set_title( |
| f"GFRMS amplitude rejection: {n_gfrms_rejected}/{len(epochs)} epochs rejected" |
| ) |
| axes[1].legend(fontsize=8) |
|
|
| fig.suptitle( |
| "iRPF Stage 1: GFRMS Amplitude Pre-filtering", fontsize=12, fontweight="bold" |
| ) |
| plt.tight_layout() |
| plt.show() |
|
|
|
|
| def improved_rpf_rejection(epochs): |
| """Reject artifacts using an improved Riemannian Potato Field (iRPF). |
| |
| This implements two complementary rejection mechanisms from [3]_, |
| applied **in parallel** on the full data: |
| |
| **GFRMS amplitude rejection** (Section 2.4.1): |
| Computes the Global Field Root Mean Square (GFRMS) across all channels |
| and uses adaptive amplitude thresholds to catch severely corrupted |
| epochs that may not be detected by Riemannian analysis alone. |
| |
| **Potato field with per-potato metrics** (Section 2.4.4): |
| Uses ``PotatoField`` with per-potato distance metrics and a |
| custom combination callable implementing ``min(Fisher, Stouffer)``. |
| |
| Both mechanisms operate on the original data independently, and their |
| rejections are combined via union. This parallel approach avoids the |
| overcorrection that can occur when running GFRMS sequentially before |
| RPF: without the adaptive robust barycenter estimation from [3]_ |
| (Section 2.4.2), sequential GFRMS pre-rejection causes the barycenter |
| to become overly tight, leading to excessive false positives. |
| |
| Note: Each potato is fit and evaluated on the same data. In a rigorous |
| benchmark you would fit only on training folds to avoid information |
| leakage. Here the potatoes are unsupervised outlier detectors, so the |
| leakage is minimal and acceptable for tutorial purposes. |
| """ |
| n_before = len(epochs) |
| available_chs = set(epochs.ch_names) |
|
|
| valid_config = [ |
| cfg |
| for cfg in POTATO_FIELD_CONFIG |
| if cfg["channels"] is None or all(ch in available_chs for ch in cfg["channels"]) |
| ] |
| if not valid_config: |
| return epochs |
|
|
| |
| is_clean_amplitude, _, _, _, _ = gfrms_amplitude_rejection(epochs, valid_config) |
| n_amplitude_rejected = n_before - is_clean_amplitude.sum() |
|
|
| |
| cov_list = compute_potato_covariances(epochs, valid_config) |
| irpf = PotatoField( |
| n_potatoes=len(valid_config), |
| metric=[cfg["metric"] for cfg in valid_config], |
| z_threshold=3, |
| p_threshold=0.01, |
| method_combination=min_fisher_stouffer, |
| ) |
| irpf.fit(cov_list) |
| is_clean_rpf = predict_clean_mask(irpf, cov_list) |
|
|
| |
| is_clean = is_clean_amplitude & is_clean_rpf |
|
|
| n_rpf_rejected = (~is_clean_rpf).sum() |
| n_total_rejected = n_before - is_clean.sum() |
| print( |
| f" iRPF: GFRMS={n_amplitude_rejected}, " |
| f"RPF={n_rpf_rejected}, " |
| f"union={n_total_rejected}/{n_before} epochs rejected" |
| ) |
|
|
| if is_clean.sum() == 0: |
| raise ValueError( |
| f"All {n_before} epochs rejected by improved RPF — " |
| "consider raising the threshold or checking data quality." |
| ) |
| return epochs[is_clean] |
|
|
|
|
| |
| rp_pipeline = paradigm.make_process_pipelines(dataset)[0] |
| rp_pipeline.insert_step( |
| StepType.EPOCHS, |
| FunctionTransformer(riemannian_potato_rejection), |
| after=StepType.EPOCHS, |
| ) |
|
|
| rpf_pipeline = paradigm.make_process_pipelines(dataset)[0] |
| rpf_pipeline.insert_step( |
| StepType.EPOCHS, |
| FunctionTransformer(riemannian_potato_field_rejection), |
| after=StepType.EPOCHS, |
| ) |
|
|
| irpf_pipeline = paradigm.make_process_pipelines(dataset)[0] |
| irpf_pipeline.insert_step( |
| StepType.EPOCHS, FunctionTransformer(improved_rpf_rejection), after=StepType.EPOCHS |
| ) |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| pipelines = {} |
| pipelines["ERP+MDM"] = make_pipeline( |
| ERPCovariances(estimator="lwf"), |
| MDM(metric={"mean": "riemann", "distance": "riemann"}), |
| ) |
|
|
| evaluation = WithinSessionEvaluation( |
| paradigm=paradigm, datasets=[dataset], suffix="rar_tutorial", overwrite=True |
| ) |
|
|
| |
| |
| |
|
|
| |
| default_pipeline = paradigm.make_process_pipelines(dataset)[0] |
| results_default = list( |
| evaluation.evaluate( |
| dataset=dataset, |
| pipelines=pipelines, |
| param_grid=None, |
| process_pipeline=default_pipeline, |
| ) |
| ) |
| for r in results_default: |
| r["preprocessing"] = "No rejection" |
|
|
| |
| results_rp = list( |
| evaluation.evaluate( |
| dataset=dataset, |
| pipelines=pipelines, |
| param_grid=None, |
| process_pipeline=rp_pipeline, |
| ) |
| ) |
| for r in results_rp: |
| r["preprocessing"] = "RP" |
|
|
| |
| results_rpf = list( |
| evaluation.evaluate( |
| dataset=dataset, |
| pipelines=pipelines, |
| param_grid=None, |
| process_pipeline=rpf_pipeline, |
| ) |
| ) |
| for r in results_rpf: |
| r["preprocessing"] = "RPF" |
|
|
| |
| results_irpf = list( |
| evaluation.evaluate( |
| dataset=dataset, |
| pipelines=pipelines, |
| param_grid=None, |
| process_pipeline=irpf_pipeline, |
| ) |
| ) |
| for r in results_irpf: |
| r["preprocessing"] = "iRPF" |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| all_results = results_default + results_rp + results_rpf + results_irpf |
| df = pd.DataFrame(all_results) |
|
|
| order = ["No rejection", "RP", "RPF", "iRPF"] |
| colors = ["#4C72B0", "#DD8452", "#55A868", "#C44E52"] |
| metrics = {"score_roc_auc": "ROC AUC", "score_f1": "F1-Score"} |
|
|
| fig, axes = plt.subplots(1, 2, figsize=(14, 5), facecolor="white") |
|
|
| for ax, (metric_col, metric_name) in zip(axes, metrics.items()): |
| grouped = df.groupby("preprocessing")[metric_col] |
| means = grouped.mean().reindex(order) |
| stds = grouped.std().reindex(order) |
|
|
| bars = ax.bar(order, means, yerr=stds, capsize=5, color=colors, edgecolor="white") |
| ax.set_ylabel(metric_name) |
| ax.set_xlabel("Preprocessing Method") |
| ax.set_title(f"P300 Classification: {metric_name}") |
|
|
| if metric_col == "score_roc_auc": |
| ax.set_ylim(0.5, 1.0) |
| else: |
| ax.set_ylim(0, 1.0) |
|
|
| for bar, mean in zip(bars, means): |
| ax.text( |
| bar.get_x() + bar.get_width() / 2.0, |
| bar.get_height() + 0.01, |
| f"{mean:.3f}", |
| ha="center", |
| va="bottom", |
| fontsize=10, |
| ) |
|
|
| fig.suptitle( |
| "BNCI2014-009: Effect of Riemannian Artifact Rejection", |
| fontsize=13, |
| fontweight="bold", |
| ) |
| plt.tight_layout() |
| plt.show() |
|
|
| |
| |
| |
|
|
| fig, axes = plt.subplots(1, 2, figsize=(14, 5), facecolor="white") |
|
|
| sessions = sorted(df["session"].unique()) |
| x = np.arange(len(sessions)) |
| width = 0.2 |
|
|
| for ax, (metric_col, metric_name) in zip(axes, metrics.items()): |
| for i, (method, color) in enumerate(zip(order, colors)): |
| method_df = df.loc[df["preprocessing"] == method] |
| |
| session_scores = method_df.groupby("session")[metric_col].mean() |
| scores = [session_scores.get(s, np.nan) for s in sessions] |
| ax.bar(x + i * width, scores, width, label=method, color=color, edgecolor="white") |
|
|
| ax.set_xlabel("Session") |
| ax.set_ylabel(metric_name) |
| ax.set_title(f"Per-session {metric_name}") |
| ax.set_xticks(x + 1.5 * width) |
| ax.set_xticklabels([f"Session {s}" for s in sessions]) |
| ax.legend() |
|
|
| if metric_col == "score_roc_auc": |
| ax.set_ylim(0.5, 1.0) |
| else: |
| ax.set_ylim(0, 1.0) |
|
|
| plt.tight_layout() |
| plt.show() |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| rpf_combined_p = rpf_vis.predict_proba(cov_list) |
|
|
| |
| |
| |
| irpf_vis = PotatoField( |
| n_potatoes=len(POTATO_FIELD_CONFIG), |
| metric=[cfg["metric"] for cfg in POTATO_FIELD_CONFIG], |
| z_threshold=3, |
| p_threshold=0.01, |
| method_combination=min_fisher_stouffer, |
| ) |
| irpf_vis.fit(cov_list) |
| irpf_combined_p = irpf_vis.predict_proba(cov_list) |
|
|
| fig, axes = plt.subplots(1, 2, figsize=(14, 5), facecolor="white") |
|
|
| |
| sorted_rpf = np.sort(rpf_combined_p) |
| sorted_irpf = np.sort(irpf_combined_p) |
| axes[0].plot(sorted_rpf, ".-", markersize=2, color="#55A868", label="RPF (Fisher)") |
| axes[0].plot(sorted_irpf, ".-", markersize=2, color="#C44E52", label="iRPF (min)") |
| axes[0].set_xlabel("Epoch index (sorted by SQI)") |
| axes[0].set_ylabel("Combined p-value (SQI)") |
| axes[0].set_title("Sorted SQI: RPF vs iRPF") |
| axes[0].set_yscale("log") |
| axes[0].axhline(0.01, color="k", linestyle="--", linewidth=1, label="p = 0.01 threshold") |
| axes[0].legend(fontsize=8) |
|
|
| n_rpf_rejected = (rpf_combined_p < 0.01).sum() |
| n_irpf_rejected = (irpf_combined_p < 0.01).sum() |
| axes[0].annotate( |
| f"RPF rejects {n_rpf_rejected}\niRPF rejects {n_irpf_rejected}", |
| xy=(0.02, 0.02), |
| xycoords="axes fraction", |
| fontsize=9, |
| bbox={"boxstyle": "round,pad=0.3", "facecolor": "wheat", "alpha": 0.5}, |
| ) |
|
|
| |
| axes[1].scatter(rpf_combined_p, irpf_combined_p, s=5, alpha=0.5, color="#4C72B0") |
| axes[1].plot([1e-10, 1], [1e-10, 1], "k--", linewidth=0.5, alpha=0.5) |
| axes[1].axhline(0.01, color="#C44E52", linestyle=":", linewidth=1, label="p = 0.01") |
| axes[1].axvline(0.01, color="#55A868", linestyle=":", linewidth=1, label="p = 0.01") |
| axes[1].set_xlabel("RPF p-value (Fisher)") |
| axes[1].set_ylabel("iRPF p-value (min(Fisher, Stouffer))") |
| axes[1].set_title("RPF vs iRPF: per-epoch combined p-values") |
| axes[1].set_xscale("log") |
| axes[1].set_yscale("log") |
| axes[1].legend() |
|
|
| plt.tight_layout() |
| plt.show() |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|