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:
ExceptionRaised 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:
objectEvery 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.Poolsafely.- property activity_thresholds: Dict[str, float]
Cut-points in the dict form the plotting and reporting code expects.
- 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:
- Raises:
ConfigError – The file is missing, malformed, contains unknown settings, or the resulting configuration is self-inconsistent.
- Return type:
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.
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.
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.
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_pathis used as-is. Otherwisemodel_diris searched for a single.kerasfile.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:
- Return type:
- 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.
- 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.
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
pathas a single all-or-nothing step.The data goes to a temporary file alongside the destination, then
os.replacemoves 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.