Skip to main content

ecg-transform

Installation

pip install ecg-transform

Example

Here is an example of defining an input schema and transforms,

from ecg_transform.inp import ECGInputSchema
from ecg_transform.t.common import LinearResample, ReorderLeads
from ecg_transform.t.scale import MinMaxNormalize
from ecg_transform.t.cut import Pad, SegmentNonoverlapping

LEAD_ORDER = ['I', 'II', 'III', 'aVR', 'aVL', 'aVF', 'V1', 'V2', 'V3', 'V4', 'V5', 'V6']
SAMPLE_RATE = 500
N_SAMPLES = SAMPLE_RATE*10

SCHEMA = ECGInputSchema(
    sample_rate=SAMPLE_RATE,
    expected_lead_order=LEAD_ORDER,
    required_num_samples=N_SAMPLES,
)

TRANSFORMS = [
    ReorderLeads(
        expected_order=LEAD_ORDER,
        missing_lead_strategy='raise',
    ),
    LinearResample(desired_sample_rate=SAMPLE_RATE),
    MinMaxNormalize(),
    SegmentNonoverlapping(segment_length=N_SAMPLES),
    Pad(pad_to_num_samples=N_SAMPLES, value=0)
]

Unit conversion & fixed-length resampling

For models with amplitude-sensitive front-ends (e.g. frozen BatchNorm calibrated in mV), use ConvertUnit to bring a signal to physical mV based on the unit declared on ECGMetadata.unit, and FourierResampleToLength to pin a fixed sample grid via scipy.signal.resample (FFT):

from ecg_transform.t.unit import ConvertUnit, FourierResampleToLength

TRANSFORMS = [
    ConvertUnit('mV'),                              # 'adc'/'counts' -> mV; 'mV' is a no-op
    ReorderLeads(LEAD_ORDER, 'raise'),
    FourierResampleToLength(1000, sample_rate=100), # length-normalize to a fixed grid
]

ConvertUnit raises if the declared unit is unknown (incl. None) — callers must declare the source unit, which makes "ADC counts silently treated as mV" (or vice versa) impossible.

Microvolts ('uV', 'µV' with either the micro sign or the Greek mu, 'microvolt', 'microvolts') and volts ('V', 'volt', 'volts') are fixed physical units: they convert without a gain, dividing by 1000 and multiplying by 1000 respectively (since 0.2.1). Units are matched case-insensitively.

The ADC gain belongs to the data, not to the transform, so there is no device-specific default. When converting ADC counts → mV, supply the gain (µV/count) one of two ways:

# (a) per-record (real, sample-specific) gain on the metadata:
meta = ECGMetadata(..., unit='adc', adc_microvolts_per_count=4.88)
transforms = [ConvertUnit('mV')]                       # reads it off each record

# (b) one corpus-wide constant (mock / no per-record metadata):
transforms = [ConvertUnit('mV', adc_microvolts_per_count=4.88)]  # applies to all

A constant passed to ConvertUnit takes precedence over per-record metadata; ADC input with neither raises.

FourierResampleToLength preserves the input dtype and is a no-op when the signal is already the target length. Prefer it over LinearResample when output must match an FFT-based pipeline — linear interpolation lacks anti-aliasing and diverges at sharp QRS peaks.

Here is an example of how ecg-transform could be used in PyTorch (which we do not require to minimize dependencies),

from typing import List
from itertools import chain

from scipy.io import loadmat

import numpy as np

import torch
from torch.utils.data import Dataset
from torch.utils.data.dataloader import DataLoader

from ecg_transform.inp import ECGInput, ECGInputSchema
from ecg_transform.t.base import ECGTransform
from ecg_transform.sample import ECGMetadata, ECGSample

class ECGDataset(Dataset):
    def __init__(
        self,
        schema,
        transforms,
        file_paths,
    ):
        self.schema = schema
        self.transforms = transforms
        self.file_paths = file_paths

    def __len__(self):
        return len(self.file_paths)

    def __getitem__(self, idx):
        mat = loadmat(self.file_paths[idx])
        metadata = ECGMetadata(
            sample_rate=int(mat['org_sample_rate'][0, 0]),
            num_samples=mat['feats'].shape[1],
            lead_names=['I', 'II', 'III', 'aVR', 'aVL', 'aVF', 'V1', 'V2', 'V3', 'V4', 'V5', 'V6'],
            unit=None,
            input_start=0,
            input_end=mat['feats'].shape[1],
        )
        inp = ECGInput(mat['feats'], metadata)
        sample = ECGSample(
            inp,
            self.schema,
            self.transforms,
        )

        return torch.from_numpy(sample.out).float(), self.file_paths[idx]

def collate_fn(inps):
    sample_ids = list(
        chain.from_iterable([[inp[1]]*inp[0].shape[0] for inp in inps])
    )
    return torch.concatenate([inp[0] for inp in inps]), sample_ids

def file_paths_to_loader(
    file_paths: List[str],
    schema: ECGInputSchema,
    transforms: List[ECGTransform],
    batch_size = 64,
    num_workers = 7,
):
    dataset = ECGDataset(
        schema,
        transforms,
        file_paths,
    )

    return DataLoader(
        dataset,
        batch_size=batch_size,
        num_workers=num_workers,
        pin_memory=True,
        sampler=None,
        shuffle=False,
        collate_fn=collate_fn,
        drop_last=False,
    )

Metadata

Release files for ecg-transform 0.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ecg-transform 0.2.1
File Size Uploaded Provenance Actions
ecg_transform-0.2.1.tar.gz 22.5 kB Without provenance Details for ecg_transform-0.2.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ecg-transform 0.2.1
File Interpreter ABI Platform Actions
ecg_transform-0.2.1-py3-none-any.whl Python 3 none any Details for ecg_transform-0.2.1-py3-none-any.whl

Total release size: 42.5 kB

Release files / ecg_transform-0.2.1.tar.gz

Download URL ecg_transform-0.2.1.tar.gz
Size 22.5 kB
Tags Source
SHA-256 checksum
How to use checksums
170501a69ef86cfda8274c31a69edabb75c7cf205e3dc9cff2db59de74b62be5
BLAKE2b-256 checksum
How to use checksums
e6847a3c6a300fe93fd3b61f791c531bac95aa2d0a700f6efb8c5568057012a4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / ecg_transform-0.2.1-py3-none-any.whl

Download URL ecg_transform-0.2.1-py3-none-any.whl
Size 20.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
876a450c62ca5ee90da1f1b45b78b51a07c3b84ea7d7c80fcc11d52e65996fd4
BLAKE2b-256 checksum
How to use checksums
21ca569f72d76fb401a09236f7725f47b996e1ef18229e5e375954b6bc146465
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for ecg-transform 0.2.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page