geolith-cli 0.2.1

Rust vector tile generator — OSM + Overture Maps → protomaps PMTiles
Documentation
#![allow(clippy::unwrap_used)] // tests and benches may unwrap (AGENTS.md).

//! Windowed `GeoTIFF` reads against fixtures whose pixel values follow a known
//! formula, so every expected value comes from the formula and not from the
//! reader.
//!
//! Fixtures in `tests/fixtures`, made with GDAL from raw arrays:
//! - `cog-formula.tif`: 300x200 Float32 COG, 64x64 tiles, DEFLATE, EPSG:32643,
//!   origin (500000, 2100000), 15 m pixels; value `row * 1000 + col`;
//!   nodata -9999 at row 7, col 5; one 150x100 overview made with
//!   `gdaladdo -r average 2`, so overview pixel `(c, r)` is the mean of
//!   its 2x2 block: `(2r + 0.5) * 1000 + 2c + 0.5`.
//! - `strip-formula.tif`: 50x40 Float32, strips of 7 rows, EPSG:4326;
//!   value `row * 1000 + col`, nodata -9999 at row 7, col 5.
//! - `int16-formula.tif`: 70x70 Int16, 32x32 tiles, DEFLATE, EPSG:4326;
//!   value `row * 100 + col`, nodata -32768 at row 3, col 4.

use std::path::{Path, PathBuf};

use geolith_cli::terrain::{Cog, Crs};

fn fixture(name: &str) -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures")
        .join(name)
}

fn open(name: &str) -> Cog {
    Cog::open(&fixture(name), None).expect("fixture opens")
}

/// Every pixel of a level-0 window against `row * scale + col`, with NaN
/// outside the raster and at the nodata pixel.
fn assert_formula(
    window: &[f32],
    (x0, y0, w, h): (i64, i64, i64, i64),
    (width, height): (i64, i64),
    scale: f32,
    nodata: (i64, i64),
) {
    assert_eq!(window.len() as i64, w * h);
    for y in 0..h {
        for x in 0..w {
            let (col, row) = (x0 + x, y0 + y);
            let got = window[(y * w + x) as usize];
            let outside = col < 0 || row < 0 || col >= width || row >= height;
            if outside || (col, row) == nodata {
                assert!(
                    got.is_nan(),
                    "pixel ({col}, {row}) should be NaN, got {got}"
                );
            } else {
                assert_eq!(got, row as f32 * scale + col as f32, "pixel ({col}, {row})");
            }
        }
    }
}

#[test]
fn a_cog_lists_full_resolution_then_its_overview() {
    let cog = open("cog-formula.tif");
    assert_eq!(cog.levels(), 2);
    assert_eq!(cog.size(0), Some((300, 200)));
    assert_eq!(cog.size(1), Some((150, 100)));
    assert_eq!(cog.size(2), None);
}

#[test]
fn a_window_across_four_tiles_matches_the_formula() {
    let mut cog = open("cog-formula.tif");
    let window = cog.read_window(0, 60, 60, 10, 10).expect("read");
    assert_formula(&window, (60, 60, 10, 10), (300, 200), 1000.0, (5, 7));
}

#[test]
fn the_nodata_pixel_reads_as_nan() {
    let mut cog = open("cog-formula.tif");
    let window = cog.read_window(0, 0, 0, 10, 10).expect("read");
    assert_formula(&window, (0, 0, 10, 10), (300, 200), 1000.0, (5, 7));
    assert!(window[7 * 10 + 5].is_nan());
}

/// 300 = 4 * 64 + 44 and 200 = 3 * 64 + 8, so the bottom-right tile holds
/// only 44 x 8 pixels of data.
#[test]
fn a_window_over_the_partial_corner_tile_matches_the_formula() {
    let mut cog = open("cog-formula.tif");
    let window = cog.read_window(0, 250, 180, 50, 20).expect("read");
    assert_formula(&window, (250, 180, 50, 20), (300, 200), 1000.0, (5, 7));
}

#[test]
fn pixels_outside_the_raster_are_nan() {
    let mut cog = open("cog-formula.tif");
    let window = cog.read_window(0, -3, 195, 6, 10).expect("read");
    assert_formula(&window, (-3, 195, 6, 10), (300, 200), 1000.0, (5, 7));
    let empty = cog.read_window(0, 400, 0, 4, 4).expect("read");
    assert!(empty.iter().all(|v| v.is_nan()));
}

#[test]
fn an_overview_window_holds_2x2_block_means() {
    let mut cog = open("cog-formula.tif");
    let (x0, y0, w, h) = (10_i64, 20_i64, 4_i64, 3_i64);
    let window = cog
        .read_window(1, x0, y0, w as u32, h as u32)
        .expect("read");
    for y in 0..h {
        for x in 0..w {
            let (c, r) = ((x0 + x) as f32, (y0 + y) as f32);
            let expected = (2.0 * r + 0.5) * 1000.0 + 2.0 * c + 0.5;
            assert_eq!(
                window[(y * w + x) as usize],
                expected,
                "overview pixel ({c}, {r})"
            );
        }
    }
}

