wfdb 0.1.6

A library for decoding and encoding Waveform Database format files.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use chrono::{NaiveDate, NaiveTime};

use crate::{Error, Result};

/// Return type for parsed optional fields from a WFDB header record line.
///
/// __INTERNAL USE ONLY__
struct OptionalFields {
    sampling_frequency: Option<f64>,
    counter_frequency: Option<f64>,
    base_counter: Option<f64>,
    num_samples: Option<u64>,
    base_time: Option<NaiveTime>,
    base_date: Option<NaiveDate>,
}

/// Type of optional field detected by format.
///
/// __INTERNAL USE ONLY__
#[derive(Debug, Clone, Copy, PartialEq)]
enum FieldType {
    Frequency,
    NumSamples,
    Time,
    Date,
}

/// Parsing state for optional fields.
///
/// __INTERNAL USE ONLY__
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
enum ParseState {
    Start,
    AfterFrequency,
    AfterNumSamples,
    AfterTime,
    AfterDate,
}

/// Metadata from the WFDB header record line.
///
/// # Examples
///
/// Here are a few examples of a validated record line:
///
/// - `100 2 360 650000 12:00:00 01/01/2000` _refer to the example on
///   [WFDB website](https://wfdb.io/spec/header-files.html#record-line)_
/// - `my_record_0 12 500/100(50) 675000 14:49:37 07/06/2025`
/// - `24_record/2 4 102400` (Many fields are optional.)
/// - `rec 2 12:30:45 01/01/2000` (Optional fields can be omitted in the middle.)
#[derive(Debug, Clone, PartialEq)]
pub struct Metadata {
    /// Identifier for the record (letters, digits, underscores only).
    pub name: String,
    /// If present, appended as /n.  Indicates a multi-segment record.
    pub num_segments: Option<usize>,
    /// Number of signals described in the header.
    pub num_signals: usize,
    /// Samples per second (Hz) per signal.
    pub sampling_frequency: Option<f64>,
    /// Frequency (Hz) for counter (secondary clock).
    pub counter_frequency: Option<f64>,
    /// Offset value for counter.
    pub base_counter: Option<f64>,
    /// Total samples per signal.
    pub num_samples: Option<u64>,
    /// Start time of the recording (HH:MM:SS).
    pub base_time: Option<NaiveTime>,
    /// Start date of the recording (DD/MM/YYYY).
    pub base_date: Option<NaiveDate>,
}

impl Metadata {
    // [Default values for part of optional fields]

    /// Default sampling frequency (Hz) when omitted from the record line.
    pub const DEFAULT_SAMPLING_FREQUENCY: f64 = 250.0;

    /// Default base counter (Hz) when omitted from the record line.
    pub const DEFAULT_BASE_COUNTER: f64 = 0.0;

    // [Metadata decoding functions]

    /// Build a metadata from the record line (first line) of __WFDB__ header.
    ///
    /// # Errors
    ///
    /// Will return an error if the format of the record line is invalid.
    pub fn from_record_line(line: &str) -> Result<Self> {
        let line = line.trim();
        let mut parts = line.split_whitespace();

        // Resolve first part: record name (required) and number of segments (optional)
        let (name, num_segments) = Self::parse_record_name(
            parts
                .next()
                .ok_or_else(|| Error::InvalidHeader("Missing record name".to_string()))?,
        )?;

        // Resolve second part: number of signals (required)
        let num_signals = parts
            .next()
            .ok_or_else(|| Error::InvalidHeader("Missing number of signals".to_string()))?
            .parse()
            .map_err(|e| Error::InvalidHeader(format!("Invalid number of signals: {e}")))?;

        // Collect remaining optional fields
        let remaining: Vec<&str> = parts.collect();

        // Parse optional fields by detecting their format
        let optional_fields = Self::parse_optional_fields(&remaining)?;

        Ok(Self {
            name,
            num_segments,
            num_signals,
            sampling_frequency: optional_fields.sampling_frequency,
            counter_frequency: optional_fields.counter_frequency,
            base_counter: optional_fields.base_counter,
            num_samples: optional_fields.num_samples,
            base_time: optional_fields.base_time,
            base_date: optional_fields.base_date,
        })
    }

