use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use h3o::{CellIndex, LatLng, Resolution};
use tippecanoe::attribute::AttributeOp;
use tippecanoe::geometry::{Draw, DrawVec, VT_CLOSEPATH, VT_LINETO, VT_MOVETO};
use tippecanoe::milo::dtoa_milo;
use tippecanoe::mvt::{MVT_BOOL, MVT_DOUBLE, MVT_NULL, MVT_STRING};
use tippecanoe::projection::PROJECTIONS;
use tippecanoe::serial::SerialVal;
use super::serialize::InFeature;
use crate::options::Options;
pub fn resolution(zoom: i32) -> u8 {
match zoom {
..=1 => 1,
2 | 3 => 2,
4 => 3,
5 => 4,
6 | 7 => 5,
8 => 6,
9 | 10 => 7,
11 => 8,
12 | 13 => 9,
14 => 10,
z => (z as f64 * 0.7).round_ties_even().min(15.0) as u8,
}
}
const CATEGORIES: usize = 64;
#[derive(Debug)]
pub struct Setup {
pub base: i32,
pub no_points: bool,
pub fade: i32,
pub windows: Vec<(u8, i32, i32)>,
resolutions: Vec<Resolution>,
accumulate: Vec<(String, AttributeOp)>,
median: Vec<String>,
category: Option<String>,
}
impl Setup {
pub fn new(o: &Options) -> Setup {
let base = o.h3_base();
let maxzoom = o.maxzoom.max(o.minzoom);
let mut windows: Vec<(u8, i32, i32)> = Vec::new();
for z in o.minzoom..base {
let r = o
.h3_resolutions
.get(&z)
.copied()
.unwrap_or_else(|| resolution(z));
match windows.last_mut() {
Some(w) if w.0 == r => w.2 = z,
_ => windows.push((r, z, z)),
}
}
for w in windows.iter_mut() {
w.1 = (w.1 - o.h3_fade).max(o.minzoom);
w.2 = (w.2 + o.h3_fade).min(maxzoom);
}
let mut resolutions: Vec<Resolution> = windows
.iter()
.map(|w| Resolution::try_from(w.0).expect("a resolution of 0 to 15"))
.collect();
resolutions.sort();
resolutions.dedup();
let mut accumulate: Vec<(String, AttributeOp)> = o
.attribute_accum
.iter()
.map(|(k, v)| (k.clone(), *v))
.collect();
accumulate.sort_by(|a, b| a.0.cmp(&b.0));
let mut median = o.h3_median.clone();
median.sort();
median.dedup();
Setup {
base: if o.h3_no_points {
base
} else {
(base - o.h3_fade).max(o.minzoom)
},
no_points: o.h3_no_points,
fade: o.h3_fade,
windows,
resolutions,
accumulate,
median,
category: o.h3_categories.clone(),
}
}
}
impl Setup {
pub fn json(&self) -> String {
let windows: Vec<String> = self
.windows
.iter()
.map(|w| format!("[{},{},{}]", w.0, w.1, w.2))
.collect();
format!(
"{{\"windows\":[{}],\"fade\":{},\"points\":{}}}",
windows.join(","),
self.fade,
if self.no_points {
"null".to_string()
} else {
self.base.to_string()
}
)
}
}
#[derive(Clone, Debug, Default)]
struct Sum {
n: u64,
sum: f64,
product: f64,
min: f64,
max: f64,
}
impl Sum {
fn add(&mut self, v: f64) {
if self.n == 0 {
*self = Sum {
n: 1,
sum: v,
product: v,
min: v,
max: v,
};
return;
}
self.n += 1;
self.sum += v;
self.product *= v;
self.min = self.min.min(v);
self.max = self.max.max(v);
}
fn merge(&mut self, o: &Sum) {
if o.n == 0 {
return;
}
if self.n == 0 {
*self = o.clone();
return;
}
self.n += o.n;
self.sum += o.sum;
self.product *= o.product;
self.min = self.min.min(o.min);
self.max = self.max.max(o.max);
}
fn value(&self, op: AttributeOp) -> Option<f64> {
if self.n == 0 {
return None;
}
Some(match op {
AttributeOp::Sum => self.sum,
AttributeOp::Product => self.product,
AttributeOp::Mean => self.sum / self.n as f64,
AttributeOp::Max => self.max,
AttributeOp::Min => self.min,
AttributeOp::Count => self.n as f64,
AttributeOp::Concat | AttributeOp::Comma => return None,
})
}
}
#[derive(Clone, Debug, Default)]
struct Bin {
count: u64,
sums: Vec<Sum>,
values: Vec<Vec<f64>>,
categories: BTreeMap<String, u64>,
uncategorized: u64,
}
impl Bin {
fn merge(&mut self, o: &Bin) {
self.count += o.count;
if self.sums.len() < o.sums.len() {
self.sums.resize(o.sums.len(), Sum::default());
}
for (a, b) in self.sums.iter_mut().zip(&o.sums) {
a.merge(b);
}
if self.values.len() < o.values.len() {
self.values.resize(o.values.len(), Vec::new());
}
for (a, b) in self.values.iter_mut().zip(&o.values) {
a.extend_from_slice(b);
}
for (k, v) in &o.categories {
*self.categories.entry(k.clone()).or_default() += v;
}
self.uncategorized += o.uncategorized;
}
}
fn median(values: &mut [f64]) -> Option<f64> {
if values.is_empty() {
return None;
}
values.sort_unstable_by(f64::total_cmp);
let n = values.len();
Some(if n % 2 == 1 {
values[n / 2]
} else {
let (a, b) = (values[n / 2 - 1], values[n / 2]);
a + (b - a) / 2.0
})
}
#[derive(Debug, Default)]
pub struct Bins {
layers: BTreeMap<String, HashMap<u64, Bin>>,
}
fn number(v: &SerialVal) -> Option<f64> {
if v.type_ == MVT_STRING {
return None;
}
let s = v.s.split('\0').next().unwrap_or("");
s.parse::<f64>().ok()
}
impl Bins {
pub fn add(
&mut self,
setup: &Setup,
layer: &str,
points: impl Iterator<Item = (i64, i64)>,
keys: &[Cow<'_, str>],
values: &[SerialVal],
) {
let mut point = Bin {
count: 1,
sums: vec![Sum::default(); setup.accumulate.len()],
values: vec![Vec::new(); setup.median.len()],
..Bin::default()
};
let mut categorized = false;
for (k, v) in keys.iter().zip(values) {
if let Ok(i) = setup.accumulate.binary_search_by(|a| a.0.as_str().cmp(k))
&& let Some(n) = number(v)
{
point.sums[i].add(n);
}
if let Ok(i) = setup.median.binary_search_by(|a| a.as_str().cmp(k))
&& let Some(n) = number(v)
{
point.values[i].push(n);
}
if setup.category.as_deref() == Some(k.as_ref()) && v.type_ != MVT_NULL {
let value = v.s.split('\0').next().unwrap_or("").to_string();
point.categories.insert(value, 1);
categorized = true;
}
}
if setup.category.is_some() && !categorized {
point.uncategorized = 1;
}
let cells = self.layers.entry(layer.to_string()).or_default();
for (x, y) in points {
let (lon, lat) = tippecanoe::projection::tile2lonlat(x, y, 32);
let Ok(ll) = LatLng::new(lat, lon) else {
continue;
};
for &r in &setup.resolutions {
cells
.entry(u64::from(ll.to_cell(r)))
.or_default()
.merge(&point);
}
}
}
}
pub type Joined = HashMap<(String, u64), Vec<(String, SerialVal)>>;
pub fn read_join(path: &str) -> Result<Joined, String> {
use arrow_array::Array;
use arrow_array::cast::AsArray;
use arrow_array::types::*;
use arrow_schema::DataType;
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
let file = std::fs::File::open(path).map_err(|e| e.to_string())?;
let reader = ParquetRecordBatchReaderBuilder::try_new(file)
.and_then(|b| b.build())
.map_err(|e| e.to_string())?;
let mut joined = Joined::new();
for batch in reader {
let batch = batch.map_err(|e| e.to_string())?;
let schema = batch.schema();
let column = |name: &str| schema.index_of(name).ok().map(|i| batch.column(i).clone());
let cells = column("h3").ok_or("no h3 column of cells")?;
let layers = column("layer");
for row in 0..batch.num_rows() {
if cells.is_null(row) {
continue;
}
let cell: u64 = match cells.data_type() {
DataType::Utf8 => cells
.as_string::<i32>()
.value(row)
.parse::<CellIndex>()
.map(u64::from),
DataType::LargeUtf8 => cells
.as_string::<i64>()
.value(row)
.parse::<CellIndex>()
.map(u64::from),
DataType::Utf8View => cells
.as_string_view()
.value(row)
.parse::<CellIndex>()
.map(u64::from),
DataType::UInt64 => Ok(cells.as_primitive::<UInt64Type>().value(row)),
DataType::Int64 => Ok(cells.as_primitive::<Int64Type>().value(row) as u64),
t => return Err(format!("the h3 column is {}, not text or a number", t)),
}
.map_err(|e| format!("cell {}: {}", row, e))?;
let layer = match &layers {
Some(l) if !l.is_null(row) => match l.data_type() {
DataType::Utf8 => l.as_string::<i32>().value(row).to_string(),
DataType::LargeUtf8 => l.as_string::<i64>().value(row).to_string(),
DataType::Utf8View => l.as_string_view().value(row).to_string(),
t => return Err(format!("the layer column is {}, not text", t)),
},
_ => String::new(),
};
let mut values = Vec::new();
for (i, field) in schema.fields().iter().enumerate() {
let name = field.name();
if name == "h3" || name == "layer" {
continue;
}
let a = batch.column(i);
if a.is_null(row) {
continue;
}
let number = |v: f64| SerialVal::new(MVT_DOUBLE, &dtoa_milo(v));
let integer = |v: String| SerialVal::new(MVT_DOUBLE, &v);
let v = match a.data_type() {
DataType::Int8 => integer(a.as_primitive::<Int8Type>().value(row).to_string()),
DataType::Int16 => {
integer(a.as_primitive::<Int16Type>().value(row).to_string())
}
DataType::Int32 => {
integer(a.as_primitive::<Int32Type>().value(row).to_string())
}
DataType::Int64 => {
integer(a.as_primitive::<Int64Type>().value(row).to_string())
}
DataType::UInt8 => {
integer(a.as_primitive::<UInt8Type>().value(row).to_string())
}
DataType::UInt16 => {
integer(a.as_primitive::<UInt16Type>().value(row).to_string())
}
DataType::UInt32 => {
integer(a.as_primitive::<UInt32Type>().value(row).to_string())
}
DataType::UInt64 => {
integer(a.as_primitive::<UInt64Type>().value(row).to_string())
}
DataType::Float32 => number(a.as_primitive::<Float32Type>().value(row) as f64),
DataType::Float64 => number(a.as_primitive::<Float64Type>().value(row)),
DataType::Decimal128(_, scale) => {
let v = a.as_primitive::<Decimal128Type>().value(row);
if *scale == 0 {
integer(v.to_string())
} else {
number(v as f64 / 10f64.powi(*scale as i32))
}
}
DataType::Boolean => boolean(a.as_boolean().value(row)),
DataType::Utf8 => string(a.as_string::<i32>().value(row)),
DataType::LargeUtf8 => string(a.as_string::<i64>().value(row)),
DataType::Utf8View => string(a.as_string_view().value(row)),
t => {
return Err(format!(
"the column {} is {}, not a number, true or false, or text",
name, t
));
}
};
values.push((name.to_string(), v));
}
joined.insert((layer, cell), values);
}
}
Ok(joined)
}
pub struct Hexagon {
pub layer: String,
pub feature: InFeature<'static>,
}
fn outline(cell: CellIndex) -> DrawVec {
let project = PROJECTIONS[0].project;
let mut ring: Vec<(f64, f64)> = cell
.boundary()
.iter()
.map(|ll| (ll.lng(), ll.lat()))
.collect();
let mut dv = DrawVec::new();
let draw_ring = |ring: &[(f64, f64)], dv: &mut DrawVec| {
for (i, &(lon, lat)) in ring.iter().chain(ring.first()).enumerate() {
let (x, y) = project(lon, lat, 32);
dv.push(Draw::new(if i == 0 { VT_MOVETO } else { VT_LINETO }, x, y));
}
dv.push(Draw::new(VT_CLOSEPATH, 0, 0));
};
let pole = [90.0, -90.0]
.into_iter()
.find(|&lat| LatLng::new(lat, 0.0).is_ok_and(|ll| ll.to_cell(cell.resolution()) == cell));
if let Some(lat) = pole {
let edge = lat.signum() * 85.0511287798066;
for p in ring.iter_mut() {
p.1 = p.1.clamp(-85.0511287798066, 85.0511287798066);
}
ring.sort_by(|a, b| a.0.total_cmp(&b.0));
ring.insert(0, (-180.0, ring[0].1));
ring.push((180.0, ring[ring.len() - 1].1));
ring.push((180.0, edge));
ring.push((-180.0, edge));
draw_ring(&ring, &mut dv);
return dv;
}
let (min, max) = ring
.iter()
.fold((f64::MAX, f64::MIN), |(a, b), p| (a.min(p.0), b.max(p.0)));
if max - min > 180.0 {
let east: Vec<(f64, f64)> = ring
.iter()
.map(|&(lon, lat)| (if lon < 0.0 { lon + 360.0 } else { lon }, lat))
.collect();
let west: Vec<(f64, f64)> = east.iter().map(|&(lon, lat)| (lon - 360.0, lat)).collect();
draw_ring(&east, &mut dv);
draw_ring(&west, &mut dv);
} else {
draw_ring(&ring, &mut dv);
}
dv
}
fn string(s: &str) -> SerialVal {
SerialVal::new(MVT_STRING, s)
}
fn double(v: f64) -> SerialVal {
SerialVal::new(MVT_DOUBLE, &dtoa_milo(v))
}
fn boolean(v: bool) -> SerialVal {
SerialVal::new(MVT_BOOL, if v { "true" } else { "false" })
}
pub fn hexagons(setup: &Setup, chunks: Vec<Bins>, joined: Option<&Joined>) -> Vec<Hexagon> {
let mut layers: BTreeMap<String, HashMap<u64, Bin>> = BTreeMap::new();
for chunk in chunks {
for (layer, cells) in chunk.layers {
let into = layers.entry(layer).or_default();
let mut cells: Vec<(u64, Bin)> = cells.into_iter().collect();
cells.sort_unstable_by_key(|c| c.0);
for (cell, bin) in cells {
into.entry(cell).or_default().merge(&bin);
}
}
}
let mut out = Vec::new();
for (layer, cells) in layers {
let mut totals: BTreeMap<&str, u64> = BTreeMap::new();
for bin in cells.values() {
for (k, v) in &bin.categories {
*totals.entry(k.as_str()).or_default() += v;
}
}
totals.remove("_other");
let mut ranked: Vec<(&str, u64)> = totals.into_iter().collect();
ranked.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
let named: Vec<String> = ranked
.iter()
.take(if ranked.len() > CATEGORIES {
CATEGORIES - 1
} else {
CATEGORIES
})
.map(|r| r.0.to_string())
.collect();
let mut cells: Vec<(CellIndex, Bin)> = cells
.into_iter()
.filter_map(|(cell, bin)| Some((CellIndex::try_from(cell).ok()?, bin)))
.collect();
cells.sort_unstable_by_key(|c| c.0);
for &(res, minzoom, maxzoom) in &setup.windows {
for (c, bin) in cells.iter_mut() {
if u8::from(c.resolution()) != res {
continue;
}
let c = *c;
let mut keys: Vec<Cow<'static, str>> = vec![
Cow::Borrowed("h3"),
Cow::Borrowed("h3_resolution"),
Cow::Borrowed("point_count"),
];
let mut values = vec![
string(&c.to_string()),
double(res as f64),
double(bin.count as f64),
];
for ((name, op), sum) in setup.accumulate.iter().zip(&bin.sums) {
if let Some(v) = sum.value(*op) {
keys.push(Cow::Owned(name.clone()));
values.push(double(v));
}
}
for (name, v) in setup.median.iter().zip(bin.values.iter_mut()) {
if let Some(m) = median(v) {
keys.push(Cow::Owned(name.clone()));
values.push(double(m));
}
}
if let Some(category) = &setup.category {
let mut other = bin.uncategorized;
let mut counts: BTreeMap<&str, u64> = BTreeMap::new();
for (k, v) in &bin.categories {
if named.iter().any(|n| n == k) {
counts.insert(k.as_str(), *v);
} else {
other += v;
}
}
if other > 0 {
counts.insert("_other", other);
}
for (k, v) in &counts {
keys.push(Cow::Owned(format!("{}:{}", category, k)));
values.push(double(*v as f64));
}
let most = counts.values().copied().max().unwrap_or(0);
let modal: Vec<&str> = counts
.iter()
.filter(|c| *c.1 == most)
.map(|c| *c.0)
.collect();
if let [value] = modal[..] {
keys.push(Cow::Borrowed("modal_category"));
values.push(string(value));
}
keys.extend(["modal_count", "modal_share", "modal_tie"].map(Cow::Borrowed));
values.extend([
double(most as f64),
double(most as f64 / bin.count as f64),
boolean(modal.len() > 1),
]);
}
if let Some(joined) = joined {
let cell = u64::from(c);
let extra = joined
.get(&(layer.clone(), cell))
.or_else(|| joined.get(&(String::new(), cell)));
for (k, v) in extra.into_iter().flatten() {
match keys.iter().position(|x| x == k) {
Some(i) => values[i] = v.clone(),
None => {
keys.push(Cow::Owned(k.clone()));
values.push(v.clone());
}
}
}
}
out.push(Hexagon {
layer: format!("{}_h3", layer),
feature: InFeature {
t: tippecanoe::geometry::VT_POLYGON as i8,
geometry: outline(c),
has_id: false,
id: 0,
tippecanoe_minzoom: minzoom,
tippecanoe_maxzoom: maxzoom,
full_keys: keys,
full_values: values,
},
});
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn setup(args: &str) -> Setup {
let argv: Vec<String> = std::iter::once("manby")
.chain(args.split(' '))
.chain(["-o", "x.pmtiles"])
.map(String::from)
.collect();
Setup::new(&crate::options::parse_args(&argv).unwrap())
}
#[test]
fn windows() {
let s = setup("-z14 --h3-base-zoom=12");
assert_eq!(
s.windows,
vec![
(1, 0, 1),
(2, 2, 3),
(3, 4, 4),
(4, 5, 5),
(5, 6, 7),
(6, 8, 8),
(7, 9, 10),
(8, 11, 11)
]
);
assert_eq!(s.resolutions.last(), Some(&Resolution::Eight));
assert_eq!(s.base, 12);
assert!(setup("-Z5 -z5 --h3").windows.is_empty());
let s = setup("-Z2 -z8 --h3-resolutions=3:3,4:3 --h3-fade=1");
assert_eq!(s.windows, vec![(2, 2, 3), (3, 2, 5), (4, 4, 6)]);
assert_eq!(s.base, 5);
assert!(!s.no_points);
let s = setup("-z6 --h3-no-points --h3-fade=2");
assert_eq!(s.windows.last(), Some(&(5, 4, 6)));
assert_eq!(s.base, 7);
assert!(s.no_points);
}
#[test]
fn resolutions_beyond_zoom_14() {
let r: Vec<u8> = (14..=24).map(resolution).collect();
assert_eq!(r, [10, 10, 11, 12, 13, 13, 14, 15, 15, 15, 15]);
}
#[test]
fn refused() {
for args in [
"-z8 --h3-resolutions=6:16",
"-z8 --h3-resolutions=7:5",
"-z8 --h3-resolutions=x",
"-z8 --h3-fade=-1",
"-z8 --h3-no-points --h3-base-zoom=4",
"-zg --h3-no-points",
"-z8 --h3-median=pop -Epop:sum",
] {
let argv: Vec<String> = std::iter::once("manby")
.chain(args.split(' '))
.chain(["-o", "x.pmtiles"])
.map(String::from)
.collect();
let resolved =
crate::options::parse_args(&argv).and_then(|mut o| o.resolve().map(|_| ()));
assert!(resolved.is_err(), "{}", args);
}
}
#[test]
fn medians() {
assert_eq!(median(&mut []), None);
assert_eq!(median(&mut [3.0, 1.0, 2.0]), Some(2.0));
assert_eq!(median(&mut [4.0, 1.0, 2.0, 10.0]), Some(3.0));
}
#[test]
fn counts_and_sums() {
let s = setup(
"-z6 --h3-base-zoom=4 -Epop:sum -Escore2:mean --h3-median=score --h3-categories=kind",
);
let project = PROJECTIONS[0].project;
let mut a = Bins::default();
let mut b = Bins::default();
for i in 0..4 {
let bins = if i == 0 { &mut a } else { &mut b };
let p = project(11.4 + i as f64 * 0.001, 48.2, 32);
let mut keys = vec![
Cow::Borrowed("pop"),
Cow::Borrowed("score"),
Cow::Borrowed("score2"),
];
let score = [0.0, 1.0, 2.0, 10.0][i];
let mut values = vec![double(10.0), double(score), double(score)];
if i < 3 {
keys.push(Cow::Borrowed("kind"));
values.push(string(if i == 2 { "cafe" } else { "park" }));
}
bins.add(&s, "places", std::iter::once(p), &keys, &values);
}
let hexes = hexagons(&s, vec![a, b], None);
assert_eq!(hexes.len(), 2);
let h = &hexes[0].feature;
assert_eq!(hexes[0].layer, "places_h3");
let get = |k: &str| {
h.full_keys
.iter()
.position(|x| x == k)
.map(|i| h.full_values[i].s.clone())
};
assert_eq!(get("point_count").as_deref(), Some("4"));
assert_eq!(get("pop").as_deref(), Some("40"));
assert_eq!(get("score2").as_deref(), Some("3.25"));
assert_eq!(get("score").as_deref(), Some("1.5"));
assert_eq!(get("kind:park").as_deref(), Some("2"));
assert_eq!(get("kind:cafe").as_deref(), Some("1"));
assert_eq!(get("kind:_other").as_deref(), Some("1"));
assert_eq!(get("modal_category").as_deref(), Some("park"));
assert_eq!(get("modal_count").as_deref(), Some("2"));
assert_eq!(get("modal_share").as_deref(), Some("0.5"));
assert_eq!(get("modal_tie").as_deref(), Some("false"));
assert_eq!((h.tippecanoe_minzoom, h.tippecanoe_maxzoom), (0, 1));
assert!(h.geometry.len() >= 7);
}
#[test]
fn joined_attributes() {
use arrow_array::{
ArrayRef, BooleanArray, Float64Array, Int64Array, RecordBatch, StringArray,
};
use std::sync::Arc;
let s = setup("-z2 --h3-no-points");
let project = PROJECTIONS[0].project;
let mut bins = Bins::default();
bins.add(
&s,
"places",
std::iter::once(project(11.4, 48.2, 32)),
&[],
&[],
);
let r1 = Resolution::try_from(1u8).unwrap();
let cell = LatLng::new(48.2, 11.4).unwrap().to_cell(r1);
let path =
std::env::temp_dir().join(format!("manby-h3-join-{}.parquet", std::process::id()));
let columns: Vec<(&str, ArrayRef)> = vec![
(
"h3",
Arc::new(StringArray::from(vec![cell.to_string(), cell.to_string()])),
),
(
"layer",
Arc::new(StringArray::from(vec![None, Some("places")])),
),
("p90", Arc::new(Float64Array::from(vec![1.5, 2.5]))),
("n", Arc::new(Int64Array::from(vec![Some(7), None]))),
("any", Arc::new(BooleanArray::from(vec![true, false]))),
("point_count", Arc::new(Int64Array::from(vec![10, 20]))),
];
let batch = RecordBatch::try_from_iter(columns).unwrap();
let mut w = parquet::arrow::ArrowWriter::try_new(
std::fs::File::create(&path).unwrap(),
batch.schema(),
None,
)
.unwrap();
w.write(&batch).unwrap();
w.close().unwrap();
let joined = read_join(path.to_str().unwrap()).unwrap();
std::fs::remove_file(&path).unwrap();
assert_eq!(joined.len(), 2);
let hexes = hexagons(&s, vec![bins], Some(&joined));
let h = hexes
.iter()
.find(|h| h.feature.full_values[0].s == cell.to_string())
.unwrap();
let get = |k: &str| {
h.feature
.full_keys
.iter()
.position(|x| x == k)
.map(|i| h.feature.full_values[i].s.clone())
};
assert_eq!(get("p90").as_deref(), Some("2.5"));
assert_eq!(get("n"), None);
assert_eq!(get("any").as_deref(), Some("false"));
assert_eq!(get("point_count").as_deref(), Some("20"));
}
#[test]
fn outlines_across_the_antimeridian_and_poles() {
let r = Resolution::try_from(1u8).unwrap();
let fiji = LatLng::new(-17.0, 179.9).unwrap().to_cell(r);
let dv = outline(fiji);
assert_eq!(dv.iter().filter(|d| d.op == VT_CLOSEPATH).count(), 2);
let pole = LatLng::new(90.0, 0.0).unwrap().to_cell(r);
let dv = outline(pole);
assert_eq!(dv.iter().filter(|d| d.op == VT_CLOSEPATH).count(), 1);
let ys: Vec<i64> = dv
.iter()
.filter(|d| d.op != VT_CLOSEPATH)
.map(|d| d.y)
.collect();
assert!(
(-1..=1).contains(ys.iter().min().unwrap()),
"{:?}",
ys.iter().min()
);
}
}