Skip to main content

xue/encode/
quantize.rs

1//! Xue v1 quantization codebooks — the port of `xuebuild/quantize.py`.
2//!
3//! A codebook is built from the `quantization.<profile>` block of a
4//! variable's registry entry, exactly as the metadata writes it, and hands
5//! the block back verbatim for the metadata (`Codebook::metadata`), so a
6//! store's `attributes.xue` is the document's block byte for byte. The port
7//! of `codebook_from_metadata` in `xuebuild/quantize.py`, refusals included.
8//!
9//! A code is a byte unless the codebook's nodata code is above 255: a
10//! series codebook (the registry's `seriesQuantization`) holds sixteen-bit
11//! codes, quantized by [`LinearCodebook::quantize_wide`]. Which width a
12//! block may take is for its reader to say (a profile's codebook is bytes,
13//! `Registry`), so the parse here accepts any code from 0 to 65535, as
14//! `codebook_from_metadata` does.
15//!
16//! All rounding is round-half-up: `round(x) = floor(x + 0.5)`. Every rounded
17//! quantity here is non-negative, so this equals round-half-away-from-zero.
18//! Round-half-even (Rust's `f64::round_ties_even`, and the IEEE 754 default)
19//! must not be used; it changes codes for values landing exactly on a half
20//! step.
21
22use serde_json::{Map, Value};
23
24use crate::encode::errors::{EncodeError, Result};
25
26/// Linear codebook, uint8 unless its nodata code needs sixteen bits. Not
27/// temperature-specific: it quantizes any linear field; the wind components
28/// reuse it with a symmetric m/s range.
29#[derive(Debug, Clone)]
30pub struct LinearCodebook {
31    pub minimum: f64,
32    /// `minimum + maximum_code × step`, the top of the clamp.
33    pub maximum: f64,
34    pub step: f64,
35    pub nodata_code: u16,
36    /// The variable's id, for the error a non-finite plane raises.
37    pub name: String,
38}
39
40impl LinearCodebook {
41    pub fn maximum_code(&self) -> u16 {
42        ((self.maximum - self.minimum) / self.step + 0.5).floor() as u16
43    }
44
45    pub fn quantize(&self, values: &[f64], codes: &mut [u8]) -> Result<()> {
46        debug_assert_eq!(values.len(), codes.len());
47        for (value, code) in values.iter().zip(codes.iter_mut()) {
48            if !value.is_finite() {
49                return Err(EncodeError::conversion(format!(
50                    "{} plane contains non-finite values",
51                    self.name
52                )));
53            }
54            let clamped = value.clamp(self.minimum, self.maximum);
55            *code = ((clamped - self.minimum) / self.step + 0.5).floor() as u8;
56        }
57        Ok(())
58    }
59
60    /// Sixteen-bit codes: the arithmetic of [`quantize`](Self::quantize),
61    /// rounding and clamp included, with the wider cast the reference's
62    /// `code_dtype` picks for a nodata code above 255.
63    pub fn quantize_wide(&self, values: &[f64], codes: &mut [u16]) -> Result<()> {
64        debug_assert_eq!(values.len(), codes.len());
65        for (value, code) in values.iter().zip(codes.iter_mut()) {
66            if !value.is_finite() {
67                return Err(EncodeError::conversion(format!(
68                    "{} plane contains non-finite values",
69                    self.name
70                )));
71            }
72            let clamped = value.clamp(self.minimum, self.maximum);
73            *code = ((clamped - self.minimum) / self.step + 0.5).floor() as u16;
74        }
75        Ok(())
76    }
77
78    pub fn decode(&self, code: u8) -> f64 {
79        self.decode_wide(u16::from(code))
80    }
81
82    pub fn decode_wide(&self, code: u16) -> f64 {
83        self.minimum + f64::from(code) * self.step
84    }
85}
86
87/// Logarithmic (`log1p`) codebook: sparse, long-tailed fields keep their
88/// light-rain resolution. Not precipitation-specific either: it quantizes
89/// any one-sided field whose interesting range spans orders of magnitude —
90/// the aerosol optical depth, the particulate matter concentrations and a
91/// river's discharge reuse it with their own trace, scale and maximum.
92#[derive(Debug, Clone)]
93pub struct PrecipitationCodebook {
94    pub trace: f64,
95    pub scale: f64,
96    pub maximum: f64,
97    pub maximum_code: u16,
98    pub overflow_code: u16,
99    pub nodata_code: u16,
100    pub name: String,
101}
102
103impl PrecipitationCodebook {
104    fn lo(&self) -> f64 {
105        (self.trace / self.scale).ln_1p()
106    }
107
108    fn hi(&self) -> f64 {
109        (self.maximum / self.scale).ln_1p()
110    }
111
112    fn span(&self) -> f64 {
113        f64::from(self.maximum_code - 1)
114    }
115
116    pub fn quantize(&self, values: &[f64], codes: &mut [u8]) -> Result<()> {
117        debug_assert_eq!(values.len(), codes.len());
118        let (lo, hi, span) = (self.lo(), self.hi(), self.span());
119        for (rate, code) in values.iter().zip(codes.iter_mut()) {
120            if !rate.is_finite() {
121                return Err(EncodeError::conversion(format!(
122                    "{} plane contains non-finite values",
123                    self.name
124                )));
125            }
126            let unit = ((rate.clamp(0.0, self.maximum) / self.scale).ln_1p() - lo) / (hi - lo);
127            let quantized = 1.0 + (span * unit + 0.5).floor();
128            let clamped = quantized.clamp(1.0, f64::from(self.maximum_code)) as u8;
129            *code = if *rate < self.trace {
130                0
131            } else if *rate > self.maximum {
132                self.overflow_code as u8
133            } else {
134                clamped
135            };
136        }
137        Ok(())
138    }
139}
140
141#[derive(Debug, Clone)]
142pub enum Book {
143    Linear(LinearCodebook),
144    Precipitation(PrecipitationCodebook),
145}
146
147/// One profile's codebook for one variable: the arithmetic, and the block
148/// it was read from.
149#[derive(Debug, Clone)]
150pub struct Codebook {
151    pub book: Book,
152    block: Map<String, Value>,
153}
154
155impl Codebook {
156    /// The codebook a `quantization` block describes (the inverse of
157    /// `metadata`). Refuses a block whose code range does not follow from
158    /// its own parameters, since then it does not say one thing. Mirrors
159    /// `codebook_from_metadata` in `xuebuild/quantize.py`, check for check.
160    pub fn from_metadata(block: &Map<String, Value>, name: &str) -> Result<Codebook> {
161        let number = |key: &str| -> Result<f64> {
162            block
163                .get(key)
164                .and_then(Value::as_f64)
165                .filter(|value| value.is_finite())
166                .ok_or_else(|| {
167                    EncodeError::conversion(format!(
168                        "{name} quantization {key} must be a finite number"
169                    ))
170                })
171        };
172        let code = |key: &str| -> Result<u16> {
173            block
174                .get(key)
175                .and_then(Value::as_u64)
176                .filter(|value| *value <= u64::from(u16::MAX))
177                .map(|value| value as u16)
178                .ok_or_else(|| {
179                    EncodeError::conversion(format!(
180                        "{name} quantization {key} must be a code from 0 to 65535"
181                    ))
182                })
183        };
184        let book = match block.get("type").and_then(Value::as_str) {
185            Some("linear") => {
186                let step = number("scale")?;
187                if step <= 0.0 || code("minimumCode")? != 0 {
188                    return Err(EncodeError::conversion(format!(
189                        "{name} linear quantization needs a positive scale and minimumCode 0"
190                    )));
191                }
192                let offset = number("offset")?;
193                let maximum_code = code("maximumCode")?;
194                let codebook = LinearCodebook {
195                    minimum: offset,
196                    maximum: offset + f64::from(maximum_code) * step,
197                    step,
198                    nodata_code: code("nodataCode")?,
199                    name: name.to_string(),
200                };
201                if codebook.maximum_code() != maximum_code || codebook.nodata_code <= maximum_code {
202                    return Err(EncodeError::conversion(format!(
203                        "{name} linear quantization code range is inconsistent"
204                    )));
205                }
206                Book::Linear(codebook)
207            }
208            Some("log1p") => {
209                if code("minimumCode")? != 1 || code("zeroCode")? != 0 {
210                    return Err(EncodeError::conversion(format!(
211                        "{name} log1p quantization needs zeroCode 0 and minimumCode 1"
212                    )));
213                }
214                let codebook = PrecipitationCodebook {
215                    trace: number("trace")?,
216                    scale: number("scale")?,
217                    maximum: number("maximum")?,
218                    maximum_code: code("maximumCode")?,
219                    overflow_code: code("overflowCode")?,
220                    nodata_code: code("nodataCode")?,
221                    name: name.to_string(),
222                };
223                if !(0.0 < codebook.trace && codebook.trace < codebook.maximum)
224                    || codebook.scale <= 0.0
225                    || !(1 < codebook.maximum_code
226                        && codebook.maximum_code < codebook.overflow_code
227                        && codebook.overflow_code < codebook.nodata_code)
228                {
229                    return Err(EncodeError::conversion(format!(
230                        "{name} log1p quantization parameters are inconsistent"
231                    )));
232                }
233                Book::Precipitation(codebook)
234            }
235            other => {
236                return Err(EncodeError::conversion(format!(
237                    "{name} quantization type {} is not one this encoder quantizes",
238                    other.map_or_else(|| "null".to_string(), |kind| format!("{kind:?}"))
239                )))
240            }
241        };
242        Ok(Codebook {
243            book,
244            block: block.clone(),
245        })
246    }
247
248    /// The block, as the document carries it and the metadata writes it.
249    pub fn metadata(&self) -> Map<String, Value> {
250        self.block.clone()
251    }
252
253    /// The code no value maps to, which pads a chunk past the grid.
254    pub fn nodata_code(&self) -> u16 {
255        match &self.book {
256            Book::Linear(codebook) => codebook.nodata_code,
257            Book::Precipitation(codebook) => codebook.nodata_code,
258        }
259    }
260
261    fn name(&self) -> &str {
262        match &self.book {
263            Book::Linear(codebook) => &codebook.name,
264            Book::Precipitation(codebook) => &codebook.name,
265        }
266    }
267
268    /// Sixteen-bit codes, for a series codebook: linear only, as the
269    /// registry's `seriesQuantization` is.
270    pub fn quantize_wide(&self, values: &[f64], codes: &mut [u16]) -> Result<()> {
271        match &self.book {
272            Book::Linear(codebook) => codebook.quantize_wide(values, codes),
273            Book::Precipitation(_) => Err(EncodeError::conversion(format!(
274                "{}: a sixteen-bit codebook is linear",
275                self.name()
276            ))),
277        }
278    }
279
280    /// Whether the codes need sixteen bits (`code_dtype` in the reference):
281    /// every other code of a consistent block is below its nodata code.
282    pub fn is_wide(&self) -> bool {
283        self.nodata_code() > 0xFF
284    }
285
286    pub fn quantize(&self, values: &[f64], codes: &mut [u8]) -> Result<()> {
287        if self.is_wide() {
288            return Err(EncodeError::conversion(format!(
289                "{}: a codebook with nodataCode {} quantizes into sixteen-bit codes, not bytes",
290                self.name(),
291                self.nodata_code()
292            )));
293        }
294        match &self.book {
295            Book::Linear(codebook) => codebook.quantize(values, codes),
296            Book::Precipitation(codebook) => codebook.quantize(values, codes),
297        }
298    }
299
300    pub fn as_linear(&self) -> Option<&LinearCodebook> {
301        match &self.book {
302            Book::Linear(codebook) => Some(codebook),
303            Book::Precipitation(_) => None,
304        }
305    }
306
307    pub fn as_precipitation(&self) -> Option<&PrecipitationCodebook> {
308        match &self.book {
309            Book::Linear(_) => None,
310            Book::Precipitation(codebook) => Some(codebook),
311        }
312    }
313}
314
315#[cfg(test)]
316mod tests {
317    use super::Codebook;
318    use crate::encode::registry::Registry;
319    use serde_json::{json, Map, Value};
320
321    fn block(value: Value) -> Map<String, Value> {
322        value.as_object().unwrap().clone()
323    }
324
325    #[test]
326    fn linear_codebook_rounds_half_up() {
327        let book = Registry::embedded().codebook("quality", "tmp2m").unwrap();
328        // -60 + 0.5 * 1 = -59.5 is exactly on a step; -59.75 sits exactly
329        // half way and must round up, which round-half-even would not do.
330        let values = [-60.0, -59.75, -59.5, 0.0, 50.0, 99.0, -99.0];
331        let mut codes = [0u8; 7];
332        book.quantize(&values, &mut codes).unwrap();
333        assert_eq!(codes, [0, 1, 1, 120, 220, 220, 0]);
334        assert_eq!(book.as_linear().unwrap().maximum, 50.0);
335        assert_eq!(book.as_linear().unwrap().decode(120), 0.0);
336        assert!(book
337            .quantize(&[f64::NAN], &mut [0])
338            .unwrap_err()
339            .to_string()
340            .contains("tmp2m"));
341    }
342
343    #[test]
344    fn precipitation_codebook_marks_dry_and_overflow() {
345        let book = Registry::embedded().codebook("quality", "prate").unwrap();
346        let values = [0.0, 0.009, 0.01, 1.0, 128.0, 200.0];
347        let mut codes = [0u8; 6];
348        book.quantize(&values, &mut codes).unwrap();
349        assert_eq!(codes[0], 0, "dry");
350        assert_eq!(codes[1], 0, "below trace is dry");
351        assert_eq!(codes[2], 1, "trace is the first positive code");
352        assert_eq!(codes[4], 253, "the maximum decodes to exactly the maximum");
353        assert_eq!(codes[5], 254, "above the maximum is the overflow code");
354        assert!(codes[3] > 1 && codes[3] < 253);
355        assert_eq!(book.as_precipitation().unwrap().overflow_code, 254);
356    }
357
358    /// The block comes back as it went in, and a block that does not say
359    /// one thing is refused the way the reference refuses it.
360    #[test]
361    fn a_codebook_is_its_block_and_nothing_else() {
362        let linear = block(
363            json!({"type": "linear", "offset": 0.0, "scale": 0.02, "minimumCode": 0, "maximumCode": 126, "nodataCode": 255}),
364        );
365        let book = Codebook::from_metadata(&linear, "clw").unwrap();
366        assert_eq!(book.metadata(), linear);
367        let mut wrong = linear.clone();
368        wrong.insert("nodataCode".into(), json!(100));
369        assert!(Codebook::from_metadata(&wrong, "clw").is_err());
370        let mut wrong = linear.clone();
371        wrong.insert("minimumCode".into(), json!(1));
372        assert!(Codebook::from_metadata(&wrong, "clw").is_err());
373        let mut wrong = linear.clone();
374        wrong.insert("scale".into(), json!("0.02"));
375        assert!(Codebook::from_metadata(&wrong, "clw")
376            .unwrap_err()
377            .to_string()
378            .contains("scale"));
379
380        let log = block(
381            json!({"type": "log1p", "trace": 0.01, "scale": 0.05, "maximum": 128.0, "minimumCode": 1, "maximumCode": 253, "zeroCode": 0, "overflowCode": 254, "nodataCode": 255}),
382        );
383        assert_eq!(
384            Codebook::from_metadata(&log, "prate").unwrap().metadata(),
385            log
386        );
387        let mut wrong = log.clone();
388        wrong.insert("overflowCode".into(), json!(253));
389        assert!(Codebook::from_metadata(&wrong, "prate").is_err());
390        let mut wrong = log.clone();
391        wrong.insert("zeroCode".into(), json!(1));
392        assert!(Codebook::from_metadata(&wrong, "prate").is_err());
393        let mut wrong = log.clone();
394        wrong.insert("type".into(), json!("cubic"));
395        assert!(Codebook::from_metadata(&wrong, "prate")
396            .unwrap_err()
397            .to_string()
398            .contains("cubic"));
399        let mut wrong = linear.clone();
400        wrong.insert("nodataCode".into(), json!(65536));
401        assert!(Codebook::from_metadata(&wrong, "clw")
402            .unwrap_err()
403            .to_string()
404            .contains("65535"));
405    }
406
407    /// A series codebook (`SERIES_CODEBOOK_TABLE` in the reference): codes
408    /// to 65535, the same round-half-up and clamp as a byte codebook, and
409    /// never quantized into bytes.
410    #[test]
411    fn a_sixteen_bit_codebook_rounds_half_up_and_clamps() {
412        let wide = block(
413            json!({"type": "linear", "offset": -90.0, "scale": 0.1, "minimumCode": 0, "maximumCode": 1500, "nodataCode": 65535}),
414        );
415        let book = Codebook::from_metadata(&wide, "tmp2m").unwrap();
416        assert!(book.is_wide());
417        assert_eq!(book.nodata_code(), 65535);
418        assert_eq!(book.metadata(), wide);
419        let linear = book.as_linear().unwrap();
420        // The clamp's top is the reference's given maximum, 60.0, exactly.
421        assert_eq!(linear.maximum, 60.0);
422        let values = [-120.0, -90.0, -89.95, 0.0, 21.37, 60.0, 75.0];
423        let mut codes = [0u16; 7];
424        book.quantize_wide(&values, &mut codes).unwrap();
425        let expected: Vec<u16> = values
426            .iter()
427            .map(|value: &f64| ((value.clamp(-90.0, 60.0) + 90.0) / 0.1 + 0.5).floor() as u16)
428            .collect();
429        assert_eq!(codes.to_vec(), expected);
430        assert_eq!(
431            (codes[0], codes[1], codes[3], codes[5], codes[6]),
432            (0, 0, 900, 1500, 1500)
433        );
434        assert!(book.quantize_wide(&[f64::INFINITY], &mut [0]).is_err());
435        assert!(
436            book.quantize(&[0.0], &mut [0u8]).is_err(),
437            "sixteen-bit codes never fit a byte"
438        );
439
440        let prate = block(
441            json!({"type": "linear", "offset": 0.0, "scale": 0.01, "minimumCode": 0, "maximumCode": 65500, "nodataCode": 65535}),
442        );
443        let book = Codebook::from_metadata(&prate, "prate").unwrap();
444        assert_eq!(book.as_linear().unwrap().maximum, 655.0);
445        let mut codes = [0u16; 3];
446        book.quantize_wide(&[0.004, 0.006, 1000.0], &mut codes)
447            .unwrap();
448        assert_eq!(codes, [0, 1, 65500]);
449
450        let narrow = Registry::embedded().codebook("quality", "prate").unwrap();
451        assert!(!narrow.is_wide());
452        assert!(
453            narrow.quantize_wide(&[1.0], &mut [0]).is_err(),
454            "a series codebook is linear"
455        );
456    }
457}