1use crate::encode::errors::{EncodeError, Result};
8use crate::encode::grid::GridInfo;
9use crate::encode::variables::STANDARD_GRAVITY;
10
11const CAT_SHEAR_LAYERS: [(u32, u32, u32); 3] = [(300, 250, 300), (250, 200, 300), (200, 200, 250)];
17
18fn cat_shear_layer(level: u32) -> Option<(u32, u32)> {
21 CAT_SHEAR_LAYERS
22 .iter()
23 .find(|(at, _, _)| *at == level)
24 .map(|&(_, above, below)| (above, below))
25}
26
27pub fn deaccumulate_precipitation(
34 current_mm: &[f64],
35 previous_mm: Option<&[f64]>,
36 step_hours: i64,
37) -> Vec<f64> {
38 let Some(previous_mm) = previous_mm else {
39 return vec![0.0; current_mm.len()];
40 };
41 current_mm
42 .iter()
43 .zip(previous_mm)
44 .map(|(current, previous)| (current - previous).max(0.0) / step_hours as f64)
45 .collect()
46}
47
48pub const PACKING_STEP_RATIO: f64 = 1.5;
52
53pub fn packing_lattice(plane: &[f64]) -> Option<(f64, f64)> {
58 let mut distinct: Vec<f64> = plane
59 .iter()
60 .copied()
61 .filter(|value| value.is_finite())
62 .collect();
63 distinct.sort_by(f64::total_cmp);
64 distinct.dedup_by(|later, earlier| later == earlier);
66 if distinct.len() < 2 {
67 return None;
68 }
69 let step = distinct
70 .windows(2)
71 .map(|pair| pair[1] - pair[0])
72 .fold(f64::INFINITY, f64::min);
73 Some((distinct[0] + 0.0, step))
74}
75
76pub fn align_packing_steps<'a>(
83 current_mm: &'a [f64],
84 previous_mm: Option<&'a [f64]>,
85) -> (
86 std::borrow::Cow<'a, [f64]>,
87 Option<std::borrow::Cow<'a, [f64]>>,
88) {
89 use std::borrow::Cow;
90 let Some(previous_mm) = previous_mm else {
91 return (Cow::Borrowed(current_mm), None);
92 };
93 let unchanged = (Cow::Borrowed(current_mm), Some(Cow::Borrowed(previous_mm)));
94 let (Some(current), Some(previous)) =
95 (packing_lattice(current_mm), packing_lattice(previous_mm))
96 else {
97 return unchanged;
98 };
99 let coarser = if current.1 >= PACKING_STEP_RATIO * previous.1 {
100 current
101 } else if previous.1 >= PACKING_STEP_RATIO * current.1 {
102 previous
103 } else {
104 return unchanged;
105 };
106 (
108 Cow::Owned(round_onto(current_mm, coarser)),
109 Some(Cow::Owned(round_onto(previous_mm, coarser))),
110 )
111}
112
113fn round_onto(plane: &[f64], (anchor, step): (f64, f64)) -> Vec<f64> {
114 plane
115 .iter()
116 .map(|value| anchor + ((value - anchor) / step).round_ties_even() * step)
117 .collect()
118}
119
120pub fn interval_rate(total_mm: &[f64], step_hours: i64) -> Result<Vec<f64>> {
134 if step_hours <= 0 {
135 return Err(EncodeError::conversion(format!(
136 "an interval precipitation total spans {step_hours} hours"
137 )));
138 }
139 Ok(total_mm
140 .iter()
141 .map(|total| total / step_hours as f64)
142 .collect())
143}
144
145pub fn average_window_start(hour: i64, window_hours: i64) -> Result<i64> {
152 if hour <= 0 {
153 return Err(EncodeError::conversion(
154 "precipitation over a window has no analysis frame",
155 ));
156 }
157 Ok(window_hours * ((hour - 1) / window_hours))
158}
159
160pub fn deaverage_precipitation(
168 current_average: &[f64],
169 hour: i64,
170 previous_average: Option<&[f64]>,
171 previous_hour: Option<i64>,
172 window_hours: i64,
173) -> Result<Vec<f64>> {
174 let window_start = average_window_start(hour, window_hours)?;
175 let accumulated_mm: Vec<f64> = current_average
176 .iter()
177 .map(|value| value * 3600.0 * (hour - window_start) as f64)
178 .collect();
179 let mut previous_mm = vec![0.0; accumulated_mm.len()];
180 let mut interval_start = window_start;
181 if let (Some(previous_average), Some(previous_hour)) = (previous_average, previous_hour) {
182 if !(window_start < previous_hour && previous_hour < hour) {
183 return Err(EncodeError::conversion(
184 "previous averaged frame is outside the current averaging window",
185 ));
186 }
187 previous_mm = previous_average
188 .iter()
189 .map(|value| value * 3600.0 * (previous_hour - window_start) as f64)
190 .collect();
191 interval_start = previous_hour;
192 }
193 Ok(deaccumulate_precipitation(
194 &accumulated_mm,
195 Some(&previous_mm),
196 hour - interval_start,
197 ))
198}
199
200pub fn dewindow_precipitation(
211 current_mm: &[f64],
212 hour: i64,
213 previous_mm: Option<&[f64]>,
214 previous_hour: Option<i64>,
215 window_hours: i64,
216) -> Result<Vec<f64>> {
217 let window_start = average_window_start(hour, window_hours)?;
218 let zeros = vec![0.0; current_mm.len()];
219 let mut predecessor_mm: &[f64] = &zeros;
220 let mut interval_start = window_start;
221 if let (Some(previous_mm), Some(previous_hour)) = (previous_mm, previous_hour) {
222 if !(window_start < previous_hour && previous_hour < hour) {
223 return Err(EncodeError::conversion(
224 "previous accumulated frame is outside the current accumulation window",
225 ));
226 }
227 predecessor_mm = previous_mm;
228 interval_start = previous_hour;
229 }
230 Ok(deaccumulate_precipitation(
231 current_mm,
232 Some(predecessor_mm),
233 hour - interval_start,
234 ))
235}
236
237const THETA_E_MINIMUM_Q: f64 = 1e-7;
240
241const PTYPE_CODES: [f64; 4] = [1.0, 3.0, 8.0, 5.0];
248
249pub fn derive_theta_e(temperature: &[f64], specific_humidity: &[f64], level_hpa: u32) -> Vec<f64> {
257 let p = f64::from(level_hpa);
258 temperature
259 .iter()
260 .zip(specific_humidity)
261 .map(|(temperature_c, humidity_g)| {
262 let t = temperature_c + 273.15;
263 let q = (humidity_g / 1000.0).max(THETA_E_MINIMUM_Q);
264 let r = q / (1.0 - q);
265 let e = p * r / (0.622 + r);
266 let ln_e = (e / 6.112).ln();
267 let dew_point = 243.5 * ln_e / (17.67 - ln_e) + 273.15;
268 let t_lcl = 1.0 / (1.0 / (dew_point - 56.0) + (t / dew_point).ln() / 800.0) + 56.0;
269 let theta = t * (1000.0 / p).powf(0.2854 * (1.0 - 0.28 * r));
270 let r_g = r * 1000.0;
271 theta * ((3.376 / t_lcl - 0.00254) * r_g * (1.0 + 0.00081 * r_g)).exp()
272 })
273 .collect()
274}
275
276pub fn derive_ptype(values: &[(String, Vec<f64>)], inputs: &[String]) -> Result<Vec<f64>> {
285 if inputs.len() != PTYPE_CODES.len() {
286 return Err(EncodeError::conversion(format!(
287 "the precipitation type combines {} flags, not {}",
288 PTYPE_CODES.len(),
289 inputs.len()
290 )));
291 }
292 let plane = |name: &str| -> Result<&[f64]> {
293 values
294 .iter()
295 .find(|(id, _)| id == name)
296 .map(|(_, plane)| plane.as_slice())
297 .ok_or_else(|| EncodeError::conversion(format!("missing {name} plane for ptype")))
298 };
299 let mut codes = vec![0.0f64; plane(&inputs[0])?.len()];
300 for (variable_id, code) in inputs.iter().zip(PTYPE_CODES) {
301 let plane = plane(variable_id)?;
302 for (slot, value) in codes.iter_mut().zip(plane) {
303 if *value > 0.0 {
304 *slot = code;
305 }
306 }
307 }
308 Ok(codes)
309}
310
311pub fn derive_vapour_flux(
318 specific_humidity: &[f64],
319 u_wind: &[f64],
320 v_wind: &[f64],
321) -> (Vec<f64>, Vec<f64>) {
322 let flux = |wind: &[f64]| -> Vec<f64> {
323 specific_humidity
324 .iter()
325 .zip(wind)
326 .map(|(q, w)| q * w / STANDARD_GRAVITY)
327 .collect()
328 };
329 (flux(u_wind), flux(v_wind))
330}
331
332pub fn derive_wave_vector(height: &[f64], direction: &[f64]) -> (Vec<f64>, Vec<f64>) {
341 let mut u = Vec::with_capacity(height.len());
342 let mut v = Vec::with_capacity(height.len());
343 for (h, degrees) in height.iter().zip(direction) {
344 let radians = degrees * (std::f64::consts::PI / 180.0);
345 let negated = -h;
346 u.push(negated * radians.sin());
347 v.push(negated * radians.cos());
348 }
349 (u, v)
350}
351
352pub const EARTH_RADIUS_M: f64 = 6371000.0;
358pub const CAT_POLAR_LATITUDE: f64 = 85.0;
359pub const CAT_TI1_FLOOR: f64 = 1e-12;
360pub const CAT_EDR_LOG_MEAN: f64 = -2.572;
361pub const CAT_EDR_LOG_STD: f64 = 0.5067;
362pub const CAT_EDR_NIL: f64 = 0.10;
366
367fn numpy_maximum(value: f64, floor: f64) -> f64 {
370 if value.is_nan() || value >= floor {
371 value
372 } else {
373 floor
374 }
375}
376
377pub struct CatPlanes<'a> {
380 pub planes: Vec<(&'a str, &'a [f64])>,
381 pub rows: usize,
382 pub columns: usize,
383 pub latitudes: &'a [f64],
385 pub longitude_step: f64,
386 pub latitude_step: f64,
387 pub wraps: bool,
388}
389
390impl CatPlanes<'_> {
391 fn plane(&self, variable_id: &str) -> Result<&[f64]> {
392 self.planes
393 .iter()
394 .find(|(id, _)| *id == variable_id)
395 .map(|(_, plane)| *plane)
396 .ok_or_else(|| {
397 EncodeError::conversion(format!(
398 "missing {variable_id} plane for the turbulence index"
399 ))
400 })
401 }
402}
403
404pub fn ellrod_ti1(input: &CatPlanes, level: u32) -> Result<(Vec<f64>, Vec<bool>)> {
419 let (above, below) = cat_shear_layer(level).ok_or_else(|| {
420 EncodeError::conversion(format!("no clear-air turbulence index on {level} hPa"))
421 })?;
422 let (rows, columns) = (input.rows, input.columns);
423 if input.latitude_step >= 0.0 {
424 return Err(EncodeError::conversion(
425 "the clear-air turbulence index needs a north-to-south grid".to_string(),
426 ));
427 }
428 if rows < 3 || input.latitudes.len() != rows {
429 return Err(EncodeError::conversion(format!(
430 "cannot difference a {rows}-row plane against {} latitudes",
431 input.latitudes.len()
432 )));
433 }
434 let u = input.plane(&format!("ugrd{level}"))?;
435 let v = input.plane(&format!("vgrd{level}"))?;
436 let u_above = input.plane(&format!("ugrd{above}"))?;
437 let v_above = input.plane(&format!("vgrd{above}"))?;
438 let z_above = input.plane(&format!("hgt{above}"))?;
439 let u_below = input.plane(&format!("ugrd{below}"))?;
440 let v_below = input.plane(&format!("vgrd{below}"))?;
441 let z_below = input.plane(&format!("hgt{below}"))?;
442 let cells = rows * columns;
443 for plane in [u, v, u_above, v_above, z_above, u_below, v_below, z_below] {
444 if plane.len() != cells {
445 return Err(EncodeError::conversion(format!(
446 "a {}-point plane is not the {rows} x {columns} grid",
447 plane.len()
448 )));
449 }
450 }
451 let rad = std::f64::consts::PI / 180.0;
452 let two_dx: Vec<f64> = input
453 .latitudes
454 .iter()
455 .map(|latitude| {
456 let cosine = (latitude * rad).cos();
457 let dx = EARTH_RADIUS_M * cosine * (input.longitude_step * rad);
458 2.0 * dx
459 })
460 .collect();
461 let dy = EARTH_RADIUS_M * (-input.latitude_step * rad);
462 let two_dy = 2.0 * dy;
463 let mut ti1 = vec![0.0f64; cells];
464 let mut valid = vec![false; cells];
465 for row in 1..rows - 1 {
466 if input.latitudes[row].abs() > CAT_POLAR_LATITUDE {
467 continue;
468 }
469 let north = (row - 1) * columns;
470 let here = row * columns;
471 let south = (row + 1) * columns;
472 let (first, last) = if input.wraps {
473 (0, columns)
474 } else {
475 (1, columns.saturating_sub(1))
476 };
477 for column in first..last {
478 let east = here + (column + 1) % columns;
479 let west = here + (column + columns - 1) % columns;
480 let dudx = (u[east] - u[west]) / two_dx[row];
481 let dvdx = (v[east] - v[west]) / two_dx[row];
482 let dudy = (u[north + column] - u[south + column]) / two_dy;
483 let dvdy = (v[north + column] - v[south + column]) / two_dy;
484 let dst = dudx - dvdy;
485 let dsh = dvdx + dudy;
486 let deformation = (dst * dst + dsh * dsh).sqrt();
487 let cell = here + column;
488 let du = u_above[cell] - u_below[cell];
489 let dv = v_above[cell] - v_below[cell];
490 let dz = numpy_maximum(z_above[cell] - z_below[cell], 1.0);
491 let shear = (du * du + dv * dv).sqrt() / dz;
492 ti1[cell] = shear * deformation;
493 valid[cell] = true;
494 }
495 }
496 Ok((ti1, valid))
497}
498
499pub fn derive_cat(input: &CatPlanes, level: u32, calibration: (f64, f64)) -> Result<Vec<f64>> {
507 let (mean, std) = calibration;
508 let (ti1, valid) = ellrod_ti1(input, level)?;
509 let b = CAT_EDR_LOG_STD / std;
510 let a = CAT_EDR_LOG_MEAN - b * mean;
511 Ok(ti1
512 .iter()
513 .zip(&valid)
514 .map(|(value, defined)| {
515 if *defined {
516 let ln_ti1 = numpy_maximum(*value, CAT_TI1_FLOOR).ln();
517 nil_below_threshold((a + b * ln_ti1).exp())
518 } else {
519 0.0
520 }
521 })
522 .collect())
523}
524
525fn nil_below_threshold(edr: f64) -> f64 {
529 if edr < CAT_EDR_NIL {
530 0.0
531 } else {
532 edr
533 }
534}
535
536pub fn uncropped_shape(grid: &GridInfo) -> (usize, usize) {
539 match grid.crop {
540 None => (grid.height, grid.width),
541 Some(crop) => (crop.source_height, crop.source_width),
542 }
543}
544
545pub fn uncropped_latitudes(grid: &GridInfo) -> Vec<f64> {
549 let (rows, _) = uncropped_shape(grid);
550 let row_start = grid.crop.map_or(0, |crop| crop.row_start) as f64;
551 (0..rows)
552 .map(|row| grid.first_latitude + (row as f64 - row_start) * grid.latitude_step)
553 .collect()
554}
555
556pub fn uncropped_wraps(grid: &GridInfo) -> bool {
559 let (_, columns) = uncropped_shape(grid);
560 (columns as f64 * grid.longitude_step - 360.0).abs() < 1e-6
561}
562
563pub(super) fn derive_cat_plane<'a>(
568 plane: impl Fn(&str) -> Result<&'a [f64]>,
569 bundle_id: &str,
570 level: u32,
571 inputs: &[String],
572 grid: &GridInfo,
573 calibration: &[(u32, f64, f64)],
574) -> Result<Vec<f64>> {
575 if grid.projection.is_some() {
576 return Err(EncodeError::conversion(format!(
577 "{bundle_id} is derived on a regular grid, and this one is on a map projection"
578 )));
579 }
580 let &(_, mean, std) = calibration
581 .iter()
582 .find(|(at, _, _)| *at == level)
583 .ok_or_else(|| {
584 EncodeError::conversion(format!(
585 "the source publishes {bundle_id} without a ln TI1 calibration for {level} hPa"
586 ))
587 })?;
588 let (rows, columns) = uncropped_shape(grid);
589 let latitudes = uncropped_latitudes(grid);
590 let planes = inputs
591 .iter()
592 .map(|id| Ok((id.as_str(), plane(id)?)))
593 .collect::<Result<Vec<_>>>()?;
594 let edr = derive_cat(
595 &CatPlanes {
596 planes,
597 rows,
598 columns,
599 latitudes: &latitudes,
600 longitude_step: grid.longitude_step,
601 latitude_step: grid.latitude_step,
602 wraps: uncropped_wraps(grid),
603 },
604 level,
605 (mean, std),
606 )?;
607 Ok(match grid.crop {
608 Some(crop) => crop.take(&edr),
609 None => edr,
610 })
611}
612
613#[cfg(test)]
614mod tests {
615 use std::borrow::Cow;
616
617 use super::{align_packing_steps, interval_rate, packing_lattice};
618
619 #[test]
622 fn the_interval_rate_is_the_total_over_the_hours_it_covers() {
623 let total = [0.0, 1.5, 12.0];
624 assert_eq!(
625 interval_rate(&total, 1).expect("an hour"),
626 vec![0.0, 1.5, 12.0]
627 );
628 assert_eq!(
629 interval_rate(&total, 3).expect("three hours"),
630 vec![0.0, 0.5, 4.0]
631 );
632 assert_eq!(
633 interval_rate(&total, 6).expect("six hours"),
634 vec![0.0, 0.25, 2.0]
635 );
636 }
637
638 #[test]
641 fn the_finer_plane_is_rounded_onto_the_coarser_lattice() {
642 let previous = [0.0, 1.0, 3.0, 5.0, 8.0, 9.0];
643 let current = [0.0, 2.0, 4.0, 6.0, 12.0, 10.0];
644 let (current_total, previous_total) = align_packing_steps(¤t, Some(&previous));
645 assert_eq!(&*current_total, ¤t);
646 assert_eq!(
647 previous_total.as_deref(),
648 Some(&[0.0, 0.0, 4.0, 4.0, 8.0, 8.0][..])
649 );
650
651 let (current_total, previous_total) =
652 align_packing_steps(&[0.0, 1.0, 3.0], Some(&[0.0, 2.0, 4.0]));
653 assert_eq!(&*current_total, &[0.0, 0.0, 4.0]);
654 assert_eq!(previous_total.as_deref(), Some(&[0.0, 2.0, 4.0][..]));
655 }
656
657 #[test]
658 fn equal_steps_and_unreadable_lattices_pass_through() {
659 for (current, previous) in [
660 (&[0.0, 1.0, 3.0][..], Some(&[0.0, 1.0, 2.0][..])),
661 (&[0.0, 0.0][..], Some(&[0.0, 1.0, 3.0][..])),
662 (&[0.0, 2.0][..], None),
663 ] {
664 let (current_total, previous_total) = align_packing_steps(current, previous);
665 assert!(matches!(current_total, Cow::Borrowed(_)));
666 assert!(previous_total.is_none_or(|plane| matches!(plane, Cow::Borrowed(_))));
667 }
668 assert_eq!(
669 packing_lattice(&[1.5, 3.5, f64::NAN, 2.5, 1.5]),
670 Some((1.5, 1.0))
671 );
672 assert_eq!(packing_lattice(&[f64::NAN, 4.0]), None);
673 }
674
675 #[test]
676 fn an_interval_of_no_hours_is_a_conversion_error() {
677 for step in [0, -3] {
678 let error = interval_rate(&[0.0; 4], step).expect_err("no interval");
679 assert!(error.to_string().contains("spans"), "{error}");
680 }
681 }
682}
683
684#[cfg(test)]
689mod cat_tests {
690 use super::{
691 derive_cat, derive_cat_plane, ellrod_ti1, nil_below_threshold, numpy_maximum,
692 uncropped_latitudes, CatPlanes, CAT_EDR_LOG_MEAN, CAT_EDR_LOG_STD, CAT_EDR_NIL,
693 CAT_SHEAR_LAYERS, CAT_TI1_FLOOR, EARTH_RADIUS_M,
694 };
695 use crate::encode::errors::{EncodeError, Result};
696 use crate::encode::grid::{CropWindow, GridInfo};
697 use crate::encode::registry::{DerivationKind, Registry};
698 use serde_json::json;
699
700 fn cat_inputs(bundle_id: &str) -> Vec<String> {
702 Registry::embedded()
703 .scalar_derivation(bundle_id)
704 .unwrap()
705 .inputs
706 .clone()
707 }
708
709 const RAD: f64 = std::f64::consts::PI / 180.0;
710
711 fn planes(level: u32, cells: usize, u: &[f64], v: &[f64]) -> Vec<(String, Vec<f64>)> {
715 let &(_, above, below) = CAT_SHEAR_LAYERS
716 .iter()
717 .find(|(at, _, _)| *at == level)
718 .unwrap();
719 let z = vec![9000.0; cells];
720 let mut out = vec![
721 (format!("ugrd{below}"), u.to_vec()),
722 (format!("vgrd{below}"), v.to_vec()),
723 (format!("hgt{below}"), z.clone()),
724 (format!("ugrd{above}"), u.iter().map(|x| x + 10.0).collect()),
725 (format!("vgrd{above}"), v.to_vec()),
726 (
727 format!("hgt{above}"),
728 z.iter().map(|x| x + 1000.0).collect(),
729 ),
730 ];
731 for (id, plane) in [(format!("ugrd{level}"), u), (format!("vgrd{level}"), v)] {
732 if !out.iter().any(|(name, _)| *name == id) {
733 out.push((id, plane.to_vec()));
734 }
735 }
736 out
737 }
738
739 fn set(planes: &mut [(String, Vec<f64>)], id: &str, plane: Vec<f64>) {
740 planes.iter_mut().find(|(name, _)| name == id).unwrap().1 = plane;
741 }
742
743 fn input<'a>(
744 planes: &'a [(String, Vec<f64>)],
745 rows: usize,
746 columns: usize,
747 latitudes: &'a [f64],
748 longitude_step: f64,
749 latitude_step: f64,
750 wraps: bool,
751 ) -> CatPlanes<'a> {
752 CatPlanes {
753 planes: planes
754 .iter()
755 .map(|(id, plane)| (id.as_str(), plane.as_slice()))
756 .collect(),
757 rows,
758 columns,
759 latitudes,
760 longitude_step,
761 latitude_step,
762 wraps,
763 }
764 }
765
766 const ROWS: usize = 9;
767 const COLUMNS: usize = 12;
768
769 fn latitudes() -> Vec<f64> {
770 (0..ROWS).map(|row| 4.0 - 1.0 * row as f64).collect()
771 }
772
773 fn close(actual: f64, expected: f64, rtol: f64) -> bool {
774 (actual - expected).abs() <= rtol * expected.abs()
775 }
776
777 fn noise(seed: u64, cells: usize) -> Vec<f64> {
779 let mut state = seed;
780 (0..cells)
781 .map(|_| {
782 state = state
783 .wrapping_mul(6364136223846793005)
784 .wrapping_add(1442695040888963407);
785 ((state >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0
786 })
787 .collect()
788 }
789
790 #[test]
791 fn pure_stretching_is_the_zonal_gradient_over_dx() {
792 let latitudes = latitudes();
793 let u: Vec<f64> = (0..ROWS * COLUMNS)
794 .map(|cell| 2.0 * (cell % COLUMNS) as f64)
795 .collect();
796 let v = vec![0.0; ROWS * COLUMNS];
797 let planes = planes(300, ROWS * COLUMNS, &u, &v);
798 let (ti1, valid) = ellrod_ti1(
799 &input(&planes, ROWS, COLUMNS, &latitudes, 1.0, -1.0, false),
800 300,
801 )
802 .unwrap();
803 for row in 1..ROWS - 1 {
804 let dx = EARTH_RADIUS_M * (latitudes[row] * RAD).cos() * (1.0 * RAD);
805 for column in 1..COLUMNS - 1 {
806 assert!(
807 close(ti1[row * COLUMNS + column], 0.01 * (2.0 / dx), 1e-12),
808 "{row} {column}"
809 );
810 }
811 assert!(!valid[row * COLUMNS] && !valid[row * COLUMNS + COLUMNS - 1]);
813 }
814 assert_eq!(ti1[4 * COLUMNS], 0.0);
815 assert!(
816 !valid[..COLUMNS].iter().any(|v| *v)
817 && !valid[(ROWS - 1) * COLUMNS..].iter().any(|v| *v)
818 );
819 }
820
821 #[test]
822 fn pure_shear_is_the_meridional_gradient_over_dy() {
823 let latitudes = latitudes();
824 let u: Vec<f64> = (0..ROWS * COLUMNS)
826 .map(|cell| -3.0 * (cell / COLUMNS) as f64)
827 .collect();
828 let v = vec![0.0; ROWS * COLUMNS];
829 let planes = planes(250, ROWS * COLUMNS, &u, &v);
830 let (ti1, _) = ellrod_ti1(
831 &input(&planes, ROWS, COLUMNS, &latitudes, 1.0, -1.0, false),
832 250,
833 )
834 .unwrap();
835 let dy = EARTH_RADIUS_M * (1.0 * RAD);
836 for row in 1..ROWS - 1 {
837 for column in 1..COLUMNS - 1 {
838 assert!(
839 close(ti1[row * COLUMNS + column], 0.01 * 3.0 / dy, 1e-12),
840 "{row} {column}"
841 );
842 }
843 }
844 }
845
846 #[test]
847 fn the_vertical_shear_divides_by_the_layer_depth() {
848 let latitudes = latitudes();
849 let u: Vec<f64> = (0..ROWS * COLUMNS)
850 .map(|cell| (cell % COLUMNS) as f64)
851 .collect();
852 let zero = vec![0.0; ROWS * COLUMNS];
853 let mut planes = planes(200, ROWS * COLUMNS, &u, &zero);
854 set(&mut planes, "vgrd200", vec![30.0; ROWS * COLUMNS]); set(&mut planes, "hgt200", vec![11000.0; ROWS * COLUMNS]);
856 let (ti1, _) = ellrod_ti1(
857 &input(&planes, ROWS, COLUMNS, &latitudes, 1.0, -1.0, false),
858 200,
859 )
860 .unwrap();
861 let dx = EARTH_RADIUS_M * 0.0f64.cos() * RAD;
862 let expected = (10.0f64 * 10.0 + 30.0 * 30.0).sqrt() / 2000.0 * (1.0 / dx);
863 assert!((ti1[4 * COLUMNS + 5] - expected).abs() <= 1e-20);
864 }
865
866 #[test]
867 fn the_first_and_last_columns_are_neighbours_on_a_wrapping_grid() {
868 let latitudes = latitudes();
869 let u = noise(32, ROWS * COLUMNS);
870 let v = noise(33, ROWS * COLUMNS);
871 let planes = planes(300, ROWS * COLUMNS, &u, &v);
872 let (ti1, valid) = ellrod_ti1(
873 &input(&planes, ROWS, COLUMNS, &latitudes, 30.0, -1.0, true),
874 300,
875 )
876 .unwrap();
877 assert!(valid[COLUMNS..(ROWS - 1) * COLUMNS].iter().all(|v| *v));
878 let r = 3;
879 let at = |plane: &[f64], row: usize, column: usize| plane[row * COLUMNS + column];
880 let two_dx = 2.0 * (EARTH_RADIUS_M * (latitudes[r] * RAD).cos() * (30.0 * RAD));
881 let two_dy = 2.0 * (EARTH_RADIUS_M * (1.0 * RAD));
882 let dudx = (at(&u, r, 1) - at(&u, r, COLUMNS - 1)) / two_dx;
883 let dvdx = (at(&v, r, 1) - at(&v, r, COLUMNS - 1)) / two_dx;
884 let dudy = (at(&u, r - 1, 0) - at(&u, r + 1, 0)) / two_dy;
885 let dvdy = (at(&v, r - 1, 0) - at(&v, r + 1, 0)) / two_dy;
886 let (dst, dsh) = (dudx - dvdy, dvdx + dudy);
887 assert_eq!(at(&ti1, r, 0), 0.01 * (dst * dst + dsh * dsh).sqrt());
890 }
891
892 #[test]
893 fn the_polar_rows_are_not_computed() {
894 let latitudes: Vec<f64> = (0..8).map(|row| 88.0 - 1.0 * row as f64).collect();
895 let u: Vec<f64> = (0..8 * 12).map(|cell| (cell % 12) as f64).collect();
896 let zero = vec![0.0; 8 * 12];
897 let planes = planes(300, 8 * 12, &u, &zero);
898 let (ti1, valid) =
899 ellrod_ti1(&input(&planes, 8, 12, &latitudes, 30.0, -1.0, true), 300).unwrap();
900 let column: Vec<bool> = (0..8).map(|row| valid[row * 12 + 5]).collect();
901 assert_eq!(column, [false, false, false, true, true, true, true, false]);
902 assert!(ti1[..3 * 12].iter().all(|value| *value == 0.0));
903 }
904
905 #[test]
906 fn a_south_to_north_grid_is_refused() {
907 let latitudes: Vec<f64> = latitudes().into_iter().rev().collect();
908 let zero = vec![0.0; ROWS * COLUMNS];
909 let planes = planes(300, ROWS * COLUMNS, &zero, &zero);
910 let refused = ellrod_ti1(
911 &input(&planes, ROWS, COLUMNS, &latitudes, 1.0, 1.0, true),
912 300,
913 );
914 assert!(matches!(refused, Err(EncodeError(_))));
915 }
916
917 const PROJECTION_ROWS: usize = 5;
918 const PROJECTION_COLUMNS: usize = 8;
919 const PROJECTION_LATITUDES: [f64; 5] = [2.0, 1.0, 0.0, -1.0, -2.0];
920 const PROJECTION_CELL: usize = 2 * PROJECTION_COLUMNS + 3;
921
922 fn projection_field() -> Vec<(String, Vec<f64>)> {
924 let cells = PROJECTION_ROWS * PROJECTION_COLUMNS;
925 let u: Vec<f64> = (0..cells)
926 .map(|cell| (cell % PROJECTION_COLUMNS) as f64)
927 .collect();
928 planes(300, cells, &u, &vec![0.0; cells])
929 }
930
931 fn projection_input(planes: &[(String, Vec<f64>)]) -> CatPlanes<'_> {
932 input(
933 planes,
934 PROJECTION_ROWS,
935 PROJECTION_COLUMNS,
936 &PROJECTION_LATITUDES,
937 1.0,
938 -1.0,
939 false,
940 )
941 }
942
943 #[test]
944 fn edr_is_the_lognormal_projection_of_ti1() {
945 let field = projection_field();
946 let grid = projection_input(&field);
947 let (ti1, valid) = ellrod_ti1(&grid, 300).unwrap();
948 let ti1_cell = ti1[PROJECTION_CELL];
949 let std = 1.2;
950 let mean = ti1_cell.ln() - 2.0 * std;
952 let edr = derive_cat(&grid, 300, (mean, std)).unwrap();
953 let b = CAT_EDR_LOG_STD / std;
954 let a = CAT_EDR_LOG_MEAN - b * mean;
955 assert_eq!(edr[PROJECTION_CELL], (a + b * ti1_cell.ln()).exp());
956 assert!(
957 (edr[PROJECTION_CELL] - (CAT_EDR_LOG_MEAN + 2.0 * CAT_EDR_LOG_STD).exp()).abs() < 1e-7
958 );
959 assert!(edr
960 .iter()
961 .zip(&valid)
962 .all(|(value, defined)| *defined || *value == 0.0));
963 let cells = PROJECTION_ROWS * PROJECTION_COLUMNS;
966 let calm_planes = self::planes(300, cells, &vec![0.0; cells], &vec![0.0; cells]);
967 let calm = derive_cat(&projection_input(&calm_planes), 300, (mean, std)).unwrap();
968 assert!(calm.iter().all(|value| *value == 0.0));
969 }
970
971 #[test]
972 fn nil_turbulence_is_written_as_zero() {
973 let field = projection_field();
974 let grid = projection_input(&field);
975 let (ti1, _) = ellrod_ti1(&grid, 300).unwrap();
976 assert!(CAT_EDR_LOG_MEAN.exp() < CAT_EDR_NIL);
978 let at_mean = derive_cat(&grid, 300, (ti1[PROJECTION_CELL].ln(), 1.2)).unwrap();
979 assert!(at_mean.iter().all(|value| *value == 0.0));
980 let projected = |t: f64| t.ln().exp();
986 let mut lowest_kept = CAT_EDR_NIL;
987 while projected(lowest_kept) >= CAT_EDR_NIL {
988 lowest_kept = lowest_kept.next_down();
989 }
990 let highest_nil = lowest_kept;
991 while projected(lowest_kept) < CAT_EDR_NIL {
992 lowest_kept = lowest_kept.next_up();
993 }
994 assert!(projected(lowest_kept) - CAT_EDR_NIL < 1e-16);
995 assert!(CAT_EDR_NIL - projected(highest_nil) < 1e-16);
996 let project = |t: f64| {
998 let b = CAT_EDR_LOG_STD / CAT_EDR_LOG_STD;
999 let a = CAT_EDR_LOG_MEAN - b * CAT_EDR_LOG_MEAN;
1000 nil_below_threshold((a + b * numpy_maximum(t, CAT_TI1_FLOOR).ln()).exp())
1001 };
1002 assert_eq!(project(highest_nil), 0.0);
1003 assert_eq!(project(lowest_kept), projected(lowest_kept));
1004 assert!((project(0.3) - 0.3).abs() < 1e-12);
1005 let mut codes = [0u8; 1];
1006 let book = Registry::embedded().codebook("quality", "cat300").unwrap();
1007 book.quantize(&[project(lowest_kept)], &mut codes).unwrap();
1008 assert_eq!(codes[0], 20);
1009 assert_eq!(nil_below_threshold(CAT_EDR_NIL), CAT_EDR_NIL);
1011 assert_eq!(nil_below_threshold(CAT_EDR_NIL.next_down()), 0.0);
1012 book.quantize(&[nil_below_threshold(CAT_EDR_NIL)], &mut codes)
1013 .unwrap();
1014 assert_eq!(codes[0], 20);
1015 assert!(nil_below_threshold(f64::NAN).is_nan());
1016 }
1017
1018 #[test]
1021 fn a_nan_is_kept_as_numpy_keeps_it() {
1022 let mut field = projection_field();
1023 let mut z = vec![10000.0; PROJECTION_ROWS * PROJECTION_COLUMNS];
1024 z[PROJECTION_CELL] = f64::NAN;
1025 set(&mut field, "hgt250", z);
1026 let edr = derive_cat(&projection_input(&field), 300, (-16.0, 1.2)).unwrap();
1027 assert!(edr[PROJECTION_CELL].is_nan());
1028 assert!(!edr[PROJECTION_CELL + 1].is_nan());
1029 }
1030
1031 #[test]
1032 fn a_crop_is_cut_after_the_derivation() {
1033 let (rows, columns) = (13, 24);
1034 let grid = GridInfo::new(columns, rows, -180.0, 60.0, 15.0, -10.0);
1035 let inputs = cat_inputs("cat250");
1036 let mut planes: Vec<(String, Vec<f64>)> = inputs
1037 .iter()
1038 .cloned()
1039 .enumerate()
1040 .map(|(index, id)| {
1041 (
1042 id,
1043 noise(7 + index as u64, rows * columns)
1044 .iter()
1045 .map(|x| x * 20.0)
1046 .collect(),
1047 )
1048 })
1049 .collect();
1050 for (id, offset) in [("hgt200", 12000.0), ("hgt300", 9000.0)] {
1051 let plane = planes
1052 .iter()
1053 .find(|(name, _)| name == id)
1054 .unwrap()
1055 .1
1056 .iter()
1057 .map(|x| x + offset)
1058 .collect();
1059 set(&mut planes, id, plane);
1060 }
1061 let calibration = [(250, -17.0, 1.1)];
1062 let lookup = |name: &str| -> Result<&[f64]> {
1063 Ok(planes
1064 .iter()
1065 .find(|(id, _)| id == name)
1066 .map(|(_, plane)| plane.as_slice())
1067 .unwrap())
1068 };
1069 let whole = derive_cat_plane(lookup, "cat250", 250, &inputs, &grid, &calibration).unwrap();
1070 let crop = CropWindow {
1072 source_width: columns,
1073 source_height: rows,
1074 row_start: 0,
1075 column_start: 20,
1076 width: 8,
1077 height: 5,
1078 };
1079 let mut cropped_grid = GridInfo::new(8, 5, 120.0, 60.0, 15.0, -10.0);
1080 cropped_grid.crop = Some(crop);
1081 assert_eq!(
1082 uncropped_latitudes(&cropped_grid),
1083 uncropped_latitudes(&grid)
1084 );
1085 let cut =
1086 derive_cat_plane(lookup, "cat250", 250, &inputs, &cropped_grid, &calibration).unwrap();
1087 assert_eq!(cut, crop.take(&whole));
1088 assert!(
1089 derive_cat_plane(lookup, "cat250", 250, &inputs, &grid, &[(300, -17.0, 1.1)]).is_err()
1090 );
1091 }
1092
1093 #[test]
1097 fn the_bundles_and_their_inputs() {
1098 let registry = Registry::embedded();
1099 assert_eq!(
1100 cat_inputs("cat250"),
1101 [
1102 "ugrd200", "vgrd200", "hgt200", "ugrd300", "vgrd300", "hgt300", "ugrd250",
1103 "vgrd250"
1104 ]
1105 );
1106 assert_eq!(
1107 cat_inputs("cat300"),
1108 ["ugrd250", "vgrd250", "hgt250", "ugrd300", "vgrd300", "hgt300"]
1109 );
1110 for &(level, above, below) in &CAT_SHEAR_LAYERS {
1111 let derivation = registry.scalar_derivation(&format!("cat{level}")).unwrap();
1112 assert_eq!(
1113 (derivation.kind, derivation.level_hpa),
1114 (DerivationKind::ClearAirTurbulence, Some(level))
1115 );
1116 for surface in [above, below, level] {
1117 for family in ["ugrd", "vgrd"] {
1118 assert!(
1119 derivation.inputs.contains(&format!("{family}{surface}")),
1120 "cat{level} {family}{surface}"
1121 );
1122 }
1123 }
1124 }
1125 assert!(registry.scalar_derivation("cape").is_none());
1126 assert!(registry.scalar_derivation("cat850").is_none());
1127 let spec = registry.variable("cat300").unwrap();
1128 assert_eq!(spec.parameter_metadata()["parameterCategory"], json!(19));
1129 assert_eq!(spec.parameter_metadata()["parameterNumber"], json!(29));
1130 assert_eq!(
1131 registry.codebook("quality", "cat300").unwrap().metadata()["maximumCode"],
1132 json!(127)
1133 );
1134 for id in ["cat300", "cat250", "cat200"] {
1135 assert!(registry.is_raw(id).unwrap(), "{id}");
1136 }
1137 }
1138
1139 #[test]
1140 fn gfs_and_ecmwf_publish_and_calibrate_all_three() {
1141 let registry = Registry::embedded();
1142 for model in ["gfs", "ecmwf", "ifs"] {
1143 let source = registry.source(model).unwrap();
1144 let published: Vec<&str> = registry
1145 .published_bundle_ids(source)
1146 .into_iter()
1147 .filter(|id| id.starts_with("cat"))
1148 .collect();
1149 assert_eq!(published, ["cat300", "cat250", "cat200"], "{model}");
1150 let levels: Vec<u32> = source
1151 .cat_calibration
1152 .iter()
1153 .map(|(level, _, _)| *level)
1154 .collect();
1155 assert_eq!(levels, [300, 250, 200], "{model}");
1156 for bundle_id in ["cat300", "cat250", "cat200"] {
1157 for input_id in registry.bundle_input_ids(source, bundle_id) {
1158 assert!(
1159 source.has_input(&input_id),
1160 "{model} {bundle_id} {input_id}"
1161 );
1162 }
1163 }
1164 }
1165 let aifs = registry.source("aifs").unwrap();
1166 assert!(!registry
1167 .published_bundle_ids(aifs)
1168 .iter()
1169 .any(|id| id.starts_with("cat")));
1170 }
1171}