wfdisc 0.1.0

Reader for CSS 3.0 / NNSA KB Core wfdisc seismological waveform descriptor files. Cross-validated against ObsPy.
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//! Streaming [`WfdiscReader`] over a wfdisc descriptor file.

use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};

use crate::error::{Error, Result};
use crate::samples::Samples;
use crate::wfdisc::{CSS_LINE_LEN, NNSA_LINE_LEN, Wfdisc};
use crate::DEFAULT_MAX_SAMPLE_BYTES;

/// Field layout variant for a wfdisc descriptor file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Schema {
    /// CSS 3.0 (Anderson et al. 1990). Lines are 283 characters.
    Css30,
    /// NNSA Knowledge Base Core schema. Lines are 287 characters; the
    /// `wfid`, `chanid`, `commid` and `lddate` columns are widened
    /// relative to CSS 3.0.
    NnsaKbCore,
    /// Whitespace-tokenized fallback used for real-world wfdisc files
    /// that do not match the canonical fixed-width layout (typical
    /// in real-world archives where `dir` is shortened, `lddate` is
    /// emitted as Oracle `DD-MON-YY` or epoch seconds, or the line is
    /// simply trimmed). Fields are recovered by ordinal position from
    /// whitespace-separated tokens.
    Loose,
}

/// Field positions for a single schema as `(start, end_exclusive)` pairs.
///
/// Slices are inclusive of `start` and exclusive of `end`, matching
/// Python's `line[start:end]` and Rust's `&line[start..end]`.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Positions {
    pub(crate) line_len: usize,
    pub(crate) sta: (usize, usize),
    pub(crate) chan: (usize, usize),
    pub(crate) time: (usize, usize),
    pub(crate) wfid: (usize, usize),
    pub(crate) chanid: (usize, usize),
    pub(crate) jdate: (usize, usize),
    pub(crate) endtime: (usize, usize),
    pub(crate) nsamp: (usize, usize),
    pub(crate) samprate: (usize, usize),
    pub(crate) calib: (usize, usize),
    pub(crate) calper: (usize, usize),
    pub(crate) instype: (usize, usize),
    pub(crate) segtype: (usize, usize),
    pub(crate) datatype: (usize, usize),
    pub(crate) clip: (usize, usize),
    pub(crate) dir: (usize, usize),
    pub(crate) dfile: (usize, usize),
    pub(crate) foff: (usize, usize),
    pub(crate) commid: (usize, usize),
    pub(crate) lddate: (usize, usize),
}

const CSS_POSITIONS: Positions = Positions {
    line_len: CSS_LINE_LEN,
    sta: (0, 6),
    chan: (7, 15),
    time: (16, 33),
    wfid: (34, 42),
    chanid: (43, 51),
    jdate: (52, 60),
    endtime: (61, 78),
    nsamp: (79, 87),
    samprate: (88, 99),
    calib: (100, 116),
    calper: (117, 133),
    instype: (134, 140),
    segtype: (141, 142),
    datatype: (143, 145),
    clip: (146, 147),
    dir: (148, 212),
    dfile: (213, 245),
    foff: (246, 256),
    commid: (257, 265),
    lddate: (266, 283),
};

const NNSA_POSITIONS: Positions = Positions {
    line_len: NNSA_LINE_LEN,
    sta: (0, 6),
    chan: (7, 15),
    time: (16, 33),
    wfid: (34, 43),
    chanid: (44, 53),
    jdate: (54, 62),
    endtime: (62, 79),
    nsamp: (80, 88),
    samprate: (89, 100),
    calib: (101, 117),
    calper: (118, 134),
    instype: (135, 141),
    segtype: (142, 143),
    datatype: (144, 146),
    clip: (147, 148),
    dir: (149, 213),
    dfile: (214, 246),
    foff: (247, 257),
    commid: (258, 267),
    lddate: (268, 287),
};

impl Schema {
    /// Auto-detect a fixed-width schema from a candidate line length.
    ///
    /// Returns `None` for the [`Schema::Loose`] fallback — that path is
    /// only chosen by the reader when no fixed-width schema matches.
    pub fn detect(line_len: usize) -> Option<Self> {
        match line_len {
            CSS_LINE_LEN => Some(Schema::Css30),
            NNSA_LINE_LEN => Some(Schema::NnsaKbCore),
            _ => None,
        }
    }

    /// Expected line length for fixed-width schemas. Returns `None` for
    /// [`Schema::Loose`].
    pub const fn line_len(self) -> Option<usize> {
        match self {
            Schema::Css30 => Some(CSS_LINE_LEN),
            Schema::NnsaKbCore => Some(NNSA_LINE_LEN),
            Schema::Loose => None,
        }
    }

