Automated sleep scoring in hibernating and non-hibernating American black bears.
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 · 193 lines · 7.8 KB · GPL-3.0
- #!/usr/bin/env python
- """
- Example script demonstrating how to preprocess a set of datasets and saving out the results.
- TODO:
- - provide different entry point by command line argument parsing using argparse
- - fix plotting (`time` encapsulated at the moment...)
- """
- import numpy as np
- import matplotlib.pyplot as plt
- try:
- # Ideally, we use a multitaper approach to compute LFP/EEG/EMG spectrograms.
- # An implementation is available on github and can be installed using:
- # pip install git+https://github.com/hbldh/lspopt.git#egg=lspopt
- from lspopt import spectrogram_lspopt
- from functools import partial
- get_spectrogram = partial(spectrogram_lspopt, c_parameter=20.)
- except ImportError:
- import warnings
- message = "Falling back to scipy.signal.spectrogram to compute the spectrogram,"
- message += "\nwhich computes the standard Baum-Welch spectrogram."
- message += "\nA multitaper approach may yield better results, "
- message += "\nfor which an implementation is available on github and can be installed with:"
- message += "\npip install git+https://github.com/hbldh/lspopt.git#egg=lspopt"
- warnings.warn(message)
- from scipy.signal import spectrogram as get_spectrogram
- from data_io import (
- ArgumentParser,
- load_dataframe,
- check_dataframe,
- load_raw_signals,
- export_preprocessed_signals,
- )
- from somnotate._utils import (
- robust_normalize,
- )
- def preprocess(raw_signal, sampling_frequency_in_hz,
- time_resolution_in_sec = 1,
- low_cut = 1.,
- high_cut = 90.,
- notch_low_cut = 45.,
- notch_high_cut = 55.,
- ):
- """Wrapper around get_spectrogram, that
- 1) computes the spectrogram for the given LFP/EEG/EMG trace,
- 2) normalizes it such that the power in a given frequency band is
- approximately normally distributed, and
- 3) excludes frequencies that are contaminated by noise using the equivalent
- of a notch filter.
- Arguments:
- ----------
- raw_signal -- (total samples, ) ndarray
- The electrophysiological signal.
- sampling_frequency_in_hz -- float
- The sampling frequency of `raw_signals`.
- time_resolution_in_sec -- int (default 1)
- The time resolution of the output array.
- low_cut, high_cut -- float (default 1.)
- The minimum/maximum frequency for which to compute the power.
- notch_low_cut, notch_high_cut -- float (default 45.)
- The frequency band for which NOT to compute the power
- (to eliminate 50 Hz noise from the output signal).
- Returns:
- --------
- preprocessed_signal -- (total samples / (sampling frequency * time resolution), total frequencies)
- The normalized spectrogram of the given signal.
- """
- # compute spectrogram
- frequencies, time, spectrogram = get_spectrogram(raw_signal,
- fs = sampling_frequency_in_hz,
- nperseg = sampling_frequency_in_hz * time_resolution_in_sec,
- noverlap = 0)
- # exclude ill-determined frequencies
- mask = (frequencies >= low_cut) & (frequencies < high_cut)
- frequencies = frequencies[mask]
- spectrogram = spectrogram[mask]
- # exclude noise-contaminated frequencies around 50 Hz;
- # this improves performance (generally, 0.1-0.5%, but 3% in at least one case)
- mask = (frequencies >= notch_low_cut) & (frequencies <= notch_high_cut)
- frequencies = frequencies[~mask]
- spectrogram = spectrogram[~mask]
- # the power in each frequency band tends to be log-normally distributed, and
- # taking the log hence transforms the distribution of power values to a normal distribution;
- # shift power values by +1 such that values close to zero remain close to zero
- # (and do not become large, negative values after log transformation)
- spectrogram = np.log(spectrogram + 1)
- # normalize the data by de-meaning and rescaling by the standard deviation
- spectrogram = robust_normalize(spectrogram, p=5., axis=1, method='standard score')
- return time, frequencies, spectrogram
- if __name__ == '__main__':
- from configuration import (
- time_resolution,
- state_annotation_signals,
- plot_raw_signals,
- )
- # --------------------------------------------------------------------------------
- # parse and check inputs
- parser = ArgumentParser()
- parser.add_argument("spreadsheet_file_path", help="Use datasets specified in /path/to/spreadsheet.csv")
- parser.add_argument("-s", "--show", action="store_true", help="Plot the output figures of the script.")
- parser.add_argument('--only',
- nargs = '+',
- type = int,
- help = 'Indices corresponding to the rows to use (default: all). Indexing starts at zero.'
- )
- args = parser.parse_args()
- # load spreadsheet / data frame
- datasets = load_dataframe(args.spreadsheet_file_path)
- # check contents of spreadsheet
- check_dataframe(datasets,
- columns = [
- 'file_path_raw_signals',
- 'sampling_frequency_in_hz',
- 'file_path_preprocessed_signals',
- ] + state_annotation_signals,
- column_to_dtype = {
- 'file_path_raw_signals' : str,
- 'sampling_frequency_in_hz' : (int, float),
- 'file_path_preprocessed_signals' : str,
- }
- )
- if args.only:
- datasets = datasets.loc[np.in1d(range(len(datasets)), args.only)]
- # --------------------------------------------------------------------------------
- # preprocess specified files
- for ii, (idx, dataset) in enumerate(datasets.iterrows()):
- print("{} ({}/{})".format(dataset['file_path_raw_signals'], ii+1, len(datasets)))
- # determine edf signals to load
- signal_labels = [dataset[column_name] for column_name in state_annotation_signals]
- # load data
- raw_signals = load_raw_signals(dataset['file_path_raw_signals'], signal_labels)
- preprocessed_signals = []
- for signal in raw_signals.T:
- time, frequencies, preprocessed_signal = preprocess(signal, dataset['sampling_frequency_in_hz'],
- time_resolution_in_sec = time_resolution,
- low_cut = 1.,
- high_cut = 90.,
- notch_low_cut = 45.,
- notch_high_cut = 55.,
- )
- preprocessed_signals.append(preprocessed_signal)
- # show input and outputs (not concatenated) for first dataset for quality control
- if args.show:
- fig, axes = plt.subplots(1+len(preprocessed_signals), 1, sharex=True)
- plot_raw_signals(
- raw_signals,
- sampling_frequency = dataset['sampling_frequency_in_hz'],
- ax = axes[0],
- )
- for signal, ax in zip(preprocessed_signals, axes[1:]):
- ax.imshow(signal, aspect='auto', origin='lower', extent=[time[0], time[-1], frequencies[0], frequencies[-1]])
- ax.set_ylabel('Frequency')
- ax.set_xlabel('Time [seconds]')
- # concatenate spectrograms into one set of features and save out
- preprocessed_signals = np.concatenate([signal.T for signal in preprocessed_signals], axis=1)
- export_preprocessed_signals(dataset['file_path_preprocessed_signals'], preprocessed_signals)
- plt.show()
01_preprocess_signals.py at commit a20f33d, under GPL-3.0 · at the source
Overview
- Institute of Arctic Biology, University of Alaska Fairbanks, Fairbanks, Alaska, United States of America
- Department of Biology, Stanford University, Stanford, California, United States of America
- Radcliffe Department of Medicine, University of Oxford, Oxford, United Kingdom
- Department of Pharmacology, University of Oxford, Oxford, United Kingdom
- Florey Department of Neuroscience and Mental Health, University of Melbourne, Parkville, Victoria, Australia
- Somnivore Pty Ltd, Bacchus Marsh, Victoria, Australia
Abstract
Hibernating bears show remarkable metabolic suppression. Their decline in core body temperature (Tb) is moderate (from 38°C to 30−35°C), but their metabolism declines as much as 75%. To understand the role of sleep in this hypometabolic state, we recorded biotelemetrically EEG, EOG and EMG data over 3500 days from 16 captive American black bears in and out of hibernation under semi-natural conditions. This data set is too large to score manually for Wake, REM- and NREM sleep, so we tested two machine learning classifiers: (1) Somnotate trained on multiple one-day recordings, and (2) Somnivore, trained on a small subset from each recording. As automated scoring methods have not been applied to hibernating species before, a major concern is the effect changing brain temperature has on the EEG and on the machine learning based detection. Therefore, we selected reference data using consensus by 3 manual sleep scorers from each of 6 bears, two one-day recordings at the highest and lowest body temperatures during hibernation when Tb was oscillating in multiday cycles, and a non-hibernating one-day recording in summer. Somnotate results were excellent when trained separately for hibernating and non-hibernating data. Training Somnotate separately for high and low Tb within hibernation did not improve results further. Sleep times in hibernation were about 2x that in summer for both automated scores and manual scores (p < 0.0001). There were no significant differences in occupancy of vigilance states between automated and manual scores in hibernation (p > 0.05), but a small overestimate of sleep time in summer (p < 0.05). Both applications yielded F-measures against manual scores in the 0.90–0.98 range. Outliers in the 0.67–0.88 range were correlated between the two applications, indicating that specific files are more challenging to annotate. We conclude that both applications have accuracies approaching that of manual scorers when trained on high quality data.
Reproduced under the paper's license (CC BY), from the paper cited above.
Repositories
Its files are read in the Code ↔ Paper reader above.
paulbrodersen/somnotate
a20f33de62511d8c172e333896608b7fc166d0f0, 5 January 2026Availability: 1 check, the latest on 27 September 2026: the link answers
- 27 September 2026: the link answers
22 files
- example_pipeline/
01_preprocess_signals.py — Python, 193 lines - example_pipeline/
02_test_state_annotation — Python, 176 lines.py - example_pipeline/
03_train_state_annotatio — Python, 67 linesn.py - example_pipeline/
04_run_state_annotation. — Python, 150 linespy - example_pipeline/
05_manual_refinement.py — Python, 177 lines - example_pipeline/
06_compare_state_annotat — Python, 185 linesions.py - example_pipeline/
07_compute_state_probabi — Python, 106 lineslities.py - example_pipeline/
07_run_missing_value_ann — Python, 181 linesotation.py - example_pipeline/
__init__.py — Python, 1 line - example_pipeline/
configuration.py — Python, 232 lines - example_pipeline/
data_io.py — Python, 362 lines - extensions/
__init__.py — Python, 1 line - extensions/
convert_hypnogram_to_mat — Python, 69 lineslab_struct.py - extensions/
convert_sleepsign_files. — Python, 140 linespy - extensions/
truncate_datasets.py — Python, 101 lines - somnotate/
__init__.py — Python, 25 lines - somnotate/
_automated_state_annotat — Python, 375 linesion.py - somnotate/
_manual_state_annotation — Python, 1,046 lines.py - somnotate/
_plotting.py — Python, 168 lines - somnotate/
_utils.py — Python, 299 lines - LICENSE — License, 674 lines
- README.md — Text, 565 lines
otoien/ConsensusCode
eaee8b368256b795c81fd9251fc4d7ca88ff08e2, 6 August 2025Availability: 1 check, the latest on 27 September 2026: the link answers
- 27 September 2026: the link answers
1 file
- LICENSE — License, 121 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;
- 20 scripts, 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.
Data Availability
The data underlying the results presented in the study are available from the National Sleep Research Resource (https://
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 3, 28 September 2026
- Authors: added Yi-Ge Huang (0000-0002-1034-1517); Paul J N Brodersen (0000-0001-5216-7863); Giancarlo Allocca (0000-0003-2237-6722); removed Yi-Ge Huang; Paul J N Brodersen; Giancarlo Allocca
Version 1, 27 September 2026: the first record
Recorded: type, language, journal, volume, issue, pages, dates, 7 authors, 10 MeSH terms, 1 funder, 23 references.
Cite
This paper
Tøien, Ø., Pittaras, E. C., Huang, Y.-G., Brodersen, P. J. N., Allocca, G., Barnes, B. M., & Heller, H. C. (2026). Automated sleep scoring in hibernating and non-hibernating American black bears. PloS one, 21(8), e0352640. https://
BibTeX
@article{tien2026automat
author = {Tøien, Øivind and Pittaras, Elsa Cecile and Huang, Yi-Ge and Brodersen, Paul J N and Allocca, Giancarlo and Barnes, Brian M and Heller, H Craig},
title = {{Automated sleep scoring in hibernating and non-hibernating American black bears}},
journal = {PloS one},
year = {2026},
month = aug,
volume = {21},
number = {8},
pages = {e0352640},
publisher = {PLOS},
issn = {1932-6203},
doi = {10.1371/
url = {https://
pmid = {42555601},
pmcid = {PMC13440796}
}
RIS
TY - JOUR
AU - Tøien, Øivind
AU - Pittaras, Elsa Cecile
AU - Huang, Yi-Ge
AU - Brodersen, Paul J N
AU - Allocca, Giancarlo
AU - Barnes, Brian M
AU - Heller, H Craig
TI - Automated sleep scoring in hibernating and non-hibernating American black bears
T2 - PloS one
J2 - PLoS One
PY - 2026
DA - 2026/
VL - 21
IS - 8
SP - e0352640
SN - 1932-6203
PB - PLOS
DO - 10.1371/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.1371/
"type": "article-journal",
"title": "Automated sleep scoring in hibernating and non-hibernating American black bears",
"container-title": "PloS one",
"author": [
{
"family": "Tøien",
"given": "Øivind"
},
{
"family": "Pittaras",
"given": "Elsa Cecile"
},
{
"family": "Huang",
"given": "Yi-Ge"
},
{
"family": "Brodersen",
"given": "Paul J N"
},
{
"family": "Allocca",
"given": "Giancarlo"
},
{
"family": "Barnes",
"given": "Brian M"
},
{
"family": "Heller",
"given": "H Craig"
}
],
"container-title-short":
"volume": "21",
"issue": "8",
"page": "e0352640",
"DOI": "10.1371/
"PMID": "42555601",
"PMCID": "PMC13440796",
"ISSN": "1932-6203",
"publisher": "PLOS",
"URL": "https://
"language": "en",
"issued": {
"date-parts": [
[
2026,
8,
5
]
]
}
}
The tracing map gets a citation of its own once an author has validated it and it has a DOI.
Similar papers
The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.
- [1] doi:10.1038/s41746-026-02946-2 [code]
- Fully-automated sleep staging for Parkinson's disease and isolated REM sleep behavior disorder.Journal: NPJ digital medicineIn common: scikit-learn, pandas, SciPy, 2 other tools, 1 reference
- [2] doi:10.3389/fnins.2026.1874302 [code]
- Architecture-data matching for EEG-EMG decoding: compact deep models match classical spectral decoders on the WAY-EEG-GAL grasp-and-lift dataset.Journal: Frontiers in neuroscienceIn common: scikit-learn, pandas, SciPy, 2 other tools, other, EEG
- [3] doi:10.3390/bioengineering13070820 [code]
- Benchmarking Multimodal Workload Classification: Effects of Modality, Validation Protocol, and Segmentation Contrast on an Open Graded-Arithmetic Dataset.Journal: Bioengineering (Basel, Switzerland)In common: scikit-learn, pandas, SciPy, 2 other tools, other, EEG
- [4] doi:10.1093/braincomms/fcag218 [code]
- Magnetoencephalography biomarkers for assessing myelin content and neuronal function in acute optic neuritis.Journal: Brain communicationsIn common: scikit-learn, pandas, SciPy, 2 other tools, other, EEG
- [5] 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: scikit-learn, pandas, SciPy, 2 other tools, other, EEG
- [6] doi:10.1007/s12021-026-09817-x [code]
- Circle of Willis-Guided Localization for Simultaneous Detection and Classification of Large Vessel Occlusions in Brain CTA.Journal: NeuroinformaticsIn common: scikit-learn, pandas, SciPy, 2 other tools, other
- [7] doi:10.1111/psyp.70397 [code]
- Cortical Contributions to Attentional Orienting and Response Cancellation in Action Stopping.Journal: PsychophysiologyIn common: scikit-learn, pandas, SciPy, 2 other tools, other
- [8] 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: scikit-learn, pandas, SciPy, 2 other tools, other - [9] doi:10.3390/bioengineering13080924 [code]
- Deep Learning-Based Temporal Gait Analysis Using a Smartphone IMU in Older Adults with and Without Non-Specific Low Back Pain.Journal: Bioengineering (Basel, Switzerland)In common: scikit-learn, pandas, SciPy, 2 other tools, other
- [10] doi:10.1371/journal.pcbi.1014555 [code]
- Body surface potential driven personalisation of electrophysiological digital twins in hypertrophic cardiomyopathy.Journal: PLoS computational biologyIn common: scikit-learn, pandas, SciPy, 2 other tools, other
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, 20 scripts, 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:59d0fa5a101b252a…
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.
