pyhealth.tasks.ptbxl#

Overview#

Task helpers for PTB-XL multi-label ECG diagnosis. This module currently implements the official 5-diagnostic-superclass classification task (NORM, MI, STTC, CD, HYP) by aggregating diagnostic SCP statements via scp_statements.csv.

Empty superclass label sets (≈400 records on v1.0.1, Wagner et al. Table 9; mainly pacemaker ECGs) are dropped by default. On the full v1.0.3 corpus, MultiLabelProcessor emits labels in alphabetical order: CD, HYP, MI, NORM, STTC. Official fold splitting is provided by pyhealth.datasets.split_by_strat_fold().

API Reference#

PyHealth tasks for PTB-XL multi-label ECG diagnosis.

Dataset link:

https://physionet.org/content/ptb-xl/1.0.3/

Dataset paper: (please cite if you use this dataset)

Patrick Wagner, Nils Strodthoff, Ralf-Dieter Bousseljot, Dieter Kreiseler, Fatima I. Lunze, Wojciech Samek, and Tobias Schaeffter. “PTB-XL, a large publicly available electrocardiography dataset.” Scientific Data 7, 154 (2020).

Dataset paper link:

https://www.nature.com/articles/s41597-020-0495-6

Author:

AxelNoun (GitHub: @AxelNoun) — external contributor, no NetID

Description:

Implements the official 5-diagnostic-superclass multi-label task and aggregation helpers. Separable for a future pyhealth.benchmarks package. Official fold splitting lives in pyhealth.datasets.split_by_strat_fold.

class pyhealth.tasks.ptbxl.Mapping#

Bases: Collection

A Mapping is a generic container for associating key/value pairs.

This class provides concrete generic implementations of all methods except for __getitem__, __iter__, and __len__.

get(k[, d]) → D[k] if k in D, else d.  d defaults to None.#
items() → a set-like object providing a view on D's items#
keys() → a set-like object providing a view on D's keys#
values() → an object providing a view on D's values#
class pyhealth.tasks.ptbxl.Path(*args, **kwargs)[source]#

Bases: PurePath

PurePath subclass that can make system calls.

Path represents a filesystem path but unlike PurePath, also offers methods to do system calls on path objects. Depending on your system, instantiating a Path will return either a PosixPath or a WindowsPath object. You can also instantiate a PosixPath or WindowsPath directly, but cannot instantiate a WindowsPath on a POSIX system or vice versa.

Construct a PurePath from one or several strings and or existing PurePath objects. The strings and path objects are combined so as to yield a canonicalized path, which is incorporated into the new PurePath object.

stat(*, follow_symlinks=True)[source]#

Return the result of the stat() system call on this path, like os.stat() does.

lstat()[source]#

Like stat(), except if the path points to a symlink, the symlink’s status information is returned, rather than its target’s.

exists(*, follow_symlinks=True)[source]#

Whether this path exists.

This method normally follows symlinks; to check whether a symlink exists, add the argument follow_symlinks=False.

is_dir()[source]#

Whether this path is a directory.

is_file()[source]#

Whether this path is a regular file (also True for symlinks pointing to regular files).

is_mount()[source]#

Check if this path is a mount point

Whether this path is a symbolic link.

is_junction()[source]#

Whether this path is a junction.

is_block_device()[source]#

Whether this path is a block device.

is_char_device()[source]#

Whether this path is a character device.

is_fifo()[source]#

Whether this path is a FIFO.

is_socket()[source]#

Whether this path is a socket.

samefile(other_path)[source]#

Return whether other_path is the same or not as this file (as returned by os.path.samefile()).

open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)[source]#

Open the file pointed to by this path and return a file object, as the built-in open() function does.

read_bytes()[source]#

Open the file in bytes mode, read it, and close the file.

read_text(encoding=None, errors=None)[source]#

Open the file in text mode, read it, and close the file.

write_bytes(data)[source]#