    pub(crate) fn positions(self) -> Option<Positions> {
        match self {
            Schema::Css30 => Some(CSS_POSITIONS),
            Schema::NnsaKbCore => Some(NNSA_POSITIONS),
            Schema::Loose => None,
        }
    }
}

/// Streaming iterator over the rows of a wfdisc descriptor file.
///
/// The reader auto-detects CSS 3.0 vs. NNSA KB Core from the first
/// non-empty line and applies that schema to all subsequent rows. When
/// a fixed-width schema is locked via [`Self::with_schema`], every row
/// must match that schema's line length or parsing stops with
/// [`Error::MixedSchemaInLockedMode`] (lenient mode does not fall back
/// to [`Schema::Loose`] in that case). [`Schema::Loose`] locked via
/// [`Self::with_schema`] always tokenizes whitespace, even for
/// canonical-length lines.
///
/// By default the reader also runs in **lenient** mode when no schema
/// is locked: lines that do not match a canonical fixed-width schema
/// are recovered via [`Wfdisc::parse_loose`] (whitespace tokenization),
/// and lines with fewer than 20 tokens (Oracle SQL*Plus prompts,
/// banners) are silently skipped. Disable with [`Self::strict`] for
/// byte-exact CSS 3.0 / NNSA KB Core compliance.
///
/// Mirrors [`mseed::MSReader`](https://docs.rs/mseed) in shape: the type
/// implements `Iterator<Item = Result<Wfdisc>>`, lets you bind a
/// concrete reader (`open()`), and exposes the `path()` it was opened
/// from so callers can resolve relative `dir` columns.
#[derive(Debug)]
pub struct WfdiscReader<R: BufRead> {
    inner: R,
    base_dir: Option<PathBuf>,
    locked_schema: Option<Schema>,
    line_buf: String,
    eof: bool,
    lenient: bool,
    max_sample_bytes: usize,
}

impl WfdiscReader<BufReader<File>> {
    /// Open a wfdisc file from disk.
    ///
    /// The parent directory of `path` is recorded as the resolution base
    /// for relative `dir` columns (see [`Wfdisc::resolve_path`]).
    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        let file = File::open(path)?;
        let base_dir = path.parent().map(|p| p.to_path_buf());
        Ok(WfdiscReader {
            inner: BufReader::new(file),
            base_dir,
            locked_schema: None,
            line_buf: String::with_capacity(NNSA_LINE_LEN + 2),
            eof: false,
            lenient: true,
            max_sample_bytes: DEFAULT_MAX_SAMPLE_BYTES,
        })
    }
}

impl<R: BufRead> WfdiscReader<R> {
    /// Wrap an arbitrary buffered reader.
    pub fn new(reader: R) -> Self {
        WfdiscReader {
            inner: reader,
            base_dir: None,
            locked_schema: None,
            line_buf: String::new(),
            eof: false,
            lenient: true,
            max_sample_bytes: DEFAULT_MAX_SAMPLE_BYTES,
        }
    }

    /// Wrap an arbitrary reader, resolving relative `dir` columns
    /// against `base_dir`.
    pub fn new_with_base(reader: R, base_dir: impl AsRef<Path>) -> Self {
        WfdiscReader {
            inner: reader,
            base_dir: Some(base_dir.as_ref().to_path_buf()),
            locked_schema: None,
            line_buf: String::new(),
            eof: false,
            lenient: true,
            max_sample_bytes: DEFAULT_MAX_SAMPLE_BYTES,
        }
    }

    /// Maximum bytes for sample payloads and gzip skip offsets when reading
    /// waveforms through this reader (default [`DEFAULT_MAX_SAMPLE_BYTES`]).
    #[must_use]
    pub fn max_sample_bytes(mut self, max: usize) -> Self {
        self.max_sample_bytes = max;
        self
    }

    /// Read waveform samples for `row`, using this reader's [`Self::base_dir`]
    /// and [`Self::max_sample_bytes`].
    ///
    /// # Errors
    ///
    /// Same as [`Wfdisc::read_samples`], plus [`Error::SampleSizeExceeded`]
    /// when the row's payload exceeds the configured cap.
    pub fn read_samples(&self, row: &Wfdisc) -> Result<Samples> {
        let base = self
            .base_dir
            .as_deref()
            .unwrap_or_else(|| Path::new("."));
        row.read_samples_with_limit(base, self.max_sample_bytes)
    }

    /// Force a specific schema instead of auto-detecting.
    pub fn with_schema(mut self, schema: Schema) -> Self {
        self.locked_schema = Some(schema);
        self
    }

    /// Switch to byte-exact CSS 3.0 / NNSA KB Core compliance: any line
    /// whose length does not match a canonical schema yields
    /// [`Error::InvalidLineLength`], and no fallback parser is used.
    ///
    /// The reader is **lenient by default** because real-world
    /// real-world wfdiscs commonly drift from the spec.
    pub fn strict(mut self) -> Self {
        self.lenient = false;
        self
    }

