Skip to main content

xue/
level3.rs

1//! Reading one NEXRAD Level 3 digital radial product (N0B, N0G) into a sweep
2//! on the fixed 0.5° beam grid.
3//!
4//! A port of the Python reference `xuebuild/nexrad/level3.py::read_sweep`,
5//! which the polar store is built from: the browser reads a live site's
6//! newest sweeps straight from the public Level 3 bucket with this, and must
7//! accept, refuse and bin exactly what the store's builder does, so a live
8//! sweep and a stored one of the same file are the same codes.
9//!
10//! The layout is the WSR-88D RPG-to-class-1-user ICD (2620001): a WMO
11//! abbreviated heading, the 18-byte message header, the 102-byte product
12//! description block, and the product symbology block — bzip2-compressed when
13//! the description block says so — whose one layer is a packet 16 (digital
14//! radial data array). Codes are copied, never requantized: the threshold
15//! words must state the codebook `docs/nexrad.md` §2 fixes, or the file is
16//! refused. Every offset is bounds-checked, and the only allocations are the
17//! decompressed body, capped before it grows, and the code grid, whose size
18//! the product code fixes rather than the file.
19
20use std::io::Read;
21
22use crate::format::{err, DecodeError};
23
24/// Beams on the fixed grid; beam `j` covers `[0.5 j, 0.5 (j + 1))` degrees
25/// from north.
26pub const LEVEL3_BEAMS: usize = 720;
27const BEAM_WIDTH: f64 = 0.5;
28
29const HEADER_BYTES: usize = 18;
30const DESCRIPTION_BYTES: usize = 102;
31const PACKET_DIGITAL_RADIAL: u16 = 16;
32
33/// The symbology block a 720 × 1840 sweep needs is about 1.3 MB; anything
34/// past this is not a product this reader accepts, and stopping here keeps a
35/// bzip2 bomb from growing the heap.
36const MAX_BODY_BYTES: u64 = 16 << 20;
37
38/// Unix seconds of the ICD's day 0, 31 December 1969: day 1 is 1 January 1970.
39const EPOCH_DAY_ZERO: i64 = -86_400;
40
41/// One accepted product: `(product code, gates, minimum ×10, increment ×10,
42/// levels)`. The threshold words must equal these exactly — −32.0 dBZ /
43/// −63.5 m/s, a 0.5 increment and 254 levels over codes 2–255.
44const PRODUCTS: [(u16, &str, u32, i16, i16, i16); 2] = [
45    (153, "n0b", 1840, -320, 5, 254),
46    (154, "n0g", 1200, -635, 5, 254),
47];
48
49/// One Level 3 sweep, its header facts, and its codes on the beam grid.
50#[derive(Debug, Clone, PartialEq)]
51pub struct Level3Sweep {
52    /// 153 (N0B) or 154 (N0G).
53    pub product_code: u16,
54    /// Gates per beam: 1840 for N0B, 1200 for N0G.
55    pub gates: u32,
56    /// The sweep's own start in Unix seconds (a supplemental SAILS sweep's,
57    /// not its volume's).
58    pub scan_time: i64,
59    /// Degrees.
60    pub elevation: f32,
61    pub latitude: f64,
62    pub longitude: f64,
63    pub height_m: f64,
64    pub vcp: i16,
65    pub volume_number: i16,
66    pub elevation_number: i16,
67    /// `720 × gates` bytes, beam-major; a beam the file does not carry is
68    /// code 0.
69    pub codes: Vec<u8>,
70}
71
72fn be_i16(data: &[u8], offset: usize) -> Option<i16> {
73    let bytes = data.get(offset..offset.checked_add(2)?)?;
74    Some(i16::from_be_bytes([bytes[0], bytes[1]]))
75}
76
77fn be_u16(data: &[u8], offset: usize) -> Option<u16> {
78    be_i16(data, offset).map(|value| value as u16)
79}
80
81/// ICD halfword `number` (10 … 60) of the product description block, signed.
82/// The block is exactly 102 bytes, so every number in range is in bounds.
83fn halfword(block: &[u8], number: usize) -> i16 {
84    let offset = (number - 10) * 2;
85    i16::from_be_bytes([block[offset], block[offset + 1]])
86}
87
88/// The 32-bit value in halfwords `number` and `number + 1`, unsigned.
89fn word(block: &[u8], number: usize) -> u32 {
90    let offset = (number - 10) * 2;
91    u32::from_be_bytes([
92        block[offset],
93        block[offset + 1],
94        block[offset + 2],
95        block[offset + 3],
96    ])
97}
98
99fn find(data: &[u8], needle: &[u8], from: usize) -> Option<usize> {
100    data.get(from..)?
101        .windows(needle.len())
102        .position(|window| window == needle)
103        .map(|position| position + from)
104}
105
106/// Offset of the message header: past the two CR CR LF lines of the WMO
107/// abbreviated heading when the file starts with four letters, else 0.
108fn skip_wmo_heading(data: &[u8]) -> Result<usize, DecodeError> {
109    if data.len() < 4 || !data[..4].iter().all(u8::is_ascii_alphabetic) {
110        return Ok(0);
111    }
112    let malformed = || err("Level 3 file has a malformed WMO heading");
113    let first = find(data, b"\r\r\n", 0).ok_or_else(malformed)?;
114    let second = find(data, b"\r\r\n", first + 3).ok_or_else(malformed)?;
115    if second > 64 {
116        return Err(malformed());
117    }
118    Ok(second + 3)
119}
120
121/// Parse one Level 3 N0B / N0G file's bytes.
122pub fn read_level3(data: &[u8]) -> Result<Level3Sweep, DecodeError> {
123    let start = skip_wmo_heading(data)?;
124    let description = data
125        .get(start + HEADER_BYTES..start + HEADER_BYTES + DESCRIPTION_BYTES)
126        .filter(|block| halfword(block, 10) == -1)
127        .ok_or_else(|| err("Level 3 file has no product description block"))?;
128    let code = halfword(description, 16);
129    let &(product_code, product, gates, minimum, increment, levels) = PRODUCTS
130        .iter()
131        .find(|entry| i32::from(entry.0) == i32::from(code))
132        .ok_or_else(|| {
133            err(format!(
134                "Level 3 product {code} is not one this product carries"
135            ))
136        })?;
137    let thresholds = (
138        halfword(description, 31),
139        halfword(description, 32),
140        halfword(description, 33),
141    );
142    if thresholds != (minimum, increment, levels) {
143        return Err(err(format!(
144            "Level 3 {product} thresholds {thresholds:?} are not the codebook (min, step, levels) {:?}",
145            (minimum, increment, levels)
146        )));
147    }
148    let days = i64::from(halfword(description, 21));
149    let seconds = i64::from(word(description, 22));
150    let scan_time = EPOCH_DAY_ZERO + days * 86_400 + seconds;
151
152    let raw = &data[start + HEADER_BYTES + DESCRIPTION_BYTES..];
153    let decompressed;
154    let body = match halfword(description, 51) {
155        0 => raw,
156        1 => {
157            decompressed = bunzip(raw, product)?;
158            &decompressed[..]
159        }
160        other => {
161            return Err(err(format!(
162                "Level 3 {product} uses compression method {other}"
163            )))
164        }
165    };
166    let codes = read_radials(body, gates as usize, product)?;
167    Ok(Level3Sweep {
168        product_code,
169        gates,
170        scan_time,
171        elevation: f32::from(halfword(description, 30)) / 10.0,
172        latitude: f64::from(word(description, 11) as i32) / 1000.0,
173        longitude: f64::from(word(description, 13) as i32) / 1000.0,
174        height_m: f64::from(halfword(description, 15)) * 0.3048,
175        vcp: halfword(description, 18),
176        volume_number: halfword(description, 20),
177        elevation_number: halfword(description, 29),
178        codes,
179    })
180}
181
182/// Every concatenated bzip2 stream, as Python's `bz2.decompress` reads them.
183fn bunzip(raw: &[u8], product: &str) -> Result<Vec<u8>, DecodeError> {
184    let mut body = Vec::new();
185    bzip2::read::MultiBzDecoder::new(raw)
186        .take(MAX_BODY_BYTES + 1)
187        .read_to_end(&mut body)
188        .map_err(|error| err(format!("Level 3 {product} symbology is not bzip2: {error}")))?;
189    if body.len() as u64 > MAX_BODY_BYTES {
190        return Err(err(format!(
191            "Level 3 {product} symbology exceeds {MAX_BODY_BYTES} bytes"
192        )));
193    }
194    Ok(body)
195}
196
197/// The symbology block's one packet 16, binned by beam centre onto the fixed
198/// 0.5° grid.
199fn read_radials(body: &[u8], gates: usize, product: &str) -> Result<Vec<u8>, DecodeError> {
200    if body.len() < 16 || be_i16(body, 0) != Some(-1) || be_i16(body, 2) != Some(1) {
201        return Err(err(format!(
202            "Level 3 {product} has no product symbology block"
203        )));
204    }
205    if be_i16(body, 8) != Some(1) || be_i16(body, 10) != Some(-1) {
206        return Err(err(format!(
207            "Level 3 {product} symbology must hold exactly one layer"
208        )));
209    }
210    let truncated = || err(format!("Level 3 {product} radial data is truncated"));
211    // Past the block header (10 bytes) and the layer header (6).
212    let offset = 16;
213    let packet = be_u16(body, offset).ok_or_else(truncated)?;
214    if packet != PACKET_DIGITAL_RADIAL {
215        return Err(err(format!(
216            "Level 3 {product} carries packet {packet}, not a digital radial array"
217        )));
218    }
219    let first_bin = be_i16(body, offset + 2).ok_or_else(truncated)?;
220    let bins = be_i16(body, offset + 4).ok_or_else(truncated)?;
221    let radials = be_i16(body, offset + 12).ok_or_else(truncated)?;
222    if first_bin != 0 || i64::from(bins) != gates as i64 {
223        return Err(err(format!(
224            "Level 3 {product} has {bins} gates from {first_bin}, not {gates} from 0"
225        )));
226    }
227    let mut codes = vec![0u8; LEVEL3_BEAMS * gates];
228    let mut filled = [false; LEVEL3_BEAMS];
229    let mut position = offset + 14;
230    for _ in 0..radials.max(0) {
231        let length = be_i16(body, position).ok_or_else(truncated)?;
232        let start_angle = be_i16(body, position + 2).ok_or_else(truncated)?;
233        let delta_angle = be_i16(body, position + 4).ok_or_else(truncated)?;
234        position += 6;
235        // A radial's bytes are read as `gates` codes from its start whatever
236        // its length says, as the reference reads them; the length only
237        // steps to the next radial, and stepping backwards is refused.
238        let length = usize::try_from(length).map_err(|_| truncated())?;
239        let end = position.checked_add(gates).ok_or_else(truncated)?;
240        let values = body.get(position..end).ok_or_else(truncated)?;
241        position = position.checked_add(length).ok_or_else(truncated)?;
242        let centre =
243            ((f64::from(start_angle) + f64::from(delta_angle) / 2.0) / 10.0).rem_euclid(360.0);
244        // Exact: the beam width is a power of two, so the division rounds
245        // nothing and floor matches Python's float floor division.
246        let beam = ((centre / BEAM_WIDTH).floor() as usize) % LEVEL3_BEAMS;
247        if filled[beam] {
248            return Err(err(format!(
249                "Level 3 {product} has two radials in beam {beam}"
250            )));
251        }
252        filled[beam] = true;
253        codes[beam * gates..(beam + 1) * gates].copy_from_slice(values);
254    }
255    Ok(codes)
256}