wfdisc 0.1.0

Reader for CSS 3.0 / NNSA KB Core wfdisc seismological waveform descriptor files. Cross-validated against ObsPy.
Documentation
//! Time helpers — Julian date (`YYYYDDD`), Gregorian YMD, and Unix epoch.
//!
//! CSS 3.0 stores trace start/end times as floating-point Unix epoch
//! seconds (`time`, `endtime`) and a redundant `jdate` integer of the form
//! `YYYYDDD` (year × 1000 + day-of-year). These helpers convert between
//! the three representations so callers do not need an extra time crate
//! for simple work.

use std::fmt;

/// A Julian date in the CSS 3.0 form `YYYYDDD`
/// (year × 1000 + 1-based day-of-year, 1..=366).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub struct JDate(pub i32);

impl JDate {
    /// The numeric year component (`YYYY`).
    pub const fn year(self) -> i32 {
        self.0 / 1000
    }

    /// The day-of-year component (`DDD`, 1-based, 1..=366).
    pub const fn doy(self) -> i32 {
        self.0 % 1000
    }
}

impl fmt::Display for JDate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:04}{:03}", self.year(), self.doy())
    }
}

/// `true` if `year` is a Gregorian leap year.
pub const fn is_leap_year(year: i32) -> bool {
    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
}

