API reference

For calling the pipeline from your own Python code rather than the command line. Generated from the docstrings in the source.

Configuration

Configuration for the EDF preprocessing pipeline.

All tunable settings live in a single config.yaml at the project root, so running the pipeline never requires editing Python source. Every setting has a sensible default, which means config.yaml is optional - delete it and the pipeline still runs with the published defaults below.

Precedence, lowest to highest:

dataclass defaults -> config.yaml -> command-line flags

exception cardiacprep.config.ConfigError[source]

Bases: Exception

Raised when configuration is missing, malformed, or self-inconsistent.

Messages are written for someone who has never read the source, since a bad config file is the most likely thing to go wrong for a new user.

class cardiacprep.config.Config[source]

Bases: object

Every tunable setting in the pipeline.

Frozen so that a worker process cannot mutate settings mid-run, and so the object can be handed to multiprocessing.Pool safely.

input_dir: Path = PosixPath('input_data')
output_dir: Path = PosixPath('output')
model_dir: Path = PosixPath('models')
model_path: Path | None = None
auto_download_model: bool = True
n_processes: int | None = None
segment_seconds: int = 10
fs_expected: int = 250
chunk_hours: int = 24
ecg_clip_mv: float = 4.0
ecg_clip_margin_mv: float = 1.0
rr_cover_min: float = 0.75
n_beats_min: int = 5
rr_min_ms: int = 250
rr_max_ms: int = 2500
max_rr_outliers: int = 1
qc_warn_below: float = 0.75
activity_very_light_mg: float = 9.04
activity_light_mg: float = 28.19
activity_moderate_mg: float = 58.08
sleep_threshold_mg: float = 9.04
night_start_hour: int = 21
night_end_hour: int = 9
mains_hz: float = 50.0
mains_notch_q: float = 30.0
ecg_bandpass_low_hz: float = 2.0
ecg_bandpass_high_hz: float = 40.0
ecg_var_min: float = 0.0001
ecg_var_max: float = 2.0
ecg_min_ptp_mv: float = 0.025
qrs_threshold: float = 0.5
rr_outlier_factor: float = 1.8
acc_clip_mg: float = 4000.0
acc_calibrate: bool = True
acc_epoch_seconds: int = 60
impute_gap_max_s: int = 600
property activity_thresholds: Dict[str, float]

Cut-points in the dict form the plotting and reporting code expects.

property segment_samples: int

Samples per analysis segment (2500 = 10 s at 250 Hz).

property chunk_seconds: int

Seconds of signal loaded into memory at a time.

property resolved_n_processes: int

Worker count, leaving one core free unless explicitly configured.

validate()[source]

Check settings are internally consistent, or explain what is wrong.

Return type:

None

__init__(input_dir=PosixPath('input_data'), output_dir=PosixPath('output'), model_dir=PosixPath('models'), model_path=None, auto_download_model=True, n_processes=None, segment_seconds=10, fs_expected=250, chunk_hours=24, ecg_clip_mv=4.0, ecg_clip_margin_mv=1.0, rr_cover_min=0.75, n_beats_min=5, rr_min_ms=250, rr_max_ms=2500, max_rr_outliers=1, qc_warn_below=0.75, activity_very_light_mg=9.04, activity_light_mg=28.19, activity_moderate_mg=58.08, sleep_threshold_mg=9.04, night_start_hour=21, night_end_hour=9, mains_hz=50.0, mains_notch_q=30.0, ecg_bandpass_low_hz=2.0, ecg_bandpass_high_hz=40.0, ecg_var_min=0.0001, ecg_var_max=2.0, ecg_min_ptp_mv=0.025, qrs_threshold=0.5, rr_outlier_factor=1.8, acc_clip_mg=4000.0, acc_calibrate=True, acc_epoch_seconds=60, impute_gap_max_s=600)
Parameters:
  • input_dir (Path)

  • output_dir (Path)

  • model_dir (Path)

  • model_path (Path | None)

  • auto_download_model (bool)

  • n_processes (int | None)

  • segment_seconds (int)

  • fs_expected (int)

  • chunk_hours (int)

  • ecg_clip_mv (float)

  • ecg_clip_margin_mv (float)

  • rr_cover_min (float)

  • n_beats_min (int)

  • rr_min_ms (int)

  • rr_max_ms (int)

  • max_rr_outliers (int)

  • qc_warn_below (float)

  • activity_very_light_mg (float)

  • activity_light_mg (float)

  • activity_moderate_mg (float)

  • sleep_threshold_mg (float)

  • night_start_hour (int)

  • night_end_hour (int)

  • mains_hz (float)

  • mains_notch_q (float)

  • ecg_bandpass_low_hz (float)

  • ecg_bandpass_high_hz (float)

  • ecg_var_min (float)

  • ecg_var_max (float)

  • ecg_min_ptp_mv (float)

  • qrs_threshold (float)

  • rr_outlier_factor (float)

  • acc_clip_mg (float)

  • acc_calibrate (bool)

  • acc_epoch_seconds (int)

  • impute_gap_max_s (int)

