Movatterモバイル変換


[0]ホーム

URL:


Title:Intracardiac Electrograms
Version:0.2.0
Description:A system for importing electrophysiological signal, based on the 'Waveform Database (WFDB)' software package, written by Moody et al 2022 <doi:10.13026/gjvw-1m31>. A R-based system to utilize 'WFDB' functions for reading and writing signal data, as well as functions for visualization and analysis are provided. A stable and broadly compatible class for working with signal data, supporting the reading in of cardiac electrophysiological files such as intracardiac electrograms, is introduced.
License:GPL (≥ 3)
Encoding:UTF-8
RoxygenNote:7.3.3
Depends:R (≥ 4.2.0),
Imports:vctrs (≥ 0.5.0), data.table (≥ 1.15.0), stats, fs, ggplot2,rlang, utils, xml2, base64enc, checkmate, stringr, signal,
Suggests:covr, knitr, rmarkdown, testthat (≥ 3.0.0), withr, fastICA,moments, lifecycle,
LinkingTo:cpp11
Config/testthat/edition:3
URL:https://shah-in-boots.github.io/EGM/
BugReports:https://github.com/shah-in-boots/EGM/issues
VignetteBuilder:knitr
NeedsCompilation:yes
Packaged:2025-11-01 23:50:59 UTC; asshah4
Author:Anish S. ShahORCID iD [aut, cre, cph], Darren Seaney [ctb]
Maintainer:Anish S. Shah <shah.in.boots@gmail.com>
Repository:CRAN
Date/Publication:2025-11-02 06:11:13 UTC

EGM: Intracardiac Electrograms

Description

A system for importing electrophysiological signal, based on the 'Waveform Database (WFDB)' software package, written by Moody et al 2022doi:10.13026/gjvw-1m31. A R-based system to utilize 'WFDB' functions for reading and writing signal data, as well as functions for visualization and analysis are provided. A stable and broadly compatible class for working with signal data, supporting the reading in of cardiac electrophysiological files such as intracardiac electrograms, is introduced.

Author(s)

Maintainer: Anish S. Shahshah.in.boots@gmail.com (ORCID) [copyright holder]

Other contributors:

See Also

Useful links:


Internal vctrs methods

Description

Internal vctrs methods


Subset a windowed object

Description

Subset a windowed object

Usage

## S3 method for class 'windowed'x[i, ...]

Arguments

x

A windowed object

i

Index to subset

...

Additional arguments passed to methods

Value

A windowed object with the specified subset of elements


Add annotations to aggm object

Description

Theadd_annotations() adds annotations to aggm object. It isspecific to this class as it requires the output ofggm() to includeddata stored inannotation_table().

Usage

add_annotations(...)

Arguments

...

Arguments passed on toggm

data

Data of theegm class, which includes header (meta) and signalinformation together.

channels

Acharacter vector of which channels to use. Can giveeither the channel label (e.g "CS 1-2") or the recording device/cathetertype (e.g "His" or "ECG"). If no channels are selected, the default is allchannels.

time_frame

A time range that should be displaced given in the formatof a vector with a length of 2. The left value is the start, and rightvalue is the end time. This is given in seconds (decimals may be used).

palette

Acharacter choice from the below options that describe thecolor choices to be used for plotting. If set to the default, which isNULL, no changes to the colors for individual channels will be performed.If a positive choice is made, then the backgroundmode argument will beset todark as the default, unless otherwise specified.WARNING: This isan experimental argument, and may be moved in future version.

  • NULL: no changes to the colors will be made. DEFAULT.

  • material: a colorscheme based off of theMaterial Design color scheme

mode

Acharacter string fromc("dark", "light") to describe thebase/background color settings to be used. If there are preset channelcolors that were exported in theegm object, these colors will be usedfor the individual channels. Ifpalette is specified, then thedarkoption will be set automatically (a palette choice cannot be made withoutunderstanding the background to plate it across).WARNING: This is anexperimental argument, and may be moved in future version.

  • Thedark theme mimics the "white on black" scheme seen inLabSystem Pro format (and most other high-contrast visualizations), for minimizing eye strain. This calls thetheme_egm_dark() function. DEFAULT.

  • Thelight theme mimics the "black on white" colors seen in thePrucka system.

  • NULL removes any theme, and uses the defaultggplot2::ggplot() settings


Add color scheme to aggm object

Description

Usingadd_colors() is part of the theme process for aggmobject, which in turn is a visual representation of anegm object. Often,theegm dataset will contain default colors based on where the signaldata was brought in from.add_colors() can allow customization of thosefeatures to some degree based onopinionated color palettes.

Usage

add_colors(object, palette, mode)

Arguments

object

Aggm object

palette

Acharacter choice from the below options that describe thecolor choices to be used for plotting. If set to the default, which isNULL, no changes to the colors for individual channels will be performed.If a positive choice is made, then the backgroundmode argument will beset todark as the default, unless otherwise specified.WARNING: This isan experimental argument, and may be moved in future version.

  • NULL: no changes to the colors will be made. DEFAULT.

  • material: a colorscheme based off of theMaterial Design color scheme

mode

Acharacter string fromc("dark", "light") to describe thebase/background color settings to be used. If there are preset channelcolors that were exported in theegm object, these colors will be usedfor the individual channels. Ifpalette is specified, then thedarkoption will be set automatically (a palette choice cannot be made withoutunderstanding the background to plate it across).WARNING: This is anexperimental argument, and may be moved in future version.

  • Thedark theme mimics the "white on black" scheme seen inLabSystem Pro format (and most other high-contrast visualizations), for minimizing eye strain. This calls thetheme_egm_dark() function. DEFAULT.

  • Thelight theme mimics the "black on white" colors seen in thePrucka system.

  • NULL removes any theme, and uses the defaultggplot2::ggplot() settings

Details

Currently, the color choices are individual decided based on thechannel source (e.g. lead) and are inspired by some modern palettes. Theeventual goal for this function is to accept a multitude of palette optionsusing heuristics similar to what is found in{ggplot2} or other graphingpackages.

Value

Returns an updatedggm object


Analyze F waves in atrial fibrillation ECG

Description

Analyze F waves in atrial fibrillation ECG

Usage

