An automated EEG-ECG framework for CAP-HRV analysis: enabling brain-heart coupling studies in sleep disorders.

Save

Background

Multimodal sleep analysis typically requires separate processing pipelines for electroencephalography (EEG) and electrocardiography (ECG), which complicates joint investigation of sleep microstructure and autonomic regulation. Cyclic alternating pattern (CAP) scoring and heart rate variability (HRV) analysis are routinely performed in different software environments, limiting temporal alignment, reproducibility, and scalability.

Methods

We present an open-source MATLAB framework that integrates rule-based CAP A1 detection and HRV feature extraction within a single, time-synchronized workflow. The pipeline performs standardized EEG and ECG preprocessing, rule-based CAP A1 detection during slow-wave sleep (SWS) implementing the Terzano scoring criteria, R-peak detection via the Pan–Tompkins algorithm, and computation of time-domain, frequency-domain, and nonlinear HRV features by calling the open-source PhysioZoo/mhrv toolbox directly. CAP annotations are aligned with 5-minute ECG epochs through the shared polysomnography (PSG) time base.

The complete code is released as an open-source repository to support reuse and extension.

Results

Because HRV features are computed by calling the PhysioZoo/mhrv toolbox directly, the pipeline introduces no reimplemented HRV routine and inherits that toolbox’s validated feature definitions. CAP A1 detection is provided as a rule-based implementation of published criteria and has not yet been benchmarked against expert manual scoring. A worked example on the OSAD+ subgroup (n = 18) demonstrates pipeline output across CAP and non-CAP epochs, and a healthy-sleep A1-event HRV reference is reported from the public CAP Sleep Database (15 controls, 785 A1 epochs) as a descriptive cross-database reference.

Conclusion

The framework provides a reproducible, rule-based, and modular tool for integrated EEG–ECG analysis of sleep microstructure and autonomic dynamics. By enabling synchronized CAP–HRV feature extraction in a single environment, it lowers the engineering barrier to brain–heart coupling research during sleep and provides a foundation for future extensions, including validated CAP detection, a matched-control study, a Python port, and cloud-based deployment.

Introduction

Sleep is a neuro-cardiorespiratory process in which the cerebral and autonomic systems work together to preserve homeostatic equilibrium. The cyclic alternating pattern (CAP) is a well-established EEG marker of cortical arousal and NREM sleep instability that reflects oscillations between activation (A-phases) and deactivation (B-phases) throughout the night (Terzano et al., 2001). Heart rate variability (HRV) provides a non-invasive index of autonomic tone and sympathetic–parasympathetic balance (Shaffer and Ginsberg, 2017).

Converging evidence shows that moment-to-moment HRV fluctuations closely mirror EEG micro-arousals, indicating a physiological link between cortical and autonomic activity during sleep (Ferri et al., 2000; Ferini-Strambi et al., 2000). Together, CAP and HRV provide complementary insight into sleep architecture, autonomic responsiveness, and the mechanisms of arousal regulation.

Brain–heart coupling is particularly disrupted in conditions such as obstructive sleep apnea (OSA) and major depressive disorder (MDD). OSA is characterized by recurring respiratory obstructions that provoke EEG micro-arousals, sympathetic surges, and cardiovascular stress (Somers et al., 2008; Narkiewicz and Somers, 2003). CAP rates are elevated in OSA, reflecting the cortical instability driven by respiratory effort and recurrent arousals (Parrino et al., 2012).

MDD is associated with poor sleep continuity, reduced slow-wave activity, and autonomic imbalance, frequently manifesting as reduced HRV and increased sympathetic tone (Benca et al., 1992; Kemp et al., 2010; Koch et al., 2019). When OSA and MDD co-occur, the combination of fragmented sleep architecture and dysregulated autonomic control may amplify physiological instability (Shukir et al., 2026).

Despite the complementary nature of EEG- and ECG-derived markers, current analytical workflows rarely integrate CAP scoring with HRV quantification in a unified environment. Manual CAP scoring remains standard but is labor-intensive, susceptible to inter-scorer variability, and difficult to scale (Rosenberg and Van Hout, 2013; Parrino et al., 2012; Mendonça et al., 2023). HRV is typically computed in separate software with independent preprocessing and manual artifact correction, complicating temporal synchronization with EEG annotations (Laborde et al., 2017).

