Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/korp-map

crates/korp-map-wire/src/fixture.rs

//! **Native-file fixtures** for tests: small GeoParquet 1.1 native files with the columns,
//! nullability, field metadata and `geo` document osm-katana's `--encoding geoarrow`
//! export writes (`nodes.point`, `ways.multilinestring|multipolygon`,
//! `relations.resolved.multipolygon`). The simplified copies `geometry_z*` are written
//! as [`ZStore`] says: native (the export since `osm-katana-native-zcols`) or WKB (the
//! exports before it).

use std::path::Path;
use std::sync::Arc;

use arrow_array::builder::{
    BinaryBuilder, Int32Builder, Int64Builder, ListBuilder, StringBuilder, UInt8Builder,
};
use arrow_array::{ArrayRef, Float32Array, Int64Array, RecordBatch, StructArray};
use arrow_buffer::NullBuffer;
use arrow_schema::{DataType, Field, Fields, Schema, SchemaRef};
use parquet::arrow::ArrowWriter;
use parquet::basic::{Compression, ZstdLevel};
use parquet::file::properties::WriterProperties;

use crate::geoarrow::NativeBuilder;
use crate::source::Kind;

/// One row's geometry.
#[derive(Clone, Debug, PartialEq)]
pub enum Geom {
    /// A point `(lon, lat)`.
    Point(f64, f64),
    /// Parts of a multilinestring.
    Lines(Vec<Vec<(f64, f64)>>),
    /// Polygons of a multipolygon, each a list of rings (outer first).
    Polygons(Vec<Vec<Vec<(f64, f64)>>>),
}

impl Geom {
    fn coords(&self) -> Vec<(f64, f64)> {
        match self {
            Geom::Point(x, y) => vec![(*x, *y)],
            Geom::Lines(p) => p.iter().flatten().copied().collect(),
            Geom::Polygons(p) => p.iter().flatten().flatten().copied().collect(),
        }
    }
}

/// One fixture row.
#[derive(Clone, Debug, PartialEq)]
pub struct Row {
    /// OSM id.
    pub id: i64,
    /// Geometry (`None` = a NULL geometry).
    pub geom: Option<Geom>,
    /// The tag JSON.
    pub tags: Option<String>,
    /// Lowest zoom the row shows at.
    pub min_zoom: u8,
}

/// Which table the file stands for: decides the per-table column.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Table {
    /// `nodes`: no extra column, no `geometry_z*`.
    Nodes,
    /// `ways`: `node_refs`.
    Ways,
    /// `relations.resolved`: `members`.
    Relations,
}

pub use crate::geoarrow::geometry_type;

/// How a fixture file stores its simplified copies `geometry_z6/z9/z12`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ZStore {
    /// In the kind's native type, declared with its native encoding; a copy of another
    /// type (an area shrunk to a `Point`) is NULL — as osm-katana writes them now.
    Native,
    /// WKB of mixed types, declared `"WKB"` — as osm-katana wrote them before.
    Wkb,
}

const Z_COLUMNS: [&str; 3] = ["geometry_z6", "geometry_z9", "geometry_z12"];

fn wkb_field(name: &str) -> Field {
    Field::new(name, DataType::Binary, true).with_metadata(
        [
            (
                "ARROW:extension:name".to_string(),
                "geoarrow.wkb".to_string(),
            ),
            ("ARROW:extension:metadata".to_string(), "{}".to_string()),
        ]
        .into(),
    )
}

