n3gb-rs 0.2.2

A Rust implementation of a hierarchical hex-based spatial indexing system based on the OSGB National Grid.
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
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
use crate::cell::HexCell;
use crate::coord::{
    ConversionMethod, Coordinate, convert_multipolygon_to_bng, convert_polygon_to_bng,
    convert_to_bng,
};
use crate::error::N3gbError;
use crate::index::{GRID_EXTENTS, generate_hex_identifier, point_to_row_col, row_col_to_center};
use crate::io::arrow::HexCellsToArrow;
use crate::io::parquet::HexCellsToGeoParquet;
use arrow_array::RecordBatch;
use geo::{BoundingRect, Intersects};
use geo_types::{MultiPolygon, Point, Polygon, Rect};
use geoarrow_array::array::{PointArray, PolygonArray};
use rayon::prelude::*;
use std::collections::HashMap;
use std::path::Path;

/// A collection of hexagonal cells covering a geographic extent.
///
/// `HexGrid` generates and manages multiple [`HexCell`]s for a given bounding box
/// and zoom level.
///
/// Use it when you need to work with multiple cells at once,
/// such as tiling an area prior to performing spatial queries.
///
/// # Example
///
/// ```
/// use n3gb_rs::HexGrid;
/// use geo_types::point;
///
/// # fn main() -> Result<(), n3gb_rs::N3gbError> {
/// // Create a grid covering an area
/// let grid = HexGrid::builder()
///     .zoom_level(10)
///     .bng_extent(&(457000.0, 339500.0), &(458000.0, 340500.0))
///     .build()?;
///
/// println!("Grid contains {} cells", grid.len());
///
/// // Find which cell contains a point
/// let pt = point! { x: 457500.0, y: 340000.0 };
/// if let Some(cell) = grid.get_cell_at(&pt) {
///     println!("Point is in cell: {}", cell.id);
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct HexGrid {
    cells: Vec<HexCell>,
    index: HashMap<(i64, i64), usize>,
    zoom_level: u8,
}

impl HexGrid {
    /// Build a `HexGrid` from a vec of cells, constructing the spatial index.
    fn new(cells: Vec<HexCell>, zoom_level: u8) -> Self {
        let index = cells
            .iter()
            .enumerate()
            .map(|(i, cell)| ((cell.row, cell.col), i))
            .collect();
        Self {
            cells,
            index,
            zoom_level,
        }
    }

    /// Creates a new [`HexGridBuilder`] for grid construction.
    ///
    /// # Returns
    ///
    /// A fresh [`HexGridBuilder`] with no parameters set.
    pub fn builder() -> HexGridBuilder {
        HexGridBuilder::new()
    }

    /// Build a grid from a bounding box extent.
    fn from_extent(
        min_x: f64,
        min_y: f64,
        max_x: f64,
        max_y: f64,
        zoom_level: u8,
    ) -> Result<Self, N3gbError> {
        let cells = generate_cells_for_extent(min_x, min_y, max_x, max_y, zoom_level)?;
        Ok(Self::new(cells, zoom_level))
    }

    /// Creates a HexGrid from a `geo_types::Rect` in BNG coordinates.
    ///
    /// # Arguments
    ///
    /// * `rect` - The bounding rectangle, in BNG (EPSG:27700) coordinates.
    /// * `zoom_level` - The zoom level for the generated cells.
    ///
    /// # Returns
    ///
    /// A `HexGrid` covering the rectangle's extent.
    ///
    /// # Errors
    ///
    /// Returns [`N3gbError::InvalidZoomLevel`] if `zoom_level` exceeds the
    /// maximum supported zoom level.
    pub fn from_rect(rect: &Rect<f64>, zoom_level: u8) -> Result<Self, N3gbError> {
        Self::from_extent(
            rect.min().x,
            rect.min().y,
            rect.max().x,
            rect.max().y,
            zoom_level,
        )
    }

    /// Create a HexGrid from British National Grid coordinates
    ///
    /// # Example
    /// ```
    /// use n3gb_rs::HexGrid;
    /// use geo_types::Point;
    ///
    /// # fn main() -> Result<(), n3gb_rs::N3gbError> {
    /// // From tuples
    /// let grid = HexGrid::from_bng_extent(&(457000.0, 339500.0), &(458000.0, 340500.0), 10)?;
    /// // From Points
    /// let grid = HexGrid::from_bng_extent(
    ///     &Point::new(457000.0, 339500.0),
    ///     &Point::new(458000.0, 340500.0),
    ///     10
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Arguments
    ///
    /// * `min` - The minimum (lower-left) corner, in BNG (EPSG:27700) coordinates.
    /// * `max` - The maximum (upper-right) corner, in BNG (EPSG:27700) coordinates.
    /// * `zoom_level` - The zoom level for the generated cells.
    ///
    /// # Returns
    ///
    /// A `HexGrid` covering the given extent.
    ///
    /// # Errors
    ///
    /// Returns [`N3gbError::InvalidZoomLevel`] if `zoom_level` exceeds the
    /// maximum supported zoom level.
    pub fn from_bng_extent(
        min: &impl Coordinate,
        max: &impl Coordinate,
        zoom_level: u8,
    ) -> Result<Self, N3gbError> {
        Self::from_extent(min.x(), min.y(), max.x(), max.y(), zoom_level)
    }

