A fast, lightweight implementation of the WFDB library and command-line tools, with identical behavior across seven programming languages
WFDB-x is a reimplementation of the WFDB Software Package (the library and its command-line tools) in seven languages: Python, C++, MATLAB/Octave, Rust, Julia, R and Kotlin, tested to give byte-for-byte identical results to the original C package and to each other. This is the Julia implementation. Website (wfdb-x.org) and the other languages · WFDB-x at a glance (overview figure) · Benchmarks · User’s manual (PDF) (chapter “Julia” for this language) · How to cite WFDB-x
WFDBX reads and writes physiological signal records in the WFDB format
used by PhysioNet. It is a complete Julia
implementation of the WFDB Software Package: the library and all of its
command-line tools. It reads and writes the same files as the original C
library, and its tools print the same output.
The package is pure Julia and uses only Julia’s standard libraries. It needs Julia 1.9 or later, and runs on Linux and macOS. Windows support is untested.
All three are written in Julia; none of them calls the C library.
read_record,
read_header, read_annotations, write_record,
write_record_physical, write_annotations and check_record read and
write whole records and annotation files as Julia matrices and vectors
(Matrix{Int32}, Vector{Int64}, …), in one call, with keyword
arguments, and throw a WfdbError on errors. They read signal files in
large blocks, so they are the fastest way to read a record.
read_metadata, set_metadata and the other
metadata functions read and change the Key: value
entries of a header. They are an addition of WFDB-x: the C package has
no equivalent. Use them for new code, analysis and notebooks.isigopen,
getvec, getann, putann, …), with the C behavior: sample by
sample and annotation by annotation, with errors reported by return
values. Use them to port a program written against the C library, or
for the exact C semantics.rdsamp, rdann, wrsamp, xform, and
29 others), with the options, output and exit status of the C tools, run
through the driver script bin/wfdbx.jl, or the short wfdbx alias of
Command-line tools (wfdbx rdsamp -r 100s). Use
them in shell scripts and pipelines, or to reproduce work done with the
original tools.The high-level functions return exactly the samples and annotations that the library functions (and the C library) give.
The package is installed from a copy of the repository. In Julia, run:
using Pkg
Pkg.develop(path="/path/to/wfdb-x/julia")
In the package REPL, ] dev /path/to/wfdb-x/julia does the same. The
package is loaded with using WFDBX. The first using WFDBX precompiles
the package. Later sessions and tool runs load it without compiling
anything.
The package is the directory julia/, which holds copies of the license
files (LICENSE, LICENSE-GPL) and of NOTICE (see
Authors and license), so that a copy of that
directory alone carries them.
The repository includes a sample record, 100s, in tests/data: the first
minute of record 100 of the
MIT-BIH Arrhythmia Database, with
two ECG signals at 360 Hz and its beat annotations.
using WFDBX
# Read the sample record from the repository's test data.
wfdbx_set_input_dir("/path/to/wfdb-x/tests/data")
rec = read_record("100s") # signals in ADC units
println(rec.fs, " ", String.(signal_names(rec)), " ", size(rec.samples))
# 360.0 ["MLII", "V5"] (21600, 2)
x = physical(rec) # signals in physical units
println(x[1, :]) # [-0.145, -0.065]
hdr = read_header("100s") # the header only, no samples
println(hdr.nsig, " ", hdr.nsamples) # 2 21600
ann = read_annotations("100s", "atr") # beat annotations
println(length(ann), " ", String.(ann.symbols[1:3]), " ", ann.samples[1:3])
# 75 ["+", "N", "N"] [18, 77, 370]
# Write the first 10 seconds as a new record in the current directory.
r10 = read_record("100s"; to="0:10")
write_record("copy", r10.samples, r10.fs; fmt=16, gains=[s.gain for s in r10.siginfo],
baselines=[s.baseline for s in r10.siginfo], adcres=11, units="mV",
names=signal_names(r10))
Each high-level function also accepts a Wfdb object as its first
argument, as in read_record(w, "100s"). It then uses the settings of that
object instead of the default ones (see
The WFDB library functions).
The examples in this section read the sample record 100s (the first
minute of record 100 of the MIT-BIH Arrhythmia Database, included with
WFDB-x in tests/data; see Quick start), with the input
directory set as there, and write their records and annotation files in the
current directory.
read_recordwfdbx_set_input_dir("/path/to/wfdb-x/tests/data") # where the sample record 100s is
rec = read_record("100s"; channels=["MLII"], from="0:10", to="0:20")
x = physical(rec)
| Argument | Meaning | Default |
|---|---|---|
record |
record name or path (see Where files are read and written) | |
channels |
signals to read, by number (0 is the first signal) or name (as in signal_names) |
all signals |
from, to |
first sample, and the sample after the last one: a sample number (a whole number; from is not negative) or a time string (see below) |
the whole record |
highres |
read a multi-frequency record at its highest sampling frequency | false |
pad |
replace invalid samples by the previous valid one | false |
checksum_warning |
warn when the data do not match the header’s checksums | true |
input_dir, network |
input directory and network access for this call only | the current settings |
legacy |
behave as the original package (see Legacy mode) | false |
An integer is a sample number. A string is a WFDB time string: "0:10"
(10 seconds), "1:02:03.5", "s3600" (sample 3600) or "e" (the end of
the record).
The result is a Record:
| Field | Contents |
|---|---|
samples |
Matrix{Int32} in ADC units, one row per sample and one column per signal |
fs |
sampling frequency in Hz (0 if the header gives none) |
siginfo |
the signal specifications (Siginfo objects): description desc, units, gain (ADC units per physical unit; 0 means uncalibrated), baseline, adcres, fmt, … |
channels |
the number of each returned signal in the record (0 is the first signal) |
name |
the record name |
sampfrom |
the number of the first sample returned |
base_time |
start time and date as text, to the second, such as "[14:00:03 21/06/2024]" |
base_time_ms |
start time in milliseconds after midnight, such as 50403500 for 14:00:03.500 |
base_date |
start date as (year, month, day) |
comments |
the info strings of the header, as bytes: its lines that begin with # after the record line (an empty or blank first line is not the record line), without the # |
checksum_ok |
false if the data do not match the header’s checksums |
base_time, base_time_ms and base_date are nothing when the header
does not give them. In siginfo, units is nothing and adcres is 0
when the header does not give them. Invalid samples are
WFDB_INVALID_SAMPLE.
Two functions help with a Record:
physical(rec) returns the samples in physical units, as a
Matrix{Float64}. Invalid samples become NaN.signal_names(rec) returns the description of each signal, as bytes,
without the white space that a header may put at either end of it. Use
String.(signal_names(rec)) to get strings.read_headerread_header(record) reads the header of a record without opening its
signal files. It returns a Header with these fields: name, fs,
counter_freq, base_counter, nsamples (0 if the header does not give
the length), nsig, siginfo, base_time, base_time_ms, base_date,
comments and metadata (the Key: value entries of the header, as
read_metadata returns them, from the .hea file only; empty for an EDF
record and for a header read from the standard input; see
Header metadata).
The others have the same meaning as in Record. It takes the
input_dir, network and legacy options of read_record.
hdr = read_header("100s")
for s in hdr.siginfo
println(String(s.desc), " ", s.fmt, " ", s.gain)
end
read_annotationsann = read_annotations("100s", "atr"; from="0:10", to="0:30")
The second argument is the annotator, the file suffix: "atr" reads
100s.atr. The fs option gives the sampling frequency when the record has
no header, or its header gives none. from, to, input_dir, network
and legacy are as in read_record. The result is an Annotations object,
in file order. length(ann) is the number of annotations.
| Field | Contents |
|---|---|
samples |
annotation times, in samples (Vector{Int64}) |
codes, symbols |
annotation codes (WFDBX.NORMAL, WFDBX.PVC, …) and their mnemonics ("N", "V", …) as bytes |
subtypes, chans, nums |
subtype, channel and annotator number of each annotation (Vector{Int32}) |
aux |
auxiliary text of each annotation as bytes, or nothing |
fs |
the frequency in which samples are counted (0 if unknown) |
record, annotator |
the names that were read |
write_recordwrite_record takes samples in ADC units. write_record_physical takes
samples in physical units and converts them with the given gains and
baselines. NaN is written as an invalid sample; an infinite value, or one
whose ADC value lies outside the range of Int32, is an error. Samples in
ADC units must also lie within that range.
x = randn(3600, 2) # random samples: the record "rand" is written by this example
write_record_physical("rand", x, 360; fmt=16, gains=1000, adcres=16, units="mV",
names=["A", "B"])
This writes the header rand.hea and the signal file rand.dat. The
sampling frequency, the gain and ADC resolution of each signal, and the
units of each calibrated signal are required; there are no defaults. A gain
of 0 marks a signal as uncalibrated, which is only allowed with
write_record; negative gains are allowed. The sampling frequency and the
gains must be finite. Per-signal options take one value for all signals, or
a vector with one value per signal; a vector of another length is an error.
The record name must not be empty, there must be at least one signal
(“write_record: at least one signal is required”), and base_time, if
given, must be a valid time (“write_record: incorrect base time ‘T’”).
adcres must be whole numbers >= 1, and adczeros and baselines whole
numbers, within the range of Int32 (integers, or finite floats with
whole values such as 12.0): otherwise “write_record: adcres must be whole
numbers within the range of a 32-bit integer” (and the same for adczeros
and baselines), also in legacy mode. Text (the record name, names,
units, comments) is written to the header as its bytes: a String as
its UTF-8 bytes, bytes as given.
Every sample must fit the storage format: a sample outside its range
(“write_record: signal 0 has a sample (40000) outside the range of format
16 (-32768 to 32767)”), in format 8 a sample more than 127 away from the
sample before it, or an invalid sample (format 8 has no invalid value),
and more than 8 signals in a FLAC format, which a FLAC file cannot hold,
throw a WfdbError before any file is touched. (Until 1.2.3, such samples
were silently wrapped around: 40000 read back as -25536.) The smallest
value of a format (-32768 in format 16, -2048 in format 212) is the value
of an invalid (missing) sample: samples equal to it, or to
WFDB_INVALID_SAMPLE, are read back as invalid, and write_record logs a
warning with @warn for them (“1 sample(s) of signal 0 will be read back
as invalid (missing) samples (format 16 stores an invalid sample as
-32768)”), except for the NaN samples of write_record_physical, which
mark missing samples deliberately; invalid_warning=false omits it.
| Argument | Meaning |
|---|---|
record |
record name (a trailing .hea is removed, as by the readers) |
samples |
matrix with one row per sample and one column per signal: integers for write_record, physical values for write_record_physical |
fs |
sampling frequency in Hz |
fmt |
storage format, such as 16, 212, 24 or 516 (FLAC; at most 8 signals); default 16. Every sample must fit it (above) |
gains, adcres, units |
gain, ADC resolution in bits, and physical units |
baselines, adczeros, names |
optional signal specifications |
base_time, comments |
start time ("hh:mm:ss dd/mm/yyyy") and info strings |
metadata |
Key: value entries, written after the comments as # Key: value: a vector of key => value pairs, or a dictionary (see Header metadata) |
samps_per_frame |
samples per frame of each signal, for a multi-frequency record |
dir |
existing directory in which to create the files |
legacy |
behave as the original package (see Legacy mode) |
invalid_warning |
false: no warning for the samples that will be read back as invalid; default true |
write_annotationsann = Annotations(samples=[100, 460, 820], symbols=[b"N", b"N", b"V"])
write_annotations("rand", "qrs", ann) # writes rand.qrs, for the record "rand" written above
The annotation types are given as symbols or as codes; for one
annotation or more, one of them is required (“write_annotations: symbols or
codes must be given”), and with no annotations an empty file is written.
Both may be given, as
read_annotations returns them, if they agree: each non-empty symbol must
be the mnemonic of the code at the same position (otherwise “symbols and
codes disagree at annotation K”, K counted from 0). subtypes, chans,
nums and aux are optional. Each of these fields is either empty or has
one element per annotation; any other length is an error, reported before
the file is touched. The codes must be from 0 to 58: 59 to 63 are the
control codes of the annotation file format (“write_annotations: annotation
code 61 is reserved (59 to 63 are the control codes of the annotation file
format)”), and other values are out of range (“write_annotations:
annotation code 64 is out of range (0 to 58)”). The times
typemin(Int64) and typemax(Int64) are reserved by the file format
(“write_annotations: annotation time T cannot be written (annotation times
must be integers from -9223372036854775807 to 9223372036854775806)”); any
other time can be written. As in C, the subtype, channel and annotator number are
stored in one byte each (other values wrap around). The fs option, 0
(none) or a finite frequency > 0, records the time resolution in the file;
ann.fs is not used. dir and legacy are as in
write_record.
If the annotations are not in time order, the file is sorted when it is
written. sort=false keeps the given order (without the library’s
advice to run sortann) and sort=true always sorts, for that call only.
Without sort, the WFDBANNSORT environment variable decides (sorting is
on unless it is 0).
Many datasets store facts about a recording in the header, as comment
lines of the form # Key: value, such as # Age: 63 or # Dx: 164889003.
These functions read and change them, without touching the rest of the
header. Keys and values are bytes (Vector{UInt8}), as all the text of a
header; String arguments are taken as their bytes.
read_metadata("rec") # ["Age" => "63", "Sex" => "F"] (as bytes)
get_metadata("rec", "age") # b"63" as a Vector{UInt8} (nothing if there is none)
set_metadata("rec", "Age", "64") # replaces the line, or adds "# Age: 64"
remove_metadata("rec", "Sex") # 1: the number of lines removed
update_metadata("rec", ["Age" => "65", "Dx" => nothing]) # several changes; nothing removes
getinfo reads it) that contains a colon. The record line is
the first line that holds something other than spaces, tabs and line
endings and does not begin with #, as the header parser finds it, in
every mode: an empty or blank line before it, and the comments before
it, are not read. The
key is the text before the first colon, the value the rest of the line,
both without spaces at either end: #Age:45, # Age: 45 and
# Age : 45 all give "Age" => "45". Comment lines without a colon are
free comments: they are not returned, and never changed. Only the .hea
file is read (not a .info file). read_metadata returns a
Vector{Pair{Vector{UInt8},Vector{UInt8}}} (MetadataEntry is the type
of its elements), in file order."age" finds
Age. A key must not be empty, and must not contain :, # or a line
break; it may contain spaces ("Date of birth"). If a header holds two
entries whose keys differ only in letter case (written by other
software), reading returns the first, and logs a warning with @warn;
set_metadata and update_metadata refuse to change that key
(ArgumentError), and remove_metadata removes both.# Key: value (# Key: if the value
is empty), with the spelling of the key given. A changed entry keeps its
position; a new one goes after the last comment line of the header. Every
other byte of the header is kept, including its line endings. The header
is replaced in one step (through a temporary file in its directory, which
then replaces it, keeping its permissions), and all the arguments are
checked first, so an error leaves it unchanged. If nothing changes,
nothing is written. update_metadata applies its changes in the order
given (a Dict in its iteration order, which is not defined).read_header finds it (input_dir
and network work the same way, for the call only). A change is written
to the header itself, or, with dir="...", to a header of the same name
in that existing directory (the signal files are not copied). A header
read from a URL can only be written elsewhere, with dir. For a
multi-segment record, the master header is read or changed, unless a
segment is named."-", a key given twice in
update_metadata, a header with no record line, or a header read from a
URL without dir) throws an ArgumentError, before anything is read or
written. A header that cannot be read or written, or a dir that does
not exist, throws a WfdbError (“can’t read header for record REC”,
“can’t write header for record REC”, “directory DIR does not exist”). In
write_record, invalid metadata throws a WfdbError (“write_record:
…”) before any file is created, as its other arguments do.Metadata often holds information about patients. WFDB-x stores it as plain
text, exactly as given, and does not de-identify it. The docstrings
(?set_metadata) give the full rules.
WfdbError. Its msg
field says what failed, such as “can’t read record 100x”. The library may
also print a message on the standard error. wfdbquiet() turns these
messages off.WfdbError: “can’t read signal data of record REC (getvec
status -3)”, also when the checksums do not match either (the C function
getvec then reports the checksum error, -4, for the incomplete last
frame); an incomplete frame is never returned. read_record allocates
memory for the samples as it reads them (at most 2^26 samples in
advance), not for the length that the header gives.WfdbError: “can’t read annotation file ANN of record REC (getann status
-3)”.WfdbError. For example, a time string such as
"0:10" needs the sampling frequency, and physical(rec) needs the gain
of each signal.ArgumentError for an invalid argument
and a WfdbError for a header that cannot be read or written (see
Header metadata).read_record
returns all the data and logs a warning with @warn: “checksum error in
record REC: the signal data do not match the checksums in its header”.
checksum_warning=false turns the warning off; rec.checksum_ok is
false either way. Checksums are only checked when a read reaches the end
of the record.write_record and write_record_physical throw a WfdbError if a
samps_per_frame value is not an integer >= 1 (“write_record:
samps_per_frame must hold integers >= 1”), or if the number of columns of
the samples is not their sum (“write_record: signals has N columns, but
samps_per_frame adds up to M”). These are checked before anything else,
and nothing is written.write_record, write_record_physical and write_annotations write
their files to temporary files in the destination directory
(.NAME.XXXXXXXX.tmp), renamed over the destinations once all of them
are complete: a failure while writing (a full disk, for example) leaves
the existing files as they were, and no temporary file is left. The
files replaced keep their permissions; a symbolic link keeps leading to
the file it leads to, which is replaced; a destination that is not a
regular file (a device) is written directly. An error that putann
reports is a write error of write_annotations.from in read_record or read_annotations, or a from or
to that is a number but not a whole one (a fraction, NaN or Inf),
throws a WfdbError (“read_annotations: from must be a whole number”),
before any file is opened. Whatever the outcome, read_record and
read_annotations close their input files before they return.read_record sets the getvec mode (highres, pad) for its own reading
only: the mode in force before the call is restored afterwards.write_record, write_record_physical and write_annotations throw a
WfdbError when a file cannot be written completely, for example on a
full disk: “write error on record REC”, “write error on annotator ANN for
record REC” (also in legacy mode).write_record
reads nothing, so it replaces any existing files of the same name.The high-level functions call wfdbquit() before and after their work, also
when they throw, which closes anything opened with the WFDB library
functions. The library’s settings (legacy mode, getvec mode, time resolution
of output annotators, input and output directories) are the same after a
call as before it, also after reading an EDF record, whose opening sets the
getvec mode and the time resolution, as in C.
check_recordreport = check_record("100s"; annotators=["atr"])
print(report)
check_record(record; annotators) checks the header of a record, its signal
specifications, every sample of its signal files, and the annotation files
named (annotators, a vector of names, or one name). It reports each
problem it finds. It never throws an exception for a problem in the record.
input_dir and network are as in read_record. It checks for problems
similar to those found by Benjamin Moody’s
wfdbcheck.
The result is a CheckReport. report.ok is true if there is no error.
report.issues lists the problems (Issues). Each has a severity, a
code (such as "checksum"), a where ("" for the record, "signal 1",
"segment s2", "annotator atr") and a message.
| Severity | Meaning |
|---|---|
error |
the record is damaged or does not follow the WFDB format: programs will read wrong data or fail |
warning |
the record can be read, but something is missing or unusual, and may give wrong results |
info |
a fact worth knowing, such as invalid (missing) samples |
Printed (print, show), the report has one line per problem, or the line
no problems found:
warning: signal 0: the units are not specified
error: signal 1: the checksum does not match: the header gives 12, the samples sum to 13
error: annotator atr: 3 annotations are out of order; the first is at sample 50, after sample 100
lines(report) returns these lines as a vector of strings. The lines are
the same in the seven languages of WFDB-x. The checks run in normal mode, even if legacy mode is on, and the library
prints no messages during the call.
What is checked:
The sample record 100s gives two warnings: its header gives no units.
WFDB-x reads and writes files exactly where they are named, and nowhere else:
| The name is | It is read from | It is written to |
|---|---|---|
a full path: /data/mitdb/100, C:\data\100 |
that path | that path |
a home path: ~/data/100 |
the user’s home directory | the user’s home directory |
a URL: https://.../100 |
that URL, if network access is on | (URLs cannot be written) |
anything else: 100, mitdb/100, ../data/100 |
the input directory | the output directory |
In this table, /data/mitdb stands for a local copy of the MIT-BIH
Arrhythmia Database, and 100 for its record 100.
The input and output directories are both the current directory unless they are set:
| Setting | Function | Option of the high-level functions | Environment variable |
|---|---|---|---|
input directory: a local directory, ~/... or a URL |
wfdbx_set_input_dir(d) |
input_dir= |
WFDBX_INPUT_DIR |
| output directory | wfdbx_set_output_dir(d) |
dir= |
WFDBX_OUTPUT_DIR |
| network access (off by default) | wfdbx_set_network(true) |
network=true |
WFDBX_NETWORK=1 |
A function call overrides the environment variable, and an option applies to
that one call. Each set function returns the previous setting.
wfdbx_get_input_dir(), wfdbx_get_output_dir() and wfdbx_get_network()
return the current settings. Directories are returned as bytes, or nothing
when none is set. Passing nothing to a set function restores the
default.
Here /data/mitdb stands for a local copy of the MIT-BIH Arrhythmia
Database:
wfdbx_set_input_dir("/data/mitdb") # a local copy of the MIT-BIH Arrhythmia Database
rec = read_record("100") # reads /data/mitdb/100.hea and 100.dat
mkpath("out")
ann = Annotations(samples=[100, 460], symbols=[b"N", b"N"])
write_annotations("100", "qrs", ann; dir="out") # writes out/100.qrs
The signal files that a header names are read from the header’s directory.
A record name is given without the .hea extension (the readers,
write_annotations and write_record also accept a trailing .hea, which
is removed). It is one of:
/data/mitdb/100) or in the home directory
(~/Documents/100s), used as given;100s, data/100s), read from the input directory if
one is set, otherwise from the current directory, and written to the
output directory if one is set, otherwise to the current directory
(missing directories are created);https://physionet.org/files/mitdb/1.0.0/100), read only if
network access is on; a URL cannot be written.The input_dir option is optional, and applies to relative names only, not
to full paths or URLs. A writer given a name with a path creates the files
in that directory, and the header names the record and its signal file
without the path (rec, rec.dat), so that the record opens under any
path that leads to it; in legacy mode, as in the original, the header gives
the name with its path. With the dir option, the name must be a plain
name (rec): the files are created in dir, and the record opens from that
directory under its plain name.
A record name is made of letters, digits, _, - and ~. / separates
directories, and the names of directories may contain any characters, such
as dots: my.data/rec is a valid record name, rec.1 is not. A name whose
last part contains a dot is the name of a file: 100s.hea is read as the
header of record 100s, and 100s.edf as an EDF file.
Records can be written under any such name: write_record("my.data/rec",
...) creates my.data/rec.hea and my.data/rec.dat. The header names the
record and its signal file without the directory (rec, rec.dat), so the
record can be read under any path that leads to it. Annotator names may
contain letters, digits, _, - and ~.
Set the input directory to the URL of the database and turn network access
on. The URL of a database is https://physionet.org/files/<database>/<version>/.
This example reads record 100 of the MIT-BIH Arrhythmia Database:
rec = read_record("100"; input_dir="https://physionet.org/files/mitdb/1.0.0/",
network=true)
A remote file that has been read is kept for the rest of the session; one
that could not be read is requested again the next time it is opened. A
download gives up when it cannot connect, or receives nothing, for 30
seconds. Only http:// and https:// URLs can be read: a name that begins
with another URL scheme, such as ftp:// or sftp://, is refused, with or
without network access, and never read as a local file name (mount the
server as a local folder, e.g. with sshfs or rclone, or download the files).
WFDB-x never assumes a sampling frequency, gain, ADC resolution or units
that a record does not give. Where one is needed, it must be given: in
write_record, as the fs option of read_annotations, or as an option of
the tools (see below). A record whose header gives no frequency has fs =
0. See
DIVERGENCES.md
for the reasons.
The tools are run through the driver script bin/wfdbx.jl. Its first
argument names the tool, and the other arguments go to the tool. The
examples in this section read the sample record 100s (the first minute of
record 100 of the MIT-BIH Arrhythmia Database, included with WFDB-x in
tests/data), from that directory as the input directory:
export WFDBX_INPUT_DIR=/path/to/wfdb-x/tests/data
julia --startup-file=no --project=/path/to/wfdb-x/julia \
/path/to/wfdb-x/julia/bin/wfdbx.jl rdsamp -r 100s -t 10
A small shell script, saved as wfdbx in a directory of the PATH, makes
this shorter:
#!/bin/sh
# wfdbx: run a WFDB-x tool, as in `wfdbx rdsamp -r 100s -t 10`
exec julia --startup-file=no --project=/path/to/wfdb-x/julia \
/path/to/wfdb-x/julia/bin/wfdbx.jl "$@"
The examples below use it:
wfdbx rdsamp -r 100s -t 10 -p # print the first 10 seconds, in physical units
wfdbx rdann -r 100s -a atr # print the annotations
The tools have the options and output of the original WFDB tools, which are
described in the WFDB Applications Guide
(third_party/wag.pdf).
WFDBX.tools() returns their names, and wfdbx --version prints the
version of WFDB-x (“WFDB-x 1.2.3”):
rdsamp, wrsamp, wfdbdesc, sigamp, snip, xform,
sampfreq, signame, signum, wfdbcat, wfdbwhichwfdbtime, time2secrdann, wrann, sortann, ann2rr, rr2annedf2mit, mit2edf, rdedfann, wav2mit, mit2wav,
wfdb2mat, a2m, m2a, ad2m, md2a, ahaecg2mit, makeid, readid,
revise, parsescpThe tools use the environment variables of the table above, also for the
files that they read or create themselves: the -i file of wrsamp,
edf2mit, wav2mit, a2m and ad2m, the input files of ahaecg2mit and
the -S script of xform are read from the input directory, and the WAV
file of mit2wav, the EDF file of mit2edf, the master header of snip -m
and the .des, .ecg, .key and .txt files of parsescp are created in
the output directory, as the records they read and write are. Such a file
cannot be read from a URL. wfdbx_input_path(name) and
wfdbx_output_path(name) return the path where a program of its own should
open such a file.
To read record 100 of the MIT-BIH Arrhythmia Database from PhysioNet:
export WFDBX_INPUT_DIR=https://physionet.org/files/mitdb/1.0.0/
export WFDBX_NETWORK=1
wfdbx rdsamp -r 100 -t 0:05
Tools that write signal parameters require them as options:
| Tool | Required options |
|---|---|
wrsamp (with -o) |
-F frequency, -G gain, -R ADC resolution, and -U units for calibrated signals |
wav2mit |
-G gain, and -U units unless the gain is 0 |
ad2m, ahaecg2mit |
-F, -G, -R, and -U unless the gain is 0 |
a2m, rdann, ann2rr, sortann, m2a |
-F frequency, when the record’s header does not give one |
For example, wfdbx wrsamp -F 250 -G 200 -R 16 -U mV -i samples.txt -o rec
writes the record rec from the text file samples.txt.
A tool can also run inside a Julia session. WFDBX.run_tool returns
its exit status and what it wrote to the standard output and the standard
error, as bytes (here, the tool runs in tests/data, where the sample record
100s is):
status, out, err = WFDBX.run_tool("rdsamp", ["-r", "100s", "-t", "s3"];
dir="/path/to/wfdb-x/tests/data")
print(String(out))
Every function of the WFDB library is available under its C name, with the
same arguments and return values, so programs and documentation written for
the C library carry over directly. Where a C function fills an array, the
Julia function fills a vector passed by the caller. The example reads the
sample record 100s (the first minute of record 100 of the MIT-BIH
Arrhythmia Database, included with WFDB-x in tests/data):
using WFDBX
wfdbx_set_input_dir("/path/to/wfdb-x/tests/data")
n = isigopen("100s", nothing, 0) # the number of signals (reads the header only)
si = [Siginfo() for _ in 1:n]
isigopen("100s", si, n) # open the signals; si receives their specifications
v = zeros(Int32, n)
for t in 0:9
getvec(v) > 0 || break # v receives one sample per signal
println(mstimstr(t), " ", v[1], " ", v[2])
end
a = Annotation()
annopen("100s", [Anninfo("atr", WFDB_READ)], 1)
while getann(0, a) == 0
println(a.time, " ", String(annstr(a.anntyp)))
end
wfdbquit()
Differences from C that come from the language:
The library state lives in a Wfdb object instead of global variables.
Every function takes one as an optional first argument. Without it, a
function uses the default object, lib(). Wfdb() creates an
independent one:
w = Wfdb()
wfdbx_set_input_dir(w, "/path/to/wfdb-x/tests/data")
sampfreq(w, "100s") # 360.0
Vector{UInt8}), because WFDB files are not
always UTF-8. Time and date strings (timstr, mstimstr, datstr) are
Strings. Arguments may be Strings or bytes. C’s NULL is nothing.WFDB_Sample and int are Int32, and
WFDB_Time and long are Int64.Siginfo, Calinfo, Anninfo, Annotation,
Seginfo) have the C field names. An annotation’s aux is nothing, or
bytes whose first byte is the length of the text that follows, as in C.getvecs(v, n) reads up to n sample vectors at once into v, as n
calls of getvec would, and returns the number it read (>= 0), or
the negative status of getvec if the first call failed (-1 at the end
of the data, < -1 on an error).wfdberror() returns the last message, and wfdbquiet() stops the
messages from being printed.wfdbquit() closes them; the directory and network settings are kept,
and so are the time resolution of output annotators (getafreq()),
which opening an EDF record sets to its sampling frequency when none is
set, and the getvec mode (getgvmode()), to which it adds
WFDB_HIGHRES, as in C. The high-level functions (read_record,
read_header, read_annotations, write_record,
write_record_physical, write_annotations, check_record) leave both
as they were.wfdbx_write_errors() returns the number of output files that the library
could not write, flush or close (found when it closes them), and
wfdbx_note_write_error() counts one more, for a file that a program
writes itself. The count belongs to the process (to one tool run, under
run_tool). The tools exit with status 1 after a write error, or when
the standard output cannot be written (“PROGRAM: write error on standard
output”); with --legacy, they keep the original exit status.The annotation codes (WFDBX.NORMAL, WFDBX.PVC, …) and the functions of
<wfdb/ecgmap.h> (isqrs, map1, map2, …) are also provided. Type
?getvec in the REPL for the documentation of a function.
Legacy mode reproduces the original WFDB package exactly, including its assumed signal parameters and its search for files. Use it only to reproduce old results:
--legacy as the first argument, as in wfdbx rdsamp --legacy -r 100s,
run in the directory of the sample record 100s (tests/data in a copy
of the repository). Legacy mode finds files through the WFDB path, which begins with the
current directory, and does not use the input directory (the files that
a tool reads itself are opened as named, relative to the current
directory); the output directory, if set, is a prefix of every output
name, those of the files that a tool creates itself included;legacy=true;wfdbx_set_legacy(true).DIVERGENCES.md describes what changes in legacy mode.
Vector{UInt8}. Use String(x)
or String.(v) to convert them.read_record and write_record work on whole blocks of
samples, and are the fastest way to read and write a record (in chunks,
with from and to, for records too large for memory). For code that
processes a record as a stream with the library functions, getvecs
reads many sample vectors in one call; a loop of getvec calls, one
sample vector each, is slower. After precompilation, the tools start
quickly; most of their startup time is Julia’s own.
BENCHMARKS.md
compares the seven languages and wfdb-python.From the root of the repository:
julia --startup-file=no --project=julia julia/test/runtests.jl # unit tests
python3 tests/conformance/harness.py check --impl julia -j8 # conformance suite
The conformance suite compares the output of every tool with that of the C implementation. DEVELOPING.md describes how the code is organized.
WFDB-x implements version 10.7.0 of the WFDB Software Package.
The WFDB library and tools were written by George B. Moody, with revisions by
Benjamin Moody and contributions from many others; parsescp was written by
George B. Moody and Edna S. Moody. Each source file names the authors of
the C code it implements, and
AUTHORS.md
gives the details. The Julia implementation was developed by Reza Sameni
(2026), through AI-assisted development, cross-language
verification and unit testing.
WFDB-x is an independent reimplementation. Its Julia code is a translation of the C code of the WFDB Software Package into Julia, written for WFDB-x; it is not code by the original WFDB developers. It follows the original’s logic and behavior, with the changes described in DIVERGENCES.md. The authors of the original C code are credited in each file and in AUTHORS.md.
The WFDB-x library is distributed under the GNU Lesser General Public
License, version 2.1 or (at your option) any later version
(LICENSE): programs under any license, proprietary ones
included, may use it on the LGPL’s terms. The command-line tools (the
apps and the wfdbx command), translations of the tools of the original
package, are distributed under the GNU General Public License, version 3 or
(at your option) any later version
(LICENSE-GPL). Each source file states its license.
The file
NOTICE,
copied into the package directory (julia/NOTICE) with both licenses
(julia/LICENSE, julia/LICENSE-GPL), summarizes this and gives the
copyright notice and license (BSD-3-Clause) of libFLAC 1.4.3, whose stream
decoder the FLAC decoder of WFDB-x translates.