No standardized, automated pipeline currently aligns EEG-defined micro-events—specifically CAP A-phases—with beat-to-beat autonomic fluctuations (Rosenberg and Van Hout, 2013).

Recent advances in computational sleep medicine reflect a broader shift toward automated, reproducible, and scalable physiological signal processing. Deep-learning-based sleep staging and multimodal feature extraction have demonstrated that previously manual tasks can be reliably automated (Stephansen et al., 2018), reinforcing the value of open-source pipelines that standardize preprocessing and feature extraction across laboratories (Vest et al., 2018; Behar et al., 2018). Integrating EEG-derived CAP dynamics with ECG-based HRV represents a step toward precision sleep medicine, in which multimodal physiological markers enable personalized mechanistic interpretation (Topol, 2019).

Given these gaps, the present work introduces an open-source, rule-based software framework for studying brain–heart interactions during sleep. This is a Technology and Code contribution: the primary deliverable is a documented, reusable pipeline rather than a clinical study. The specific aims are: (i) to implement a modular EEG–ECG pipeline that extracts CAP dynamics and HRV features in a single, synchronized environment; (ii) to specify the synchronization logic that aligns CAP A1-phase annotations with 5-minute ECG epochs; (iii) to compute HRV features by calling the PhysioZoo/mhrv toolbox directly, so that the extracted features inherit the validated definitions of that toolbox; and (iv) to demonstrate pipeline output through a worked example on an OSA-with-comorbid-depression (OSAD+) subgroup.

No clinical or statistical inference is drawn from the demonstration data.

Materials and methods

System architecture and software implementation

The framework is a modular, open-source system that combines EEG-based CAP detection and ECG-derived HRV computation in a single reproducible procedure. The architecture comprises five sequential modules: (i) data ingestion, (ii) signal preprocessing, (iii) CAP event detection, (iv) HRV feature extraction, and (v) multimodal synchronization and output. Figure 1 provides a schematic overview.

The pipeline is implemented entirely in MATLAB (R2023b; MathWorks, Natick, MA, USA). All custom scripts—covering signal preprocessing, CAP–ECG synchronization, and HRV feature extraction—are organized as independent, callable modules so that individual stages can be reused or replaced. The repository contains: (i) EEG and ECG preprocessing scripts; (ii) the CAP A1 detection module implementing the Terzano criteria (Terzano et al., 2002); (iii) the CAP–ECG synchronization module; (iv) HRV feature-extraction scripts that call the PhysioZoo/mhrv toolbox (Behar et al., 2018) directly; and (v) a worked-example script that runs the full pipeline on a representative subject.

The HRV routines call the PhysioZoo/mhrv toolbox directly on the extracted R-R series, so the reported HRV values are those produced by mhrv itself. Dependencies and run instructions are documented in the repository README. The code is available at https://github.com/ahsankhandoker/CAP-HRV under a CC-BY 4.0 license, with a versioned archive deposited on Zenodo (DOI assigned on acceptance).

Dataset and participants

