Skip to main content

xue/encode/
grid.rs

1//! Grid discovery, the -180-first column roll, and regional cropping — the
2//! port of `xuebuild/grid.py`.
3
4use 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/// A rectangular window cut out of every extracted plane, indexed in the
13/// -180-first layout the column roll produces.
14///
15/// `column_start` may run past the source's last column: a window crossing the
16/// antimeridian continues from column 0, so columns are always taken modulo
17/// `source_width`. Rows never wrap — the grid ends at the poles.
18#[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    /// The window of one `(source_height, source_width)` plane.
30    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/// The thinning a source's `Downsample` asks for, fixed to one file's grid:
43/// every `factor` x `factor` block of the `(source_height, source_width)`
44/// plane becomes its maximum. Never serialized: the bundle's grid is the
45/// thinned one.
46/// Mirrors `BlockReduction` in `xuebuild/grid.py`.
47#[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    /// The block maximum of one `(source_height, source_width)` plane. A NaN
60    /// anywhere in a block is the block's value, as numpy's `max` has it, so
61    /// a broken record still fails the completeness check downstream instead
62    /// of vanishing into a maximum (`f64::max` would drop it).
63    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    /// Columns every extracted plane is rolled right by, so grids GDAL leaves
104    /// starting at Greenwich (the sflux Gaussian grid) come out in the same
105    /// -180-first layout as every other source. 0 for grids GDAL already
106    /// rotates.
107    pub column_roll: usize,
108    /// Regional window applied after the roll (showcase cases). When set,
109    /// every field above describes the *cropped* planes, and the window
110    /// carries the source dimensions the extraction actually reads. Never
111    /// serialized: the cropped origin and extent already say where the data is.
112    pub crop: Option<CropWindow>,
113    /// Set for a source published coarser than it arrives (MRMS): the
114    /// extracted planes are the source grid, and every field above describes
115    /// the thinned grid their block maxima land on, before any crop. Never
116    /// serialized either.
117    pub downsample: Option<BlockReduction>,
118    /// Set on a grid on a map projection ([`GridInfo::projected`]), which has
119    /// none of the regular fields: this says where its cells are, and a window's
120    /// or a tier's is that window's or tier's own.
121    pub projection: Option<ProjectedGrid>,
122    /// Set on a regular Gaussian grid, beside the regular fields every other
123    /// number here still comes from.
124    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    /// The grid a projected file's planes are published on. Its regular fields
152    /// are NaN, so arithmetic on them cannot pass for a place.
153    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    /// `(height, width)` of the plane the extraction reads.
173    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    /// The grid produced by keeping every second row and column. For the
184    /// 721-row production grid the last kept row still lands exactly on the
185    /// south pole, and 720 columns at a doubled step still cover 360 degrees. A
186    /// projected grid's first cell stays where it is at twice the spacing, and a
187    /// Gaussian grid's rows are every second one of those it had.
188    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    /// The grid a source's block reduction publishes — the port of
211    /// `downsample_grid` in `xuebuild/grid.py`: one cell per
212    /// `factor` x `factor` block, centered on the block (half a source step
213    /// in per extra cell, rounded to ten decimals the way a crop's origin
214    /// is), at `factor` times the step. The source must divide into whole
215    /// blocks, and a global or rolled grid is not thinned.
216    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
283/// How far a file's first latitude may lie from the Gaussian row it is taken
284/// for, as a fraction of a row. GDAL's even spacing is within 0.014 of one of the
285/// true rows on sflux; on CFSv2, whose step is 180°/190, it starts true and a
286/// window cut from the northern hemisphere is at most this far off.
287const GAUSSIAN_ROW_TOLERANCE: f64 = 0.25;
288
289/// Which rows of the Gaussian grid of `n` a file's are: the inverse of the
290/// iteration's first guess, rounded, so a whole file's are all of them and a file
291/// cut out of one starts wherever its first latitude says, its rows still
292/// consecutive. A file that is not on the grid is refused. Mirrors
293/// `gaussian_rows` in `xuebuild/grid.py`.
294pub 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
316/// How far short of (or past) a full circle a grid's columns may fall, as a
317/// fraction of one cell, and still be the global grid they clearly are.
318const GLOBAL_SPAN_TOLERANCE_CELLS: f64 = 1e-3;
319
320/// Give a global grid the exact step and origin its column count implies —
321/// the port of `snap_global_longitudes` in `xuebuild/grid.py`, which
322/// explains the rule; the two must agree to the bit.
323///
324/// GDAL derives a GRIB grid's longitude step from the first and last
325/// longitudes, and WAVEWATCH III writes the 0.25° grid's last column as
326/// 359.750016°, which makes a 0.2500000111° step whose 1440 columns do not
327/// close the circle. A grid whose columns span 360° to within a thousandth
328/// of a cell is the global grid: its step becomes `360 / width` and its
329/// first center is placed on that step's grid (rounding half up) when it
330/// lies within the same tolerance of it. Exact and regional grids pass
331/// through unchanged.
332pub 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
349/// The steps a regional grid is snapped to, as (unit, divisor) in the
350/// order they are tried: whole thousandths of a degree, then whole
351/// arc-minutes (EFAS's 1/60°, which no decimal spells: the double GDAL
352/// derives for it needs seventeen digits, more than some `gdalinfo`
353/// releases print). Mirrors `_REGIONAL_STEP_UNITS` in `xuebuild/grid.py`.
354fn regional_step_units() -> [(f64, f64); 2] {
355    [(1e-3, 1000.0), (1.0 / 60.0, 60.0)]
356}
357
358/// Give a regional grid the round step it was clearly published on — the
359/// port of `snap_regional_steps` in `xuebuild/grid.py`, which
360/// explains the rule; the two must agree to the bit.
361///
362/// The same GDAL habit that puts a global grid a hair off the globe puts a
363/// regional one a hair off its step: MRMS writes the last longitude of its
364/// 0.01° grid two millionths short, which GDAL turns into a 0.0099999997°
365/// step. A grid whose cells, at the nearest whole thousandth of a degree
366/// or, failing that, the nearest whole arc-minute (EFAS's 1/60°), span its
367/// extent to within a thousandth of a cell is on that step, on both axes
368/// independently, and its first *center* is placed on the half-step grid
369/// (a grid whose edges are on whole steps has its centers half a step in)
370/// when it lies within the same tolerance. A step that is near neither
371/// passes through unchanged, as does a global grid.
372pub 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
389/// One axis of [`snap_regional_steps`]: `(step, first)` snapped, or as
390/// given. The snapped values are whole units divided out at the end —
391/// `30 / 1000` is the double nearest 0.03 where `30 * 0.001` is not.
392fn 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
412/// Roll grids that start at Greenwich to the -180-first layout.
413///
414/// GDAL's GRIB driver rotates global regular lat/lon grids to start at -180
415/// but leaves the sflux Gaussian grid starting at longitude 0; downstream
416/// (shaders, posters, particles) assumes one layout, so the columns whose
417/// centers lie at or past 180 degrees move to the front of every extracted
418/// plane.
419pub fn normalize_longitudes(grid: GridInfo) -> GridInfo {
420    // A wrapping grid GDAL already rotated starts within half a wrap of -180;
421    // the sflux grid's first cell center computes to exactly 0.0, so the test
422    // must be "starts near -180", not "non-positive".
423    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
442/// Round to ten decimal places the way Python's `round(value, 10)` does:
443/// correct decimal rounding, ties to even.
444fn round10(value: f64) -> f64 {
445    format!("{value:.10}").parse().unwrap_or(value)
446}
447
448/// Restrict a grid to the smallest whole-cell window covering `bbox`
449/// (`west, south, east, north`, degrees).
450///
451/// The window keeps the cell whose center sits at or before each lower edge
452/// and the one at or after each upper edge, so the cropped planes always cover
453/// the requested box outright. On a wrapping source grid `west > east` crosses
454/// the antimeridian; the returned origin is renormalized into [-180, 180) and
455/// the window, not the metadata, carries the wrap.
456///
457/// On a projected grid the box is a curved patch: see `crop_projected`. A
458/// Gaussian grid is cropped by its regular fields, and its rows follow.
459pub 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    // Degrees east of the grid's origin. A wrapping grid has every longitude
494    // on some column. A regional grid is taken in the copy of the world it
495    // lies in: a satellite disk over the Pacific runs from 80.7 to 200.7, and
496    // a box spelled -170 is at 190 on it, while a box a few degrees west of
497    // the origin is west of it, not most of the way around the world.
498    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
569/// Points walked along each edge of a box, ends included: an edge is a curve on
570/// the projected plane, and these bound it to well under a cell of any window a
571/// case asks for.
572const BBOX_EDGE_POINTS: usize = 64;
573/// Past this the cone's radius runs away, and a box reaching a pole is the whole
574/// grid in any case.
575const BBOX_LATITUDE_LIMIT: f64 = 89.9;
576
577/// The smallest whole-cell window covering a box's edges. Each of the four edges
578/// is walked in [`BBOX_EDGE_POINTS`] points and projected; the window takes the
579/// cell at or before the lowest column and row they reach and the one at or after
580/// the highest, the rule a regular grid's crop has, clamped to the grid. A box
581/// wholly off the grid is refused.
582fn 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        // Every corner of the box lies inside the window, spelled either way.
682        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    /// The whole CFSv2 grid is all the rows; a window is wherever its first
723    /// latitude says, and a file that is not on the grid is refused.
724    #[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        // Half a row off, past the last row, or at another grid's step.
741        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        // A Himawari disk on plate carrée: 80.7 to 200.7 at 0.04°, not wrapping.
792        let disk = GridInfo::new(3000, 3000, 80.7, 60.0, 0.04, -0.04);
793        assert!(!disk.wraps());
794        // A box spelled west of -180 lands on the disk's eastern columns...
795        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        // ...the same box spelled past 180 is the same window...
800        let same = crop_grid(disk.clone(), (190.0, 0.0, 200.0, 10.0)).unwrap();
801        assert_eq!(same.crop, east.crop);
802        // ...a box just west of the origin clamps to it rather than reading
803        // as almost a whole world east, and one east of the disk misses it.
804        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            // The sflux Gaussian grid before its roll: first center at 0.
834            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    /// The MRMS grid as GDAL reports it, and a crop of it as the GRIB writer
860    /// re-rounds it, both land on 0.01° with their centers half a step in.
861    #[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        // A step that is not near a thousandth — the radar mosaic's
888        // power-of-two tiles, the Gaussian grid — passes through.
889        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        // 0.03 comes out as the double nearest 0.03, not 30 * 0.001.
898        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    /// The EFAS grid is on the arc-minute, which no thousandth spells: GDAL
904    /// derives 0.016666666666666607 and -0.016666666666666226 from the
905    /// coordinates, and both axes land on the double nearest 1/60 with the
906    /// centers on the half-minute grid — the same doubles the Python side
907    /// writes, however many digits its `gdalinfo` printed.
908    #[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        // A step a whole thousandth off stays off; so does one near no minute.
940        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    /// The CFSv2 T126 Gaussian grid, as GDAL reports the surface flux
953    /// records: 384 x 190 from a corner at (-0.46875, 89.7507), so the
954    /// first cell center is exactly on Greenwich — the sflux grid's shape.
955    /// It closes the circle at 360 / 384, and the columns at or past 180
956    /// move to the front, which is what puts it in the -180-first layout
957    /// every other source arrives in.
958    #[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        // A wrapping grid is never re-stepped as a regional one.
976        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        // 192 columns of 0.9375° is exactly half the world, so the roll is
983        // the grid's own half: column 0 of the rolled plane is 180° E.
984        assert_eq!(rolled.column_roll as f64 * rolled.longitude_step, 180.0);
985    }
986
987    /// A 48 x 40 cell window cut out of that grid with `gdal_translate
988    /// -srcwin` — the CFSv2 test fixture. GDAL re-derives the step from the
989    /// window's first and last coordinates and lands a hair off 0.9375, and
990    /// the regional snap must leave it there: a 0.9375° step is nowhere
991    /// near a whole thousandth of a degree, and rounding it to 0.938 would
992    /// move the last column a fortieth of a cell.
993    #[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        // And a window of a global grid is not rolled either.
1012        assert_eq!(normalize_longitudes(snapped).column_roll, 0);
1013    }
1014
1015    /// The other CFSv2 grid: the 1° pressure-level series of the `pgb`
1016    /// family, which GDAL reports as 360 x 181 from a corner at
1017    /// (-180.5, 90.5). Its step is already exactly 1° and its first cell
1018    /// center already at -180, so the global snap changes nothing and there
1019    /// is no roll — the family arrives in the -180-first layout the surface
1020    /// grid has to be rolled into.
1021    #[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        // A wrapping grid is never re-stepped as a regional one.
1031        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        // 181 rows of 1° is pole to pole, the row count the 90 x 91 tile
1041        // cuts into two rows of tiles, the last one cell short.
1042        assert_eq!(181_usize.div_ceil(91), 2);
1043    }
1044
1045    /// The 45 x 38 cell window of that grid the CFSv2 pressure-level fixture
1046    /// was cut to with `gdal_translate -srcwin 270 30 45 38`: GDAL reports
1047    /// the geotransform (89.5, 1, 0, 60.5, 0, -1), so the window keeps whole
1048    /// degrees, the regional snap leaves both axes where they are, and
1049    /// nothing rolls.
1050    #[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}