#!/usr/bin/env python3 """Generate a unified interactive macro table HTML from DATASET_METADATA_CATALOG. Outputs a self-contained HTML fragment (summary cards + DataTables table) to ``docs/source/_static/macro_table.html``. Run this script before building the Sphinx docs:: python scripts/generate_macro_table.py """ from __future__ import annotations import html import os import sys from pathlib import Path import pandas as pd # Ensure the repo root and sphinxext dir are importable _REPO_ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(_REPO_ROOT)) sys.path.insert(0, str(_REPO_ROOT / "docs" / "source" / "sphinxext")) from dataset_constants import ( # noqa: E402 PARADIGM_COLORS, PARADIGM_LABELS, country_flag, normalize_country, normalize_health, ) # --------------------------------------------------------------------------- # Constants # --------------------------------------------------------------------------- _PARADIGM_LABELS = PARADIGM_LABELS _PARADIGM_COLORS = PARADIGM_COLORS _HEALTH_COLORS = {"healthy": "#2E7D32", "patients": "#E65100", "mixed": "#F9A825"} _OUTPUT_PATH = _REPO_ROOT / "docs" / "source" / "_static" / "macro_table.html" # --------------------------------------------------------------------------- # Flatten metadata catalog → DataFrame # --------------------------------------------------------------------------- def _safe_get(obj, *attrs, default=None): """Safely traverse nested attributes.""" for attr in attrs: if obj is None: return default obj = getattr(obj, attr, None) return obj if obj is not None else default def catalog_to_dataframe(catalog=None) -> pd.DataFrame: """Flatten ``DATASET_METADATA_CATALOG`` into a pandas DataFrame. Parameters ---------- catalog : dict-like, optional Override catalog. Defaults to ``DATASET_METADATA_CATALOG``. Returns ------- pd.DataFrame One row per dataset with all key metadata columns. """ if catalog is None: from moabb.datasets.metadata import DATASET_METADATA_CATALOG catalog = DATASET_METADATA_CATALOG rows = [] for name, meta in catalog.items(): acq = meta.acquisition par = meta.participants exp = meta.experiment doc = meta.documentation aux = _safe_get(acq, "auxiliary_channels") ps = meta.paradigm_specific tags = meta.tags ds = meta.data_structure gender = _safe_get(par, "gender") handedness = _safe_get(par, "handedness") row = { # --- Core (visible by default) --- "dataset": name, "paradigm": _safe_get(exp, "paradigm", default=""), "n_subjects": _safe_get(par, "n_subjects", default=0), "n_channels": _safe_get(acq, "n_channels", default=0), "n_eeg_channels": (_safe_get(acq, "channel_types") or {}).get("eeg", 0), "n_classes": _safe_get(exp, "n_classes"), "sampling_rate": _safe_get(acq, "sampling_rate", default=0), "trial_duration": _safe_get(exp, "trial_duration"), "sessions": meta.sessions_per_subject or 1, "runs": meta.runs_per_session or 1, "health_status": _safe_get(par, "health_status", default=""), "doi": _safe_get(doc, "doi"), # --- Hidden by default (toggled via ColVis) --- # Experiment "class_labels": ", ".join(_safe_get(exp, "class_labels") or []), "stimulus_type": _safe_get(exp, "stimulus_type"), "primary_modality": _safe_get(exp, "primary_modality"), "feedback_type": _safe_get(exp, "feedback_type"), "synchronicity": _safe_get(exp, "synchronicity"), "mode": _safe_get(exp, "mode"), "study_design": _safe_get(exp, "study_design"), # Acquisition "hardware": _safe_get(acq, "hardware"), "reference": _safe_get(acq, "reference"), "sensor_type": _safe_get(acq, "sensor_type"), "montage": _safe_get(acq, "montage"), "line_freq": _safe_get(acq, "line_freq"), "filters": _safe_get(acq, "filters"), "cap_manufacturer": _safe_get(acq, "cap_manufacturer"), "software": _safe_get(acq, "software"), # Participants "clinical_population": _safe_get(par, "clinical_population"), "age_mean": _safe_get(par, "age_mean"), "age_min": _safe_get(par, "age_min"), "age_max": _safe_get(par, "age_max"), "gender": ( ", ".join(f"{k}:{v}" for k, v in gender.items()) if isinstance(gender, dict) else "" ), "handedness": ( handedness if isinstance(handedness, str) else ( ", ".join(f"{k}:{v}" for k, v in handedness.items()) if isinstance(handedness, dict) else "" ) ), "bci_experience": _safe_get(par, "bci_experience"), # Documentation "license": _safe_get(doc, "license"), "country": _normalize_country(_safe_get(doc, "country")), "institution": _safe_get(doc, "institution"), "publication_year": _safe_get(doc, "publication_year"), "repository": _safe_get(doc, "repository"), "senior_author": _safe_get(doc, "senior_author"), "data_url": _safe_get(doc, "data_url"), # Tags "tags_pathology": ", ".join(_safe_get(tags, "pathology") or []), "tags_modality": ", ".join(_safe_get(tags, "modality") or []), "tags_type": ", ".join(_safe_get(tags, "type") or []), # Structure "file_format": meta.file_format or "", "has_eog": _safe_get(aux, "has_eog", default=False), "has_emg": _safe_get(aux, "has_emg", default=False), # Duration placeholder (to be filled manually) "duration_hours": None, # Data structure "n_trials": _fmt_trials(_safe_get(ds, "n_trials")), "n_blocks": _safe_get(ds, "n_blocks"), "trials_context": _safe_get(ds, "trials_context"), # Paradigm-specific "stimulus_frequencies": _fmt_freq_list( _safe_get(ps, "stimulus_frequencies_hz") ), "code_type": _safe_get(ps, "code_type"), "n_targets": _safe_get(ps, "n_targets"), "n_repetitions": _safe_get(ps, "n_repetitions"), "isi_ms": _safe_get(ps, "isi_ms"), "soa_ms": _safe_get(ps, "soa_ms"), "imagery_tasks": ", ".join(_safe_get(ps, "imagery_tasks") or []), } rows.append(row) df = pd.DataFrame(rows) df = df.sort_values("dataset").reset_index(drop=True) return df def _fmt_trials(val) -> str: """Format n_trials which can be int, dict, or str.""" if val is None: return "" if isinstance(val, (int, float)): return str(int(val)) if isinstance(val, dict): return ", ".join(f"{k}: {v}" for k, v in val.items()) return str(val) def _fmt_freq_list(val) -> str: """Format a list of stimulus frequencies compactly.""" if not val: return "" if isinstance(val, list) and len(val) > 6: return f"{val[0]:g}–{val[-1]:g} Hz ({len(val)} freqs)" if isinstance(val, list): return ", ".join(f"{f:g}" for f in val) return str(val) # Country/health helpers imported from dataset_constants _normalize_country = normalize_country _country_flag = country_flag # --------------------------------------------------------------------------- # HTML generation # --------------------------------------------------------------------------- _CARD_ICONS = { "datasets": ( '' ), "subjects": ( '' ), "paradigms": ( '' ), "countries": ( '' ), "years": ( '' ), } def _build_paradigm_bar(df: pd.DataFrame) -> str: """Build an inline paradigm distribution bar.""" counts = df["paradigm"].value_counts() total = len(df) segments = [] for paradigm in ["imagery", "p300", "ssvep", "cvep", "rstate"]: n = counts.get(paradigm, 0) if n == 0: continue pct = n / total * 100 color = _PARADIGM_COLORS.get(paradigm, "#757575") label = _PARADIGM_LABELS.get(paradigm, paradigm) segments.append( f'
" ) legend_items = [] for paradigm in ["imagery", "p300", "ssvep", "cvep", "rstate"]: n = counts.get(paradigm, 0) if n == 0: continue color = _PARADIGM_COLORS.get(paradigm, "#757575") label = _PARADIGM_LABELS.get(paradigm, paradigm) legend_items.append( f'" ) return ( f'" ) def _build_summary_cards(df: pd.DataFrame) -> str: """Build HTML for the top-row summary metric cards.""" total_datasets = len(df) total_subjects = int(df["n_subjects"].sum()) n_paradigms = df["paradigm"].nunique() countries = df["country"].dropna().nunique() year_min = df["publication_year"].dropna() year_range = ( f"{int(year_min.min())}–{int(year_min.max())}" if len(year_min) else "N/A" ) cards_data = [ ("datasets", "Datasets", str(total_datasets), "curated BCI datasets"), ("subjects", "Subjects", f"{total_subjects:,}", "total participants"), ("paradigms", "Paradigms", str(n_paradigms), "BCI paradigm types"), ("countries", "Countries", str(countries), "represented"), ("years", "Years", year_range, "publication span"), ] items = [] for i, (icon_key, label, value, subtitle) in enumerate(cards_data): icon_svg = _CARD_ICONS.get(icon_key, "") items.append( f'| {col[0]} | " for col in _TABLE_COLUMNS) thead = f"
|---|
| {c} | " for c in cells) body_rows.append(f'