Contiguous temporal withholding for hemispheric analysis in frontal EEG during cycling.
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 · 297 lines · 12 KB · no license
- # -*- coding: utf-8 -*-
- """
- Created on Wed Feb 11 14:02:57 2026
- @author: USER
- """
- # -*- coding: utf-8 -*-
- """
- BiLSTM baseline with contiguous temporal test-block evaluation.
- Dataset overview
- - The database contains 4 subjects.
- - For each subject, multiple pedaling sessions were recorded.
- - Each session was segmented into contraction epochs.
- - For each contraction epoch, 18 electrode-wise segments were generated (one per electrode).
- - The .mat file stores the concatenation of all sessions for that subject.
- Therefore, the total number of samples in X is:
- N = (pedaling_sessions) × (contraction_epochs_per_session) × 18
- Per subject (from the dataset overview table):
- - Subject 1: 2 × 100 × 18 = 3600
- - Subject 2: 3 × 100 × 18 = 5400
- - Subject 3: 3 × 62 × 18 = 3348
- - Subject 4: 3 × 40 × 18 = 2160
- Variables inside each .mat file
- - X: array shaped (N, 1, T)
- N = total electrode-wise segments across all sessions
- T = number of time samples per segment (e.g., 164 for Subject 1 in the uploaded file)
- Values are float64.
- - Y_text: array shaped (N, 1)
- Hemisphere labels as strings '0' and '1', one label per electrode-wise segment:
- '0' = Left hemisphere electrode
- '1' = Right hemisphere electrode
- Important
- - Each input sample to the BiLSTM corresponds to ONE electrode segment from ONE contraction epoch
- (not a full 18-channel contraction).
- Evaluation protocol (contiguous temporal ablation)
- - Select a contiguous block of length floor(test_fraction * N) as TEST.
- - Use the remaining samples as a pool; shuffle them; split into TRAIN and VALIDATION.
- - Train the BiLSTM with early stopping and learning-rate reduction.
- - Evaluate on the TEST block.
- - Repeat across num_blocks start positions distributed across the time axis.
- - Repeat the whole procedure repeat_index = 1..5 and save metrics to Excel each time.
- """
- import time
- import scipy.io
- import numpy as np
- import tensorflow as tf
- import pandas as pd
- from sklearn.preprocessing import LabelEncoder
- from sklearn.metrics import confusion_matrix, precision_recall_fscore_support
- from tensorflow.keras.models import Sequential
- from tensorflow.keras.layers import Bidirectional, LSTM, Dense, Dropout
- from tensorflow.keras.utils import to_categorical
- from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
- from tensorflow.keras.optimizers import Adam
- # ---------------- Baseline hyperparameters ----------------
- for subject_number in range(1, 5):
- validation_fraction = 0.1 # fraction of the remaining pool reserved for validation
- epochs = 40
- batch_size = 32
- test_fraction = 0.20 # contiguous fraction of samples used as TEST
- num_blocks = 20 # number of contiguous TEST blocks (start positions)
- num_repeats = 5 # number of full repeats saved as separate Excel files
- for repeat_index in range(1, num_repeats + 1):
- # Reproducibility (same seed per repeat_index)
- np.random.seed(42)
- tf.random.set_seed(42)
- print(f"\nSubject: {subject_number}")
- print("Model: BiLSTM")
- print("Protocol: contiguous TEST block; validation from shuffled remainder")
- print("Labels: 0 = Left, 1 = Right")
- # ---------------- Load data ----------------
- # Keep filename convention consistent with your stored files.
- # If your files are named 'XY_Voluntario_{k}_text.mat', change this line accordingly.
- mat_filename = f"Subject_{subject_number}.mat"
- mat_data = scipy.io.loadmat(mat_filename)
- # Raw variables from file
- signal_segments = mat_data["X"] # shape (N, 1, T)
- hemisphere_labels_raw = mat_data["Y_text"].squeeze() # shape (N,) or (N,1) after squeeze
- # Convert labels to a clean 1D string array, e.g., ['0','1',...]
- hemisphere_labels_str = np.array([str(s[0]) for s in hemisphere_labels_raw])
- # Encode labels (strings -> int -> one-hot)
- label_encoder = LabelEncoder()
- hemisphere_labels_int = label_encoder.fit_transform(hemisphere_labels_str)
- hemisphere_labels_onehot = to_categorical(hemisphere_labels_int)
- # Reshape signals for LSTM input: (N, T, 1)
- # The middle dimension (1) is removed; each sample is an electrode-wise temporal segment.
- signal_segments_flat = signal_segments.squeeze(axis=1) # (N, T)
- signal_lstm_input = signal_segments_flat[..., np.newaxis] # (N, T, 1)
- total_samples = signal_lstm_input.shape[0]
- print("Total samples (electrode-wise segments):", total_samples)
- # Length of contiguous TEST block
- test_block_length = int(np.floor(test_fraction * total_samples))
- if test_block_length < 1:
- raise ValueError("Contiguous TEST block is too small. Increase N or test_fraction.")
- # Start indices distributed across the time axis
- test_start_indices = np.linspace(0, total_samples - test_block_length, num_blocks, dtype=int)
- # ---------------- Callbacks (baseline) ----------------
- callbacks = [
- EarlyStopping(
- monitor="val_loss",
- patience=8,
- restore_best_weights=True
- ),
- ReduceLROnPlateau(
- monitor="val_loss",
- factor=0.5,
- patience=4,
- verbose=1
- )
- ]
- # Store metrics for each contiguous block run
- all_results = []
- # ---------------- Contiguous block evaluation ----------------
- for block_index, test_start in enumerate(test_start_indices):
- test_end = test_start + test_block_length
- print(f"\n=== RUN {block_index + 1}/{num_blocks} ===")
- print(f"TEST block indices: {test_start}–{test_end - 1}")
- # Mask to exclude the TEST block from the training pool
- keep_mask = np.ones(total_samples, dtype=bool)
- keep_mask[test_start:test_end] = False
- # Remaining pool (TRAIN + VALIDATION)
- remaining_signals = signal_lstm_input[keep_mask]
- remaining_labels = hemisphere_labels_onehot[keep_mask]
- # TEST block (contiguous in time)
- test_signals = signal_lstm_input[test_start:test_end]
- test_labels = hemisphere_labels_onehot[test_start:test_end]
- # Shuffle the remaining pool before splitting into TRAIN / VALIDATION
- shuffled_indices = np.arange(remaining_signals.shape[0])
- np.random.shuffle(shuffled_indices)
- remaining_signals = remaining_signals[shuffled_indices]
- remaining_labels = remaining_labels[shuffled_indices]
- # Manual TRAIN / VALIDATION split
- split_index = int((1.0 - validation_fraction) * remaining_signals.shape[0])
- train_signals = remaining_signals[:split_index]
- train_labels = remaining_labels[:split_index]
- val_signals = remaining_signals[split_index:]
- val_labels = remaining_labels[split_index:]
- # ---------------- Model (rebuilt each run) ----------------
- model = Sequential([
- Bidirectional(
- LSTM(
- 32,
- input_shape=(signal_lstm_input.shape[1], signal_lstm_input.shape[2])
- )
- ),
- Dropout(0.5),
- Dense(64, activation="relu"),
- Dropout(0.4),
- Dense(hemisphere_labels_onehot.shape[1], activation="softmax")
- ])
- model.compile(
- optimizer=Adam(learning_rate=0.001, clipnorm=1.0),
- loss="categorical_crossentropy",
- metrics=["accuracy"]
- )
- start_time = time.time()
- history = model.fit(
- train_signals, train_labels,
- epochs=epochs,
- batch_size=batch_size,
- validation_data=(val_signals, val_labels),
- callbacks=callbacks,
- verbose=0,
- shuffle=True
- )
- elapsed_s = time.time() - start_time
- # Final training/validation accuracy from the last epoch recorded
- train_acc = history.history["accuracy"][-1]
- val_acc = history.history["val_accuracy"][-1]
- gap_train_val = train_acc - val_acc
- # Evaluate on TEST block
- test_loss, test_acc = model.evaluate(test_signals, test_labels, verbose=0)
- # Predictions on TEST
- test_prob = model.predict(test_signals, verbose=0)
- test_pred = np.argmax(test_prob, axis=1)
- test_true = np.argmax(test_labels, axis=1)
- # Confusion matrix and per-class metrics
- cm = confusion_matrix(test_true, test_pred)
- # Using labels=[0,1] ensures consistent order: class 0 (Left), class 1 (Right)
- precision, recall, f1, _ = precision_recall_fscore_support(
- test_true,
- test_pred,
- average=None,
- labels=[0, 1],
- zero_division=0
- )
- print(f"Train acc (final): {train_acc:.4f}")
- print(f"Val acc (final): {val_acc:.4f}")
- print(f"Test acc: {test_acc:.4f}")
- print(f"Recall (Left=0): {recall[0]:.4f}")
- print(f"Recall (Right=1): {recall[1]:.4f}")
- print(f"F1 (Left=0): {f1[0]:.4f}")
- print(f"F1 (Right=1): {f1[1]:.4f}")
- print(f"Time (s): {elapsed_s:.2f}")
- # Store results for this contiguous block
- all_results.append({
- "run": block_index + 1,
- "test_block_start": int(test_start),
- "test_block_end": int(test_end - 1),
- "n_train": int(train_signals.shape[0]),
- "n_val": int(val_signals.shape[0]),
- "n_test": int(test_signals.shape[0]),
- "train_acc": float(train_acc),
- "val_acc": float(val_acc),
- "test_acc": float(test_acc),
- "gap_train_val": float(gap_train_val),
- "time_s": float(elapsed_s),
- "epochs_used": int(len(history.history["accuracy"])),
- # Confusion matrix entries for binary classification
- "cm_00": int(cm[0, 0]),
- "cm_01": int(cm[0, 1]),
- "cm_10": int(cm[1, 0]),
- "cm_11": int(cm[1, 1]),
- # Class-wise metrics (0=Left, 1=Right)
- "prec_0_left": float(precision[0]),
- "rec_0_left": float(recall[0]),
- "f1_0_left": float(f1[0]),
- "prec_1_right": float(precision[1]),
- "rec_1_right": float(recall[1]),
- "f1_1_right": float(f1[1]),
- })
- # ---------------- End-of-repeat summary ----------------
- print("\n===== SUMMARY OF CONTIGUOUS BLOCK RUNS =====")
- for r in all_results:
- print(
- f"Run {r['run']:02d} | "
- f"Train {r['train_acc']:.3f} | "
- f"Val {r['val_acc']:.3f} | "
- f"Test {r['test_acc']:.3f} | "
- f"rec(L=0) {r['rec_0_left']:.3f} | rec(R=1) {r['rec_1_right']:.3f} | "
- f"prec(L=0) {r['prec_0_left']:.3f} | prec(R=1) {r['prec_1_right']:.3f} | "
- f"f1(L=0) {r['f1_0_left']:.3f} | f1(R=1) {r['f1_1_right']:.3f} | "
- f"test_block {r['test_block_start']}-{r['test_block_end']}"
- )
- # ---------------- Save results to Excel ----------------
- results_df = pd.DataFrame(all_results)
- # Output name per subject and repeat index
- excel_name = f"Subject{subject_number}_results_repeat{repeat_index}.xlsx"
- results_df.to_excel(excel_name, index=False)
- print(f"File saved: {excel_name}")
Test_block.py at commit a102e4b, no license · at the source
Overview
- Center for Research and Advanced Studies (Cinvestav), Monterrey’s Unit, Apodaca, Nuevo León 66628, Mexico
- Center for Research and Advanced Studies (Cinvestav), Saltillo’s Unit, Ramos Arizpe, Coahuila 25900, Mexico
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.
Repositories
Its files are read in the Code ↔ Paper reader above.
u.pc.cd/vpk
Availability: 1 check, the latest on 29 September 2026: the link answers (HTTP 200)
- 29 September 2026: the link answers (HTTP 200)
drcrane369/bilstm-contiguous-test
a102e4b6b3c2f1ed3740cc7a11bccb9f874fcc31, 11 February 2026Availability: 1 check, the latest on 29 September 2026: the link answers
- 29 September 2026: the link answers
2 files
- Test_block.py, Python, 297 lines
- README.md, Text, 28 lines
The paper's code and data availability statement is in the Data section.
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:
- 2 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
- 1 script, each with its path and the digest of its content;
- no match between paragraphs and code yet;
- 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
No dataset and no data link were found in the paper.
Availability statements
The paper has a data availability statement and a code and data availability statement. Its license (CC BY-NC-ND) does not allow reproducing them here; in short, from what the harvester recognized in them:
- no repository, dataset or request procedure was recognized in them
Read them in the paper: doi.org/10.1016/j.mex.2026.103928.
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, language, journal, volume, pages, dates, 3 authors, 5 keywords, 1 funder, 14 references.
Cite
This paper
Hernández-del-Valle, R. C., Gutiérrez, D., & Castelán, M. (2026). Contiguous temporal withholding for hemispheric analysis in frontal EEG during cycling. MethodsX, 16, 103928. https://
BibTeX
@article{hernandezdelval
author = {Hernández-del-Valle, Roberto Carlos and Gutiérrez, David and Castelán, Mario},
title = {{Contiguous temporal withholding for hemispheric analysis in frontal EEG during cycling}},
journal = {MethodsX},
year = {2026},
month = apr,
volume = {16},
pages = {103928},
publisher = {Elsevier},
issn = {2215-0161},
doi = {10.1016/
url = {https://
pmid = {42100749},
pmcid = {PMC13147397}
}
RIS
TY - JOUR
AU - Hernández-del-Valle, Roberto Carlos
AU - Gutiérrez, David
AU - Castelán, Mario
TI - Contiguous temporal withholding for hemispheric analysis in frontal EEG during cycling
T2 - MethodsX
J2 - MethodsX
PY - 2026
DA - 2026/
VL - 16
SP - 103928
SN - 2215-0161
PB - Elsevier
DO - 10.1016/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.1016/
"type": "article-journal",
"title": "Contiguous temporal withholding for hemispheric analysis in frontal EEG during cycling",
"container-title": "MethodsX",
"author": [
{
"family": "Hernández-del-Valle",
"given": "Roberto Carlos"
},
{
"family": "Gutiérrez",
"given": "David"
},
{
"family": "Castelán",
"given": "Mario"
}
],
"container-title-short":
"volume": "16",
"page": "103928",
"DOI": "10.1016/
"PMID": "42100749",
"PMCID": "PMC13147397",
"ISSN": "2215-0161",
"publisher": "Elsevier",
"URL": "https://
"language": "en",
"issued": {
"date-parts": [
[
2026,
4,
24
]
]
}
}
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.1002/ana.78203 [code]
- AI-Driven Mapping of Seizure Spread Patterns.Journal: Annals of neurologyIn common: Keras, TensorFlow, scikit-learn, 3 other tools, EEG, 1 reference
- [2] doi:10.1093/sleepadvances/zpag051 [code]
- What matters beyond model choice for wearable sleep staging? How personalization, evaluation choices, and easy-to-classify wake impact performance.Journal: Sleep advances : a journal of the Sleep Research SocietyIn common: Keras, TensorFlow, scikit-learn, 3 other tools, methods / tools, EEG
- [3] doi:10.1038/s41598-026-52330-z [code]
- SHAP analysis of an improved EEG-based mental workload classification framework: utilizing data augmentation and explainable AI.Journal: Scientific reportsIn common: Keras, TensorFlow, scikit-learn, 3 other tools, methods / tools, EEG
- [4] doi:10.1038/s41597-025-05174-7 [code]
- A large-scale MEG and EEG dataset for object recognition in naturalistic scenesJournal: n/aIn common: Keras, TensorFlow, scikit-learn, 3 other tools, methods / tools, EEG
- [5] doi:10.1126/sciadv.aed3650 [code]
- Truthful visualizations for mass spectrometry imaging enable high-spatial-resolution interactive &
lt;i& gt;m/ z& lt;/ i& gt; mapping and exploration. Journal: Science advancesIn common: Keras, TensorFlow, scikit-learn, 3 other tools, methods / tools - [6] doi:10.1039/d6ra03343a [code]
- A benchmark dataset and interpretable deep learning framework for drug-induced developmental neurotoxicity prediction.Journal: RSC advancesIn common: Keras, TensorFlow, scikit-learn, 3 other tools, methods / tools
- [7] doi:10.1177/13872877261453512 [code]
- Fluorescence spectroscopy and machine learning methods for detection of Alzheimer's disease from circulating white blood cells.Journal: Journal of Alzheimer's disease : JADIn common: Keras, TensorFlow, scikit-learn, 3 other tools, methods / tools
- [8] doi:10.1002/nbm.70263 [code]
- Cross-Site Generalization of CNN-Based $$ {B}_1^{+} $$ Mapping in UHF MRI.Journal: NMR in biomedicineIn common: Keras, TensorFlow, scikit-learn, 3 other tools, methods / tools
- [9] doi:10.1186/s12938-026-01555-0 [code]
- Incorporating normal periventricular changes for enhanced pathological white matter hyperintensity segmentation: on multiclass deep learning approaches.Journal: Biomedical engineering onlineIn common: Keras, TensorFlow, scikit-learn, 3 other tools, methods / tools
- [10] doi:10.1038/s41597-026-07184-5 [code]
- A Multiple Sclerosis MRI Dataset with Tri-Mask Annotations for Lesion Segmentation.Journal: Scientific dataIn common: Keras, TensorFlow, scikit-learn, 3 other tools, methods / tools
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: 2 repositories of the authors' code, each at its verified commit and with its license, 1 script, and 0 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:45ebe132c7976459…
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.