const MONTH_LENGTHS: [u32; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

const fn days_in_month(year: i32, month: u32) -> u32 {
    if month == 2 && is_leap_year(year) {
        29
    } else {
        MONTH_LENGTHS[(month - 1) as usize]
    }
}

/// Convert (`year`, `month`, `day`) to a [`JDate`].
///
/// Returns `None` if `month` is not 1..=12 or `day` is out of range for
/// the given month.
pub fn ymd_to_jdate(year: i32, month: u32, day: u32) -> Option<JDate> {
    if !(1..=12).contains(&month) {
        return None;
    }
    if day < 1 || day > days_in_month(year, month) {
        return None;
    }
    let mut doy: u32 = 0;
    let mut m: u32 = 1;
    while m < month {
        doy += days_in_month(year, m);
        m += 1;
    }
    doy += day;
    Some(JDate(year * 1000 + doy as i32))
}

/// Convert a [`JDate`] back to (`year`, `month`, `day`).
///
/// Returns `None` if the day-of-year is out of range for the year.
pub fn jdate_to_ymd(jdate: JDate) -> Option<(i32, u32, u32)> {
    let year = jdate.year();
    let mut doy = jdate.doy();
    if !(1..=366).contains(&doy) {
        return None;
    }
    if doy == 366 && !is_leap_year(year) {
        return None;
    }
    let mut month: u32 = 1;
    while month <= 12 {
        let dim = days_in_month(year, month) as i32;
        if doy <= dim {
            return Some((year, month, doy as u32));
        }
        doy -= dim;
        month += 1;
    }
    None
}

/// Days from year 1970-01-01 to `year-01-01`.
fn days_since_epoch_to_year(year: i32) -> i64 {
    let mut days: i64 = 0;
    if year >= 1970 {
        let mut y = 1970;
        while y < year {
            days += if is_leap_year(y) { 366 } else { 365 };
            y += 1;
        }
    } else {
        let mut y = year;
        while y < 1970 {
            days -= if is_leap_year(y) { 366 } else { 365 };
            y += 1;
        }
    }
    days
}

/// Convert Unix epoch seconds (UTC) to a [`JDate`].
///
/// Mirrors how Pisces / ObsPy derive `jdate` from the `time` field on a
/// wfdisc row.
pub fn jdate_from_epoch(epoch_seconds: f64) -> JDate {
    let total_days = (epoch_seconds / 86_400.0).floor() as i64;

    let mut year: i32 = 1970;
    let mut remaining = total_days;
    if remaining >= 0 {
        loop {
            let yd = if is_leap_year(year) { 366 } else { 365 };
            if remaining < yd as i64 {
                break;
            }
            remaining -= yd as i64;
            year += 1;
        }
    } else {
        while remaining < 0 {
            year -= 1;
            let yd = if is_leap_year(year) { 366 } else { 365 };
            remaining += yd as i64;
        }
    }
    let doy = (remaining as i32) + 1;
    JDate(year * 1000 + doy)
}

/// Convert (`year`, `month`, `day`, `hour`, `min`, `sec`) to Unix epoch
/// seconds.
pub fn ymd_hms_to_epoch(year: i32, month: u32, day: u32, hour: u32, min: u32, sec: f64) -> f64 {
    let day_index_in_year = ymd_to_jdate(year, month, day).map(|j| j.doy() - 1).unwrap_or(0);
    let day_index = days_since_epoch_to_year(year) + day_index_in_year as i64;
    (day_index as f64) * 86_400.0 + (hour as f64) * 3600.0 + (min as f64) * 60.0 + sec
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn leap_year_rules() {
        assert!(is_leap_year(2000));
        assert!(is_leap_year(2024));
        assert!(!is_leap_year(2100));
        assert!(!is_leap_year(2023));
    }

    #[test]
    fn jdate_components_and_display() {
        let j = JDate(2011031);
        assert_eq!(j.year(), 2011);
        assert_eq!(j.doy(), 31);
        assert_eq!(format!("{j}"), "2011031");
    }

    #[test]
    fn ymd_jan_1_is_doy_1() {
        assert_eq!(ymd_to_jdate(2011, 1, 1), Some(JDate(2011001)));
    }

    #[test]
    fn ymd_jan_31_2011_matches_test_data() {
        // The test wfdisc files all carry jdate=2011031 (Jan 31 2011).
        assert_eq!(ymd_to_jdate(2011, 1, 31), Some(JDate(2011031)));
    }

    #[test]
    fn ymd_handles_leap_year_feb_29() {
        assert_eq!(ymd_to_jdate(2024, 2, 29), Some(JDate(2024060)));
        assert_eq!(ymd_to_jdate(2023, 2, 29), None);
    }

    #[test]
    fn ymd_rejects_invalid_month_and_day() {
        assert!(ymd_to_jdate(2023, 0, 1).is_none());
        assert!(ymd_to_jdate(2023, 13, 1).is_none());
        assert!(ymd_to_jdate(2023, 1, 0).is_none());
        assert!(ymd_to_jdate(2023, 1, 32).is_none());
    }

    #[test]
    fn jdate_to_ymd_round_trips() {
        for &(y, m, d) in &[
            (2011, 1, 31),
            (2024, 2, 29),
            (2024, 12, 31),
            (1970, 1, 1),
            (2000, 3, 1),
        ] {
            let j = ymd_to_jdate(y, m, d).unwrap();
            assert_eq!(jdate_to_ymd(j), Some((y, m, d)));
        }
    }

    #[test]
    fn jdate_to_ymd_rejects_doy_366_in_non_leap() {
        assert!(jdate_to_ymd(JDate(2023366)).is_none());
        assert!(jdate_to_ymd(JDate(2024366)).is_some());
    }

    #[test]
    fn epoch_zero_is_1970_001() {
        assert_eq!(jdate_from_epoch(0.0), JDate(1970001));
    }

    #[test]
    fn epoch_for_test_data_is_2011_031() {
        // 1296474900.0 epoch seconds corresponds to 2011-01-31 11:55:00 UTC.
        assert_eq!(jdate_from_epoch(1_296_474_900.0), JDate(2011031));
    }

    #[test]
    fn epoch_round_trip_for_test_data() {
        let secs = ymd_hms_to_epoch(2011, 1, 31, 11, 55, 0.0);
        assert_eq!(secs, 1_296_474_900.0);
        assert_eq!(jdate_from_epoch(secs), JDate(2011031));
    }

    #[test]
    fn epoch_negative_pre_1970() {
        // 1969-12-31 00:00:00 UTC is one day before the epoch.
        let secs = ymd_hms_to_epoch(1969, 12, 31, 0, 0, 0.0);
        assert_eq!(secs, -86_400.0);
        assert_eq!(jdate_from_epoch(secs), JDate(1969365));
    }
}