Skip to main content

xue/encode/
registry.rs

1//! The registry document (`docs/registry.md`): the variables, bundles and
2//! sources an encoder builds, read from one JSON document in place of a
3//! table of its own.
4//!
5//! The Python tables author the document (`xue registry` prints it,
6//! `xuebuild.registry.document_json` hands it to the wheel); this encoder
7//! implements the closed sets of rule names the document dispatches on
8//! (`Conversion`, `GdalRule`, `Predictor`, `Decimation`, `Companion`,
9//! `BundleKind`, `DerivationKind`, the two codebook types) and refuses a
10//! document that names anything else, or whose `registrySchema` it does not
11//! implement, before any input is read. A key a reader does not know is
12//! ignored, so the document can gain keys without a release.
13//!
14//! The snapshot `rust/xue/registry.json` is embedded as the CLI's default;
15//! `xue registry --output rust/xue/registry.json` regenerates it and
16//! `tests/test_registry.py` holds it to the Python tables.
17
18use std::collections::HashMap;
19use std::sync::Arc;
20
21use serde::Deserialize;
22use serde_json::{Map, Value};
23
24use crate::encode::errors::{EncodeError, Result};
25use crate::encode::quantize::Codebook;
26use crate::encode::sources::SourceSpec;
27use crate::encode::variables::{
28    deserialize_ensemble, AerosolIdentity, EnsembleIdentity, MatchSpec, VariableSpec,
29};
30
31/// The document schema this reader implements.
32pub const REGISTRY_SCHEMA: u64 = 1;
33
34/// The snapshot committed beside the crate: what `xue-encode` reads when no
35/// `--registry` is given.
36pub const EMBEDDED_DOCUMENT: &str = include_str!("../../registry.json");
37
38// -- the closed sets ----------------------------------------------------------
39
40/// How a variable's chunks are predicted: chained against the previous
41/// frame, or stacked as they are.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
43#[serde(rename_all = "lowercase")]
44pub enum Predictor {
45    Delta,
46    Raw,
47}
48
49/// How a reduced tier samples the full one: the site's own code, or the
50/// warmest code around the site.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
52#[serde(rename_all = "lowercase")]
53pub enum Decimation {
54    Sample,
55    Peak,
56}
57
58/// An artifact a variable's bundle ships beside the store.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
60#[serde(rename_all = "lowercase")]
61pub enum Companion {
62    Poster,
63    Video,
64}
65
66/// The unit rule of one variable: the arithmetic that takes a record's
67/// values to the variable's unit, and the spellings a record may carry.
68/// The semantics are in `units.rs`.
69#[derive(Debug, Clone, PartialEq, Deserialize)]
70#[serde(tag = "rule", rename_all = "kebab-case")]
71pub enum Conversion {
72    /// Identity; `acceptedUnits` lists the spellings, no list accepts any.
73    #[serde(rename = "none")]
74    Identity {
75        #[serde(default, rename = "acceptedUnits")]
76        accepted_units: Option<Vec<String>>,
77    },
78    Celsius,
79    SoilTemperature,
80    PrecipitationRate,
81    PrecipitationAccumulation,
82    PascalToHectopascal,
83    MetreToKilometre,
84    MassRatioToGPerKg,
85    ProportionToPercent,
86    CloudCover,
87    DegreesTrue,
88    GeopotentialToMetres,
89    MassDensityToMicrograms,
90    #[serde(rename = "per-second-to-1e-5")]
91    PerSecondTo1e5,
92    CodeTable {
93        table: String,
94    },
95}
96
97/// How a variable's record is recognised among a GRIB's bands as GDAL
98/// describes them. The semantics are in `inspect.rs`.
99#[derive(Debug, Clone, PartialEq, Deserialize)]
100#[serde(tag = "rule", rename_all = "kebab-case")]
101pub enum GdalRule {
102    Surface {
103        elements: Vec<String>,
104    },
105    Height {
106        element: String,
107        metres: u32,
108    },
109    EntireAtmosphere {
110        element: String,
111    },
112    MeanSeaLevel {
113        elements: Vec<String>,
114    },
115    Isobaric {
116        element: String,
117        hpa: u32,
118    },
119    #[serde(rename_all = "camelCase")]
120    CloudLayer {
121        element: String,
122        short_name: String,
123        phrases: Vec<String>,
124    },
125    Template,
126    TemplateAerosol,
127    /// An ensemble product under an identity of its own: the parameter and
128    /// first surface read off the assembled template beside the record's
129    /// ensemble identity and, for a template over a time interval, the one
130    /// interval's length in hours and its process.
131    #[serde(rename_all = "camelCase")]
132    TemplateEnsemble {
133        discipline: u8,
134        category: u8,
135        number: u8,
136        level_type: u8,
137        /// `None` accepts any surface value, a missing one included.
138        #[serde(default)]
139        level_value: Option<f64>,
140        #[serde(deserialize_with = "deserialize_ensemble")]
141        ensemble: EnsembleIdentity,
142        /// Set for a record over a time interval (templates 4.9, 4.10,
143        /// 4.12), together with `statistical`.
144        #[serde(default)]
145        hours: Option<u32>,
146        #[serde(default)]
147        statistical: Option<u8>,
148    },
149    TemplateRank,
150    TemplateMrms,
151    TotalPrecipitation,
152    AccumulationFromStart,
153    LocalParameter {
154        category: u8,
155        number: u8,
156    },
157    Phrase {
158        element: String,
159        phrases: Vec<String>,
160    },
161    GeopotentialSurface {
162        elements: Vec<String>,
163    },
164}
165
166/// What a bundle's arrays hold.
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
168#[serde(rename_all = "lowercase")]
169pub enum BundleKind {
170    Scalar,
171    Vector,
172    Composite,
173    Volume,
174}
175
176/// The algorithm a derived bundle's members are computed by.
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
178#[serde(rename_all = "kebab-case")]
179pub enum DerivationKind {
180    VapourFlux,
181    WaveVector,
182    ThetaE,
183    PrecipitationType,
184    ClearAirTurbulence,
185    PrecipitationRate,
186}
187
188/// A bundle computed in the converter from `inputs`.
189#[derive(Debug, Clone, PartialEq, Deserialize)]
190#[serde(rename_all = "camelCase")]
191pub struct Derivation {
192    pub kind: DerivationKind,
193    pub inputs: Vec<String>,
194    /// The isobaric surface, where the algorithm takes one.
195    #[serde(default)]
196    pub level_hpa: Option<u32>,
197}
198
199/// One `bundles` entry. A bundle id absent from the document is the scalar
200/// bundle of the variable of the same id.
201#[derive(Debug, Clone, PartialEq, Deserialize)]
202#[serde(rename_all = "camelCase")]
203pub struct BundleSpec {
204    #[serde(skip)]
205    pub id: String,
206    pub kind: BundleKind,
207    /// The variables the bundle's arrays hold, in file order.
208    #[serde(default)]
209    pub members: Vec<String>,
210    #[serde(default)]
211    pub derivation: Option<Derivation>,
212    /// A composite's producer id, the channels it reads, and the subset a
213    /// source may lack.
214    #[serde(default)]
215    pub producer: Option<String>,
216    #[serde(default)]
217    pub inputs: Vec<String>,
218    #[serde(default)]
219    pub optional_inputs: Vec<String>,
220}
221
222// -- the raw entries ------------------------------------------------------------
223
224#[derive(Deserialize)]
225#[serde(rename_all = "camelCase")]
226struct Document {
227    registry_schema: u64,
228    variables: Map<String, Value>,
229    bundles: Map<String, Value>,
230    sources: Map<String, Value>,
231}
232
233#[derive(Deserialize)]
234struct ProducerBlock {
235    id: String,
236}
237
238#[derive(Deserialize)]
239#[serde(rename_all = "camelCase")]
240struct VariableEntry {
241    label: String,
242    unit: String,
243    parameter: Map<String, Value>,
244    #[serde(default)]
245    producer: Option<ProducerBlock>,
246    #[serde(default)]
247    aerosol: Option<Map<String, Value>>,
248    #[serde(default)]
249    ensemble: Option<Map<String, Value>>,
250    #[serde(default)]
251    quantization: Option<Map<String, Value>>,
252    #[serde(default)]
253    series_quantization: Option<Value>,
254    value_range: (f64, f64),
255    fill_values: Vec<f64>,
256    #[serde(rename = "static")]
257    static_: bool,
258    predictor: Predictor,
259    decimation: Decimation,
260    companions: Vec<Companion>,
261    conversion: Conversion,
262    #[serde(rename = "match")]
263    matching: MatchSpec,
264}
265
266fn refused(message: impl Into<String>) -> EncodeError {
267    EncodeError::conversion(format!("registry document: {}", message.into()))
268}
269
270/// An integer field of a metadata block, or an error naming it.
271fn block_u64(block: &Map<String, Value>, key: &str, context: &str) -> Result<u64> {
272    block
273        .get(key)
274        .and_then(Value::as_u64)
275        .ok_or_else(|| refused(format!("{context} {key} must be a non-negative integer")))
276}
277
278/// A `(scaleFactor, scaledValue)` pair of a metadata block: `None` when
279/// both are null (GRIB2's missing pattern), the pair when both are set.
280fn block_limit(
281    block: &Map<String, Value>,
282    scale_key: &str,
283    value_key: &str,
284    context: &str,
285) -> Result<Option<(i64, u64)>> {
286    match (block.get(scale_key), block.get(value_key)) {
287        (Some(Value::Null), Some(Value::Null)) | (None, None) => Ok(None),
288        (Some(scale), Some(value)) => {
289            let scale = scale.as_i64().ok_or_else(|| {
290                refused(format!("{context} {scale_key} must be an integer or null"))
291            })?;
292            let value = value.as_u64().ok_or_else(|| {
293                refused(format!(
294                    "{context} {value_key} must be a non-negative integer or null"
295                ))
296            })?;
297            Ok(Some((scale, value)))
298        }
299        _ => Err(refused(format!(
300            "{context} {scale_key} and {value_key} must both be set or both null"
301        ))),
302    }
303}
304
305/// The aerosol identity a variable's `aerosol` block carries.
306fn parse_aerosol(block: &Map<String, Value>, context: &str) -> Result<AerosolIdentity> {
307    let limit = |scale_key: &str, value_key: &str| -> Result<Option<(i8, u32)>> {
308        Ok(block_limit(block, scale_key, value_key, context)?
309            .map(|(scale, value)| (scale as i8, value as u32)))
310    };
311    Ok(AerosolIdentity {
312        aerosol_type: block_u64(block, "aerosolType", context)? as u16,
313        size_type: block_u64(block, "typeOfSizeInterval", context)? as u8,
314        size_first: limit("scaleFactorOfFirstSize", "scaledValueOfFirstSize")?,
315        size_second: limit("scaleFactorOfSecondSize", "scaledValueOfSecondSize")?,
316        wavelength_type: block_u64(block, "typeOfWavelengthInterval", context)? as u8,
317        wavelength_first: limit(
318            "scaleFactorOfFirstWavelength",
319            "scaledValueOfFirstWavelength",
320        )?,
321        wavelength_second: limit(
322            "scaleFactorOfSecondWavelength",
323            "scaledValueOfSecondWavelength",
324        )?,
325    })
326}
327
328fn variable_spec(id: &str, entry: VariableEntry) -> Result<VariableSpec> {
329    let context = format!("variables.{id}: parameter");
330    let parameter = &entry.parameter;
331    let grib2_discipline = block_u64(parameter, "discipline", &context)? as u8;
332    let grib2_category = block_u64(parameter, "parameterCategory", &context)? as u8;
333    let grib2_number = block_u64(parameter, "parameterNumber", &context)? as u8;
334    let grib2_level_type = block_u64(parameter, "typeOfFirstFixedSurface", &context)? as u8;
335    // `scaledValue × 10^−scaleFactor`, the arithmetic every matcher compares
336    // a record's surface with.
337    let grib2_level_value = block_limit(
338        parameter,
339        "scaleFactorOfFirstFixedSurface",
340        "scaledValueOfFirstFixedSurface",
341        &context,
342    )?
343    .map(|(scale, value)| value as f64 / 10f64.powi(scale as i32));
344    let grib2_aerosol = entry
345        .aerosol
346        .as_ref()
347        .map(|block| parse_aerosol(block, &format!("variables.{id}: aerosol")))
348        .transpose()?;
349    let ensemble = entry
350        .ensemble
351        .as_ref()
352        .map(|block| {
353            EnsembleIdentity::from_block(block)
354                .map_err(|error| refused(format!("variables.{id}: ensemble: {}", error.0)))
355        })
356        .transpose()?;
357    for rule in &entry.matching.gdal {
358        if let GdalRule::TemplateEnsemble {
359            hours, statistical, ..
360        } = rule
361        {
362            // An interval template names both its length and its process;
363            // an instantaneous one neither.
364            if hours.is_some() != statistical.is_some() || *hours == Some(0) {
365                return Err(refused(format!(
366                    "variables.{id}: a template-ensemble rule sets hours and statistical together, hours above zero"
367                )));
368            }
369        }
370    }
371    let mut codebooks: HashMap<String, Codebook> = HashMap::new();
372    if let Some(quantization) = &entry.quantization {
373        for (profile, block) in quantization {
374            let block = block.as_object().ok_or_else(|| {
375                refused(format!(
376                    "variables.{id}: quantization.{profile} must be an object"
377                ))
378            })?;
379            let book = Codebook::from_metadata(block, id).map_err(|error| {
380                refused(format!("variables.{id}: quantization.{profile}: {error}"))
381            })?;
382            // A profile's codes are what every map store, container and
383            // tier holds: bytes.
384            if book.is_wide() {
385                return Err(refused(format!(
386                    "variables.{id}: quantization.{profile}: a profile codebook's codes are bytes, \
387                     every code from 0 to 255"
388                )));
389            }
390            codebooks.insert(profile.clone(), book);
391        }
392    }
393    // The codebook a series store holds the variable in, whatever the
394    // profile (`docs/registry.md`): linear, and sixteen-bit, since a block
395    // whose codes fit a byte would leave the store's width to the profile.
396    let series_codebook = entry
397        .series_quantization
398        .as_ref()
399        .map(|block| -> Result<Codebook> {
400            let block = block
401                .as_object()
402                .ok_or_else(|| refused(format!("variables.{id}: seriesQuantization must be an object")))?;
403            let book = Codebook::from_metadata(block, &format!("{id} series"))
404                .map_err(|error| refused(format!("variables.{id}: seriesQuantization: {error}")))?;
405            if book.as_linear().is_none() {
406                return Err(refused(format!("variables.{id}: seriesQuantization is a linear codebook")));
407            }
408            if !book.is_wide() {
409                return Err(refused(format!(
410                    "variables.{id}: seriesQuantization holds sixteen-bit codes, a nodataCode above 255"
411                )));
412            }
413            Ok(book)
414        })
415        .transpose()?;
416    Ok(VariableSpec {
417        id: id.to_string(),
418        label: entry.label,
419        output_unit: entry.unit,
420        value_range: entry.value_range,
421        fill_values: entry.fill_values,
422        static_: entry.static_,
423        predictor: entry.predictor,
424        decimation: entry.decimation,
425        companions: entry.companions,
426        conversion: entry.conversion,
427        parameter: entry.parameter,
428        grib2_discipline,
429        grib2_category,
430        grib2_number,
431        grib2_level_type,
432        grib2_level_value,
433        producer_id: entry.producer.map(|producer| producer.id),
434        aerosol: entry.aerosol,
435        grib2_aerosol,
436        ensemble,
437        codebooks,
438        series_codebook,
439        matching: entry.matching,
440    })
441}
442
443// -- the registry ---------------------------------------------------------------
444
445/// The parsed, validated document.
446#[derive(Debug)]
447pub struct Registry {
448    pub schema: u64,
449    variables: HashMap<String, VariableSpec>,
450    variable_order: Vec<String>,
451    bundles: HashMap<String, BundleSpec>,
452    sources: HashMap<String, SourceSpec>,
453    source_order: Vec<String>,
454}
455
456impl Registry {
457    /// Parse and validate one document, refusing the whole of it on the
458    /// first problem, with the field and value named.
459    pub fn parse(text: &str) -> Result<Arc<Registry>> {
460        let document: Document = serde_json::from_str(text)
461            .map_err(|error| refused(format!("not a registry document: {error}")))?;
462        if document.registry_schema != REGISTRY_SCHEMA {
463            return Err(refused(format!(
464                "registrySchema {} is not one this encoder implements ({REGISTRY_SCHEMA})",
465                document.registry_schema
466            )));
467        }
468        let mut variables = HashMap::with_capacity(document.variables.len());
469        let mut variable_order = Vec::with_capacity(document.variables.len());
470        for (id, value) in document.variables {
471            let entry: VariableEntry = serde_json::from_value(value)
472                .map_err(|error| refused(format!("variables.{id}: {error}")))?;
473            variables.insert(id.clone(), variable_spec(&id, entry)?);
474            variable_order.push(id);
475        }
476        let mut bundles = HashMap::with_capacity(document.bundles.len());
477        for (id, value) in document.bundles {
478            let mut entry: BundleSpec = serde_json::from_value(value)
479                .map_err(|error| refused(format!("bundles.{id}: {error}")))?;
480            entry.id = id.clone();
481            bundles.insert(id, entry);
482        }
483        let mut sources = HashMap::with_capacity(document.sources.len());
484        let mut source_order = Vec::with_capacity(document.sources.len());
485        for (id, value) in document.sources {
486            let entry: SourceSpec = serde_json::from_value(value)
487                .map_err(|error| refused(format!("sources.{id}: {error}")))?;
488            if entry.id != id {
489                return Err(refused(format!("sources.{id}: id is {:?}", entry.id)));
490            }
491            sources.insert(id.clone(), entry);
492            source_order.push(id);
493        }
494        let registry = Registry {
495            schema: document.registry_schema,
496            variables,
497            variable_order,
498            bundles,
499            sources,
500            source_order,
501        };
502        registry.validate()?;
503        Ok(Arc::new(registry))
504    }
505
506    /// The snapshot embedded in the crate.
507    pub fn embedded() -> Arc<Registry> {
508        Self::parse(EMBEDDED_DOCUMENT).expect("the embedded registry document is valid")
509    }
510
511    /// `docs/registry.md` §Validation: every id a bundle or a source names
512    /// resolves, a vector has two members, a derivation names its surface
513    /// where its algorithm takes one.
514    fn validate(&self) -> Result<()> {
515        let is_variable = |id: &str| self.variables.contains_key(id);
516        let is_bundle_id = |id: &str| is_variable(id) || self.bundles.contains_key(id);
517        for (id, bundle) in &self.bundles {
518            let context = format!("bundles.{id}");
519            for member in bundle
520                .members
521                .iter()
522                .chain(&bundle.inputs)
523                .chain(&bundle.optional_inputs)
524                .chain(
525                    bundle
526                        .derivation
527                        .iter()
528                        .flat_map(|derivation| &derivation.inputs),
529                )
530            {
531                if !is_variable(member) {
532                    return Err(refused(format!(
533                        "{context} names {member:?}, which is not a variable"
534                    )));
535                }
536            }
537            match bundle.kind {
538                BundleKind::Scalar if !bundle.members.is_empty() => {
539                    return Err(refused(format!("{context} is a scalar with members")));
540                }
541                BundleKind::Vector if bundle.members.len() != 2 => {
542                    return Err(refused(format!(
543                        "{context} is a vector with {} members, not two",
544                        bundle.members.len()
545                    )));
546                }
547                BundleKind::Composite | BundleKind::Volume if bundle.members.is_empty() => {
548                    return Err(refused(format!("{context} has no members")));
549                }
550                _ => {}
551            }
552            if let Some(derivation) = &bundle.derivation {
553                let takes_level = matches!(
554                    derivation.kind,
555                    DerivationKind::ThetaE | DerivationKind::ClearAirTurbulence
556                );
557                if takes_level && derivation.level_hpa.is_none() {
558                    return Err(refused(format!("{context} derivation needs levelHpa")));
559                }
560                if derivation.inputs.is_empty() {
561                    return Err(refused(format!("{context} derivation has no inputs")));
562                }
563            }
564        }
565        for (id, source) in &self.sources {
566            let context = format!("sources.{id}");
567            for variable_id in source
568                .input_variable_ids
569                .iter()
570                .chain(&source.optional_at_analysis)
571                .chain(source.statistical_processes.iter().map(|(id, _)| id))
572                .chain(source.bands.iter().map(|(id, _)| id))
573                .chain(source.ensembles.iter().map(|(id, _)| id))
574                .chain(
575                    source
576                        .interval_precipitation_pairs
577                        .iter()
578                        .flat_map(|(rate_id, total_id)| [rate_id, total_id]),
579                )
580                .chain(source.variable_first_hours.iter().map(|(id, _)| id))
581                .chain(source.variable_step_hours.iter().map(|(id, _)| id))
582                .chain(
583                    source
584                        .companion_files
585                        .iter()
586                        .flat_map(|companion| &companion.variable_ids),
587                )
588            {
589                if !is_variable(variable_id) {
590                    return Err(refused(format!(
591                        "{context} names {variable_id:?}, which is not a variable"
592                    )));
593                }
594            }
595            if !source.interval_precipitation_pairs.is_empty() && !source.interval_precipitation {
596                return Err(refused(format!(
597                    "{context} lists intervalPrecipitationPairs without intervalPrecipitation"
598                )));
599            }
600            if source
601                .variable_first_hours
602                .iter()
603                .any(|(_, hour)| *hour <= 0)
604            {
605                return Err(refused(format!(
606                    "{context} variableFirstHours must be above zero"
607                )));
608            }
609            if source
610                .variable_step_hours
611                .iter()
612                .any(|(_, hours)| *hours <= 0)
613            {
614                return Err(refused(format!(
615                    "{context} variableStepHours must be above zero"
616                )));
617            }
618            if source.windowed_precipitation && source.accumulation_window_hours <= 0 {
619                return Err(refused(format!(
620                    "{context} accumulationWindowHours must be above zero"
621                )));
622            }
623            let shapes = [
624                source.accumulated_precipitation,
625                source.averaged_precipitation,
626                source.interval_precipitation,
627                source.windowed_precipitation,
628            ];
629            if shapes.iter().filter(|shape| **shape).count() > 1 {
630                return Err(refused(format!(
631                    "{context} declares more than one precipitation shape"
632                )));
633            }
634            for bundle_id in source
635                .bundle_scalar_ids
636                .iter()
637                .chain(&source.core_bundle_ids)
638                .chain(&source.bundle_vector_ids)
639                .chain(&source.bundle_composite_ids)
640                .chain(&source.bundle_volume_ids)
641                .chain(&source.series_bundle_ids)
642            {
643                if !is_bundle_id(bundle_id) {
644                    return Err(refused(format!(
645                        "{context} publishes {bundle_id:?}, which is neither a variable nor a bundle"
646                    )));
647                }
648            }
649        }
650        Ok(())
651    }
652
653    // -- lookups --------------------------------------------------------------
654
655    pub fn variable(&self, variable_id: &str) -> Result<&VariableSpec> {
656        self.variables
657            .get(variable_id)
658            .ok_or_else(|| EncodeError::conversion(format!("unsupported variable: {variable_id}")))
659    }
660
661    pub fn source(&self, model: &str) -> Result<&SourceSpec> {
662        self.sources
663            .get(model)
664            .ok_or_else(|| EncodeError::conversion(format!("unsupported model: {model}")))
665    }
666
667    /// The source whose manifest `model` string is `manifest_model`.
668    pub fn source_by_manifest_model(&self, manifest_model: &str) -> Option<&SourceSpec> {
669        self.sources()
670            .find(|source| source.manifest_model == manifest_model)
671    }
672
673    pub fn bundle(&self, bundle_id: &str) -> Option<&BundleSpec> {
674        self.bundles.get(bundle_id)
675    }
676
677    /// Every variable, in document order.
678    pub fn variables(&self) -> impl Iterator<Item = &VariableSpec> {
679        self.variable_order.iter().map(|id| &self.variables[id])
680    }
681
682    /// Every source, in document order.
683    pub fn sources(&self) -> impl Iterator<Item = &SourceSpec> {
684        self.source_order.iter().map(|id| &self.sources[id])
685    }
686
687    /// One profile's codebook for one variable.
688    pub fn codebook(&self, profile: &str, variable_id: &str) -> Result<Codebook> {
689        self.variable(variable_id)?
690            .codebooks
691            .get(profile)
692            .cloned()
693            .ok_or_else(|| {
694                EncodeError::conversion(format!("no {profile} codebook for {variable_id}"))
695            })
696    }
697
698    /// The variable's series codebook (`seriesQuantization`), if it has one;
699    /// an unregistered id has none.
700    pub fn series_codebook(&self, variable_id: &str) -> Option<&Codebook> {
701        self.variables
702            .get(variable_id)
703            .and_then(|spec| spec.series_codebook.as_ref())
704    }
705
706    /// The variables whose series-store codes are sixteen-bit: every
707    /// variable of `series_bundle_ids` (those of `bundle_ids` alone on a
708    /// restricted build) that has a series codebook, in that order. The
709    /// reference's `series_widened_ids`, over the same document.
710    pub fn series_widened_ids(
711        &self,
712        series_bundle_ids: &[String],
713        bundle_ids: Option<&[String]>,
714    ) -> Vec<String> {
715        let mut widened: Vec<String> = Vec::new();
716        for bundle_id in series_bundle_ids {
717            if bundle_ids.is_some_and(|wanted| !wanted.contains(bundle_id)) {
718                continue;
719            }
720            for variable_id in self.bundle_variable_ids(bundle_id) {
721                if self.series_codebook(&variable_id).is_some() && !widened.contains(&variable_id) {
722                    widened.push(variable_id);
723                }
724            }
725        }
726        widened
727    }
728
729    /// Whether any published variable has a codebook under `profile`.
730    pub fn knows_profile(&self, profile: &str) -> bool {
731        self.variables()
732            .any(|spec| spec.codebooks.contains_key(profile))
733    }
734
735    /// Whether a variable is time-invariant; an unregistered id is not.
736    pub fn is_static(&self, variable_id: &str) -> bool {
737        self.variables
738            .get(variable_id)
739            .is_some_and(|spec| spec.static_)
740    }
741
742    /// Whether a variable's chunks stack RAW rather than chaining.
743    pub fn is_raw(&self, variable_id: &str) -> Result<bool> {
744        Ok(self.variable(variable_id)?.predictor == Predictor::Raw)
745    }
746
747    // -- bundles ---------------------------------------------------------------
748
749    /// The variables one bundle carries, in bundle order: a scalar's own, a
750    /// vector's pair, a composite's components, a volume's levels.
751    pub fn bundle_variable_ids(&self, bundle_id: &str) -> Vec<String> {
752        match self.bundles.get(bundle_id) {
753            Some(bundle) if !bundle.members.is_empty() => bundle.members.clone(),
754            _ => vec![bundle_id.to_string()],
755        }
756    }
757
758    /// The two component variables of a vector bundle, or `None`.
759    pub fn vector_components(&self, bundle_id: &str) -> Option<(&str, &str)> {
760        let bundle = self.bundles.get(bundle_id)?;
761        (bundle.kind == BundleKind::Vector)
762            .then(|| (bundle.members[0].as_str(), bundle.members[1].as_str()))
763    }
764
765    /// A composite's components, or `None` for any other bundle.
766    pub fn composite_components(&self, bundle_id: &str) -> Option<&[String]> {
767        let bundle = self.bundles.get(bundle_id)?;
768        (bundle.kind == BundleKind::Composite).then_some(bundle.members.as_slice())
769    }
770
771    /// A volume's members, or `None` for any other bundle.
772    pub fn volume_components(&self, bundle_id: &str) -> Option<&[String]> {
773        let bundle = self.bundles.get(bundle_id)?;
774        (bundle.kind == BundleKind::Volume).then_some(bundle.members.as_slice())
775    }
776
777    /// The derivation of a bundle the converter computes, or `None`.
778    pub fn derivation(&self, bundle_id: &str) -> Option<&Derivation> {
779        self.bundles.get(bundle_id)?.derivation.as_ref()
780    }
781
782    /// The derivation of a scalar the per-frame stage computes from other
783    /// planes (the equivalent potential temperature, the precipitation
784    /// type, the turbulence index); the precipitation rate is the per-file
785    /// stage's and is not one.
786    pub fn scalar_derivation(&self, bundle_id: &str) -> Option<&Derivation> {
787        let bundle = self.bundles.get(bundle_id)?;
788        let derivation = bundle.derivation.as_ref()?;
789        (bundle.kind == BundleKind::Scalar && derivation.kind != DerivationKind::PrecipitationRate)
790            .then_some(derivation)
791    }
792
793    /// Whether a vector bundle is derived rather than read.
794    pub fn is_derived_vector(&self, bundle_id: &str) -> bool {
795        self.bundles
796            .get(bundle_id)
797            .is_some_and(|bundle| bundle.kind == BundleKind::Vector && bundle.derivation.is_some())
798    }
799
800    /// The source inputs one vector bundle is built from: a wind pair is
801    /// its own two components, a derived pair its derivation's inputs.
802    pub fn vector_input_ids(&self, bundle_id: &str) -> Vec<String> {
803        match self.bundles.get(bundle_id) {
804            Some(bundle) if bundle.kind == BundleKind::Vector => {
805                bundle.derivation.as_ref().map_or_else(
806                    || bundle.members.clone(),
807                    |derivation| derivation.inputs.clone(),
808                )
809            }
810            _ => vec![bundle_id.to_string()],
811        }
812    }
813
814    /// The source input variables one published bundle is built from. A
815    /// composite reads its producer's inputs less the optional ones the
816    /// source does not fetch; the precipitation rate reads the first of its
817    /// derivation's inputs the source lists.
818    pub fn bundle_input_ids(&self, source: &SourceSpec, bundle_id: &str) -> Vec<String> {
819        if let Some(total_id) = source.interval_total_of(bundle_id) {
820            return vec![total_id.to_string()];
821        }
822        let Some(bundle) = self.bundles.get(bundle_id) else {
823            return vec![bundle_id.to_string()];
824        };
825        if let Some(derivation) = &bundle.derivation {
826            if derivation.kind == DerivationKind::PrecipitationRate {
827                return derivation
828                    .inputs
829                    .iter()
830                    .filter(|id| source.input_variable_ids.contains(id))
831                    .take(1)
832                    .cloned()
833                    .collect();
834            }
835            return derivation.inputs.clone();
836        }
837        match bundle.kind {
838            BundleKind::Composite => bundle
839                .inputs
840                .iter()
841                .filter(|id| {
842                    !bundle.optional_inputs.contains(id) || source.input_variable_ids.contains(id)
843                })
844                .cloned()
845                .collect(),
846            BundleKind::Vector | BundleKind::Volume => bundle.members.clone(),
847            BundleKind::Scalar => vec![bundle_id.to_string()],
848        }
849    }
850
851    /// The precipitation-rate bundle a source derives in its per-file
852    /// stage, as `(bundle id, raw input id)`: the listed scalar whose
853    /// derivation is the rate, on a source whose precipitation arrives
854    /// accumulated, averaged, as an interval total or as a window's.
855    /// `None` on a source that reads the rate as it is.
856    pub fn derived_precipitation(&self, source: &SourceSpec) -> Result<Option<(String, String)>> {
857        if !(source.accumulated_precipitation
858            || source.averaged_precipitation
859            || source.interval_precipitation
860            || source.windowed_precipitation)
861        {
862            return Ok(None);
863        }
864        let mut found: Option<(String, String)> = None;
865        for bundle_id in &source.bundle_scalar_ids {
866            if source.interval_total_of(bundle_id).is_some() {
867                continue;
868            }
869            let is_rate = self
870                .derivation(bundle_id)
871                .is_some_and(|derivation| derivation.kind == DerivationKind::PrecipitationRate);
872            if !is_rate {
873                continue;
874            }
875            let Some(raw_id) = self.bundle_input_ids(source, bundle_id).into_iter().next() else {
876                continue;
877            };
878            if found.is_some() {
879                return Err(EncodeError::conversion(format!(
880                    "{} derives more than one precipitation rate",
881                    source.manifest_model
882                )));
883            }
884            found = Some((bundle_id.clone(), raw_id));
885        }
886        Ok(found)
887    }
888
889    /// The further rates a source derives from interval totals beside its
890    /// one precipitation rate, as `(bundle id, raw input id)`, those whose
891    /// total this build reads (`SourceSpec::interval_precipitation_pairs`).
892    pub fn interval_precipitation_pairs(&self, source: &SourceSpec) -> Vec<(String, String)> {
893        source
894            .interval_precipitation_pairs
895            .iter()
896            .filter(|(rate_id, _)| source.bundle_scalar_ids.contains(rate_id))
897            .cloned()
898            .collect()
899    }
900
901    /// The forecast hour a bundle's series starts at when its inputs are
902    /// absent from every earlier frame (`SourceSpec::variable_first_hours`):
903    /// the latest of its inputs', `None` for a bundle whose inputs are in
904    /// every frame.
905    pub fn bundle_first_hour(&self, source: &SourceSpec, bundle_id: &str) -> Option<i64> {
906        self.bundle_input_ids(source, bundle_id)
907            .iter()
908            .chain(std::iter::once(&bundle_id.to_string()))
909            .filter_map(|id| source.first_hour_of(id))
910            .max()
911    }
912
913    /// Whether a bundle is read from an input written only every so many
914    /// hours (`SourceSpec::variable_step_hours`): its axis is then its own.
915    pub fn bundle_has_step(&self, source: &SourceSpec, bundle_id: &str) -> bool {
916        self.bundle_input_ids(source, bundle_id)
917            .iter()
918            .any(|id| source.step_hours_of(id).is_some())
919    }
920
921    /// Whether a bundle is read from an input some frame past the analysis
922    /// may lack by the source's cadence rules (`SourceSpec::is_cadenced`).
923    pub fn bundle_is_cadenced(&self, source: &SourceSpec, bundle_id: &str) -> bool {
924        self.bundle_input_ids(source, bundle_id)
925            .iter()
926            .any(|id| source.is_cadenced(id))
927    }
928
929    /// Whether a bundle has a frame at `hour` by its inputs' cadence rules:
930    /// every input is carried there. Mirrors `bundle_carried_at` in
931    /// `xuebuild/discover.py`.
932    pub fn bundle_carried_at(&self, source: &SourceSpec, bundle_id: &str, hour: i64) -> bool {
933        self.bundle_input_ids(source, bundle_id)
934            .iter()
935            .all(|id| source.carries_input(id, hour))
936    }
937
938    /// The ensemble block a variable is written with on a source: the
939    /// source's own for it (`SourceSpec::ensembles`), else the variable's.
940    pub fn ensemble(
941        &self,
942        source: &SourceSpec,
943        variable_id: &str,
944    ) -> Result<Option<EnsembleIdentity>> {
945        if let Some((_, identity)) = source.ensembles.iter().find(|(id, _)| id == variable_id) {
946            return Ok(Some(*identity));
947        }
948        Ok(self.variable(variable_id)?.ensemble)
949    }
950
951    /// Every bundle a source can publish, in manifest order: its scalars,
952    /// then each listed vector whose inputs it fetches, then each listed
953    /// composite whose producer's channels it fetches, then each listed
954    /// volume whose members it fetches. A derived scalar counts the same
955    /// way — listed, it ships only when its inputs are.
956    pub fn published_bundle_ids<'a>(&self, source: &'a SourceSpec) -> Vec<&'a str> {
957        let fetched = |bundle_id: &str| {
958            self.bundle_input_ids(source, bundle_id)
959                .iter()
960                .all(|id| source.input_variable_ids.contains(id))
961        };
962        source
963            .bundle_scalar_ids
964            .iter()
965            .chain(&source.bundle_vector_ids)
966            .chain(&source.bundle_composite_ids)
967            .chain(&source.bundle_volume_ids)
968            .map(String::as_str)
969            .filter(|bundle_id| fetched(bundle_id))
970            .collect()
971    }
972
973    /// The published scalars of `scalar_ids` whose series has no analysis
974    /// frame: the rate a source derives by de-accumulating, de-averaging
975    /// or differencing a window, and any scalar read from a record the
976    /// source lists under `optional_at_analysis`.
977    pub fn analysis_optional_ids<'a>(
978        &self,
979        source: &SourceSpec,
980        scalar_ids: &[&'a str],
981    ) -> Vec<&'a str> {
982        scalar_ids
983            .iter()
984            .copied()
985            .filter(|bundle_id| {
986                let derived_rate = self
987                    .derivation(bundle_id)
988                    .is_some_and(|derivation| derivation.kind == DerivationKind::PrecipitationRate)
989                    && (source.accumulated_precipitation
990                        || source.averaged_precipitation
991                        || source.windowed_precipitation);
992                derived_rate
993                    || self
994                        .bundle_input_ids(source, bundle_id)
995                        .iter()
996                        .any(|input_id| source.optional_at_analysis.contains(input_id))
997            })
998            .collect()
999    }
1000}
1001
1002/// The snapshot widened by hand with the ensemble keys of the registry
1003/// document, independent of which source publishes them: a median rule on
1004/// `tmp2m`, its 25th percentile, a spread, a 24-hour probability, a pair
1005/// of interval totals and a first hour on CMA GEPS.
1006#[cfg(test)]
1007pub(crate) mod ensemble_fixture {
1008    use serde_json::{json, Value};
1009
1010    pub(crate) fn rule(
1011        category: u8,
1012        number: u8,
1013        level_type: u8,
1014        level_value: Value,
1015        ensemble: Value,
1016        hours: Value,
1017        statistical: Value,
1018    ) -> Value {
1019        json!({
1020            "rule": "template-ensemble", "discipline": 0, "category": category, "number": number,
1021            "levelType": level_type, "levelValue": level_value, "ensemble": ensemble,
1022            "hours": hours, "statistical": statistical,
1023        })
1024    }
1025
1026    pub(crate) fn document() -> Value {
1027        let mut document: Value = serde_json::from_str(super::EMBEDDED_DOCUMENT).unwrap();
1028        let variables = &mut document["variables"];
1029        let median = rule(
1030            0,
1031            0,
1032            103,
1033            json!(2.0),
1034            json!({"percentileValue": 50}),
1035            json!(null),
1036            json!(null),
1037        );
1038        variables["tmp2m"]["match"]["gdal"]
1039            .as_array_mut()
1040            .unwrap()
1041            .push(median);
1042        let mut quartile = variables["tmp2m"].clone();
1043        quartile["label"] = json!("2 meter temperature, 25th percentile");
1044        quartile["ensemble"] = json!({"percentileValue": 25});
1045        quartile["match"]["gdal"] = json!([rule(
1046            0,
1047            0,
1048            103,
1049            json!(2.0),
1050            json!({"percentileValue": 25}),
1051            json!(null),
1052            json!(null)
1053        )]);
1054        variables["tmp2mq25"] = quartile;
1055        let mut total = variables["apcp"].clone();
1056        total["match"]["gdal"] = json!([rule(
1057            1,
1058            8,
1059            1,
1060            json!(null),
1061            json!({"percentileValue": 25}),
1062            json!(6),
1063            json!(1)
1064        )]);
1065        variables["apcpq25"] = total;
1066        let mut rate = variables["prate"].clone();
1067        rate["ensemble"] = json!({"percentileValue": 25});
1068        rate["match"]["gdal"] = json!([]);
1069        variables["prateq25"] = rate;
1070        let mut spread = variables["prmsl"].clone();
1071        spread["ensemble"] = json!({"derivedForecast": 4});
1072        spread["match"]["gdal"] = json!([rule(
1073            3,
1074            1,
1075            101,
1076            json!(null),
1077            json!({"derivedForecast": 4}),
1078            json!(null),
1079            json!(null)
1080        )]);
1081        variables["prmslsd"] = spread;
1082        let probability = json!({
1083            "probabilityType": 3, "scaleFactorOfLowerLimit": 2, "scaledValueOfLowerLimit": 1000,
1084            "scaleFactorOfUpperLimit": null, "scaledValueOfUpperLimit": null,
1085        });
1086        let mut above = variables["apcp"].clone();
1087        above["unit"] = json!("%");
1088        above["ensemble"] = probability.clone();
1089        above["quantization"] = variables["tmp2m"]["quantization"].clone();
1090        above["match"]["gdal"] =
1091            json!([rule(1, 8, 1, json!(null), probability, json!(24), json!(1))]);
1092        variables["apcp24gt10"] = above;
1093        let source = &mut document["sources"]["cmageps"];
1094        source["ensembles"] =
1095            json!([["tmp2m", {"percentileValue": 50}], ["prmsl", {"derivedForecast": 0}]]);
1096        source["intervalPrecipitationPairs"] = json!([["prateq25", "apcpq25"]]);
1097        source["variableFirstHours"] = json!([["apcp24gt10", 24]]);
1098        for id in ["tmp2mq25", "prateq25", "prmslsd", "apcp24gt10"] {
1099            source["bundleScalarIds"]
1100                .as_array_mut()
1101                .unwrap()
1102                .push(json!(id));
1103        }
1104        for id in ["tmp2mq25", "apcpq25", "prmslsd", "apcp24gt10"] {
1105            source["inputVariableIds"]
1106                .as_array_mut()
1107                .unwrap()
1108                .push(json!(id));
1109        }
1110        source["optionalAtAnalysis"]
1111            .as_array_mut()
1112            .unwrap()
1113            .push(json!("apcpq25"));
1114        document
1115    }
1116}
1117
1118#[cfg(test)]
1119mod tests {
1120    use super::{
1121        BundleKind, Companion, Conversion, Decimation, DerivationKind, EnsembleIdentity, GdalRule,
1122        Predictor, Registry,
1123    };
1124    use serde_json::{json, Value};
1125
1126    #[test]
1127    fn the_snapshot_parses_into_its_representative_entries() {
1128        let registry = Registry::embedded();
1129        assert_eq!(registry.schema, 1);
1130
1131        // A linear codebook and a log1p one, profile for profile.
1132        let tmp2m = registry.variable("tmp2m").unwrap();
1133        assert_eq!(tmp2m.label, "2 meter temperature");
1134        assert_eq!(tmp2m.output_unit, "°C");
1135        assert_eq!(
1136            (
1137                tmp2m.grib2_discipline,
1138                tmp2m.grib2_category,
1139                tmp2m.grib2_number,
1140                tmp2m.grib2_level_type
1141            ),
1142            (0, 0, 0, 103)
1143        );
1144        assert_eq!(tmp2m.grib2_level_value, Some(2.0));
1145        assert_eq!(tmp2m.conversion, Conversion::Celsius);
1146        assert_eq!(tmp2m.predictor, Predictor::Delta);
1147        assert_eq!(tmp2m.companions, [Companion::Poster, Companion::Video]);
1148        let quality = registry.codebook("quality", "tmp2m").unwrap();
1149        let linear = quality.as_linear().unwrap();
1150        assert_eq!(
1151            (linear.minimum, linear.step, linear.maximum_code()),
1152            (-60.0, 0.5, 220)
1153        );
1154        assert_eq!(quality.metadata()["type"], json!("linear"));
1155        assert_eq!(
1156            registry
1157                .codebook("compact", "tmp2m")
1158                .unwrap()
1159                .as_linear()
1160                .unwrap()
1161                .step,
1162            1.0
1163        );
1164        let prate = registry.codebook("balanced", "prate").unwrap();
1165        assert!(prate.as_linear().is_none());
1166        assert_eq!(prate.metadata()["maximumCode"], json!(125));
1167        assert_eq!(prate.metadata()["type"], json!("log1p"));
1168        assert!(registry.codebook("quality", "tp").is_err(), "input-only");
1169        assert!(registry.codebook("lossless", "tmp2m").is_err());
1170        assert!(registry.knows_profile("balanced") && !registry.knows_profile("lossless"));
1171
1172        // The surface value of a layer is `scaledValue × 10^−scaleFactor`.
1173        assert_eq!(
1174            registry.variable("tsoil2").unwrap().grib2_level_value,
1175            Some(0.1)
1176        );
1177        assert_eq!(registry.variable("tcdc").unwrap().grib2_level_value, None);
1178        let aod = registry.variable("aoddust").unwrap();
1179        assert_eq!(aod.grib2_aerosol.unwrap().aerosol_type, 62001);
1180        assert_eq!(aod.grib2_aerosol.unwrap().wavelength_second, Some((9, 565)));
1181        assert_eq!(
1182            registry
1183                .variable("pm25")
1184                .unwrap()
1185                .grib2_aerosol
1186                .unwrap()
1187                .wavelength_first,
1188            None
1189        );
1190        assert_eq!(
1191            registry.variable("dustr").unwrap().producer_id.as_deref(),
1192            Some("shachen")
1193        );
1194        assert_eq!(
1195            registry.variable("ir039").unwrap().decimation,
1196            Decimation::Peak
1197        );
1198        assert_eq!(registry.variable("prmsl").unwrap().companions, []);
1199        assert!(registry.variable("orog").unwrap().static_ && registry.is_static("orog"));
1200        assert!(registry.is_raw("prate").unwrap() && !registry.is_raw("tmp2m").unwrap());
1201        assert!(registry
1202            .variable("thetae850")
1203            .unwrap()
1204            .matching
1205            .gdal
1206            .is_empty());
1207        assert_eq!(
1208            registry.variable("rh850").unwrap().matching.gdal,
1209            [GdalRule::Isobaric {
1210                element: "RH".into(),
1211                hpa: 850
1212            }]
1213        );
1214        assert!(registry.variable("nothing").is_err());
1215
1216        // A vector bundle and a derived one; a scalar is any id not listed.
1217        assert_eq!(
1218            registry.vector_components("wind10m"),
1219            Some(("ugrd10m", "vgrd10m"))
1220        );
1221        assert_eq!(
1222            registry.bundle_variable_ids("wind10m"),
1223            ["ugrd10m", "vgrd10m"]
1224        );
1225        assert_eq!(registry.vector_input_ids("wind10m"), ["ugrd10m", "vgrd10m"]);
1226        assert!(!registry.is_derived_vector("wind10m"));
1227        assert!(registry.is_derived_vector("qflux850"));
1228        assert_eq!(
1229            registry.vector_input_ids("qflux850"),
1230            ["spfh850", "ugrd850", "vgrd850"]
1231        );
1232        assert_eq!(
1233            registry.bundle_variable_ids("qflux850"),
1234            ["uqflx850", "vqflx850"]
1235        );
1236        let thetae = registry.scalar_derivation("thetae850").unwrap();
1237        assert_eq!(
1238            (thetae.kind, thetae.level_hpa),
1239            (DerivationKind::ThetaE, Some(850))
1240        );
1241        assert!(
1242            registry.scalar_derivation("prate").is_none(),
1243            "the rate is the per-file stage's"
1244        );
1245        assert_eq!(
1246            registry.derivation("prate").unwrap().kind,
1247            DerivationKind::PrecipitationRate
1248        );
1249        assert_eq!(registry.bundle_variable_ids("tmp2m"), ["tmp2m"]);
1250        assert_eq!(registry.bundle("refl3d").unwrap().kind, BundleKind::Volume);
1251        assert_eq!(
1252            registry.composite_components("dustrgb").unwrap(),
1253            ["dustr", "dustg", "dustb"]
1254        );
1255        assert_eq!(registry.volume_components("cloud3d").unwrap().len(), 24);
1256
1257        // A source with a companion family, and the inputs resolved through it.
1258        let gfs = registry.source("gfs").unwrap();
1259        assert_eq!(gfs.manifest_model, "GFS");
1260        assert_eq!(gfs.companion_files.len(), 1);
1261        assert_eq!(gfs.companion_files[0].id, "wave");
1262        assert!(gfs.companion_files[0]
1263            .variable_ids
1264            .contains(&"htsgw".to_string()));
1265        assert_eq!(
1266            gfs.companion_of("htsgw")
1267                .map(|companion| companion.id.as_str()),
1268            Some("wave")
1269        );
1270        assert_eq!(gfs.steps, [(120, 1), (240, 3)]);
1271        assert_eq!(gfs.production_grid, (1440, 721));
1272        assert_eq!(gfs.cat_calibration[0].0, 300);
1273        assert_eq!(registry.bundle_input_ids(gfs, "prate"), ["prate"]);
1274        assert_eq!(registry.derived_precipitation(gfs).unwrap(), None);
1275        let ecmwf = registry.source("ecmwf").unwrap();
1276        assert_eq!(
1277            registry.derived_precipitation(ecmwf).unwrap(),
1278            Some(("prate".to_string(), "tp".to_string()))
1279        );
1280        assert_eq!(
1281            registry.analysis_optional_ids(ecmwf, &["tmp2m", "prate", "gust"]),
1282            ["prate", "gust"]
1283        );
1284        // The window a source's precipitation input is taken over: the
1285        // averaging window's wherever no total is accumulated over one.
1286        assert_eq!(
1287            registry
1288                .source("sflux")
1289                .unwrap()
1290                .precipitation_window_hours(),
1291            6
1292        );
1293        assert!(!gfs.windowed_precipitation && gfs.accumulation_window_hours == 12);
1294        // A total that starts over every twelve hours: the rate is derived
1295        // from it, and has no analysis frame, on that flag.
1296        let woofnam = registry.source("woofnam").unwrap();
1297        assert!(woofnam.windowed_precipitation);
1298        assert_eq!(woofnam.precipitation_window_hours(), 12);
1299        assert_eq!(
1300            registry.derived_precipitation(woofnam).unwrap(),
1301            Some(("prate".to_string(), "apcp".to_string()))
1302        );
1303        assert_eq!(
1304            registry.analysis_optional_ids(woofnam, &["tmp2m", "prate"]),
1305            ["prate"]
1306        );
1307        let cfs = registry.source("cfs").unwrap();
1308        assert_eq!(cfs.companion_files[0].production_grid, Some((360, 181)));
1309        assert!(cfs.companion_files[0].own_grid());
1310        assert_eq!(
1311            registry
1312                .source("mrms")
1313                .unwrap()
1314                .downsample
1315                .map(|downsample| downsample.factor),
1316            Some(2)
1317        );
1318        assert!(registry.source("hrrr").unwrap().grid_relative_winds);
1319        assert_eq!(
1320            registry.source("hrrr").unwrap().production_grid,
1321            (1799, 1059)
1322        );
1323        assert!(registry.source("rrfs").unwrap().grid_relative_winds);
1324        assert!(!gfs.grid_relative_winds);
1325        assert_eq!(cfs.gaussian_n, Some(95));
1326        assert_eq!(registry.source("sflux").unwrap().gaussian_n, Some(768));
1327        assert_eq!(gfs.gaussian_n, None);
1328        assert_eq!(registry.source("efas").unwrap().latest_filename, None);
1329        assert_eq!(
1330            registry.source_by_manifest_model("HRRR").unwrap().id,
1331            "hrrr"
1332        );
1333        assert!(registry.source("nothing").is_err());
1334        assert_eq!(registry.sources().count(), 34);
1335        assert_eq!(registry.variables().count(), 416);
1336    }
1337
1338    /// The ensemble keys of the document: a variable's own block, a
1339    /// source's override of a single-forecast variable, the rule with its
1340    /// parameters, a pair of interval totals and a first hour.
1341    #[test]
1342    fn the_ensemble_keys_parse_into_the_identities_they_name() {
1343        let registry = Registry::parse(&super::ensemble_fixture::document().to_string()).unwrap();
1344        let cmageps = registry.source("cmageps").unwrap();
1345        assert_eq!(
1346            registry.ensemble(cmageps, "tmp2m").unwrap(),
1347            Some(EnsembleIdentity::Percentile(50))
1348        );
1349        assert_eq!(
1350            registry.ensemble(cmageps, "prmsl").unwrap(),
1351            Some(EnsembleIdentity::Derived(0))
1352        );
1353        assert_eq!(
1354            registry.ensemble(cmageps, "tmp2mq25").unwrap(),
1355            Some(EnsembleIdentity::Percentile(25))
1356        );
1357        assert_eq!(
1358            registry.ensemble(cmageps, "prmslsd").unwrap(),
1359            Some(EnsembleIdentity::Derived(4))
1360        );
1361        assert_eq!(
1362            registry.ensemble(cmageps, "apcp24gt10").unwrap(),
1363            Some(EnsembleIdentity::probability(3, Some((2, 1000)), None))
1364        );
1365        let gfs = registry.source("gfs").unwrap();
1366        assert_eq!(
1367            registry.ensemble(gfs, "tmp2m").unwrap(),
1368            None,
1369            "the override is the source's"
1370        );
1371        assert_eq!(
1372            registry.variable("apcp24gt10").unwrap().matching.gdal,
1373            [GdalRule::TemplateEnsemble {
1374                discipline: 0,
1375                category: 1,
1376                number: 8,
1377                level_type: 1,
1378                level_value: None,
1379                ensemble: EnsembleIdentity::probability(3, Some((2, 1000)), None),
1380                hours: Some(24),
1381                statistical: Some(1),
1382            }]
1383        );
1384        // The pair's rate reads its total and is published only when the
1385        // build reads it; the rate has no analysis frame, like `prate`.
1386        assert_eq!(registry.bundle_input_ids(cmageps, "prateq25"), ["apcpq25"]);
1387        assert_eq!(
1388            registry.interval_precipitation_pairs(cmageps),
1389            [("prateq25".to_string(), "apcpq25".to_string())]
1390        );
1391        assert!(registry.published_bundle_ids(cmageps).contains(&"prateq25"));
1392        assert_eq!(
1393            registry.analysis_optional_ids(cmageps, &["tmp2m", "prateq25"]),
1394            ["prateq25"]
1395        );
1396        assert_eq!(
1397            registry.derived_precipitation(cmageps).unwrap(),
1398            Some(("prate".to_string(), "apcp".to_string()))
1399        );
1400        assert_eq!(registry.bundle_first_hour(cmageps, "apcp24gt10"), Some(24));
1401        assert_eq!(registry.bundle_first_hour(cmageps, "tmp2m"), None);
1402    }
1403
1404    #[test]
1405    fn a_step_counts_from_the_first_hour() {
1406        let mut document = super::ensemble_fixture::document();
1407        document["sources"]["cmageps"]["variableStepHours"] =
1408            json!([["apcp24gt10", 12], ["prmslsd", 6]]);
1409        let registry = Registry::parse(&document.to_string()).unwrap();
1410        let cmageps = registry.source("cmageps").unwrap();
1411        let carried = |id: &str| -> Vec<i64> {
1412            [0, 3, 6, 12, 21, 24, 27, 30, 36, 48, 150, 156, 162, 234, 240]
1413                .into_iter()
1414                .filter(|hour| cmageps.carries_input(id, *hour))
1415                .collect()
1416        };
1417        assert_eq!(carried("apcp24gt10"), [24, 36, 48, 156, 240]);
1418        assert_eq!(
1419            carried("prmslsd"),
1420            [0, 6, 12, 24, 30, 36, 48, 150, 156, 162, 234, 240]
1421        );
1422        assert_eq!(carried("tmp2mq25").len(), 15);
1423        assert!(cmageps.is_cadenced("apcp24gt10") && cmageps.is_cadenced("prmslsd"));
1424        assert!(!cmageps.is_cadenced("tmp2mq25"));
1425        assert!(registry.bundle_has_step(cmageps, "prmslsd"));
1426        assert!(!registry.bundle_has_step(cmageps, "tmp2mq25"));
1427        assert!(registry.bundle_carried_at(cmageps, "apcp24gt10", 36));
1428        assert!(!registry.bundle_carried_at(cmageps, "apcp24gt10", 30));
1429        // Every source of the snapshot names its steps, the empty list included.
1430        let snapshot = Registry::embedded();
1431        let ecmwf = snapshot.source("ecmwf").unwrap();
1432        assert_eq!(ecmwf.step_hours_of("apcp24gt10"), Some(12));
1433        assert_eq!(ecmwf.first_hour_of("apcp24gt10"), Some(24));
1434        assert!(snapshot
1435            .source("gfs")
1436            .unwrap()
1437            .variable_step_hours
1438            .is_empty());
1439    }
1440
1441    fn snapshot() -> Value {
1442        serde_json::from_str(super::EMBEDDED_DOCUMENT).unwrap()
1443    }
1444
1445    fn refusal(document: &Value) -> String {
1446        Registry::parse(&document.to_string())
1447            .expect_err("refused")
1448            .to_string()
1449    }
1450
1451    #[test]
1452    fn a_document_outside_the_closed_sets_is_refused_whole() {
1453        let mut document = snapshot();
1454        document["registrySchema"] = json!(2);
1455        assert!(refusal(&document).contains("registrySchema 2"));
1456
1457        let mut document = snapshot();
1458        document["variables"]["tmp2m"]["conversion"]["rule"] = json!("fahrenheit");
1459        let message = refusal(&document);
1460        assert!(
1461            message.contains("variables.tmp2m") && message.contains("fahrenheit"),
1462            "{message}"
1463        );
1464
1465        let mut document = snapshot();
1466        document["variables"]["tmp2m"]["match"]["gdal"][0]["rule"] = json!("altitude");
1467        assert!(refusal(&document).contains("altitude"));
1468
1469        let mut document = snapshot();
1470        document["variables"]["ir039"]["decimation"] = json!("mean");
1471        assert!(refusal(&document).contains("mean"));
1472
1473        let mut document = snapshot();
1474        document["variables"]["tmp2m"]["quantization"]["quality"]["type"] = json!("cubic");
1475        assert!(refusal(&document).contains("cubic"));
1476
1477        let mut document = snapshot();
1478        document["bundles"]["wind10m"]["members"] = json!(["ugrd10m", "vgrd10m", "gust"]);
1479        assert!(refusal(&document).contains("not two"));
1480
1481        let mut document = snapshot();
1482        document["bundles"]["wind10m"]["members"][1] = json!("vgrd9m");
1483        let message = refusal(&document);
1484        assert!(
1485            message.contains("bundles.wind10m") && message.contains("vgrd9m"),
1486            "{message}"
1487        );
1488
1489        let mut document = snapshot();
1490        document["bundles"]["thetae850"]["derivation"]["kind"] = json!("theta-w");
1491        assert!(refusal(&document).contains("theta-w"));
1492
1493        let mut document = snapshot();
1494        document["sources"]["gfs"]["bundleScalarIds"][0] = json!("tmp3m");
1495        let message = refusal(&document);
1496        assert!(
1497            message.contains("sources.gfs") && message.contains("tmp3m"),
1498            "{message}"
1499        );
1500
1501        let mut document = snapshot();
1502        document["sources"]["gfs"]["inputVariableIds"][0] = json!("tmp3m");
1503        assert!(refusal(&document).contains("tmp3m"));
1504
1505        // An ensemble block the format does not admit, wherever it is.
1506        let mut document = super::ensemble_fixture::document();
1507        document["variables"]["prmslsd"]["ensemble"] =
1508            json!({"derivedForecast": 4, "percentileValue": 50});
1509        assert!(refusal(&document).contains("variables.prmslsd"));
1510        let mut document = super::ensemble_fixture::document();
1511        document["variables"]["tmp2mq25"]["match"]["gdal"][0]["ensemble"] =
1512            json!({"percentileValue": 101});
1513        assert!(refusal(&document).contains("percentileValue"));
1514        let mut document = super::ensemble_fixture::document();
1515        document["sources"]["cmageps"]["ensembles"][0][1] = json!({"probabilityType": 3});
1516        assert!(refusal(&document).contains("sources.cmageps"));
1517        // An interval rule names its hours and its process together.
1518        let mut document = super::ensemble_fixture::document();
1519        document["variables"]["apcpq25"]["match"]["gdal"][0]["statistical"] = json!(null);
1520        assert!(refusal(&document).contains("variables.apcpq25"));
1521        // Every id the three source keys name is a variable.
1522        for (key, path) in [
1523            ("ensembles", 0),
1524            ("intervalPrecipitationPairs", 1),
1525            ("variableFirstHours", 0),
1526        ] {
1527            let mut document = super::ensemble_fixture::document();
1528            document["sources"]["cmageps"][key][0][path] = json!("tmp3m");
1529            let message = refusal(&document);
1530            assert!(
1531                message.contains("sources.cmageps") && message.contains("tmp3m"),
1532                "{key}: {message}"
1533            );
1534        }
1535        // A step names a variable and is above zero.
1536        let mut document = super::ensemble_fixture::document();
1537        document["sources"]["cmageps"]["variableStepHours"] = json!([["tmp3m", 12]]);
1538        let message = refusal(&document);
1539        assert!(
1540            message.contains("sources.cmageps") && message.contains("tmp3m"),
1541            "{message}"
1542        );
1543        let mut document = super::ensemble_fixture::document();
1544        document["sources"]["cmageps"]["variableStepHours"] = json!([["apcp24gt10", 0]]);
1545        assert!(refusal(&document).contains("variableStepHours must be above zero"));
1546
1547        // One precipitation shape to a source, over a window of at least an
1548        // hour.
1549        let mut document = snapshot();
1550        document["sources"]["gfs"]["averagedPrecipitation"] = json!(true);
1551        document["sources"]["gfs"]["windowedPrecipitation"] = json!(true);
1552        let message = refusal(&document);
1553        assert!(
1554            message.contains("sources.gfs")
1555                && message.contains("more than one precipitation shape"),
1556            "{message}"
1557        );
1558        let mut document = snapshot();
1559        document["sources"]["gfs"]["windowedPrecipitation"] = json!(true);
1560        document["sources"]["gfs"]["accumulationWindowHours"] = json!(0);
1561        assert!(refusal(&document).contains("accumulationWindowHours"));
1562
1563        // A key a reader does not know is ignored, not refused.
1564        let mut document = snapshot();
1565        document["variables"]["tmp2m"]["colour"] = json!("red");
1566        document["sources"]["gfs"]["mascot"] = json!("goose");
1567        document["bundles"]["wind10m"]["note"] = json!("gusty");
1568        assert!(Registry::parse(&document.to_string()).is_ok());
1569    }
1570
1571    /// The reference's series codebook table, as the document carries it
1572    /// once switched on.
1573    fn series_block(offset: f64, scale: f64, maximum_code: u64) -> Value {
1574        json!({"type": "linear", "offset": offset, "scale": scale, "minimumCode": 0, "maximumCode": maximum_code, "nodataCode": 65535})
1575    }
1576
1577    #[test]
1578    fn a_series_codebook_is_sixteen_bit_and_linear() {
1579        // Starts from no series codebook, whatever the snapshot ships.
1580        let mut document = snapshot();
1581        for variable in document["variables"]
1582            .as_object_mut()
1583            .expect("variables")
1584            .values_mut()
1585        {
1586            variable
1587                .as_object_mut()
1588                .expect("variable")
1589                .remove("seriesQuantization");
1590        }
1591        let tmp2m = series_block(-90.0, 0.1, 1500);
1592        document["variables"]["tmp2m"]["seriesQuantization"] = tmp2m.clone();
1593        document["variables"]["ugrd10m"]["seriesQuantization"] = series_block(-100.0, 0.1, 2000);
1594        document["variables"]["vgrd10m"]["seriesQuantization"] = series_block(-100.0, 0.1, 2000);
1595        document["variables"]["prate"]["seriesQuantization"] = series_block(0.0, 0.01, 65500);
1596        let registry = Registry::parse(&document.to_string()).unwrap();
1597        let book = registry.series_codebook("tmp2m").expect("tmp2m is widened");
1598        assert!(book.is_wide());
1599        assert_eq!(Value::Object(book.metadata()), tmp2m);
1600        assert!(registry.series_codebook("prmsl").is_none());
1601
1602        // The rule of `series_widened_ids`: the series bundles' variables
1603        // with a codebook, those of a restricted build alone.
1604        let series: Vec<String> = ["tmp2m", "prmsl", "wind10m", "prate"]
1605            .map(String::from)
1606            .to_vec();
1607        assert_eq!(
1608            registry.series_widened_ids(&series, None),
1609            ["tmp2m", "ugrd10m", "vgrd10m", "prate"]
1610        );
1611        let restricted: Vec<String> = vec!["wind10m".into(), "tcdc".into()];
1612        assert_eq!(
1613            registry.series_widened_ids(&series, Some(&restricted)),
1614            ["ugrd10m", "vgrd10m"]
1615        );
1616        assert!(registry.series_widened_ids(&[], None).is_empty());
1617
1618        // A profile codebook stays bytes; a series one is linear and wide,
1619        // every code to 65535 and consistent.
1620        let mut wrong = snapshot();
1621        wrong["variables"]["tmp2m"]["quantization"]["quality"] = series_block(-90.0, 0.1, 1500);
1622        let message = refusal(&wrong);
1623        assert!(
1624            message.contains("quantization.quality") && message.contains("bytes"),
1625            "{message}"
1626        );
1627        let mut wrong = snapshot();
1628        wrong["variables"]["tmp2m"]["seriesQuantization"] = json!({"type": "linear", "offset": -60.0, "scale": 0.5, "minimumCode": 0, "maximumCode": 220, "nodataCode": 255});
1629        assert!(refusal(&wrong).contains("sixteen-bit"));
1630        let mut wrong = snapshot();
1631        wrong["variables"]["prate"]["seriesQuantization"] = json!({"type": "log1p", "trace": 0.01, "scale": 0.05, "maximum": 128.0, "minimumCode": 1, "maximumCode": 65533, "zeroCode": 0, "overflowCode": 65534, "nodataCode": 65535});
1632        assert!(refusal(&wrong).contains("linear"));
1633        let mut wrong = snapshot();
1634        wrong["variables"]["tmp2m"]["seriesQuantization"] = series_block(-90.0, 0.1, 1500);
1635        wrong["variables"]["tmp2m"]["seriesQuantization"]["minimumCode"] = json!(1);
1636        assert!(refusal(&wrong).contains("seriesQuantization"));
1637        let mut wrong = snapshot();
1638        wrong["variables"]["tmp2m"]["seriesQuantization"] = series_block(-90.0, 0.1, 1500);
1639        wrong["variables"]["tmp2m"]["seriesQuantization"]["nodataCode"] = json!(65536);
1640        assert!(refusal(&wrong).contains("65535"));
1641        let mut wrong = snapshot();
1642        wrong["variables"]["tmp2m"]["seriesQuantization"] = json!([1, 2]);
1643        assert!(refusal(&wrong).contains("must be an object"));
1644    }
1645}