Interpretable metrics for evaluating fidelity, diversity, and privacy in synthetic EEG data
The 25 matches
- [1] § Proposed metrics on EEG synthetic data › Fidelity › Time › Frequency ↔ src/frequency_fidelity.py, lines 16–56 · score 0.94 · power spectral densities, fast ripple, dominant frequency, spectral coherence, frequency domain, Frequency fidelity
- [2] § Proposed metrics on EEG synthetic data › Diversity ↔ src/diversity.py, lines 11–55 · score 0.92 · Diversity evaluation, Geometric diversity, Intrinsic diversity, pairwise distances, UMAP, synthetic EEG
- [3] § Proposed metrics on EEG synthetic data › Fidelity › Complexity ↔ src/complexity_fidelity.py, lines 12–65 · score 0.90 · Lempel Ziv complexity, Multifractal Detrended Fluctuation, Multifractal Detrended Cross, Detrended Cross Correlation, permutation entropy, sample entropy
- [4] § Proposed metrics on EEG synthetic data › Fidelity › Time ↔ src/time_fidelity.py, lines 13–38 · score 0.80 · translation invariant, standard deviation, Mahalanobis distance, Wasserstein distance, Hjorth, mobility
- [5] § Proposed metrics on EEG synthetic data › Fidelity › Time-frequency ↔ src/time_frequency_fidelity.py, lines 827–961 · score 0.77 · duty cycle, burst statistics, peak, frequency fidelity, envelopes, duration
- [6] § Proposed metrics on EEG synthetic data › Privacy › Nearest-neighbours ↔ src/privacy.py, lines 139–195 · score 0.75 · closely synthetic signals, Nearest neighbour, NN distances, Warping, L2, DTW
- [7] § Proposed metrics on EEG synthetic data › Fidelity › Spatial ↔ src/evaluation_score.py, lines 611–660 · score 0.73 · channel correlation matrix, cross channel, Spatial fidelity, SD normalised, deviation, RS
- [8] § Validation results ↔ src/complexity_fidelity.py, lines 955–1030 · score 0.71 · PermEn, SampEn, RR RS, SS distributions, LZC, entropy
- [9] § Proposed metrics on EEG synthetic data › Fidelity › Spatial ↔ src/spatial_fidelity.py, lines 4–26 · score 0.71 · channel dependency structure, correlation matrices, Spatial fidelity, Frobenius, variability, SS
- [10] § Proposed metrics on EEG synthetic data › Privacy › Membership inference ↔ src/privacy.py, lines 139–195 · score 0.69 · Membership inference risk, modified entropy, prediction, MIR, confidence, training
- [11] § Proposed metrics on EEG synthetic data › Fidelity › Spatial › Fidelity score ↔ src/evaluation_score.py, lines 664–729 · score 0.69 · global fidelity score, Adaptive weights, weighted geometric, aggregation, component, entropy
- [12] § Proposed metrics on EEG synthetic data › Fidelity › Time-frequency ↔ src/time_frequency_fidelity.py, lines 25–67 · score 0.68 · Continuous Wavelet Transform, scalogram represents, frequency fidelity, CWT, synthetic signals, metric
- [13] § Proposed metrics on EEG synthetic data › Fidelity › Complexity › Complexity metrics interpretation ↔ src/complexity_fidelity.py, lines 12–65 · score 0.67 · correlation coefficients, cross fluctuation, complexity metrics, exponents, Multifractal, entropy
- [14] § Proposed metrics on EEG synthetic data › Fidelity › Time › Time fidelity score ↔ src/evaluation_score.py, lines 60–138 · score 0.67 · Hjorth Activity, SD normalised WD, Mahalanobis distance, Mobility, synthetic signals, score
- [15] § Proposed metrics on EEG synthetic data › Fidelity › Time-frequency › Visual element ↔ src/time_frequency_fidelity.py, lines 653–717 · score 0.66 · db_ref, freq_scale, vmax, vmin, Intensity, log
- [16] § Proposed metrics on EEG synthetic data › Privacy › Nearest-neighbours ↔ src/diversity.py, lines 260–372 · score 0.65 · distance computation, Nearest neighbour, NN distances, Euclidean, globally, synthetic
- [17] § Validation results ↔ src/validation/complexity_validation.py, lines 236–307 · score 0.64 · PermEn, phase randomised, SampEn, LZC, Validation, entropy
- [18] § Proposed metrics on EEG synthetic data › Privacy › Privacy score ↔ src/evaluation_score.py, lines 812–911 · score 0.62 · Cohen style, NN distances, attacks, accuracy, mapped, components
- [19] § Proposed metrics on EEG synthetic data › Fidelity › Time ↔ src/evaluation_score.py, lines 60–138 · score 0.58 · Hjorth activity, Mahalanobis distance, mobility, synthetic signals, covariance, WD
- [20] § Proposed metrics on EEG synthetic data › Diversity › Diversity score ↔ src/evaluation_score.py, lines 733–808 · score 0.56 · diversity components, compensation, aggregation, ratios, weights, coverage
- [21] § Proposed metrics on EEG synthetic data › Fidelity › Complexity › Visual element ↔ src/complexity_fidelity.py, lines 683–830 · score 0.55 · cross Hurst exponent, singularity spectrum, width, MFDCCA, multifractal
- [22] § Validation results ↔ src/diversity.py, lines 11–55 · score 0.55 · Nearest neighbour distances, UMAP, uniqueness, pairwise, coverage, Diversity
- [23] § Proposed metrics on EEG synthetic data › Fidelity › Time › Frequency fidelity score ↔ src/evaluation_score.py, lines 140–223 · score 0.54 · band power, dominant frequency, synthetic signals, Coherence, scores, spectral
- [24] § Methods › Validation ↔ src/validation/complexity_validation.py, lines 33–160 · score 0.53 · fractal metrics, theoretically, exception, surrogate, Validation, noise
- [25] § Proposed metrics on EEG synthetic data › Fidelity › Complexity › Complexity fidelity score ↔ src/complexity_fidelity.py, lines 683–830 · score 0.53 · cross Hurst exponents, real synthetic, width, multifractal, spectrum, fidelity
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 · 911 lines · 29 KB · LGPL-3.0 · 7 matches
- from time_fidelity import *
- from frequency_fidelity import *
- from time_frequency_fidelity import *
- from complexity_fidelity import *
- from spatial_fidelity import *
- from diversity import *
- from privacy import *
- def _sim(a, b, eps=1e-12):
- """Normalised absolute-difference similarity in [0,1]."""
- return 1.0 - np.abs(a - b) / (np.abs(a) + np.abs(b) + eps)
- def _entropy_weights(values, eps=1e-12):
- """
- Compute entropy-based adaptive weights.
- Higher variability → lower entropy → higher weight.
- Parameters
- ----------
- values : list or array-like
- Vector of metric values across domains.
- Returns
- -------
- np.ndarray
- Normalized weights summing to 1.
- """
- x = np.asarray(values, dtype=float)
- # Normalize to positive probabilities
- x = np.clip(x, eps, None)
- p = x / np.sum(x)
- # Shannon entropy
- H = -np.sum(p * np.log(p + eps))
- H_max = np.log(len(p))
- # Information utility (1 - normalized entropy)
- utility = 1 - (H / H_max)
- # If all equal → fallback to uniform weights
- if not np.isfinite(utility) or utility <= 0:
- return np.ones_like(x) / len(x)
- # Weight proportional to deviation from uniformity
- w = p * utility
- w = np.clip(w, eps, None)
- return w / np.sum(w)
- def _weighted_geometric_mean(x, w=None, eps=1e-12):
- x = np.asarray(x, dtype=float)
- x = np.clip(x, eps, 1.0)
- if w is None:
- w = np.ones_like(x) / x.size
- w = np.asarray(w, dtype=float)
- w = w / (np.sum(w) + eps)
- return float(np.prod(x ** w))
- def compute_time_fidelity_score(real_data, synthetic_data, weights=None):
- """
- Compute a time-domain fidelity score between real and synthetic signals
- using Hjorth parameter statistics.
- Integrated components (each mapped as S = 1/(1 + distance)):
- 1. Normalised WD for Hjorth Activity
- 2. Normalised WD for Hjorth Mobility
- 3. Normalised WD for Hjorth Complexity
- 4. Mahalanobis distance between Hjorth means
- All distances are in SD units:
- - Hjorth WDs are normalised by the real-data SD.
- - Mahalanobis is inherently scale-normalised via the covariance.
- Parameters
- ----------
- real_data : np.ndarray or list
- Real signals of shape [n_signals, n_samples].
- synthetic_data : np.ndarray or list
- Synthetic signals with the same shape as real_data.
- weights : dict, optional
- Weights for the components. Keys:
- {'activity','mobility','complexity','mahalanobis'}.
- Default: equal weights across all provided components 0.25 each.
- Returns
- -------
- float
- Composite time-domain fidelity score in [0, 1].
- """
- # Defaults (auto-balance across 4 components)
- if weights is None:
- w = 1.0 / 4.0
- weights = {
- 'activity': w, 'mobility': w, 'complexity': w, 'mahalanobis': w
- }
- # Ensure all keys exist; missing ones default to 0 (excluded from sum)
- for k in ('activity', 'mobility', 'complexity', 'mahalanobis'):
- weights.setdefault(k, 0.0)
- # Compute base Hjorth metrics
- tf = TimeFidelity()
- hj = tf.compute_hjorth_metrics(real_data, synthetic_data, verbose=False)
- import numpy as _np
- # distance (in SD units) -> similarity
- def _sim(d):
- d = float(d)
- if not _np.isfinite(d) or d < 0:
- return 0.0
- return 1.0 / (1.0 + d)
- # Use SD-normalised WDs for Hjorth parameters
- activity_score = _sim(hj['WD_Activity_normSD'])
- mobility_score = _sim(hj['WD_Mobility_normSD'])
- complexity_score = _sim(hj['WD_Complexity_normSD'])
- # Mahalanobis is already scale-normalised
- mahalanobis_score = _sim(hj['Mahalanobis'])
- # Weighted combination
- time_fidelity_score = (
- weights['activity'] * activity_score +
- weights['mobility'] * mobility_score +
- weights['complexity'] * complexity_score +
- weights['mahalanobis'] * mahalanobis_score
- )
- # Print components
- print(f"Time Fidelity Score : {time_fidelity_score:.3f}")
- print("Time Fidelity Components:")
- print(f" Activity (norm WD): {activity_score:.3f}")
- print(f" Mobility (norm WD): {mobility_score:.3f}")
- print(f" Complexity (norm WD): {complexity_score:.3f}")
- print(f" Mahalanobis : {mahalanobis_score:.3f}")
- return time_fidelity_score
- def compute_frequency_fidelity_score(real_data, synthetic_data, fs, weights=None):
- """
- Compute a similarity score between real and synthetic signals that blends
- spectral-band power, dominant frequency, coherence and a PSD–Wasserstein
- similarity term.
- Parameters
- ----------
- real_data : list | np.ndarray
- List/array of real signals (shape: [n_signals, n_samples] or 1-D).
- synthetic_data : list | np.ndarray
- List/array of synthetic signals (shape: [n_signals, n_samples] or 1-D).
- fs : int
- Sampling frequency (Hz).
- weights : dict, optional
- Weights for the four sub-scores. Must contain the keys:
- {'relative', 'dom_freq', 'psd_coherence', 'wasserstein'}
- Defaults to: {'relative': 0.40,
- 'dom_freq': 0.20,
- 'psd_coherence': 0.20,
- 'wasserstein': 0.20}
- Example usage:
- --------------
- real_data = np.random.randn(10, 2048) # 10 real signals, each 2048 samples
- synthetic_data = np.random.randn(10, 2048) # 10 synthetic signals, each 2048 samples
- evaluation_score.compute_frequency_fidelity_score(real_data, synthetic_data, fs=2048)
- Returns
- -------
- float
- Composite frequency-domain fidelity score in the range (0, 1].
- """
- # Helper: robust scalar casting
- def _as_float(x, default=np.nan):
- """
- Best-effort conversion of metric outputs (float/array/dict) into a scalar float.
- """
- if isinstance(x, (int, float, np.floating)):
- return float(x)
- if isinstance(x, np.generic):
- return float(x)
- if isinstance(x, (list, tuple, np.ndarray)):
- arr = np.asarray(x, dtype=float)
- if arr.size == 0:
- return float(default)
- return float(np.nanmean(arr))
- if isinstance(x, dict):
- # Try common summary paths used across your metric API
- candidates = [
- ("RS Summary", "Global Mean"),
- ("RS Summary", "Mean"),
- ("Summary", "Global Mean"),
- ("Summary", "Mean"),
- ("Global Mean",),
- ("Mean",),
- ("wd",),
- ("WD",),
- ("distance",),
- ("value",),
- ]
- for path in candidates:
- v = x
- ok = True
- for k in path:
- if isinstance(v, dict) and k in v:
- v = v[k]
- else:
- ok = False
- break
- if ok:
- return _as_float(v, default=default)
- return float(default)
- try:
- return float(x)
- except Exception:
- return float(default)
- # Default values definition
- analysis_band = (0.5, 500.0) # Hz
- win_seconds = 4.0 # Welch window length (s)
- window = 'hann'
- detrend = 'constant'
- overlap = 0.5 # 50%
- # Keep analysis band under Nyquist
- nyq = fs / 2.0
- analysis_band = (analysis_band[0], min(analysis_band[1], nyq))
- # Initialize FrequencyFidelity class
- frequency_fidelity = FrequencyFidelity(
- fs,
- analysis_band=analysis_band,
- win_seconds=win_seconds,
- window=window,
- detrend=detrend,
- overlap=overlap
- )
- # Weights
- if weights is None:
- weights = {
- 'relative': 0.40,
- 'dom_freq': 0.20,
- 'psd_coherence': 0.20,
- 'wasserstein': 0.20
- }
- # Fallback – add any missing keys with zero weight
- for k in ('relative', 'dom_freq', 'psd_coherence', 'wasserstein'):
- weights.setdefault(k, 0.0)
- # Optionally normalize weights to sum to 1 (prevents accidental scaling)
- wsum = float(sum(weights.values()))
- if wsum > 0:
- weights = {k: float(v) / wsum for k, v in weights.items()}
- # Shape handling
- if isinstance(real_data, np.ndarray) and real_data.ndim == 1:
- real_data = [real_data]
- if isinstance(synthetic_data, np.ndarray) and synthetic_data.ndim == 1:
- synthetic_data = [synthetic_data]
- # 1) Relative power
- freqs_r, psd_r, rel_power_r, dominant_freq_r = frequency_fidelity.compute_relative_power(
- real_data,
- analysis_band=analysis_band,
- win_seconds=win_seconds,
- window=window,
- detrend=detrend,
- overlap=overlap
- )
- freqs_s, psd_s, rel_power_s, dominant_freq_s = frequency_fidelity.compute_relative_power(
- synthetic_data,
- analysis_band=analysis_band,
- win_seconds=win_seconds,
- window=window,
- detrend=detrend,
- overlap=overlap
- )
- band_names = ["Delta", "Theta", "Alpha", "Beta", "Gamma"]
- real_mean_rel_power = np.array([np.nanmean(rel_power_r[b]) for b in band_names], dtype=float)
- synth_mean_rel_power = np.array([np.nanmean(rel_power_s[b]) for b in band_names], dtype=float)
- mean_band_diff = np.nanmean(np.abs(real_mean_rel_power - synth_mean_rel_power) * 100.0) # %
- # Map diff → similarity (clipped ≥ 0.2 to avoid 0 in extreme cases)
- relative_power_score = max(0.2, 1.0 - mean_band_diff / 20.0)
- relative_power_score = float(np.clip(relative_power_score, 0.0, 1.0))
- # 2) Dominant frequency
- freq_diff = abs(np.nanmean(dominant_freq_r) - np.nanmean(dominant_freq_s))
- dominant_freq_score = max(0.2, 1.0 - freq_diff / 3.0)
- dominant_freq_score = float(np.clip(dominant_freq_score, 0.0, 1.0))
- # 3) Coherence
- coh = frequency_fidelity.spectral_coherence(
- real_data, synthetic_data,
- mode="all_vs_all",
- per_band=False,
- analysis_band=analysis_band,
- win_seconds=2.0,
- window=window,
- detrend=detrend,
- overlap=overlap
- )
- # Robustly extract and validate coherence scalar
- coh_val = coh.get("RS Summary", {}).get("Global Mean", np.nan) if isinstance(coh, dict) else np.nan
- coh_val = _as_float(coh_val, default=np.nan)
- mean_coherence = 0.0
- if np.isfinite(coh_val):
- mean_coherence = float(np.clip(coh_val, 0.0, 1.0))
- # 4) Spectral Wasserstein distance
- wd_psd_raw = frequency_fidelity.spectral_wasserstein_distance(
- real_data, synthetic_data,
- fmin=analysis_band[0],
- fmax=analysis_band[1],
- mode="pairmean",
- per_band=False
- )
- # Robustly extract scalar WD
- wd_psd = _as_float(wd_psd_raw, default=np.nan)
- # Map distance → similarity
- wasserstein_score = 0.2
- if np.isfinite(wd_psd):
- wasserstein_score = float(1.0 / (1.0 + wd_psd))
- wasserstein_score = float(np.clip(wasserstein_score, 0.0, 1.0))
- # Composite score
- frequency_fidelity_score = (
- weights['relative'] * relative_power_score +
- weights['dom_freq'] * dominant_freq_score +
- weights['psd_coherence'] * mean_coherence +
- weights['wasserstein'] * wasserstein_score
- )
- frequency_fidelity_score = float(np.clip(frequency_fidelity_score, 0.0, 1.0))
- print(f"Frequency Fidelity Score: {frequency_fidelity_score:.2f}")
- return frequency_fidelity_score
- def compute_time_frequency_fidelity_score(real_data, synthetic_data, fs, *, weights=None, mode: str = "auto",
- pad: bool = True, rr_zip_strategy: str = "consecutive", ss_zip_strategy: str = "consecutive",return_sd: bool = False,
- return_per_pair: bool = False, verbose: bool = True):
- """
- Composite time frequnecy similarity for 1-D or 2-D inputs.
- Reuses `compute_scalogram_similarity_metrics` and combines RS per-pair metrics:
- score_i = w_cssim * SSIM_i
- + w_rmse * (1 / (1 + nRMSE_i))
- + w_cos * Cosine_i
- Parameters
- ----------
- real_data, synthetic_data : array_like
- 1-D (T,) or 2-D (N, T). Only these are required.
- weights : dict, optional
- {'color_ssim':0.4, 'rmse':0.3, 'cosine_similarity':0.3} by default.
- mode : {"auto","zip","all_vs_all"}, default "auto"
- - "auto": use "zip" if both inputs are 1-D or both are 2-D with the same N; else "all_vs_all".
- - "zip": index-wise pairing.
- - "all_vs_all": every real vs every synthetic.
- pad : bool, default True
- Right-pad signals to a common length before CWT.
- rr_zip_strategy, ss_zip_strategy : {"consecutive","halves"}
- Zip strategies for within-set RR/SS in the metrics method.
- return_sd : bool, default False
- Also return SD of per-pair scores.
- return_per_pair : bool, default False
- Also return list of per-pair scores.
- verbose : bool, default True
- Print a brief summary.
- Example usage:
- --------------
- real_data = np.random.randn(10, 2048) # 10 real signals, each 2048 samples
- synthetic_data = np.random.randn(10, 2048) # 10 synthetic signals, each 2048 samples
- evaluation_score.compute_scalogram_fidelity_score(real_data, synthetic_data, fs=2048)
- Returns
- -------
- mean_score : float
- (sd_score) : float, optional if return_sd=True
- (per_pair_scores) : list[float], optional if return_per_pair=True
- """
- if weights is None:
- weights = {'color_ssim': 0.4, 'rmse': 0.3, 'cosine_similarity': 0.3}
- w_cssim = float(weights.get('color_ssim', 0.4))
- w_rmse = float(weights.get('rmse', 0.3))
- w_cos = float(weights.get('cosine_similarity', 0.3))
- # Normalize inputs: auto-wrap 1-D → (1, T)
- R = np.asarray(real_data, dtype=float)
- S = np.asarray(synthetic_data, dtype=float)
- if R.ndim == 1:
- R = R[None, :] # shape (1, T)
- if S.ndim == 1:
- S = S[None, :] # shape (1, T)
- # Auto-select pairing if requested
- if mode == "auto":
- if R.shape[0] == S.shape[0]:
- eff_mode = "zip" # pairwise 1–1
- else:
- eff_mode = "all_vs_all" # every real vs every synthetic
- else:
- eff_mode = mode
- scalo = TimeFrequencyFidelity(fs=fs)
- # Reuse your metrics method (does RS, RR, SS under the same mode/strategies)
- metrics = scalo.compute_scalogram_similarity_metrics(
- R, S,
- mode=eff_mode, pad=pad,
- rr_zip_strategy=rr_zip_strategy, ss_zip_strategy=ss_zip_strategy,
- )
- # RS per-pair lists → composite per-pair scores
- ssim_list = metrics.get("Per-pair SSIM (RS)", [])
- nrmse_list = metrics.get("Per-pair NRMSE (RS)", [])
- cos_list = metrics.get("Per-pair Cosine (RS)", [])
- scores = []
- for ssim_i, nrmse_i, cos_i in zip(ssim_list, nrmse_list, cos_list):
- cos_i = max(-1.0, min(1.0, float(cos_i))) # safety
- sim_rmse = 1.0 / (1.0 + float(nrmse_i)) # maps to (0,1]
- score_i = w_cssim*float(ssim_i) + w_rmse*sim_rmse + w_cos*cos_i
- scores.append(float(score_i))
- if not scores:
- mean_score = float('nan'); sd_score = float('nan')
- else:
- arr = np.asarray(scores, dtype=float)
- mean_score = float(np.mean(arr))
- sd_score = float(np.std(arr, ddof=1)) if arr.size > 1 else float('nan')
- if verbose:
- label = eff_mode if eff_mode != "zip" else f"zip"
- print(f"Time-frequency Fidelity Score: {mean_score:.3f} | mode: {label}, pairs: {len(scores)}")
- #out = (mean_score,)
- #if return_sd:
- #out += (sd_score,)
- #if return_per_pair:
- #out += (scores,)
- #return out if len(out) > 1 else out[0]
- def compute_complexity_fidelity_score(
- real_data,
- synthetic_data,
- q_range=np.arange(-5, 5, 0.1),
- weights=None
- ):
- """
- Complexity fidelity score combining fractal and entropy/complexity similarities.
- Final aggregation: weighted geometric mean over available (finite) subscores.
- This penalizes collapse in any single complexity component.
- Subscores (mapped to [0,1], higher = closer match):
- - dcca, mfdfa, mfdcca, sampen, permen, lzc
- """
- # Default: equal weights across ALL subscores (6 components)
- if weights is None:
- weights = {
- 'dcca': 1/6, 'mfdfa': 1/6, 'mfdcca': 1/6,
- 'sampen': 1/6, 'permen': 1/6, 'lzc': 1/6
- }
- # Wrap 1D arrays
- if isinstance(real_data, np.ndarray) and real_data.ndim == 1:
- real_data = [real_data]
- if isinstance(synthetic_data, np.ndarray) and synthetic_data.ndim == 1:
- synthetic_data = [synthetic_data]
- # Helpers
- def _sim_range(a, b, lo, hi):
- d = min(abs(float(a) - float(b)), hi - lo)
- return 1.0 - d / (hi - lo)
- def _mean_Hq(signals, q_range, get_scales):
- Hqs = []
- for x in signals:
- scales = get_scales(len(x))
- if len(scales) < 4:
- continue
- _, info = nk.fractal_dfa(x, scale=scales, multifractal=True, q=q_range, show=False)
- Hq = np.asarray(info["H"])
- if np.all(np.isfinite(Hq)):
- Hqs.append(Hq)
- if not Hqs:
- return None
- return np.nanmean(np.vstack(Hqs), axis=0)
- # Fractality scores
- fs_dcca = ComplexityFidelity(real_data, synthetic_data, method='DCCA', q_range=q_range)
- fs_dcca.compute_fractal_metrics()
- H_rr, H_rs = fs_dcca.means[:2]
- F_DCCA = _sim_range(H_rr, H_rs, lo=0.3, hi=1.2)
- fs_mfdfa = ComplexityFidelity(real_data, synthetic_data, method='MFDFA', q_range=q_range)
- fs_mfdfa.compute_fractal_metrics()
- H_r, H_s = fs_mfdfa.means
- S_H_mfdfa = _sim_range(H_r, H_s, lo=0.3, hi=1.2)
- dummy = ComplexityFidelity(real_data, synthetic_data, method='MFDFA', q_range=q_range)
- Hq_r = _mean_Hq(real_data, q_range, dummy._get_win_sizes)
- Hq_s = _mean_Hq(synthetic_data, q_range, dummy._get_win_sizes)
- if Hq_r is not None and Hq_s is not None:
- rmse = float(np.sqrt(np.nanmean((Hq_r - Hq_s) ** 2)))
- tau = 0.15
- S_Hq = float(np.exp(-rmse / tau))
- else:
- S_Hq = np.nan
- F_MFDFA = S_H_mfdfa if np.isnan(S_Hq) else 0.5 * S_H_mfdfa + 0.5 * S_Hq
- fs_mfdcca = ComplexityFidelity(real_data, synthetic_data, method='MFDCCA', q_range=q_range)
- fs_mfdcca.compute_fractal_metrics()
- Hc_rr, Hc_rs = fs_mfdcca.means[:2]
- Da_rr, Da_rs = fs_mfdcca.deltaAlpha_means[:2]
- S_H_mfdcca = _sim_range(Hc_rr, Hc_rs, lo=0.3, hi=1.2)
- S_Dalpha = _sim_range(Da_rr, Da_rs, lo=0.0, hi=0.5)
- F_MFDCCA = 0.7 * S_H_mfdcca + 0.3 * S_Dalpha
- # Entropy / algorithmic scores
- cf_entropy = ComplexityFidelity(real_data, synthetic_data, method='MFDFA', q_range=q_range)
- e = cf_entropy.compute_entropy_complexity_metrics(
- real_data, synthetic_data,
- sampen_m=2, sampen_r=None,
- permen_m=3, permen_tau=1,
- lzc_threshold=None,
- n_surrogates=0,
- verbose=False
- )
- def _to_sim(wd_norm):
- return np.nan if not np.isfinite(wd_norm) else 1.0 / (1.0 + float(wd_norm))
- S_SampEn = _to_sim(e.get("WD_SampEn_norm", np.nan))
- S_PermEn = _to_sim(e.get("WD_PermEn_norm", np.nan))
- S_LZC = _to_sim(e.get("WD_LZC_norm", np.nan))
- subscores = {
- 'dcca': F_DCCA,
- 'mfdfa': F_MFDFA,
- 'mfdcca': F_MFDCCA,
- 'sampen': S_SampEn,
- 'permen': S_PermEn,
- 'lzc': S_LZC
- }
- # Keep only finite subscores
- keys = [k for k, v in subscores.items() if np.isfinite(v)]
- if not keys:
- raise RuntimeError("Complexity fidelity score could not be computed (all subscores NaN).")
- vals = np.array([subscores[k] for k in keys], dtype=float)
- # Collect weights for valid keys, renormalize
- w = np.array([float(weights.get(k, 0.0)) for k in keys], dtype=float)
- if float(np.sum(w)) <= 0:
- w = np.ones_like(vals) / vals.size
- else:
- w = w / float(np.sum(w))
- score = _weighted_geometric_mean(vals, w)
- # Printing
- print(f"Complexity Score: {score:0.3f}\n")
- for k, v, wi in zip(keys, vals, w):
- print(f"{k.upper():8s}: {v:0.3f} | weight = {wi:0.3f}")
- return float(np.clip(score, 0.0, 1.0))
- def compute_spatial_fidelity_score(real_data, synthetic_data):
- """
- Compute spatial fidelity score based on cross-channel
- correlation matrix similarity.
- The score is derived from the SD-normalised deviation:
- z_SC = (μ_RS - μ_RR) / σ_RR
- F_spatial = 1 / (1 + |z_SC|)
- Parameters
- ----------
- real_data : array-like
- Shape (N, C, T) or (C, T)
- synthetic_data : array-like
- Shape (N, C, T) or (C, T)
- Returns
- -------
- float
- Spatial fidelity score in [0,1]
- """
- real_data = np.asarray(real_data)
- synthetic_data = np.asarray(synthetic_data)
- if real_data.ndim == 2:
- # ambiguous: could be (C,T) or (N,T)
- # spatial fidelity is only valid if axis 0 == channels
- if real_data.shape[0] < 2:
- raise ValueError("Need at least 2 channels for spatial fidelity.")
- # optional: enforce expected C
- # if real_data.shape[0] != expected_C: raise ...
- elif real_data.ndim == 3:
- if real_data.shape[1] < 2:
- raise ValueError("Need at least 2 channels for spatial fidelity.")
- else:
- raise ValueError(f"Invalid real_data shape {real_data.shape}; expected 2D or 3D.")
- spatial_eval = SpatialFidelity()
- results = spatial_eval.evaluate(real_data, synthetic_data)
- spatial_score = results.get("F_spatial", np.nan)
- # Safety clip
- spatial_score = float(np.clip(spatial_score, 0.0, 1.0))
- print(f"Spatial Fidelity Score: {spatial_score:.3f}")
- return spatial_score
- use_adaptive_weights = False
- def compute_fidelity_score(real_data, synthetic_data, fs):
- """
- Computes global fidelity score using entropy-adaptive weighting
- and weighted geometric aggregation.
- Parameters
- ----------
- real_data : list or np.ndarray
- List of real signals.
- synthetic_data : list or np.ndarray
- List of synthetic signals.
- fs : int
- Sampling frequency of the signals.
- Returns
- -------
- float
- Fidelity score in [0,1] (higher ⇒ closer match).
- Example usage:
- --------------
- real_data = np.random.randn(10, 2048) # 10 real signals, each 2048 samples
- synthetic_data = np.random.randn(10, 2048) # 10 synthetic signals, each 2048 samples
- evaluation_score.compute_fidelity_score(real_data, synthetic_data, fs=2048)
- """
- time_sim = compute_time_fidelity_score(real_data, synthetic_data)
- freq_sim = compute_frequency_fidelity_score(real_data, synthetic_data, fs)
- scalogram_sim = compute_time_frequency_fidelity_score(real_data, synthetic_data, fs)
- fractal_sim = compute_complexity_fidelity_score(real_data, synthetic_data)
- spatial_sim = compute_spatial_fidelity_score(real_data,synthetic_data)
- components = np.array([
- time_sim,
- freq_sim,
- scalogram_sim,
- fractal_sim,
- spatial_sim
- ], dtype=float)
- # Compute weights
- if use_adaptive_weights:
- weights = _entropy_weights(components)
- else:
- weights = np.ones(4) / 4.0
- # Weighted geometric mean (penalizes collapse)
- eps = 1e-12
- fidelity_score = np.prod(
- np.clip(components, eps, 1.0) ** weights
- )
- fidelity_score = float(np.clip(fidelity_score, 0.0, 1.0))
- print(f"\nGlobal Fidelity Score: {fidelity_score:.3f}")
- print("Domain Scores:")
- print(f" Time : {time_sim:.3f}")
- print(f" Frequency : {freq_sim:.3f}")
- print(f" Time-Freq : {scalogram_sim:.3f}")
- print(f" Complexity : {fractal_sim:.3f}")
- print(f" Spatial : {spatial_sim:.3f}")
- print("Adaptive Weights:")
- print(f" {weights}")
- return fidelity_score
- def compute_diversity_score(real_data, synthetic_data, weights=None, n_components=2):
- """
- Composite diversity score in [0,1].
- Aggregation:
- - If `weights` is provided: weighted geometric mean using those weights.
- - Else: entropy-adaptive weights + weighted geometric mean.
- This avoids linear compensation across heterogeneous diversity components.
- """
- def normalize_ratio(ratio):
- if not np.isfinite(ratio) or ratio <= 0:
- return np.nan
- return float(np.exp(-abs(np.log(ratio))))
- div = Diversity(n_components=n_components)
- m_cov = div.compute_coverage_diversity(real_data, synthetic_data)
- m_geom = div.compute_geometric_diversity(real_data, synthetic_data)
- m_intr = div.compute_intrinsic_diversity(real_data, synthetic_data)
- # 1) Coverage / Outliers
- C_cov = float(m_cov['Coverage'])
- O_out = float(m_cov['Outliers'])
- # 2) Geometric diversity
- LM_PCA = float(m_geom['PCA_LabelMixingScore'])
- LM_UM = float(m_geom['UMAP_LabelMixingScore'])
- D_PCA = float(m_geom['PCA_OverlapMahalanobis'])
- D_UM = float(m_geom['UMAP_OverlapMahalanobis'])
- CS_PCA = float(m_geom['PCA_CovShape'])
- CS_UM = float(m_geom['UMAP_CovShape'])
- # 3) Intrinsic ratios (normalized)
- U_NN = normalize_ratio(m_intr['Uniqueness_NN'])
- G_glob = normalize_ratio(m_intr['Global_Diversity'])
- L_loc_P10 = normalize_ratio(m_intr['Local_Diversity_P10'])
- L_loc_P50 = normalize_ratio(m_intr['Local_Diversity_P50'])
- comps = np.array([
- C_cov, O_out,
- LM_PCA, LM_UM,
- D_PCA, D_UM,
- CS_PCA, CS_UM,
- U_NN, G_glob,
- L_loc_P10, L_loc_P50
- ], dtype=float)
- names = [
- "coverage", "outliers",
- "pca_labelmix", "umap_labelmix",
- "pca_overlap", "umap_overlap",
- "pca_covshape", "umap_covshape",
- "uniqueness", "global_div",
- "local_div_p10", "local_div_p50"
- ]
- # Drop NaNs
- valid = np.isfinite(comps)
- comps_v = comps[valid]
- names_v = [n for n, ok in zip(names, valid) if ok]
- if comps_v.size == 0:
- raise RuntimeError("Diversity score could not be computed (all submetrics NaN).")
- # Entropy weights
- w = _entropy_weights(comps_v)
- diversity_score = _weighted_geometric_mean(comps_v, w)
- # Printing
- print(f"Final Diversity Score: {diversity_score:0.3f}\n")
- for n, v, wi in zip(names_v, comps_v, w):
- print(f"{n:16s}: {v:0.3f} | weight = {wi:0.3f}")
- return float(np.clip(diversity_score, 0.0, 1.0))
- def compute_privacy_score(
- real_data,
- synthetic_data,
- y_real: np.ndarray | None = None,
- *,
- normalize: str | None = "zscore_global",
- length_normalize: bool = True,
- weights: dict | None = None,
- ) -> tuple[float, dict]:
- """
- Composite privacy score in [0, 1]; higher = safer.
- Components (all mapped to [0,1] safety scores):
- - L2 effect size d_L2 (from NN distances, R–S vs R–R)
- - DTW effect size d_DTW (same)
- - Optional: MIR (1 - attack accuracy),
- if y_real (labels) is provided.
- """
- pr = Privacy()
- # 1) Distance-based effect sizes (Cohen-style)
- eff = pr.compute_distance_effect_sizes(
- real_data,
- synthetic_data,
- normalize=normalize,
- length_normalize=length_normalize,
- )
- d_l2 = eff["l2"]["effect_size_d"]
- d_dtw = eff["dtw"]["effect_size_d"]
- def effect_size_to_safety(d: float,
- low: float = 0.0,
- high: float = 0.8) -> float:
- """Map effect size d to [0,1] safety."""
- if np.isnan(d):
- return np.nan
- if d <= low:
- return 0.0
- if d >= high:
- return 1.0
- return float((d - low) / (high - low))
- scores = {
- "l2": effect_size_to_safety(d_l2),
- "dtw": effect_size_to_safety(d_dtw),
- }
- # 2) Optional MIR component (requires true labels)
- scores["mir"] = None
- if y_real is not None:
- mir = pr.compute_mir_metrics(
- real_data,
- synthetic_data,
- y_real=y_real,
- normalize=normalize,
- verbose=False,
- )
- # You could also take max / mean of all attacks here
- attack_acc = float(mir["confidence_attack_acc"])
- attack_acc = max(0.5, min(1.0, attack_acc)) # clip to [0.5,1]
- scores["mir"] = 2.0 * (1.0 - attack_acc)
- # 3) Weights + aggregate
- base_w = {
- "l2": 1.0,
- "dtw": 1.0,
- "mir": (1.0 if scores["mir"] is not None else 0.0),
- }
- if weights is not None:
- base_w.update(weights)
- # Remove MIR weight if MIR is None
- if scores["mir"] is None:
- base_w.pop("mir", None)
- # Normalise weights
- tot = sum(base_w.values())
- base_w = {k: v / tot for k, v in base_w.items()}
- # Aggregate privacy score
- privacy_score = sum(base_w[k] * scores[k] for k in base_w)
- print(f"Privacy Score (0–1, higher = safer): {privacy_score:.2f}")
- print(f" - L2 safety score : {scores['l2']:.2f} (from d_L2 = {d_l2:.2f})")
- print(f" - DTW safety score : {scores['dtw']:.2f} (from d_DTW = {d_dtw:.2f})")
- if scores["mir"] is not None:
- print(f" - MIR safety score : {scores['mir']:.2f}")
- else:
- print(" - MIR safety score : n/a (labels not provided)")
- return privacy_score, scores
evaluation_score.py at commit cb00911, under LGPL-3.0 · at the source
Overview
- LIBPhys, NOVA School of Science and Technology, Largo da Torre, 2829-516, Almada, Portugal
- Department of Neurology and Neurosurgery, Brain Center, University Medical Center Utrecht, Part of ERN EpiCARE, P.O. box 85500, 3508, GA Utrecht, The Netherlands
- Stichting Epilepsie Instellingen Nederland (SEIN), Heemstede, The Netherlands
Abstract
The generation of synthetic electroencephalography (EEG) data offers a promising solution to the limited availability of clinical neurophysiological recordings, particularly intracranial EEG (iEEG), where acquisition is invasive, complex, and restricted to small patient cohorts. Although generative models can produce realistic signals, progress in this field is constrained by the absence of standardized and physiologically grounded evaluation protocols. Current assessment strategies rely largely on basic statistical similarity measures and fail to capture the intrinsic properties of EEG, including non-stationarity, spectral organization, and fractal dynamics. Here, we propose a comprehensive evaluation framework for synthetic (i)EEG that integrates fidelity, diversity, and privacy within a unified and interpretable protocol. The framework combines analyses across time, frequency, time–frequency, complexity, and spatial domains using established signal-processing and nonlinear-dynamics metrics. Interpretation is grounded in principled normalization strategies and effect-size conventions, and is further summarized through composite domain-level scores that enable transparent and reproducible comparison across datasets and generative models. Implemented as the open-source Python library, seege_ provides a standardized and interpretable toolkit for evaluating synthetic neurophysiological data, advancing methodological rigor in generative modeling for clinical and neuroscientific research.
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 25 matches between paragraphs and lines of code.
BiosignalsLibphys/seege_
cb009112058a01e45a8aaf2ab4d0313611bdd82c, 18 August 2026Availability: 1 check, the latest on 29 September 2026: the link answers
- 29 September 2026: the link answers
21 files
- diversity_metrics_tutori
al.ipynb , Jupyter, 498 lines - main.py, Python, 171 lines
- setup.py, Python, 12 lines
- src/
complexity_fidelity.py , Python, 1,139 lines, 5 matches - src/
diversity.py , Python, 495 lines, 3 matches - src/
evaluation_score.py , Python, 911 lines, 7 matches - src/
frequency_fidelity.py , Python, 861 lines, 1 match - src/
preprocessing.py , Python, 56 lines - src/
privacy.py , Python, 458 lines, 2 matches - src/
spatial_fidelity.py , Python, 218 lines, 1 match - src/
time_fidelity.py , Python, 234 lines, 1 match - src/
time_frequency_fidelity. , Python, 961 lines, 3 matchespy - src/
validation/ , Python, 322 lines, 2 matchescomplexity_validation.py - src/
validation/ , Python, 203 linesdiversity_validation.py - src/
validation/ , Python, 175 linesfrequency_validation.py - src/
validation/ , Python, 283 linesprivacy_validation.py - src/
validation/ , Python, 351 linestime_frequency_validatio n.py - src/
validation/ , Python, 102 linestime_validation.py - usage_tutorial.ipynb, Jupyter, 213 lines
- LICENSE, License, 165 lines
- README.md, Text, 67 lines
Code availability
The Python library is available on Github: seege_ (https://
Reproduced under the paper's license (CC BY), from the paper cited above.
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;
- 19 scripts, each with its path and the digest of its content;
- 25 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
- figshare:11734575, at figshare; found in “Data availability”
- figshare:c1, at figshare; found in the references
Data availability
The datasets generated during and/
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 1, 29 September 2026: the first record
Recorded: type, journal, dates, 9 authors, 4 keywords, 1 funder, 48 references.
Cite
This paper
Silveira, I., Silva, L., Furk, D., Marques, B., Ao, N., Hoogteijling, S., Heijink, I., Zijlmans, M., & Gamboa, H. (2026). Interpretable metrics for evaluating fidelity, diversity, and privacy in synthetic EEG data. Research Square (preprint). https://
BibTeX
@article{silveira2026int
author = {Silveira, Inês and Silva, Luís and Furk, Dania and Marques, Beatriz and Ao, Nianfei and Hoogteijling, Sem and Heijink, Irene and Zijlmans, Maeike and Gamboa, Hugo},
title = {{Interpretable metrics for evaluating fidelity, diversity, and privacy in synthetic EEG data}},
journal = {Research Square (preprint)},
year = {2026},
month = apr,
publisher = {Research Square},
issn = {2693-5015},
doi = {10.21203/
url = {https://
}
RIS
TY - JOUR
AU - Silveira, Inês
AU - Silva, Luís
AU - Furk, Dania
AU - Marques, Beatriz
AU - Ao, Nianfei
AU - Hoogteijling, Sem
AU - Heijink, Irene
AU - Zijlmans, Maeike
AU - Gamboa, Hugo
TI - Interpretable metrics for evaluating fidelity, diversity, and privacy in synthetic EEG data
T2 - Research Square (preprint)
J2 - Res Sq
PY - 2026
DA - 2026/
SN - 2693-5015
PB - Research Square
DO - 10.21203/
UR - https://
ER -
CSL-JSON
{
"id": "10.21203/
"type": "article",
"title": "Interpretable metrics for evaluating fidelity, diversity, and privacy in synthetic EEG data",
"container-title": "Research Square (preprint)",
"author": [
{
"family": "Silveira",
"given": "Inês"
},
{
"family": "Silva",
"given": "Luís"
},
{
"family": "Furk",
"given": "Dania"
},
{
"family": "Marques",
"given": "Beatriz"
},
{
"family": "Ao",
"given": "Nianfei"
},
{
"family": "Hoogteijling",
"given": "Sem"
},
{
"family": "Heijink",
"given": "Irene"
},
{
"family": "Zijlmans",
"given": "Maeike"
},
{
"family": "Gamboa",
"given": "Hugo"
}
],
"container-title-short":
"DOI": "10.21203/
"ISSN": "2693-5015",
"publisher": "Research Square",
"URL": "https://
"issued": {
"date-parts": [
[
2026,
4,
16
]
]
}
}
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.7554/elife.110588 [code]
- Opening the black box toward a modular approach to spike sorting.Journal: eLifeIn common: UMAP, Numba, scikit-image, 6 other tools
- [2] doi:10.1038/s42003-026-10957-8 [code]
- Brain defence by the extracellular matrix protein Cochlin.Journal: Communications biologyIn common: UMAP, Numba, scikit-image, 6 other tools
- [3] doi:10.1093/nar/gkag706 [code]
- scDifformer: diffusion-based post-training for virtual cell modeling across large-scale single-cell data.Journal: Nucleic acids researchIn common: UMAP, Numba, scikit-image, 6 other tools
- [4] doi:10.1162/imag.a.1276 [code]
- High-resolution whole-brain magnetic resonance spectroscopic imaging in youth at risk for psychosis.Journal: Imaging neuroscience (Cambridge, Mass.)In common: UMAP, Numba, scikit-image, 6 other tools
- [5] doi:10.1016/j.xcrm.2026.102766 [code]
- A longitudinal single-cell and spatial multiomic atlas of pediatric high-grade glioma.Journal: Cell reports. MedicineIn common: UMAP, Numba, scikit-image, 6 other tools
- [6] doi:10.1016/j.isci.2026.116825 [code]
- Social hierarchy shapes behavioral and transcriptional responses to chronic stress and ketamine in male mice.Journal: iScienceIn common: UMAP, Numba, scikit-image, 6 other tools
- [7] doi:10.1371/journal.pbio.3003915 [code]
- Noise-invariant representations of sound emerge along the canonical cortical hierarchy.Journal: PLoS biologyIn common: UMAP, Numba, scikit-image, 6 other tools
- [8] doi:10.3389/fnsys.2026.1822122 [code]
- Convergence-divergence circuits for multimodal integration of innate and learned opponent valences.Journal: Frontiers in systems neuroscienceIn common: UMAP, Numba, scikit-image, 6 other tools
- [9] doi:10.1038/s41467-026-72057-9 [code]
- Sex-specific behavioral feedback modulates sensorimotor processing and drives flexible social behavior.Journal: Nature communicationsIn common: UMAP, Numba, scikit-image, 6 other tools
- [10] doi:10.3390/s26154773 [code]
- EEG-Based Supported Diagnosis of ADHD Using Subject-Specific HMMs and Stationary RKHS Embeddings.Journal: Sensors (Basel, Switzerland)In common: Numba, seaborn, scikit-learn, 4 other tools, EEG, 1 reference
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, 19 scripts, and 25 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:21fe89403fcae318…
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.
