manby 0.2.7

Builds vector tilesets from geographic features, like tippecanoe, several times faster
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
//! `--h3`: below a base zoom, each layer's points are binned into H3
//! hexagons, a resolution for each zoom as freestiler picks them unless
//! `--h3-resolutions` gives them, and the hexagons, with how many points each
//! holds and what `--accumulate-attribute` and `--h3-median` make of their
//! attributes, go in a layer of their own, `<layer>_h3`. The points show from
//! the base zoom, or with `--h3-no-points` not at all.
//!
//! The points are counted as they are read, into their cells of each
//! resolution, each chunk on its own. A point's cell is found at each
//! resolution, as freestiler finds it, since a coarse cell does not hold all
//! of the finer cells that it is the parent of. Once every input is read,
//! the chunks' cells are added up in the order of the chunks, and the
//! hexagons go in as one more chunk, so tippecanoe's tiling and dropping
//! work on them as on any polygons.

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;

/// The H3 resolution for a zoom, as freestiler maps them: hexagons a little
/// smaller than a tile's 256 pixels make them, and beyond zoom 14 seven
/// tenths of the zoom, rounded half to even as R rounds.
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,
    }
}

/// Category values kept by name; the rest count as `_other`.
const CATEGORIES: usize = 64;

/// What `--h3` needs, worked out from the options.
#[derive(Debug)]
pub struct Setup {
    /// The zoom from which the points show.
    pub base: i32,
    /// `--h3-no-points`: the points don't show.
    pub no_points: bool,
    /// `--h3-fade`: the zooms each resolution shows beyond its own.
    pub fade: i32,
    /// Each resolution's zooms: resolution, first zoom, last zoom.
    pub windows: Vec<(u8, i32, i32)>,
    /// The resolutions into which the points are counted.
    resolutions: Vec<Resolution>,
    /// The attributes to accumulate, and how.
    accumulate: Vec<(String, AttributeOp)>,
    /// `--h3-median`: the attributes whose median each hexagon has.
    median: Vec<String>,
    /// `--h3-categories`: the attribute whose values are counted.
    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)),
            }
        }
        // --h3-fade: each resolution shows beyond its own zooms, to fade
        // into the next
        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 {
    /// The resolutions, their zooms, `--h3-fade` and the zoom from which the
    /// points show, as JSON, for `manby serve`'s map:
    /// `{"windows":[[resolution,minzoom,maxzoom],...],"fade":1,"points":10}`.
    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()
            }
        )
    }
}

/// An attribute's points, added up as one of tippecanoe's accumulations.
#[derive(Clone, Debug, Default)]
struct Sum {
    /// The points that have the attribute.
    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,
            // strings of every point of a hexagon would be too long to keep
            AttributeOp::Concat | AttributeOp::Comma => return None,
        })
    }
}

/// The points of one cell.
#[derive(Clone, Debug, Default)]
struct Bin {
    count: u64,
    sums: Vec<Sum>,
    /// `--h3-median`: each attribute's values.
    values: Vec<Vec<f64>>,
    /// `--h3-categories`: the points of each value, and of none.
    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;
    }
}

/// The median of some values, the mean of the middle two of an even number
/// of them, as DuckDB's `MEDIAN` makes it.
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
    })
}

/// The points one chunk counted, by layer and cell.
#[derive(Debug, Default)]
pub struct Bins {
    layers: BTreeMap<String, HashMap<u64, Bin>>,
}

/// The number an attribute's value stands for, or None for one that isn't
/// a number.
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 {
    /// Counts the points of a feature, at world coordinates `points`, with
    /// its attributes.
    pub fn add(
        &mut self,
        setup: &Setup,
        layer: &str,
        points: impl Iterator<Item = (i64, i64)>,
        keys: &[Cow<'_, str>],
        values: &[SerialVal],
    ) {
        // what the feature adds to each of its points' cells
        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);
            }
        }
    }
}

/// `--h3-join`: attributes for cells, by cell and layer, or for any layer's
/// cell under the empty layer name.
pub type Joined = HashMap<(String, u64), Vec<(String, SerialVal)>>;

/// Reads a Parquet file of attributes for cells: an `h3` column of cells, as
/// text or numbers, an optional `layer` column, and the attributes. Numbers,
/// true and false, and text become attributes; nulls are left out.
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)
}

/// A hexagon, ready to serialize.
pub struct Hexagon {
    pub layer: String,
    pub feature: InFeature<'static>,
}

/// The world coordinates of a cell's outline, as a polygon: split where it
/// crosses the antimeridian, and around a pole filled to the edge of the
/// Web Mercator world.
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 {
        // the vertices around the pole, west to east, closed along the edge
        let edge = lat.signum() * 85.0511287798066;
        // what is beyond the edge of the Web Mercator world doesn't show
        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 {
        // across the antimeridian: once east of it, once west
        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" })
}

/// The hexagons of the bins of every chunk, added up in the order given,
/// with the attributes that `--h3-join` gives their cells.
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 {
        // the category values kept by name: the most common, by count and name
        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;
            }
        }
        // a value of "_other" is counted with the others
        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));
                    }
                    // the most common value, unless two or more are
                    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),
                    ]);
                }
                // --h3-join: the cell's attributes for this layer, or any,
                // over those of the same name
                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());

        // given resolutions, and a zoom of overlap each way
        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);

        // only hexagons, to the maximum zoom
        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)];
            // the last point has no kind
            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);
        // one hexagon at each of resolutions 1 and 2, for zooms 0-1 and 2-3
        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);

        // one row for any layer's cell, and one for this layer's, which wins
        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"));
        // over the hexagon's own
        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()
        );
    }
}