analyze_atrial_signal(  atrial_signal,  frequency,  characteristics = c("amplitude", "approximate_entropy", "dominant_frequency"),  ...)

Arguments

atrial_signal

Numeric vector of the atrial signal

frequency

Sampling frequency of the signal

characteristics

Vector of characteristics to analyze

...

Additional parameters for specific analyses

Value

A list containing the results of the requested analyses


Annotation Table

Description

annotation_table() modifies thedata.table class to workwith annotation data. The columns are of all equal length, and each rowdescribes a single annotation (although there may be duplicate time points).

Usage

annotation_table(  annotator = character(),  time = character(),  sample = integer(),  frequency = integer(),  type = character(),  subtype = character(),  channel = integer(),  number = integer(),  ...)is_annotation_table(x)

Arguments

annotator

String that is the name of a WFDB-compatible annotationtype, serving as the extension for the file that is written containing thatannotation. Please seeread_annotation() andwrite_annotation() forfurther details.

time

Acharacter time stamp of the annotation, written in the formatofHH:MM:SS.SSS, starting at00:00:00.000. This is converted to theappropriate time based on the header file (which records the actual starttime and sampling frequency). This is often a missing variable and isgiven for compatibility with the WFDB applications.

sample

Aninteger representing the sample number of the annotation

frequency

Aninteger that represents the sampling frequency in Hertz

type

Acharacter or string representing the type of the annotation

subtype

Acharacter or string representing the subtype of theannotation

channel

Aninteger representing the channel number of theannotation, or acharacter representing the channel name

number

An additionalinteger value or number that classifies theannotation (allows for compatibility with multiple annotation types)

...

Additional arguments to be passed to the function

x

Adata.table object that represents an annotation table

Details

Theannotation_table() function creates a compatible table thatcan be used withwrite_annotation() andread_annotation() functions.

Value

Adata.table that has invariant columns that are compatible withthe WFDB library. The key columns include the sample index, the type ofannotation (and its subtype and number qualifier), and the channel.

Annotation files

The following annotation file types are described below.

ecgpuwave

ecgpuwave analyzes an ECG signal from the specified record, detecting theQRS complexes and locating the beginning, peak, and end of the P, QRS, andST-T waveforms. The output of ecgpuwave is written as a standard WFDB-formatannotation file (the extension is "*.ecgpuwave", as would be expected). Thisfile can be converted into text format usingrdann. Further details aregiven at theECGPUWAVEpage.

Thetype column can bep,t, orN for the peak of the P wave, Twave, and QRS (R peak) directly. The output notation also includes waveformonset XXX and waveform offset XXX. Thenumber column gives furtherinformation about each of thesetype labels.

Thenumber column gives modifier information. If thetype classifieris a T wave annotation, thenumber column can be 0 (normal), 1(inverted), 2 (positive), 3 (negative), 4 (biphasic negative-positive), 5(biphasic positive-negative). If thetype is an waveform onset or offset,thennumber can be 0 (P wave), 1 (QRS complex), 2 (T wave).


Annotator systems for WFDB objects

Description

These functions create templates for annotation in R and extend the ability for developers to create their own annotation systems that are stable for WFDB objects. They are compatible with WFDB annotations and can be written out to a WFDB-compatible file. This also allows extensibility.


Convert an egm object to an ecg object

Description

Converts a generalegm object to a specializedecg objectfor 12-lead ECG analysis.

Usage

as_ecg(x, ...)

Arguments

x

An object of classegm

...

Additional arguments

Value

An object of classecg


Read in ECG and EGM data from Bard (LabSystem Pro)

Description

This function allows for reading in LS Pro data based on theirtext export of signals. Signals can be exported directly from the LS Prosystem. The actual software is written byBard.

TheLabSystem Prowas acquired by Boston Scientific from the original companyBard.They are a common electrophysiology signal processing device forvisualization and measurement of intracardiac signals.

Usage

read_bard(file, n = Inf)read_bard_header(file)read_bard_signal(file, n = Inf)

Arguments

file

The path to the file where the data is located. It must be a*.txt file. See details below about its format.

n

Number of signal values to return (this will be the same for eachchannel of data). Defaults to all values.

Value

Anegm class object that is a list of EP signals the format of adata.table, with an attachedheader attribute that containsadditional recording data.

Data Export

The steps to data export are as follows.

  1. Start LabSystem PRO

  2. Open a patient record

  3. Display a waveform recording in a Review Window

  4. Scroll to a point of interest in a waveform recording

  5. Right click on the review window to the left of the region of interest

  6. Select an Export option, either a default time range or the entire visiblepage (which depends on the sweep speed).

Data Format

[Header] Recording info – contains (example):[Header]<CR><LF> File Type: 1<CR><LF> Version: 1<CR><LF> Channels exported: 22<CR><LF> Samples per channel: 5000<CR><LF> Start time:  6:55:24<CR><LF> End time:  6:55:29<CR><LF> Ch. Info. Pointer: 320<CR><LF> Stamp Data: T<CR><LF> Mux format: 0<CR><LF> Mux Block Size: <CR><LF> Data Format 1<CR><LF> Sample Rate: 1000Hz<CR><LF>[Header] Channel info (per channel example):  Channel #: 1<CR><LF>  Label: III<CR><LF> Range: 5mv <CR><LF> Low: 1Hz<CR><LF> High: 100Hz<CR><LF> Sample rate: 1000Hz<CR><LF> Color: 0000FF<CR><LF> Scale: -7<CR><LF>[Data] As described below:-256,-1056,576,-256,320,-736,144,576,-592,176,608,240,176,-560,496,-144,0,0,-32,-48,-32,-80<CR><LF>

Channel Data is interleaved in the example above (sample indexed at 1):

1 2 3 ... 22
Ch1:1 Ch2:1 Ch3:1 ... Ch22:1
Ch1:2 Ch2:2 Ch3:2 ... Ch22:2
Ch1:3 Ch2:3 Ch3:3 ... Ch22:3
... ... ... ... ...
Ch1:5000 Ch2:5000 Ch3:5000 ... Ch22:5000

Concatenate windowed objects

Description

Concatenate windowed objects

Usage

## S3 method for class 'windowed'c(...)

Arguments

...

windowed objects to concatenate

Value