    /// Create a HexGrid from WGS84 (lon/lat) coordinates
    ///
    /// # Example
    /// ```
    /// use n3gb_rs::HexGrid;
    /// use geo_types::Point;
    ///
    /// # fn main() -> Result<(), n3gb_rs::N3gbError> {
    /// // From tuples (lon, lat)
    /// let grid = HexGrid::from_wgs84_extent(&(-2.3, 53.4), &(-2.2, 53.5), 10, n3gb_rs::ConversionMethod::Proj)?;
    /// // From Points
    /// let grid = HexGrid::from_wgs84_extent(
    ///     &Point::new(-2.3, 53.4),
    ///     &Point::new(-2.2, 53.5),
    ///     10,
    ///     n3gb_rs::ConversionMethod::Proj,
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Arguments
    ///
    /// * `min` - The minimum (lower-left) corner, in WGS84 (lon/lat) coordinates.
    /// * `max` - The maximum (upper-right) corner, in WGS84 (lon/lat) coordinates.
    /// * `zoom_level` - The zoom level for the generated cells.
    /// * `method` - The conversion backend used to project from WGS84 to BNG.
    ///
    /// # Returns
    ///
    /// A `HexGrid` covering the given extent.
    ///
    /// # Errors
    ///
    /// Returns [`N3gbError::ProjectionError`] if projecting the corners from
    /// WGS84 to BNG fails, or [`N3gbError::InvalidZoomLevel`] if `zoom_level`
    /// exceeds the maximum supported zoom level.
    pub fn from_wgs84_extent(
        min: &impl Coordinate,
        max: &impl Coordinate,
        zoom_level: u8,
        method: ConversionMethod,
    ) -> Result<Self, N3gbError> {
        let min_bng = convert_to_bng(min, method)?;
        let max_bng = convert_to_bng(max, method)?;
        Self::from_extent(
            min_bng.x(),
            min_bng.y(),
            max_bng.x(),
            max_bng.y(),
            zoom_level,
        )
    }

    /// Creates a HexGrid from a polygon in BNG coordinates.
    ///
    /// Generates hex cells for the polygon's bounding box, then filters
    /// to only include cells whose hexagon intersects the polygon.
    ///
    /// # Example
    /// ```
    /// use n3gb_rs::HexGrid;
    /// use geo_types::{Polygon, LineString, coord};
    ///
    /// # fn main() -> Result<(), n3gb_rs::N3gbError> {
    /// let polygon = Polygon::new(
    ///     LineString::from(vec![
    ///         coord! { x: 457000.0, y: 339500.0 },
    ///         coord! { x: 458000.0, y: 339500.0 },
    ///         coord! { x: 458000.0, y: 340500.0 },
    ///         coord! { x: 457000.0, y: 340500.0 },
    ///         coord! { x: 457000.0, y: 339500.0 },
    ///     ]),
    ///     vec![],
    /// );
    /// let grid = HexGrid::from_bng_polygon(&polygon, 10)?;
    /// assert!(!grid.is_empty());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Arguments
    ///
    /// * `polygon` - The polygon, in BNG (EPSG:27700) coordinates.
    /// * `zoom_level` - The zoom level for the generated cells.
    ///
    /// # Returns
    ///
    /// A `HexGrid` containing only the cells whose hexagon intersects the
    /// polygon. Empty if the polygon has no bounding rectangle.
    ///
    /// # Errors
    ///
    /// Returns [`N3gbError::InvalidZoomLevel`] if `zoom_level` exceeds the
    /// maximum supported zoom level.
    pub fn from_bng_polygon(polygon: &Polygon<f64>, zoom_level: u8) -> Result<Self, N3gbError> {
        let bbox = match polygon.bounding_rect() {
            Some(rect) => rect,
            None => return Ok(Self::new(Vec::new(), zoom_level)),
        };

        Ok(Self::from_rect(&bbox, zoom_level)?
            .retain(|cell| polygon.intersects(&cell.to_polygon())))
    }