    /// `true` when whitespace-tokenized recovery and skip-on-garbage are enabled.
    pub fn is_lenient(&self) -> bool {
        self.lenient
    }

    /// Directory used to resolve relative `dir` paths.
    pub fn base_dir(&self) -> Option<&Path> {
        self.base_dir.as_deref()
    }

    /// Schema currently in force, if one has been observed or set.
    pub fn schema(&self) -> Option<Schema> {
        self.locked_schema
    }

    fn read_line(&mut self) -> Result<Option<&str>> {
        loop {
            self.line_buf.clear();
            let n = self.inner.read_line(&mut self.line_buf)?;
            if n == 0 {
                self.eof = true;
                return Ok(None);
            }
            let trimmed = self
                .line_buf
                .trim_end_matches(['\r', '\n'])
                .trim_end_matches(' ')
                .len();
            // Skip fully blank lines.
            if trimmed == 0 {
                continue;
            }
            return Ok(Some(self.line_buf.trim_end_matches(['\r', '\n'])));
        }
    }
}

impl WfdiscReader<BufReader<File>> {
    /// Convenience: read every row into a `Vec`, returning the first
    /// parse error if any.
    pub fn read_all(self) -> Result<Vec<Wfdisc>> {
        self.collect()
    }
}

impl<R: BufRead> Iterator for WfdiscReader<R> {
    type Item = Result<Wfdisc>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if self.eof {
                return None;
            }
            let line = match self.read_line() {
                Ok(Some(l)) => l.to_string(),
                Ok(None) => return None,
                Err(e) => return Some(Err(e)),
            };

            if let Some(schema) = self.locked_schema {
                return Some(match schema {
                    Schema::Loose => {
                        let token_count = line.split_whitespace().count();
                        if token_count < 20 {
                            if self.lenient {
                                continue;
                            }
                            return Some(Err(Error::InvalidLineLength { got: line.len() }));
                        }
                        Wfdisc::parse_loose(&line)
                    }
                    Schema::Css30 | Schema::NnsaKbCore => {
                        let positions = schema.positions().expect("fixed-width schema");
                        if line.len() == positions.line_len {
                            Wfdisc::parse_with(&line, schema)
                        } else {
                            Err(Error::MixedSchemaInLockedMode {
                                got: line.len(),
                                schema,
                                expected: positions.line_len,
                            })
                        }
                    }
                });
            }

            // Try fixed-width detect.
            if let Some(schema) = Schema::detect(line.len()) {
                self.locked_schema = Some(schema);
                return Some(Wfdisc::parse_with(&line, schema));
            }

            // Lenient fallback: whitespace tokenization. Lines with too
            // few tokens (Oracle SQL*Plus prompts, banners, blank lines)
            // are silently skipped.
            if self.lenient {
                let token_count = line.split_whitespace().count();
                if token_count < 20 {
                    continue;
                }
                if self.locked_schema.is_none() {
                    self.locked_schema = Some(Schema::Loose);
                }
                return Some(Wfdisc::parse_loose(&line));
            }

            return Some(Err(Error::InvalidLineLength { got: line.len() }));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::DataType;
    use std::io::Cursor;

    const CSS_BYTES: &[u8] = include_bytes!("../tests/data/test_css.wfdisc");
    const NNSA_BYTES: &[u8] = include_bytes!("../tests/data/test_nnsa.wfdisc");

    #[test]
    fn iter_yields_six_rows_for_test_css() {
        let r = WfdiscReader::new(BufReader::new(Cursor::new(CSS_BYTES)));
        let rows: Vec<_> = r.collect::<Result<_>>().unwrap();
        assert_eq!(rows.len(), 6);
        assert_eq!(rows[0].schema, Schema::Css30);
    }

    #[test]
    fn iter_yields_six_rows_for_test_nnsa() {
        let r = WfdiscReader::new(BufReader::new(Cursor::new(NNSA_BYTES)));
        let rows: Vec<_> = r.collect::<Result<_>>().unwrap();
        assert_eq!(rows.len(), 6);
        assert_eq!(rows[0].schema, Schema::NnsaKbCore);
        assert_eq!(rows[5].chan, "HHN");
        assert_eq!(rows[5].datatype, DataType::I4);
    }

    #[test]
    fn schema_detect_recognises_known_lengths() {
        assert_eq!(Schema::detect(283), Some(Schema::Css30));
        assert_eq!(Schema::detect(287), Some(Schema::NnsaKbCore));
        assert_eq!(Schema::detect(100), None);
    }

    #[test]
    fn schema_line_len() {
        assert_eq!(Schema::Css30.line_len(), Some(283));
        assert_eq!(Schema::NnsaKbCore.line_len(), Some(287));
        assert_eq!(Schema::Loose.line_len(), None);
    }