A windowed object containing all the elements of the input objects


Calculate Approximate Entropy (Ap_en) of a time series

Description

This function computes the approximate entropy (Ap_en) of a time series usingthe method described by Pincus (1991). Ap_en is a measure of the regularityand complexity of the time series. It is calculated by comparing vectorsderived from the time series in an m-dimensional embedded space and in an(m+1)-dimensional space. The basic steps are:

  1. Embedding: The time series is embedded into vectors of length m (andm+1) by taking successive elements. For a time series of length N, thisproduces (N - m + 1) (or (N - m) for m+1) vectors.

  2. Distance Calculation: For each pair of embedded vectors, the Chebyshevdistance (i.e., the maximum absolute difference among corresponding elements)is computed. If the distance between two vectors is less than or equal to atolerance r, they are considered "similar."

  3. Counting and Averaging: For each embedded vector, the function countsthe number of similar vectors (including itself) and takes the naturallogarithm of the ratio of this count to the total number of vectors. Theselog-values are then averaged to yield a statistic phi.

  4. Ap_en Calculation: The approximate entropy is the difference betweenthe phi computed for dimension m and the phi computed for dimension m+1,i.e., Ap_en = phi(m) - phi(m+1).

The tolerance r is typically chosen as a multiple of the standard deviationof the time series (commonly 3.5 * sd(x)). If r is not provided (or isnegative), it is calculated automatically.

Usage

calculate_approximate_entropy(x, m = 3, r = NULL, implementation = "C++")

Arguments

x

Numeric vector of the time series

m

Embedding dimension (sample size), default is 3

r

Tolerance (threshold), default is 3.5 * sd(x)

implementation

Method to use for calculation, default is "C++", but canalso be done in "R". The C++ implementation is faster.

Value

Approximate Entropy value

References

Pincus, S. M. (1991). Approximate entropy as a measure of systemcomplexity. Proceedings of the National Academy of Sciences, 88(6),2297-2301.

Examples

# Example: Calculate approximate entropy for a random time seriesset.seed(123)x <- rnorm(1000)calculate_approximate_entropy(x, m = 3, r = -1, implementation = "R")

Calculate Dominant Frequency of a time series

Description

Calculate Dominant Frequency of a time series

Usage

calculate_dominant_frequency(x, frequency, f_min = 4, f_max = 9)

Arguments

x

Numeric vector of the time series

frequency

Sampling frequency of the signal

f_min

Minimum frequency to consider (default 4 Hz)

f_max

Maximum frequency to consider (default 9 Hz)

Value

Dominant Frequency in Hz


Identify the color for a channel based on palettes

Description

This primarily restricts the colors to color-space safe options. It isintended to be used withadd_colors() to provide a color scheme for theggm object. It has been exposed to users for custom or advanced themingoptions.

Usage

color_channels(x, palette, mode = "dark")

Arguments

x

Vector ofcharacter names of requested ECG or EGM leads

palette

Acharacter choice from the below options that describe thecolor choices to be used for plotting. If set to the default, which isNULL, no changes to the colors for individual channels will be performed.If a positive choice is made, then the backgroundmode argument will beset todark as the default, unless otherwise specified.WARNING: This isan experimental argument, and may be moved in future version.

  • NULL: no changes to the colors will be made. DEFAULT.

  • material: a colorscheme based off of theMaterial Design color scheme

mode

Acharacter string fromc("dark", "light") to describe thebase/background color settings to be used. If there are preset channelcolors that were exported in theegm object, these colors will be usedfor the individual channels. Ifpalette is specified, then thedarkoption will be set automatically (a palette choice cannot be made withoutunderstanding the background to plate it across).WARNING: This is anexperimental argument, and may be moved in future version.

  • Thedark theme mimics the "white on black" scheme seen inLabSystem Pro format (and most other high-contrast visualizations), for minimizing eye strain. This calls thetheme_egm_dark() function. DEFAULT.

  • Thelight theme mimics the "black on white" colors seen in thePrucka system.

  • NULL removes any theme, and uses the defaultggplot2::ggplot() settings

Value

Vector of hex code colors ascharacter based on the selectedpalette and light/dark mode


Theming and color options forggm objects

Description

[Experimental]

The general purpose is to improve visualization of electrical signals. Thereis a pattern of colors that are generally given from different recordingsoftware, and they can be replicated to help improve visibility.

Usage

theme_egm()theme_egm_light()theme_egm_dark()

Value

Aggm object, with inheritance similar toggplot2::theme_minimal()


Detect QRS complexes in ECG signals

Description

detect_QRS() implements a modified Pan-Tompkins algorithm todetect QRS complexes in ECG signals. The function applies a sequence ofprocessing steps including bandpass filtering, differentiation, squaring, andmoving window integration to identify R peaks in the signal.

Usage

detect_QRS(signal, frequency, window_size = 0.15)

Arguments

signal

Numeric vector representing the ECG signal

frequency

Sampling frequency of the signal in Hz

window_size

Width of the integration window in seconds, default is0.150 seconds

Details

The Pan-Tompkins algorithm is a widely-used method for QRS detectionin ECG signals. This implementation follows these steps:

  1. Bandpass filtering (5-15 Hz) to reduce noise and emphasize QRS complexes

  2. Differentiation to highlight the steep slopes of QRS complexes 3. Squaringto amplify high-frequency components 4. Moving window integration to considerthe overall QRS morphology 5. Adaptive thresholding to identify peaks 6.Application of a refractory period to prevent multiple detections of the sameQRS complex

The function is designed to work with single-lead ECG signals, typicallysampled at 250-1000 Hz.

Value

Integer vector containing the sample indices of detected QRScomplexes

References

Pan, J., & Tompkins, W. J. (1985). A real-time QRS detectionalgorithm. IEEE Transactions on Biomedical Engineering, (3), 230-236.doi:10.1109/TBME.1985.325532

Examples

## Not run: # Load ECG dataecg_data <- read_muse(system.file("extdata", "muse-sinus.xml", package = "EGM"))# Extract lead II signalsignal <- ecg_data$signal$II# Get sampling frequency from headerfreq <- attributes(ecg_data$header)$record_line$frequency# Detect QRS complexesqrs_locations <- detect_QRS(signal, freq)# Plot ECG with detected QRS complexesplot(signal, type = "l", xlab = "Sample", ylab = "Amplitude")points(qrs_locations, signal[qrs_locations], col = "red", pch = 19)## End(Not run)