    /// Creates a HexGrid from a polygon in WGS84 (lon/lat) coordinates.
    ///
    /// Projects the polygon to BNG, then generates hex cells for the
    /// polygon's bounding box and filters to cells that intersect.
    ///
    /// # Example
    /// ```
    /// use n3gb_rs::HexGrid;
    /// use geo_types::{Polygon, LineString, coord};
    ///
    /// # fn main() -> Result<(), n3gb_rs::N3gbError> {
    /// let polygon = Polygon::new(
    ///     LineString::from(vec![
    ///         coord! { x: -2.3, y: 53.4 },
    ///         coord! { x: -2.2, y: 53.4 },
    ///         coord! { x: -2.2, y: 53.5 },
    ///         coord! { x: -2.3, y: 53.5 },
    ///         coord! { x: -2.3, y: 53.4 },
    ///     ]),
    ///     vec![],
    /// );
    /// let grid = HexGrid::from_wgs84_polygon(&polygon, 10, n3gb_rs::ConversionMethod::Proj)?;
    /// assert!(!grid.is_empty());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Arguments
    ///
    /// * `polygon` - The polygon, in WGS84 (lon/lat) coordinates.
    /// * `zoom_level` - The zoom level for the generated cells.
    /// * `method` - The conversion backend used to project from WGS84 to BNG.
    ///
    /// # Returns
    ///
    /// A `HexGrid` containing only the cells whose hexagon intersects the
    /// projected polygon.
    ///
    /// # Errors
    ///
    /// Returns [`N3gbError::ProjectionError`] if projecting the polygon from
    /// WGS84 to BNG fails, or [`N3gbError::InvalidZoomLevel`] if `zoom_level`
    /// exceeds the maximum supported zoom level.
    pub fn from_wgs84_polygon(
        polygon: &Polygon<f64>,
        zoom_level: u8,
        method: ConversionMethod,
    ) -> Result<Self, N3gbError> {
        let bng_polygon = convert_polygon_to_bng(polygon, method)?;
        Self::from_bng_polygon(&bng_polygon, zoom_level)
    }

    /// Creates a HexGrid from a multipolygon in BNG coordinates.
    ///
    /// Generates hex cells for each polygon in the multipolygon and
    /// combines them, deduplicating overlapping cells.
    ///
    /// # Example
    /// ```
    /// use n3gb_rs::HexGrid;
    /// use geo_types::{MultiPolygon, Polygon, LineString, coord};
    ///
    /// # fn main() -> Result<(), n3gb_rs::N3gbError> {
    /// let poly1 = Polygon::new(
    ///     LineString::from(vec![
    ///         coord! { x: 457000.0, y: 339500.0 },
    ///         coord! { x: 457500.0, y: 339500.0 },
    ///         coord! { x: 457500.0, y: 340000.0 },
    ///         coord! { x: 457000.0, y: 340000.0 },
    ///         coord! { x: 457000.0, y: 339500.0 },
    ///     ]),
    ///     vec![],
    /// );
    /// let poly2 = Polygon::new(
    ///     LineString::from(vec![
    ///         coord! { x: 457500.0, y: 340000.0 },
    ///         coord! { x: 458000.0, y: 340000.0 },
    ///         coord! { x: 458000.0, y: 340500.0 },
    ///         coord! { x: 457500.0, y: 340500.0 },
    ///         coord! { x: 457500.0, y: 340000.0 },
    ///     ]),
    ///     vec![],
    /// );
    /// let mp = MultiPolygon::new(vec![poly1, poly2]);
    /// let grid = HexGrid::from_bng_multipolygon(&mp, 10)?;
    /// assert!(!grid.is_empty());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Arguments
    ///
    /// * `multipolygon` - The multipolygon, in BNG (EPSG:27700) coordinates.
    /// * `zoom_level` - The zoom level for the generated cells.
    ///
    /// # Returns
    ///
    /// A `HexGrid` containing only the cells whose hexagon intersects any
    /// polygon, with duplicates removed. Empty if the multipolygon has no
    /// bounding rectangle.
    ///
    /// # Errors
    ///
    /// Returns [`N3gbError::InvalidZoomLevel`] if `zoom_level` exceeds the
    /// maximum supported zoom level.
    pub fn from_bng_multipolygon(
        multipolygon: &MultiPolygon<f64>,
        zoom_level: u8,
    ) -> Result<Self, N3gbError> {
        let bbox = match multipolygon.bounding_rect() {
            Some(rect) => rect,
            None => return Ok(Self::new(Vec::new(), zoom_level)),
        };

        Ok(Self::from_rect(&bbox, zoom_level)?
            .retain(|cell| multipolygon.intersects(&cell.to_polygon())))
    }

    /// Creates a HexGrid from a multipolygon in WGS84 (lon/lat) coordinates.
    ///
    /// Projects the multipolygon to BNG, then generates hex cells for each
    /// polygon and combines them, deduplicating overlapping cells.
    ///
    /// # Example
    /// ```
    /// use n3gb_rs::HexGrid;
    /// use geo_types::{MultiPolygon, Polygon, LineString, coord};
    ///
    /// # fn main() -> Result<(), n3gb_rs::N3gbError> {
    /// let poly1 = Polygon::new(
    ///     LineString::from(vec![
    ///         coord! { x: -2.3, y: 53.4 },
    ///         coord! { x: -2.25, y: 53.4 },
    ///         coord! { x: -2.25, y: 53.45 },
    ///         coord! { x: -2.3, y: 53.45 },
    ///         coord! { x: -2.3, y: 53.4 },
    ///     ]),
    ///     vec![],
    /// );
    /// let poly2 = Polygon::new(
    ///     LineString::from(vec![
    ///         coord! { x: -2.25, y: 53.45 },
    ///         coord! { x: -2.2, y: 53.45 },
    ///         coord! { x: -2.2, y: 53.5 },
    ///         coord! { x: -2.25, y: 53.5 },
    ///         coord! { x: -2.25, y: 53.45 },
    ///     ]),
    ///     vec![],
    /// );
    /// let mp = MultiPolygon::new(vec![poly1, poly2]);
    /// let grid = HexGrid::from_wgs84_multipolygon(&mp, 10, n3gb_rs::ConversionMethod::Proj)?;
    /// assert!(!grid.is_empty());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Arguments
    ///
    /// * `multipolygon` - The multipolygon, in WGS84 (lon/lat) coordinates.
    /// * `zoom_level` - The zoom level for the generated cells.
    /// * `method` - The conversion backend used to project from WGS84 to BNG.
    ///
    /// # Returns
    ///
    /// A `HexGrid` containing only the cells whose hexagon intersects any
    /// projected polygon, with duplicates removed.
    ///
    /// # Errors
    ///
    /// Returns [`N3gbError::ProjectionError`] if projecting the multipolygon
    /// from WGS84 to BNG fails, or [`N3gbError::InvalidZoomLevel`] if
    /// `zoom_level` exceeds the maximum supported zoom level.
    pub fn from_wgs84_multipolygon(
        multipolygon: &MultiPolygon<f64>,
        zoom_level: u8,
        method: ConversionMethod,
    ) -> Result<Self, N3gbError> {
        let bng_multipolygon = convert_multipolygon_to_bng(multipolygon, method)?;
        Self::from_bng_multipolygon(&bng_multipolygon, zoom_level)
    }

