1use std::collections::BTreeMap;
11use std::path::{Path, PathBuf};
12use std::sync::{Arc, Condvar, Mutex};
13
14use serde_json::{json, Map, Value};
15use time::OffsetDateTime;
16
17use crate::encode::binformat::{self, ChunkPayload, ChunkTables, HOUR_SECONDS};
18use crate::encode::derive::{
19 derive_cat_plane, derive_ptype, derive_theta_e, derive_vapour_flux, derive_wave_vector,
20 interval_rate,
21};
22use crate::encode::discover::{
23 discover_records, discover_series, frame_of, Discovered, FileFrames,
24};
25use crate::encode::errors::{EncodeError, Result};
26use crate::encode::gdalio::{needs_serial_access, netcdf_guard, Dataset};
27use crate::encode::gribpng::GribPngFile;
28use crate::encode::grid::{
29 crop_grid, gaussian_rows, normalize_longitudes, snap_global_longitudes, snap_regional_steps,
30 GridInfo,
31};
32use crate::encode::ladder::{build_ladder, bundle_tile, playback_bandwidth, Rung, Tier};
33use crate::encode::metadata::{axis_unit_seconds, build_metadata};
34use crate::encode::model::{PlaneSource, SourceFrame};
35use crate::encode::parallel::for_each_ordered;
36use crate::encode::poster::encode_poster;
37use crate::encode::pyjson::dumps_default;
38use crate::encode::quantize::Book;
39use crate::encode::registry::{Companion, DerivationKind, Registry};
40use crate::encode::report::{build_report, write_manifest};
41use crate::encode::reproject::{lambert_conformal_from_wkt, rotate_winds, ProjectedGrid};
42use crate::encode::sources::{family_frame_path, SourceSpec};
43use crate::encode::spool::SeriesSpool;
44use crate::encode::temporal::build_chunks;
45use crate::encode::variables::VariableSpec;
46use crate::encode::zarrstore;
47use crate::format::{ChunkEntry, Predictor, TileGeometry, VariableEntry, NO_DEPENDENCY};
48
49pub use crate::encode::derive::{
52 align_packing_steps, average_window_start, deaccumulate_precipitation, deaverage_precipitation,
53 dewindow_precipitation,
54};
55pub use crate::encode::ladder::decimate_codes;
57
58pub const DEFAULT_ZSTD_LEVEL: i32 = 15;
59
60#[derive(Debug, Clone)]
61pub struct ConvertOptions {
62 pub profile: String,
63 pub zstd_level: i32,
64 pub require_complete: bool,
65 pub expected_hours: i64,
66 pub manifest_path: Option<PathBuf>,
67 pub force: bool,
68 pub skip_variants: bool,
69 pub model: String,
70 pub bbox: Option<(f64, f64, f64, f64)>,
71 pub bundle_ids: Option<Vec<String>>,
72 pub last_hour: Option<i64>,
73 pub extract_workers: usize,
74 pub compress_workers: usize,
75 pub verbose: bool,
76 pub zarr: bool,
79 pub container: bool,
82 pub series_bundle_ids: Vec<String>,
86}
87
88impl Default for ConvertOptions {
89 fn default() -> Self {
90 let cpus = std::thread::available_parallelism().map_or(4, std::num::NonZeroUsize::get);
91 Self {
92 profile: "quality".into(),
93 zstd_level: DEFAULT_ZSTD_LEVEL,
94 require_complete: false,
95 expected_hours: 120,
96 manifest_path: None,
97 force: false,
98 skip_variants: false,
99 model: "gfs".into(),
100 bbox: None,
101 bundle_ids: None,
102 last_hour: None,
103 extract_workers: cpus.min(16),
105 compress_workers: cpus,
106 verbose: false,
107 zarr: true,
110 container: false,
111 series_bundle_ids: Vec::new(),
112 }
113 }
114}
115
116pub fn grid_family_of<'a>(source: &'a SourceSpec, variable_id: &str) -> Option<&'a str> {
120 source
121 .grid_family_of(variable_id)
122 .map(|companion| companion.id.as_str())
123}
124
125pub fn bundle_grid_family<'a>(
137 registry: &Registry,
138 source: &'a SourceSpec,
139 bundle_id: &str,
140) -> Result<Option<&'a str>> {
141 let mut families: Vec<Option<&'a str>> = Vec::new();
142 for variable_id in registry.bundle_input_ids(source, bundle_id) {
143 let family = grid_family_of(source, &variable_id);
144 if !families.contains(&family) {
145 families.push(family);
146 }
147 }
148 if families.len() > 1 {
149 let mut named: Vec<&str> = families
150 .iter()
151 .map(|family| family.unwrap_or("the primary file"))
152 .collect();
153 named.sort_unstable();
154 return Err(EncodeError::conversion(format!(
155 "the {bundle_id} bundle of {} reads {}: every variable of a bundle must be on one grid",
156 source.manifest_model,
157 named.join(", ")
158 )));
159 }
160 Ok(families.first().copied().flatten())
161}
162
163pub fn store_dimensions(
180 registry: &Registry,
181 source: &SourceSpec,
182 bundle_id: &str,
183) -> Result<[String; 3]> {
184 let variable_ids = registry.bundle_variable_ids(bundle_id);
185 let own_axis = (source.bundle_scalar_ids.iter().any(|id| id == bundle_id)
186 && (!registry
187 .analysis_optional_ids(source, &[bundle_id])
188 .is_empty()
189 || registry.bundle_first_hour(source, bundle_id).is_some()
190 || registry.bundle_has_step(source, bundle_id)))
191 || registry.is_static(&variable_ids[0]);
192 let family = bundle_grid_family(registry, source, bundle_id)?;
193 if let Some(family) = family {
194 if !zarrstore::is_coordinate_suffix(family) {
195 return Err(EncodeError::conversion(format!(
196 "grid family {family:?} of {} cannot name a coordinate array",
197 source.manifest_model
198 )));
199 }
200 }
201 let (row, column) = if source.grid_relative_winds {
202 ("y", "x")
203 } else {
204 ("latitude", "longitude")
205 };
206 Ok([
207 if own_axis {
208 format!("time_{bundle_id}")
209 } else {
210 "time".to_owned()
211 },
212 family.map_or_else(|| row.to_owned(), |family| format!("{row}_{family}")),
213 family.map_or_else(|| column.to_owned(), |family| format!("{column}_{family}")),
214 ])
215}
216
217fn grid_info(path: &Path, source: &SourceSpec, family: Option<&str>) -> Result<GridInfo> {
230 let dataset = Dataset::open(path)?;
231 let (width, height) = dataset.size();
232 let transform = dataset.geo_transform()?;
233 if transform[2] != 0.0 || transform[4] != 0.0 {
234 return Err(EncodeError::conversion(format!(
235 "rotated grids are unsupported: {}",
236 path.display()
237 )));
238 }
239 let projection = lambert_conformal_from_wkt(&dataset.projection_wkt())?;
240 if let Some(projection) = projection {
241 if !source.grid_relative_winds {
242 return Err(EncodeError::conversion(format!(
243 "{} is on a map projection, which this source does not declare",
244 path.display()
245 )));
246 }
247 if transform[1] <= 0.0 || transform[5] >= 0.0 {
248 return Err(EncodeError::conversion(format!(
249 "grid must run west-to-east and north-to-south: {}",
250 path.display()
251 )));
252 }
253 let [x0, dx, y0, dy] = [transform[0], transform[1], transform[3], transform[5]].map(round3);
258 return Ok(GridInfo::projected(
259 ProjectedGrid {
260 projection,
261 width,
262 height,
263 x0: x0 + dx / 2.0,
264 y0: y0 + dy / 2.0,
265 dx,
266 dy,
267 },
268 None,
269 ));
270 }
271 if source.grid_relative_winds {
272 return Err(EncodeError::conversion(format!(
273 "{} is a regular grid, but this source declares a projected one",
274 path.display()
275 )));
276 }
277 let (longitude_step, latitude_step) = (transform[1], transform[5]);
278 if longitude_step <= 0.0 || latitude_step >= 0.0 {
279 return Err(EncodeError::conversion(format!(
280 "grid must run west-to-east and north-to-south: {}",
281 path.display()
282 )));
283 }
284 let mut grid =
285 normalize_longitudes(snap_regional_steps(snap_global_longitudes(GridInfo::new(
286 width,
287 height,
288 transform[0] + longitude_step / 2.0,
289 transform[3] + latitude_step / 2.0,
290 longitude_step,
291 latitude_step,
292 ))));
293 if let Some(downsample) = source.downsample {
294 grid = grid.downsampled(downsample.factor, path)?;
295 }
296 if let (Some(n), None) = (source.gaussian_n, family) {
297 grid.gaussian = Some(gaussian_rows(&grid, n, path)?);
298 }
299 Ok(grid)
300}
301
302fn grid_relative_vectors<'a>(
308 registry: &Registry,
309 source: &SourceSpec,
310 vector_ids: &[&'a str],
311) -> Result<Vec<&'a str>> {
312 if !source.grid_relative_winds {
313 return Ok(Vec::new());
314 }
315 let derived: Vec<&str> = vector_ids
316 .iter()
317 .copied()
318 .filter(|id| registry.is_derived_vector(id))
319 .collect();
320 if !derived.is_empty() {
321 return Err(EncodeError::conversion(format!(
322 "{} has grid-relative winds, so it cannot derive {derived:?}",
323 source.manifest_model
324 )));
325 }
326 Ok(vector_ids.to_vec())
327}
328
329fn round3(value: f64) -> f64 {
332 format!("{value:.3}").parse().unwrap_or(value)
333}
334
335fn convert_units(spec: &VariableSpec, unit: &str, values: &mut [f64]) -> Result<()> {
344 spec.conversion.convert(unit, values)
345}
346
347pub enum PlaneSources {
351 Uniform(PlaneSource),
352 PerVariable(Vec<(String, PlaneSource)>),
353}
354
355impl PlaneSources {
356 fn for_variable(&self, variable_id: &str) -> Result<&PlaneSource> {
357 match self {
358 PlaneSources::Uniform(source) => Ok(source),
359 PlaneSources::PerVariable(sources) => sources
360 .iter()
361 .find(|(id, _)| id == variable_id)
362 .map(|(_, source)| source)
363 .ok_or_else(|| {
364 EncodeError::conversion(format!("no plane source for {variable_id}"))
365 }),
366 }
367 }
368}
369
370pub struct PlaneGrids(Vec<(String, GridInfo)>);
376
377impl PlaneGrids {
378 fn for_variable(&self, variable_id: &str) -> Result<&GridInfo> {
379 self.0
380 .iter()
381 .find(|(id, _)| id == variable_id)
382 .map(|(_, grid)| grid)
383 .ok_or_else(|| EncodeError::conversion(format!("no grid for {variable_id}")))
384 }
385}
386
387fn extract_planes(
415 frames: &FileFrames,
416 grids: &PlaneGrids,
417 plane_sources: &PlaneSources,
418 uncropped_ids: &[String],
419 registry: &Registry,
420) -> Result<(Vec<(String, Vec<f64>)>, Vec<(String, Vec<f64>)>)> {
421 let mut by_file: Vec<(&PathBuf, Vec<usize>)> = Vec::new();
424 for (index, entry) in frames.iter().enumerate() {
425 match by_file.iter_mut().find(|(path, _)| **path == entry.1.path) {
426 Some((_, held)) => held.push(index),
427 None => by_file.push((&entry.1.path, vec![index])),
428 }
429 }
430 let mut planes: Vec<Option<Vec<f64>>> = vec![None; frames.len()];
431 let mut wholes: Vec<Option<Vec<f64>>> = vec![None; frames.len()];
432 let keep_whole = |position: usize| uncropped_ids.contains(&frames[position].0);
433 for (source, positions) in by_file {
434 let first_id = &frames[positions[0]].0;
435 let (source_height, source_width) = grids.for_variable(first_id)?.source_shape();
436 let unscale = plane_sources.for_variable(first_id)?.unscale;
437 let serial = needs_serial_access(source);
438 let mut unfinished: Vec<(usize, Vec<f64>)> = Vec::new();
439 {
440 let _serial = serial.then(netcdf_guard);
444 let dataset = Dataset::open(source)?;
445 let png = GribPngFile::open(source);
446 if dataset.size() != (source_width, source_height) {
447 return Err(EncodeError::conversion(format!(
448 "extracted plane size mismatch for {}",
449 source.display()
450 )));
451 }
452 for &position in &positions {
453 let frame = &frames[position].1;
454 let mut plane = match &png {
455 Some(png) => png.read_band_f64(&dataset, frame.band)?,
456 None => dataset.read_band_f64(frame.band)?,
457 };
458 if unscale {
459 let band = dataset.band_info(frame.band)?;
460 if band.scale != 1.0 || band.offset != 0.0 {
461 for value in &mut plane {
462 *value = *value * band.scale + band.offset;
463 }
464 }
465 }
466 if serial {
467 unfinished.push((position, plane));
468 } else {
469 let (finished, whole) = finish_plane(
470 &frames[position],
471 plane,
472 grids,
473 plane_sources,
474 keep_whole(position),
475 registry,
476 )?;
477 planes[position] = Some(finished);
478 wholes[position] = whole;
479 }
480 }
481 }
482 for (position, plane) in unfinished {
483 let (finished, whole) = finish_plane(
484 &frames[position],
485 plane,
486 grids,
487 plane_sources,
488 keep_whole(position),
489 registry,
490 )?;
491 planes[position] = Some(finished);
492 wholes[position] = whole;
493 }
494 }
495 let uncropped = frames
496 .iter()
497 .zip(wholes)
498 .filter_map(|((variable_id, _), whole)| whole.map(|whole| (variable_id.clone(), whole)))
499 .collect();
500 let planes = frames
501 .iter()
502 .zip(planes)
503 .map(|((variable_id, _), plane)| (variable_id.clone(), plane.expect("every frame read")))
504 .collect();
505 Ok((planes, uncropped))
506}
507
508fn finish_plane(
515 (variable_id, frame): &(String, SourceFrame),
516 mut plane: Vec<f64>,
517 grids: &PlaneGrids,
518 plane_sources: &PlaneSources,
519 keep_whole: bool,
520 registry: &Registry,
521) -> Result<(Vec<f64>, Option<Vec<f64>>)> {
522 let source = &frame.path;
523 let spec = registry.variable(variable_id)?;
524 let grid = grids.for_variable(variable_id)?;
525 let (source_height, source_width) = grid.source_shape();
526 if grid.column_roll > 0 {
527 let roll = grid.column_roll;
528 let mut rolled = vec![0f64; plane.len()];
529 for row in 0..source_height {
530 let base = row * source_width;
531 for column in 0..source_width {
532 rolled[base + column] = plane[base + (column + source_width - roll) % source_width];
533 }
534 }
535 plane = rolled;
536 }
537 plane_sources
540 .for_variable(variable_id)?
541 .apply_fill(&mut plane);
542 fill_missing(spec, &mut plane);
543 if let Some(downsample) = &grid.downsample {
544 plane = downsample.take(&plane)?;
545 }
546 let mut whole: Option<Vec<f64>> = None;
547 if let Some(crop) = grid.crop {
548 let cropped = crop.take(&plane);
549 if keep_whole {
550 whole = Some(plane);
551 }
552 plane = cropped;
553 }
554 if plane.iter().any(|value| !value.is_finite()) {
555 return Err(EncodeError::conversion(format!(
556 "Xue v1 requires complete planes, found non-finite values in {}",
557 source.display()
558 )));
559 }
560 convert_units(spec, &frame.unit, &mut plane)?;
561 if let Some(whole) = whole.as_mut() {
562 convert_units(spec, &frame.unit, whole)?;
563 }
564 Ok((plane, whole))
565}
566
567fn fill_missing(spec: &VariableSpec, plane: &mut [f64]) {
574 if spec.fill_values.is_empty() {
575 return;
576 }
577 PlaneSource {
578 unscale: false,
579 fill_values: spec.fill_values.clone(),
580 fill_nan: false,
581 fill_replacement: spec.value_range.0,
582 }
583 .apply_fill(plane);
584}
585
586#[derive(Debug, Clone)]
589pub(super) struct PlaneStats {
590 pub variable_id: String,
591 pub max_abs_error: f64,
592 pub clamped_points: u64,
593 pub overflow_points: u64,
594}
595
596#[derive(Default)]
599struct PlaneSlot {
600 state: Mutex<Option<std::result::Result<Arc<Vec<f64>>, String>>>,
601 ready: Condvar,
602}
603
604impl PlaneSlot {
605 fn publish(&self, value: std::result::Result<Arc<Vec<f64>>, String>) {
606 *self.state.lock().expect("plane slot") = Some(value);
607 self.ready.notify_all();
608 }
609
610 fn wait(&self) -> Result<Arc<Vec<f64>>> {
611 let mut state = self.state.lock().expect("plane slot");
612 while state.is_none() {
613 state = self.ready.wait(state).expect("plane slot");
614 }
615 state.clone().expect("published").map_err(EncodeError)
616 }
617}
618
619fn write_series_store(
624 codes: &zarrstore::StoreCodes<'_>,
625 variables: &[&str],
626 bundle_offsets: &[i64],
627 spool: Option<&SeriesSpool>,
628 path: &Path,
629 pool: &rayon::ThreadPool,
630) -> Result<zarrstore::StoreReport> {
631 let widened: Vec<&str> = variables
632 .iter()
633 .copied()
634 .filter(|variable_id| spool.is_some_and(|spool| spool.contains(variable_id)))
635 .collect();
636 let Some(spool) = spool.filter(|_| !widened.is_empty()) else {
637 return zarrstore::write_store(codes, path, true, Some(zarrstore::SERIES_BLOCK), pool);
638 };
639 let quantizations: Vec<(&str, Map<String, Value>)> = widened
640 .iter()
641 .map(|variable_id| {
642 (
643 *variable_id,
644 spool.codebook(variable_id).expect("spooled").metadata(),
645 )
646 })
647 .collect();
648 let metadata = zarrstore::series_metadata(codes.metadata, &quantizations);
649 let planes = widened
650 .iter()
651 .map(|variable_id| spool.planes(variable_id, bundle_offsets))
652 .collect::<Result<Vec<_>>>()?;
653 let wide: Vec<zarrstore::WideVariable<'_>> = widened
654 .iter()
655 .zip(&planes)
656 .map(|(variable_id, planes)| zarrstore::WideVariable {
657 id: (*variable_id).to_owned(),
658 codes: planes,
659 })
660 .collect();
661 let series_codes = zarrstore::StoreCodes {
662 metadata: &metadata,
663 variables: codes
664 .variables
665 .iter()
666 .map(|variable| zarrstore::StoreVariable {
667 id: variable.id.clone(),
668 previous: variable.previous,
669 planes: if widened.contains(&variable.id.as_str()) {
670 Vec::new()
671 } else {
672 variable.planes.clone()
673 },
674 })
675 .collect(),
676 tile: codes.tile,
677 };
678 zarrstore::write_store_widened(
679 &series_codes,
680 &wide,
681 path,
682 true,
683 Some(zarrstore::SERIES_BLOCK),
684 pool,
685 )
686}
687
688type QuantizedFile = (i64, Vec<(String, Vec<u8>)>, Vec<PlaneStats>);
691
692type DerivedPrecipitation = (String, String);
697
698#[allow(clippy::too_many_arguments)]
699fn quantize_file(
700 frames: &FileFrames,
701 grids: &PlaneGrids,
702 profile: &str,
703 plane_source: &PlaneSources,
704 source: &SourceSpec,
705 precipitation: Option<&DerivedPrecipitation>,
706 interval_pairs: &[DerivedPrecipitation],
707 interval_start: Option<i64>,
708 previous: Option<(i64, Option<Arc<PlaneSlot>>)>,
709 own: Option<Arc<PlaneSlot>>,
710 derived_vector_ids: &[&str],
711 drop_ids: &[String],
712 derived_scalar_ids: &[&str],
713 rotated_vector_ids: &[&str],
714 registry: &Registry,
715 series_spool: Option<&SeriesSpool>,
716) -> Result<QuantizedFile> {
717 let lead = frames[0].1.lead_seconds;
718 let hour = lead / HOUR_SECONDS;
721
722 let mut uncropped_ids: Vec<String> = Vec::new();
725 for bundle_id in derived_scalar_ids {
726 let Some(derivation) = registry.scalar_derivation(bundle_id) else {
727 continue;
728 };
729 if derivation.kind != DerivationKind::ClearAirTurbulence {
730 continue;
731 }
732 for id in &derivation.inputs {
733 if !uncropped_ids.contains(id) {
734 uncropped_ids.push(id.clone());
735 }
736 }
737 }
738 let (extracted, uncropped) =
739 match extract_planes(frames, grids, plane_source, &uncropped_ids, registry) {
740 Ok(planes) => planes,
741 Err(error) => {
742 if let Some(slot) = own {
744 slot.publish(Err(error.to_string()));
745 }
746 return Err(error);
747 }
748 };
749 let mut values: Vec<(String, Vec<f64>)> = extracted;
750
751 let raw_precipitation_id = precipitation
752 .filter(|(_, raw_id)| values.iter().any(|(name, _)| name == raw_id))
753 .map(|(_, raw_id)| raw_id.as_str());
754 if let (Some(slot), Some(raw_id)) = (own, raw_precipitation_id) {
755 let plane = values
756 .iter()
757 .find(|(name, _)| name == raw_id)
758 .map(|(_, plane)| Arc::new(plane.clone()))
759 .expect("published raw precipitation plane");
760 slot.publish(Ok(plane));
761 }
762 let mut previous_plane: Option<Arc<Vec<f64>>> = None;
763 let mut previous_hour: Option<i64> = None;
764 if let Some((hour, slot)) = previous {
765 previous_hour = Some(hour);
766 previous_plane = match slot {
769 Some(slot) => Some(slot.wait()?),
770 None => None,
771 };
772 }
773
774 if let (Some(raw_id), Some((bundle_id, _))) = (raw_precipitation_id, precipitation) {
775 let position = values
776 .iter()
777 .position(|(name, _)| name == raw_id)
778 .expect("raw precipitation plane");
779 let (_, raw) = values.remove(position);
780 let derived = if source.accumulated_precipitation {
781 let step = previous_hour.map_or(1, |previous| hour - previous);
786 let (current_total, previous_total) =
787 align_packing_steps(&raw, previous_plane.as_deref().map(Vec::as_slice));
788 deaccumulate_precipitation(¤t_total, previous_total.as_deref(), step)
789 } else if source.interval_precipitation {
790 let previous_hour = previous_hour.ok_or_else(|| {
795 EncodeError::conversion(format!(
796 "the interval precipitation frame at hour {hour} names no interval"
797 ))
798 })?;
799 interval_rate(&raw, hour - previous_hour)?
800 } else if source.windowed_precipitation {
801 dewindow_precipitation(
805 &raw,
806 hour,
807 previous_plane.as_deref().map(Vec::as_slice),
808 previous_hour,
809 source.accumulation_window_hours,
810 )?
811 } else {
812 deaverage_precipitation(
816 &raw,
817 hour,
818 previous_plane.as_deref().map(Vec::as_slice),
819 previous_hour,
820 source.average_window_hours,
821 )?
822 };
823 values.insert(position, (bundle_id.clone(), derived));
824 }
825 for (rate_id, total_id) in interval_pairs {
828 let Some(position) = values.iter().position(|(name, _)| name == total_id) else {
829 continue;
830 };
831 let interval_start = interval_start.ok_or_else(|| {
832 EncodeError::conversion(format!(
833 "the interval precipitation frame at hour {hour} names no interval"
834 ))
835 })?;
836 let (_, total) = values.remove(position);
837 values.insert(
838 position,
839 (
840 rate_id.clone(),
841 interval_rate(&total, hour - interval_start)?,
842 ),
843 );
844 }
845
846 for bundle_id in rotated_vector_ids {
852 let (u_id, v_id) = registry.vector_components(bundle_id).ok_or_else(|| {
853 EncodeError::conversion(format!("{bundle_id} is not a vector bundle"))
854 })?;
855 let projection = grids.for_variable(u_id)?.projection.ok_or_else(|| {
856 EncodeError::conversion(format!(
857 "{bundle_id} has grid-relative winds on a regular grid"
858 ))
859 })?;
860 let position = |name: &str| {
861 values.iter().position(|(id, _)| id == name).ok_or_else(|| {
862 EncodeError::conversion(format!("missing {name} plane for {bundle_id}"))
863 })
864 };
865 let (u_at, v_at) = (position(u_id)?, position(v_id)?);
866 let mut u = std::mem::take(&mut values[u_at].1);
867 let mut v = std::mem::take(&mut values[v_at].1);
868 rotate_winds(&projection, &mut u, &mut v)?;
869 values[u_at].1 = u;
870 values[v_at].1 = v;
871 }
872
873 for bundle_id in derived_vector_ids {
878 let derivation = registry.derivation(bundle_id).ok_or_else(|| {
879 EncodeError::conversion(format!("{bundle_id} is not a derived bundle"))
880 })?;
881 let inputs = &derivation.inputs;
882 let plane = |name: &str| -> Result<&Vec<f64>> {
883 values
884 .iter()
885 .find(|(id, _)| id == name)
886 .map(|(_, plane)| plane)
887 .ok_or_else(|| {
888 EncodeError::conversion(format!("missing {name} plane for {bundle_id}"))
889 })
890 };
891 let (component_u, component_v) = match derivation.kind {
892 DerivationKind::WaveVector => derive_wave_vector(plane(&inputs[0])?, plane(&inputs[1])?),
893 DerivationKind::VapourFlux => {
894 derive_vapour_flux(plane(&inputs[0])?, plane(&inputs[1])?, plane(&inputs[2])?)
895 }
896 other => {
897 return Err(EncodeError::conversion(format!(
898 "{bundle_id} is a vector bundle derived by {other:?}, which is not a vector algorithm"
899 )))
900 }
901 };
902 let (u_id, v_id) = registry
903 .vector_components(bundle_id)
904 .expect("a derived vector bundle is a vector");
905 values.push((u_id.to_string(), component_u));
906 values.push((v_id.to_string(), component_v));
907 }
908 for bundle_id in derived_scalar_ids {
913 let derivation = registry.scalar_derivation(bundle_id).ok_or_else(|| {
914 EncodeError::conversion(format!("{bundle_id} is not a derived scalar"))
915 })?;
916 let inputs = &derivation.inputs;
917 let derived = match derivation.kind {
918 DerivationKind::PrecipitationType => derive_ptype(&values, inputs)?,
919 DerivationKind::ClearAirTurbulence => {
920 let level = derivation.level_hpa.expect("validated: a surface");
921 let grid = grids.for_variable(&inputs[0])?;
922 let plane = |name: &str| -> Result<&[f64]> {
925 uncropped
926 .iter()
927 .chain(values.iter())
928 .find(|(id, _)| id == name)
929 .map(|(_, plane)| plane.as_slice())
930 .ok_or_else(|| EncodeError::conversion(format!("missing {name} plane for {bundle_id}")))
931 };
932 derive_cat_plane(plane, bundle_id, level, inputs, grid, &source.cat_calibration)?
933 }
934 DerivationKind::ThetaE => {
935 let level = derivation.level_hpa.expect("validated: a surface");
936 let plane = |name: &str| -> Result<&Vec<f64>> {
937 values
938 .iter()
939 .find(|(id, _)| id == name)
940 .map(|(_, plane)| plane)
941 .ok_or_else(|| EncodeError::conversion(format!("missing {name} plane for {bundle_id}")))
942 };
943 derive_theta_e(plane(&inputs[0])?, plane(&inputs[1])?, level)
944 }
945 other => {
946 return Err(EncodeError::conversion(format!(
947 "{bundle_id} is a scalar bundle derived by {other:?}, which is not a per-frame algorithm"
948 )))
949 }
950 };
951 values.push(((*bundle_id).to_string(), derived));
952 }
953 values.retain(|(name, _)| !drop_ids.contains(name));
954
955 let mut codes = Vec::with_capacity(values.len());
956 let mut stats = Vec::with_capacity(values.len());
957 for (variable_id, plane_values) in &values {
958 let book = registry.codebook(profile, variable_id)?;
959 let mut plane_codes = vec![0u8; plane_values.len()];
960 book.quantize(plane_values, &mut plane_codes)?;
961 match &book.book {
962 Book::Linear(linear) => {
963 let mut clamped = 0u64;
964 let mut max_error = 0.0f64;
965 for (value, code) in plane_values.iter().zip(&plane_codes) {
966 if *value < linear.minimum || *value > linear.maximum {
967 clamped += 1;
968 } else {
969 max_error = max_error.max((linear.decode(*code) - value).abs());
970 }
971 }
972 stats.push(PlaneStats {
973 variable_id: variable_id.clone(),
974 max_abs_error: max_error,
975 clamped_points: clamped,
976 overflow_points: 0,
977 });
978 }
979 Book::Precipitation(precipitation) => {
980 let overflow = plane_codes
981 .iter()
982 .filter(|code| u16::from(**code) == precipitation.overflow_code)
983 .count() as u64;
984 stats.push(PlaneStats {
985 variable_id: variable_id.clone(),
986 max_abs_error: 0.0,
987 clamped_points: 0,
988 overflow_points: overflow,
989 });
990 }
991 }
992 codes.push((variable_id.clone(), plane_codes));
993 if let Some(spool) = series_spool.filter(|spool| spool.contains(variable_id)) {
998 spool.quantize_and_write(variable_id, lead, plane_values)?;
999 }
1000 }
1001 Ok((lead, codes, stats))
1002}
1003
1004fn bundle_chunks(
1021 variable_ids: &[&str],
1022 offsets: &[i64],
1023 codes: &BTreeMap<i64, Vec<(String, Vec<u8>)>>,
1024 geometry: &TileGeometry,
1025 registry: &Registry,
1026) -> Result<ChunkTables> {
1027 let mut variables: Vec<VariableEntry> = Vec::with_capacity(variable_ids.len());
1028 for (index, variable_id) in variable_ids.iter().enumerate() {
1029 variables.push(VariableEntry {
1030 variable_id: index as u8 + 1,
1031 predictor: if registry.is_raw(variable_id)? {
1032 Predictor::Raw
1033 } else {
1034 Predictor::Previous
1035 },
1036 });
1037 }
1038
1039 let names: BTreeMap<u8, &str> = variable_ids
1041 .iter()
1042 .enumerate()
1043 .map(|(index, variable_id)| (index as u8 + 1, *variable_id))
1044 .collect();
1045 let plane = |offset: i64, variable_id: u8| -> Result<&[u8]> {
1046 let name = names[&variable_id];
1047 codes
1048 .get(&offset)
1049 .and_then(|planes| planes.iter().find(|(id, _)| id == name))
1050 .map(|(_, plane)| plane.as_slice())
1051 .ok_or_else(|| {
1052 EncodeError::conversion(format!("missing {name} plane at offset {offset}"))
1053 })
1054 };
1055 let (groups, raw) = build_chunks(offsets, &variables, &plane, geometry)?;
1056 Ok(ChunkTables {
1057 variables,
1058 groups,
1059 chunks: raw
1060 .into_iter()
1061 .map(|(entry, payload)| ChunkPayload { entry, payload })
1062 .collect(),
1063 })
1064}
1065
1066fn crc32_hex(bytes: &[u8]) -> String {
1067 format!("{:08x}", binformat::crc32_plane(bytes))
1068}
1069
1070const BUNDLE_WRITERS: usize = 4;
1075
1076fn write_variable_bundle(
1077 variable_id: &str,
1078 output: &Path,
1079 metadata: &Value,
1080 geometry: &TileGeometry,
1081 tables: ChunkTables,
1082 frame_count: u32,
1083 zstd_level: i32,
1084 options: &ConvertOptions,
1085 pool: &rayon::ThreadPool,
1086) -> Result<Value> {
1087 log!(
1088 options,
1089 "compressing {} {variable_id} chunks at zstd level {zstd_level}",
1090 tables.chunks.len()
1091 );
1092 let tables = compress_all(tables, zstd_level, pool)?;
1093 let metadata_json = serde_json::to_string(metadata).expect("serializable metadata");
1094 let bundle_bytes =
1095 binformat::write_bundle_v2(output, &metadata_json, geometry, &tables, frame_count)?;
1096 log!(
1097 options,
1098 "wrote {} ({:.2} MB)",
1099 output.display(),
1100 bundle_bytes.len() as f64 / 1e6
1101 );
1102
1103 verify_bundle_bytes(&bundle_bytes)?;
1107 log!(
1108 options,
1109 "verified {} {variable_id} chunks by full read-back decode",
1110 tables.chunks.len()
1111 );
1112
1113 let mut report = Map::new();
1114 report.insert("variable".into(), json!(variable_id));
1115 report.insert("output".into(), json!(output.display().to_string()));
1116 report.insert("byteLength".into(), json!(bundle_bytes.len()));
1117 report.insert("crc32".into(), json!(crc32_hex(&bundle_bytes)));
1118 Ok(Value::Object(report))
1119}
1120
1121fn compress_all(
1122 tables: ChunkTables,
1123 zstd_level: i32,
1124 pool: &rayon::ThreadPool,
1125) -> Result<ChunkTables> {
1126 use rayon::prelude::*;
1127
1128 let ChunkTables {
1129 variables,
1130 groups,
1131 chunks,
1132 } = tables;
1133 let chunks = pool.install(|| {
1134 chunks
1135 .into_par_iter()
1136 .map(|chunk| {
1137 let payload = zstd_compress(&chunk.payload, zstd_level)?;
1138 Ok(ChunkPayload {
1139 entry: ChunkEntry {
1140 compressed_length: payload.len() as u32,
1141 crc32: chunk.entry.crc32,
1142 },
1143 payload,
1144 })
1145 })
1146 .collect::<Result<Vec<_>>>()
1147 })?;
1148 Ok(ChunkTables {
1149 variables,
1150 groups,
1151 chunks,
1152 })
1153}
1154
1155pub(crate) fn zstd_compress(payload: &[u8], level: i32) -> Result<Vec<u8>> {
1156 use zstd::zstd_safe::{CCtx, CParameter};
1161
1162 let mut context = CCtx::create();
1163 for parameter in [
1164 CParameter::CompressionLevel(level),
1165 CParameter::ChecksumFlag(true),
1166 ] {
1167 context.set_parameter(parameter).map_err(|code| {
1168 EncodeError::conversion(format!("zstd parameter rejected: {}", error_name(code)))
1169 })?;
1170 }
1171 let mut output = Vec::with_capacity(zstd::zstd_safe::compress_bound(payload.len()));
1172 context.compress2(&mut output, payload).map_err(|code| {
1173 EncodeError::conversion(format!("zstd compression failed: {}", error_name(code)))
1174 })?;
1175 Ok(output)
1176}
1177
1178fn error_name(code: usize) -> &'static str {
1179 zstd::zstd_safe::get_error_name(code)
1180}
1181
1182fn verify_bundle_bytes(bytes: &[u8]) -> Result<()> {
1184 let mut bundle = crate::Bundle::open(bytes)
1185 .map_err(|error| EncodeError::bundle(format!("read-back parse failed: {}", error.0)))?;
1186 let variables: Vec<u8> = bundle.variable_ids().to_vec();
1187 let offsets: Vec<u16> = bundle.frame_offsets().to_vec();
1188 for variable_id in variables {
1189 for frame_offset in &offsets {
1190 match bundle.decode_frame(crate::FrameRequest {
1191 variable_id,
1192 frame_offset: *frame_offset,
1193 }) {
1194 Ok(_) => {}
1195 Err(error) => {
1196 return Err(EncodeError::bundle(format!(
1200 "read-back decode failed for variable {variable_id} at offset {frame_offset}: {}",
1201 error.0
1202 )));
1203 }
1204 }
1205 }
1206 }
1207 Ok(())
1208}
1209
1210fn cadence_offsets(
1218 registry: &Registry,
1219 source: &SourceSpec,
1220 bundle_id: &str,
1221 offsets: &[i64],
1222 unit_seconds: i64,
1223) -> Vec<i64> {
1224 offsets
1225 .iter()
1226 .copied()
1227 .filter(|offset| {
1228 let seconds = offset * unit_seconds;
1229 seconds % HOUR_SECONDS == 0
1230 && registry.bundle_carried_at(source, bundle_id, seconds / HOUR_SECONDS)
1231 })
1232 .collect()
1233}
1234
1235pub fn validate_build<'a>(
1241 options: &ConvertOptions,
1242 registry: &'a Registry,
1243) -> Result<(&'a SourceSpec, Vec<&'a str>)> {
1244 let source = registry.source(&options.model)?;
1245 if !registry.knows_profile(&options.profile) {
1246 return Err(EncodeError::conversion(format!(
1247 "unknown profile: {}",
1248 options.profile
1249 )));
1250 }
1251 let published = registry.published_bundle_ids(source);
1252 for bundle_id in &published {
1255 for variable_id in registry.bundle_variable_ids(bundle_id) {
1256 registry.codebook(&options.profile, &variable_id)?;
1257 }
1258 }
1259 if let Some(bundle_ids) = &options.bundle_ids {
1260 let unsupported = bundle_ids
1261 .iter()
1262 .any(|id| !published.contains(&id.as_str()));
1263 if unsupported || bundle_ids.is_empty() {
1264 return Err(EncodeError::conversion(format!(
1265 "{} publishes {published:?}, not {bundle_ids:?}",
1266 source.manifest_model
1267 )));
1268 }
1269 }
1270 Ok((source, published))
1271}
1272
1273pub fn convert_bin(
1291 inputs: &[PathBuf],
1292 output_dir: &Path,
1293 options: &ConvertOptions,
1294 registry: &Registry,
1295) -> Result<Value> {
1296 if !options.container && !options.zarr {
1297 return Err(EncodeError::conversion(
1298 "a build without the container needs the store: pass zarr=True",
1299 ));
1300 }
1301 let (source, published) = validate_build(options, registry)?;
1302
1303 let Discovered {
1305 per_file,
1306 variable_ids,
1307 available_vector_ids,
1308 available_derived_ids,
1309 available_composite_ids,
1310 available_volume_ids,
1311 drop_ids,
1312 grid_path,
1313 plane_source,
1314 producer_versions,
1315 mut variable_families,
1316 } = if source.series_file {
1317 discover_series(inputs, options, source, &published, registry)?
1318 } else {
1319 discover_records(inputs, options, source, &published, registry)?
1320 };
1321
1322 let reference_id = variable_ids[0].as_str();
1324 let lead_seconds: Vec<i64> = per_file
1325 .iter()
1326 .map(|frames| {
1327 frame_of(frames, reference_id)
1328 .map(|frame| frame.lead_seconds)
1329 .ok_or_else(|| EncodeError::conversion(format!("missing {reference_id} record")))
1330 })
1331 .collect::<Result<_>>()?;
1332 let unit_seconds = axis_unit_seconds(&lead_seconds);
1333 let offsets: Vec<i64> = lead_seconds
1334 .iter()
1335 .map(|seconds| seconds / unit_seconds)
1336 .collect();
1337 if *offsets.last().expect("non-empty axis") >= i64::from(NO_DEPENDENCY) {
1338 return Err(EncodeError::conversion(format!(
1339 "the axis needs {} steps of {unit_seconds} s, past the u16 frame offset range",
1340 offsets.last().expect("non-empty axis")
1341 )));
1342 }
1343 let run_time: OffsetDateTime = frame_of(&per_file[0], reference_id)
1344 .expect("reference frame")
1345 .run_time
1346 .to_offset(time::UtcOffset::UTC);
1347 if !source.observation {
1348 let cycle = Some(u32::from(run_time.hour()));
1352 let axis = source.forecast_hours(*offsets.last().expect("non-empty axis"), cycle)?;
1353 let tail: Vec<i64> = axis
1354 .iter()
1355 .copied()
1356 .filter(|hour| *hour >= offsets[0])
1357 .collect();
1358 if offsets != tail {
1359 return Err(EncodeError::conversion(format!(
1360 "forecast hours must be a contiguous run of the {} axis",
1361 source.manifest_model
1362 )));
1363 }
1364 if options.require_complete {
1365 let expected = source.forecast_hours(options.expected_hours, cycle)?;
1366 if offsets != expected {
1367 return Err(EncodeError::conversion(format!(
1368 "complete build requires forecast hours 0 through {} on the {} axis",
1369 options.expected_hours, source.manifest_model
1370 )));
1371 }
1372 }
1373 }
1374
1375 for bundle_id in registry.published_bundle_ids(source) {
1382 let family = bundle_grid_family(registry, source, bundle_id)?;
1383 for variable_id in registry.bundle_variable_ids(bundle_id) {
1384 variable_families.retain(|(id, _)| *id != variable_id);
1385 variable_families.push((variable_id, family));
1386 }
1387 }
1388 let family_of = |variable_id: &str| -> Option<&str> {
1389 variable_families
1390 .iter()
1391 .find(|(id, _)| id == variable_id)
1392 .and_then(|(_, family)| *family)
1393 };
1394 let mut family_order: Vec<Option<&str>> = Vec::new();
1399 for variable_id in &variable_ids {
1400 let family = family_of(variable_id);
1401 if !family_order.contains(&family) {
1402 family_order.push(family);
1403 }
1404 }
1405 let mut grids: Vec<(Option<&str>, GridInfo)> = Vec::new();
1406 for family in &family_order {
1407 let mut family_grid = grid_info(&family_frame_path(&grid_path, *family), source, *family)?;
1408 if options.require_complete {
1409 let (production_grid, _) = source.family_grid(*family)?;
1410 if (family_grid.width, family_grid.height) != production_grid {
1411 let where_ = match family {
1412 Some(family) => format!(" for the {family} family"),
1413 None => String::new(),
1414 };
1415 return Err(EncodeError::conversion(format!(
1416 "production build requires a {}x{} grid{where_}",
1417 production_grid.0, production_grid.1
1418 )));
1419 }
1420 }
1421 if let Some(bbox) = options.bbox {
1422 family_grid = crop_grid(family_grid, bbox)?;
1423 log!(
1424 options,
1425 "cropped {} to {}x{} ({bbox:?})",
1426 family.unwrap_or("the run"),
1427 family_grid.width,
1428 family_grid.height
1429 );
1430 }
1431 grids.push((*family, family_grid));
1432 }
1433 let grid_for = |family: Option<&str>| -> &GridInfo {
1434 &grids
1435 .iter()
1436 .find(|(held, _)| *held == family)
1437 .expect("every family in play has a grid")
1438 .1
1439 };
1440 let grid = grid_for(family_order[0]).clone();
1443 let read_grids = PlaneGrids(
1445 variable_ids
1446 .iter()
1447 .map(|variable_id| {
1448 (
1449 variable_id.clone(),
1450 grid_for(family_of(variable_id)).clone(),
1451 )
1452 })
1453 .collect(),
1454 );
1455
1456 log!(
1458 options,
1459 "extracting and quantizing {} files with {} workers",
1460 per_file.len(),
1461 options.extract_workers
1462 );
1463 let precipitation: Option<DerivedPrecipitation> = registry
1466 .derived_precipitation(source)?
1467 .filter(|(_, raw_id)| variable_ids.contains(raw_id));
1468 let plan = sharing_plan(
1469 &per_file,
1470 precipitation.as_ref().map(|(_, raw_id)| raw_id.as_str()),
1471 source,
1472 )?;
1473 let interval_pairs: Vec<DerivedPrecipitation> = registry
1476 .interval_precipitation_pairs(source)
1477 .into_iter()
1478 .filter(|(_, total_id)| variable_ids.contains(total_id))
1479 .collect();
1480 let interval_starts: Vec<Option<i64>> = per_file
1481 .iter()
1482 .enumerate()
1483 .map(|(index, frames)| {
1484 let held = interval_pairs
1485 .iter()
1486 .find_map(|(_, total_id)| frame_of(frames, total_id));
1487 held.map(|frame| interval_start(&per_file, index, frame, source))
1488 .transpose()
1489 })
1490 .collect::<Result<_>>()?;
1491 let derived_vector_ids: Vec<&str> = available_vector_ids
1492 .iter()
1493 .copied()
1494 .filter(|bundle_id| registry.is_derived_vector(bundle_id))
1495 .collect();
1496 let derived_scalar_ids: Vec<&str> = available_derived_ids.clone();
1497 let rotated_vector_ids = grid_relative_vectors(registry, source, &available_vector_ids)?;
1498 let widened = if options.zarr {
1504 registry.series_widened_ids(&options.series_bundle_ids, options.bundle_ids.as_deref())
1505 } else {
1506 Vec::new()
1507 };
1508 let series_spool = SeriesSpool::create(
1509 &std::env::temp_dir(),
1510 widened
1511 .iter()
1512 .map(|variable_id| {
1513 let grid = grid_for(family_of(variable_id));
1514 let codebook = registry
1515 .series_codebook(variable_id)
1516 .expect("a widened variable has one")
1517 .clone();
1518 (variable_id.clone(), codebook, grid.width * grid.height)
1519 })
1520 .collect(),
1521 &offsets,
1522 unit_seconds,
1523 )?;
1524 let results = for_each_ordered(per_file.len(), options.extract_workers, |index| {
1525 let (previous, own) = plan[index].clone();
1526 quantize_file(
1527 &per_file[index],
1528 &read_grids,
1529 &options.profile,
1530 &plane_source,
1531 source,
1532 precipitation.as_ref(),
1533 &interval_pairs,
1534 interval_starts[index],
1535 previous,
1536 own,
1537 &derived_vector_ids,
1538 &drop_ids,
1539 &derived_scalar_ids,
1540 &rotated_vector_ids,
1541 registry,
1542 series_spool.as_ref(),
1543 )
1544 })?;
1545
1546 let mut stats: Vec<PlaneStats> = Vec::new();
1547 let mut codes_by_offset: BTreeMap<i64, Vec<(String, Vec<u8>)>> = BTreeMap::new();
1548 for (lead, codes, file_stats) in results {
1549 codes_by_offset.insert(lead / unit_seconds, codes);
1550 stats.extend(file_stats);
1551 }
1552 log!(
1553 options,
1554 "quantized {} planes",
1555 codes_by_offset.values().map(Vec::len).sum::<usize>()
1556 );
1557
1558 let mut scalar_variable_ids: Vec<&str> = source
1562 .bundle_scalar_ids
1563 .iter()
1564 .map(String::as_str)
1565 .filter(|id| registry.scalar_derivation(id).is_none() || available_derived_ids.contains(id))
1566 .collect();
1567 if let Some(bundle_ids) = &options.bundle_ids {
1568 scalar_variable_ids.retain(|id| bundle_ids.iter().any(|wanted| wanted == id));
1569 }
1570 let mut encoded_variable_ids: Vec<String> = scalar_variable_ids
1571 .iter()
1572 .map(|id| (*id).to_string())
1573 .collect();
1574 for bundle_id in available_vector_ids
1575 .iter()
1576 .chain(&available_composite_ids)
1577 .chain(&available_volume_ids)
1578 {
1579 encoded_variable_ids.extend(registry.bundle_variable_ids(bundle_id));
1580 }
1581 let mut companion_variable_ids: Vec<&str> = scalar_variable_ids
1586 .iter()
1587 .copied()
1588 .filter(|id| {
1589 registry
1590 .variable(id)
1591 .is_ok_and(|spec| spec.companions.contains(&Companion::Poster))
1592 })
1593 .collect();
1594
1595 let mut variable_offsets: BTreeMap<String, Vec<i64>> = encoded_variable_ids
1602 .iter()
1603 .map(|id| (id.clone(), offsets.clone()))
1604 .collect();
1605 if offsets.len() > 1 && offsets[0] == 0 {
1610 for variable_id in registry.analysis_optional_ids(source, &scalar_variable_ids) {
1611 variable_offsets.insert(variable_id.to_string(), offsets[1..].to_vec());
1612 }
1613 }
1614 let mut late_ids: Vec<String> = Vec::new();
1618 for bundle_id in &scalar_variable_ids {
1619 if !registry.bundle_is_cadenced(source, bundle_id) {
1620 continue;
1621 }
1622 let kept = cadence_offsets(
1623 registry,
1624 source,
1625 bundle_id,
1626 &variable_offsets[*bundle_id],
1627 unit_seconds,
1628 );
1629 if kept.is_empty() {
1630 late_ids.push((*bundle_id).to_string());
1631 } else {
1632 variable_offsets.insert((*bundle_id).to_string(), kept);
1633 }
1634 }
1635 if !late_ids.is_empty() {
1636 eprintln!(
1637 "WARNING building without {}, which start past the last frame of this run",
1638 late_ids.join(", ")
1639 );
1640 scalar_variable_ids.retain(|id| !late_ids.iter().any(|late| late == id));
1641 companion_variable_ids.retain(|id| !late_ids.iter().any(|late| late == id));
1642 encoded_variable_ids.retain(|id| !late_ids.contains(id));
1643 for id in &late_ids {
1644 variable_offsets.remove(id);
1645 }
1646 }
1647 for variable_id in &encoded_variable_ids {
1651 if registry.is_static(variable_id) {
1652 variable_offsets.insert(variable_id.clone(), vec![offsets[0]]);
1653 }
1654 }
1655
1656 std::fs::create_dir_all(output_dir).map_err(|error| {
1658 EncodeError::conversion(format!("cannot create {}: {error}", output_dir.display()))
1659 })?;
1660 let mut poster_reports: BTreeMap<&str, Value> = BTreeMap::new();
1661 for variable_id in &companion_variable_ids {
1662 let first = variable_offsets[*variable_id][0];
1663 let plane = codes_by_offset[&first]
1664 .iter()
1665 .find(|(name, _)| name == variable_id)
1666 .map(|(_, plane)| plane)
1667 .ok_or_else(|| {
1668 EncodeError::conversion(format!("missing {variable_id} plane at the first frame"))
1669 })?;
1670 let (payload, poster_grid) = encode_poster(plane, grid_for(family_of(variable_id)))?;
1671 let poster_path = output_dir.join(format!("{variable_id}.poster.bin"));
1672 binformat::write_atomic(&poster_path, &payload)?;
1673 let metadata = build_metadata(
1674 run_time,
1675 &variable_offsets[*variable_id],
1676 &poster_grid,
1677 &options.profile,
1678 &[variable_id],
1679 source,
1680 unit_seconds,
1681 &producer_versions,
1682 registry,
1683 )?;
1684 poster_reports.insert(
1685 variable_id,
1686 json!({
1687 "path": poster_path.display().to_string(),
1688 "width": poster_grid.width,
1689 "height": poster_grid.height,
1690 "byteLength": payload.len(),
1691 "crc32": crc32_hex(&payload),
1692 "metadataJson": dumps_default(&metadata),
1693 }),
1694 );
1695 log!(
1696 options,
1697 "wrote {} ({:.1} KB)",
1698 poster_path.display(),
1699 payload.len() as f64 / 1e3
1700 );
1701 }
1702
1703 let ladder: Vec<Rung<'_>> = if options.skip_variants {
1713 Vec::new()
1714 } else {
1715 build_ladder(
1716 &source.variant_factors,
1717 &grids,
1718 &codes_by_offset,
1719 |name| grid_for(family_of(name)),
1720 &options.profile,
1721 registry,
1722 )?
1723 };
1724
1725 let mut submit_order: Vec<&str> = available_volume_ids.clone();
1729 submit_order.extend_from_slice(&available_composite_ids);
1730 submit_order.extend_from_slice(&available_vector_ids);
1731 submit_order.extend_from_slice(&scalar_variable_ids);
1732 let mut report_order: Vec<&str> = scalar_variable_ids.clone();
1733 report_order.extend_from_slice(&available_vector_ids);
1734 report_order.extend_from_slice(&available_composite_ids);
1735 report_order.extend_from_slice(&available_volume_ids);
1736
1737 let mut tiers: Vec<Tier<'_>> = Vec::new();
1745 for bundle_id in &submit_order {
1746 let family = family_of(registry.bundle_variable_ids(bundle_id)[0].as_str());
1750 tiers.push(Tier {
1751 bundle_id,
1752 suffix: "",
1753 factor: 1,
1754 grid: grid_for(family),
1755 codes: &codes_by_offset,
1756 });
1757 for rung in &ladder {
1758 tiers.push(Tier {
1759 bundle_id,
1760 suffix: rung.suffix.as_str(),
1761 factor: rung.factor,
1762 grid: &rung
1763 .grids
1764 .iter()
1765 .find(|(held, _)| *held == family)
1766 .expect("every family in play has a rung")
1767 .1,
1768 codes: &rung.codes_by_offset,
1769 });
1770 }
1771 }
1772 let mut shared_stores: Vec<(usize, PathBuf)> = Vec::new();
1777 if options.zarr {
1778 let mut tiers_in_play: Vec<(usize, &str)> = vec![(1, "")];
1779 tiers_in_play.extend(
1780 ladder
1781 .iter()
1782 .map(|rung| (rung.factor, rung.suffix.as_str())),
1783 );
1784 for (factor, suffix) in tiers_in_play {
1785 let store = output_dir.join(format!("{}{suffix}.zarr", zarrstore::SHARED_STORE_STEM));
1786 let group = store.join("zarr.json");
1787 if group.is_file() {
1788 std::fs::remove_file(&group).map_err(|error| {
1789 EncodeError::conversion(format!("cannot remove {}: {error}", group.display()))
1790 })?;
1791 }
1792 shared_stores.push((factor, store));
1793 }
1794 }
1795 let shared_store = |factor: usize| -> &Path {
1796 &shared_stores
1797 .iter()
1798 .find(|(held, _)| *held == factor)
1799 .expect("every tier has a shared store")
1800 .1
1801 };
1802 let pool = zarrstore::compression_pool(options.compress_workers)?;
1803 let write_tier = |tier: &Tier<'_>| -> Result<(Value, Option<zarrstore::BundleWrite>)> {
1804 let bundle_variables: Vec<String> = registry.bundle_variable_ids(tier.bundle_id);
1805 let variables: Vec<&str> = bundle_variables.iter().map(String::as_str).collect();
1806 let bundle_offsets: &[i64] = &variable_offsets[variables[0]];
1807 let (_, family_tile) = source.family_grid(family_of(variables[0]))?;
1808 let metadata = build_metadata(
1809 run_time,
1810 bundle_offsets,
1811 tier.grid,
1812 &options.profile,
1813 &variables,
1814 source,
1815 unit_seconds,
1816 &producer_versions,
1817 registry,
1818 )?;
1819 let tile = bundle_tile(family_tile, tier.grid, tier.factor);
1820 let mut report = if options.container {
1821 let geometry = TileGeometry::new(
1822 tier.grid.width as u32,
1823 tier.grid.height as u32,
1824 tile.0 as u32,
1825 tile.1 as u32,
1826 )
1827 .map_err(|error| EncodeError::conversion(error.0))?;
1828 let tables =
1829 bundle_chunks(&variables, bundle_offsets, tier.codes, &geometry, registry)?;
1830 write_variable_bundle(
1831 tier.bundle_id,
1832 &output_dir.join(format!("{}{}.xue", tier.bundle_id, tier.suffix)),
1833 &metadata,
1834 &geometry,
1835 tables,
1836 bundle_offsets.len() as u32,
1837 options.zstd_level,
1838 options,
1839 &pool,
1840 )?
1841 } else {
1842 json!({"variable": tier.bundle_id, "container": false})
1843 };
1844 let mut bundle_write = None;
1845 if options.zarr {
1846 let mut store_variables = Vec::with_capacity(variables.len());
1851 for variable_id in &variables {
1852 let planes = bundle_offsets
1853 .iter()
1854 .map(|offset| {
1855 tier.codes
1856 .get(offset)
1857 .and_then(|planes| planes.iter().find(|(id, _)| id == variable_id))
1858 .map(|(_, plane)| plane.as_slice())
1859 .ok_or_else(|| {
1860 EncodeError::conversion(format!(
1861 "missing {variable_id} plane at offset {offset}"
1862 ))
1863 })
1864 })
1865 .collect::<Result<Vec<_>>>()?;
1866 store_variables.push(zarrstore::StoreVariable {
1867 id: (*variable_id).to_owned(),
1868 previous: !registry.is_raw(variable_id)?,
1869 planes,
1870 });
1871 }
1872 let codes = zarrstore::StoreCodes {
1873 metadata: &metadata,
1874 variables: store_variables,
1875 tile,
1876 };
1877 let store_path = shared_store(tier.factor);
1878 let store = zarrstore::write_bundle_arrays(
1879 &codes,
1880 store_path,
1881 tier.bundle_id,
1882 &store_dimensions(registry, source, tier.bundle_id)?,
1883 &pool,
1884 )?;
1885 log!(
1886 options,
1887 "wrote {} into {} ({:.2} MB)",
1888 tier.bundle_id,
1889 store_path.display(),
1890 store.byte_length as f64 / 1e6
1891 );
1892 report["zarr"] = store.to_value();
1893 bundle_write = Some(store);
1894 if tier.factor == 1
1895 && options
1896 .series_bundle_ids
1897 .iter()
1898 .any(|id| id == tier.bundle_id)
1899 {
1900 let series_path = output_dir.join(format!("{}.series.zarr", tier.bundle_id));
1905 let series = write_series_store(
1906 &codes,
1907 &variables,
1908 bundle_offsets,
1909 series_spool.as_ref(),
1910 &series_path,
1911 &pool,
1912 );
1913 if let Some(spool) = &series_spool {
1914 for variable_id in &variables {
1915 spool.release(variable_id);
1916 }
1917 }
1918 let series = series?;
1919 log!(
1920 options,
1921 "wrote {} ({:.2} MB)",
1922 series_path.display(),
1923 series.byte_length as f64 / 1e6
1924 );
1925 report["series"] = series.to_value();
1926 }
1927 }
1928 if tier.factor > 1 {
1929 let byte_length = if options.container {
1932 report["byteLength"].as_u64()
1933 } else {
1934 report["zarr"]["byteLength"].as_u64()
1935 }
1936 .unwrap_or(0) as usize;
1937 let object = report.as_object_mut().expect("report object");
1938 object.insert("width".into(), json!(tier.grid.width));
1939 object.insert("height".into(), json!(tier.grid.height));
1940 object.insert(
1941 "bandwidth".into(),
1942 json!(playback_bandwidth(byte_length, bundle_offsets.len())),
1943 );
1944 }
1945 Ok((report, bundle_write))
1946 };
1947 let written = for_each_ordered(tiers.len(), BUNDLE_WRITERS, |index| {
1948 write_tier(&tiers[index])
1949 })?;
1950 drop(series_spool);
1952
1953 let mut full_reports: BTreeMap<&str, Value> = BTreeMap::new();
1954 let mut variant_reports: BTreeMap<&str, Vec<Value>> = BTreeMap::new();
1955 let mut store_writes: Vec<((usize, &str), zarrstore::BundleWrite)> = Vec::new();
1956 for (tier, (report, bundle_write)) in tiers.iter().zip(written) {
1957 if let Some(bundle_write) = bundle_write {
1958 store_writes.push(((tier.factor, tier.bundle_id), bundle_write));
1959 }
1960 if tier.factor == 1 {
1961 full_reports.insert(tier.bundle_id, report);
1962 } else {
1963 variant_reports
1964 .entry(tier.bundle_id)
1965 .or_default()
1966 .push(report);
1967 }
1968 }
1969
1970 for (factor, store) in &shared_stores {
1974 let writes = report_order
1975 .iter()
1976 .map(|bundle_id| {
1977 store_writes
1978 .iter()
1979 .find(|((held_factor, held_id), _)| {
1980 held_factor == factor && held_id == bundle_id
1981 })
1982 .map(|(_, bundle_write)| bundle_write)
1983 .ok_or_else(|| {
1984 EncodeError::bundle(format!(
1985 "{bundle_id} was not written into {}",
1986 store.display()
1987 ))
1988 })
1989 })
1990 .collect::<Result<Vec<_>>>()?;
1991 let (part, crc32) = zarrstore::write_part(store, &writes)?;
1992 log!(options, "wrote {}", part.display());
1993 let rung = ladder.iter().position(|rung| rung.factor == *factor);
1994 for bundle_id in &report_order {
1995 let report = match rung {
1996 None => full_reports.get_mut(bundle_id),
1997 Some(index) => variant_reports
1998 .get_mut(bundle_id)
1999 .and_then(|reports| reports.get_mut(index)),
2000 }
2001 .expect("every bundle has a report on every tier");
2002 report["zarr"]["crc32"] = json!(crc32);
2003 }
2004 }
2005
2006 let bundle_reports: Vec<Value> = report_order
2007 .iter()
2008 .map(|bundle_id| full_reports[bundle_id].clone())
2009 .collect();
2010
2011 let report = build_report(
2013 output_dir,
2014 source,
2015 &grid,
2016 options,
2017 &bundle_reports,
2018 &variant_reports,
2019 &poster_reports,
2020 &stats,
2021 &available_vector_ids,
2022 &encoded_variable_ids,
2023 registry,
2024 )?;
2025
2026 if let Some(manifest_path) = &options.manifest_path {
2028 write_manifest(
2029 manifest_path,
2030 options,
2031 source,
2032 &bundle_reports,
2033 &variant_reports,
2034 &poster_reports,
2035 grid_for,
2036 &offsets,
2037 unit_seconds,
2038 run_time,
2039 registry,
2040 )?;
2041 }
2042
2043 Ok(Value::Object(report))
2044}
2045
2046pub fn zstd_version() -> String {
2047 let version = zstd::zstd_safe::version_number();
2048 format!(
2049 "{}.{}.{}",
2050 version / 10_000,
2051 (version / 100) % 100,
2052 version % 100
2053 )
2054}
2055
2056fn interval_start(
2065 per_file: &[FileFrames],
2066 index: usize,
2067 frame: &SourceFrame,
2068 source: &SourceSpec,
2069) -> Result<i64> {
2070 let hour = frame.lead_seconds / HOUR_SECONDS;
2071 if index > 0 {
2072 return Ok(per_file[index - 1][0].1.lead_seconds / HOUR_SECONDS);
2073 }
2074 let cycle = frame.run_time.to_offset(time::UtcOffset::UTC).hour();
2075 let axis = source.forecast_hours(hour, Some(u32::from(cycle)))?;
2076 match axis.get(axis.len().wrapping_sub(2)) {
2077 Some(&start) => Ok(start),
2078 None if hour > 0 => Ok(0),
2079 None => Err(EncodeError::conversion(format!(
2080 "the interval precipitation frame at hour {hour} names no interval"
2081 ))),
2082 }
2083}
2084
2085type SharingPlan = Vec<(
2092 Option<(i64, Option<Arc<PlaneSlot>>)>,
2093 Option<Arc<PlaneSlot>>,
2094)>;
2095
2096fn sharing_plan(
2097 per_file: &[FileFrames],
2098 raw_precipitation_id: Option<&str>,
2099 source: &SourceSpec,
2100) -> Result<SharingPlan> {
2101 let mut plan: SharingPlan = Vec::with_capacity(per_file.len());
2102 let mut previous_slot: Option<Arc<PlaneSlot>> = None;
2103 for (index, frames) in per_file.iter().enumerate() {
2104 let frame = raw_precipitation_id.and_then(|id| frame_of(frames, id));
2105 let previous = match (&previous_slot, frame) {
2106 _ if frame.is_some() && source.interval_precipitation => Some((
2107 interval_start(per_file, index, frame.expect("a frame"), source)?,
2108 None,
2109 )),
2110 (Some(slot), Some(_)) => Some((
2111 frame_of(&per_file[index - 1], raw_precipitation_id.expect("id"))
2112 .expect("predecessor frame")
2113 .lead_seconds
2114 / HOUR_SECONDS,
2115 Some(Arc::clone(slot)),
2116 )),
2117 _ => None,
2118 };
2119 let mut own = None;
2120 if let (Some(frame), Some(raw_id)) = (frame, raw_precipitation_id) {
2121 if !source.interval_precipitation && index + 1 < per_file.len() {
2122 if let Some(successor) = frame_of(&per_file[index + 1], raw_id) {
2123 let hour = frame.lead_seconds / HOUR_SECONDS;
2124 let shares = source.accumulated_precipitation
2128 || average_window_start(
2129 successor.lead_seconds / HOUR_SECONDS,
2130 source.precipitation_window_hours(),
2131 )? < hour;
2132 if shares {
2133 own = Some(Arc::new(PlaneSlot::default()));
2134 }
2135 }
2136 }
2137 }
2138 previous_slot = own.clone();
2139 plan.push((previous, own));
2140 }
2141 Ok(plan)
2142}
2143
2144#[cfg(test)]
2145mod grid_family_tests {
2146 use super::{bundle_grid_family, grid_family_of};
2147 use crate::encode::registry::Registry;
2148
2149 #[test]
2155 fn every_bundle_is_built_on_one_grid() {
2156 let registry = Registry::embedded();
2157 let cfs = registry.source("cfs").expect("cfs");
2158 for bundle_id in [
2159 "tmp2m", "prate", "tcdc", "dswrf", "tmpsfc", "icec", "icetk", "wind10m",
2160 ] {
2161 assert_eq!(
2162 bundle_grid_family(®istry, cfs, bundle_id).expect("one grid"),
2163 None,
2164 "{bundle_id}"
2165 );
2166 }
2167 for bundle_id in [
2168 "prmsl", "hgt1000", "hgt850", "hgt700", "hgt500", "hgt200", "tmp1000", "tmp850",
2169 "tmp700", "tmp500", "tmp250", "tmp200", "vvel500", "wind1000", "wind925", "wind850",
2170 "wind700", "wind500", "wind250", "wind200", "qflux925", "qflux850", "qflux700",
2171 "qflux500",
2172 ] {
2173 assert_eq!(
2174 bundle_grid_family(®istry, cfs, bundle_id).expect("one grid"),
2175 Some("pgb"),
2176 "{bundle_id}"
2177 );
2178 }
2179 for variable_id in &cfs.companion_files[0].variable_ids {
2183 assert_eq!(
2184 grid_family_of(cfs, variable_id),
2185 Some("pgb"),
2186 "{variable_id}"
2187 );
2188 }
2189 for model in [
2190 "gfs", "ecmwf", "ifs", "aifs", "sflux", "hrrr", "rrfs", "gefsaero", "ifshres", "mrms",
2191 "mrms3d",
2192 ] {
2193 let source = registry.source(model).expect(model);
2194 for bundle_id in source
2195 .bundle_scalar_ids
2196 .iter()
2197 .chain(&source.bundle_vector_ids)
2198 .chain(&source.bundle_volume_ids)
2199 {
2200 assert_eq!(
2201 bundle_grid_family(®istry, source, bundle_id).expect("one grid"),
2202 None,
2203 "{model} {bundle_id}"
2204 );
2205 }
2206 }
2207 }
2208}
2209
2210#[cfg(test)]
2211mod composite_tests {
2212 use crate::encode::registry::Registry;
2213
2214 #[test]
2215 fn the_dust_rgb_reads_four_windows_or_three_without_the_11_2_one() {
2216 let registry = Registry::embedded();
2220 for model in ["himawari", "himawarijp", "goeseast", "goeswest"] {
2221 let source = registry.source(model).expect(model);
2222 assert_eq!(
2223 registry.bundle_input_ids(source, "dustrgb"),
2224 ["ir086", "ir104", "ir112", "ir123"],
2225 "{model}"
2226 );
2227 }
2228 let meteosat = registry.source("meteosat").expect("meteosat");
2229 assert_eq!(
2230 registry.bundle_input_ids(meteosat, "dustrgb"),
2231 ["ir086", "ir104", "ir123"]
2232 );
2233 for model in ["himawari", "goeseast", "goeswest", "meteosat"] {
2236 let source = registry.source(model).expect(model);
2237 assert_eq!(
2238 registry.bundle_variable_ids("dustrgb"),
2239 ["dustr", "dustg", "dustb"]
2240 );
2241 assert!(
2242 registry
2243 .published_bundle_ids(source)
2244 .starts_with(&["ir104", "ir039", "dustrgb"]),
2245 "{model}"
2246 );
2247 }
2248 }
2249
2250 #[test]
2251 fn the_debra_confidence_reads_five_windows_and_is_one_variable() {
2252 let registry = Registry::embedded();
2257 assert_eq!(registry.bundle_variable_ids("dustcf"), ["dustcf"]);
2258 assert_eq!(registry.bundle_variable_ids("zhouye"), ["zhouye"]);
2259 for model in ["himawari", "goeseast", "goeswest"] {
2260 let source = registry.source(model).expect(model);
2261 for bundle_id in ["dustcf", "zhouye"] {
2262 assert_eq!(
2263 registry.bundle_input_ids(source, bundle_id),
2264 ["ir039", "wv062", "ir086", "ir104", "ir123"],
2265 "{model} {bundle_id}"
2266 );
2267 }
2268 assert_eq!(
2269 registry.published_bundle_ids(source),
2270 ["ir104", "ir039", "dustrgb", "dustcf", "zhouye", "truecolor"],
2271 "{model}"
2272 );
2273 }
2274 let meteosat = registry.source("meteosat").expect("meteosat");
2275 assert_eq!(
2276 registry.published_bundle_ids(meteosat),
2277 ["ir104", "ir039", "dustrgb", "truecolor"]
2278 );
2279 }
2280
2281 #[test]
2282 fn the_true_colour_reads_four_bands_or_three_without_the_green_one() {
2283 let registry = Registry::embedded();
2287 assert_eq!(
2288 registry.bundle_variable_ids("truecolor"),
2289 ["truer", "trueg", "trueb"]
2290 );
2291 for model in ["himawari", "himawarijp", "meteosat"] {
2292 let source = registry.source(model).expect(model);
2293 assert_eq!(
2294 registry.bundle_input_ids(source, "truecolor"),
2295 ["vis047", "vis051", "vis064", "nir086", "ir039", "ir104"],
2296 "{model}"
2297 );
2298 }
2299 assert_eq!(
2300 registry.published_bundle_ids(registry.source("himawarijp").expect("himawarijp")),
2301 ["ir104", "ir039", "dustrgb", "truecolor"]
2302 );
2303 for model in ["goeseast", "goeswest"] {
2304 let source = registry.source(model).expect(model);
2305 assert_eq!(
2306 registry.bundle_input_ids(source, "truecolor"),
2307 ["vis047", "vis064", "nir086", "ir039", "ir104"],
2308 "{model}"
2309 );
2310 }
2311 for source in registry.sources().filter(|source| {
2313 source
2314 .bundle_composite_ids
2315 .iter()
2316 .any(|id| id == "truecolor")
2317 }) {
2318 for input in registry.bundle_input_ids(source, "truecolor") {
2319 assert!(source.has_input(&input), "{} {input}", source.id);
2320 }
2321 }
2322 assert!(registry.composite_components("nightmicro").is_none());
2323 }
2324}
2325
2326#[cfg(test)]
2327mod volume_tests {
2328 use crate::encode::registry::Registry;
2329
2330 #[test]
2334 fn the_reflectivity_volume_is_its_33_levels_in_order() {
2335 let registry = Registry::embedded();
2336 let source = registry.source("mrms3d").expect("mrms3d");
2337 let levels = registry.volume_components("refl3d").expect("a volume");
2338 assert_eq!(levels.len(), 33);
2339 assert_eq!(
2340 (levels[0].as_str(), levels[32].as_str()),
2341 ("refl500", "refl19000")
2342 );
2343 assert_eq!(registry.bundle_variable_ids("refl3d"), levels);
2344 assert_eq!(registry.bundle_input_ids(source, "refl3d"), levels);
2345 assert_eq!(registry.published_bundle_ids(source), ["refl3d"]);
2346 for variable_id in levels {
2347 assert!(registry.is_raw(variable_id).unwrap(), "{variable_id}");
2348 }
2349 for variable_id in ["prate", "cref", "ptype", "cat300"] {
2350 assert!(registry.is_raw(variable_id).unwrap(), "{variable_id}");
2351 }
2352 for variable_id in ["tmp2m", "ir104", "clw1500"] {
2353 assert!(!registry.is_raw(variable_id).unwrap(), "{variable_id}");
2354 }
2355 assert!(registry.is_raw("refl600").is_err());
2356 for model in ["gfs", "ecmwf", "mrms", "himawari", "cma", "woof"] {
2358 assert!(
2359 !registry
2360 .published_bundle_ids(registry.source(model).expect(model))
2361 .contains(&"refl3d"),
2362 "{model}"
2363 );
2364 }
2365 }
2366
2367 #[test]
2371 fn the_cloud_water_volume_is_its_24_levels_in_order() {
2372 let registry = Registry::embedded();
2373 let source = registry.source("woof").expect("woof");
2374 let levels = registry.volume_components("cloud3d").expect("a volume");
2375 assert_eq!(levels.len(), 24);
2376 assert_eq!(
2377 (levels[0].as_str(), levels[23].as_str()),
2378 ("clw250", "clw12000")
2379 );
2380 assert_eq!(registry.bundle_input_ids(source, "cloud3d"), levels);
2381 assert_eq!(
2382 registry.published_bundle_ids(source),
2383 [
2384 "tmp2m", "prate", "tmpsfc", "dpt2m", "tcdc", "lcdc", "mcdc", "hcdc", "hpbl",
2385 "dswrf", "orog", "prmsl", "wind10m", "wind80m", "cloud3d",
2386 ]
2387 );
2388 for model in [
2389 "gfs", "ecmwf", "hrrr", "rrfs", "ifshres", "mrms3d", "himawari",
2390 ] {
2391 assert!(
2392 !registry
2393 .published_bundle_ids(registry.source(model).expect(model))
2394 .contains(&"cloud3d"),
2395 "{model}"
2396 );
2397 }
2398 }
2399}
2400
2401#[cfg(test)]
2402mod store_dimension_tests {
2403 use super::{cadence_offsets, store_dimensions};
2404 use crate::encode::binformat::HOUR_SECONDS;
2405 use crate::encode::registry::Registry;
2406
2407 fn names(model: &str, bundle_id: &str) -> [String; 3] {
2408 let registry = Registry::embedded();
2409 let source = registry.source(model).expect("source");
2410 store_dimensions(®istry, source, bundle_id).expect("dimensions")
2411 }
2412
2413 #[test]
2419 fn a_bundle_takes_its_own_names_only_where_a_rule_cuts_it() {
2420 assert_eq!(names("gfs", "tmp2m"), ["time", "latitude", "longitude"]);
2421 assert_eq!(names("gfs", "wind10m"), ["time", "latitude", "longitude"]);
2422 assert_eq!(names("gfs", "prate"), ["time", "latitude", "longitude"]);
2423 assert_eq!(names("gfs", "orog"), ["time_orog", "latitude", "longitude"]);
2424 assert_eq!(
2425 names("ecmwf", "prate"),
2426 ["time_prate", "latitude", "longitude"]
2427 );
2428 assert_eq!(
2429 names("ecmwf", "gust"),
2430 ["time_gust", "latitude", "longitude"]
2431 );
2432 assert_eq!(
2433 names("ecmwf", "apcp24gt10"),
2434 ["time_apcp24gt10", "latitude", "longitude"]
2435 );
2436 assert_eq!(names("ecmwf", "prmslsd"), ["time", "latitude", "longitude"]);
2437 assert_eq!(
2438 names("ecmwf", "tmp850sd"),
2439 ["time", "latitude", "longitude"]
2440 );
2441 assert_eq!(
2442 names("ifshres", "dswrf"),
2443 ["time_dswrf", "latitude", "longitude"]
2444 );
2445 assert_eq!(names("cfs", "tmp2m"), ["time", "latitude", "longitude"]);
2446 assert_eq!(
2447 names("cfs", "hgt500"),
2448 ["time", "latitude_pgb", "longitude_pgb"]
2449 );
2450 assert_eq!(
2451 names("cfs", "wind850"),
2452 ["time", "latitude_pgb", "longitude_pgb"]
2453 );
2454 assert_eq!(names("hrrr", "tmp2m"), ["time", "y", "x"]);
2455 assert_eq!(names("hrrr", "wind10m"), ["time", "y", "x"]);
2456 assert_eq!(names("hrrr", "orog"), ["time_orog", "y", "x"]);
2457 assert_eq!(names("rrfs", "smokesfc"), ["time", "y", "x"]);
2458 }
2459
2460 #[test]
2464 fn a_first_hour_and_an_interval_pair_cut_the_axis() {
2465 let document = crate::encode::registry::ensemble_fixture::document().to_string();
2466 let registry = Registry::parse(&document).unwrap();
2467 let source = registry.source("cmageps").unwrap();
2468 let names =
2469 |bundle_id: &str| store_dimensions(®istry, source, bundle_id).expect("dimensions");
2470 assert_eq!(
2471 names("apcp24gt10"),
2472 ["time_apcp24gt10", "latitude", "longitude"]
2473 );
2474 assert_eq!(
2475 names("prateq25"),
2476 ["time_prateq25", "latitude", "longitude"]
2477 );
2478 assert_eq!(names("prate"), ["time_prate", "latitude", "longitude"]);
2479 assert_eq!(names("tmp2mq25"), ["time", "latitude", "longitude"]);
2480 assert_eq!(names("prmslsd"), ["time", "latitude", "longitude"]);
2481 }
2482
2483 fn stepped_registry() -> std::sync::Arc<Registry> {
2487 let mut document = crate::encode::registry::ensemble_fixture::document();
2488 document["sources"]["cmageps"]["variableStepHours"] =
2489 serde_json::json!([["apcp24gt10", 12], ["prmslsd", 6]]);
2490 Registry::parse(&document.to_string()).unwrap()
2491 }
2492
2493 #[test]
2494 fn a_step_gives_a_bundle_its_own_axis() {
2495 let registry = stepped_registry();
2496 let source = registry.source("cmageps").unwrap();
2497 let names =
2498 |bundle_id: &str| store_dimensions(®istry, source, bundle_id).expect("dimensions");
2499 assert_eq!(
2500 names("apcp24gt10"),
2501 ["time_apcp24gt10", "latitude", "longitude"]
2502 );
2503 assert_eq!(names("prmslsd"), ["time_prmslsd", "latitude", "longitude"]);
2505 assert_eq!(names("tmp2mq25"), ["time", "latitude", "longitude"]);
2506 }
2507
2508 #[test]
2509 fn a_step_thins_the_axis_to_its_cadence() {
2510 let registry = stepped_registry();
2511 let source = registry.source("cmageps").unwrap();
2512 let axis: Vec<i64> = (0..=144).step_by(3).chain((150..=240).step_by(6)).collect();
2513 assert_eq!(
2514 cadence_offsets(®istry, source, "apcp24gt10", &axis, HOUR_SECONDS),
2515 (24..=240).step_by(12).collect::<Vec<i64>>()
2516 );
2517 assert_eq!(
2518 cadence_offsets(®istry, source, "prmslsd", &axis, HOUR_SECONDS),
2519 axis.iter()
2520 .copied()
2521 .filter(|hour| hour % 6 == 0)
2522 .collect::<Vec<i64>>()
2523 );
2524 assert!(
2526 cadence_offsets(®istry, source, "apcp24gt10", &[0, 3, 6], HOUR_SECONDS).is_empty()
2527 );
2528 assert_eq!(
2530 cadence_offsets(®istry, source, "apcp24gt10", &[1410, 1440, 2160], 60),
2531 [1440, 2160]
2532 );
2533 }
2534}
2535
2536#[cfg(test)]
2537mod validate_tests {
2538 use super::{validate_build, ConvertOptions};
2539 use crate::encode::registry::Registry;
2540
2541 fn options(model: &str) -> ConvertOptions {
2542 ConvertOptions {
2543 model: model.into(),
2544 ..ConvertOptions::default()
2545 }
2546 }
2547
2548 #[test]
2552 fn a_build_is_validated_from_the_document_alone() {
2553 let registry = Registry::embedded();
2554 let (source, published) = validate_build(&options("gfs"), ®istry).expect("gfs builds");
2555 assert_eq!(source.manifest_model, "GFS");
2556 let every = ConvertOptions {
2557 bundle_ids: Some(published.iter().map(|id| (*id).to_string()).collect()),
2558 ..options("gfs")
2559 };
2560 assert!(validate_build(&every, ®istry).is_ok());
2561
2562 let refusal =
2563 |options: &ConvertOptions| validate_build(options, ®istry).unwrap_err().to_string();
2564 assert_eq!(
2565 refusal(&options("nosuchmodel")),
2566 "unsupported model: nosuchmodel"
2567 );
2568 let profile = ConvertOptions {
2569 profile: "nosuchprofile".into(),
2570 ..options("gfs")
2571 };
2572 assert_eq!(refusal(&profile), "unknown profile: nosuchprofile");
2573 let bundles = ConvertOptions {
2574 bundle_ids: Some(vec!["nosuchbundle".into()]),
2575 ..options("gfs")
2576 };
2577 assert!(refusal(&bundles).starts_with("GFS publishes "));
2578 let none = ConvertOptions {
2579 bundle_ids: Some(Vec::new()),
2580 ..options("gfs")
2581 };
2582 assert!(refusal(&none).starts_with("GFS publishes "));
2583 }
2584}