Electrocardiogram data class for 12-lead ECG studies

Description

This class serves as a specialized extension of theegm classspecifically for standard 12-lead electrocardiogram data. It inherits allfunctionality fromegm while providing additional validation and methodsspecific to 12-lead ECG analysis.

Usage

ecg(  signal = signal_table(),  header = header_table(),  annotation = annotation_table(),  ...)is_ecg(x)

Arguments

signal

Asignal_table object generated by thesignal_table()function containing standard ECG leads

header

Aheader_table object generated by theheader_table()function

annotation

Aannotation_table object generated by theannotation_table() function

...

Additional arguments to be passed to the function

x

Anecg object to be used with support functions

Details

Theecg object contains the same three components asegm:

The primary difference is that this class enforces validation to ensurethe data represents a standard 12-lead ECG with appropriate lead names.

Value

An object of classecg (which inherits fromegm) containingsignal, header, and annotation components.


Electrogram data class from electrophysiology studies

Description

This class serves as a combinatorial class to describecardiovascular electrical signal data in R. It is based off of the formatsavailable in WFDB, but has been formatted for ease of use within theRecosystem. Anegm object contains three components in a list:

These components help to navigate, and visualize data. Theegm class isthe backbone for working with WFDB objects in R, and provides an interfacefor integrating or converting other raw signal data to a WFDB format.

Usage

egm(  signal = signal_table(),  header = header_table(),  annotation = annotation_table(),  ...)is_egm(x)

Arguments

signal

Asignal_table object generated by thesignal_table()function

header

Aheader_table object generated by theheader_table()function

annotation

Aannotation_table object generated by theannotation_table() function

...

Additional arguments to be passed to the function

x