Return type:

None

cardiacprep.config.load_config(path=None, overrides=None)[source]

Build a validated Config from a YAML file plus command-line overrides.

Parameters:
  • path (Path | None) – Explicit config file. If None, config.yaml in the current directory is used when present; otherwise defaults apply.

  • overrides (Dict[str, Any] | None) – Values that win over the file. Entries whose value is None are ignored, so unset CLI flags do not clobber file settings.

Raises:

ConfigError – The file is missing, malformed, contains unknown settings, or the resulting configuration is self-inconsistent.

Return type:

Config

Entry point

Single command-line entry point.

The pipeline used to expose three separate commands with no visible relationship to each other. They are now subcommands of one:

cardiac-prep process process .edf recordings cardiac-prep summarise summarise a whole processed dataset cardiac-prep inspect plot one participant’s results

Each subcommand keeps its own argument parser, so cardiac-prep process --help shows exactly what process.py --help always showed. This module only decides which one to call.

Subcommand modules are imported lazily. Importing the processing code pulls in TensorFlow, which takes seconds; there is no reason for cardiac-prep --help or cardiac-prep inspect to pay that cost.

class cardiacprep.entry.Command[source]

Command(module, summary)

module: str

Alias for field number 0

summary: str

Alias for field number 1

static __new__(_cls, module, summary)

Create new instance of Command(module, summary)

Parameters:

Reading and preparing signals

cardiacprep.read_utils.mean_amplitude_deviation(vm, epoch_samples)[source]

Mean Amplitude Deviation of a vector-magnitude signal, per epoch.

MAD is the mean absolute deviation from the epoch’s own mean:

MAD = mean(|VM - mean(VM)|)

Subtracting the epoch mean removes the constant 1 g of gravity, which is why no separate detrending step is needed - and why adding one would be wrong. A high-pass filter ahead of this would strip out slow movement that the published cut-points were derived to include.

Returns one value per epoch, in the units of vm. A trailing partial epoch is measured on whatever samples it has rather than discarded, so a recording that is not a whole number of epochs long keeps its final minutes.

Processing

cardiacprep.proc_utils.doImp(df_qc, mrk_name, gap_lim=600, tseg=10)[source]

Impute missing values in a time-indexed pandas DataFrame.

  • Linearly interpolate gaps ≤ gap_lim (in seconds).

  • Fill longer gaps using average values from same time-of-day bin across minutes.

Parameters: - df_qc: DataFrame with time index in seconds. - mrk_name: column name to impute. - gap_lim: maximum gap length (in seconds) to interpolate (default: 10 min = 600). - tseg: sampling interval in seconds (default: 10s).

Returns: - df_qc with two new columns: {mrk_name}_imputed and {mrk_name}_was_imputed

Main script for processing multi-day EDF files containing ECG and Accelerometer data.

This script reads EDF files, processes the signals in daily chunks to manage memory, performs quality control, calculates heart rate, HRV, and activity metrics, imputes missing data, and generates a comprehensive summary report and plots for each participant.

cardiacprep.proc_edf.init_worker(config, verbose=False)[source]

Load the QRS model once per worker process.

Loading in the initialiser rather than per file means the model is read from disk once per core instead of once per recording. Logging is reconfigured here because a spawned worker inherits no handlers.

cardiacprep.proc_edf.procECG(f, i, chunk_samples, fname, cfg, model, signal_label='ECG', fs=250)[source]

Processes a single chunk of ECG data.

Returns an empty DataFrame if the chunk starts past the end of the recording, which procEDF filters out before concatenating.

cardiacprep.proc_edf.calculate_summary_metrics(df_qc, cfg)[source]

Resamples data to 10-minute windows and calculates robust summary metrics.

cardiacprep.proc_edf.calculate_daily_hrv_for_report(df_qc, cfg)[source]

Calculates the daily median RMSSD from 10-minute sleep periods for the report table.

cardiacprep.proc_edf.procEDF(edf_file, cfg, model, model_info=None)[source]

Main processing pipeline for a single EDF file.

cardiacprep.proc_edf.procEDF_wrapper(edf_filename)[source]

Entry point for multiprocessing.Pool.

Reads the model and settings from the per-worker globals populated by init_worker(), because a loaded Keras model cannot be pickled and sent to a worker as an argument.

Loading results back in

