OSCR

Contiguous temporal withholding for hemispheric analysis in frontal EEG during cycling.

Code ↔ Paper

The paper beside its authors' code: matches between them have not been computed for this paper yet.

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

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Wed Feb 11 14:02:57 2026
  4. @author: USER
  5. """
  6. # -*- coding: utf-8 -*-
  7. """
  8. BiLSTM baseline with contiguous temporal test-block evaluation.
  9. Dataset overview
  10. - The database contains 4 subjects.
  11. - For each subject, multiple pedaling sessions were recorded.
  12. - Each session was segmented into contraction epochs.
  13. - For each contraction epoch, 18 electrode-wise segments were generated (one per electrode).
  14. - The .mat file stores the concatenation of all sessions for that subject.
  15. Therefore, the total number of samples in X is:
  16. N = (pedaling_sessions) × (contraction_epochs_per_session) × 18
  17. Per subject (from the dataset overview table):
  18. - Subject 1: 2 × 100 × 18 = 3600
  19. - Subject 2: 3 × 100 × 18 = 5400
  20. - Subject 3: 3 × 62 × 18 = 3348
  21. - Subject 4: 3 × 40 × 18 = 2160
  22. Variables inside each .mat file
  23. - X: array shaped (N, 1, T)
  24. N = total electrode-wise segments across all sessions
  25. T = number of time samples per segment (e.g., 164 for Subject 1 in the uploaded file)
  26. Values are float64.
  27. - Y_text: array shaped (N, 1)
  28. Hemisphere labels as strings '0' and '1', one label per electrode-wise segment:
  29. '0' = Left hemisphere electrode
  30. '1' = Right hemisphere electrode
  31. Important
  32. - Each input sample to the BiLSTM corresponds to ONE electrode segment from ONE contraction epoch
  33. (not a full 18-channel contraction).
  34. Evaluation protocol (contiguous temporal ablation)
  35. - Select a contiguous block of length floor(test_fraction * N) as TEST.
  36. - Use the remaining samples as a pool; shuffle them; split into TRAIN and VALIDATION.
  37. - Train the BiLSTM with early stopping and learning-rate reduction.
  38. - Evaluate on the TEST block.
  39. - Repeat across num_blocks start positions distributed across the time axis.
  40. - Repeat the whole procedure repeat_index = 1..5 and save metrics to Excel each time.
  41. """
  42. import time
  43. import scipy.io
  44. import numpy as np
  45. import tensorflow as tf
  46. import pandas as pd
  47. from sklearn.preprocessing import LabelEncoder
  48. from sklearn.metrics import confusion_matrix, precision_recall_fscore_support
  49. from tensorflow.keras.models import Sequential
  50. from tensorflow.keras.layers import Bidirectional, LSTM, Dense, Dropout
  51. from tensorflow.keras.utils import to_categorical
  52. from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
  53. from tensorflow.keras.optimizers import Adam
  54. # ---------------- Baseline hyperparameters ----------------
  55. for subject_number in range(1, 5):
  56. validation_fraction = 0.1 # fraction of the remaining pool reserved for validation
  57. epochs = 40
  58. batch_size = 32
  59. test_fraction = 0.20 # contiguous fraction of samples used as TEST
  60. num_blocks = 20 # number of contiguous TEST blocks (start positions)
  61. num_repeats = 5 # number of full repeats saved as separate Excel files
  62. for repeat_index in range(1, num_repeats + 1):
  63. # Reproducibility (same seed per repeat_index)
  64. np.random.seed(42)
  65. tf.random.set_seed(42)
  66. print(f"\nSubject: {subject_number}")
  67. print("Model: BiLSTM")
  68. print("Protocol: contiguous TEST block; validation from shuffled remainder")
  69. print("Labels: 0 = Left, 1 = Right")
  70. # ---------------- Load data ----------------
  71. # Keep filename convention consistent with your stored files.
  72. # If your files are named 'XY_Voluntario_{k}_text.mat', change this line accordingly.
  73. mat_filename = f"Subject_{subject_number}.mat"
  74. mat_data = scipy.io.loadmat(mat_filename)
  75. # Raw variables from file
  76. signal_segments = mat_data["X"] # shape (N, 1, T)
  77. hemisphere_labels_raw = mat_data["Y_text"].squeeze() # shape (N,) or (N,1) after squeeze
  78. # Convert labels to a clean 1D string array, e.g., ['0','1',...]
  79. hemisphere_labels_str = np.array([str(s[0]) for s in hemisphere_labels_raw])
  80. # Encode labels (strings -> int -> one-hot)
  81. label_encoder = LabelEncoder()
  82. hemisphere_labels_int = label_encoder.fit_transform(hemisphere_labels_str)
  83. hemisphere_labels_onehot = to_categorical(hemisphere_labels_int)
  84. # Reshape signals for LSTM input: (N, T, 1)
  85. # The middle dimension (1) is removed; each sample is an electrode-wise temporal segment.
  86. signal_segments_flat = signal_segments.squeeze(axis=1) # (N, T)
  87. signal_lstm_input = signal_segments_flat[..., np.newaxis] # (N, T, 1)
  88. total_samples = signal_lstm_input.shape[0]
  89. print("Total samples (electrode-wise segments):", total_samples)
  90. # Length of contiguous TEST block
  91. test_block_length = int(np.floor(test_fraction * total_samples))
  92. if test_block_length < 1:
  93. raise ValueError("Contiguous TEST block is too small. Increase N or test_fraction.")
  94. # Start indices distributed across the time axis
  95. test_start_indices = np.linspace(0, total_samples - test_block_length, num_blocks, dtype=int)
  96. # ---------------- Callbacks (baseline) ----------------
  97. callbacks = [
  98. EarlyStopping(
  99. monitor="val_loss",
  100. patience=8,
  101. restore_best_weights=True
  102. ),
  103. ReduceLROnPlateau(
  104. monitor="val_loss",
  105. factor=0.5,
  106. patience=4,
  107. verbose=1
  108. )
  109. ]
  110. # Store metrics for each contiguous block run
  111. all_results = []
  112. # ---------------- Contiguous block evaluation ----------------
  113. for block_index, test_start in enumerate(test_start_indices):
  114. test_end = test_start + test_block_length
  115. print(f"\n=== RUN {block_index + 1}/{num_blocks} ===")
  116. print(f"TEST block indices: {test_start}–{test_end - 1}")
  117. # Mask to exclude the TEST block from the training pool
  118. keep_mask = np.ones(total_samples, dtype=bool)
  119. keep_mask[test_start:test_end] = False
  120. # Remaining pool (TRAIN + VALIDATION)
  121. remaining_signals = signal_lstm_input[keep_mask]
  122. remaining_labels = hemisphere_labels_onehot[keep_mask]
  123. # TEST block (contiguous in time)
  124. test_signals = signal_lstm_input[test_start:test_end]
  125. test_labels = hemisphere_labels_onehot[test_start:test_end]
  126. # Shuffle the remaining pool before splitting into TRAIN / VALIDATION
  127. shuffled_indices = np.arange(remaining_signals.shape[0])
  128. np.random.shuffle(shuffled_indices)
  129. remaining_signals = remaining_signals[shuffled_indices]
  130. remaining_labels = remaining_labels[shuffled_indices]
  131. # Manual TRAIN / VALIDATION split
  132. split_index = int((1.0 - validation_fraction) * remaining_signals.shape[0])
  133. train_signals = remaining_signals[:split_index]
  134. train_labels = remaining_labels[:split_index]
  135. val_signals = remaining_signals[split_index:]
  136. val_labels = remaining_labels[split_index:]
  137. # ---------------- Model (rebuilt each run) ----------------
  138. model = Sequential([
  139. Bidirectional(
  140. LSTM(
  141. 32,
  142. input_shape=(signal_lstm_input.shape[1], signal_lstm_input.shape[2])
  143. )
  144. ),
  145. Dropout(0.5),
  146. Dense(64, activation="relu"),
  147. Dropout(0.4),
  148. Dense(hemisphere_labels_onehot.shape[1], activation="softmax")
  149. ])
  150. model.compile(
  151. optimizer=Adam(learning_rate=0.001, clipnorm=1.0),
  152. loss="categorical_crossentropy",
  153. metrics=["accuracy"]
  154. )
  155. start_time = time.time()
  156. history = model.fit(
  157. train_signals, train_labels,
  158. epochs=epochs,
  159. batch_size=batch_size,
  160. validation_data=(val_signals, val_labels),
  161. callbacks=callbacks,
  162. verbose=0,
  163. shuffle=True
  164. )
  165. elapsed_s = time.time() - start_time
  166. # Final training/validation accuracy from the last epoch recorded
  167. train_acc = history.history["accuracy"][-1]
  168. val_acc = history.history["val_accuracy"][-1]
  169. gap_train_val = train_acc - val_acc
  170. # Evaluate on TEST block
  171. test_loss, test_acc = model.evaluate(test_signals, test_labels, verbose=0)
  172. # Predictions on TEST
  173. test_prob = model.predict(test_signals, verbose=0)
  174. test_pred = np.argmax(test_prob, axis=1)
  175. test_true = np.argmax(test_labels, axis=1)
  176. # Confusion matrix and per-class metrics
  177. cm = confusion_matrix(test_true, test_pred)
  178. # Using labels=[0,1] ensures consistent order: class 0 (Left), class 1 (Right)
  179. precision, recall, f1, _ = precision_recall_fscore_support(
  180. test_true,
  181. test_pred,
  182. average=None,
  183. labels=[0, 1],
  184. zero_division=0
  185. )
  186. print(f"Train acc (final): {train_acc:.4f}")
  187. print(f"Val acc (final): {val_acc:.4f}")
  188. print(f"Test acc: {test_acc:.4f}")
  189. print(f"Recall (Left=0): {recall[0]:.4f}")
  190. print(f"Recall (Right=1): {recall[1]:.4f}")
  191. print(f"F1 (Left=0): {f1[0]:.4f}")
  192. print(f"F1 (Right=1): {f1[1]:.4f}")
  193. print(f"Time (s): {elapsed_s:.2f}")
  194. # Store results for this contiguous block
  195. all_results.append({
  196. "run": block_index + 1,
  197. "test_block_start": int(test_start),
  198. "test_block_end": int(test_end - 1),
  199. "n_train": int(train_signals.shape[0]),
  200. "n_val": int(val_signals.shape[0]),
  201. "n_test": int(test_signals.shape[0]),
  202. "train_acc": float(train_acc),
  203. "val_acc": float(val_acc),
  204. "test_acc": float(test_acc),
  205. "gap_train_val": float(gap_train_val),
  206. "time_s": float(elapsed_s),
  207. "epochs_used": int(len(history.history["accuracy"])),
  208. # Confusion matrix entries for binary classification
  209. "cm_00": int(cm[0, 0]),
  210. "cm_01": int(cm[0, 1]),
  211. "cm_10": int(cm[1, 0]),
  212. "cm_11": int(cm[1, 1]),
  213. # Class-wise metrics (0=Left, 1=Right)
  214. "prec_0_left": float(precision[0]),
  215. "rec_0_left": float(recall[0]),
  216. "f1_0_left": float(f1[0]),
  217. "prec_1_right": float(precision[1]),
  218. "rec_1_right": float(recall[1]),
  219. "f1_1_right": float(f1[1]),
  220. })
  221. # ---------------- End-of-repeat summary ----------------
  222. print("\n===== SUMMARY OF CONTIGUOUS BLOCK RUNS =====")
  223. for r in all_results:
  224. print(
  225. f"Run {r['run']:02d} | "
  226. f"Train {r['train_acc']:.3f} | "
  227. f"Val {r['val_acc']:.3f} | "
  228. f"Test {r['test_acc']:.3f} | "
  229. f"rec(L=0) {r['rec_0_left']:.3f} | rec(R=1) {r['rec_1_right']:.3f} | "
  230. f"prec(L=0) {r['prec_0_left']:.3f} | prec(R=1) {r['prec_1_right']:.3f} | "
  231. f"f1(L=0) {r['f1_0_left']:.3f} | f1(R=1) {r['f1_1_right']:.3f} | "
  232. f"test_block {r['test_block_start']}-{r['test_block_end']}"
  233. )
  234. # ---------------- Save results to Excel ----------------
  235. results_df = pd.DataFrame(all_results)
  236. # Output name per subject and repeat index
  237. excel_name = f"Subject{subject_number}_results_repeat{repeat_index}.xlsx"
  238. results_df.to_excel(excel_name, index=False)
  239. print(f"File saved: {excel_name}")

Test_block.py at commit a102e4b, no license · at the source

Overview

Authors: Roberto Carlos Hernández-del-Valle1, David Gutiérrez1, Mario Castelán2
ORCID iDs: Mario Castelán
  1. Center for Research and Advanced Studies (Cinvestav), Monterrey’s Unit, Apodaca, Nuevo León 66628, Mexico
  2. Center for Research and Advanced Studies (Cinvestav), Saltillo’s Unit, Ramos Arizpe, Coahuila 25900, Mexico
Journal: MethodsX, volume 16, article 103928
Dates: received 25 February 2026; accepted 23 April 2026; published online 24 April 2026
Type: Research article · Language: English
License: CC BY-NC-ND
Identifiers: DOI 10.1016/j.mex.2026.103928 · PMID 42100749 · PMCID PMC13147397 · OpenAlex W7155526546
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: EEG (modality), methods / tools (subfield)
Methods: Preprocessing, Machine learning, Connectivity, Statistics
Keywords: EEG methodology, Contiguous-block validation, Temporal model evaluation, Recall-based metrics, Sequential data partitioning
Topic: Functional Brain Connectivity Studies (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Funding: SECIHTI
Citations: not cited yet (Europe PMC); 15 references in the paper

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

License: none: the authors keep all their rights
State: the link answers, verified on 29 September 2026
Evidence: the link answers
Software Heritage: not checked
Found in: the resources table
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Availability: 1 check, the latest on 29 September 2026: the link answers (HTTP 200)
  • 29 September 2026: the link answers (HTTP 200)
At the source: u.pc.cd/vPK

drcrane369/bilstm-contiguous-test

License: none: the authors keep all their rights
State: the link answers, verified on 29 September 2026
Evidence: files inventoried
Commit: a102e4b6b3c2f1ed3740cc7a11bccb9f874fcc31, 11 February 2026
Languages: Python (1)
Size: 8 files, 1 script
Software Heritage: not archived
Found in: the resources table
Holds: README, environment (requirements.txt)
Not found: license file, CITATION.cff, tests, continuous integration, documentation
Tools: Keras (1 file), NumPy (1 file), pandas (1 file), scikit-learn (1 file), SciPy (1 file), TensorFlow (1 file)
Availability: 1 check, the latest on 29 September 2026: the link answers
  • 29 September 2026: the link answers
2 files

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://doi.org/10.1016/j.mex.2026.103928

BibTeX

@article{hernandezdelvalle2026contiguous,
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/j.mex.2026.103928},
url = {https://doi.org/10.1016/j.mex.2026.103928},
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/04/24
VL - 16
SP - 103928
SN - 2215-0161
PB - Elsevier
DO - 10.1016/j.mex.2026.103928
UR - https://doi.org/10.1016/j.mex.2026.103928
LA - en
ER -

CSL-JSON

{
"id": "10.1016/j.mex.2026.103928",
"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": "MethodsX",
"volume": "16",
"page": "103928",
"DOI": "10.1016/j.mex.2026.103928",
"PMID": "42100749",
"PMCID": "PMC13147397",
"ISSN": "2215-0161",
"publisher": "Elsevier",
"URL": "https://doi.org/10.1016/j.mex.2026.103928",
"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 neurology
In 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 Society
In 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 reports
In 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 scenes
Journal: n/a
In 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 advances
In 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 advances
In 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 : JAD
In 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 biomedicine
In 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 online
In 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 data
In 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.

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.