Anegm object, typically generated by theegm() function, to beused with support functions (e.g.is_egm()

Details

The individual components of the class are further defined in theirrespective children functionssignal_table(),header_table(),annotation_table(). They are very simple classes that build upon thedata.table class that allow for class safety checks when working withdifferent data types (particularly WFDB).

IMPORTANT: Theegm class can be built from ground-up by the user,however it is primarily generated for the user using the other read/writefunctions, such asread_bard() orread_wfdb().

Value

An object of classegm that is always a list of the above threecomponents. Oftentimes, theannotation_table object may be missing, andit is replaced with an empty table as a place holder.


Extract F wave features from ECG

Description

This function analyzes F waves in an ECG signal, extracting variouscharacteristics.

Usage

extract_f_waves(  object,  lead = NULL,  qrs_method = "adaptive_svd",  f_characteristics = "amplitude",  verbose = TRUE,  .force_all = FALSE,  ...)

Arguments

object

An object of classegm or of subclassecg

lead

Optional. A character string specifying the lead to analyze. IfNULL (default), all available surface leads will be processed.

qrs_method

Method for ventricular signal removal. Default is"adaptive_svd" for adaptive singular value decomposition.

f_characteristics

Vector of characteristics to analyze from ECGsignal. Options: "amplitude", "approximate_entropy", "dominant_frequency".Please seecalculate_approximate_entropy() andcalculate_dominant_frequency() for more details.

verbose

Logical. If TRUE, print information about which leads will beanalyzed. Default is TRUE.

.force_all

Logical. If FALSE (default), only process surface ECG leads.If TRUE, process all available leads. This parameter is ignored if the objectis of class 'ecg', in which case all leads are processed.

...

Additional arguments passed to methods

Value

A list containing F wave features for each processed lead

References

Park, Junbeom, Chungkeun Lee, Eran Leshem, Ira Blau, Sungsoo Kim, Jung MyungLee, Jung-A Hwang, Byung-il Choi, Moon-Hyoung Lee, and Hye Jin Hwang. "EarlyDifferentiation of Long-Standing Persistent Atrial Fibrillation Using theCharacteristics of Fibrillatory Waves in Surface ECG Multi-Leads." ScientificReports 9 (February 26, 2019): 2746.https://doi.org/10.1038/s41598-019-38928-6.

Hyvarinen, A., and Oja, E. (2000). Independent component analysis: algorithmsand applications.Neural Networks, 13(4-5), 411-430.


Extract raw signal data from anegm object

Description

Raw signal data may be all that is required, particularly whenstoring or manipulating data, or for example, feeding it into an analyticalpipeline. This means the extraneous elements, such as themeta information,may be unnecessary. This function helps to strip away and extract just thesignal data itself and channel names.

Usage

extract_signal(object, data_format = c("data.frame", "matrix", "array"), ...)

Arguments

object

Anegm object that contains the signal data to be extracted

data_format

Acharacter choice of eitherdata.frame (default),matrix, orarray that tells how the data should be structured.Further explanation in the details.

...

Additional arguments to be passed to the function

Details

The options to return the data vary based on need. The data can beextracted as follows:

Value

An object as described by theformat option


Format a windowed object for printing

Description

Format a windowed object for printing

Usage

## S3 method for class 'windowed'format(x, ...)

Arguments

x

A windowed object

...

Additional arguments passed to methods

Value

Invisibly returns x


Visualization of EGMs usingggplot

Description

[Experimental]

Theggm() function is used to plot objects of theegm class. Thisfunction however is more than just a plotting function - it serves as avisualization tool and confirmation of patterns, annotations, and underlyingwaveforms in the data. The power of this, instead of being a⁠geom_*()⁠object, is that annotations, intervals, and measurements can be addedincrementally.

Usage

ggm(  data,  channels = character(),  time_frame = NULL,  palette = NULL,  mode = "dark",  ...)

Arguments

data

Data of theegm class, which includes header (meta) and signalinformation together.

channels

Acharacter vector of which channels to use. Can giveeither the channel label (e.g "CS 1-2") or the recording device/cathetertype (e.g "His" or "ECG"). If no channels are selected, the default is allchannels.

time_frame

A time range that should be displaced given in the formatof a vector with a length of 2. The left value is the start, and rightvalue is the end time. This is given in seconds (decimals may be used).

palette

Acharacter choice from the below options that describe thecolor choices to be used for plotting. If set to the default, which isNULL, no changes to the colors for individual channels will be performed.If a positive choice is made, then the backgroundmode argument will beset todark as the default, unless otherwise specified.WARNING: This isan experimental argument, and may be moved in future version.

  • NULL: no changes to the colors will be made. DEFAULT.

  • material: a colorscheme based off of theMaterial Design color scheme

mode

Acharacter string fromc("dark", "light") to describe thebase/background color settings to be used. If there are preset channelcolors that were exported in theegm object, these colors will be usedfor the individual channels. Ifpalette is specified, then thedarkoption will be set automatically (a palette choice cannot be made withoutunderstanding the background to plate it across).WARNING: This is anexperimental argument, and may be moved in future version.

  • Thedark theme mimics the "white on black" scheme seen inLabSystem Pro format (and most other high-contrast visualizations), for minimizing eye strain. This calls thetheme_egm_dark() function. DEFAULT.

  • Thelight theme mimics the "black on white" colors seen in thePrucka system.

  • NULL removes any theme, and uses the defaultggplot2::ggplot() settings

...

Additional arguments to be passed to the function

Value

An{ggplot2} compatible object with theggm class, whichcontains additional elements about the header and annotations of theoriginal data.


Header Table

Description

header_table() modifies thedata.table class to work withheader data. The header data is read in from a similar format as to that ofWFDB files and should be compatible/interchangeable when writing out to disk.The details extensively cover the type of data that is input. Generally, thisfunction is called by⁠read_*_header()⁠ functions and will generally not becalled by the end-user.

Usage

header_table(  record_name = character(),  number_of_channels = integer(),  frequency = 250,  samples = integer(),  start_time = strptime(Sys.time(), "%Y-%m-%d %H:%M:%OSn"),  ADC_saturation = integer(),  file_name = character(),  storage_format = 16L,  ADC_gain = 200L,  ADC_baseline = ADC_zero,  ADC_units = "mV",  ADC_resolution = 12L,  ADC_zero = 0L,  initial_value = ADC_zero,  checksum = 0L,  blocksize = 0L,  label = character(),  info_strings = list(),  additional_gain = 1,  low_pass = integer(),  high_pass = integer(),  color = "#000000",  scale = integer())is_header_table(x)

Arguments

record_name

Acharacter vector of record line information

number_of_channels

Aninteger describing number of signals

frequency

Anumeric value of sampling frequency, 250 Hz default

samples

Aninteger for the number of samples

start_time

ThePOSIXct time of recording, with miliseconds included.For example,strptime(start_time, "%Y-%m-%d %H:%M%:%OSn") where asdescribed inbase::strptime()

ADC_saturation

Aninteger representing ADC saturation

file_name

Acharacter for the signal specific information

storage_format

Aninteger of the bits for the storage format, 16-bitdefault

ADC_gain

Aninteger of ADC gain, default of 200

ADC_baseline

Aninteger of ADC baseline, defaults toADC_zero

ADC_units

Acharacter to describe ADC units, "mV" is default

ADC_resolution

Aninteger for ADC resolution, default is 12

ADC_zero

Aninteger for ADC zero, defaults to 0

initial_value

Aninteger for the initial value, defaults toADC_zero value

checksum

Aninteger that serves as the checksum

blocksize

Aninteger of the block size

label

Acharacter description of the signal

info_strings

Alist of strings that will be written as an appendixto the header file, usually containing information about the channels,(e.g. list of colors, extra labels, etc).

additional_gain

Anumeric Additional gain, defaults to 1.0

low_pass

Aninteger Low pass filter

high_pass

Aninteger High pass filter

color

Acharacter Color as hexadecimal format, defaults to black

scale

Aninteger Scale

x

Adata.table object that serves as the header table

Details

Theheader_table object is relatively complex in that it directlydeals with properties of the signal, and allows compatibility with WFDBfiles and other raw header files for other signal objects. It can be writtenout usingwrite_wfdb().

Value

Aheader_table object that is an extension of thedata.tableclass. This contains an adaptation of the function arguments, allowing forcompatibility with the WFDB class.

Header file structure

There are three components to the header file:

  1. Record line that contains the following information, in the orderdocumented, however pieces may be missing based on different parameters.From left to right...

    • Record name

    • Number of signals: represents number of segments/channels

    • Sampling frequency (optional)

    • Number of samples (optional)

    • Time: in HH:MM:SS format (optional)

    • Date: in DD/MM/YYYY (optional)

  2. Signal specification lines contains specifications for individualsignals, and there must be as many signal lines as there are reported by theabove record line. From left to right....

    • File name: usually *.dat

    • Formatinteger: represents storage type, e.g. 8-bit or 16-bit

    • ADC gain: ADC units per physical unit (optional)

      • Baseline: corresponds to 0 physical units, sep = '*(0)" (optional)

      • Units: with '/' as a field separator e.g '*/mV' (optional)

    • ADC resolutioninteger: bits, usually 8 or 16 (optional)

    • ADC zero: represents middle of ADC input range (optional)

    • Initial value (optional)

    • Checksum (optional)

    • Block size (optional)

    • Description: text or label information (optional)

  3. Info strings are unstructured lines that contains information aboutthe record. Usually are descriptive. Starts with initial '#' withoutpreceding white space at beginning of line.


Helper function to apply interpolation

Description

Helper function to apply interpolation

Usage

interpolate_signal(  original_samples,  original_values,  new_samples,  interpolation_method)

Test if an object is a windowed object

Description

Test if an object is a windowed object

Usage

is_windowed(x)

Arguments

x

An object to test

Value

TRUE if x is a windowed object, FALSE otherwise


Apply a function to each element of a windowed object

Description

Apply a function to each element of a windowed object

Usage

lapply.windowed(X, FUN, ...)

Arguments

X

A windowed object

FUN

A function to apply to each element

...

Additional arguments passed to FUN

Value

A list of the results of applying FUN to each element of X,or a new windowed object if all results are egm objects


Read in ECG data from MUSE

Description

This function serves to read/convert XML based files from the MUSE system todigital signal. This can subsequently be written into other formats. The MUSEsystem is somewhat proprietary, and each version may or may not allow exportoptions into XML.

Usage

read_muse(file)

Arguments

file

An ECG file from MUSE in XML format

Details

GE Healthcare MUSE v9 is currently the model that is being used. Thesefunctions have not been tested in older versions.

Value

Anegm class object that is a list ofeps signals the format of adata.table, with an attachedheader attribute that containsadditional recording data.


Print a windowed object

Description

Print a windowed object

Usage

## S3 method for class 'windowed'print(x, ...)

Arguments

x

A windowed object

...

Additional arguments passed to methods

Value

Invisibly returns x


Read Prucka System Files

Description

read_prucka() reads both the signal data (.txt) and header information(.inf) exported from the Prucka cardiac electrophysiology system, which isthe underlying recording software used in GE Healthcare's CardioLab EPsystem.

Usage

read_prucka(signal_file, header_file = NULL, n = Inf)read_prucka_header(header_file)read_prucka_signal(signal_file, n = Inf)

Arguments

signal_file

Path to the *.txt signal data file

header_file

Path to the *.inf header file. If NULL, will look for afile with the same base name as signal_file but with .inf extension.

n

Number of signal values to return (this will be the same for eachchannel of data). Defaults to all values.

Details

Exporting from GE CardioLab/Prucka

To export data from the GE CardioLab system:

  1. Open the study/recording in CardioLab

  2. Select the time segment you want to export

  3. Navigate toFile > Export orTools > Export

  4. ChooseASCII Export orText Export format

  5. Select the channels to export

  6. Choose export location and filename

  7. The system will create two files:

    • X####.txt: Space-delimited signal data

    • X####.inf: Header file with metadata

File Format Details

Signal file (*.txt):

Header file (*.inf):

Both files must have the same base name (e.g., X001.txt and X001.inf).

Notes

Value

Anegm class object that is a list of EP signals the format of adata.table, with an attachedheader attribute that containsadditional recording data.


Signal tables

Description

Thesignal_table() function modifies thedata.table class towork with electrical signal data. The input should be a data set of equalnumber of rows. It will add a column of index positions calledsample ifit does not already exist.

Usage

signal_table(...)is_signal_table(x)

Arguments

...

Alist of equal lengths

x

data.frame A data frame of signal data

Value

An object of classsignal_table, which is an extension of thedata.table class. Thesample column isinvariant and will always bepresent. The other columns represent additional channels.


Standardize windows of signal data

Description

Standardizeswindowed objects by applying varioustransformations to each window. This function converts eachegm object in awindowed list to a standardized data frame with uniform properties,facilitating comparison and analysis.

Usage

standardize_windows(  x,  standardization_method = c("time_normalize"),  target_samples = 500,  target_ms = NULL,  interpolation_method = c("linear", "spline", "step"),  align_feature = NULL,  preserve_amplitude = TRUE,  preserve_class = FALSE,  ...)

Arguments

x

Awindowed object to standardize

standardization_method

Acharacter string specifying the standardization method.Currently supported: "time_normalize".

target_samples

The desired number of samples for each standardizedwindow. Default is 500 samples. This parameter takes precedence if bothtarget_samples and target_ms are provided.

target_ms

Alternative specification in milliseconds. If provided andtarget_samples is NULL, the function will convert this to samples based onthe signal's sampling frequency.

interpolation_method

The method used for interpolation whenresampling. Options are "linear" (default), "spline", or "step".

align_feature

Feature to align windows around, either a characterstring matching an annotation type or a list of criteria for finding aspecific annotation. Default is NULL (no alignment).

preserve_amplitude

Logical. If TRUE (default), maintains originalamplitude range after resampling.

preserve_class

Logical. If TRUE, returns awindowed object withstandardized data frames. If FALSE (default), returns a plain list of dataframes.

...

Additional arguments passed to specific standardization methods.

Details

Currently supported standardization methods:

Additional options:

Value

Ifpreserve_class=TRUE, awindowed object containing standardizeddata frames. Ifpreserve_class=FALSE, a plain list of standardized dataframes.

Examples

## Not run: # Read in ECG dataecg <- read_wfdb("ecg", test_path(), "ecgpuwave")# Create windows based on sinus rhythmwindows <- window_signal(  ecg,  method = "rhythm",  rhythm_type = "sinus",  onset_criteria = list(type = "(", number = 0),  offset_criteria = list(type = ")", number = 2),  reference_criteria = list(type = "N"))# Standardize windows to exactly 500 samplesstd_windows <- standardize_windows(  windows,  method = "time_normalize",  target_samples = 500)# Alternatively, standardize to 500 milliseconds (depends on sampling frequency)std_windows_ms <- standardize_windows(  windows,  method = "time_normalize",  target_ms = 500)# Standardize windows with QRS alignmentaligned_windows <- standardize_windows(  windows,  method = "time_normalize",  target_samples = 500,  align_feature = "N"  # Align on QRS complexes)## End(Not run)

Time normalize windows to a standard length

Description

Time normalize windows to a standard length

Usage

time_normalize_windows(  x,  target_samples = 500,  target_ms = NULL,  interpolation_method = "linear",  align_feature = NULL,  preserve_amplitude = TRUE,  ...)

Validate that signal data represents a standard 12-lead ECG

Description

Validate that signal data represents a standard 12-lead ECG

Usage

validate_ecg_data(signal, header)

Arguments

signal

A signal_table object

header

A header_table object

Value

TRUE if valid, throws error otherwise


Waveform Database (WFDB) Software Package

Description

This implementation of WFDB is a back-end for the WFDB using a combination ofpython,C++, andC language. The related functions are documentedseparately. This serves as an overview of the conversion of WFDB formats to Rformats. In this documentation, the specific WFDB generated files will bedescribed.

Arguments

record

String that will be used to name the WFDB record. Cannotinclude extensions, and is not a filepath. alphanumeric characters areacceptable, as well as hyphens (-) and underscores (_)

record_dir

File path of directory that should be used read and writefiles. Defaults to current directory.

annotator

String that is the name of a WFDB-compatible annotationtype, serving as the extension for the file that is written containing thatannotation. Please seeread_annotation() andwrite_annotation() forfurther details.

...

Additional arguments to be passed to the function

WFDB

The WFDB (Waveform Database) Software Package has been developed over thepast thirty years, providing a large collection of software for processingand analyzing physiological waveforms. The package is written in highlyportable C and can be used on all popular platforms, including GNU/Linux,MacOS X, MS-Windows, and all versions of Unix.

The foundation of the WFDB Software Package is the WFDB library,consisting of a set of functions for reading and writing digitized signalsand annotations. These functions can be used by programs written in C, C++,or Fortran, running under any operating system for which an ANSI/ISO Ccompiler is available, including all versions of Unix, MS-DOS, MS-Windows,the Macintosh OS, and VMS.

Data format

The records that the WFDB uses have three components...

  1. Signals: integer values that are at equal intervals at a certain samplingfrequency

  2. Header attributes: recording information such as sample number, gain,sampling frequency

  3. Annotations: information about the record such as a beat labels or alarmtriggers

Author(s)

Original software: George Moody, Tom Pollard, Benjamin Moody
R implementation: Anish S. Shah
Last updated: 2025-11-01


Standard WFDB annotation nomenclature

Description

Provides the standard label definitions used by WFDBannotation files. These helper functions make it easier tointerpret the contents of theannotation_table() object byexposing the symbol, mnemonic, and description that correspond toeach label store value defined in the WFDB Applications Guide(Moody and collaborators).

Usage

wfdb_annotation_labels(symbol = NULL, label_store = NULL)wfdb_annotation_decode(annotation, column = "type")

Arguments

symbol

Optional character vector of WFDB annotation symbolsto filter the results.

label_store

Optional integer vector of WFDB label storevalues to filter the results.

annotation

Anannotation_table() or compatible data framewhose annotation symbols or label store values should be augmentedwith the standard WFDB nomenclature.

column

Name of the column withinannotation that containseither the WFDB symbol (default, for thetype column) or thelabel store values. If the column is numeric it is matched onlabel_store, otherwise a symbol lookup is performed.

Details

The returned table is derived from the WFDB ApplicationGuide and matches the canonical label store values used by theWFDB software distribution. Entries that are not currently definedby the specification are omitted.

Value

wfdb_annotation_labels() returns a data frame with columnslabel_store,symbol,mnemonic, anddescription.wfdb_annotation_decode() returns the input annotationtable with the WFDB nomenclature columns appended.

References

Moody GB.WFDB Applications Guide. PhysioNet. Available athttps://www.physionet.org/physiotools/wag/.

Examples

wfdb_annotation_labels()wfdb_annotation_labels(symbol = c("N", "V"))ann <- annotation_table(  annotator = "example",  sample = c(100L, 200L),  type = c("N", "V"))wfdb_annotation_decode(ann)

Read WFDB-compatible annotation file

Description

Individual annotation types are described as both a command-linetool for annotating WFDB-files, as well as the extension that is appended totherecord name to notate the type. Generally, the types of annotationsthat are supported are described below:

A more thorough explanation is given in the details. Additionally, files whenbeing read in are converted from a binary format to a textual format. The rawdata however may be inadequate, as the original annotation may be erroneous.In these cases, an emptyannotation_table object will be returned.

Usage

read_annotation(  record,  annotator,  record_dir = ".",  begin = 0,  end = NA_real_,  header = NULL)write_annotation(data, annotator, record, record_dir = ".")

Arguments

record

String that will be used to name the WFDB record. Cannotinclude extensions, and is not a filepath. alphanumeric characters areacceptable, as well as hyphens (-) and underscores (_)

annotator

String that is the name of a WFDB-compatible annotationtype, serving as the extension for the file that is written containing thatannotation. Please seeread_annotation() andwrite_annotation() forfurther details.

record_dir

File path of directory that should be used read and writefiles. Defaults to current directory.

begin,end

Acharacter in the format ofHH:MM:SS that will be usedto help parse the time of the annotation. These parameters together createthe time range to extract. The default of0 is a shortcut for00:00:00.Theseconds argument can include a decimal place.

header

A header file is an optional named list of parameters thatwill be used to organize and describe the signal input from thedataargument. If thetype is given, specific additional elements will besearched for, such as the low or high pass filters, colors, or other signalattributes. At minimum, the following elements are required (as cannot becalculated):

  • frequency = sample frequency in Hertz asinteger

  • label = vector of names for each channel ascharacter

  • start_time = date/time object

data

Anannotation_table containing the 6 invariant columns requiredby theannotation_table() function

Value

This function will either read in an annotation using theread_annotation() function in the format of anannotation_table object, or write to file/disk anannotation_table to a WFDB-compatible annotation file using thewrite_annotation() function.

IMPORTANT: as annotation files are created by annotators that weredeveloped independently, there is a higher chance of an erroroneous filebeing created on disk. As such, this function will note an error an return anemptyannotation_table at times.

Annotation files

The following annotation file types are described below.

ecgpuwave

ecgpuwave analyzes an ECG signal from the specified record, detecting theQRS complexes and locating the beginning, peak, and end of the P, QRS, andST-T waveforms. The output of ecgpuwave is written as a standard WFDB-formatannotation file (the extension is "*.ecgpuwave", as would be expected). Thisfile can be converted into text format usingrdann. Further details aregiven at theECGPUWAVEpage.

Thetype column can bep,t, orN for the peak of the P wave, Twave, and QRS (R peak) directly. The output notation also includes waveformonset XXX and waveform offset XXX. Thenumber column gives furtherinformation about each of thesetype labels.

Thenumber column gives modifier information. If thetype classifieris a T wave annotation, thenumber column can be 0 (normal), 1(inverted), 2 (positive), 3 (negative), 4 (biphasic negative-positive), 5(biphasic positive-negative). If thetype is an waveform onset or offset,thennumber can be 0 (P wave), 1 (QRS complex), 2 (T wave).


I/O of WFDB-compatible signal & header files from EP recording systems

Description

This function allows for WFDB files to be read from any WFDB-compatiblesystem, and also allows writing out WFDB-compatible files from specific EPrecording systems, as indicated in the details section. Writing WFDB leads tocreation of both adat (signal) andhea (header) file. These are bothrequired for reading in files as well.

Usage

write_wfdb(  data,  record,  record_dir = ".",  header = NULL,  info_strings = list(),  units = c("digital", "physical"),  ...)read_wfdb(  record,  record_dir = ".",  annotator = NULL,  begin = 0,  end = NA_integer_,  interval = NA_integer_,  units = c("digital", "physical"),  channels = character(),  ...)read_signal(  record,  record_dir = ".",  header = NULL,  begin = 0,  end = NA_integer_,  interval = NA_integer_,  units = c("digital", "physical"),  channels = character(),  ...)read_header(record, record_dir = ".", ...)

Arguments

data

Can either be anegm object, or adata.frame (or similar)object. The function will appropriately set defaults based on the type.

  • egm = Will extract signal and header data directly from object, and thus is simplest to convert to a WFDB format

  • signal_table = This is a customizeddata.table class that has an invariant column containing sample information.

  • data.frame ordata.table = Must have a column that represents a time point or index, and columns that represent signal values (preferably integers)

record

String that will be used to name the WFDB record. Cannotinclude extensions, and is not a filepath. alphanumeric characters areacceptable, as well as hyphens (-) and underscores (_)

record_dir

File path of directory that should be used read and writefiles. Defaults to current directory.

header

A header file is an optional named list of parameters thatwill be used to organize and describe the signal input from thedataargument. If thetype is given, specific additional elements will besearched for, such as the low or high pass filters, colors, or other signalattributes. At minimum, the following elements are required (as cannot becalculated):

  • frequency = sample frequency in Hertz asinteger

  • label = vector of names for each channel ascharacter

  • start_time = date/time object

info_strings

Alist of strings that will be written as an appendixto the header file, usually containing information about the channels,(e.g. list of colors, extra labels, etc).

units

Acharacter string representing eitherdigital (DEFAULT) orphysicalunits that should be used for signal values.

  • "digital" = Returns raw ADC (analog-to-digital converter) counts as storedin the .dat file. These are integer values representing the digitized signalwithout any scaling applied. Use this to preserve exact round-trip fidelity.

  • "physical" = Returns signal values converted to physical units (e.g., mV)using the formula:physical = (digital - baseline) / gain, wherebaselineandgain are specified in the header file. This is the human-readable formatfor analysis.

...

Additional arguments to be passed to the function

annotator

String that is the name of a WFDB-compatible annotationtype, serving as the extension for the file that is written containing thatannotation. Please seeread_annotation() andwrite_annotation() forfurther details.

begin,end,interval

Timepoint as aninteger (representing seconds),which is converted to an index position based on sampling frequency. Thedefault is to start at the beginning of the record. Ifend orintervalare given, the earlier of the two will be returned. Theend argumentgives a time index to read until. Theinterval argument is the length oftime past the start point.

channels

Either the signal/channel in acharacter vector as a name or number.Allows for duplication of signal or to re-order signal if needed. Ifnothing is given, will default to all channels available.

Details

Thebegin,end, andinterval arguments are converted into samplepositions using the sampling frequency declared in the WFDB header. Thereader first determines the starting sample frombegin, then givesprecedence tointerval (when supplied) before falling back toend. Anyrequest that extends beyond the recorded range is clamped so that the callerstill receives all available data without a hard failure.

Value

Depends on if it is a reading or writing function. For writing, willoutput an WFDB-based object reflecting the function. For reading, willoutput an extension of adata.table object reflecting the underlyingfunction (e.g.signal_table() will return an object of class).

Functions

Recording systems

Type of signal data, as specified by the recording system, that are currentlysupported.


WFDB path utilities

Description

These functions are used to help find and locate commands from theinstallation of WFDB. They are helpful in setting and getting path optionsand specific WFDB commands. They are primarily internal helper functions, butare documented for troubleshooting purposes.

Usage

find_wfdb_software()set_wfdb_path(.path)find_wfdb_command(.app, .path = getOption("wfdb_path"))

Arguments

.path

Acharacter string that describes the path to the WFDB binarydirectory

.app

The name of WFDB software command or application as acharacter

Value

These functions are helper functions to work with the user-installedWFDB software. They do not always return an object, and are primarily usedfor their side effects. They are primarily developer functions, but areexposed to the user to help troubleshoot issues with their installation ofWFDB.


Window signal data based on different methods

Description

[Experimental]

Creates windows of signal data using various methods, such as rhythm patterns,time intervals, or reference points. Each window is returned as an individualegm object for further analysis.

Usage

window(object, window_method = c("rhythm"), ...)window_by_rhythm(  object,  rhythm_type = "sinus",  onset_criteria,  offset_criteria,  reference_criteria = NULL,  adjust_sample_indices = TRUE,  ...)

Arguments

object

Object of theegm class, which includes header, signalinformation, and annotation information.

window_method

Acharacter string specifying the windowing method.Options include:

  • rhythm - Windows based on rhythm patterns (requires rhythm_type and criteria)

...

Additional arguments passed to specific windowing methods.

rhythm_type

Acharacter string specifying the rhythm type (e.g.,"sinus"). Currently supported: "sinus" (requires reference check).

onset_criteria

A named list of criteria to identify onset points.Names should match column names in the annotation table.

offset_criteria

A named list of criteria to identify offset points.Names should match column names in the annotation table.

reference_criteria

A named list of criteria to identify referencepoints that must exist between onset and offset. Set to NULL to skipreference validation.

adjust_sample_indices

Logical, whether to adjust annotation sampleindices in the returned windows to be relative to the window start. Defaultis TRUE.

Details

This function provides a modular approach to windowing electrophysiologicalsignals. The method parameter determines the windowing strategy, with eachmethod requiring its own set of additional parameters.

Value

A list ofegm objects, each representing a window of the originalsignal.


Create awindowed object containing a list of egm segments

Description

[Experimental]

windowed objects are lists ofegm objects that represent segments orwindows of the original signal. This allows for specialized methods to beapplied to collections of signal windows. This function primarily serves asthe class generation function, and only applies class attributes. It is usedby thewindow() function to ensure appropriate class and properties.

Usage

windowed(  x = list(),  window_method = "rhythm",  source_record = character(),  ...)

Arguments

x

A list ofegm objects

window_method

The windowing method used to create the list

source_record

The name of the original record

...

Additional arguments passed to methods

Value

An object of classwindowed which inherits fromlist


[8]ページ先頭

©2009-2025 Movatter.jp