Open the file in bytes mode, write to it, and close the file.

write_text(data, encoding=None, errors=None, newline=None)[source]#

Open the file in text mode, write to it, and close the file.

iterdir()[source]#

Yield path objects of the directory contents.

The children are yielded in arbitrary order, and the special entries ‘.’ and ‘..’ are not included.

glob(pattern, *, case_sensitive=None)[source]#

Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.

rglob(pattern, *, case_sensitive=None)[source]#

Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree.

walk(top_down=True, on_error=None, follow_symlinks=False)[source]#

Walk the directory tree from this directory, similar to os.walk().

classmethod cwd()[source]#

Return a new path pointing to the current working directory.

classmethod home()[source]#

Return a new path pointing to the user’s home directory (as returned by os.path.expanduser(‘~’)).

absolute()[source]#

Return an absolute version of this path by prepending the current working directory. No normalization or symlink resolution is performed.

Use resolve() to get the canonical path to a file.

resolve(strict=False)[source]#

Make the path absolute, resolving all symlinks on the way and also normalizing it.

owner()[source]#

Return the login name of the file owner.

group()[source]#

Return the group name of the file gid.

Return the path to which the symbolic link points.

touch(mode=438, exist_ok=True)[source]#

Create this file with the given access mode, if it doesn’t exist.

mkdir(mode=511, parents=False, exist_ok=False)[source]#

Create a new directory at this given path.

chmod(mode, *, follow_symlinks=True)[source]#

Change the permissions of the path, like os.chmod().

lchmod(mode)[source]#

Like chmod(), except if the path points to a symlink, the symlink’s permissions are changed, rather than its target’s.

Remove this file or link. If the path is a directory, use rmdir() instead.

rmdir()[source]#

Remove this directory. The directory must be empty.

rename(target)[source]#

Rename this path to the target path.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

replace(target)[source]#

Rename this path to the target path, overwriting if that path exists.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

Make this path a symlink pointing to the target path. Note the order of arguments (link, target) is the reverse of os.symlink.

Make this path a hard link pointing to the same file as target.

Note the order of arguments (self, target) is the reverse of os.link’s.

expanduser()[source]#

Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)

property anchor#

The concatenation of the drive and root, or ‘’.

as_posix()#

Return the string representation of the path with forward (/) slashes.

as_uri()#

Return the path as a ‘file’ URI.

property drive#

The drive prefix (letter or UNC path), if any.

is_absolute()#

True if the path is absolute (has both a root and, if applicable, a drive).

is_relative_to(other, /, *_deprecated)#

Return True if the path is relative to another path or False.

is_reserved()#

Return True if the path contains one of the special names reserved by the system, if any.

joinpath(*pathsegments)#

Combine this path with one or several arguments, and return a new path representing either a subpath (if all arguments are relative paths) or a totally different path (if one of the arguments is anchored).

match(path_pattern, *, case_sensitive=None)#

Return True if this path matches the given pattern.

property name#

The final path component, if any.

property parent#

The logical parent of the path.

property parents#

A sequence of this path’s logical parents.

property parts#

An object providing sequence-like access to the components in the filesystem path.

relative_to(other, /, *_deprecated, walk_up=False)#

Return the relative path to another path identified by the passed arguments. If the operation is not possible (because this is not related to the other path), raise ValueError.

The walk_up parameter controls whether .. may be used to resolve the path.

property root#

The root of the path, if any.

property stem#

The final path component, minus its last suffix.

property suffix#

The final component’s last suffix, if any.

This includes the leading period. For example: ‘.txt’

property suffixes#

A list of the final component’s suffixes, if any.

These include the leading periods. For example: [‘.tar’, ‘.gz’]

with_name(name)#

Return a new path with the file name changed.

with_segments(*pathsegments)#

Construct a new path object from any number of path-like objects. Subclasses may override this method to customize how new path objects are created from methods like iterdir().

with_stem(stem)#

Return a new path with the stem changed.

