crates/korp-map-quality/tests/data_metrics.rs
//! End to end without a server: a reply in the wire's own shape (an Arrow IPC stream with
//! zstd-compressed buffers, GeoArrow native multipolygons) is decoded and measured
//! against a land reference on a view's grid.
use std::sync::Arc;
use arrow_array::builder::{Float64Builder, ListBuilder, StructBuilder};
use arrow_array::{ArrayRef, Int64Array, RecordBatch, StringArray, UInt8Array};
use arrow_schema::{DataType, Field, Fields, Schema};
use korp_map_quality::land::LandRef;
use korp_map_quality::metrics::{self, Class};
use korp_map_quality::view::{Kind, PLACES, View};
use korp_map_quality::wire::{self, Reply};
fn coord_fields() -> Fields {
Fields::from(vec![
Field::new("x", DataType::Float64, false),
Field::new("y", DataType::Float64, false),
])
}
/// A multipolygon: polygons of rings of lon/lat.
type MultiPolygon = Vec<Vec<Vec<[f64; 2]>>>;
/// One areas reply: rows of (tags, multipolygon).
fn areas_ipc(rows: &[(&str, MultiPolygon)]) -> Vec<u8> {
let coord = StructBuilder::new(
coord_fields(),
vec![
Box::new(Float64Builder::new()),
Box::new(Float64Builder::new()),
],
);
let ring = ListBuilder::new(coord).with_field(Arc::new(Field::new(
"element",
DataType::Struct(coord_fields()),
false,
)));
let poly = ListBuilder::new(ring);
let mut mp = ListBuilder::new(poly);
for (_, polys) in rows {
for p in polys {
for r in p {
for c in r {
let s = mp.values().values().values();
s.field_builder::<Float64Builder>(0)
.unwrap()
.append_value(c[0]);
s.field_builder::<Float64Builder>(1)
.unwrap()
.append_value(c[1]);
s.append(true);
}
mp.values().values().append(true);
}
mp.values().append(true);
}
mp.append(true);
}
let geom: ArrayRef = Arc::new(mp.finish());
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::Int64, false),
Field::new("tags", DataType::Utf8, true),
Field::new("min_zoom", DataType::UInt8, false),
Field::new("geometry", geom.data_type().clone(), true),
]));
let n = rows.len();
let b = RecordBatch::try_new(
schema.clone(),
vec![
Arc::new(Int64Array::from_iter_values(0..n as i64)),
Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.0))),
Arc::new(UInt8Array::from(vec![6u8; n])),
geom,
],
)
.unwrap();
let opts = arrow_ipc::writer::IpcWriteOptions::default()
.try_with_compression(Some(arrow_ipc::CompressionType::ZSTD))
.unwrap();
let mut out = Vec::new();
let mut w =
arrow_ipc::writer::StreamWriter::try_new_with_options(&mut out, &schema, opts).unwrap();
w.write(&b).unwrap();
w.finish().unwrap();
drop(w);
out
}
fn rect(b: [f64; 4]) -> Vec<[f64; 2]> {
vec![
[b[0], b[1]],
[b[2], b[1]],
[b[2], b[3]],
[b[0], b[3]],
[b[0], b[1]],
]
}
#[test]
fn a_view_half_forest_half_bare_with_a_sliver_between_two_forests() {
let mut v = View::new(&PLACES[3], 16.0);
v.width = 400;
v.height = 200;
v.bbox = v.grid().bbox();
let g = v.grid();
let b = g.bbox();
let lon = |x: f64| b[0] + (b[2] - b[0]) * x / 400.0;
let lat = |y: f64| b[3] - (b[3] - b[1]) * y / 200.0; // close enough at this size
// Two forests side by side on the left half, a 1-px sliver between them; a lake.
let left = rect([lon(-10.0), lat(210.0), lon(100.0), lat(-10.0)]);
let right = rect([lon(101.0), lat(210.0), lon(200.0), lat(-10.0)]);
let lake = rect([lon(300.0), lat(120.0), lon(340.0), lat(80.0)]);
let body = areas_ipc(&[
(r#"{"natural":"wood"}"#, vec![vec![left]]),
(r#"{"landuse":"forest"}"#, vec![vec![right]]),
(r#"{"natural":"water","name":"Testsjön"}"#, vec![vec![lake]]),
(
r#"{"boundary":"administrative","admin_level":"7"}"#,
vec![vec![rect([lon(-50.0), lat(250.0), lon(450.0), lat(-50.0)])]],
),
]);
let (features, _) = wire::decode(Kind::Areas, &body).expect("decodes");
assert_eq!(features.len(), 4);
let reply = Reply {
kind: "areas".into(),
rows: 4,
bytes: body.len(),
features,
..Reply::default()
};
// All land.
let land = LandRef::new(vec![rect([b[0] - 1.0, b[1] - 1.0, b[2] + 1.0, b[3] + 1.0])]).mask(&g);
assert!(land.iter().all(|&l| l));
let m = metrics::data_metrics(&v, &[reply], &land);
// Left half forest (200 of 400 columns, minus the sliver column) + the lake (40×40).
let want = 100.0 * (199.0 * 200.0 + 1600.0) / 80_000.0;
assert!(
(m.coverage_filled_pct - want).abs() < 0.6,
"{} vs {want}",
m.coverage_filled_pct
);
assert_eq!(
m.area_rows.get(&Class::Boundary),
Some(&1),
"the kommun outline is counted, never painted"
);
// The one-column sliver between the forests runs off the canvas top and bottom, so it
// is not enclosed: no gap here (the enclosed case is the next test).
assert_eq!(m.gaps.count, 0);
assert!(
m.largest
.iter()
.any(|l| l.name.as_deref() == Some("Testsjön") && l.px.is_some())
);
}
#[test]
fn an_enclosed_sliver_between_neighbours_is_a_gap() {
let mut v = View::new(&PLACES[1], 16.0);
v.width = 200;
v.height = 200;
v.bbox = v.grid().bbox();
let g = v.grid();
let ll = |x: f64, y: f64| {
let (lo, la) = g.to_lonlat(x, y);
[lo, la]
};
let r = |x0: f64, y0: f64, x1: f64, y1: f64| {
vec![ll(x0, y1), ll(x1, y1), ll(x1, y0), ll(x0, y0), ll(x0, y1)]
};
// A frame of forest around two farmland fields that miss each other by one pixel.
let body = areas_ipc(&[
(
r#"{"natural":"wood"}"#,
vec![vec![r(0.0, 0.0, 200.0, 200.0), r(50.0, 50.0, 150.0, 150.0)]],
),
(
r#"{"landuse":"farmland"}"#,
vec![vec![r(50.0, 50.0, 100.0, 150.0)]],
),
(
r#"{"landuse":"meadow"}"#,
vec![vec![r(101.0, 50.0, 150.0, 150.0)]],
),
]);
let (features, _) = wire::decode(Kind::Areas, &body).unwrap();
let reply = Reply {
kind: "areas".into(),
features,
..Reply::default()
};
let land = vec![true; 200 * 200];
let m = metrics::data_metrics(&v, &[reply], &land);
assert_eq!(m.gaps.count, 1, "{:?}", m.gaps);
assert_eq!(m.gaps.pixels, 100);
}