Data were obtained from the American Center for Psychiatry and Neurology (ACPN), Abu Dhabi, UAE, under Institutional Review Board approval (IRB #0019, 2017). All participants provided written informed consent. Participants were adult UAE nationals (age > 18 years) with a confirmed OSA diagnosis; patients with known cardiovascular disease were excluded.

Participant characteristics are summarized in Table 1.

Two patient groups were studied. The OSA-only group (n = 26; 17 male, 8 female, 1 sex not recorded; mean age 47.6 ± 13.7 years; BMI 36.9 ± 12.1 kg/m2) comprised patients with confirmed OSA and no comorbid depressive disorder. The OSAD+ group (n = 18; 11 male, 7 female; mean age 42.9 ± 10.3 years; BMI 31.3 ± 6.3 kg/m2) comprised patients with OSA and clinically assessed depressive symptoms.

Depressive symptom severity was assessed by a consultant psychiatrist using the Patient Health Questionnaire-9 (PHQ-9), a nine-item self-report instrument with total scores from 0 to 27. Published cutoffs define five severity bands: none–minimal (0–4), mild (5–9), moderate (10–14), moderately severe (15–19), and severe (20–27) (Kroenke et al., 2001). Patients scoring ≥ 10 were classified as having clinically significant depressive symptoms (PHQ-9 ≥ 10), a screening-level threshold that does not constitute a structured-interview diagnosis of MDD; this distinction is retained throughout.

Patients within each group were matched by age, sex, and OSA severity.

A ten-channel PSG system (Miniscreen Plus™) was used. EEG was acquired at 100 Hz using the international 10–20 system (derivations C3-A2, C4-A1, F3-A2, F4-A1, O1-A2, O2-A1). ECG was recorded from a single Lead II configuration at 200 Hz.

EOG, submental EMG, a nasal pressure transducer, thoracic/abdominal inductance belts, and pulse oximetry were also recorded. Sleep stages and respiratory events were scored according to AASM guidelines by the recording center.

EEG preprocessing

The C4-A1 EEG channel was selected for CAP detection, as this central derivation provides reliable detection of the high-amplitude delta-burst morphology characteristic of CAP A1 events. A 50 Hz notch filter was applied to the EEG signal to remove power-line interference, followed by a fourth-order Butterworth bandpass filter (0.5–30 Hz) spanning the delta, theta, alpha, and beta bands. A subsequent delta-band filter (0.5–4 Hz) was applied to the C4-A1 signal to isolate SWS-associated activity.

Both EEG and ECG signals were standardized and segmented into consecutive, non-overlapping 5-minute epochs. Although conventional EEG scoring uses 30-second epochs, the 5-minute window was selected to provide a sufficient number of R-R intervals for stable frequency-domain and nonlinear HRV estimation, consistent with established short-term HRV recommendations (Task Force of the European Society of Cardiology and the North American Society of Pacing and Electrophysiology, 1996; Sandercock et al., 2005). The ECG signal (200 Hz) was downsampled to 100 Hz to share a common time base with the EEG for synchronization (Section 2.6); HRV features themselves were computed from R-peak timings derived at the native ECG resolution (Section 2.5).

CAP A1 detection (rule-based implementation)

CAP A1 events were detected using a rule-based implementation of the scoring criteria described by Terzano et al. (2002). We emphasize at the outset that this module is a deterministic implementation of published rules, not a CAP detector validated against expert manual scoring; no manually scored CAP labels were available in the present dataset, so detection performance (sensitivity, specificity, F1, Cohen’s κ) is not reported here.

A validation protocol against an expert-annotated public resource is described in Section 4 as the immediate next step.

Within each 5-minute epoch, candidate CAP A1 events—high-amplitude delta bursts during SWS—were identified using the following explicit parameters, in accordance with Terzano et al. (2002): (i) minimum A-phase duration 1 s; (ii) maximum A-phase duration 60 s; (iii) amplitude criterion—the peak delta-band envelope within the candidate event must exceed the mean background delta-band amplitude of the surrounding epoch by a factor of at least 1.33 (i.e., ≥ 1/3 above background); and (iv) the candidate event must fall within a polysomnographically confirmed Stage III (slow-wave) sleep epoch. The background amplitude reference was the mean absolute value of the delta-filtered C4-A1 signal over the full 5-minute epoch, excluding the candidate-event window.

The current implementation detects CAP A1 subtypes during SWS only; CAP A2/A3 subtypes and CAP occurring during Stage 2 NREM—both clinically relevant, particularly in OSA, where A3 events predominate—are outside the present scope and are noted as planned extensions (Section 4).

ECG preprocessing and HRV feature extraction

ECG epochs corresponding to CAP and non-CAP periods were processed separately. R-peaks were detected with the Pan–Tompkins algorithm (Pan and Tompkins, 1985). A multi-step fallback strategy handled epochs with poor peak detection: if fewer than five R-peaks were detected, the detector was re-applied at a reduced effective sampling rate, then after discarding the first 500 samples of the epoch, and finally on an amplitude-clipped version of the signal.

Epochs yielding fewer than five R-peaks after all fallback steps were discarded. R-R intervals were computed as the time difference between consecutive R-peaks. Ectopic and artifactual intervals were screened at the epoch level: epochs with a mean heart rate below 50 bpm or an SDNN above 300 ms were excluded as physiologically implausible, consistent with standard short-term HRV quality control (Task Force of the European Society of Cardiology and the North American Society of Pacing and Electrophysiology, 1996; Laborde et al., 2017).

No interpolation or resampling of the R-R series was applied prior to nonlinear analysis. The number and proportion of retained versus excluded epochs are reported in Section 3.1, with the per-group breakdown of excluded epochs to allow assessment of selection bias.

HRV features were computed by calling the PhysioZoo/mhrv toolbox directly. The extracted features (defined in Table 2) comprise mean heart rate (HR); time-domain indices (AVNN, SDNN, RMSSD, pNN50, SEM); frequency-domain indices computed via Lomb–Scargle spectral analysis (VLF, LF, HF, total power, nVLF, nLF, nHF, LF/HF, LF peak, HF peak); nonlinear indices (SD1, SD2, DFA α1, DFA α2, SampEn); and the spectral slope β — 22 features in total.

CAP–ECG synchronization

EEG-derived CAP annotations and ECG-derived HRV features were integrated at the epoch level through the shared PSG time base. The procedure is as follows. First, NREM intervals identified from the hypnogram were divided into consecutive 5-minute epochs.

Sleep staging is performed on standard 30-second PSG epochs; a 5-minute analysis epoch therefore spans ten consecutive 30-second staged epochs. A 5-minute epoch was admitted to CAP–HRV analysis only if it lay within a contiguous NREM segment, and the Stage III requirement of the CAP A1 rule (Section 2.4) was evaluated against the underlying 30-second staging: a candidate A1 event was accepted only when its supporting 30-second epoch was scored Stage III. Thus the 5-minute window defines the HRV analysis length, while the 30-second staging governs CAP eligibility; the two are not conflated.

Second, for each admitted epoch, the CAP A1 detector (Section 2.4) determined whether at least one qualifying A1 event was present. The epoch was labeled CAP (1) if it contained one or more A1 events and non-CAP (0) otherwise; epochs containing a mixture of CAP and non-CAP intervals were labeled CAP on the presence of any qualifying A1 event. Third, the corresponding 5-minute ECG segment was extracted using the shared timestamp, and HRV features were computed from it (Section 2.5), producing one feature vector per epoch.

The final output is a synchronized table in which each row is one 5-minute epoch with a full HRV feature vector and a CAP label.

This design has an important and explicit consequence for interpretation. A CAP A1 event lasts 1–60 s, whereas the analysis epoch is 300 s; a single qualifying event therefore occupies at most 20% and frequently far less of the labeled epoch. The measured HRV consequently reflects the entire epoch—both arousal-associated and inter-arousal intervals—rather than the instantaneous autonomic response to an individual A-phase.

Because the present dataset stored CAP information at the epoch and patient level rather than as event-level onset/offset timings, the exact fraction of each epoch occupied by A1 activity could not be recomputed here; it is therefore reported descriptively at the patient level as the CAP rate (Table 1) and is flagged as a quantity to be measured directly in the validation work described in Section 4. The released synchronization module exposes the event-level timing hooks required for an event-locked analysis at finer temporal resolution, which we identify as the appropriate route for isolating event-related autonomic effects. Figure 2 depicts the temporal mapping of CAP events to ECG epochs.

Reproducibility

The pipeline contains no stochastic components: the bandpass and notch filters are linear time-invariant operations, the Pan–Tompkins detector is threshold-based and deterministic, the Lomb–Scargle estimator operates on fixed-length R-R arrays without random initialization, and the nonlinear routines (DFA, SampEn, Poincaré) are deterministically defined. The pipeline is therefore deterministic by construction and returns identical outputs for identical inputs within a fixed software environment; we report this as a design property rather than as an empirical result, since re-running deterministic code on fixed hardware is expected to reproduce its outputs. A more informative robustness check—quantifying output variation across operating systems and MATLAB versions—is identified as future work in Section 4.

Control reference cohort and A1-event HRV

To provide a healthy-sleep HRV reference for CAP A1 events, we additionally analyzed the publicly available CAP Sleep Database (capslpdb) (Goldberger et al., 2000; Terzano et al., 2001), a collection of expert-scored polysomnographic recordings from the Sleep Disorders Center of the Ospedale Maggiore of Parma, Italy. The database provides 16 healthy controls (records n1–n16); one recording (n16) contains EEG only and lacks an ECG channel and was therefore excluded, leaving 15 controls with ECG. For each control, the 5-minute ECG epochs coinciding with expert-annotated CAP A1 events during NREM sleep were extracted (810 A1 epochs in total) and processed with the same HRV pipeline used for the patient data (Sections 2.4–2.5): R-peaks were detected with the Pan–Tompkins algorithm, epochs failing the quality criteria of Section 2.5 were discarded, the full HRV feature set was computed per epoch, and per-epoch values were averaged within each subject.

This cohort is used strictly as a descriptive, cross-database HRV reference; because it differs from the patient recordings in database, site, acquisition system, and population, no statistical comparison between controls and patients is performed (Section 4).

Results

Pipeline performance and epoch retention

The integrated framework automated all processing steps—CAP detection, R-peak extraction, HRV computation, and feature assembly—end to end. On the test workstation (Windows 10 x64, Intel Core i7, 16 GB RAM), runtime profiling yielded a mean processing time of approximately 12 s per epoch, corresponding to 8–10 min per subject for a full overnight recording. For reference, manual CAP scoring combined with separate HRV extraction typically requires 20–30 min per subject (Berntson et al., 2005; Parrino et al., 2012; Hartmann and Baumert, 2019; Vest et al., 2018).

Epoch retention after quality filtering varied across subjects. On average, 50.5% of NREM epochs passed the quality thresholds (heart rate ≥ 50 bpm and SDNN ≤ 300 ms), corresponding to a mean of 29.1 ± 21.7 retained epochs per subject across the OSA and OSAD+ groups combined; 43 of 44 subjects yielded at least one valid epoch. Because this exclusion rate is substantial, we examined whether retention was systematically related to signal quality.

Excluded epochs were dominated by low R-peak yield and high-SDNN artifact (noise-contaminated segments) rather than by physiological bradycardia: the 50 bpm threshold targets noise rather than sleep bradycardia, which was not observed as a systematic feature of this dataset. We note as a limitation (Section 4) that a fuller characterization of retained versus excluded epochs by sleep-stage distribution and time-of-night would further constrain potential selection bias; the released pipeline logs the per-epoch exclusion reason to support this in future analyses.

Worked example: running the pipeline end to end

To illustrate typical use, the repository includes a worked-example script that ingests a single subject’s EEG and ECG, runs preprocessing, CAP A1 detection, R-peak detection, HRV extraction, and synchronization, and writes the synchronized feature table. On a representative OSAD+ subject the script produced a labeled table of 5-minute epochs, each carrying the full HRV feature vector and its CAP label, with the per-epoch exclusion log written alongside. This example serves as the entry point for new users and as a template for batch processing across a cohort.

Practical limitations of the example—single-channel CAP detection, offline (non-real-time) operation, and MATLAB licensing—are discussed in Section 4.

Reproducibility

Consistent with the deterministic design described in Section 2.7, repeated executions of the complete pipeline on identical input data under a fixed software environment produced numerically identical HRV feature vectors at floating-point precision. We report this as confirmation of deterministic behavior rather than as evidence of cross-environment robustness; quantifying variation across operating systems and MATLAB versions remains future work (Section 4).

Descriptive case study: OSAD+ subgroup

To illustrate pipeline output on real physiological data, the framework was applied to the OSAD+ subgroup (n = 18). This analysis is strictly a technical demonstration of output structure; no statistical or clinical inference is drawn from it. Descriptive summaries of extracted HRV features for CAP and non-CAP epochs are presented in Table 3.

The pipeline produced complete, well-structured feature vectors for every retained epoch, with values falling in physiologically plausible ranges. We deliberately refrain from interpreting CAP-versus-non-CAP differences in this subgroup as physiological findings, because (i) no inferential test is applied and (ii) the epoch-level labeling described in Section 2.6 means any such difference reflects epoch context rather than event-locked autonomic response.

Control A1-event HRV (reference cohort)

Applying the pipeline to the 15 capslpdb control subjects, 785 of 810 A1 epochs (96.9%) passed quality control—substantially higher retention than in the patient recordings (Section 3.1), consistent with the cleaner signals of healthy volunteers. The resulting A1-event HRV is summarized in Table 4. The values are physiologically consistent with a young, healthy cohort (ages 23–42 years): mean heart rate 65.2 ± 6.8 bpm, AVNN 933.8 ± 102.0 ms, and comparatively high vagally mediated variability (RMSSD 82.8 ± 35.6 ms; pNN50 95.4 ± 3.6%, computed with the same threshold convention as the patient pipeline), with sympathovagal balance below unity (LF/HF 0.79 ± 0.21) and fractal and entropy indices in the expected ranges (DFA α1 0.81 ± 0.10; SampEn 1.68 ± 0.21).

Internal consistency checks confirmed that SD1 reproduced RMSSD/√2 to within 0.5% and that nLF + nHF summed to 100% in every subject. In this cohort the 50 bpm exclusion rarely bound: retained epochs had a median heart rate of 65 bpm (5th–95th percentile 52–77 bpm), only 10.6% fell below 55 bpm, and none of the 25 excluded epochs were excluded for physiological bradycardia (exclusions were dominated by low R-peak yield), supporting the cutoff as a noise rather than a bradycardia filter. These values are provided as a healthy-sleep A1-event HRV reference only; because they derive from a different database, site, and acquisition system than the patient recordings, they are not compared statistically with the OSA or OSAD+ groups (Section 4).

Discussion

This paper presents a rule-based, modular, and deterministic MATLAB framework for integrated EEG–ECG analysis of sleep microstructure and autonomic dynamics. The pipeline automates EEG and ECG preprocessing, implements Terzano-criterion CAP A1 detection during SWS, synchronizes CAP annotations with 5-minute ECG epochs through a shared PSG time base, and extracts a comprehensive HRV feature set spanning time, frequency, and nonlinear domains. Its contribution is engineering and methodological: it lowers the barrier to synchronized CAP–HRV feature extraction, which previously required two separate software environments and manual temporal alignment.

A distinction must be drawn between the two analytic components. HRV features are produced by the PhysioZoo/mhrv toolbox invoked directly, so they inherit that toolbox’s validated definitions and are not reimplemented or re-benchmarked here. The CAP detection module, by contrast, is a rule-based implementation of published criteria and has not been benchmarked against expert manual scoring; no manually scored CAP labels were available in this dataset.

Accordingly, we do not describe the CAP component as validated. The immediate next step—and the most important one for this pipeline—is to benchmark CAP A1 detection against an expert-annotated public resource such as the CAP Sleep Database on PhysioNet, reporting sensitivity, specificity, F1, and Cohen’s κ against the manual scores; the released code is structured to accept that database’s annotations directly, and a validation protocol accompanies the repository.

A key methodological point concerns the CAP-to-ECG epoch mapping. CAP A1 events last 1–60 s, yet stable HRV estimation requires windows of at least several minutes. Labeling a 5-minute epoch as CAP whenever it contains any A1 event means the measured HRV reflects the whole epoch, and brief events are diluted within it; a single event can occupy as little as a fraction of one percent of the window.

The CAP-versus-non-CAP HRV contrasts reported here—and many comparable contrasts in the literature (Ferri et al., 2000; Ferini-Strambi et al., 2000; Somers et al., 1993)—therefore characterize epoch-level autonomic context, not the instantaneous response to individual arousals. Researchers requiring event-locked HRV (e.g., in the seconds surrounding each A-phase) should use the event-level timing hooks exposed by the synchronization module; quantifying per-epoch A1 occupancy and testing whether autonomic differences scale with within-epoch CAP density are the natural first analyses on that path. The closest methodological precedent for such event-locked CAP–HRV analysis is the work of Ferri and colleagues (Ferri et al., 2000; Ferini-Strambi et al., 2000), who characterized autonomic activation during CAP A-phases at fine temporal resolution; the planned event-locked mode would extend that approach within the present integrated, open-source pipeline.

Several limitations constrain the current implementation. First, CAP detection was not benchmarked against expert scorers, and detects only A1 subtypes during SWS; A2/A3 subtypes and Stage 2 CAP are not yet implemented. Second, the control reference cohort (Sections 2.8 and 3.5) is a descriptive cross-database reference, not a matched control arm: it derives from a different database (capslpdb; Parma, Italy), site, and acquisition system, and a younger, healthy population (ages 23–42 years), and lacks patient-matched demographic and PSG data.

Any control-versus-patient contrast would therefore confound group status with database, site, equipment, and age; for this reason no between-group statistical comparison is performed, and a matched, single-site control arm remains necessary before any control-referenced claim can be made. Third, the MATLAB dependency limits accessibility for researchers without a license. Fourth, all patients are from a single UAE institution, limiting generalizability.

Fifth, the pipeline is offline only and has not been evaluated for real-time use. Sixth, the 50 bpm heart-rate exclusion, while consistent with HRV quality-control conventions, may occasionally exclude valid bradycardic epochs in specific populations, though this was not observed here. Seventh, the PHQ-9 ≥ 10 criterion is a screening-level threshold, not a structured-interview diagnosis of MDD.

Two points follow for interpretation. First, the principal contribution of this work is the open-source CAP–HRV pipeline, demonstrated on the OSA and OSAD+ recordings; the control-group analysis is provided only as an exploratory HRV reference, and the conclusions of the manuscript do not rely on it. Second, the control sample was available primarily as an HRV reference cohort and was not fully phenotyped with the same demographic and polysomnographic detail as the OSA cohort; consequently, comparisons involving controls should be interpreted as exploratory and hypothesis-generating rather than as baseline-matched group comparisons.

The framework is designed for scalability. Its modular structure allows individual stages to be parallelized or replaced; the per-epoch processing model maps naturally onto batch execution across large sleep databases; and the deterministic design makes distributed runs auditable. Planned developments include: benchmarking CAP detection against the PhysioNet CAP Sleep Database with standard performance metrics; extending detection to CAP A2/A3 and Stage 2 NREM; porting the pipeline to Python to remove the licensing barrier and enable cloud deployment; adding an event-locked synchronization mode; and evaluating robustness across operating systems and MATLAB versions.

Compared with existing tools—Kubios (proprietary; HRV only), PhysioZoo (open-source; HRV only) (Behar et al., 2018; Vest et al., 2018), and manual CAP scoring tools (labor-intensive; variable) (Rosenberg and Van Hout, 2013; Parrino et al., 2012; Mendonça et al., 2023)—the present framework fills the specific niche of synchronized, automated, open-source CAP–HRV feature extraction in a single environment, while being explicit about what it does and does not yet validate. Additional autonomic context for CAP and arousal-related HRV changes is provided by prior physiological studies (Somers et al., 1993; Narkiewicz et al., 1998; Licht et al., 2008; Kemp et al., 2010; Narkiewicz and Somers, 2003).

Conclusion

We present an open-source EEG–ECG framework for extracting integrated CAP and HRV features from overnight polysomnography within a single, time-synchronized environment. The pipeline implements rule-based CAP A1 detection during SWS using Terzano criteria, synchronizes annotations with 5-minute ECG epochs through a shared PSG time base, and extracts a comprehensive HRV feature set by calling the PhysioZoo/mhrv toolbox directly. The pipeline is deterministic by construction.

A worked example and a descriptive OSAD+ case study demonstrate output structure across CAP and non-CAP epochs. The CAP component is provided as a rule-based implementation pending validation against expert scoring, which we identify as the principal next step. The framework provides an accessible, modular foundation for multimodal sleep research on brain–heart interactions and for future extensions including validated CAP detection, a Python port, and cloud-based deployment.

Related articles

PubMed

Echocardiography-led multimodal assessment for pulmonary hypertension in a right heart catheterization-referred cohort: incremental value of ECG and natriuretic peptides.

Background Right heart catheterization (RHC) is the reference standard for diagnosing pulmonary hypertension (PH), whereas echocardiography is the primary noninvasive tool for identifying patients who require further evaluation. Whether electrocardiography (ECG) and natriuretic peptides provide incremental diagnostic information beyond echocardiographic assessment in patients referred for RHC remains uncertain. Methods This single-center retrospective study included 130 hospitalized patients...

PLOS

Correction: Diagnostic accuracy of digital technologies compared with 12-lead ECG in the diagnosis of atrial fibrillation in adults: A protocol for a systematic review

The fourth author’s initials appear incorrectly in the citation. The correct citation is: Sheron VA, Surenthirakumaran R, Gooden TE, Lip GYH, Thomas GN, J. Moore D, et al. (2024) Diagnostic accuracy of digital technologies compared with 12-lead ECG in the diagnosis of atrial fibrillation in adults: A protocol for a systematic review. PLoS ONE 19(5): e0301729. https://doi.org/10.1371/journal.pone.0301729 .