API Reference#

Full API documentation automatically generated from source docstrings.

API#

class pmecg.BackgroundAttentionMap(data, *, polarity, color=None, show_colormap=True, rhythm_strips_attention=None)[source]#

Bases: AbstractAttentionMap

Render attention as semi-transparent background blocks behind each ECG row.

Parameters:
  • data (AttentionDataType) – Attention input (DataFrame or tuple formats).

  • polarity (AttentionPolarity) – 'positive' for non-negative attention; 'signed' for values spanning both negative and positive.

  • color (AttentionColorType | None, optional) – The color(s) used for rendering, following the same semantics as in the base class. By default, red for positive polarity and blue/red for signed polarity.

  • show_colormap (bool, optional) – Whether to show the right-side color scale. By default True.

  • rhythm_strips_attention (AttentionDataType | None, optional) – Attention data for rhythm strip rows. See AbstractAttentionMap for full documentation. By default None.

class pmecg.ECGInformation(hospital=None, patient_name=None, age=None, sex=None, date=None, machine_model=None, filter=None)[source]#

Bases: object

Patient and recording metadata to be printed on the ECG plot.

Parameters:
  • hospital (str, optional) – Name of the hospital or clinic where the ECG was recorded.

  • patient_name (str, optional) – Name of the patient.

  • age (int, optional) – Age of the patient in years.

  • sex (str, optional) – Sex of the patient (e.g. “Male”, “Female”).

  • date (str, optional) – Date of the recording (any human-readable format, e.g. “2024-01-15”).

  • machine_model (str, optional) – ECG machine model, printed in the bottom-right corner.

  • filter (str, optional) – Description of the filter(s) applied to the ECG (e.g. “0.05-150 Hz”).

class pmecg.ECGPlotter(grid_mode='cm', speed=25.0, voltage=10.0, row_distance=3.0, line_width=0.5, grid_color='#f4aaaa', print_information=False, print_available_leads=False, show_time_axis=False, show_calibration=True, show_leads_labels=True, show_separators=True, disconnect_segments=True, show_dpi=300)[source]#

Bases: object

Generate paper-like ECG plots from signal data.

Instantiate with visual parameters (speed, voltage scale, grid style, etc.), then call plot() to render one or more ECGs using the same configuration.