Loading and reshaping one participant’s processed output.

Shared by the subject-level plotting commands so they agree on where files live and how derived views are computed.

The pipeline writes a single per-subject file, *_df_qc.csv.gz, holding 10-second resolution data. The daily and 24-hour views are derived from it here rather than read from disk, because no stage of the pipeline writes them.

exception cardiacprep.subject_data.SubjectNotFoundError[source]

Raised when a participant has no processed output to plot.

cardiacprep.subject_data.list_subjects(output_dir)[source]

Return the ids of every participant with processed output, sorted.

A subject counts as processed only if the QC file is actually present, so a half-finished or failed run does not show up as available.

cardiacprep.subject_data.load_subject_qc(output_dir, subject_id)[source]

Load a participant’s 10-second QC table, indexed by time.

Raises:

SubjectNotFoundError – The participant folder or its QC file is absent. The message lists what is available, since a mistyped id is the most likely cause.

cardiacprep.subject_data.daily_summary(df_qc)[source]

Average heart rate per calendar day.

Derived from the 10-second data because the pipeline writes no daily file.

cardiacprep.subject_data.daily_profile(df_qc)[source]

Median heart rate by time of day, averaged across all recorded days.

Uses the median rather than the mean, matching how the PDF report builds its 24-hour profile, so the two cannot disagree.

Model weights

Locating the QRS detector weights and recording which weights were used.

The weights are distributed separately from this repository, so the pipeline has to find whatever the user downloaded rather than assume a fixed filename. Discovery is by extension, but the exact file and its SHA-256 are recorded in every output row - a filename is a naming convention, whereas a hash is a verifiable claim about which model produced a given result.

exception cardiacprep.model_utils.ModelError[source]

Raised when the QRS detector weights cannot be located unambiguously.

cardiacprep.model_utils.find_model(model_dir, model_path=None)[source]

Return the QRS detector weights file to load.

An explicit model_path is used as-is. Otherwise model_dir is searched for a single .keras file.

Refusing to choose between multiple candidates is deliberate: silently loading the wrong weights would corrupt every downstream result while the pipeline appeared to succeed.

Raises:

ModelError – No weights found, or more than one candidate.

Parameters:
  • model_dir (Path)

  • model_path (Path | None)

Return type:

Path

cardiacprep.model_utils.sha256_of(path, chunk_bytes=1048576)[source]

Hash a file in chunks so large weights do not have to fit in memory.

Parameters:
Return type:

str

cardiacprep.model_utils.model_fingerprint(path)[source]

Provenance columns identifying the weights used for a run.

Written into every row of the summary output so a result can always be traced back to the exact model that produced it, and so a third party can verify their copy matches by hashing it.

Parameters:

path (Path)

Return type:

Dict[str, str]

Utilities

Writing result files so an interrupted run cannot leave partial output.

A plain to_csv writes straight to its destination, so a Ctrl-C, an out-of-memory kill or a machine going to sleep mid-write leaves a truncated file that still looks like a finished result. Weeks later there is nothing to distinguish it from a complete one except a gzip CRC failure.

Writing to a temporary file and renaming it into place removes that state: the destination either does not exist or is complete.

cardiacprep.io_utils.atomic_write_csv(frame, path, **to_csv_kwargs)[source]

Write a DataFrame to path as a single all-or-nothing step.

The data goes to a temporary file alongside the destination, then os.replace moves it into place. That rename is atomic within a filesystem, so a reader never sees a half-written file, and an interrupted run leaves the previous version untouched rather than a corrupt one.

Compression is inferred from the destination suffix when not given, since the temporary name would otherwise defeat pandas’ own inference.

Parameters:
  • frame – Anything with a to_csv(path, **kwargs) method.

  • path – Final destination. Parent directories are created if needed.

  • **to_csv_kwargs – Passed through to to_csv.

Returns:

The destination path.

Logging setup shared by the command line and by worker processes.

Worker processes are started with the ‘spawn’ method on macOS and Windows, which means they do not inherit logging configuration from the parent. Each worker therefore calls configure_logging() again in its initialiser.

cardiacprep.logging_utils.get_logger(name=None)[source]

Return the package logger, or a named child of it.

cardiacprep.logging_utils.configure_logging(verbose=False, include_process=False)[source]

Send package log records to stderr.

Parameters:
  • verbose – Include DEBUG records as well as INFO and above.

  • include_process – Prefix each line with the worker process name. Useful when several recordings are processed at once and their output would otherwise interleave unattributably.

cardiacprep.logging_utils.quieten_dependency(name, level=30)[source]

Raise the log level of a noisy dependency by name.

Rarely needed, since configure_logging already hides third-party INFO, but useful if a dependency logs warnings that are not actionable.