    /// Keeps only cells matching the predicate, rebuilding the spatial index.
    fn retain<F>(self, predicate: F) -> Self
    where
        F: Fn(&HexCell) -> bool + Sync,
    {
        let cells: Vec<HexCell> = self
            .cells
            .into_par_iter()
            .filter(|cell| predicate(cell))
            .collect();
        Self::new(cells, self.zoom_level)
    }

    /// Returns the zoom level of this grid.
    ///
    /// # Returns
    ///
    /// The zoom level shared by all cells in this grid.
    pub fn zoom_level(&self) -> u8 {
        self.zoom_level
    }

    /// Returns the number of cells in this grid.
    ///
    /// # Returns
    ///
    /// The count of cells in this grid.
    pub fn len(&self) -> usize {
        self.cells.len()
    }

    /// Returns `true` if the grid contains no cells.
    ///
    /// # Returns
    ///
    /// `true` if the grid contains no cells, `false` otherwise.
    pub fn is_empty(&self) -> bool {
        self.cells.is_empty()
    }

    /// Returns a slice of all cells in this grid.
    ///
    /// # Returns
    ///
    /// A slice borrowing all cells in this grid.
    pub fn cells(&self) -> &[HexCell] {
        &self.cells
    }

    /// Returns an iterator over the cells in this grid.
    ///
    /// # Returns
    ///
    /// An iterator yielding a reference to each cell in this grid.
    pub fn iter(&self) -> impl Iterator<Item = &HexCell> {
        self.cells.iter()
    }

    /// Looks up which hex cell a point falls in.
    ///
    /// Converts the point to a grid `(row, col)` address, then uses the
    /// spatial index to find the cell at that address in O(1) time.
    ///
    /// Returns `Some(&HexCell)` if found, or `None` if the point falls
    /// outside this grid's extent.
    ///
    /// # Arguments
    ///
    /// * `point` - The point to locate, in BNG (EPSG:27700) coordinates.
    ///
    /// # Returns
    ///
    /// `Some(&HexCell)` containing the point, or `None` if no cell in this
    /// grid contains it.
    pub fn get_cell_at(&self, point: &Point<f64>) -> Option<&HexCell> {
        let (row, col) = point_to_row_col(point, self.zoom_level).ok()?;
        self.index.get(&(row, col)).map(|&i| &self.cells[i])
    }

    /// Converts all cells to hexagonal polygons.
    ///
    /// # Returns
    ///
    /// A vector containing the hexagonal polygon for each cell in this grid.
    pub fn to_polygons(&self) -> Vec<Polygon<f64>> {
        self.cells
            .par_iter()
            .map(|cell| cell.to_polygon())
            .collect()
    }

    /// Returns cells matching the given predicate.
    ///
    /// # Arguments
    ///
    /// * `predicate` - A closure called with each cell; cells for which it
    ///   returns `true` are included.
    ///
    /// # Returns
    ///
    /// A vector of references to the cells that satisfy the predicate.
    pub fn filter<F>(&self, predicate: F) -> Vec<&HexCell>
    where
        F: Fn(&HexCell) -> bool,
    {
        self.cells.iter().filter(|cell| predicate(cell)).collect()
    }

    /// Converts all cell centers to an Arrow PointArray.
    ///
    /// # Returns
    ///
    /// A [`PointArray`] containing the center point of each cell in this grid.
    pub fn to_arrow_points(&self) -> PointArray {
        self.cells.to_arrow_points()
    }

    /// Converts all cells to an Arrow PolygonArray.
    ///
    /// # Returns
    ///
    /// A [`PolygonArray`] containing the hexagonal polygon for each cell in
    /// this grid.
    pub fn to_arrow_polygons(&self) -> PolygonArray {
        self.cells.to_arrow_polygons()
    }

