Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / dem_ingest / src / sample.rs
sample.rs227 lines · 8.2 KiBRaw
| 1 | //! COP90 sampling: a bounded LRU of decoded 1° GeoTIFF tiles and the |
| 2 | //! nearest-neighbour resample that turns an output map tile's grid points into |
| 3 | //! biased `u16` heights. Decoding a tile is deterministic, so the cache only |
| 4 | //! affects speed — two threads with their own caches produce identical grids. |
| 5 | |
| 6 | use std::collections::{HashMap, VecDeque}; |
| 7 | use std::path::Path; |
| 8 | |
| 9 | use crate::geotags::read_geotags; |
| 10 | use crate::tilemath::{tile_x_to_lon, tile_y_to_lat}; |
| 11 | |
| 12 | /// Sea level in the biased `u16` grid: `round(0 m) + 32768`. |
| 13 | pub const SEA_LEVEL: u16 = 32768; |
| 14 | |
| 15 | /// Cap on decoded 1° COP90 tiles held at once (~6 MB each): 96 entries stay |
| 16 | /// well under a gigabyte while the id-order walk keeps neighbours close. |
| 17 | const DEM_CACHE_CAP: usize = 96; |
| 18 | |
| 19 | /// One decoded COP90 tile: Float32 heights plus its geo transform from its own tags. |
| 20 | pub struct CopTile { |
| 21 | width: u32, |
| 22 | height: u32, |
| 23 | /// Longitude of the pixel (0,0) centre's west edge; latitude of its north edge. |
| 24 | west: f64, |
| 25 | north: f64, |
| 26 | pixel_w: f64, |
| 27 | pixel_h: f64, |
| 28 | nodata: Option<f64>, |
| 29 | data: Vec<f32>, |
| 30 | } |
| 31 | |
| 32 | impl CopTile { |
| 33 | /// Nearest-neighbour sample as a biased `u16`; out-of-range, nodata and NaN |
| 34 | /// cells read as sea level. |
| 35 | pub fn sample(&self, lon: f64, lat: f64) -> u16 { |
| 36 | let col = ((lon - self.west) / self.pixel_w).floor() as i64; |
| 37 | let row = ((self.north - lat) / self.pixel_h).floor() as i64; |
| 38 | if col < 0 || row < 0 || col >= self.width as i64 || row >= self.height as i64 { |
| 39 | return SEA_LEVEL; |
| 40 | } |
| 41 | let v = self.data[row as usize * self.width as usize + col as usize] as f64; |
| 42 | if !v.is_finite() || self.nodata == Some(v) { |
| 43 | return SEA_LEVEL; |
| 44 | } |
| 45 | elevation_to_stored(v) |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | /// Sample one output tile's grid, or `None` when no DEM tile under it exists. |
| 50 | pub fn sample_tile( |
| 51 | dem_dir: &Path, |
| 52 | ox: u64, |
| 53 | oy: u64, |
| 54 | out_zoom: u8, |
| 55 | dim: usize, |
| 56 | cache: &mut DemCache, |
| 57 | ) -> Result<Option<Vec<u16>>, String> { |
| 58 | let mut grid = Vec::with_capacity(dim * dim); |
| 59 | let mut any_data = false; |
| 60 | for row in 0..dim { |
| 61 | // Grid point fractional position within the output tile, top-left origin. |
| 62 | let fy = oy as f64 + row as f64 / (dim as f64 - 1.0); |
| 63 | let lat = tile_y_to_lat(fy, out_zoom); |
| 64 | for col in 0..dim { |
| 65 | let fx = ox as f64 + col as f64 / (dim as f64 - 1.0); |
| 66 | let lon = tile_x_to_lon(fx, out_zoom); |
| 67 | // The 1° COP90 cell this lon/lat lands in, by its south-west corner. |
| 68 | let key = (lon.floor() as i32, lat.floor() as i32); |
| 69 | let sample = match cache.get_or_decode(dem_dir, key)? { |
| 70 | Some(tile) => { |
| 71 | any_data = true; |
| 72 | tile.sample(lon, lat) |
| 73 | } |
| 74 | // No DEM here: sea level. A tile entirely over missing DEM is dropped by the caller. |
| 75 | None => SEA_LEVEL, |
| 76 | }; |
| 77 | grid.push(sample); |
| 78 | } |
| 79 | } |
| 80 | Ok(any_data.then_some(grid)) |
| 81 | } |
| 82 | |
| 83 | /// Bounded LRU of decoded COP90 tiles (`None` = no tile file for that 1° cell). |
| 84 | pub struct DemCache { |
| 85 | map: HashMap<(i32, i32), Option<CopTile>>, |
| 86 | order: VecDeque<(i32, i32)>, |
| 87 | } |
| 88 | |
| 89 | impl DemCache { |
| 90 | pub fn new() -> Self { |
| 91 | Self { map: HashMap::new(), order: VecDeque::new() } |
| 92 | } |
| 93 | |
| 94 | pub fn get_or_decode( |
| 95 | &mut self, |
| 96 | dem_dir: &Path, |
| 97 | key: (i32, i32), |
| 98 | ) -> Result<&Option<CopTile>, String> { |
| 99 | if !self.map.contains_key(&key) { |
| 100 | let path = dem_dir.join(tile_filename(key.0, key.1)); |
| 101 | let decoded = if path.is_file() { |
| 102 | Some( |
| 103 | decode_cop_tile(&path, key) |
| 104 | .map_err(|e| format!("decoding {}: {e}", path.display()))?, |
| 105 | ) |
| 106 | } else { |
| 107 | None |
| 108 | }; |
| 109 | self.order.push_back(key); |
| 110 | self.map.insert(key, decoded); |
| 111 | while self.map.len() > DEM_CACHE_CAP { |
| 112 | if let Some(old) = self.order.pop_front() { |
| 113 | self.map.remove(&old); |
| 114 | } else { |
| 115 | break; |
| 116 | } |
| 117 | } |
| 118 | } |
| 119 | Ok(self.map.get(&key).expect("just inserted")) |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | /// The COP90 file covering the 1° cell with south-west corner (`tlon`, `tlat`): |
| 124 | /// `Copernicus_DSM_30_N00_00_E006_00_DEM.tif` covers lat 0..1, lon 6..7. |
| 125 | fn tile_filename(tlon: i32, tlat: i32) -> String { |
| 126 | let lat_part = if tlat >= 0 { |
| 127 | format!("N{tlat:02}") |
| 128 | } else { |
| 129 | format!("S{:02}", -tlat) |
| 130 | }; |
| 131 | let lon_part = if tlon >= 0 { |
| 132 | format!("E{tlon:03}") |
| 133 | } else { |
| 134 | format!("W{:03}", -tlon) |
| 135 | }; |
| 136 | format!("Copernicus_DSM_30_{lat_part}_00_{lon_part}_00_DEM.tif") |
| 137 | } |
| 138 | |
| 139 | /// Decode one COP90 tile: Float32 pixels via the `tiff` crate, geo transform |
| 140 | /// from the file's own ModelPixelScale/ModelTiepoint tags (falling back to the |
| 141 | /// 1° filename grid when the tags are absent). |
| 142 | fn decode_cop_tile(path: &Path, key: (i32, i32)) -> Result<CopTile, String> { |
| 143 | let file = std::fs::File::open(path).map_err(|e| format!("opening: {e}"))?; |
| 144 | let mut decoder = tiff::decoder::Decoder::new(file).map_err(|e| format!("tiff header: {e}"))?; |
| 145 | let (width, height) = decoder.dimensions().map_err(|e| format!("tiff dimensions: {e}"))?; |
| 146 | if width == 0 || height == 0 { |
| 147 | return Err("a COP90 tile has no pixels".to_string()); |
| 148 | } |
| 149 | let data = match decoder.read_image().map_err(|e| format!("tiff pixels: {e}"))? { |
| 150 | tiff::decoder::DecodingResult::F32(v) => v, |
| 151 | _ => return Err("a COP90 tile is Float32, got another sample type".to_string()), |
| 152 | }; |
| 153 | if data.len() != width as usize * height as usize { |
| 154 | return Err(format!( |
| 155 | "a COP90 tile has {}x{} pixels but {} samples", |
| 156 | width, |
| 157 | height, |
| 158 | data.len() |
| 159 | )); |
| 160 | } |
| 161 | // Filename grid fallback: the 1° cell the name promises. |
| 162 | let geo = read_geotags(path).unwrap_or_default(); |
| 163 | Ok(CopTile { |
| 164 | width, |
| 165 | height, |
| 166 | west: geo.west.unwrap_or(key.0 as f64), |
| 167 | north: geo.north.unwrap_or((key.1 + 1) as f64), |
| 168 | pixel_w: geo.pixel_w.unwrap_or(1.0 / width as f64), |
| 169 | pixel_h: geo.pixel_h.unwrap_or(1.0 / height as f64), |
| 170 | nodata: geo.nodata, |
| 171 | data, |
| 172 | }) |
| 173 | } |
| 174 | |
| 175 | /// Biased `u16` for metres: `round(m) + 32768`; non-finite reads as sea level, clamps. |
| 176 | fn elevation_to_stored(m: f64) -> u16 { |
| 177 | if !m.is_finite() { |
| 178 | return SEA_LEVEL; |
| 179 | } |
| 180 | (m.round() + 32768.0).clamp(0.0, u16::MAX as f64) as u16 |
| 181 | } |
| 182 | |
| 183 | #[cfg(test)] |
| 184 | mod tests { |
| 185 | use super::*; |
| 186 | |
| 187 | #[test] |
| 188 | fn elevation_bias_puts_sea_level_at_32768() { |
| 189 | assert_eq!(elevation_to_stored(0.0), 32768); |
| 190 | assert_eq!(elevation_to_stored(1.0), 32769); |
| 191 | // Sub-metre precision rounds to the nearest metre. |
| 192 | assert_eq!(elevation_to_stored(0.6), 32769); |
| 193 | // The Dead Sea shore, ~-430 m, sits below the bias. |
| 194 | assert_eq!(elevation_to_stored(-430.0), 32338); |
| 195 | // Non-finite and out-of-range input reads as sea level / clamps. |
| 196 | assert_eq!(elevation_to_stored(f64::NAN), 32768); |
| 197 | assert_eq!(elevation_to_stored(f64::INFINITY), 32768); |
| 198 | assert_eq!(elevation_to_stored(-40000.0), 0); |
| 199 | } |
| 200 | |
| 201 | #[test] |
| 202 | fn tile_filenames_cover_all_hemispheres() { |
| 203 | assert_eq!(tile_filename(6, 0), "Copernicus_DSM_30_N00_00_E006_00_DEM.tif"); |
| 204 | assert_eq!(tile_filename(-70, -38), "Copernicus_DSM_30_S38_00_W070_00_DEM.tif"); |
| 205 | assert_eq!(tile_filename(138, 73), "Copernicus_DSM_30_N73_00_E138_00_DEM.tif"); |
| 206 | assert_eq!(tile_filename(-88, -89), "Copernicus_DSM_30_S89_00_W088_00_DEM.tif"); |
| 207 | } |
| 208 | |
| 209 | #[test] |
| 210 | fn cop_tile_samples_nearest_neighbour_and_sea_level() { |
| 211 | let tile = CopTile { |
| 212 | width: 2, |
| 213 | height: 2, |
| 214 | west: 6.0, |
| 215 | north: 1.0, |
| 216 | pixel_w: 0.5, |
| 217 | pixel_h: 0.5, |
| 218 | nodata: Some(-32768.0), |
| 219 | data: vec![100.0, -32768.0, f32::NAN, -50.0], |
| 220 | }; |
| 221 | assert_eq!(tile.sample(6.1, 0.9), 32868); |
| 222 | assert_eq!(tile.sample(6.6, 0.9), 32768, "nodata reads as sea level"); |
| 223 | assert_eq!(tile.sample(6.1, 0.4), 32768, "NaN reads as sea level"); |
| 224 | assert_eq!(tile.sample(6.6, 0.4), 32718); |
| 225 | assert_eq!(tile.sample(99.0, 99.0), 32768, "out of range reads as sea level"); |
| 226 | } |
| 227 | } |