    /// Parse optional fields by detecting their format.
    fn parse_optional_fields(fields: &[&str]) -> Result<OptionalFields> {
        // Assign default values to all optional fields first
        let mut sampling_frequency = None;
        let mut counter_frequency = None;
        let mut base_counter = None;
        let mut num_samples = None;
        let mut base_time = None;
        let mut base_date = None;

        let mut state = ParseState::Start;

        for field in fields {
            let field_type = Self::detect_field_type(field, state)?;

            match field_type {
                FieldType::Frequency => {
                    (sampling_frequency, counter_frequency, base_counter) =
                        Self::parse_frequency_field(field)?;
                    state = ParseState::AfterFrequency;
                }
                FieldType::NumSamples => {
                    let n = field.parse().map_err(|e| {
                        Error::InvalidHeader(format!("Invalid number of samples: {e}"))
                    })?;
                    num_samples = Some(n);
                    state = ParseState::AfterNumSamples;
                }
                FieldType::Time => {
                    base_time = Self::parse_base_time(field)?;
                    state = ParseState::AfterTime;
                }
                FieldType::Date => {
                    base_date = Self::parse_base_date(field)?;
                    state = ParseState::AfterDate;
                }
            }
        }

        Ok(OptionalFields {
            sampling_frequency,
            counter_frequency,
            base_counter,
            num_samples,
            base_time,
            base_date,
        })
    }

    /// Detect the type of an optional field based on its format and current parse state.
    ///
    /// # Errors
    ///
    /// Returns an error if a field appears out of order or is duplicated.
    fn detect_field_type(field: &str, state: ParseState) -> Result<FieldType> {
        // Time: contains colon (HH:MM:SS)
        if field.contains(':') {
            if state >= ParseState::AfterTime {
                return Err(Error::InvalidHeader(
                    "Duplicate or out-of-order time field".to_string(),
                ));
            }
            return Ok(FieldType::Time);
        }

        // Date: DD/MM/YYYY pattern - contains two `/` separators
        if field.matches('/').count() == 2 {
            if state >= ParseState::AfterTime {
                if state >= ParseState::AfterDate {
                    return Err(Error::InvalidHeader(
                        "Duplicate or out-of-order date field".to_string(),
                    ));
                }
                return Ok(FieldType::Date);
            }
            return Err(Error::InvalidHeader(
                "Date field appears before time field".to_string(),
            ));
        }

        // Frequency with counter: contains single `/` or `(`
        if field.contains('/') || field.contains('(') {
            if state >= ParseState::AfterFrequency {
                return Err(Error::InvalidHeader(
                    "Duplicate or out-of-order frequency field".to_string(),
                ));
            }
            return Ok(FieldType::Frequency);
        }

        // Plain numeric field: frequency or num_samples based on state
        match state {
            ParseState::Start => Ok(FieldType::Frequency),
            ParseState::AfterFrequency => Ok(FieldType::NumSamples),
            _ => Err(Error::InvalidHeader(format!(
                "Unexpected numeric field '{field}' after time/date"
            ))),
        }
    }

    /// Parse record name and num of segments (optional).
    fn parse_record_name(field: &str) -> Result<(String, Option<usize>)> {
        let (name, num_segments) = match field.split_once('/') {
            Some((name, num_segments)) => {
                let num_segments = num_segments.parse().map_err(|e| {
                    Error::InvalidHeader(format!("Invalid number of segments: {e}"))
                })?;
                if num_segments == 0 {
                    return Err(Error::InvalidHeader(
                        "Number of segments must be greater than zero".to_string(),
                    ));
                }
                (name, Some(num_segments))
            }
            None => (field, None),
        };

        // The record name only contains letters, digits, and underscores
        if name.is_empty() {
            return Err(Error::InvalidHeader("Record name is empty".to_string()));
        }
        if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
            return Err(Error::InvalidHeader(format!(
                "Record name '{name}' contains invalid characters, expected letters, digits, and underscores"
            )));
        }