    #[test]
    fn open_records_base_dir() {
        let path = Path::new("tests/data/test_css.wfdisc");
        let r = WfdiscReader::open(path).unwrap();
        assert_eq!(r.base_dir(), Some(Path::new("tests/data")));
    }

    #[test]
    fn skips_blank_lines() {
        let mut bytes: Vec<u8> = Vec::new();
        bytes.extend_from_slice(CSS_BYTES);
        bytes.extend_from_slice(b"\n\n   \n");
        let r = WfdiscReader::new(BufReader::new(Cursor::new(bytes)));
        let rows: Vec<_> = r.collect::<Result<_>>().unwrap();
        assert_eq!(rows.len(), 6);
    }

    #[test]
    fn malformed_line_surfaces_invalid_length_in_strict_mode() {
        let bytes = b"too short\n";
        let r = WfdiscReader::new(BufReader::new(Cursor::new(&bytes[..]))).strict();
        let err = r.collect::<Result<Vec<_>>>().unwrap_err();
        assert!(matches!(err, Error::InvalidLineLength { .. }));
    }

    #[test]
    fn lenient_default_skips_garbage_lines() {
        // Mimics an Oracle SQL*Plus spool prefix glued in front of real rows.
        let mut bytes: Vec<u8> = Vec::new();
        bytes.extend_from_slice(b"USER@db > spool off;\n");
        bytes.extend_from_slice(CSS_BYTES);
        let r = WfdiscReader::new(BufReader::new(Cursor::new(bytes)));
        let rows: Vec<_> = r.collect::<std::result::Result<Vec<_>, _>>().unwrap();
        assert_eq!(rows.len(), 6);
    }

    // Non-canonical "compact" CSS layout used in some real-world
    // exports: 32-char `dir` instead of 64, ASCII-int-style padding,
    // and an epoch-seconds `lddate`. Values are entirely synthetic
    // (round numbers, no real station, no real timestamp).
    const COMPACT_LINE: &str = "TEST01 BHZ       1000000000.00000       -1       -1  2001252  1000000009.99000     1000       100.0              1.0              1.0 -      - s4 - .                                synthetic.w                               0       -1  1000000000.00000\n";

    #[test]
    fn lenient_recovers_non_canonical_compact_line() {
        let r = WfdiscReader::new(BufReader::new(Cursor::new(COMPACT_LINE.as_bytes())));
        let rows: Vec<_> = r.collect::<std::result::Result<Vec<_>, _>>().unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].schema, Schema::Loose);
        assert_eq!(rows[0].sta, "TEST01");
        assert_eq!(rows[0].chan, "BHZ");
        assert_eq!(rows[0].nsamp, 1000);
        assert_eq!(rows[0].datatype, crate::DataType::S4);
        assert_eq!(rows[0].dfile, "synthetic.w");
        assert_eq!(rows[0].foff, 0);
    }

    #[test]
    fn strict_mode_rejects_non_canonical_line() {
        // Whitespace-collapsed synthetic single-space layout — also non-canonical.
        let line = "TEST01 BHZ 1000000000.0 -1 -1 2001252 1000000009.99 1000 100.0 1.0 1.0 - - s4 - . synthetic.w 0 -1 1000000000.0\n";
        let r = WfdiscReader::new(BufReader::new(Cursor::new(line.as_bytes()))).strict();
        let err = r.collect::<Result<Vec<_>>>().unwrap_err();
        assert!(matches!(err, Error::InvalidLineLength { .. }));
    }

    #[test]
    fn locked_schema_overrides_autodetect() {
        let r = WfdiscReader::new(BufReader::new(Cursor::new(CSS_BYTES)))
            .with_schema(Schema::Css30);
        let rows: Vec<_> = r.collect::<Result<_>>().unwrap();
        assert_eq!(rows.len(), 6);
    }

    #[test]
    fn locked_loose_schema_parses_fixed_width_lines_as_loose() {
        let r = WfdiscReader::new(BufReader::new(Cursor::new(CSS_BYTES)))
            .with_schema(Schema::Loose);
        let rows: Vec<_> = r.collect::<Result<_>>().unwrap();
        assert_eq!(rows.len(), 6);
        assert!(rows.iter().all(|r| r.schema == Schema::Loose));
    }

    #[test]
    fn locked_css_schema_rejects_mismatched_length_in_lenient_mode() {
        let r = WfdiscReader::new(BufReader::new(Cursor::new(COMPACT_LINE.as_bytes())))
            .with_schema(Schema::Css30);
        let err = r.collect::<Result<Vec<_>>>().unwrap_err();
        assert!(matches!(
            err,
            Error::MixedSchemaInLockedMode {
                schema: Schema::Css30,
                expected: 283,
                ..
            }
        ));
    }
}