fn geo_json(kind: Kind, table: Table, zs: ZStore) -> String {
    let cover = r#""covering":{"bbox":{"xmin":["bbox","xmin"],"ymin":["bbox","ymin"],"xmax":["bbox","xmax"],"ymax":["bbox","ymax"]}}"#;
    let gt = match kind {
        Kind::Points => "Point",
        Kind::Lines => "MultiLineString",
        Kind::Areas => "MultiPolygon",
    };
    let mut cols = format!(
        r#""geometry":{{"encoding":"{}","geometry_types":["{gt}"],{cover}}}"#,
        kind.native_encoding()
    );
    if table != Table::Nodes {
        for z in Z_COLUMNS {
            cols.push_str(&match zs {
                ZStore::Wkb => format!(
                    r#","{z}":{{"encoding":"WKB","geometry_types":["Point","LineString","MultiLineString","Polygon","MultiPolygon"]}}"#
                ),
                ZStore::Native => format!(
                    r#","{z}":{{"encoding":"{}","geometry_types":["{gt}"]}}"#,
                    kind.native_encoding()
                ),
            });
        }
    }
    format!(r#"{{"version":"1.1.0","primary_column":"geometry","columns":{{{cols}}}}}"#)
}

/// The schema osm-katana's export gives `table`'s `kind` file.
#[must_use]
pub fn schema(kind: Kind, table: Table, zs: ZStore) -> SchemaRef {
    let bbox = DataType::Struct(Fields::from(
        ["xmin", "ymin", "xmax", "ymax"]
            .map(|n| Field::new(n, DataType::Float32, true))
            .to_vec(),
    ));
    let mut f = vec![
        Field::new("id", DataType::Int64, false),
        Field::new("geometry", geometry_type(kind), true),
        Field::new("tags", DataType::Utf8, true),
    ];
    match table {
        Table::Nodes => {}
        Table::Ways => f.push(Field::new(
            "node_refs",
            DataType::List(Arc::new(Field::new("item", DataType::Int64, true))),
            true,
        )),
        Table::Relations => f.push(Field::new("members", DataType::Utf8, true)),
    }
    f.push(Field::new("version", DataType::Int32, true));
    f.push(Field::new("min_zoom", DataType::UInt8, false));
    f.push(Field::new("bbox", bbox, true));
    if table != Table::Nodes {
        f.extend(Z_COLUMNS.map(|n| match zs {
            ZStore::Wkb => wkb_field(n),
            ZStore::Native => Field::new(n, geometry_type(kind), true),
        }));
    }
    Arc::new(Schema::new_with_metadata(
        f,
        [("geo".to_string(), geo_json(kind, table, zs))].into(),
    ))
}

fn geometry_array(kind: Kind, rows: &[Row]) -> ArrayRef {
    let mut b = NativeBuilder::new(kind);
    for r in rows {
        match (&r.geom, kind) {
            (Some(Geom::Point(x, y)), Kind::Points) => b.push_point(*x, *y),
            (Some(Geom::Lines(p)), Kind::Lines) => b.push_lines(p),
            (Some(Geom::Polygons(p)), Kind::Areas) => b.push_polygons(p),
            _ => b.push_null(),
        }
    }
    b.finish()
}

fn wkb_head(v: &mut Vec<u8>, t: u32) {
    v.push(1);
    v.extend(t.to_le_bytes());
}

fn wkb_coords(v: &mut Vec<u8>, c: &[(f64, f64)]) {
    v.extend((c.len() as u32).to_le_bytes());
    for (x, y) in c {
        v.extend(x.to_le_bytes());
        v.extend(y.to_le_bytes());
    }
}

/// **The fixture's simplified copy** of a row for `geometry_z<z>` (WKB, as osm-katana
/// writes it): null when the row shows only above `z`; a line keeps each part's two
/// ends (a `LineString` for one part, else a `MultiLineString`); an area keeps the
/// first three corners of each ring (a `MultiPolygon`), except that at z6 every fourth
/// area (id % 4 == 0) has shrunk to a `Point` — too small to draw there.
#[must_use]
pub fn generalised(kind: Kind, row: &Row, z: u8) -> Option<Vec<u8>> {
    if row.min_zoom > z {
        return None;
    }
    let mut v = Vec::new();
    match (&row.geom, kind) {
        (Some(Geom::Lines(parts)), Kind::Lines) => {
            let ends: Vec<Vec<(f64, f64)>> =
                parts.iter().map(|p| vec![p[0], p[p.len() - 1]]).collect();
            if ends.len() == 1 {
                wkb_head(&mut v, 2);
                wkb_coords(&mut v, &ends[0]);
            } else {
                wkb_head(&mut v, 5);
                v.extend((ends.len() as u32).to_le_bytes());
                for e in &ends {
                    wkb_head(&mut v, 2);
                    wkb_coords(&mut v, e);
                }
            }
        }
        (Some(Geom::Polygons(polys)), Kind::Areas) => {
            if z == 6 && row.id % 4 == 0 {
                let (x, y) = polys[0][0][0];
                wkb_head(&mut v, 1);
                v.extend(x.to_le_bytes());
                v.extend(y.to_le_bytes());
                return Some(v);
            }
            wkb_head(&mut v, 6);
            v.extend((polys.len() as u32).to_le_bytes());
            for poly in polys {
                wkb_head(&mut v, 3);
                v.extend((poly.len() as u32).to_le_bytes());
                for ring in poly {
                    let r = if ring.len() >= 4 {
                        vec![ring[0], ring[1], ring[2], ring[0]]
                    } else {
                        ring.clone()
                    };
                    wkb_coords(&mut v, &r);
                }
            }
        }
        _ => return None,
    }
    Some(v)
}

/// The f32 at or below `v`.
fn f32_down(v: f64) -> f32 {
    let f = v as f32;
    if f64::from(f) > v { f.next_down() } else { f }
}

/// The f32 at or above `v`.
fn f32_up(v: f64) -> f32 {
    let f = v as f32;
    if f64::from(f) < v { f.next_up() } else { f }
}

/// The rows as one batch of [`schema`]`(kind, table, zs)`.
#[must_use]
pub fn batch(kind: Kind, table: Table, rows: &[Row], zs: ZStore) -> RecordBatch {
    let schema = schema(kind, table, zs);
    let mut cols: Vec<ArrayRef> = vec![
        Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.id))),
        geometry_array(kind, rows),
    ];
    let mut tags = StringBuilder::new();
    for r in rows {
        tags.append_option(r.tags.as_deref());
    }
    cols.push(Arc::new(tags.finish()));
    match table {
        Table::Nodes => {}
        Table::Ways => {
            let mut b = ListBuilder::new(Int64Builder::new()).with_field(Arc::new(Field::new(
                "item",
                DataType::Int64,
                true,
            )));
            for r in rows {
                let n = r.geom.as_ref().map_or(0, |g| g.coords().len());
                for k in 0..n {
                    b.values().append_value(r.id * 1000 + k as i64);
                }
                b.append(true);
            }
            cols.push(Arc::new(b.finish()));
        }
        Table::Relations => {
            let mut b = StringBuilder::new();
            for r in rows {
                b.append_value(format!(
                    r#"[{{"type":"way","ref":{},"role":"outer"}}]"#,
                    r.id
                ));
            }
            cols.push(Arc::new(b.finish()));
        }
    }
    let mut v = Int32Builder::new();
    let mut z = UInt8Builder::new();
    for r in rows {
        v.append_value(1);
        z.append_value(r.min_zoom);
    }
    cols.push(Arc::new(v.finish()));
    cols.push(Arc::new(z.finish()));
    let ext: Vec<Option<[f32; 4]>> = rows
        .iter()
        .map(|r| {
            r.geom.as_ref().map(|g| {
                let c = g.coords();
                let fold = |f: fn(f64, f64) -> f64, init: f64, pick: fn(&(f64, f64)) -> f64| {
                    c.iter().map(pick).fold(init, f)
                };
                [
                    f32_down(fold(f64::min, f64::INFINITY, |p| p.0)),
                    f32_down(fold(f64::min, f64::INFINITY, |p| p.1)),
                    f32_up(fold(f64::max, f64::NEG_INFINITY, |p| p.0)),
                    f32_up(fold(f64::max, f64::NEG_INFINITY, |p| p.1)),
                ]
            })
        })
        .collect();
    let child = |k: usize| {
        Arc::new(Float32Array::from(
            ext.iter().map(|e| e.map(|e| e[k])).collect::<Vec<_>>(),
        )) as ArrayRef
    };
    let DataType::Struct(bf) = schema
        .field_with_name("bbox")
        .expect("bbox")
        .data_type()
        .clone()
    else {
        unreachable!()
    };
    cols.push(Arc::new(StructArray::new(
        bf,
        vec![child(0), child(1), child(2), child(3)],
        Some(NullBuffer::from(
            ext.iter().map(Option::is_some).collect::<Vec<_>>(),
        )),
    )));
    if table != Table::Nodes {
        for z in [6u8, 9, 12] {
            cols.push(match zs {
                ZStore::Wkb => {
                    let mut b = BinaryBuilder::new();
                    for r in rows {
                        b.append_option(generalised(kind, r, z));
                    }
                    Arc::new(b.finish())
                }
                ZStore::Native => {
                    let mut b = NativeBuilder::new(kind);
                    for r in rows {
                        match generalised(kind, r, z) {
                            Some(w) => {
                                b.push_wkb(&w);
                            }
                            None => b.push_null(),
                        }
                    }
                    b.finish()
                }
            });
        }
    }
    RecordBatch::try_new(schema, cols).expect("fixture batch fits its schema")
}

/// Write `rows` as `path`, `row_group_rows` rows per row group, zstd, with statistics.
pub fn write(
    path: &Path,
    kind: Kind,
    table: Table,
    rows: &[Row],
    row_group_rows: usize,
    zs: ZStore,
) -> parquet::errors::Result<()> {
    let b = batch(kind, table, rows, zs);
    let props = WriterProperties::builder()
        .set_compression(Compression::ZSTD(ZstdLevel::default()))
        .set_max_row_group_row_count(Some(row_group_rows.max(1)))
        .build();
    let mut w = ArrowWriter::try_new(std::fs::File::create(path)?, b.schema(), Some(props))?;
    w.write(&b)?;
    w.close()?;
    Ok(())
}