with_suffix(suffix)#

Return a new path with the file suffix changed. If the path has no suffix, add given suffix. If the given suffix is an empty string, remove the suffix from the path.

class pyhealth.tasks.ptbxl.Any(*args, **kwargs)[source]#

Bases: object

Special type indicating an unconstrained type.

  • Any is compatible with every type.

  • Any assumed to have all methods.

  • All values assumed to be instances of Any.

Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.

class pyhealth.tasks.ptbxl.Patient(patient_id, data_source)[source]#

Bases: object

Patient class representing a sequence of events.

patient_id#

Unique patient identifier.

Type:

str

data_source#

DataFrame containing all events, sorted by timestamp.

Type:

pl.DataFrame

event_type_partitions#

Dictionary mapping event types to their respective DataFrame partitions.

Type:

Dict[str, pl.DataFrame]

Initialize a Patient instance.

Parameters:
  • patient_id (str) – Unique patient identifier.

  • data_source (pl.DataFrame) – DataFrame containing all events.

__init__(patient_id, data_source)[source]#

Initialize a Patient instance.

Parameters:
  • patient_id (str) – Unique patient identifier.

  • data_source (pl.DataFrame) – DataFrame containing all events.

get_events(event_type=None, start=None, end=None, filters=None, return_df=False)[source]#

Get events with optional type and time filters.

Parameters:
  • event_type (Optional[str]) – Type of events to filter.

  • start (Optional[datetime]) – Start time for filtering events.

  • end (Optional[datetime]) – End time for filtering events.

  • return_df (bool) – Whether to return a DataFrame or a list of Event objects.

  • filters (Optional[List[tuple]]) – Additional filters as [(attr, op, value), …], e.g.: [(“attr1”, “!=”, “abnormal”), (“attr2”, “!=”, 1)]. Filters are applied after type and time filters. The logic is “AND” between different filters.

Returns:

Filtered events as a DataFrame or a list of Event objects.

Return type:

Union[pl.DataFrame, List[Event]]

class pyhealth.tasks.ptbxl.BaseTask(code_mapping=None)[source]#

Bases: ABC

Initialize a task with optional code mapping.

Parameters:

code_mapping (Optional[Dict[str, Tuple[str, str]]]) –

optional dict mapping feature keys to (source_vocab, target_vocab) tuples. For example:

code_mapping={
    "conditions": ("ICD9CM", "CCSCM"),
    "procedures": ("ICD9PROC", "CCSPROC"),
    "drugs": ("NDC", "ATC"),
}

When provided, the corresponding input_schema entries are upgraded from "sequence" to ("sequence", {"code_mapping": (src, tgt)}) so that the SequenceProcessor maps raw codes at fit/process time.

task_name: str#
output_schema: Dict[str, Union[str, Type]]#
__init__(code_mapping=None)[source]#

Initialize a task with optional code mapping.

Parameters:

code_mapping (Optional[Dict[str, Tuple[str, str]]]) –

optional dict mapping feature keys to (source_vocab, target_vocab) tuples. For example:

code_mapping={
    "conditions": ("ICD9CM", "CCSCM"),
    "procedures": ("ICD9PROC", "CCSPROC"),
    "drugs": ("NDC", "ATC"),
}

When provided, the corresponding input_schema entries are upgraded from "sequence" to ("sequence", {"code_mapping": (src, tgt)}) so that the SequenceProcessor maps raw codes at fit/process time.

input_schema: Dict[str, Union[str, Type]]#
pre_filter(df)[source]#
Return type:

LazyFrame

pyhealth.tasks.ptbxl.load_diagnostic_class_map(scp_statements_path)[source]#

Map SCP acronym → diagnostic_class for diagnostic statements only.

Called when constructing PTBXLSuperclassClassification.

Parameters:

scp_statements_path (str | Path) – Path to official scp_statements.csv.

Returns:

Mapping used for 5-superclass aggregation.

Return type:

dict[str, str]

