use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use anyhow::{Context as _, bail};
use crate::config::{DatasetConfig, Reader};
use crate::coverage::Grid;
use crate::numbers::{
AreaCoverage, AreaValue, CoverageTable, FALLBACK_REACH, area_value, centroid_cell,
};
use geolith::terrain::cog::Cog;
use geolith::terrain::crs::Crs;
use geolith::terrain::dem::Dem;
#[non_exhaustive]
#[derive(Debug)]
pub enum Raster {
Whole(Dem),
Windowed(WindowedRaster),
}
impl Raster {
pub fn open(path: &Path, config: &DatasetConfig) -> anyhow::Result<Raster> {
match config.reader {
Reader::Whole => Dem::open(path, config.crs())
.with_context(|| format!("reading {}", path.display()))
.map(Raster::Whole),
Reader::Windowed => WindowedRaster::open(path, config.crs()).map(Raster::Windowed),
}
}
pub fn grid(&self) -> anyhow::Result<Grid> {
match self {
Raster::Whole(dem) => Grid::from_dem(dem),
Raster::Windowed(raster) => Ok(raster.grid),
}
}
}
#[derive(Debug, Clone)]
pub struct WindowedRaster {
path: PathBuf,
crs: Option<Crs>,
grid: Grid,
levels: Vec<(u32, u32)>,
}
impl WindowedRaster {
pub fn open(path: &Path, crs: Option<Crs>) -> anyhow::Result<WindowedRaster> {
let cog = Cog::open(path, crs).with_context(|| format!("reading {}", path.display()))?;
let grid = Grid::from_cog(&cog).with_context(|| path.display().to_string())?;
let levels = (0..cog.levels())
.filter_map(|level| cog.size(level))
.collect();
Ok(WindowedRaster {
path: path.to_path_buf(),
crs,
grid,
levels,
})
}
#[must_use]
pub fn path(&self) -> &Path {
&self.path
}
#[must_use]
pub const fn grid(&self) -> Grid {
self.grid
}
#[must_use]
pub fn levels(&self) -> &[(u32, u32)] {
&self.levels
}
pub fn open_cog(&self) -> anyhow::Result<Cog> {
Cog::open(&self.path, self.crs).with_context(|| format!("reading {}", self.path.display()))
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct ReadStats {
pub windows: u64,
pub pixels: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Window {
level: usize,
x0: i64,
y0: i64,
width: u32,
height: u32,
}
pub fn area_values_windowed(
table: &CoverageTable,
raster: &WindowedRaster,
config: &DatasetConfig,
threads: usize,
) -> anyhow::Result<(Vec<AreaValue>, ReadStats)> {
let (values, windows) = values_and_windows(table, raster, config, threads)?;
let stats = ReadStats {
windows: windows.len() as u64,
pixels: windows
.iter()
.map(|w| u64::from(w.width) * u64::from(w.height))
.sum(),
};
Ok((values, stats))
}
fn values_and_windows(
table: &CoverageTable,
raster: &WindowedRaster,
config: &DatasetConfig,
threads: usize,
) -> anyhow::Result<(Vec<AreaValue>, Vec<Window>)> {
if !raster.grid.matches(&table.grid) {
bail!(
"{}: raster grid differs from the first raster",
raster.path.display()
);
}
let grid = &table.grid;
let results = run_pool(
table.areas.len(),
threads,
|| raster.open_cog(),
|cog, i| {
let area = &table.areas[i];
let w = area_window(area, grid)?;
let samples = cog
.read_window(w.level, w.x0, w.y0, w.width, w.height)
.with_context(|| format!("{}: area {}", raster.path.display(), area.area_id))?;
let (width, height) = (i64::from(w.width), i64::from(w.height));
let decoded = |col: i64, row: i64| {
let (x, y) = (col - w.x0, row - w.y0);
if x < 0 || y < 0 || x >= width || y >= height {
return None;
}
config.decode(samples[(y * width + x) as usize])
};
Ok((area_value(area, grid, &decoded), w))
},
)?;
Ok(results.into_iter().unzip())
}
fn area_window(area: &AreaCoverage, grid: &Grid) -> anyhow::Result<Window> {
let centroid = centroid_cell(area.centroid, grid);
let points = area
.cells
.iter()
.map(|c| (i64::from(c.col), i64::from(c.row)))
.chain(centroid);
let mut bounds: Option<(i64, i64, i64, i64)> = None;
for (col, row) in points {
bounds = Some(match bounds {
None => (col, row, col, row),
Some((c0, r0, c1, r1)) => (c0.min(col), r0.min(row), c1.max(col), r1.max(row)),
});
}
let Some((c0, r0, c1, r1)) = bounds else {
return Ok(Window {
level: 0,
x0: 0,
y0: 0,
width: 0,
height: 0,
});
};
let span = |lo: i64, hi: i64| {
hi.checked_sub(lo)
.and_then(|d| d.checked_add(1 + 2 * FALLBACK_REACH))
.and_then(|n| u32::try_from(n).ok())
.with_context(|| {
format!(
"area {}: its window spans cells {lo}..={hi} plus {FALLBACK_REACH} on each side, past u32",
area.area_id
)
})
};
Ok(Window {
level: 0,
x0: c0 - FALLBACK_REACH,
y0: r0 - FALLBACK_REACH,
width: span(c0, c1)?,
height: span(r0, r1)?,
})
}
pub fn run_pool<T: Send>(
jobs: usize,
threads: usize,
open: impl Fn() -> anyhow::Result<Cog> + Sync,
job: impl Fn(&mut Cog, usize) -> anyhow::Result<T> + Sync,
) -> anyhow::Result<Vec<T>> {
if jobs == 0 {
return Ok(Vec::new());
}
let workers = threads.clamp(1, jobs);
let next = AtomicUsize::new(0);
let failed = AtomicBool::new(false);
let errors: Mutex<Vec<(Option<usize>, anyhow::Error)>> = Mutex::new(Vec::new());
let fail = |at: Option<usize>, e: anyhow::Error| {
failed.store(true, Ordering::Relaxed);
if let Ok(mut list) = errors.lock() {
list.push((at, e));
}
};
let done: anyhow::Result<Vec<Vec<(usize, T)>>> = std::thread::scope(|s| {
let handles: Vec<_> = (0..workers)
.map(|_| {
s.spawn(|| {
let mut out = Vec::with_capacity(jobs / workers + 1);
let mut cog = match open() {
Ok(cog) => cog,
Err(e) => {
fail(None, e);
return out;
}
};
while !failed.load(Ordering::Relaxed) {
let i = next.fetch_add(1, Ordering::Relaxed);
if i >= jobs {
break;
}
match job(&mut cog, i) {
Ok(result) => out.push((i, result)),
Err(e) => fail(Some(i), e),
}
}
out
})
})
.collect();
handles
.into_iter()
.map(|h| h.join().map_err(|_| anyhow::anyhow!("a worker panicked")))
.collect()
});
let done = done?;
let mut errors = errors
.into_inner()
.map_err(|_| anyhow::anyhow!("a worker panicked"))?;
errors.sort_by_key(|(at, _)| *at);
if let Some((at, e)) = errors.into_iter().next() {
return Err(match at {
Some(i) => e.context(format!("job {i} of {jobs}")),
None => e.context("opening a reader"),
});
}
let mut slots: Vec<Option<T>> = std::iter::repeat_with(|| None).take(jobs).collect();
for (i, result) in done.into_iter().flatten() {
slots[i] = Some(result);
}
slots
.into_iter()
.enumerate()
.map(|(i, slot)| slot.with_context(|| format!("job {i} of {jobs} gave no result")))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::areas::Area;
use crate::coverage::CellWeight;
use crate::numbers::{FALLBACK_REACH, area_values};
use geo::{MultiPolygon, Polygon, polygon};
const TILE: u32 = 16;
const PIXEL: f64 = 0.05;
const ORIGIN: (f64, f64) = (70.0, 30.0);
enum Samples {
F32(Vec<f32>),
U8(Vec<u8>),
}
impl Samples {
fn bits(&self) -> u16 {
match self {
Samples::F32(_) => 32,
Samples::U8(_) => 8,
}
}
fn format(&self) -> u16 {
match self {
Samples::F32(_) => 3,
Samples::U8(_) => 1,
}
}
fn bytes(&self, i: Option<usize>) -> Vec<u8> {
match self {
Samples::F32(v) => i.map_or(0.0, |i| v[i]).to_le_bytes().to_vec(),
Samples::U8(v) => vec![i.map_or(0, |i| v[i])],
}
}
}
fn shorts(values: &[u16]) -> Vec<u8> {
values.iter().flat_map(|v| v.to_le_bytes()).collect()
}
fn longs(values: &[u32]) -> Vec<u8> {
values.iter().flat_map(|v| v.to_le_bytes()).collect()
}
fn doubles(values: &[f64]) -> Vec<u8> {
values.iter().flat_map(|v| v.to_le_bytes()).collect()
}
fn write_tiled(
path: &Path,
width: u32,
height: u32,
samples: &Samples,
epsg: u16,
nodata: Option<&str>,
) {
let across = width.div_ceil(TILE);
let down = height.div_ceil(TILE);
let mut out = vec![b'I', b'I', 42, 0, 0, 0, 0, 0];
let (mut offsets, mut counts) = (Vec::new(), Vec::new());
for ty in 0..down {
for tx in 0..across {
offsets.push(out.len() as u32);
let start = out.len();
for y in ty * TILE..(ty + 1) * TILE {
for x in tx * TILE..(tx + 1) * TILE {
let inside = x < width && y < height;
let i = inside.then(|| (y * width + x) as usize);
out.extend(samples.bytes(i));
}
}
counts.push((out.len() - start) as u32);
}
}
let geokeys: Vec<u16> = if epsg == 4326 {
vec![1, 1, 0, 3, 1024, 0, 1, 2, 1025, 0, 1, 1, 2048, 0, 1, 4326]
} else {
vec![1, 1, 0, 3, 1024, 0, 1, 1, 1025, 0, 1, 1, 3072, 0, 1, epsg]
};
let mut entries: Vec<(u16, u16, u32, Vec<u8>)> = vec![
(256, 4, 1, longs(&[width])),
(257, 4, 1, longs(&[height])),
(258, 3, 1, shorts(&[samples.bits()])),
(259, 3, 1, shorts(&[1])),
(262, 3, 1, shorts(&[1])),
(277, 3, 1, shorts(&[1])),
(284, 3, 1, shorts(&[1])),
(322, 4, 1, longs(&[TILE])),
(323, 4, 1, longs(&[TILE])),
(324, 4, offsets.len() as u32, longs(&offsets)),
(325, 4, counts.len() as u32, longs(&counts)),
(339, 3, 1, shorts(&[samples.format()])),
(33550, 12, 3, doubles(&[PIXEL, PIXEL, 0.0])),
(
33922,
12,
6,
doubles(&[0.0, 0.0, 0.0, ORIGIN.0, ORIGIN.1, 0.0]),
),
(34735, 3, geokeys.len() as u32, shorts(&geokeys)),
];
if let Some(text) = nodata {
let mut bytes = text.as_bytes().to_vec();
bytes.push(0);
entries.push((42113, 2, bytes.len() as u32, bytes));
}
let mut fields = Vec::with_capacity(entries.len());
for (tag, kind, count, bytes) in entries {
let value = if bytes.len() <= 4 {
let mut inline = bytes;
inline.resize(4, 0);
inline
} else {
if out.len() % 2 == 1 {
out.push(0);
}
let at = out.len() as u32;
out.extend(bytes);
at.to_le_bytes().to_vec()
};
fields.push((tag, kind, count, value));
}
if out.len() % 2 == 1 {
out.push(0);
}
let ifd = out.len() as u32;
out[4..8].copy_from_slice(&ifd.to_le_bytes());
out.extend((fields.len() as u16).to_le_bytes());
for (tag, kind, count, value) in fields {
out.extend(tag.to_le_bytes());
out.extend(kind.to_le_bytes());
out.extend(count.to_le_bytes());
out.extend(value);
}
out.extend(0_u32.to_le_bytes());
std::fs::write(path, out).expect("write tiff");
}
fn config(reader: &str, crs_epsg: &str) -> DatasetConfig {
DatasetConfig::from_json_str(&format!(
r##"{{"id": "t", "name": "T", "unit": "mm", "period": "pentad",
"scale": 1.0, "offset": 0.0, "valid_min": 0.0, "valid_max": 5000.0,
"nodata": -9999.0, "crs_epsg": {crs_epsg},
"file_template": "t.{{year}}.{{month}}.{{pentad}}.tif",
"max_zoom": 6, "tile_size": 256, "season_start": "06-01",
"stale_after_days": 18, "attribution": "a", "source_url": "https://example.org",
"licence": "CC BY 4.0", "reader": "{reader}",
"ramp": [{{"value": 0.0, "color": "#ffffd9"}},
{{"value": 5.0, "color": "#0c2c84"}}]}}"##
))
.expect("test config is valid")
}
fn ndvi_config() -> DatasetConfig {
DatasetConfig::from_json_str(include_str!("../data/datasets/ndvi.json"))
.expect("the ndvi config is valid")
}
fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> Polygon<f64> {
polygon![(x: x0, y: y0), (x: x1, y: y0), (x: x1, y: y1), (x: x0, y: y1), (x: x0, y: y0)]
}
fn area(id: &str, parts: Vec<Polygon<f64>>) -> Area {
Area {
code: None,
id: id.to_owned(),
name: id.to_owned(),
country: "IN".to_owned(),
level: "county".to_owned(),
parent_id: None,
parent_name: None,
region_code: None,
shape: MultiPolygon::new(parts),
}
}
fn corner(col: u32, row: u32) -> (f64, f64) {
(
ORIGIN.0 + f64::from(col) * PIXEL,
ORIGIN.1 - f64::from(row) * PIXEL,
)
}
const W: u32 = 40;
const H: u32 = 24;
fn varied() -> Vec<f32> {
let mut values: Vec<f32> = (0..W * H)
.map(|i| ((i * 37) % 101) as f32 * 0.5 + 1.0)
.collect();
for row in 6..=10 {
for col in 28..=32 {
if (col, row) != (32, 8) {
values[(row * W + col) as usize] = -9999.0;
}
}
}
values
}
fn varied_areas() -> Vec<Area> {
let (x0, y0) = corner(3, 2);
let (x1, y1) = corner(9, 7);
let (ex0, ey0) = corner(37, 18);
let (nx0, ny0) = corner(30, 8);
vec![
area(
"inner",
vec![polygon![
(x: x0 + 0.013, y: y0 - 0.01), (x: x1 + 0.6, y: y0 - 0.2),
(x: x1 + 0.3, y: y1 - 0.4), (x: x0 + 0.1, y: y1)
]],
),
area(
"edge",
vec![rect(ex0 + 0.01, ey0 - 0.4, ex0 + 0.3, ey0 - 0.01)],
),
area(
"fallback",
vec![rect(nx0 + 0.01, ny0 - 0.04, nx0 + 0.04, ny0 - 0.01)],
),
]
}
fn values_of(raster: &Raster, areas: &[Area], config: &DatasetConfig) -> Vec<AreaValue> {
let table = CoverageTable::build(areas, raster.grid().expect("wgs84 grid"));
area_values(&table, raster, config, Path::new("t.tif")).expect("values")
}
#[test]
fn windowed_values_equal_whole_values() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("t.tif");
write_tiled(&path, W, H, &Samples::F32(varied()), 4326, None);
let areas = varied_areas();
let whole = Raster::open(&path, &config("whole", "4326")).expect("whole");
let windowed = Raster::open(&path, &config("windowed", "4326")).expect("windowed");
assert!(matches!(windowed, Raster::Windowed(_)), "{windowed:?}");
let whole_values = values_of(&whole, &areas, &config("whole", "4326"));
let windowed_values = values_of(&windowed, &areas, &config("windowed", "4326"));
assert_eq!(whole_values, windowed_values);
let by_id = |id: &str| {
windowed_values
.iter()
.find(|v| v.area_id == id)
.expect("area")
};
let fallback = by_id("fallback");
assert!(fallback.fallback, "{fallback:?}");
let (cx, cy) = corner(32, 8);
let [x, y] = fallback.fallback_cell.expect("a fallback cell");
assert!(
(x - (cx + PIXEL / 2.0)).abs() < 1e-9 && (y - (cy - PIXEL / 2.0)).abs() < 1e-9,
"{fallback:?}"
);
let edge = by_id("edge");
assert!(edge.value.is_some() && edge.cells > 0, "{edge:?}");
}
#[test]
fn one_window_per_area() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("t.tif");
write_tiled(&path, W, H, &Samples::F32(varied()), 4326, None);
let config = config("windowed", "4326");
let Raster::Windowed(raster) = Raster::open(&path, &config).expect("open") else {
panic!("a windowed config opens a windowed raster");
};
let areas = varied_areas();
let table = CoverageTable::build(&areas, raster.grid());
let (_, stats) = area_values_windowed(&table, &raster, &config, 2).expect("values");
assert_eq!(stats.windows, areas.len() as u64);
let (_, windows) = values_and_windows(&table, &raster, &config, 2).expect("values");
assert_eq!(windows.len(), areas.len());
let pixels: u64 = windows
.iter()
.map(|w| u64::from(w.width) * u64::from(w.height))
.sum();
assert_eq!(stats.pixels, pixels);
for id in ["inner", "edge"] {
let i = table
.areas
.iter()
.position(|a| a.area_id == id)
.expect("area");
let cells = &table.areas[i].cells;
let col_min = i64::from(cells.iter().map(|c| c.col).min().expect("cells"));
let col_max = i64::from(cells.iter().map(|c| c.col).max().expect("cells"));
let row_min = i64::from(cells.iter().map(|c| c.row).min().expect("cells"));
let row_max = i64::from(cells.iter().map(|c| c.row).max().expect("cells"));
let w = windows[i];
assert_eq!(w.level, 0, "{id}");
assert!(w.x0 <= col_min - FALLBACK_REACH, "{id}: {w:?}");
assert!(w.y0 <= row_min - FALLBACK_REACH, "{id}: {w:?}");
assert!(
w.x0 + i64::from(w.width) > col_max + FALLBACK_REACH,
"{id}: {w:?}"
);
assert!(
w.y0 + i64::from(w.height) > row_max + FALLBACK_REACH,
"{id}: {w:?}"
);
}
let inner = table
.areas
.iter()
.position(|a| a.area_id == "inner")
.expect("inner");
let cells = &table.areas[inner].cells;
let cols = cells.iter().map(|c| c.col).max().expect("cells")
- cells.iter().map(|c| c.col).min().expect("cells")
+ 1;
assert_eq!(
i64::from(windows[inner].width),
i64::from(cols) + 2 * FALLBACK_REACH
);
let rows = cells.iter().map(|c| c.row).max().expect("cells")
- cells.iter().map(|c| c.row).min().expect("cells")
+ 1;
assert_eq!(
i64::from(windows[inner].height),
i64::from(rows) + 2 * FALLBACK_REACH
);
let col_min = cells.iter().map(|c| c.col).min().expect("cells");
let row_min = cells.iter().map(|c| c.row).min().expect("cells");
assert_eq!(windows[inner].x0, i64::from(col_min) - FALLBACK_REACH);
assert_eq!(windows[inner].y0, i64::from(row_min) - FALLBACK_REACH);
}
fn windowed_raster(dir: &Path) -> WindowedRaster {
let path = dir.join("t.tif");
write_tiled(&path, W, H, &Samples::F32(varied()), 4326, None);
let Raster::Windowed(raster) =
Raster::open(&path, &config("windowed", "4326")).expect("open")
else {
panic!("a windowed config opens a windowed raster");
};
raster
}
fn only_window(dir: &Path, one: Area) -> (Window, AreaValue, AreaValue) {
let raster = windowed_raster(dir);
let cfg = config("windowed", "4326");
let table = CoverageTable::build(std::slice::from_ref(&one), raster.grid());
let (values, windows) = values_and_windows(&table, &raster, &cfg, 1).expect("values");
let whole = Raster::open(&dir.join("t.tif"), &config("whole", "4326")).expect("whole");
let whole_values = values_of(&whole, &[one], &config("whole", "4326"));
let pick = |v: &[AreaValue]| {
v.iter()
.find(|v| v.area_id == "one")
.cloned()
.expect("area")
};
(windows[0], pick(&values), pick(&whole_values))
}
#[test]
fn an_area_off_the_grid_reads_its_centroid_cell_window() {
let dir = tempfile::tempdir().expect("tempdir");
let (x0, y0) = (ORIGIN.0 - 10.0 * PIXEL, ORIGIN.1 - 5.0 * PIXEL);
let off = area(
"one",
vec![rect(x0 + 0.01, y0 - 0.04, x0 + 0.04, y0 - 0.01)],
);
let (w, windowed, whole) = only_window(dir.path(), off);
assert_eq!(
(w.x0, w.y0, w.width, w.height),
(-10 - FALLBACK_REACH, 5 - FALLBACK_REACH, 5, 5),
"{w:?}"
);
assert_eq!(windowed, whole);
assert_eq!(windowed.value, None);
}
#[test]
fn an_off_grid_centroid_widens_the_window() {
let dir = tempfile::tempdir().expect("tempdir");
let y0 = ORIGIN.1 - 5.0 * PIXEL;
let wide = area(
"one",
vec![rect(ORIGIN.0 - 1.0, y0 - 0.04, ORIGIN.0 + 0.07, y0 - 0.01)],
);
let (w, windowed, whole) = only_window(dir.path(), wide);
assert_eq!(
(w.x0, w.y0, w.width, w.height),
(-10 - FALLBACK_REACH, 5 - FALLBACK_REACH, 16, 5),
"{w:?}"
);
assert_eq!(windowed, whole);
assert!(windowed.value.is_some(), "{windowed:?}");
}
#[test]
fn an_area_without_shape_reads_an_empty_window() {
let raster = {
let dir = tempfile::tempdir().expect("tempdir");
windowed_raster(dir.path()).grid()
};
let empty = AreaCoverage {
area_id: "empty".to_owned(),
centroid: (f64::NAN, f64::NAN),
cells: Vec::new(),
};
let w = area_window(&empty, &raster).expect("an empty window");
assert_eq!((w.width, w.height), (0, 0), "{w:?}");
}
#[test]
fn a_window_span_past_u32_names_the_area() {
let grid = {
let dir = tempfile::tempdir().expect("tempdir");
windowed_raster(dir.path()).grid()
};
let far = AreaCoverage {
area_id: "far-away".to_owned(),
centroid: (ORIGIN.0 + 8_589_934_592.5 * PIXEL, ORIGIN.1 - 0.5 * PIXEL),
cells: vec![CellWeight {
col: 0,
row: 0,
fraction: 1.0,
area_m2: 1.0,
}],
};
let err = area_window(&far, &grid).expect_err("a span past u32");
let text = format!("{err:#}");
assert!(text.contains("far-away"), "{text}");
}
#[test]
fn a_flagged_cell_lowers_coverage_not_the_value() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("ndvi.tif");
let mut raw = vec![200_u8; (W * H) as usize];
for (col, row, v) in [(4, 3, 100), (5, 3, 100), (4, 4, 100), (5, 4, 254)] {
raw[(row * W + col) as usize] = v;
}
write_tiled(&path, W, H, &Samples::U8(raw), 4326, None);
let config = ndvi_config();
let raster = Raster::open(&path, &config).expect("open");
assert!(matches!(raster, Raster::Windowed(_)), "{raster:?}");
let (x0, y0) = corner(4, 3);
let (x1, y1) = corner(6, 5);
let values = values_of(&raster, &[area("a", vec![rect(x0, y1, x1, y0)])], &config);
let v = values.iter().find(|v| v.area_id == "a").expect("area");
let expected = config.decode(100.0).expect("100 is valid");
let value = v.value.expect("a value");
assert!((value - expected).abs() < 1e-12, "{value} vs {expected}");
let row_area = |row: u32| {
let top = (ORIGIN.1 - f64::from(row) * PIXEL).to_radians();
let bottom = (ORIGIN.1 - f64::from(row + 1) * PIXEL).to_radians();
top.sin() - bottom.sin()
};
let (north, south) = (row_area(3), row_area(4));
let expected_pct = (2.0 * north + south) / (2.0 * north + 2.0 * south) * 100.0;
assert!((v.coverage_pct - expected_pct).abs() < 1e-9, "{v:?}");
assert!((v.coverage_pct - 75.0).abs() < 0.01, "{v:?}");
assert_eq!(v.cells, 3);
}
#[test]
fn the_pool_opens_one_cog_per_worker() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("t.tif");
write_tiled(&path, W, H, &Samples::F32(varied()), 4326, None);
let opened = AtomicUsize::new(0);
let results = run_pool(
50,
3,
|| {
opened.fetch_add(1, Ordering::SeqCst);
Cog::open(&path, None).map_err(anyhow::Error::from)
},
|cog, i| {
let v = cog.read_window(0, i as i64 % 40, 0, 1, 1)?;
Ok((i * 7, v.len()))
},
)
.expect("pool");
assert_eq!(opened.load(Ordering::SeqCst), 3);
let expected: Vec<(usize, usize)> = (0..50).map(|i| (i * 7, 1)).collect();
assert_eq!(results, expected);
}
#[test]
fn a_failing_job_is_named() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("t.tif");
write_tiled(&path, W, H, &Samples::F32(varied()), 4326, None);
let err = run_pool(
20,
4,
|| Cog::open(&path, None).map_err(anyhow::Error::from),
|_, i| {
if i == 13 {
bail!("boom")
}
Ok(i)
},
)
.expect_err("job 13 fails");
let text = format!("{err:#}");
assert!(text.contains("job 13"), "{text}");
assert!(text.contains("boom"), "{text}");
}
#[test]
fn a_cog_on_another_crs_is_refused() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("merc.tif");
write_tiled(&path, W, H, &Samples::F32(varied()), 3857, None);
let err = Raster::open(&path, &config("windowed", "null")).expect_err("not wgs84");
let text = format!("{err:#}");
assert!(text.contains("EPSG:4326"), "{text}");
assert!(text.contains("merc.tif"), "{text}");
}
}