    /// Converts all cells to an Arrow RecordBatch with all attributes.
    ///
    /// # Returns
    ///
    /// A [`RecordBatch`] containing every cell's attributes.
    ///
    /// # Errors
    ///
    /// Returns [`N3gbError::IoError`] if the record batch cannot be
    /// constructed.
    pub fn to_record_batch(&self) -> Result<RecordBatch, N3gbError> {
        self.cells.to_record_batch()
    }

    /// Writes all cells to a GeoParquet file.
    ///
    /// # Arguments
    ///
    /// * `path` - The filesystem path to write the GeoParquet file to.
    ///
    /// # Returns
    ///
    /// `()` on success, once all cells have been written to the file.
    ///
    /// # Errors
    ///
    /// Returns [`N3gbError::IoError`] if the file cannot be written.
    pub fn to_geoparquet(&self, path: impl AsRef<Path>) -> Result<(), N3gbError> {
        self.cells.to_geoparquet(path)
    }
}

impl<'a> IntoIterator for &'a HexGrid {
    type Item = &'a HexCell;
    type IntoIter = std::slice::Iter<'a, HexCell>;

    fn into_iter(self) -> Self::IntoIter {
        self.cells.iter()
    }
}

impl IntoIterator for HexGrid {
    type Item = HexCell;
    type IntoIter = std::vec::IntoIter<HexCell>;

    fn into_iter(self) -> Self::IntoIter {
        self.cells.into_iter()
    }
}

/// Builder for constructing a [`HexGrid`].
///
/// Remeber that the builder struct is there to collect and normalise inputs (converting to BNG if needed)
/// then .build() passes the final object into the HexGrid constructors
/// this does the actual work — generating cells, filtering, building the HashMap index, etc.
///
/// It returns a result - either an error or the actual hex grid
///
/// # Example
///
/// ```
/// use n3gb_rs::HexGrid;
///
/// # fn main() -> Result<(), n3gb_rs::N3gbError> {
/// let grid = HexGrid::builder()
///     .zoom_level(10)
///     .bng_extent(&(457000.0, 339500.0), &(458000.0, 340500.0))
///     .build()?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Default, Clone)]
pub struct HexGridBuilder {
    zoom_level: Option<u8>,
    min_x: Option<f64>,
    min_y: Option<f64>,
    max_x: Option<f64>,
    max_y: Option<f64>,
    polygon: Option<Polygon<f64>>,
    multipolygon: Option<MultiPolygon<f64>>,
    conversion_method: ConversionMethod,
}

impl HexGridBuilder {
    /// Creates a new builder with no parameters set.
    ///
    /// # Returns
    ///
    /// A fresh `HexGridBuilder` with no parameters set.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the zoom level (0-15).
    ///
    /// # Arguments
    ///
    /// * `zoom_level` - The zoom level for the generated cells.
    ///
    /// # Returns
    ///
    /// The updated builder, for chaining.
    pub fn zoom_level(mut self, zoom_level: u8) -> Self {
        self.zoom_level = Some(zoom_level);
        self
    }

    /// Sets the WGS84→BNG conversion backend.
    ///
    /// Must be called before any `wgs84_*` input method.
    /// Defaults to [`ConversionMethod::Proj`].
    ///
    /// # Arguments
    ///
    /// * `method` - The conversion backend used to project from WGS84 to BNG.
    ///
    /// # Returns
    ///
    /// The updated builder, for chaining.
    pub fn conversion_method(mut self, method: ConversionMethod) -> Self {
        self.conversion_method = method;
        self
    }

    /// Sets the extent from a `geo_types::Rect` in BNG coordinates.
    ///
    /// # Arguments
    ///
    /// * `rect` - The bounding rectangle, in BNG (EPSG:27700) coordinates.
    ///
    /// # Returns
    ///
    /// The updated builder, for chaining.
    pub fn rect(mut self, rect: &Rect<f64>) -> Self {
        self.min_x = Some(rect.min().x);
        self.min_y = Some(rect.min().y);
        self.max_x = Some(rect.max().x);
        self.max_y = Some(rect.max().y);
        self
    }

    /// Set extent from British National Grid coordinates
    ///
    /// # Example
    /// ```
    /// use n3gb_rs::HexGrid;
    ///
    /// # fn main() -> Result<(), n3gb_rs::N3gbError> {
    /// let grid = HexGrid::builder()
    ///     .zoom_level(10)
    ///     .bng_extent(&(457000.0, 339500.0), &(458000.0, 340500.0))
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Arguments
    ///
    /// * `min` - The minimum (lower-left) corner, in BNG (EPSG:27700) coordinates.
    /// * `max` - The maximum (upper-right) corner, in BNG (EPSG:27700) coordinates.
    ///
    /// # Returns
    ///
    /// The updated builder, for chaining.
    pub fn bng_extent(mut self, min: &impl Coordinate, max: &impl Coordinate) -> Self {
        self.min_x = Some(min.x());
        self.min_y = Some(min.y());
        self.max_x = Some(max.x());
        self.max_y = Some(max.y());
        self
    }

