pyhealth.datasets.PTBXLDataset#
Overview#
PTB-XL is a large publicly available 12-lead ECG dataset from PhysioNet
(version 1.0.3). It contains 21,799 clinical ECG records of 10 seconds
from 18,869 patients, with multi-label SCP-ECG statements, official
stratified folds (strat_fold), and demographic / site / device metadata
suited to shift-aware evaluation. Only v1.0.3 is supported (v1.0.1 figures
of 21,837 records / 18,885 patients come from Wagner et al., Scientific
Data 2020, and must not be mixed with the PhysioNet v1.0.3 counts).
For more information see PhysioNet PTB-XL v1.0.3 and Wagner et al., Scientific Data 2020.
Optional dependency: install waveform I/O with pip install 'pyhealth[ptbxl]'.
PTBXLDataset.root is the version directory passed to the constructor.
Derived metadata CSVs are written under metadata_cache_dir (default
~/.cache/pyhealth/datasets/ptbxl/), not into root, so read-only
data mounts stay untouched. BaseDataset.load_table concatenates
root / file_path and cannot take an absolute path; PTB-XL overrides
load_table to read the derived CSV from the metadata cache.
API Reference#
- class pyhealth.datasets.PTBXLDataset(root, dataset_name=None, config_path=None, sampling_rate=100, metadata_cache_dir=None, **kwargs)[source]#
Bases:
BaseDatasetPhysioNet PTB-XL ECG dataset (v1.0.3).
Dataset: https://physionet.org/content/ptb-xl/1.0.3/
Expects
root(data_root) to point at the extracted v1.0.3 directory containingptbxl_database.csv,scp_statements.csv,records100/, andrecords500/. Raw data must live outside the git repo. Earlier PhysioNet releases (v1.0.1 / v1.0.2) are not supported: they still contain duplicate records removed in v1.0.2 / v1.0.3 (21,837 records in v1.0.1, 21,799 in v1.0.3). The release version is not detected; only missing required columns raise an error.Derived metadata CSVs are written under PyHealth’s dataset cache (
~/.cache/pyhealth/datasets/ptbxl/by default), not intoroot, so read-only / shared data mounts stay untouched. Override withmetadata_cache_dir. Filenames include the sampling rate, a short hash of the resolved data root, and a content hash ofptbxl_database.csvso different roots and source versions never share a derived CSV.BaseDatasetcache identity (global_event_df) further includes those hashes viadataset_name(same pattern as EEGBCI). The derived CSV and resolved YAML are written beforeBaseDataset.__init__runs, so withPYHEALTH_REQUIRE_CACHE_DIRset and nocache_dirthey are still written tometadata_cache_dirbeforeBaseDatasetraises.- Parameters:
root (str) – Version root of the PTB-XL download (signal + official CSVs).
dataset_name (str | None) – Optional name prefix; defaults to
ptbxl_{sampling_rate}hz. Root and metadata content hashes are appended so two data roots cannot share aBaseDatasetcache.config_path (str | Path | None) – Optional YAML config; defaults to
configs/ptbxl.yaml.sampling_rate (int) –
100(default) or500.metadata_cache_dir (str | Path | None) – Directory for derived
ptbxl-pyhealth-*.csv. Defaults toMODULE_CACHE_PATH / "ptbxl".**kwargs – Forwarded to
BaseDataset(cache_dir,dev, …).
- root#
Same as the constructor
root(the PTB-XL version directory). Derived metadata is not stored here.- Type:
Note
Age missing (NaN) vs HIPAA-censored (
age == 300for ≥90) are exposed asage_is_missing/age_is_censored. Sex is encoded as0= male,1= female (Wagner et al., Scientific Data, Table 2); values are passed through unchanged.scp_codeskeeps the original stringified dict; likelihood0means unknown confidence. Label aggregation lives in task modules.recording_dateis used as the event timestamp.Examples
>>> dataset = PTBXLDataset(root="/data/ptb-xl/1.0.3") >>> dataset.stats() >>> patient = dataset.get_patient(dataset.unique_patient_ids[0]) >>> event = patient.get_events(event_type="records")[0] >>> signal = load_ptbxl_record(event.signal_file)
Initializes the BaseDataset.
- Parameters:
root (str) – The root directory where dataset files are stored.
tables (List[str]) – List of table names to load.
dataset_name (Optional[str]) – Name of the dataset. Defaults to class name.
config_path (Optional[str]) – Path to the configuration YAML file.
cache_dir (Optional[str | Path]) –
Directory for caching processed data. Behavior depends on the type passed:
None (default): Auto-generates a cache path under the default pyhealth cache directory.
str or Path: Used as the root cache directory path. A UUID is appended to the provided path to capture dataset configuration.
num_workers (int) – Number of worker processes for parallel operations.
dev (bool) – Whether to run in dev mode (limits to 1000 patients).
- load_table(table_name)[source]#
Load tables from
metadata_cache_dir, not the user data root.See the comment on
super().__init__in__init__().- Parameters:
table_name (str) – Table name from the YAML config.
- Returns:
The Dask dataframe produced by
BaseDataset.load_table().
- property scp_statements_path: Path#
Path to official
scp_statements.csvunder the data root.- Returns:
Absolute path to
scp_statements.csv.- Return type:
- prepare_metadata()[source]#
Build rate-/root-specific metadata CSV under
metadata_cache_dir.- Return type:
- Returns:
None
Examples
>>> >>> ds = PTBXLDataset(root="/data/ptb-xl/1.0.3") >>> ds.prepare_metadata()
- property default_task: PTBXLSuperclassClassification#
Return the 5-superclass multi-label task wired to this data root.
Matches other signal datasets (EEGBCI / TUAB / SleepEDF): BaseDataset exposes
default_taskas a read-only property and never assigns to it in__init__.- Returns:
Default task instance.
- Return type:
- clean_tmpdir()#
Removes the temporary directories this dataset created.
Other jobs may share the same cache directory and still be using their own directories under
tmp/, so those are left alone.tmp/itself is removed once it is empty.- Return type:
- create_tmpdir()#
Creates and returns a new temporary directory within the cache.
- Returns:
The path to the new temporary directory.
- Return type:
- get_patient(patient_id)#
Retrieves a Patient object for the given patient ID.
- Parameters:
patient_id (str) – The ID of the patient to retrieve.
- Returns:
The Patient object for the given ID.
- Return type:
- Raises:
AssertionError – If the patient ID is not found in the dataset.
- property global_event_df: LazyFrame#
Returns the path to the cached event dataframe.
- Returns:
The path to the cached event dataframe.
- Return type:
- iter_patients(df=None)#
Yields Patient objects for each unique patient in the dataset.
- load_data()#
Loads data from the specified tables.
- Returns:
A concatenated lazy frame of all tables.
- Return type:
dd.DataFrame
- set_task(task=None, num_workers=None, input_processors=None, output_processors=None, split=None)#
Processes the base dataset to generate the task-specific sample dataset. The cache structure is as follows:
{task_name}_{task_uuid}/ # Cached data for specific task based on task name, schema, and args task_df.ld/ # Intermediate task dataframe based on schema samples_{proc_uuid}.ld/ # Final processed samples after applying processors schema.pkl # Saved SampleBuilder schema split.npz # Sample indices per split part (with split= only) *.bin # Processed sample files
- Parameters:
task (Optional[BaseTask]) – The task to set. Uses default task if None.
num_workers (int) – Number of workers for multi-threading. Default is self.num_workers.
input_processors (Optional[Dict[str, FeatureProcessor]]) – Pre-fitted input processors. If provided, these will be used instead of creating new ones from task’s input_schema. Defaults to None.
output_processors (Optional[Dict[str, FeatureProcessor]]) – Pre-fitted output processors. If provided, these will be used instead of creating new ones from task’s output_schema. Defaults to None.
split (Optional[Split]) – Split the samples, e.g. by patient with
PatientSplit, and fit every processor on the first (training) part only, so the other parts never shape preprocessing. The parts are used as the split returns them. Samples are streamed; nothing is loaded into memory beyond the per-sample index that processing already keeps. Defaults to None: fit on all samples and return one dataset, as before.
- Returns:
The generated sample dataset, or, with
split, a tuple with one dataset per part, training part first, whose processors were fitted on the training part.- Return type:
Examples
>>> from pyhealth.datasets import PatientSplit >>> train, val, test = dataset.set_task( ... task, split=PatientSplit(ratios=(0.7, 0.1, 0.2), seed=42) ... )
- Raises:
AssertionError – If no default task is found and task is None.