        Ok((name.to_string(), num_segments))
    }

    /// Parse frequency definitions (optional)
    fn parse_frequency_field(field: &str) -> Result<(Option<f64>, Option<f64>, Option<f64>)> {
        let (sampling_part, counter_part) = match field.split_once('/') {
            Some((s, c)) => (s, Some(c)),
            None => (field, None),
        };

        if sampling_part.is_empty() {
            return Err(Error::InvalidHeader(
                "Sampling frequency is empty".to_string(),
            ));
        }

        let sampling_frequency = Some(
            sampling_part
                .parse()
                .map_err(|e| Error::InvalidHeader(format!("Invalid sampling frequency: {e}")))?,
        );

        if let Some(sampling_frequency) = sampling_frequency
            && sampling_frequency <= 0.0
        {
            return Err(Error::InvalidHeader(format!(
                "Sampling frequency must be greater than zero, got {sampling_frequency}"
            )));
        }

        let (counter_frequency, base_counter) = match counter_part {
            Some(counter_str) => Self::parse_counter_frequency(counter_str)?,
            None => (None, None),
        };

        Ok((sampling_frequency, counter_frequency, base_counter))
    }

    /// Parse `counter_freq` or `counter_freq(base_counter)`
    fn parse_counter_frequency(field: &str) -> Result<(Option<f64>, Option<f64>)> {
        // Check for parentheses: counter_freq(base_counter)
        if let Some(paren_start) = field.find('(') {
            let paren_end = field.find(')').ok_or_else(|| {
                Error::InvalidHeader("Missing closing parenthesis in counter frequency".to_string())
            })?;

            let counter_freq = field[..paren_start]
                .parse()
                .map_err(|e| Error::InvalidHeader(format!("Invalid counter frequency: {e}")))?;

            let base_counter = field[paren_start + 1..paren_end]
                .parse()
                .map_err(|e| Error::InvalidHeader(format!("Invalid base counter value: {e}")))?;

            if counter_freq <= 0.0 {
                return Ok((None, None));
            }

            Ok((Some(counter_freq), Some(base_counter)))
        } else {
            let counter_freq = field
                .parse()
                .map_err(|e| Error::InvalidHeader(format!("Invalid counter frequency: {e}")))?;

            if counter_freq <= 0.0 {
                return Ok((None, None));
            }

            Ok((Some(counter_freq), None))
        }
    }

    /// Parse time in HH:MM:SS format
    fn parse_base_time(field: &str) -> Result<Option<NaiveTime>> {
        let time = NaiveTime::parse_from_str(field, "%H:%M:%S").map_err(|_| {
            Error::InvalidHeader(format!("Invalid base time '{field}', expected HH:MM:SS"))
        })?;
        Ok(Some(time))
    }

    /// Parse date in DD/MM/YYYY format
    fn parse_base_date(field: &str) -> Result<Option<NaiveDate>> {
        let date = NaiveDate::parse_from_str(field, "%d/%m/%Y").map_err(|_| {
            Error::InvalidHeader(format!("Invalid base date '{field}', expected DD/MM/YYYY"))
        })?;
        Ok(Some(date))
    }

    // [Accessors]

    /// Get the record name of the metadata.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the number of segments of the metadata.
    #[must_use]
    pub const fn num_segments(&self) -> Option<usize> {
        self.num_segments
    }

    /// Get the number of signals of the metadata.
    #[must_use]
    pub const fn num_signals(&self) -> usize {
        self.num_signals
    }

    /// Get the sampling frequency of the metadata.
    ///
    /// Fallback to the default sampling frequency when omitted.
    #[must_use]
    pub fn sampling_frequency(&self) -> f64 {
        self.sampling_frequency
            .unwrap_or(Self::DEFAULT_SAMPLING_FREQUENCY)
    }

    /// Get the counter frequency of the metadata.
    ///
    /// Fallback to the sampling frequency when omitted.
    #[must_use]
    pub fn counter_frequency(&self) -> f64 {
        self.counter_frequency
            .unwrap_or_else(|| self.sampling_frequency())
    }

    /// Get the base counter of the metadata.
    ///
    /// Fallback to the default base counter when omitted.
    #[must_use]
    pub fn base_counter(&self) -> f64 {
        self.base_counter.unwrap_or(Self::DEFAULT_BASE_COUNTER)
    }

    /// Get the number of samples of the metadata.
    #[must_use]
    pub const fn num_samples(&self) -> Option<u64> {
        self.num_samples
    }

    /// Get the base time of the metadata.
    #[must_use]
    pub const fn base_time(&self) -> Option<NaiveTime> {
        self.base_time
    }

    /// Get the base date of the metadata.
    #[must_use]
    pub const fn base_date(&self) -> Option<NaiveDate> {
        self.base_date
    }
}