Parameters:
  • grid_mode ({'cm', None}, optional) – Grid style to overlay on the plot. 'cm' draws lines every 0.1 cm (= 1 mm), with every 5th line slightly thicker. Pass None to disable the grid. By default 'cm'.

  • speed (float, optional) – The speed of the plot in mm/s, by default 25.0

  • voltage (float, optional) – The space (in mm) corresponding to 1 mV, by default 10.0

  • row_distance (float, optional) – Distance between the zero-lines of consecutive rows, expressed in mV, by default 3.0

  • line_width (float, optional) – Thickness of the ECG signal lines (and calibration pulse) in points, by default 0.5

  • grid_color (str, optional) – Color of the grid lines. Any matplotlib color string is accepted (e.g. ‘#f4aaaa’, ‘lightgray’, ‘gray’). By default ‘#f4aaaa’ (light ECG-paper red).

  • print_information (bool, optional) – Whether to print diagnostic parameters (speed, voltage, sampling frequency) and any extra metadata in the corners of the figure, by default False.

  • print_available_leads (bool, optional) – Whether to include the list of available leads in the diagnostic line. Only has an effect when print_information=True. By default False.

  • show_time_axis (bool, optional) – Whether to show the time axis (x-axis ticks and spine) at the bottom of the figure, by default False.

  • show_calibration (bool, optional) – Whether to show the calibration pulse in the left margin of each row, by default True.

  • show_leads_labels (bool, optional) – Whether to print lead names onto the plot, by default True.

  • show_separators (bool, optional) – Whether to draw short vertical tick marks at the boundary between adjacent lead columns within each row, by default True.

  • disconnect_segments (bool, optional) – If True, the last sample of each segment is set to NaN so that adjacent segments are not visually connected in the plot. By default True.

  • show_dpi (int, optional) – DPI applied to the figure before displaying it when show=True. Has no effect when show=False. By default 300.

plot(ecg_data, configuration=None, sampling_frequency=500.0, show=True, information=None, stats=None, attention_map=None, rhythm_strips=None)[source]#

Plot the ECG in ecg_data using the plotting configuration specified in configuration.

Parameters:
  • ecg_data (ECGDataType) – ECG signal data to plot.

  • configuration (ConfigurationDataType | None, optional) – The plotting configuration to be used. By default None, meaning that each lead is plotted on its own row for its entire duration.

  • sampling_frequency (float, optional) – The sampling frequency of the ECG data in Hz, by default 500.0

  • show (bool, optional) – Whether to show the plot, by default True

  • information (ECGInformation | None, optional) – Patient and recording metadata. When self.print_information is True, the hospital, patient name and date are printed above the first ECG row, and the machine model is printed in the bottom-right corner.

  • stats (ECGStats | None, optional) – Computed ECG statistics. When self.print_information is True, any non-None field is printed in the top-right corner, arranged in columns of up to three rows.

  • attention_map (AbstractAttentionMap | None, optional) – Optional attention overlay. Pass an instance of BackgroundAttentionMap, IntervalAttentionMap, or LineColorAttentionMap, where you specify the attention data and the style settings. When an attention map requests a color scale, plot() expands the right margin automatically to preserve the ECG plotting area. You can disable this by setting show_colormap=False in the AttentionMap initialization.

  • rhythm_strips (RhythmStripsConfig | None, optional) – Optional rhythm strips appended after the configuration rows. Every lead present in rhythm_strips.ecg_data is plotted as a full-width row showing the entire recording. When rhythm_strips.speed differs from the plotter’s speed, those rows use the specified paper speed and the figure width is expanded if needed. By default None.

Returns:

The matplotlib figure object containing the plot

Return type:

matplotlib.figure.Figure

class pmecg.ECGStats(bpm=None, snr=None, rr_interval_ms=None, hrv_ms=None, pr_interval_ms=None, qrs_duration_ms=None, qt_interval_ms=None, qtc_interval_ms=None, p_axis_deg=None, qrs_axis_deg=None, t_axis_deg=None)[source]#

Bases: object

Computed ECG diagnostic statistics to be printed on the plot.

All fields default to None (not shown). Any field that is set will be displayed in the top-right corner when print_information=True, arranged in columns of three rows.

Parameters:
  • bpm (float, optional) – Heart rate in beats per minute.

  • snr (float, optional) – Signal-to-noise ratio in dB.

  • rr_interval_ms (float, optional) – Mean RR interval (beat-to-beat) in milliseconds.

  • hrv_ms (float, optional) – Heart-rate variability — statistical spread of RR intervals (ms).

  • pr_interval_ms (float, optional) – PR interval in milliseconds.

  • qrs_duration_ms (float, optional) – QRS complex duration in milliseconds.

  • qt_interval_ms (float, optional) – QT interval in milliseconds.

  • qtc_interval_ms (float, optional) – Corrected QT interval (QTc) in milliseconds.

  • p_axis_deg (float, optional) – P-wave axis in degrees.

  • qrs_axis_deg (float, optional) – QRS axis in degrees.

  • t_axis_deg (float, optional) – T-wave axis in degrees.

class pmecg.IntervalAttentionMap(data, *, polarity, color=None, max_attention_mV=0.25, alpha=0.25, show_colormap=False, smoothing_window=None, rhythm_strips_attention=None)[source]#

Bases: AbstractAttentionMap

Render attention as a colored band around the ECG trace.

Parameters:
  • data (AttentionDataType) – Attention scores.

  • polarity (AttentionPolarity) – 'positive' for non-negative attention; 'signed' for values spanning both negative and positive.

  • color (AttentionColorType | None, optional) – The color(s) used for rendering, following the same semantics as in the base class. By default, red for positive polarity and blue/red for signed polarity.

  • max_attention_mV (float, optional) – Maximum half-width of the attention band in mV (at attention strength 1). By default 0.25.

  • alpha (float, optional) – Transparency of the band (0 = fully transparent, 1 = opaque). By default 0.25.

  • show_colormap (bool, optional) – Whether to show the right-side color scale. By default False, since the band itself provides a strong visual cue of the attention score.

  • smoothing_window (int | None, optional) – If set, applies a moving-average with this window size to the attention values before rendering. None disables smoothing. By default None.

  • rhythm_strips_attention (AttentionDataType | None, optional) – Attention data for rhythm strip rows. See AbstractAttentionMap for full documentation. By default None.

class pmecg.LeadSegment(lead, start, end)[source]#

Bases: object

Advanced per-lead configuration entry for a row.

Parameters:
  • lead (str) – Lead name as it appears in the input data.

  • start (int) – First sample index (inclusive).

  • end (int) – Last sample index (exclusive).

  • Example:: – LeadSegment(lead=’I’, start=0, end=500)

class pmecg.LineColorAttentionMap(data, *, polarity, color=None, show_colormap=True, rhythm_strips_attention=None)[source]#

Bases: AbstractAttentionMap

Render attention as a gradient-colored line drawn on top of the ECG trace.

Parameters:
  • data (AttentionDataType) – Attention input (DataFrame or tuple formats).

  • polarity (AttentionPolarity) – 'positive' for non-negative attention; 'signed' for values spanning both negative and positive.

  • color (AttentionColorType | None, optional) – The color(s) used for rendering, following the same semantics as in the base class. By default, red for positive polarity and blue/red for signed polarity.

  • show_colormap (bool, optional) – Whether to show the right-side color scale. By default True.

  • rhythm_strips_attention (AttentionDataType | None, optional) – Attention data for rhythm strip rows. See AbstractAttentionMap for full documentation. By default None.

class pmecg.RhythmStripsConfig(ecg_data, speed=None)[source]#

Bases: object

Configuration for rhythm strip rows appended after the main layout rows.

Parameters:
  • ecg_data (ECGDataType) – ECG signal source for the rhythm strip rows. All leads present in this dataset are plotted as full-width rhythm strip rows. Lead names are derived from the data itself (DataFrame column names, or the lead-name list in the tuple form), so no separate leads argument is needed.

  • speed (float | None, optional) – Paper speed in mm/s for the rhythm strips. When None, the plotter’s main speed is used. By default None.

pmecg.attention_map_from_indices_annotations(ecg_data, **annotations_by_lead)[source]#

Build an attention DataFrame from per-lead sample-index annotations.

Parameters:
  • ecg_data (ECGDataType) – ECG data used to determine the output lead names and number of samples. The helper accepts the same DataFrame and tuple formats supported by pmecg.ECGPlotter.

  • **annotations_by_lead (list[dict]) –

    Keyword arguments keyed by lead name. Each value must be a list of dictionaries with two required keys:

    • "index_range" — a 2-element list or tuple [start, end) of non-negative integer sample indices (half-open interval).

    • "attention_value" — a finite float attention score for that range.

    Example:

    attention_map_from_indices_annotations(
        ecg_data,
        II=[{"index_range": [100, 300], "attention_value": 0.8}],
        V1=[{"index_range": [50, 150], "attention_value": 0.5}],
    )
    

Returns:

Attention values aligned to the ECG samples, with one column per lead and one row per ECG sample. Leads without annotations are filled with zeros.

Return type:

pandas.DataFrame

Raises:

ValueError – If a lead name is missing from ecg_data, if an annotation payload is malformed, or if an index range is invalid or falls outside the ECG recording length.

pmecg.attention_map_from_time_annotations(ecg_data, fs, **annotations_by_lead)[source]#

Build an attention DataFrame from per-lead time annotations.

Parameters:
  • ecg_data (ECGDataType) – ECG data used to determine the output lead names and number of samples.

  • fs (float) – Sampling frequency in Hz.

  • **annotations_by_lead (list[dict]) –

    Keyword arguments keyed by lead name. Each value must be a list of dictionaries with two required keys:

    • "time_range" — a 2-element list or tuple [start, end) of non-negative floats in seconds (half-open interval).

    • "attention_value" — a finite float attention score for that range.

    Example:

    attention_map_from_time_annotations(
        ecg_data, fs=500,
        II=[{"time_range": [0.2, 0.6], "attention_value": 0.8}],
        V1=[{"time_range": [0.1, 0.3], "attention_value": 0.5}],
    )
    

Returns:

Attention values aligned to the ECG samples, with one column per lead and one row per ECG sample. Leads without annotations are filled with zeros.

Return type:

pandas.DataFrame

Raises:

ValueError – If fs is invalid, if a lead name is missing from ecg_data, if an annotation payload is malformed, or if a time range is invalid or falls outside the ECG recording duration.

pmecg.cabrera_factory(template, ecg_data, leads_map=None)[source]#

Build Cabrera-ordered ECG data and plotting configuration from a template.

Cabrera format reorders the six limb leads as aVL, I, -aVR, II, aVF, III (instead of the standard I, II, III, aVR, aVL, aVF) and creates a new -aVR lead (negated aVR).

Parameters:
  • template (str) – Name of a built-in template to expand. The template must reference all six limb leads (supported: '1x6', '1x12', '2x6', '4x3', '2x6+1', '4x3+1', '2x6+3', '4x3+3').

  • ecg_data (ECGDataType) – ECG input. Must include all six limb leads. When the input uses non-canonical column names, provide leads_map to map them.

  • leads_map (LeadsMap | None, optional) –

    Optional mapping from canonical lead names (I, II, aVR, …) to the corresponding column names in ecg_data. Pass None when the input already uses canonical names. By default None.

    If the custom column name mapped to aVR starts with '-' (e.g. LeadsMap(aVR='-aVR') or LeadsMap(aVR='-AVR')), the data are assumed to be already negated and the sign flip is skipped; only the rename to '-aVR' is performed.

Returns:

A pair of (modified_ecg_data, cabrera_configuration) where:

  • modified_ecg_data is a copy of the input where the 'aVR' column (or lead) has been renamed to '-aVR'. The sign is flipped unless the source column name already starts with '-', in which case the data are treated as pre-negated.

  • cabrera_configuration is the layout configuration with limb leads reordered into Cabrera sequence, using the same column names as the returned modified_ecg_data. Rhythm-strip rows (string entries in multi-row templates) are also resolved through leads_map.

Return type:

tuple[ECGDataType, ConfigurationDataType]

Raises:

ValueError – If the template does not reference all six limb leads, or if the 'aVR' lead is missing from the input data.

pmecg.expand_to_12_leads(ecg_data, leads_map=None)[source]#

Derive the four missing limb leads and return a full 12-lead ECG DataFrame.

Given an ECG containing at least leads I, II, V1–V6, this function computes the four remaining limb leads using Einthoven’s law:

\[\begin{split}\text{III} &= \text{II} - \text{I} \\ \text{aVR} &= -\tfrac{\text{I} + \text{II}}{2} \\ \text{aVL} &= \text{I} - \tfrac{\text{II}}{2} \\ \text{aVF} &= \text{II} - \tfrac{\text{I}}{2}\end{split}\]
Parameters:
  • ecg_data (ECGDataType) – ECG input. Must contain at least leads I, II, V1–V6. Non-standard leads or extra columns are not carried through; the output contains only the 12 standard leads in canonical order. When the input uses non-canonical column names, supply leads_map to map them to canonical names.

  • leads_map (LeadsMap | None, optional) – Mapping from canonical lead names (I, II, V1, …) to the column names present in ecg_data. Pass None when the input already uses canonical names. By default None.

Returns:

12-lead ECG DataFrame with columns in standard order: I, II, III, aVR, aVL, aVF, V1, V2, V3, V4, V5, V6.

Return type:

pandas.DataFrame

Raises:

ValueError – If any of the eight required leads (I, II, V1–V6) is missing from the input data or the leads map.

pmecg.template_factory(template, ecg_data, leads_map)[source]#

Resolve a built-in template to an explicit configuration for the provided ECG input.

Parameters:
  • template (str) – Name of the built-in template to expand. Supported values: '1x1', '1x2', '1x3', '1x4', '1x6', '1x8', '1x12', '2x4', '2x6', '4x3', '2x4+1', '2x6+1', '4x3+1', '2x4+3', '2x6+3', '4x3+3'.

  • ecg_data (ECGDataType) – The ECG input used to resolve the final lead names. Must be the same object (or an object of the same type and with the same columns/lead names) that will later be passed to plot().

  • leads_map (LeadsMap | None) – Optional mapping from conventional template lead names (I, II, aVR, aVL, aVF, V1, …) to the corresponding column names in ecg_data. Pass None when the input already uses the canonical names.

Returns:

Explicit plotting configuration: a list where each element is either a string (full-width rhythm strip) or a list of strings (leads concatenated within the same row).

Return type:

ConfigurationDataType

Raises:

ValueError – If template is not one of the supported template names, if a required canonical lead is missing from both leads_map and ecg_data, or if leads_map contains invalid or duplicate mappings.

class pmecg.AbstractAttentionMap(data, *, polarity, show_colormap=True, rhythm_strips_attention=None)[source]#

Bases: ABC

Base class for attention-aware ECG overlays. Subclass this to implement a custom visual style.

Three built-in implementations are provided: IntervalAttentionMap, BackgroundAttentionMap, and LineColorAttentionMap. To create a custom style, subclass AbstractAttentionMap and implement the abstract _rgba_for_value and build_artists methods.

The shared prepare() step converts the raw input into a lead-aligned pandas.DataFrame, validates the requested polarity, applies a global scaling factor when values exceed magnitude 1, and segments the attention values according to the ECG layout.

Parameters:
  • data (AttentionDataType) – Attention signal: a pandas.DataFrame whose columns are lead names, or a (array, lead_names) tuple.

  • polarity (AttentionPolarity) – 'positive' for non-negative attention values rendered with a single color; 'signed' for values spanning both negative and positive, rendered with two colors.

  • show_colormap (bool, optional) – Whether to render the right-side color scale next to the plot. By default True.

  • rhythm_strips_attention (AttentionDataType | None, optional) – Attention data for rhythm strip rows appended via RhythmStripsConfig. The columns must be named after the rhythm strip lead(s); any rhythm strip whose name is absent from this dataset will be rendered without an attention overlay. The data is scaled with the same global scale factor derived from data, so colors are directly comparable between the main layout and the rhythm strip rows. The number of samples may differ from data — a common case is a rhythm strip that shows more of the recording than the main layout does. By default None.

class pmecg.LeadsMap(I=None, II=None, III=None, aVR=None, aVL=None, aVF=None, V1=None, V2=None, V3=None, V4=None, V5=None, V6=None, *, AVR=None, AVL=None, AVF=None)[source]#

Bases: _LeadsMapBase

Optional mapping from canonical leads to input lead names.

All 12 fields default to None; only the leads that differ from their canonical names need to be specified. For example, if the input ECG data uses "LI" for lead I and "-aVR" for lead aVR:

LeadsMap(I="LI", aVR="-aVR")

This allows the built-in templates to be resolved correctly even when the input data uses non-canonical lead names.

Deprecated since version Keyword: arguments AVR, AVL, AVF (uppercase) are accepted for backward compatibility but will be removed in a future release. Use aVR, aVL, aVF instead.

Parameters:
  • I (str | None)

  • II (str | None)

  • III (str | None)

  • aVR (str | None)

  • aVL (str | None)

  • aVF (str | None)

  • V1 (str | None)

  • V2 (str | None)

  • V3 (str | None)

  • V4 (str | None)

  • V5 (str | None)

  • V6 (str | None)

  • AVR (str | None)

  • AVL (str | None)

  • AVF (str | None)

Return type:

LeadsMap

Types#

Type aliases used throughout pmecg.

Import these in annotations to describe input/output shapes clearly:

from pmecg.types import ECGDataType, ConfigurationDataType, LeadSegment, RhythmStripsConfig, AttentionDataType
pmecg.types.AttentionArrayType#

Raw attention scores. The following data types are supported:

  • a 2-D NumPy array of shape (n_samples, n_leads)

  • a list of 1-D arrays of shape (n_samples,) for each lead

alias of ndarray | List[ndarray]

pmecg.types.AttentionColorType#

A single color string (positive-only) or a (negative, positive) color pair (signed).

Colors should be specified in a format accepted by Matplotlib, e.g. hex strings like #FF0000 or named colors like "red".

alias of str | Tuple[str, str]

pmecg.types.AttentionDataType#

Attention scores input accepted by the *AttentionMap classes.

The following formats are accepted:

  • a tuple of (scores, lead_names) where scores is AttentionArrayType and lead_names is a list of lead name strings.

  • a pandas.DataFrame whose columns are named after the leads.

alias of Tuple[List[ndarray] | ndarray, List[str]] | DataFrame

pmecg.types.AttentionPolarity#

Whether attention values are positive-only or span negative and positive.

alias of Literal[‘positive’, ‘signed’]

pmecg.types.ConfigurationDataType#

Layout configuration accepted by plot().

Either a purely string-based layout or a purely LeadSegment-based layout — the two kinds cannot be mixed within the same configuration.

String-based (each row element is a str or list[str]):

  • a list of lead name strings — those leads are concatenated side-by-side in one row, or

  • a single lead name string — that lead occupies the full row width.

Segment-based (each row element is a LeadSegment or list[LeadSegment]):

  • a list of LeadSegment objects — leads with explicit start/end sample indices in one row, or

  • a single LeadSegment object — a lead with explicit range occupying the full row width.

Example (string-based):

config = [
    ["I", "II", "III"],  # Leads I, II, III in the first row
    "aVR",                # Lead aVR in the second row
    ["aVL", "aVF"],       # Leads aVL and aVF in the third row
]

Example (segment-based):

config = [
    [LeadSegment(lead='I', start=0, end=500), LeadSegment(lead='II', start=0, end=500)],
    [LeadSegment(lead='III', start=0, end=1000)],
]

alias of List[List[str] | str] | List[List[LeadSegment] | LeadSegment]

pmecg.types.ECGDataType#

ECG signal input accepted by ECGPlotter.

The following formats are accepted:

  • a tuple of (signal, lead_names) where signal is either a 2D NumPy array of shape (n_samples, n_leads) or a list of 1D arrays of shape (n_samples,) for each lead, and lead_names is a list of strings naming the leads.

  • a pandas.DataFrame whose columns are named after the leads.

alias of Tuple[List[ndarray] | ndarray, List[str]] | DataFrame

class pmecg.types.LeadSegment(lead, start, end)[source]#

Advanced per-lead configuration entry for a row.

Parameters:
  • lead (str) – Lead name as it appears in the input data.

  • start (int) – First sample index (inclusive).

  • end (int) – Last sample index (exclusive).

  • Example:: – LeadSegment(lead=’I’, start=0, end=500)

class pmecg.types.RhythmStripsConfig(ecg_data, speed=None)[source]#

Configuration for rhythm strip rows appended after the main layout rows.

Parameters:
  • ecg_data (ECGDataType) – ECG signal source for the rhythm strip rows. All leads present in this dataset are plotted as full-width rhythm strip rows. Lead names are derived from the data itself (DataFrame column names, or the lead-name list in the tuple form), so no separate leads argument is needed.

  • speed (float | None, optional) – Paper speed in mm/s for the rhythm strips. When None, the plotter’s main speed is used. By default None.