1use std::path::Path;
5
6use serde_json::{json, Map, Value};
7
8use crate::encode::errors::{EncodeError, Result};
9use crate::encode::reproject::ProjectedGrid;
10use crate::projection::{gaussian_latitude, GaussianRows};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub struct CropWindow {
20 pub source_width: usize,
21 pub source_height: usize,
22 pub row_start: usize,
23 pub column_start: usize,
24 pub width: usize,
25 pub height: usize,
26}
27
28impl CropWindow {
29 pub fn take(&self, plane: &[f64]) -> Vec<f64> {
31 let mut cropped = Vec::with_capacity(self.width * self.height);
32 for row in self.row_start..self.row_start + self.height {
33 let base = row * self.source_width;
34 for column in self.column_start..self.column_start + self.width {
35 cropped.push(plane[base + column % self.source_width]);
36 }
37 }
38 cropped
39 }
40}
41
42#[derive(Debug, Clone, Copy, PartialEq)]
48pub struct BlockReduction {
49 pub factor: usize,
50 pub source_width: usize,
51 pub source_height: usize,
52}
53
54impl BlockReduction {
55 pub fn source_shape(&self) -> (usize, usize) {
56 (self.source_height, self.source_width)
57 }
58
59 pub fn take(&self, plane: &[f64]) -> Result<Vec<f64>> {
64 if plane.len() != self.source_width * self.source_height {
65 return Err(EncodeError::conversion(format!(
66 "plane has {} cells, expected {}x{}",
67 plane.len(),
68 self.source_width,
69 self.source_height
70 )));
71 }
72 let k = self.factor;
73 let (width, height) = (self.source_width / k, self.source_height / k);
74 let mut reduced = Vec::with_capacity(width * height);
75 for row in 0..height {
76 for column in 0..width {
77 let mut best = f64::NEG_INFINITY;
78 for r in 0..k {
79 let base = (row * k + r) * self.source_width + column * k;
80 for value in &plane[base..base + k] {
81 if value.is_nan() || best.is_nan() {
82 best = f64::NAN;
83 } else if *value > best {
84 best = *value;
85 }
86 }
87 }
88 reduced.push(best);
89 }
90 }
91 Ok(reduced)
92 }
93}
94
95#[derive(Debug, Clone)]
96pub struct GridInfo {
97 pub width: usize,
98 pub height: usize,
99 pub first_longitude: f64,
100 pub first_latitude: f64,
101 pub longitude_step: f64,
102 pub latitude_step: f64,
103 pub column_roll: usize,
108 pub crop: Option<CropWindow>,
113 pub downsample: Option<BlockReduction>,
118 pub projection: Option<ProjectedGrid>,
122 pub gaussian: Option<GaussianRows>,
125}
126
127impl GridInfo {
128 pub fn new(
129 width: usize,
130 height: usize,
131 first_longitude: f64,
132 first_latitude: f64,
133 longitude_step: f64,
134 latitude_step: f64,
135 ) -> Self {
136 Self {
137 width,
138 height,
139 first_longitude,
140 first_latitude,
141 longitude_step,
142 latitude_step,
143 column_roll: 0,
144 crop: None,
145 downsample: None,
146 projection: None,
147 gaussian: None,
148 }
149 }
150
151 pub fn projected(projection: ProjectedGrid, crop: Option<CropWindow>) -> Self {
154 Self {
155 crop,
156 projection: Some(projection),
157 ..Self::new(
158 projection.width,
159 projection.height,
160 f64::NAN,
161 f64::NAN,
162 f64::NAN,
163 f64::NAN,
164 )
165 }
166 }
167
168 pub fn wraps(&self) -> bool {
169 (self.width as f64 * self.longitude_step - 360.0).abs() < 1e-6
170 }
171
172 pub fn source_shape(&self) -> (usize, usize) {
174 if let Some(downsample) = &self.downsample {
175 return downsample.source_shape();
176 }
177 match self.crop {
178 None => (self.height, self.width),
179 Some(crop) => (crop.source_height, crop.source_width),
180 }
181 }
182
183 pub fn decimated(&self) -> Self {
189 if let Some(projection) = &self.projection {
190 return Self::projected(projection.decimated(), None);
191 }
192 Self {
193 width: self.width.div_ceil(2),
194 height: self.height.div_ceil(2),
195 first_longitude: self.first_longitude,
196 first_latitude: self.first_latitude,
197 longitude_step: self.longitude_step * 2.0,
198 latitude_step: self.latitude_step * 2.0,
199 column_roll: 0,
200 crop: None,
201 downsample: None,
202 projection: None,
203 gaussian: self.gaussian.map(|rows| GaussianRows {
204 row_stride: rows.row_stride * 2,
205 ..rows
206 }),
207 }
208 }
209
210 pub fn downsampled(&self, factor: usize, path: &Path) -> Result<Self> {
217 if factor < 1 {
218 return Err(EncodeError::conversion(format!(
219 "downsample factor must be positive, not {factor}"
220 )));
221 }
222 if !self.width.is_multiple_of(factor) || !self.height.is_multiple_of(factor) {
223 return Err(EncodeError::conversion(format!(
224 "{} is {}x{}, which does not divide into {factor}x{factor} blocks",
225 path.display(),
226 self.width,
227 self.height
228 )));
229 }
230 if self.wraps() || self.column_roll != 0 {
231 return Err(EncodeError::conversion(format!(
232 "{} is a global grid, which this source does not thin",
233 path.display()
234 )));
235 }
236 let k = factor as f64;
237 Ok(Self {
238 width: self.width / factor,
239 height: self.height / factor,
240 first_longitude: round10(self.first_longitude + self.longitude_step * (k - 1.0) / 2.0),
241 first_latitude: round10(self.first_latitude + self.latitude_step * (k - 1.0) / 2.0),
242 longitude_step: self.longitude_step * k,
243 latitude_step: self.latitude_step * k,
244 column_roll: 0,
245 crop: None,
246 downsample: Some(BlockReduction {
247 factor,
248 source_width: self.width,
249 source_height: self.height,
250 }),
251 projection: None,
252 gaussian: None,
253 })
254 }
255
256 pub fn metadata(&self) -> Map<String, Value> {
257 let mut block = Map::new();
258 block.insert("width".into(), json!(self.width));
259 block.insert("height".into(), json!(self.height));
260 block.insert("layout".into(), json!("row-major"));
261 block.insert("rowOrder".into(), json!("north-to-south"));
262 block.insert("columnOrder".into(), json!("west-to-east"));
263 if let Some(projection) = &self.projection {
264 block.insert("wrapLongitude".into(), json!(false));
265 block.insert("projection".into(), Value::Object(projection.metadata()));
266 return block;
267 }
268 block.insert("firstLongitude".into(), json!(self.first_longitude));
269 block.insert("firstLatitude".into(), json!(self.first_latitude));
270 block.insert("longitudeStep".into(), json!(self.longitude_step));
271 block.insert("latitudeStep".into(), json!(self.latitude_step));
272 block.insert("wrapLongitude".into(), json!(self.wraps()));
273 if let Some(rows) = &self.gaussian {
274 block.insert(
275 "gaussian".into(),
276 json!({"n": rows.n, "firstRow": rows.first_row, "rowStride": rows.row_stride}),
277 );
278 }
279 block
280 }
281}
282
283const GAUSSIAN_ROW_TOLERANCE: f64 = 0.25;
288
289pub fn gaussian_rows(grid: &GridInfo, n: u32, path: &Path) -> Result<GaussianRows> {
295 let order = 2.0 * f64::from(n);
296 let first_row = ((90.0 - grid.first_latitude) * (order + 0.5) / 180.0 - 0.25).floor();
297 let step = grid.latitude_step.abs();
298 if first_row < 0.0
299 || first_row + grid.height as f64 > order
300 || (step * 2.0 * f64::from(n) - 180.0).abs() > 1.8
301 || (gaussian_latitude(n, first_row as u32) - grid.first_latitude).abs()
302 > step * GAUSSIAN_ROW_TOLERANCE
303 {
304 return Err(EncodeError::conversion(format!(
305 "{} is not on the Gaussian grid of {n} latitudes per hemisphere",
306 path.display()
307 )));
308 }
309 Ok(GaussianRows {
310 n,
311 first_row: first_row as u32,
312 row_stride: 1,
313 })
314}
315
316const GLOBAL_SPAN_TOLERANCE_CELLS: f64 = 1e-3;
319
320pub fn snap_global_longitudes(grid: GridInfo) -> GridInfo {
333 let span = grid.width as f64 * grid.longitude_step;
334 if (span - 360.0).abs() > grid.longitude_step * GLOBAL_SPAN_TOLERANCE_CELLS {
335 return grid;
336 }
337 let step = 360.0 / grid.width as f64;
338 let mut first = (grid.first_longitude / step + 0.5).floor() * step;
339 if (first - grid.first_longitude).abs() > step * GLOBAL_SPAN_TOLERANCE_CELLS {
340 first = grid.first_longitude;
341 }
342 GridInfo {
343 longitude_step: step,
344 first_longitude: first,
345 ..grid
346 }
347}
348
349fn regional_step_units() -> [(f64, f64); 2] {
355 [(1e-3, 1000.0), (1.0 / 60.0, 60.0)]
356}
357
358pub fn snap_regional_steps(grid: GridInfo) -> GridInfo {
373 if grid.wraps() {
374 return grid;
375 }
376 let (longitude_step, first_longitude) =
377 snap_axis(grid.longitude_step, grid.first_longitude, grid.width);
378 let (latitude_step, first_latitude) =
379 snap_axis(grid.latitude_step, grid.first_latitude, grid.height);
380 GridInfo {
381 longitude_step,
382 first_longitude,
383 latitude_step,
384 first_latitude,
385 ..grid
386 }
387}
388
389fn snap_axis(step: f64, first: f64, count: usize) -> (f64, f64) {
393 let count = count as f64;
394 for (unit, divisor) in regional_step_units() {
395 let units = (step / unit + 0.5).floor();
396 let rounded = units / divisor;
397 if units == 0.0
398 || (count * step - count * rounded).abs() > step.abs() * GLOBAL_SPAN_TOLERANCE_CELLS
399 {
400 continue;
401 }
402 let half_steps = (first / (rounded / 2.0) + 0.5).floor();
403 let mut snapped_first = (half_steps * units) / (2.0 * divisor);
404 if (snapped_first - first).abs() > rounded.abs() * GLOBAL_SPAN_TOLERANCE_CELLS {
405 snapped_first = first;
406 }
407 return (rounded, snapped_first);
408 }
409 (step, first)
410}
411
412pub fn normalize_longitudes(grid: GridInfo) -> GridInfo {
420 if !grid.wraps() || grid.first_longitude < -90.0 {
424 return grid;
425 }
426 let pivot = ((180.0 - grid.first_longitude) / grid.longitude_step - 1e-9).ceil();
427 if pivot < 0.0 || pivot > grid.width as f64 {
428 return grid;
429 }
430 let pivot = pivot as usize;
431 let roll = grid.width.saturating_sub(pivot);
432 if roll == 0 || roll >= grid.width {
433 return grid;
434 }
435 GridInfo {
436 first_longitude: grid.first_longitude + pivot as f64 * grid.longitude_step - 360.0,
437 column_roll: roll,
438 ..grid
439 }
440}
441
442fn round10(value: f64) -> f64 {
445 format!("{value:.10}").parse().unwrap_or(value)
446}
447
448pub fn crop_grid(grid: GridInfo, bbox: (f64, f64, f64, f64)) -> Result<GridInfo> {
460 if grid.crop.is_some() {
461 return Err(EncodeError::conversion("a grid can only be cropped once"));
462 }
463 let (west, south, east, north) = bbox;
464 let printed = format!("({west}, {south}, {east}, {north})");
465 if !(-90.0..90.0).contains(&south) || south >= north || north > 90.0 {
466 return Err(EncodeError::conversion(format!(
467 "bbox latitudes must satisfy -90 <= south < north <= 90: {printed}"
468 )));
469 }
470 if !(-360.0..=360.0).contains(&west) || !(-360.0..=360.0).contains(&east) {
471 return Err(EncodeError::conversion(format!(
472 "bbox longitudes must be within [-360, 360]: {printed}"
473 )));
474 }
475 if east < west && !grid.wraps() {
476 return Err(EncodeError::conversion(
477 "only a wrapping grid can be cropped across the antimeridian",
478 ));
479 }
480 let mut span = (east - west).rem_euclid(360.0);
481 if span == 0.0 {
482 if east < west || !grid.wraps() {
483 return Err(EncodeError::conversion(format!(
484 "bbox must have a positive longitude span: {printed}"
485 )));
486 }
487 span = 360.0;
488 }
489 if let Some(projection) = grid.projection {
490 return crop_projected(&grid, &projection, west, south, east, north);
491 }
492
493 let mut offset = (west - grid.first_longitude).rem_euclid(360.0);
499 if !grid.wraps() && offset > (grid.width - 1) as f64 * grid.longitude_step + 1e-9 {
500 offset -= 360.0;
501 }
502 let mut column_start = (offset / grid.longitude_step + 1e-9).floor() as i64;
503 let mut column_end = ((offset + span) / grid.longitude_step - 1e-9).ceil() as i64;
504 let width: i64;
505 if grid.wraps() {
506 width = (column_end - column_start + 1).min(grid.width as i64);
507 if width >= grid.width as i64 {
508 column_start = 0;
509 }
510 column_start = column_start.rem_euclid(grid.width as i64);
511 } else {
512 column_start = column_start.max(0);
513 column_end = column_end.min(grid.width as i64 - 1);
514 width = column_end - column_start + 1;
515 }
516 let width = if grid.wraps() && width >= grid.width as i64 {
517 grid.width as i64
518 } else {
519 width
520 };
521 if width <= 0 {
522 return Err(EncodeError::conversion(format!(
523 "bbox does not overlap the source grid: {printed}"
524 )));
525 }
526
527 let row_start =
528 (((north - grid.first_latitude) / grid.latitude_step + 1e-9).floor() as i64).max(0);
529 let row_end = (((south - grid.first_latitude) / grid.latitude_step - 1e-9).ceil() as i64)
530 .min(grid.height as i64 - 1);
531 let height = row_end - row_start + 1;
532 if height <= 0 {
533 return Err(EncodeError::conversion(format!(
534 "bbox does not overlap the source grid: {printed}"
535 )));
536 }
537
538 let mut first_longitude = grid.first_longitude + column_start as f64 * grid.longitude_step;
539 if width < grid.width as i64 {
540 first_longitude = (first_longitude + 180.0).rem_euclid(360.0) - 180.0;
541 }
542 let (width, height) = (width as usize, height as usize);
543 let (row_start, column_start) = (row_start as usize, column_start as usize);
544 Ok(GridInfo {
545 width,
546 height,
547 first_longitude: round10(first_longitude),
548 first_latitude: round10(grid.first_latitude + row_start as f64 * grid.latitude_step),
549 longitude_step: grid.longitude_step,
550 latitude_step: grid.latitude_step,
551 column_roll: grid.column_roll,
552 crop: Some(CropWindow {
553 source_width: grid.width,
554 source_height: grid.height,
555 row_start,
556 column_start,
557 width,
558 height,
559 }),
560 downsample: grid.downsample,
561 projection: None,
562 gaussian: grid.gaussian.map(|rows| GaussianRows {
563 first_row: rows.first_row + row_start as u32 * rows.row_stride,
564 ..rows
565 }),
566 })
567}
568
569const BBOX_EDGE_POINTS: usize = 64;
573const BBOX_LATITUDE_LIMIT: f64 = 89.9;
576
577fn crop_projected(
583 grid: &GridInfo,
584 projected: &ProjectedGrid,
585 west: f64,
586 south: f64,
587 east: f64,
588 north: f64,
589) -> Result<GridInfo> {
590 let south = south.max(-BBOX_LATITUDE_LIMIT);
591 let north = north.min(BBOX_LATITUDE_LIMIT);
592 let (mut lowest_column, mut highest_column) = (f64::INFINITY, f64::NEG_INFINITY);
593 let (mut lowest_row, mut highest_row) = (f64::INFINITY, f64::NEG_INFINITY);
594 let last = (BBOX_EDGE_POINTS - 1) as f64;
595 for index in 0..BBOX_EDGE_POINTS {
596 let longitude = west + (east - west) * index as f64 / last;
597 let latitude = south + (north - south) * index as f64 / last;
598 for (point_longitude, point_latitude) in [
599 (longitude, south),
600 (longitude, north),
601 (west, latitude),
602 (east, latitude),
603 ] {
604 let (x, y) = projected
605 .projection
606 .forward_wrapped(point_longitude, point_latitude);
607 let column = (x - projected.x0) / projected.dx;
608 let row = (y - projected.y0) / projected.dy;
609 lowest_column = lowest_column.min(column);
610 highest_column = highest_column.max(column);
611 lowest_row = lowest_row.min(row);
612 highest_row = highest_row.max(row);
613 }
614 }
615 let column_start = ((lowest_column + 1e-9).floor() as i64).max(0);
616 let column_end = ((highest_column - 1e-9).ceil() as i64).min(grid.width as i64 - 1);
617 let row_start = ((lowest_row + 1e-9).floor() as i64).max(0);
618 let row_end = ((highest_row - 1e-9).ceil() as i64).min(grid.height as i64 - 1);
619 let width = column_end - column_start + 1;
620 let height = row_end - row_start + 1;
621 if width <= 0 || height <= 0 {
622 return Err(EncodeError::conversion(format!(
623 "bbox does not overlap the source grid: ({west}, {south}, {east}, {north})"
624 )));
625 }
626 let (row_start, column_start) = (row_start as usize, column_start as usize);
627 let (height, width) = (height as usize, width as usize);
628 Ok(GridInfo::projected(
629 projected.window(row_start, column_start, height, width),
630 Some(CropWindow {
631 source_width: grid.width,
632 source_height: grid.height,
633 row_start,
634 column_start,
635 width,
636 height,
637 }),
638 ))
639}
640
641#[cfg(test)]
642mod tests {
643 use super::{
644 crop_grid, gaussian_rows, normalize_longitudes, snap_global_longitudes,
645 snap_regional_steps, BlockReduction, GridInfo,
646 };
647 use crate::encode::reproject::{LambertConformal, ProjectedGrid};
648 use crate::projection::GaussianRows;
649 use std::path::Path;
650
651 fn hrrr() -> ProjectedGrid {
652 ProjectedGrid {
653 projection: LambertConformal {
654 radius: 6371229.0,
655 standard_parallel_1: 38.5,
656 standard_parallel_2: 38.5,
657 latitude_of_origin: 38.5,
658 central_meridian: -97.5,
659 },
660 width: 1799,
661 height: 1059,
662 x0: -2697520.143,
663 y0: 1587306.153,
664 dx: 3000.0,
665 dy: -3000.0,
666 }
667 }
668
669 #[test]
670 fn a_box_on_a_projected_grid_is_the_window_around_its_edges() {
671 let grid = hrrr();
672 let cropped = crop_grid(GridInfo::projected(grid, None), (-100.0, 35.0, -95.0, 40.0))
673 .expect("window");
674 let crop = cropped.crop.expect("a window");
675 assert_eq!((crop.source_width, crop.source_height), (1799, 1059));
676 assert_eq!((crop.width, crop.height), (cropped.width, cropped.height));
677 assert_eq!(cropped.source_shape(), (1059, 1799));
678 let window = cropped.projection.expect("projected");
679 assert_eq!(window.x0, grid.x0 + crop.column_start as f64 * grid.dx);
680 assert_eq!(window.y0, grid.y0 + crop.row_start as f64 * grid.dy);
681 for (longitude, latitude) in [(-100.0, 35.0), (-95.0, 35.0), (-100.0, 40.0), (260.0, 40.0)]
683 {
684 let (x, y) = grid.projection.forward_wrapped(longitude, latitude);
685 let (column, row) = ((x - window.x0) / window.dx, (y - window.y0) / window.dy);
686 assert!(
687 column >= 0.0 && column <= (window.width - 1) as f64,
688 "{longitude} {column}"
689 );
690 assert!(
691 row >= 0.0 && row <= (window.height - 1) as f64,
692 "{latitude} {row}"
693 );
694 }
695 assert!(crop_grid(GridInfo::projected(grid, None), (-95.0, 35.0, -100.0, 40.0)).is_err());
696 assert!(crop_grid(GridInfo::projected(grid, None), (100.0, 35.0, 110.0, 40.0)).is_err());
697 assert!(
698 crop_grid(cropped, (-100.0, 35.0, -95.0, 40.0)).is_err(),
699 "cropped once"
700 );
701 }
702
703 #[test]
704 fn a_projected_grid_says_nothing_regular() {
705 let block = GridInfo::projected(hrrr(), None).decimated().metadata();
706 assert_eq!(
707 block.keys().map(String::as_str).collect::<Vec<_>>(),
708 [
709 "width",
710 "height",
711 "layout",
712 "rowOrder",
713 "columnOrder",
714 "wrapLongitude",
715 "projection"
716 ]
717 );
718 assert_eq!(block["width"], 900);
719 assert_eq!(block["projection"]["dy"], -6000.0);
720 }
721
722 #[test]
725 fn a_gaussian_grid_finds_its_rows() {
726 let path = Path::new("x");
727 let step = -180.0 / 190.0;
728 let whole = GridInfo::new(384, 190, -180.0, 89.7507 + step / 2.0, 0.9375, step);
729 assert_eq!(
730 gaussian_rows(&whole, 95, path).unwrap(),
731 GaussianRows {
732 n: 95,
733 first_row: 0,
734 row_stride: 1
735 }
736 );
737 let first = crate::projection::gaussian_latitude(95, 30);
738 let window = GridInfo::new(48, 40, 90.0, first, 0.9375, step);
739 assert_eq!(gaussian_rows(&window, 95, path).unwrap().first_row, 30);
740 assert!(gaussian_rows(
742 &GridInfo::new(48, 40, 90.0, first + step / 2.0, 0.9375, step),
743 95,
744 path
745 )
746 .is_err());
747 assert!(
748 gaussian_rows(&GridInfo::new(48, 170, 90.0, first, 0.9375, step), 95, path).is_err()
749 );
750 assert!(
751 gaussian_rows(&GridInfo::new(48, 40, 90.0, first, 0.9375, -0.5), 95, path).is_err()
752 );
753 }
754
755 #[test]
756 fn a_crop_and_a_tier_keep_a_gaussian_grid_s_rows() {
757 let step = -180.0 / 190.0;
758 let mut grid = GridInfo::new(384, 190, -180.0, 89.277, 0.9375, step);
759 grid.gaussian = Some(GaussianRows {
760 n: 95,
761 first_row: 0,
762 row_stride: 1,
763 });
764 let cropped = crop_grid(grid, (0.0, 0.0, 30.0, 30.0)).expect("window");
765 let row_start = cropped.crop.expect("a window").row_start as u32;
766 assert_eq!(
767 cropped.gaussian,
768 Some(GaussianRows {
769 n: 95,
770 first_row: row_start,
771 row_stride: 1
772 })
773 );
774 let tier = cropped.decimated();
775 assert_eq!(
776 tier.gaussian,
777 Some(GaussianRows {
778 n: 95,
779 first_row: row_start,
780 row_stride: 2
781 })
782 );
783 assert_eq!(tier.metadata()["gaussian"]["rowStride"], 2);
784 }
785
786 const WAVE_STEP: f64 = 0.2500000111188325;
787 const WAVE_ORIGIN: f64 = -180.12500000555943;
788
789 #[test]
790 fn a_regional_grid_past_the_antimeridian_is_cropped_in_its_own_copy_of_the_world() {
791 let disk = GridInfo::new(3000, 3000, 80.7, 60.0, 0.04, -0.04);
793 assert!(!disk.wraps());
794 let east = crop_grid(disk.clone(), (-170.0, 0.0, -160.0, 10.0)).unwrap();
796 assert_eq!(east.crop.as_ref().unwrap().column_start, 2732);
797 assert_eq!(east.width, 252);
798 assert_eq!(east.first_longitude, -170.02);
799 let same = crop_grid(disk.clone(), (190.0, 0.0, 200.0, 10.0)).unwrap();
801 assert_eq!(same.crop, east.crop);
802 let west = crop_grid(disk.clone(), (70.0, 0.0, 90.0, 10.0)).unwrap();
805 assert_eq!(west.crop.as_ref().unwrap().column_start, 0);
806 assert_eq!(west.first_longitude, 80.7);
807 assert!(crop_grid(disk, (-150.0, 0.0, -100.0, 10.0)).is_err());
808 }
809
810 #[test]
811 fn the_wave_grid_snaps_to_the_pgrb2_grid() {
812 let raw = GridInfo::new(
813 1440,
814 721,
815 WAVE_ORIGIN + WAVE_STEP / 2.0,
816 90.0,
817 WAVE_STEP,
818 -0.25,
819 );
820 assert!(!raw.wraps(), "as GDAL reports it, the grid does not close");
821 let snapped = snap_global_longitudes(raw);
822 assert_eq!(
823 (snapped.longitude_step, snapped.first_longitude),
824 (0.25, -180.0)
825 );
826 assert!(snapped.wraps());
827 }
828
829 #[test]
830 fn exact_and_regional_grids_pass_through_unchanged() {
831 for grid in [
832 GridInfo::new(1440, 721, -180.0, 90.0, 0.25, -0.25),
833 GridInfo::new(3072, 1536, 0.0, 89.91, 0.1171875, -0.117),
835 GridInfo::new(80, 80, 118.0, 38.0, WAVE_STEP, -0.25),
836 GridInfo::new(80, 80, 118.0, 38.0, 0.25, -0.25),
837 ] {
838 let snapped = snap_global_longitudes(grid.clone());
839 assert_eq!(snapped.longitude_step, grid.longitude_step);
840 assert_eq!(snapped.first_longitude, grid.first_longitude);
841 }
842 }
843
844 #[test]
845 fn an_origin_off_the_step_grid_keeps_its_step_only() {
846 let grid = GridInfo::new(1440, 721, -179.9, 90.0, WAVE_STEP, -0.25);
847 let snapped = snap_global_longitudes(grid);
848 assert_eq!(snapped.longitude_step, 0.25);
849 assert_eq!(snapped.first_longitude, -179.9);
850 }
851
852 #[test]
853 fn a_grid_more_than_a_thousandth_of_a_cell_short_is_not_global() {
854 let grid = GridInfo::new(1440, 721, -180.0, 90.0, 0.25 * (1.0 - 2e-3), -0.25);
855 let snapped = snap_global_longitudes(grid.clone());
856 assert_eq!(snapped.longitude_step, grid.longitude_step);
857 }
858
859 #[test]
862 fn the_mrms_grid_snaps_to_its_hundredth() {
863 let step = 0.0099999997142449;
864 let full = snap_regional_steps(GridInfo::new(
865 7000,
866 3500,
867 -129.99999999985712 + step / 2.0,
868 54.9999999998571 - 0.0099999997142041 / 2.0,
869 step,
870 -0.0099999997142041,
871 ));
872 assert_eq!((full.longitude_step, full.latitude_step), (0.01, -0.01));
873 assert_eq!(
874 (full.first_longitude, full.first_latitude),
875 (-129.995, 54.995)
876 );
877 let crop_step = 0.009999993710692;
878 let crop = snap_regional_steps(GridInfo::new(
879 160,
880 160,
881 -77.60000099685537 + crop_step / 2.0,
882 51.795,
883 crop_step,
884 -0.01,
885 ));
886 assert_eq!((crop.longitude_step, crop.first_longitude), (0.01, -77.595));
887 for grid in [
890 GridInfo::new(512, 512, 100.0, 40.0, 360.0 / 65536.0, -360.0 / 65536.0),
891 GridInfo::new(3072, 1536, -180.0, 89.91, 0.1171875, -0.117),
892 ] {
893 let same = snap_regional_steps(grid.clone());
894 assert_eq!(same.longitude_step, grid.longitude_step);
895 assert_eq!(same.first_longitude, grid.first_longitude);
896 }
897 let thirty =
899 snap_regional_steps(GridInfo::new(100, 100, -100.0, 40.0, 0.03 + 1e-10, -0.03));
900 assert_eq!(thirty.longitude_step, 0.03);
901 }
902
903 #[test]
909 fn the_efas_grid_snaps_to_its_arc_minute() {
910 let (lon_step, lat_step) = (0.016666666666666607, -0.016666666666666226);
911 let full = snap_regional_steps(GridInfo::new(
912 4530,
913 2970,
914 -25.25 + lon_step / 2.0,
915 72.25 + lat_step / 2.0,
916 lon_step,
917 lat_step,
918 ));
919 assert_eq!(
920 (full.longitude_step, full.latitude_step),
921 (1.0 / 60.0, -1.0 / 60.0)
922 );
923 assert_eq!(
924 (full.first_longitude, full.first_latitude),
925 (-3029.0 / 120.0, 8669.0 / 120.0)
926 );
927 let crop = snap_regional_steps(GridInfo::new(
928 21,
929 15,
930 -0.75 + lon_step / 2.0,
931 39.55 + lat_step / 2.0,
932 lon_step,
933 lat_step,
934 ));
935 assert_eq!(
936 (crop.first_longitude, crop.first_latitude),
937 (-89.0 / 120.0, 4745.0 / 120.0)
938 );
939 for grid in [
941 GridInfo::new(100, 100, -100.0, 40.0, 0.011, -0.011),
942 GridInfo::new(100, 100, -100.0, 40.0, 0.0175, -0.0175),
943 ] {
944 let same = snap_regional_steps(grid.clone());
945 assert_eq!(
946 (same.longitude_step, same.first_longitude),
947 (grid.longitude_step, grid.first_longitude)
948 );
949 }
950 }
951
952 #[test]
959 fn the_cfs_gaussian_grid_snaps_to_the_circle_and_rolls_to_minus_180() {
960 let longitude_step = 0.9375;
961 let latitude_step = -0.9473684210526316;
962 let raw = GridInfo::new(
963 384,
964 190,
965 -0.46875 + longitude_step / 2.0,
966 89.7507 + latitude_step / 2.0,
967 longitude_step,
968 latitude_step,
969 );
970 assert_eq!(raw.first_longitude, 0.0, "the first center is on Greenwich");
971 assert!(raw.wraps());
972 let snapped = snap_global_longitudes(raw);
973 assert_eq!(snapped.longitude_step, 360.0 / 384.0);
974 assert_eq!(snapped.first_longitude, 0.0);
975 let snapped = snap_regional_steps(snapped);
977 assert_eq!(snapped.longitude_step, 0.9375);
978 let rolled = normalize_longitudes(snapped);
979 assert_eq!(rolled.column_roll, 192);
980 assert_eq!(rolled.first_longitude, -180.0);
981 assert_eq!((rolled.width, rolled.height), (384, 190));
982 assert_eq!(rolled.column_roll as f64 * rolled.longitude_step, 180.0);
985 }
986
987 #[test]
994 fn a_crop_of_the_cfs_grid_keeps_its_gaussian_steps() {
995 let longitude_step = 0.9374986808510636;
996 let latitude_step = -0.9473684358974358;
997 let raw = GridInfo::new(
998 48,
999 40,
1000 89.53112565957447 + longitude_step / 2.0,
1001 59.434895217948714 + latitude_step / 2.0,
1002 longitude_step,
1003 latitude_step,
1004 );
1005 assert!(!raw.wraps());
1006 let snapped = snap_regional_steps(snap_global_longitudes(raw.clone()));
1007 assert_eq!(snapped.longitude_step, longitude_step);
1008 assert_eq!(snapped.latitude_step, latitude_step);
1009 assert_eq!(snapped.first_longitude, raw.first_longitude);
1010 assert_eq!(snapped.first_latitude, raw.first_latitude);
1011 assert_eq!(normalize_longitudes(snapped).column_roll, 0);
1013 }
1014
1015 #[test]
1022 fn the_cfs_one_degree_grid_needs_neither_snapping_nor_a_roll() {
1023 let raw = GridInfo::new(360, 181, -180.5 + 0.5, 90.5 - 0.5, 1.0, -1.0);
1024 assert_eq!((raw.first_longitude, raw.first_latitude), (-180.0, 90.0));
1025 assert!(raw.wraps());
1026 let snapped = snap_global_longitudes(raw);
1027 assert_eq!(snapped.longitude_step, 360.0 / 360.0);
1028 assert_eq!(snapped.longitude_step, 1.0);
1029 assert_eq!(snapped.first_longitude, -180.0);
1030 let snapped = snap_regional_steps(snapped);
1032 assert_eq!((snapped.longitude_step, snapped.latitude_step), (1.0, -1.0));
1033 let rolled = normalize_longitudes(snapped);
1034 assert_eq!(rolled.column_roll, 0);
1035 assert_eq!(
1036 (rolled.first_longitude, rolled.first_latitude),
1037 (-180.0, 90.0)
1038 );
1039 assert_eq!((rolled.width, rolled.height), (360, 181));
1040 assert_eq!(181_usize.div_ceil(91), 2);
1043 }
1044
1045 #[test]
1051 fn a_crop_of_the_cfs_one_degree_grid_keeps_its_whole_degrees() {
1052 let raw = GridInfo::new(45, 38, 89.5 + 0.5, 60.5 - 0.5, 1.0, -1.0);
1053 assert!(!raw.wraps());
1054 let snapped = snap_regional_steps(snap_global_longitudes(raw));
1055 assert_eq!((snapped.longitude_step, snapped.latitude_step), (1.0, -1.0));
1056 assert_eq!(
1057 (snapped.first_longitude, snapped.first_latitude),
1058 (90.0, 60.0)
1059 );
1060 assert_eq!(normalize_longitudes(snapped).column_roll, 0);
1061 }
1062
1063 #[test]
1064 fn the_block_maximum_keeps_the_strongest_cell_and_propagates_nan() {
1065 let grid = snap_regional_steps(GridInfo::new(4, 2, -129.995, 54.995, 0.01, -0.01))
1066 .downsampled(2, Path::new("x"))
1067 .expect("divides");
1068 assert_eq!((grid.width, grid.height), (2, 1));
1069 assert_eq!(
1070 (grid.first_longitude, grid.first_latitude),
1071 (-129.99, 54.99)
1072 );
1073 assert_eq!((grid.longitude_step, grid.latitude_step), (0.02, -0.02));
1074 assert_eq!(grid.source_shape(), (2, 4));
1075 let reduction = grid.downsample.expect("reduction");
1076 assert_eq!(
1077 reduction,
1078 BlockReduction {
1079 factor: 2,
1080 source_width: 4,
1081 source_height: 2
1082 }
1083 );
1084 let plane = [0.0, 5.5, -1.0, f64::NAN, 3.0, 1.0, 2.0, 0.0];
1085 let reduced = reduction.take(&plane).expect("reduces");
1086 assert_eq!(reduced[0], 5.5);
1087 assert!(reduced[1].is_nan());
1088 assert!(GridInfo::new(5, 2, -129.995, 54.995, 0.01, -0.01)
1089 .downsampled(2, Path::new("x"))
1090 .is_err());
1091 }
1092}