#[test]
fn an_overview_transform_doubles_the_pixel_size_at_the_same_origin() {
    let cog = open("cog-formula.tif");
    let full = cog.geo_transform(0).expect("level 0");
    let overview = cog.geo_transform(1).expect("level 1");
    assert_eq!((full.origin_x, full.origin_y), (500_000.0, 2_100_000.0));
    assert_eq!((full.pixel_width, full.pixel_height), (15.0, 15.0));
    assert_eq!(
        (overview.origin_x, overview.origin_y),
        (500_000.0, 2_100_000.0)
    );
    assert_eq!((overview.pixel_width, overview.pixel_height), (30.0, 30.0));
    assert!(cog.geo_transform(2).is_none());
    assert_eq!(cog.crs(), Crs::from_epsg(32_643).expect("UTM 43N"));
}

#[test]
fn a_stripped_tiff_reads_across_strip_boundaries() {
    let mut cog = open("strip-formula.tif");
    assert_eq!(cog.levels(), 1);
    assert_eq!(cog.crs(), Crs::Wgs84);
    let window = cog.read_window(0, 2, 5, 40, 12).expect("read");
    assert_formula(&window, (2, 5, 40, 12), (50, 40), 1000.0, (5, 7));
}

#[test]
fn integer_samples_read_as_f32_with_nodata_as_nan() {
    let mut cog = open("int16-formula.tif");
    let window = cog.read_window(0, 0, 0, 70, 70).expect("read");
    assert_formula(&window, (0, 0, 70, 70), (70, 70), 100.0, (4, 3));
}

#[test]
fn repeated_and_interleaved_level_reads_agree() {
    let mut cog = open("cog-formula.tif");
    let first = cog.read_window(0, 100, 100, 30, 30).expect("read");
    let overview = cog.read_window(1, 0, 0, 8, 8).expect("read overview");
    let again = cog.read_window(0, 100, 100, 30, 30).expect("read again");
    assert_formula(&again, (100, 100, 30, 30), (300, 200), 1000.0, (5, 7));
    assert_eq!(first.len(), again.len());
    assert!(first.iter().zip(&again).all(|(a, b)| a == b));
    assert_eq!(
        overview[0], 500.5,
        "overview pixel (0, 0) is the mean of 0, 1, 1000, 1001"
    );
}

#[test]
fn a_missing_level_is_an_error() {
    let mut cog = open("cog-formula.tif");
    let err = cog.read_window(5, 0, 0, 1, 1).expect_err("no level 5");
    assert!(err.to_string().contains("level 5 does not exist"), "{err}");
}

/// UTM 43N centre of pixel (col, row) in `cog-formula.tif`.
fn utm_centre(col: f64, row: f64) -> (f64, f64) {
    (
        500_000.0 + (col + 0.5) * 15.0,
        2_100_000.0 - (row + 0.5) * 15.0,
    )
}

#[test]
fn a_mosaic_patch_samples_the_source_pixels_under_a_tile() {
    use geolith_cli::terrain::{CogMosaic, ElevationSource};
    let utm = Crs::from_epsg(32_643).expect("UTM 43N");
    let mosaic = CogMosaic::open(&[fixture("cog-formula.tif")], None).expect("open");
    // A box around pixels (100..140, 50..90), as WGS84 bounds.
    let (lon0, lat1) = utm.to_wgs84(utm_centre(100.0, 50.0).0, utm_centre(100.0, 50.0).1);
    let (lon1, lat0) = utm.to_wgs84(utm_centre(140.0, 90.0).0, utm_centre(140.0, 90.0).1);
    let patches = mosaic
        .patches((lon0, lat0, lon1, lat1), 15.0)
        .expect("patches");
    assert_eq!(patches.len(), 1);
    for (col, row) in [(100.0, 50.0), (120.0, 70.0), (140.0, 90.0)] {
        let (x, y) = utm_centre(col, row);
        let got = patches[0].sample(x, y).expect("inside the patch");
        assert_eq!(got, (row * 1000.0 + col) as f32, "pixel ({col}, {row})");
    }
    assert!(
        patches[0].values.len() < 300 * 200 / 10,
        "reads a window, not the raster"
    );
}

#[test]
fn a_coarse_tile_reads_the_overview() {
    use geolith_cli::terrain::{CogMosaic, ElevationSource};
    let mosaic = CogMosaic::open(&[fixture("cog-formula.tif")], None).expect("open");
    let patches = mosaic
        .patches(mosaic.wgs84_bounds(), 30.0)
        .expect("patches");
    assert_eq!(
        patches[0].transform.pixel_width, 30.0,
        "30 m tile pixels use the 30 m overview"
    );
}

