Trust-gated synthetic EEG augmentation reduces performance drops when generalizing to new patients.
The 15 matches
- [1] § Methods ↔ tga/runner.py, lines 224–236 · score 0.73 · geometry aware teacher, logistic regression, transform, classifier, covariance, trained
- [2] § Methods ↔ scripts/legacy/run_TGA_pack_motor_bciiv2a_binary.py, lines 10–115 · score 0.66 · BCI IV, motor imagery, 38 Hz, padding, scoring
- [3] § Methods ↔ scripts/tga_painmunich_pack_resting_eeg.py, lines 74–149 · score 0.64 · notch filtered, rejected, Artifact, stride, 45 Hz, channel
- [4] § Methods ↔ scripts/legacy/run_TGA_plot_calibration.py, lines 8–85 · score 0.61 · threshold probability, Decision curve, reliability, calibration, bins
- [5] § Methods ↔ tga/runner.py, lines 76–119 · score 0.61 · subject stratified validation, class balanced, split
- [6] § Methods ↔ tga/runner.py, lines 184–193 · score 0.59 · Ledoit Wolf, shrinkage covariance, windows
- [7] § Results ↔ tga/runner.py, lines 224–236 · score 0.58 · geometry aware teacher, covariance features, transform, class, training
- [8] § Results ↔ scripts/legacy/run_TGA_summarize_paper_packet.py, lines 76–221 · score 0.54 · paired deltas, harm rate, worst, framing, baseline, seed
- [9] § Results ↔ scripts/legacy/run_TGA_negative_control_random_gate.py, lines 202–272 · score 0.54 · random gating, ShallowConvNet, EEGNet, matched
- [10] § Methods ↔ scripts/legacy/run_TGA_pain_calibration_replay.py, lines 232–295 · score 0.52 · Decision curve, Brier, ECE, threshold, calibration, bins
- [11] § Results ↔ scripts/legacy/run_TGA_summarize_subjectlevel.py, lines 41–185 · score 0.52 · paired deltas, harm rate, metrics, framing, baseline, seed
- [12] § Results ↔ scripts/legacy/run_TGA_plot_calibration.py, lines 8–85 · score 0.52 · threshold probabilities, Decision curve, calibration, EEGNet, scarcity, gating
- [13] § Methods ↔ scripts/legacy/run_TGA_pack_motor_bciiv2a_binary.py, lines 10–115 · score 0.52 · motor imagery, binary, BCI, IV, classes
- [14] § Methods ↔ scripts/legacy/run_TGA_generate_pain_pool_vae_ldm.py, lines 526–576 · score 0.52 · X_pool.npy, y_pool.npy, reused, seed, fold
- [15] § Methods ↔ scripts/legacy/run_TGA_build_pain_pool_vae_ldm.py, lines 1296–1324 · score 0.51 · X_pool.npy, y_pool.npy, reused, class
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 · 540 lines · 18 KB · MIT · 4 matches
- """TGA runner utilities (reviewer-proof).
- This module is intentionally self-contained so a reviewer can:
- - install dependencies from `requirements.txt`
- - run the analysis/replay scripts in `scripts/`
- It implements the minimal APIs expected by the provided scripts.
- Important note on reproducibility:
- The manuscript uses fixed-fold, subject-disjoint evaluation with a teacher gate
- and a fail-closed selection rule. The heavy generator training routines are in
- separate scripts. The functions here focus on evaluation discipline and the
- teacher gate, and provide reference EEGNet / ShallowConvNet implementations.
- If you have a GPU and the required data packaged as `.npz`, you can run end-to-end
- experiments. Otherwise, you can still reproduce analysis artifacts from existing
- run folders.
- """
- from __future__ import annotations
- import glob
- import os
- from dataclasses import dataclass
- from pathlib import Path
- from typing import Iterable, Optional, Tuple
- import numpy as np
- # ML
- from sklearn.covariance import LedoitWolf
- from sklearn.linear_model import LogisticRegression
- from sklearn.metrics import average_precision_score, roc_auc_score
- from sklearn.preprocessing import StandardScaler
- # Torch
- import torch
- import torch.nn as nn
- import torch.nn.functional as F
- # -----------------------------------------------------------------------------
- # Basic helpers
- # -----------------------------------------------------------------------------
- def seed_all(seed: int) -> None:
- """Seed numpy and torch."""
- np.random.seed(seed)
- torch.manual_seed(seed)
- torch.cuda.manual_seed_all(seed)
- def load_meta_array(meta_npz: np.lib.npyio.NpzFile, key: str, N: int) -> np.ndarray:
- """Load an array from meta.npz and validate length."""
- if key not in meta_npz:
- raise KeyError(f"meta_npz missing key='{key}'. Available={list(meta_npz.keys())}")
- arr = np.asarray(meta_npz[key])
- if arr.shape[0] != N:
- raise ValueError(f"meta[{key}] length {arr.shape[0]} != N {N}")
- return arr
- def _subject_majority_labels(y: np.ndarray, groups: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
- """Return (unique_subjects, subject_label) using majority vote over windows."""
- groups = np.asarray(groups)
- y = np.asarray(y).astype(int)
- subs = np.unique(groups)
- y_sub = np.zeros(len(subs), dtype=int)
- for i, s in enumerate(subs):
- m = groups == s
- vals, cnt = np.unique(y[m], return_counts=True)
- y_sub[i] = int(vals[int(np.argmax(cnt))])
- return subs, y_sub
- def make_val_split_subject_stratified(
- trainval_idx: np.ndarray,
- y: np.ndarray,
- groups: np.ndarray,
- val_frac: float,
- rng: np.random.Generator,
- ) -> Tuple[np.ndarray, np.ndarray]:
- """Subject-stratified validation split.
- Splits by subject (group) to avoid leakage. Attempts to preserve class balance
- at the subject level.
- """
- trainval_idx = np.asarray(trainval_idx)
- y_tv = np.asarray(y)[trainval_idx]
- g_tv = np.asarray(groups)[trainval_idx]
- subs, y_sub = _subject_majority_labels(y_tv, g_tv)
- # Stratify subjects by label
- subs0 = subs[y_sub == 0]
- subs1 = subs[y_sub == 1]
- n_val0 = max(1, int(round(len(subs0) * val_frac))) if len(subs0) > 0 else 0
- n_val1 = max(1, int(round(len(subs1) * val_frac))) if len(subs1) > 0 else 0
- val_subs = []
- if len(subs0) > 0:
- val_subs.append(rng.choice(subs0, size=min(n_val0, len(subs0)), replace=False))
- if len(subs1) > 0:
- val_subs.append(rng.choice(subs1, size=min(n_val1, len(subs1)), replace=False))
- if len(val_subs) == 0:
- # Degenerate case; fall back to random split by index
- n_val = max(1, int(round(len(trainval_idx) * val_frac)))
- perm = rng.permutation(trainval_idx)
- return perm[n_val:], perm[:n_val]
- val_subs = np.concatenate(val_subs)
- is_val = np.isin(g_tv, val_subs)
- va_idx = trainval_idx[is_val]
- tr_idx = trainval_idx[~is_val]
- return tr_idx, va_idx
- def apply_scarcity_by_subject_stratified(
- tr_idx: np.ndarray,
- y: np.ndarray,
- groups: np.ndarray,
- scarcity: float,
- rng: np.random.Generator,
- ) -> np.ndarray:
- """Subsample training subjects to emulate scarcity."""
- tr_idx = np.asarray(tr_idx)
- if scarcity >= 0.999:
- return tr_idx
- y_tr = np.asarray(y)[tr_idx]
- g_tr = np.asarray(groups)[tr_idx]
- subs, y_sub = _subject_majority_labels(y_tr, g_tr)
- subs0 = subs[y_sub == 0]
- subs1 = subs[y_sub == 1]
- # Choose at least 1 subject per class when possible
- n_keep0 = max(1, int(round(len(subs0) * scarcity))) if len(subs0) > 0 else 0
- n_keep1 = max(1, int(round(len(subs1) * scarcity))) if len(subs1) > 0 else 0
- keep_subs = []
- if len(subs0) > 0:
- keep_subs.append(rng.choice(subs0, size=min(n_keep0, len(subs0)), replace=False))
- if len(subs1) > 0:
- keep_subs.append(rng.choice(subs1, size=min(n_keep1, len(subs1)), replace=False))
- if len(keep_subs) == 0:
- # fallback: uniform subsample by index
- n_keep = max(1, int(round(len(tr_idx) * scarcity)))
- return rng.choice(tr_idx, size=n_keep, replace=False)
- keep_subs = np.concatenate(keep_subs)
- mask = np.isin(g_tr, keep_subs)
- return tr_idx[mask]
- def zscore_per_subject(X: np.ndarray, groups: np.ndarray, eps: float = 1e-8) -> np.ndarray:
- """Per-subject, per-channel z-score normalization.
- X: (N, C, T)
- groups: (N,) subject IDs
- """
- X = np.asarray(X, dtype=np.float32)
- g = np.asarray(groups)
- out = np.empty_like(X)
- for s in np.unique(g):
- m = g == s
- Xi = X[m]
- # mean/std per channel over all windows and time
- mu = Xi.mean(axis=(0, 2), keepdims=True)
- sd = Xi.std(axis=(0, 2), keepdims=True)
- out[m] = (Xi - mu) / (sd + eps)
- return out
- # -----------------------------------------------------------------------------
- # Teacher: SPD covariance features + logistic regression
- # -----------------------------------------------------------------------------
- def _covariance_ledoitwolf(x_ct: np.ndarray, eps: float = 1e-6) -> np.ndarray:
- """Compute shrinkage covariance for one window.
- x_ct: (C, T)
- """
- x_tc = np.asarray(x_ct, dtype=np.float64).T # (T, C)
- lw = LedoitWolf().fit(x_tc)
- cov = lw.covariance_
- cov = cov + eps * np.eye(cov.shape[0])
- return cov
- def _logm_spd(cov: np.ndarray) -> np.ndarray:
- """Log-Euclidean map for SPD matrix via eigen-decomposition."""
- w, V = np.linalg.eigh(cov)
- w = np.clip(w, 1e-12, None)
- logw = np.log(w)
- return (V * logw[None, :]) @ V.T
- def _vec_upper(mat: np.ndarray) -> np.ndarray:
- iu = np.triu_indices(mat.shape[0])
- return mat[iu]
- def covariance_features_logeuclid(X: np.ndarray, eps: float = 1e-6) -> np.ndarray:
- """Compute log-Euclidean covariance features for a batch.
- Returns a 2D array of shape (N, D).
- """
- X = np.asarray(X)
- N, C, T = X.shape
- feats = np.zeros((N, C * (C + 1) // 2), dtype=np.float64)
- for i in range(N):
- cov = _covariance_ledoitwolf(X[i], eps=eps)
- logc = _logm_spd(cov)
- feats[i] = _vec_upper(logc)
- return feats
- def train_teacher(Xtr: np.ndarray, ytr: np.ndarray, seed: int = 0, eps: float = 1e-6):
- """Train the geometry-aware teacher (scaler + logistic regression)."""
- seed_all(seed)
- feats = covariance_features_logeuclid(Xtr, eps=eps)
- scaler = StandardScaler().fit(feats)
- Xs = scaler.transform(feats)
- clf = LogisticRegression(
- max_iter=1000,
- class_weight="balanced",
- solver="liblinear",
- random_state=seed,
- ).fit(Xs, ytr)
- return scaler, clf
- def teacher_filter_agree_quantile(
- Xs: np.ndarray,
- ys: np.ndarray,
- scaler: StandardScaler,
- clf: LogisticRegression,
- keep_quantile: float,
- min_keep: int = 200,
- eps: float = 1e-6,
- ):
- """Filter synthetic candidates by teacher agreement and confidence quantile.
- Returns (X_keep, y_keep).
- """
- if Xs is None or ys is None or len(ys) == 0:
- return np.empty((0,), dtype=np.float32), np.empty((0,), dtype=np.int64)
- feats = covariance_features_logeuclid(Xs, eps=eps)
- Xf = scaler.transform(feats)
- proba = clf.predict_proba(Xf)
- pred = np.argmax(proba, axis=1)
- conf = np.max(proba, axis=1)
- ys = np.asarray(ys).astype(int)
- agree = pred == ys
- if agree.sum() < min_keep:
- # Fail closed: too few label-consistent samples.
- return np.empty((0, Xs.shape[1], Xs.shape[2]), dtype=np.float32), np.empty((0,), dtype=np.int64)
- conf_agree = conf[agree]
- tau = np.quantile(conf_agree, keep_quantile)
- keep = agree & (conf >= tau)
- # If pruning is too strict but we have enough agreeing samples, keep top-min_keep
- if keep.sum() < min_keep:
- idx_agree = np.where(agree)[0]
- order = np.argsort(-conf[idx_agree])
- idx_keep = idx_agree[order[:min_keep]]
- else:
- idx_keep = np.where(keep)[0]
- return np.asarray(Xs[idx_keep], dtype=np.float32), np.asarray(ys[idx_keep], dtype=np.int64)
- def find_synth_pool(pool_root: str, seed: int, fold: int) -> Tuple[np.ndarray, np.ndarray]:
- """Locate and load (X_pool.npy, y_pool.npy) for a given seed and fold.
- This helper tries common directory patterns and falls back to a glob search.
- """
- root = Path(pool_root)
- candidates = [
- root / f"seed_{seed}" / f"fold_{fold}" / "X_pool.npy",
- root / f"seed{seed}" / f"fold{fold}" / "X_pool.npy",
- root / f"seed_{seed}" / f"fold{fold}" / "X_pool.npy",
- root / f"seed{seed}" / f"fold_{fold}" / "X_pool.npy",
- ]
- x_path: Optional[Path] = None
- for c in candidates:
- if c.exists():
- x_path = c
- break
- if x_path is None:
- # Glob fallback
- patt = str(root / f"**/*seed*{seed}*/*fold*{fold}*/X_pool.npy")
- hits = glob.glob(patt, recursive=True)
- if hits:
- x_path = Path(hits[0])
- if x_path is None:
- raise FileNotFoundError(
- f"Could not find X_pool.npy for seed={seed}, fold={fold} under {pool_root}. "
- f"Tried common patterns and glob." )
- y_path = x_path.parent / "y_pool.npy"
- if not y_path.exists():
- # Some pools use Y_pool.npy
- y_path2 = x_path.parent / "Y_pool.npy"
- if y_path2.exists():
- y_path = y_path2
- else:
- raise FileNotFoundError(f"Found {x_path} but missing y_pool.npy in {x_path.parent}")
- Xs = np.load(x_path)
- ys = np.load(y_path)
- return np.asarray(Xs, dtype=np.float32), np.asarray(ys, dtype=np.int64)
- # -----------------------------------------------------------------------------
- # Torch models
- # -----------------------------------------------------------------------------
- class EEGNet(nn.Module):
- """A compact EEGNet-like architecture for (C, T) windows."""
- def __init__(self, C: int, T: int, n_classes: int = 2, F1: int = 8, D: int = 2, F2: int = 16, dropout: float = 0.25):
- super().__init__()
- self.C = C
- self.T = T
- # Block 1: temporal conv
- self.conv_temporal = nn.Conv2d(1, F1, kernel_size=(1, 64), padding=(0, 32), bias=False)
- self.bn1 = nn.BatchNorm2d(F1)
- # Depthwise spatial conv
- self.conv_spatial = nn.Conv2d(F1, F1 * D, kernel_size=(C, 1), groups=F1, bias=False)
- self.bn2 = nn.BatchNorm2d(F1 * D)
- self.act = nn.ELU()
- self.pool1 = nn.AvgPool2d(kernel_size=(1, 4))
- self.drop1 = nn.Dropout(dropout)
- # Separable conv
- self.sep_depth = nn.Conv2d(F1 * D, F1 * D, kernel_size=(1, 16), padding=(0, 8), groups=F1 * D, bias=False)
- self.sep_point = nn.Conv2d(F1 * D, F2, kernel_size=(1, 1), bias=False)
- self.bn3 = nn.BatchNorm2d(F2)
- self.pool2 = nn.AvgPool2d(kernel_size=(1, 8))
- self.drop2 = nn.Dropout(dropout)
- # Compute flattened dim
- with torch.no_grad():
- x = torch.zeros(1, 1, C, T)
- x = self.drop1(self.pool1(self.act(self.bn2(self.conv_spatial(self.bn1(self.conv_temporal(x)))))))
- x = self.drop2(self.pool2(self.act(self.bn3(self.sep_point(self.sep_depth(x))))))
- flat = int(np.prod(x.shape[1:]))
- self.classifier = nn.Linear(flat, n_classes)
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- # x: (N, C, T)
- x = x.unsqueeze(1) # (N, 1, C, T)
- x = self.conv_temporal(x)
- x = self.bn1(x)
- x = self.conv_spatial(x)
- x = self.bn2(x)
- x = self.act(x)
- x = self.pool1(x)
- x = self.drop1(x)
- x = self.sep_depth(x)
- x = self.sep_point(x)
- x = self.bn3(x)
- x = self.act(x)
- x = self.pool2(x)
- x = self.drop2(x)
- x = torch.flatten(x, start_dim=1)
- return self.classifier(x)
- class ShallowConvNet(nn.Module):
- """A shallow ConvNet variant for (C, T) windows."""
- def __init__(self, C: int, T: int, n_classes: int = 2, F: int = 40, dropout: float = 0.5):
- super().__init__()
- self.conv_time = nn.Conv2d(1, F, kernel_size=(1, 25), padding=(0, 12), bias=False)
- self.conv_spat = nn.Conv2d(F, F, kernel_size=(C, 1), bias=False)
- self.bn = nn.BatchNorm2d(F)
- self.pool = nn.AvgPool2d(kernel_size=(1, 75), stride=(1, 15))
- self.drop = nn.Dropout(dropout)
- with torch.no_grad():
- x = torch.zeros(1, 1, C, T)
- x = self.conv_time(x)
- x = self.conv_spat(x)
- x = self.bn(x)
- x = torch.square(x)
- x = self.pool(x)
- x = torch.log(torch.clamp(x, min=1e-6))
- x = self.drop(x)
- flat = int(np.prod(x.shape[1:]))
- self.classifier = nn.Linear(flat, n_classes)
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- x = x.unsqueeze(1)
- x = self.conv_time(x)
- x = self.conv_spat(x)
- x = self.bn(x)
- x = torch.square(x)
- x = self.pool(x)
- x = torch.log(torch.clamp(x, min=1e-6))
- x = self.drop(x)
- x = torch.flatten(x, start_dim=1)
- return self.classifier(x)
- # -----------------------------------------------------------------------------
- # Training / inference
- # -----------------------------------------------------------------------------
- @torch.no_grad()
- def torch_predict_proba(model: nn.Module, X: np.ndarray, device: str = "cpu", infer_bs: int = 256, num_workers: int = 0) -> np.ndarray:
- model.eval()
- model.to(device)
- X = np.asarray(X, dtype=np.float32)
- N = X.shape[0]
- out = np.zeros((N, 2), dtype=np.float32)
- for i in range(0, N, infer_bs):
- xb = torch.from_numpy(X[i:i+infer_bs]).to(device)
- logits = model(xb)
- probs = torch.softmax(logits, dim=1).cpu().numpy()
- out[i:i+infer_bs] = probs
- return out
- def _safe_auc(y: np.ndarray, p: np.ndarray) -> float:
- y = np.asarray(y).reshape(-1)
- p = np.asarray(p).reshape(-1)
- if len(np.unique(y)) < 2:
- return float("nan")
- return float(roc_auc_score(y, p))
- def _safe_ap(y: np.ndarray, p: np.ndarray) -> float:
- y = np.asarray(y).reshape(-1)
- p = np.asarray(p).reshape(-1)
- if len(np.unique(y)) < 2:
- return float("nan")
- return float(average_precision_score(y, p))
- def train_torch_model(
- model: nn.Module,
- n_classes: int,
- Xtr: np.ndarray,
- ytr: np.ndarray,
- Xva: np.ndarray,
- yva: np.ndarray,
- device: str = "cpu",
- epochs: int = 100,
- patience: int = 15,
- lr: float = 1e-3,
- weight_decay: float = 0.0,
- batch_size: int = 128,
- infer_bs: int = 256,
- num_workers: int = 0,
- amp: bool = False,
- seed: int = 0,
- log_path: Optional[str] = None,
- ):
- """Train a torch model with early stopping on validation AUROC.
- Returns: (best_model, best_val_auc, best_val_ap, fallback_flag)
- """
- seed_all(seed)
- Xtr = np.asarray(Xtr, dtype=np.float32)
- ytr = np.asarray(ytr, dtype=np.int64)
- Xva = np.asarray(Xva, dtype=np.float32)
- yva = np.asarray(yva, dtype=np.int64)
- model = model.to(device)
- # Class-balanced weights
- cls_counts = np.bincount(ytr, minlength=n_classes).astype(np.float32)
- cls_counts = np.maximum(cls_counts, 1.0)
- weights = (cls_counts.sum() / (n_classes * cls_counts))
- w_t = torch.tensor(weights, dtype=torch.float32, device=device)
- opt = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay)
- scaler = torch.cuda.amp.GradScaler(enabled=(amp and device.startswith("cuda")))
- best_auc = -1e9
- best_ap = -1e9
- best_state = None
- bad = 0
- # simple numpy batching
- idx = np.arange(len(ytr))
- for ep in range(epochs):
- model.train()
- np.random.shuffle(idx)
- for i in range(0, len(idx), batch_size):
- b = idx[i:i+batch_size]
- xb = torch.from_numpy(Xtr[b]).to(device)
- yb = torch.from_numpy(ytr[b]).to(device)
- opt.zero_grad(set_to_none=True)
- with torch.cuda.amp.autocast(enabled=(amp and device.startswith("cuda"))):
- logits = model(xb)
- loss = F.cross_entropy(logits, yb, weight=w_t)
- scaler.scale(loss).backward()
- scaler.step(opt)
- scaler.update()
- # validation
- probs = torch_predict_proba(model, Xva, device=device, infer_bs=infer_bs, num_workers=0)
- p1 = probs[:, 1]
- vauc = _safe_auc(yva, p1)
- vap = _safe_ap(yva, p1)
- if np.isfinite(vauc) and vauc > best_auc + 1e-6:
- best_auc = float(vauc)
- best_ap = float(vap)
- best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
- bad = 0
- else:
- bad += 1
- if bad >= patience:
- break
- if best_state is not None:
- model.load_state_dict(best_state)
- return model, float(best_auc), float(best_ap), False
runner.py at commit 1ac3d64, under MIT · at the source
Overview
Abstract
The abstract is not reproduced here: the paper's license (CC BY-NC-ND) does not allow it. Read it in the paper, at the publisher or on Europe PMC.
Repository
Its files are read in the Code ↔ Paper reader above, with 15 matches between paragraphs and lines of code.
danielchoi0315/TGA-repo
1ac3d641a1b63a1514a50dfa77fbe07bde1e250e, 30 August 2026Availability: 1 check, the latest on 28 September 2026: the link answers
- 28 September 2026: the link answers
54 files
- scripts/
legacy/ , Python, 4 linesrun_TGA_build_pain_manif est.py - scripts/
legacy/ , Python, 1,433 lines, 1 matchrun_TGA_build_pain_pool_ vae_ldm.py - scripts/
legacy/ , Python, 115 linesrun_TGA_fix_brainvision_ refs.py - scripts/
legacy/ , Python, 71 linesrun_TGA_fix_raw_results_ csv.py - scripts/
legacy/ , Python, 694 lines, 1 matchrun_TGA_generate_pain_po ol_vae_ldm.py - scripts/
legacy/ , Python, 4 linesrun_TGA_make_pain_plan.p y - scripts/
legacy/ , Python, 184 linesrun_TGA_motor_manifold_d iagnostic.py - scripts/
legacy/ , Python, 275 lines, 1 matchrun_TGA_negative_control _random_gate.py - scripts/
legacy/ , Python, 519 linesrun_TGA_osf_download_rec ursive.py - scripts/
legacy/ , Python, 118 lines, 2 matchesrun_TGA_pack_motor_bciiv 2a_binary.py - scripts/
legacy/ , Python, 4 linesrun_TGA_pack_pain_from_p lan.py - scripts/
legacy/ , Python, 4 linesrun_TGA_pack_pain_restin g_eeg.py - scripts/
legacy/ , Python, 298 lines, 1 matchrun_TGA_pain_calibration _replay.py - scripts/
legacy/ , Python, 301 linesrun_TGA_pain_subject_lev el_replay.py - scripts/
legacy/ , Python, 286 linesrun_TGA_pain_subject_lev el_replay_sharded.py - scripts/
legacy/ , Python, 4 linesrun_TGA_pipeline.py - scripts/
legacy/ , Python, 4 linesrun_TGA_pipeline_fastcac he.py - scripts/
legacy/ , Python, 88 lines, 2 matchesrun_TGA_plot_calibration .py - scripts/
legacy/ , Python, 224 lines, 1 matchrun_TGA_summarize_paper_ packet.py - scripts/
legacy/ , Python, 188 lines, 1 matchrun_TGA_summarize_subjec tlevel.py - scripts/
legacy/ , Python, 375 linesrun_TGA_train_motor_ddpm _unet_ema.py - scripts/
run_TGA_build_motor_pool , Shell, 48 liness_5x5_ema.sh - scripts/
run_TGA_build_pain_manif , Python, 4 linesest.py - scripts/
run_TGA_build_pain_pools , Shell, 18 lines_5x5.sh - scripts/
run_TGA_make_pain_plan.p , Python, 4 linesy - scripts/
run_TGA_pack_pain_from_p , Python, 4 lineslan.py - scripts/
run_TGA_pack_pain_restin , Python, 4 linesg_eeg.py - scripts/
run_TGA_pain_manifold_au , Shell, 54 linesdit_5x5.sh - scripts/
run_TGA_pipeline.py , Python, 20 lines - scripts/
run_TGA_pipeline_fastcac , Python, 9 lineshe.py - scripts/
tga_build_pain_pool_vae_ , Python, 1,433 linesldm.py - scripts/
tga_download_osf_recursi , Python, 519 linesve.py - scripts/
tga_fix_brainvision_refs , Python, 115 lines.py - scripts/
tga_fix_raw_results_csv. , Python, 71 linespy - scripts/
tga_generate_pain_pool_v , Python, 694 linesae_ldm.py - scripts/
tga_motor_manifold_diagn , Python, 184 linesostic.py - scripts/
tga_pack_bciiv2a_binary. , Python, 118 linespy - scripts/
tga_painmunich_build_man , Python, 64 linesifest.py - scripts/
tga_painmunich_make_plan , Python, 54 lines.py - scripts/
tga_painmunich_pack_from , Python, 43 lines_plan.py - scripts/
tga_painmunich_pack_rest , Python, 153 lines, 1 matching_eeg.py - scripts/
tga_plot_calibration.py , Python, 88 lines - scripts/
tga_random_gating_negati , Python, 275 linesve_control.py - scripts/
tga_replay_pain_calibrat , Python, 298 linesion.py - scripts/
tga_replay_pain_subject_ , Python, 301 lineslevel.py - scripts/
tga_replay_pain_subject_ , Python, 286 lineslevel_sharded.py - scripts/
tga_summarize_paper_pack , Python, 224 lineset.py - scripts/
tga_summarize_subjectlev , Python, 188 linesel.py - scripts/
tga_train_motor_ddpm_une , Python, 375 linest_ema.py - tests/
test_torch_rng_compat.py , Python, 61 lines - tga/
__init__.py , Python, 1 line - tga/
runner.py , Python, 540 lines, 4 matches - LICENSE, License, 21 lines
- README.md, Text, 69 lines
Code availability statement
The paper has a code availability statement. Its license (CC BY-NC-ND) does not allow reproducing it here; in short, from what the harvester recognized in it:
- it points to the authors' code: danielchoi0315/
TGA-repo
Read it in the paper: doi.org/10.1038/s41746-026-02778-0.
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;
- 52 scripts, each with its path and the digest of its content;
- 15 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
- bbci.de/
competition/ , at bbci.de; found in “Data availability”iv - osf:srpbg, at OSF; found in the text, “Methods”
Data availability statement
The paper has a data availability statement. Its license (CC BY-NC-ND) does not allow reproducing it here; in short, from what the harvester recognized in it:
- it points to a dataset: bbci.de/
competition/ iv
Read it in the paper: doi.org/10.1038/s41746-026-02778-0.
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 1, 28 September 2026: the first record
Recorded: type, language, journal, volume, issue, pages, dates, 4 authors, 4 keywords, 1 funder, 16 references.
Cite
This paper
Choi, D., Yip, C., Choi, A., & Park, J. (2026). Trust-gated synthetic EEG augmentation reduces performance drops when generalizing to new patients. NPJ digital medicine, 9(1), 634. https://
BibTeX
@article{choi2026trust,
author = {Choi, Daniel and Yip, Cordelia and Choi, Andrew and Park, Junho},
title = {{Trust-gated synthetic EEG augmentation reduces performance drops when generalizing to new patients}},
journal = {NPJ digital medicine},
year = {2026},
month = may,
volume = {9},
number = {1},
pages = {634},
publisher = {Nature Publishing Group},
issn = {2398-6352},
doi = {10.1038/
url = {https://
pmid = {42185473},
pmcid = {PMC13482338}
}
RIS
TY - JOUR
AU - Choi, Daniel
AU - Yip, Cordelia
AU - Choi, Andrew
AU - Park, Junho
TI - Trust-gated synthetic EEG augmentation reduces performance drops when generalizing to new patients
T2 - NPJ digital medicine
J2 - NPJ Digit Med
PY - 2026
DA - 2026/
VL - 9
IS - 1
SP - 634
SN - 2398-6352
PB - Nature Publishing Group
DO - 10.1038/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.1038/
"type": "article-journal",
"title": "Trust-gated synthetic EEG augmentation reduces performance drops when generalizing to new patients",
"container-title": "NPJ digital medicine",
"author": [
{
"family": "Choi",
"given": "Daniel"
},
{
"family": "Yip",
"given": "Cordelia"
},
{
"family": "Choi",
"given": "Andrew"
},
{
"family": "Park",
"given": "Junho"
}
],
"container-title-short":
"volume": "9",
"issue": "1",
"page": "634",
"DOI": "10.1038/
"PMID": "42185473",
"PMCID": "PMC13482338",
"ISSN": "2398-6352",
"publisher": "Nature Publishing Group",
"URL": "https://
"language": "en",
"issued": {
"date-parts": [
[
2026,
5,
25
]
]
}
}
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.1038/s41598-026-47627-y [code]
- QuantumNeuroXAI: a quantum-inspired deep learning framework with explainability for brain signal analysis and neurological disorder detection.Journal: Scientific reportsIn common: MNE-Python, PyTorch, scikit-learn, 4 other tools, bbci.de/competition/iv, EEG, 2 references
- [2] doi:10.1002/hbm.70528 [code]
- Explainable AI Insights Into EEG Classification and Its Alignment to Neural Correlates.Journal: Human brain mappingIn common: MOABB, MNE-Python, PyTorch, 5 other tools, EEG, 1 reference
- [3] doi: [code]
- Self-Rectifying Integrate-and-Fire Neuron and Collaborative Trim Training Framework for SNN-Based EEG Motor Imagery ClassificationJournal: Brain sciencesIn common: PyTorch, SciPy, Matplotlib, 1 other tool, bbci.de/competition/iv, EEG, 3 references
- [4] doi:10.1371/journal.pone.0354976 [code]
- Improved motor imagery BCI performance via task-unaware compression in the BELT Bayesian Edge-Cloud architecture.Journal: PloS oneIn common: MNE-Python, pandas, SciPy, 2 other tools, bbci.de/competition/iv, EEG, 1 reference
- [5] doi:10.1371/journal.pone.0347671 [code]
- RMETNet: A cross-subject motor imagery EEG signal classification model based on TSLANet and riemannian geometry features.Journal: PloS oneIn common: MNE-Python, PyTorch, scikit-learn, 4 other tools, EEG, 2 references
- [6] doi:10.1186/s13634-026-01330-2 [code]
- Leednet: a lightweight network for event detection in EEG signals.Journal: Journal on advances in signal processingIn common: MNE-Python, PyTorch, scikit-learn, 4 other tools, EEG, 2 references
- [7] doi:10.3390/s26051730 [code]
- SFE-GAT: Structure-Feature Evolution Graph Attention Network for Motor Imagery Decoding.Journal: Sensors (Basel, Switzerland)In common: PyTorch, SciPy, Matplotlib, 1 other tool, bbci.de/competition/iv, EEG, 1 reference
- [8] doi:10.3389/fnhum.2026.1895016 [code]
- A confidence-gated source selection strategy for cross-session transfer in brain-computer interfaces.Journal: Frontiers in human neuroscienceIn common: MOABB, MNE-Python, scikit-learn, 2 other tools, EEG, 1 reference
- [9] doi:10.3389/fnins.2026.1874302 [code]
- Architecture-data matching for EEG-EMG decoding: compact deep models match classical spectral decoders on the WAY-EEG-GAL grasp-and-lift dataset.Journal: Frontiers in neuroscienceIn common: PyTorch, scikit-learn, pandas, 3 other tools, EEG, 3 references
- [10] doi:10.3390/bios16080437 [code]
- Deep Learning for Ear-EEG-Based Brain-Computer Interface: A Systematic Comparison and Design Insights.Journal: BiosensorsIn common: MNE-Python, PyTorch, scikit-learn, 3 other tools, EEG, 2 references
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, 52 scripts, and 15 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:a967a0434bc2819a…
Add the badge to its README
The badge links the code to this page. Copy one of these into the README of the paper's code: only you decide where it goes, and nothing is changed for you.
Markdown
[, paste the snippet at the top, then “Commit changes…” and, to review it first, “Create a new branch and start a pull request”. You open the pull request; OSCR asks for no permission.
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.