Examples

>>> 
>>> mapping = load_diagnostic_class_map("/data/ptb-xl/1.0.3/scp_statements.csv")
>>> mapping["NORM"]
'NORM'
pyhealth.tasks.ptbxl.aggregate_diagnostic_superclasses(scp_codes, diagnostic_class_map)[source]#

Aggregate stringified scp_codes to unique diagnostic superclasses.

Includes every SCP key present in the dict (likelihood 0 = unknown confidence still counts). Only codes with diagnostic == 1 in scp_statements.csv contribute a superclass.

Parameters:
Returns:

Sorted unique superclass labels (subset of NORM/MI/STTC/CD/HYP).

Return type:

list[str]

Examples

>>> aggregate_diagnostic_superclasses(
...     "{'IMI': 80.0, 'SR': 0.0}", {"IMI": "MI"}
... )
['MI']
class pyhealth.tasks.ptbxl.PTBXLSuperclassClassification(scp_statements_path=None, drop_empty_labels=True)[source]#

Bases: BaseTask

5-superclass multi-label classification on PTB-XL.

Labels are the official diagnostic superclasses NORM, MI, STTC, CD, HYP obtained by mapping diagnostic SCP statements via scp_statements.csv.

MultiLabelProcessor.fit sorts observed labels alphabetically, so on the full v1.0.3 corpus the multi-hot vector is CD, HYP, MI, NORM, STTC. The constructor does not pin this order.

After aggregation, about 400 records have no diagnostic superclass (Wagner et al., Scientific Data Table 9, counted on v1.0.1’s 21,837 records; mainly pacemaker ECGs). By default these are dropped (drop_empty_labels=True) because an all-zero multi-hot target breaks typical multi-label nonconformity scores used in CPBench, and matches common PTB-XL literature practice.

Each sample also carries strat_fold, site, device, age, sex, age_is_censored, and age_is_missing for official splits and downstream shift evaluations.

age is always an integer so litdata and default_collate can batch it. Missing age is -1 (see age_is_missing). HIPAA-censored ages (≥90, stored as 300 in ptbxl_database.csv) are clipped to 90 in the sample while age_is_censored stays True. The raw 300 remains in the derived metadata CSV.

Note

71-SCP multi-label classification and age regression are intentionally not implemented here; add them in this module in a follow-up PR.

Parameters:
  • scp_statements_path (str | Path | None) – Path to scp_statements.csv. Required unless set later via the dataset’s default_task.

  • drop_empty_labels (bool) – Drop records with no superclass after aggregation. Defaults to True.

Examples

>>> 
>>> from pyhealth.datasets import PTBXLDataset
>>> from pyhealth.tasks import PTBXLSuperclassClassification
>>> ds = PTBXLDataset(root="/data/ptb-xl/1.0.3")
>>> samples = ds.set_task(PTBXLSuperclassClassification(
...     scp_statements_path="/data/ptb-xl/1.0.3/scp_statements.csv"
... ))

Initialize a task with optional code mapping.

Parameters:

code_mapping –

optional dict mapping feature keys to (source_vocab, target_vocab) tuples. For example:

code_mapping={
    "conditions": ("ICD9CM", "CCSCM"),
    "procedures": ("ICD9PROC", "CCSPROC"),
    "drugs": ("NDC", "ATC"),
}

When provided, the corresponding input_schema entries are upgraded from "sequence" to ("sequence", {"code_mapping": (src, tgt)}) so that the SequenceProcessor maps raw codes at fit/process time.

task_name: str = 'PTBXLSuperclassClassification'#
input_schema: ClassVar[dict[str, str]] = {'signal': 'tensor'}#
output_schema: ClassVar[dict[str, str]] = {'labels': 'multilabel'}#
superclass_names: ClassVar[tuple[str, ...]] = ('NORM', 'MI', 'STTC', 'CD', 'HYP')#
pre_filter(df)#
Return type:

LazyFrame