    /// Set extent from WGS84 (lon/lat) coordinates
    ///
    /// # Example
    /// ```
    /// use n3gb_rs::HexGrid;
    ///
    /// # fn main() -> Result<(), n3gb_rs::N3gbError> {
    /// let grid = HexGrid::builder()
    ///     .zoom_level(10)
    ///     .wgs84_extent(&(-2.3, 53.4), &(-2.2, 53.5))?
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Arguments
    ///
    /// * `min` - The minimum (lower-left) corner, in WGS84 (lon/lat) coordinates.
    /// * `max` - The maximum (upper-right) corner, in WGS84 (lon/lat) coordinates.
    ///
    /// # Returns
    ///
    /// The updated builder, for chaining.
    ///
    /// # Errors
    ///
    /// Returns [`N3gbError::ProjectionError`] if projecting the corners from
    /// WGS84 to BNG fails.
    pub fn wgs84_extent(
        mut self,
        min: &impl Coordinate,
        max: &impl Coordinate,
    ) -> Result<Self, N3gbError> {
        let min_bng = convert_to_bng(min, self.conversion_method)?;
        let max_bng = convert_to_bng(max, self.conversion_method)?;
        self.min_x = Some(min_bng.x());
        self.min_y = Some(min_bng.y());
        self.max_x = Some(max_bng.x());
        self.max_y = Some(max_bng.y());
        Ok(self)
    }

    /// Sets the geometry from a polygon in BNG coordinates.
    ///
    /// When a polygon is set, the grid will only include cells that
    /// intersect the polygon, not the full bounding box.
    ///
    /// # Example
    /// ```
    /// use n3gb_rs::HexGrid;
    /// use geo_types::{Polygon, LineString, coord};
    ///
    /// # fn main() -> Result<(), n3gb_rs::N3gbError> {
    /// let polygon = Polygon::new(
    ///     LineString::from(vec![
    ///         coord! { x: 457000.0, y: 339500.0 },
    ///         coord! { x: 458000.0, y: 339500.0 },
    ///         coord! { x: 458000.0, y: 340500.0 },
    ///         coord! { x: 457000.0, y: 340500.0 },
    ///         coord! { x: 457000.0, y: 339500.0 },
    ///     ]),
    ///     vec![],
    /// );
    /// let grid = HexGrid::builder()
    ///     .zoom_level(10)
    ///     .bng_polygon(polygon)
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Arguments
    ///
    /// * `polygon` - The polygon, in BNG (EPSG:27700) coordinates.
    ///
    /// # Returns
    ///
    /// The updated builder, for chaining.
    pub fn bng_polygon(mut self, polygon: Polygon<f64>) -> Self {
        self.polygon = Some(polygon);
        self
    }

    /// Sets the geometry from a polygon in WGS84 (lon/lat) coordinates.
    ///
    /// Projects the polygon to BNG, then filters cells to those
    /// that intersect the polygon.
    ///
    /// # Example
    /// ```
    /// use n3gb_rs::HexGrid;
    /// use geo_types::{Polygon, LineString, coord};
    ///
    /// # fn main() -> Result<(), n3gb_rs::N3gbError> {
    /// let polygon = Polygon::new(
    ///     LineString::from(vec![
    ///         coord! { x: -2.3, y: 53.4 },
    ///         coord! { x: -2.2, y: 53.4 },
    ///         coord! { x: -2.2, y: 53.5 },
    ///         coord! { x: -2.3, y: 53.5 },
    ///         coord! { x: -2.3, y: 53.4 },
    ///     ]),
    ///     vec![],
    /// );
    /// let grid = HexGrid::builder()
    ///     .zoom_level(10)
    ///     .wgs84_polygon(polygon)?
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Arguments
    ///
    /// * `polygon` - The polygon, in WGS84 (lon/lat) coordinates.
    ///
    /// # Returns
    ///
    /// The updated builder, for chaining.
    ///
    /// # Errors
    ///
    /// Returns [`N3gbError::ProjectionError`] if projecting the polygon from
    /// WGS84 to BNG fails.
    pub fn wgs84_polygon(mut self, polygon: Polygon<f64>) -> Result<Self, N3gbError> {
        let bng_polygon = convert_polygon_to_bng(&polygon, self.conversion_method)?;
        self.polygon = Some(bng_polygon);
        Ok(self)
    }