/// `int16-formula.tif` and `strip-formula.tif` overlap at 73.0-73.05 E,
/// 18.96-19.0 N. The mosaic keeps the order it was given, so either file
/// can be the primary source.
#[test]
fn overlapping_sources_come_back_in_the_given_order() {
    use geolith_cli::terrain::{CogMosaic, ElevationSource};
    let bbox = (73.01, 18.97, 73.02, 18.98);
    // Pixel (15, 25) of the 0.001° int16 grid: lon 73.0155, lat 18.9745.
    let (lon, lat) = (73.0155, 18.9745);
    let int16_first = CogMosaic::open(
        &[fixture("int16-formula.tif"), fixture("strip-formula.tif")],
        None,
    )
    .expect("open");
    let patches = int16_first.patches(bbox, 100.0).expect("patches");
    assert_eq!(patches.len(), 2);
    assert_eq!(patches[0].sample(lon, lat), Some(25.0 * 100.0 + 15.0));

    let strip_first = CogMosaic::open(
        &[fixture("strip-formula.tif"), fixture("int16-formula.tif")],
        None,
    )
    .expect("open");
    let patches = strip_first.patches(bbox, 100.0).expect("patches");
    // The 0.001° strip grid: col 15, row 25 again.
    assert_eq!(patches[0].sample(lon, lat), Some(25.0 * 1000.0 + 15.0));
}

/// `two-band.tif`: 4x3 Float32, two samples per pixel.
#[test]
fn a_multi_band_raster_is_rejected() {
    let err = Cog::open(&fixture("two-band.tif"), None).expect_err("two bands");
    assert!(err.to_string().contains("2 samples per pixel"), "{err}");
}

#[test]
fn a_file_that_is_not_a_tiff_is_an_error() {
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("x.tif");
    std::fs::write(&path, b"not a tiff").expect("write");
    let err = Cog::open(&path, None).expect_err("not a tiff");
    assert!(err.to_string().contains("open"), "{err}");
}

/// In `cog-formula.tif` the overview tiles sit first and the full-resolution
/// tiles start at byte 22300 (`tiffdump` `TileOffsets`). Cutting the file there
/// keeps every directory and the overview but loses the level-0 tiles.
#[test]
fn a_truncated_tile_is_an_error_while_the_overview_still_reads() {
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("cut.tif");
    let bytes = std::fs::read(fixture("cog-formula.tif")).expect("fixture");
    std::fs::write(&path, &bytes[..22_300]).expect("write");
    let mut cog = Cog::open(&path, None).expect("directories are intact");
    let overview = cog
        .read_window(1, 0, 0, 4, 4)
        .expect("overview tiles are intact");
    assert_eq!(overview[0], 500.5);
    let err = cog
        .read_window(0, 0, 0, 4, 4)
        .expect_err("level-0 tile is gone");
    assert!(err.to_string().contains("read chunk 0"), "{err}");
}

#[test]
fn debug_output_names_the_file_and_levels() {
    let text = format!("{:?}", open("cog-formula.tif"));
    assert!(
        text.contains("cog-formula.tif") && text.contains("levels"),
        "{text}"
    );
}

/// A real CDSE NDVI COG is tiled 512x512 ZSTD (`ndvi-zstd.tif` is a 512x512
/// crop of the 2019-01-1 global dekad) and `ndvi-deflate.tif` is GDAL's
/// DEFLATE copy of the same 512x512 pixels. The reader must give the same
/// sample for sample from both: the ZSTD decoder is the only difference, and
/// the expected values come from GDAL, never from this reader.
#[test]
fn a_zstd_cog_reads_like_its_deflate_twin() {
    let mut zstd = open("ndvi-zstd.tif");
    let mut deflate = open("ndvi-deflate.tif");
    let (w, h) = (512, 512);
    let zstd_window = zstd.read_window(0, 0, 0, w, h).expect("zstd decodes");
    let deflate_window = deflate.read_window(0, 0, 0, w, h).expect("deflate decodes");
    assert_eq!(zstd_window.len(), (w * h) as usize);
    assert_eq!(deflate_window.len(), zstd_window.len());
    let mut valued = 0_usize;
    for (index, (a, b)) in zstd_window.iter().zip(&deflate_window).enumerate() {
        match (a.is_nan(), b.is_nan()) {
            (true, true) => continue,
            (false, false) => {
                valued += 1;
                assert_eq!(a, b, "sample {index} differs from the DEFLATE copy");
            }
            _ => panic!("sample {index}: one copy is nodata, the other is {a} / {b}"),
        }
    }
    // The crop is real vegetated land, not an empty or nodata window.
    assert!(valued > 200_000, "only {valued} samples carry a value");
}