    /// Sets the geometry from a multipolygon in BNG coordinates.
    ///
    /// When a multipolygon is set, the grid will only include cells that
    /// intersect any of the polygons, with duplicates removed.
    ///
    /// # Example
    /// ```
    /// use n3gb_rs::HexGrid;
    /// use geo_types::{MultiPolygon, Polygon, LineString, coord};
    ///
    /// # fn main() -> Result<(), n3gb_rs::N3gbError> {
    /// let poly1 = Polygon::new(
    ///     LineString::from(vec![
    ///         coord! { x: 457000.0, y: 339500.0 },
    ///         coord! { x: 457500.0, y: 339500.0 },
    ///         coord! { x: 457500.0, y: 340000.0 },
    ///         coord! { x: 457000.0, y: 340000.0 },
    ///         coord! { x: 457000.0, y: 339500.0 },
    ///     ]),
    ///     vec![],
    /// );
    /// let poly2 = Polygon::new(
    ///     LineString::from(vec![
    ///         coord! { x: 457500.0, y: 340000.0 },
    ///         coord! { x: 458000.0, y: 340000.0 },
    ///         coord! { x: 458000.0, y: 340500.0 },
    ///         coord! { x: 457500.0, y: 340500.0 },
    ///         coord! { x: 457500.0, y: 340000.0 },
    ///     ]),
    ///     vec![],
    /// );
    /// let mp = MultiPolygon::new(vec![poly1, poly2]);
    /// let grid = HexGrid::builder()
    ///     .zoom_level(10)
    ///     .bng_multipolygon(mp)
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Arguments
    ///
    /// * `multipolygon` - The multipolygon, in BNG (EPSG:27700) coordinates.
    ///
    /// # Returns
    ///
    /// The updated builder, for chaining.
    pub fn bng_multipolygon(mut self, multipolygon: MultiPolygon<f64>) -> Self {
        self.multipolygon = Some(multipolygon);
        self
    }

    /// Sets the geometry from a multipolygon in WGS84 (lon/lat) coordinates.
    ///
    /// Projects the multipolygon to BNG, then filters cells to those
    /// that intersect any of the polygons.
    ///
    /// # Example
    /// ```
    /// use n3gb_rs::HexGrid;
    /// use geo_types::{MultiPolygon, Polygon, LineString, coord};
    ///
    /// # fn main() -> Result<(), n3gb_rs::N3gbError> {
    /// let poly1 = Polygon::new(
    ///     LineString::from(vec![
    ///         coord! { x: -2.3, y: 53.4 },
    ///         coord! { x: -2.25, y: 53.4 },
    ///         coord! { x: -2.25, y: 53.45 },
    ///         coord! { x: -2.3, y: 53.45 },
    ///         coord! { x: -2.3, y: 53.4 },
    ///     ]),
    ///     vec![],
    /// );
    /// let poly2 = Polygon::new(
    ///     LineString::from(vec![
    ///         coord! { x: -2.25, y: 53.45 },
    ///         coord! { x: -2.2, y: 53.45 },
    ///         coord! { x: -2.2, y: 53.5 },
    ///         coord! { x: -2.25, y: 53.5 },
    ///         coord! { x: -2.25, y: 53.45 },
    ///     ]),
    ///     vec![],
    /// );
    /// let mp = MultiPolygon::new(vec![poly1, poly2]);
    /// let grid = HexGrid::builder()
    ///     .zoom_level(10)
    ///     .wgs84_multipolygon(mp)?
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Arguments
    ///
    /// * `multipolygon` - The multipolygon, in WGS84 (lon/lat) coordinates.
    ///
    /// # Returns
    ///
    /// The updated builder, for chaining.
    ///
    /// # Errors
    ///
    /// Returns [`N3gbError::ProjectionError`] if projecting the multipolygon
    /// from WGS84 to BNG fails.
    pub fn wgs84_multipolygon(
        mut self,
        multipolygon: MultiPolygon<f64>,
    ) -> Result<Self, N3gbError> {
        let bng_multipolygon = convert_multipolygon_to_bng(&multipolygon, self.conversion_method)?;
        self.multipolygon = Some(bng_multipolygon);
        Ok(self)
    }

    /// Builds the [`HexGrid`].
    ///
    /// # Returns
    ///
    /// The constructed [`HexGrid`], built from the multipolygon, polygon, or
    /// extent that was set on the builder.
    ///
    /// # Errors
    ///
    /// Returns [`N3gbError::InvalidZoomLevel`] if `zoom_level` exceeds the
    /// maximum supported zoom level, and propagates any error from the
    /// selected construction source.
    ///
    /// # Panics
    ///
    /// Panics if `zoom_level` has not been set, or if neither extent, polygon,
    /// nor multipolygon has been set.
    pub fn build(self) -> Result<HexGrid, N3gbError> {
        let zoom_level = self.zoom_level.expect("zoom_level must be set");

        match (self.multipolygon, self.polygon) {
            (Some(mp), _) => HexGrid::from_bng_multipolygon(&mp, zoom_level),
            (_, Some(p)) => HexGrid::from_bng_polygon(&p, zoom_level),
            (None, None) => {
                let min_x = self
                    .min_x
                    .expect("extent, polygon, or multipolygon must be set");
                let min_y = self
                    .min_y
                    .expect("extent, polygon, or multipolygon must be set");
                let max_x = self
                    .max_x
                    .expect("extent, polygon, or multipolygon must be set");
                let max_y = self
                    .max_y
                    .expect("extent, polygon, or multipolygon must be set");
                HexGrid::from_extent(min_x, min_y, max_x, max_y, zoom_level)
            }
        }
    }
}

/// Generates all hex cells that cover a bounding box.
///
/// This is the single entry point for all grid construction. Every public
/// constructor (`from_bng_extent`, `from_rect`, `from_bng_polygon`, etc.)
/// ultimately calls this function.
///
/// ## How it works
///
/// 1. Converts the four corners of the bounding box to grid `(row, col)` addresses.
/// 2. Takes the min/max of those to get the full row and column range.
/// 3. Iterates every `(row, col)` pair in that range (in parallel via Rayon).
/// 4. For each pair, computes the hex center point and generates a `HexCell`.
/// 5. Filters out any cells whose center falls outside the BNG grid extents.
///
/// ## Errors
///
/// Returns `Err(InvalidZoomLevel)` if `zoom_level` exceeds `MAX_ZOOM_LEVEL`.
fn generate_cells_for_extent(
    min_x: f64,
    min_y: f64,
    max_x: f64,
    max_y: f64,
    zoom_level: u8,
) -> Result<Vec<HexCell>, N3gbError> {
    let (ll_row, ll_col) = point_to_row_col(&(min_x, min_y), zoom_level)?;
    let (lr_row, lr_col) = point_to_row_col(&(max_x, min_y), zoom_level)?;
    let (ur_row, ur_col) = point_to_row_col(&(max_x, max_y), zoom_level)?;
    let (ul_row, ul_col) = point_to_row_col(&(min_x, max_y), zoom_level)?;

    let min_row = ll_row.min(lr_row).min(ur_row).min(ul_row);
    let max_row = ll_row.max(lr_row).max(ur_row).max(ul_row);
    let min_col = ll_col.min(lr_col).min(ur_col).min(ul_col);
    let max_col = ll_col.max(lr_col).max(ur_col).max(ul_col);

    let row_cols: Vec<(i64, i64)> = (min_row..=max_row)
        .flat_map(|row| (min_col..=max_col).map(move |col| (row, col)))
        .collect();

    let cells: Vec<HexCell> = row_cols
        .into_par_iter()
        .filter_map(|(row, col)| {
            let center = row_col_to_center(row, col, zoom_level).ok()?;

            if center.x() < GRID_EXTENTS[0] || center.y() < GRID_EXTENTS[1] {
                return None;
            }

            let id = generate_hex_identifier(center.x(), center.y(), zoom_level);
            Some(HexCell::new(id, center, zoom_level, row, col))
        })
        .collect();

    Ok(cells)
}

#[cfg(test)]
mod tests {
    use super::*;
    use geo_types::{coord, point};

    #[test]
    fn test_hex_grid_from_bng_extent() -> Result<(), N3gbError> {
        let grid = HexGrid::from_bng_extent(&(457000.0, 339500.0), &(458000.0, 340500.0), 10)?;
        assert!(!grid.is_empty());
        assert_eq!(grid.zoom_level(), 10);

        for cell in grid.iter() {
            assert_eq!(cell.zoom_level, 10);
        }
        Ok(())
    }

    #[test]
    fn test_hex_grid_from_rect() -> Result<(), N3gbError> {
        let rect = Rect::new(
            coord! { x: 457000.0, y: 339500.0 },
            coord! { x: 458000.0, y: 340500.0 },
        );
        let grid = HexGrid::from_rect(&rect, 10)?;
        assert!(!grid.is_empty());
        Ok(())
    }

    #[test]
    fn test_hex_grid_builder() -> Result<(), N3gbError> {
        let grid = HexGrid::builder()
            .zoom_level(10)
            .bng_extent(&(457000.0, 339500.0), &(458000.0, 340500.0))
            .build()?;

        assert!(!grid.is_empty());
        assert_eq!(grid.zoom_level(), 10);
        Ok(())
    }

    #[test]
    fn test_hex_grid_builder_with_rect() -> Result<(), N3gbError> {
        let rect = Rect::new(
            coord! { x: 457000.0, y: 339500.0 },
            coord! { x: 458000.0, y: 340500.0 },
        );
        let grid = HexGrid::builder().zoom_level(10).rect(&rect).build()?;

        assert!(!grid.is_empty());
        Ok(())
    }

    #[test]
    fn test_get_cell_at() -> Result<(), N3gbError> {
        let grid = HexGrid::from_bng_extent(&(457000.0, 339500.0), &(458000.0, 340500.0), 10)?;
        let pt = point! { x: 457500.0, y: 340000.0 };

        let cell = grid.get_cell_at(&pt);
        assert!(cell.is_some());
        Ok(())
    }

    #[test]
    fn test_filter_cells() -> Result<(), N3gbError> {
        let grid = HexGrid::from_bng_extent(&(457000.0, 339500.0), &(458000.0, 340500.0), 10)?;

        let filtered = grid.filter(|cell| cell.easting() > 457500.0);
        assert!(!filtered.is_empty());
        Ok(())
    }

    #[test]
    fn test_to_polygons() -> Result<(), N3gbError> {
        let grid = HexGrid::from_bng_extent(&(457000.0, 339500.0), &(458000.0, 340500.0), 10)?;
        let polygons = grid.to_polygons();

        assert_eq!(polygons.len(), grid.len());
        Ok(())
    }

    #[test]
    fn test_invalid_zoom_level() {
        let result = HexGrid::from_bng_extent(&(457000.0, 339500.0), &(458000.0, 340500.0), 20);
        assert!(matches!(result, Err(N3gbError::InvalidZoomLevel(20))));
    }
}