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
use crate::coord::{ConversionMethod, Coordinate, Crs, convert_line_to_bng, convert_to_bng};
use crate::error::N3gbError;
use crate::geom::create_hexagon;
use crate::index::{
    CELL_RADIUS, decode_hex_identifier, generate_hex_identifier, offset_to_cube, point_to_row_col,
    row_col_to_center,
};
use crate::io::arrow::HexCellsToArrow;
use crate::io::parquet::HexCellsToGeoParquet;
use arrow_array::RecordBatch;
use geo::Centroid;
use geo_types::{Geometry, LineString, Point, Polygon};
use geoarrow_array::array::{PointArray, PolygonArray};
use std::collections::HashSet;
use std::path::Path;

/// A single hexagonal cell in the n3gb spatial indexing system.
///
/// Each `HexCell` represents one hexagon in the grid, with a unique identifier,
/// center point in British National Grid (BNG) coordinates, and grid position.
///
/// # Example
///
/// ```
/// use n3gb_rs::HexCell;
///
/// # fn main() -> Result<(), n3gb_rs::N3gbError> {
/// // Create from BNG coordinates
/// let cell = HexCell::from_bng(&(383640.0, 398260.0), 12)?;
/// println!("Cell ID: {}", cell.id);
/// println!("Center: ({}, {})", cell.easting(), cell.northing());
///
/// // Convert the cell to a polygon for GIS operations (like wanging it on a map)
/// let polygon = cell.to_polygon();
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct HexCell {
    /// Unique encoded identifier for this cell (Base64 URL-safe)
    pub id: String,
    /// Center point in British National Grid coordinates (EPSG:27700)
    pub center: Point<f64>,
    /// Zoom level (0-15), where higher values mean smaller cells
    pub zoom_level: u8,
    /// Row index in the hexagonal grid
    pub row: i64,
    /// Column index in the hexagonal grid
    pub col: i64,
}

impl HexCell {
    /// Constructs a `HexCell` directly from its component fields.
    ///
    /// # Arguments
    /// * `id` - The encoded hex identifier for the cell.
    /// * `center` - The cell center point in British National Grid coordinates.
    /// * `zoom_level` - The zoom level (0-15) of the cell.
    /// * `row` - The row index in the hexagonal grid.
    /// * `col` - The column index in the hexagonal grid.
    ///
    /// # Returns
    /// A new `HexCell` with the given field values.
    pub(crate) fn new(id: String, center: Point<f64>, zoom_level: u8, row: i64, col: i64) -> Self {
        Self {
            id,
            center,
            zoom_level,
            row,
            col,
        }
    }

    /// Create a HexCell from an encoded hex identifier
    ///
    /// # Arguments
    /// * `id` - The Base64 URL-safe encoded hex identifier to decode.
    ///
    /// # Returns
    /// The decoded `HexCell` corresponding to the identifier.
    ///
    /// # Errors
    /// Returns [`N3gbError::InvalidIdentifierLength`], [`N3gbError::InvalidChecksum`],
    /// [`N3gbError::Base64DecodeError`], or [`N3gbError::UnsupportedVersion`] if the
    /// identifier cannot be decoded, and [`N3gbError::InvalidZoomLevel`] if the decoded
    /// zoom level is out of range while re-indexing.
    ///
    /// # Example
    /// ```
    /// use n3gb_rs::HexCell;
    ///
    /// # fn main() -> Result<(), n3gb_rs::N3gbError> {
    /// let cell = HexCell::from_bng(&(383640.0, 398260.0), 12)?;
    /// let restored = HexCell::from_hex_id(&cell.id)?;
    /// assert_eq!(cell.id, restored.id);
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_hex_id(id: &str) -> Result<Self, N3gbError> {
        let (_, easting, northing, zoom) = decode_hex_identifier(id)?;
        let (row, col) = point_to_row_col(&(easting, northing), zoom)?;

        Ok(Self {
            id: id.to_string(),
            center: Point::new(easting, northing),
            zoom_level: zoom,
            row,
            col,
        })
    }

    /// Create HexCells from a LineString in BNG coordinates.
    ///
    /// Samples points along the line and returns all unique cells that intersect it.
    ///
    /// # Arguments
    /// * `line` - The line in British National Grid coordinates to sample.
    /// * `zoom` - The zoom level (0-15) at which to generate cells.
    ///
    /// # Returns
    /// A vector of unique `HexCell`s that the line passes through.
    ///
    /// # Errors
    /// Returns [`N3gbError::InvalidZoomLevel`] if `zoom` exceeds the maximum supported zoom level.
    pub fn from_line_string_bng(line: &LineString, zoom: u8) -> Result<Vec<Self>, N3gbError> {
        if zoom > crate::index::MAX_ZOOM_LEVEL {
            return Err(N3gbError::InvalidZoomLevel(zoom));
        }
        let cell_radius = CELL_RADIUS[zoom as usize];
        let step_size = cell_radius * 0.5;

        let total_length: f64 = line
            .0
            .windows(2)
            .map(|w| {
                let dx = w[1].x - w[0].x;
                let dy = w[1].y - w[0].y;
                (dx * dx + dy * dy).sqrt()
            })
            .sum();

        let estimated_cells = ((total_length / cell_radius) * 1.5) as usize + line.0.len();

        let mut seen: HashSet<(i64, i64)> = HashSet::with_capacity(estimated_cells);
        let mut cells: Vec<HexCell> = Vec::with_capacity(estimated_cells);

        for window in line.0.windows(2) {
            let start = &window[0];
            let end = &window[1];

            let dx = end.x - start.x;
            let dy = end.y - start.y;
            let segment_length = (dx * dx + dy * dy).sqrt();
            let steps = (segment_length / step_size).ceil() as usize;

            for i in 0..=steps {
                let t = if steps == 0 {
                    0.0
                } else {
                    i as f64 / steps as f64
                };
                let x = start.x + t * dx;
                let y = start.y + t * dy;

                let (row, col) = point_to_row_col(&(x, y), zoom)?;

                if seen.insert((row, col)) {
                    let center = row_col_to_center(row, col, zoom)?;
                    let id = generate_hex_identifier(center.x(), center.y(), zoom);
                    cells.push(HexCell::new(id, center, zoom, row, col));
                }
            }
        }

        Ok(cells)
    }

    /// Create HexCells along a LineString in WGS84 coordinates.
    ///
    /// Converts the line to BNG and returns all unique cells that intersect it.
    ///
    /// # Arguments
    /// * `line` - The line in WGS84 (lon/lat) coordinates to sample.
    /// * `zoom` - The zoom level (0-15) at which to generate cells.
    /// * `method` - The coordinate conversion method used to project WGS84 to BNG.
    ///
    /// # Returns
    /// A vector of unique `HexCell`s that the line passes through.
    ///
    /// # Errors
    /// Returns [`N3gbError::ProjectionError`] if converting the line to BNG fails, and
    /// [`N3gbError::InvalidZoomLevel`] if `zoom` exceeds the maximum supported zoom level.
    pub fn from_line_string_wgs84(
        line: &LineString,
        zoom: u8,
        method: ConversionMethod,
    ) -> Result<Vec<Self>, N3gbError> {
        let bng_line = convert_line_to_bng(line, method)?;
        Self::from_line_string_bng(&bng_line, zoom)
    }

    /// Create a HexCell from British National Grid coordinates
    ///
    /// # Arguments
    /// * `coord` - The BNG coordinate (tuple or `Point`) to index.
    /// * `zoom` - The zoom level (0-15) at which to generate the cell.
    ///
    /// # Returns
    /// The `HexCell` containing the given coordinate.
    ///
    /// # Errors
    /// Returns [`N3gbError::InvalidZoomLevel`] if `zoom` exceeds the maximum supported zoom level.
    ///
    /// # Example
    /// ```
    /// use n3gb_rs::HexCell;
    /// use geo_types::Point;
    ///
    /// # fn main() -> Result<(), n3gb_rs::N3gbError> {
    /// // From tuple
    /// let cell = HexCell::from_bng(&(383640.0, 398260.0), 12)?;
    /// // From Point
    /// let cell = HexCell::from_bng(&Point::new(383640.0, 398260.0), 12)?;
    /// println!("Cell ID: {}", cell.id);
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_bng(coord: &impl Coordinate, zoom: u8) -> Result<Self, N3gbError> {
        let (row, col) = point_to_row_col(coord, zoom)?;
        let center = row_col_to_center(row, col, zoom)?;
        let id = generate_hex_identifier(center.x(), center.y(), zoom);

        Ok(Self {
            id,
            center,
            zoom_level: zoom,
            row,
            col,
        })
    }

    /// Create a HexCell from WGS84 (lon/lat) coordinates
    ///
    /// # Arguments
    /// * `coord` - The WGS84 coordinate (tuple or `Point`) to index.
    /// * `zoom` - The zoom level (0-15) at which to generate the cell.
    /// * `method` - The coordinate conversion method used to project WGS84 to BNG.
    ///
    /// # Returns
    /// The `HexCell` containing the given coordinate.
    ///
    /// # Errors
    /// Returns [`N3gbError::ProjectionError`] if converting the coordinate to BNG fails, and
    /// [`N3gbError::InvalidZoomLevel`] if `zoom` exceeds the maximum supported zoom level.
    ///
    /// # Example
    /// ```
    /// use n3gb_rs::{HexCell, ConversionMethod};
    /// use geo_types::Point;
    ///
    /// # fn main() -> Result<(), n3gb_rs::N3gbError> {
    /// // From tuple
    /// let cell = HexCell::from_wgs84(&(-2.248, 53.481), 12, ConversionMethod::Proj)?;
    /// // From Point
    /// let cell = HexCell::from_wgs84(&Point::new(-2.248, 53.481), 12, ConversionMethod::Proj)?;
    /// println!("Cell ID: {}", cell.id);
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_wgs84(
        coord: &impl Coordinate,
        zoom: u8,
        method: ConversionMethod,
    ) -> Result<Self, N3gbError> {
        let bng = convert_to_bng(coord, method)?;
        Self::from_bng(&bng, zoom)
    }

    /// Create HexCells from an arbitrary `geo_types::Geometry`.
    ///
    /// Dispatches on geometry type and CRS to produce one or more cells.
    /// Points and polygon centroids produce a single cell; lines and
    /// collections may produce many.
    ///
    /// # Arguments
    /// * `geom` - The geometry to convert into one or more cells.
    /// * `zoom` - The zoom level (0-15) at which to generate cells.
    /// * `crs` - The coordinate reference system of the input geometry.
    /// * `method` - The coordinate conversion method used to project WGS84 to BNG.
    ///
    /// # Returns
    /// A vector of `HexCell`s derived from the geometry.
    ///
    /// # Errors
    /// Returns [`N3gbError::InvalidZoomLevel`] if `zoom` exceeds the maximum supported zoom level,
    /// [`N3gbError::ProjectionError`] if a WGS84 coordinate fails to project to BNG, and
    /// [`N3gbError::GeometryParseError`] if the geometry type is unsupported.
    pub fn from_geometry(
        geom: Geometry<f64>,
        zoom: u8,
        crs: Crs,
        method: ConversionMethod,
    ) -> Result<Vec<Self>, N3gbError> {
        match geom {
            Geometry::Point(pt) => {
                let cell = match crs {
                    Crs::Wgs84 => {
                        let bng = convert_to_bng(&pt, method)?;
                        Self::from_bng(&bng, zoom)?
                    }
                    Crs::Bng => Self::from_bng(&pt, zoom)?,
                };
                Ok(vec![cell])
            }
            Geometry::LineString(line) => match crs {
                Crs::Wgs84 => {
                    let bng_line = convert_line_to_bng(&line, method)?;
                    Self::from_line_string_bng(&bng_line, zoom)
                }
                Crs::Bng => Self::from_line_string_bng(&line, zoom),
            },
            Geometry::MultiLineString(mls) => {
                let mut all_cells = Vec::new();
                for line in mls.0 {
                    let cells = match crs {
                        Crs::Wgs84 => {
                            let bng_line = convert_line_to_bng(&line, method)?;
                            Self::from_line_string_bng(&bng_line, zoom)?
                        }
                        Crs::Bng => Self::from_line_string_bng(&line, zoom)?,
                    };
                    all_cells.extend(cells);
                }
                Ok(all_cells)
            }
            Geometry::Polygon(poly) => {
                if let Some(centroid) = poly.centroid() {
                    let cell = match crs {
                        Crs::Wgs84 => {
                            let bng = convert_to_bng(&centroid, method)?;
                            Self::from_bng(&bng, zoom)?
                        }
                        Crs::Bng => Self::from_bng(&centroid, zoom)?,
                    };
                    Ok(vec![cell])
                } else {
                    Ok(vec![])
                }
            }
            Geometry::MultiPolygon(mp) => {
                let mut cells = Vec::new();
                for poly in mp.0 {
                    if let Some(centroid) = poly.centroid() {
                        let cell = match crs {
                            Crs::Wgs84 => {
                                let bng = convert_to_bng(&centroid, method)?;
                                Self::from_bng(&bng, zoom)?
                            }
                            Crs::Bng => Self::from_bng(&centroid, zoom)?,
                        };
                        cells.push(cell);
                    }
                }
                Ok(cells)
            }
            Geometry::MultiPoint(mp) => {
                let mut cells = Vec::new();
                for pt in mp.0 {
                    let cell = match crs {
                        Crs::Wgs84 => {
                            let bng = convert_to_bng(&pt, method)?;
                            Self::from_bng(&bng, zoom)?
                        }
                        Crs::Bng => Self::from_bng(&pt, zoom)?,
                    };
                    cells.push(cell);
                }
                Ok(cells)
            }
            Geometry::GeometryCollection(gc) => {
                let mut all_cells = Vec::new();
                for g in gc.0 {
                    all_cells.extend(Self::from_geometry(g, zoom, crs, method)?);
                }
                Ok(all_cells)
            }
            _ => Err(N3gbError::GeometryParseError(
                "Unsupported geometry type".to_string(),
            )),
        }
    }

    /// Returns the grid distance (number of hex steps) between two cells.
    ///
    /// Both cells must be at the same zoom level.
    ///
    /// # Arguments
    /// * `other` - The other cell to measure the grid distance to.
    ///
    /// # Returns
    /// The number of hex steps between this cell and `other`.
    ///
    /// # Errors
    /// Returns [`N3gbError::ZoomLevelMismatch`] if the two cells are at different zoom levels.
    ///
    /// # Example
    ///
    /// ```
    /// use n3gb_rs::HexCell;
    ///
    /// # fn main() -> Result<(), n3gb_rs::N3gbError> {
    /// let a = HexCell::from_bng(&(383640.0, 398260.0), 10)?;
    /// let b = HexCell::from_bng(&(383640.0, 398260.0), 10)?;
    /// assert_eq!(a.grid_distance(&b)?, 0);
    /// # Ok(())
    /// # }
    /// ```
    pub fn grid_distance(&self, other: &Self) -> Result<u64, N3gbError> {
        if self.zoom_level != other.zoom_level {
            return Err(N3gbError::ZoomLevelMismatch(
                self.zoom_level,
                other.zoom_level,
            ));
        }
        let (q1, r1, s1) = offset_to_cube(self.row, self.col);
        let (q2, r2, s2) = offset_to_cube(other.row, other.col);
        let dist = ((q1 - q2).abs() + (r1 - r2).abs() + (s1 - s2).abs()) / 2;
        Ok(dist as u64)
    }

    /// Returns the easting (x-coordinate) of the cell center in meters.
    ///
    /// # Returns
    /// The easting (x-coordinate) of the cell center in meters.
    pub fn easting(&self) -> f64 {
        self.center.x()
    }

    /// Returns the northing (y-coordinate) of the cell center in meters.
    ///
    /// # Returns
    /// The northing (y-coordinate) of the cell center in meters.
    pub fn northing(&self) -> f64 {
        self.center.y()
    }

    /// Converts this cell to a hexagonal polygon.
    ///
    /// Returns a `geo_types::Polygon` representing the hexagon boundary,
    /// suitable for spatial operations or GeoJSON export.
    ///
    /// # Returns
    /// A `geo_types::Polygon` representing the hexagon boundary of this cell.
    pub fn to_polygon(&self) -> Polygon<f64> {
        create_hexagon(&self.center, CELL_RADIUS[self.zoom_level as usize])
    }

    /// Converts this cell's center to an Arrow PointArray.
    ///
    /// # Returns
    /// A `PointArray` containing this cell's center point.
    pub fn to_arrow_points(&self) -> PointArray {
        std::slice::from_ref(self).to_arrow_points()
    }

    /// Converts this cell to an Arrow PolygonArray.
    ///
    /// # Returns
    /// A `PolygonArray` containing this cell's hexagon polygon.
    pub fn to_arrow_polygons(&self) -> PolygonArray {
        std::slice::from_ref(self).to_arrow_polygons()
    }

    /// Converts this cell to an Arrow RecordBatch with all attributes.
    ///
    /// # Returns
    /// A `RecordBatch` containing this cell's attributes and geometry.
    ///
    /// # Errors
    /// Returns [`N3gbError::IoError`] if building the record batch fails.
    pub fn to_record_batch(&self) -> Result<RecordBatch, N3gbError> {
        std::slice::from_ref(self).to_record_batch()
    }

    /// Writes this cell to a GeoParquet file.
    ///
    /// # Arguments
    /// * `path` - The filesystem path to write the GeoParquet file to.
    ///
    /// # Returns
    /// `()` on success once the file has been written.
    ///
    /// # Errors
    /// Returns [`N3gbError::IoError`] if writing the GeoParquet file fails.
    pub fn to_geoparquet(&self, path: impl AsRef<Path>) -> Result<(), N3gbError> {
        std::slice::from_ref(self).to_geoparquet(path)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_grid_distance_same_cell() -> Result<(), N3gbError> {
        let cell = HexCell::from_bng(&(383640.0, 398260.0), 10)?;
        assert_eq!(cell.grid_distance(&cell)?, 0);
        Ok(())
    }

    #[test]
    fn test_grid_distance_adjacent() -> Result<(), N3gbError> {
        let a = HexCell::from_bng(&(383640.0, 398260.0), 10)?;
        let width = crate::index::CELL_WIDTHS[10];
        let b = HexCell::from_bng(&(a.easting() + width, a.northing()), 10)?;
        assert_eq!(a.grid_distance(&b)?, 1);
        Ok(())
    }

    #[test]
    fn test_grid_distance_zoom_mismatch() {
        let a = HexCell::from_bng(&(383640.0, 398260.0), 10).unwrap();
        let b = HexCell::from_bng(&(383640.0, 398260.0), 12).unwrap();
        assert!(matches!(
            a.grid_distance(&b),
            Err(N3gbError::ZoomLevelMismatch(10, 12))
        ));
    }

    #[test]
    fn test_from_bng_tuple() -> Result<(), N3gbError> {
        let cell = HexCell::from_bng(&(383640.0, 398260.0), 12)?;

        assert_eq!(cell.zoom_level, 12);
        assert!(!cell.id.is_empty());
        assert!(cell.row > 0);
        assert!(cell.col > 0);
        Ok(())
    }

    #[test]
    fn test_from_bng_point() -> Result<(), N3gbError> {
        let point = Point::new(383640.0, 398260.0);
        let cell = HexCell::from_bng(&point, 12)?;

        assert_eq!(cell.zoom_level, 12);
        assert!(!cell.id.is_empty());
        assert!(cell.row > 0);
        assert!(cell.col > 0);
        Ok(())
    }

    #[test]
    fn test_from_wgs84_tuple() -> Result<(), N3gbError> {
        let cell = HexCell::from_wgs84(&(-2.248, 53.481), 12, ConversionMethod::default())?;

        assert_eq!(cell.zoom_level, 12);
        assert!(!cell.id.is_empty());
        // Should be Manchester area
        assert!(cell.easting() > 380000.0 && cell.easting() < 390000.0);
        assert!(cell.northing() > 390000.0 && cell.northing() < 400000.0);
        Ok(())
    }

    #[test]
    fn test_from_wgs84_point() -> Result<(), N3gbError> {
        let point = Point::new(-2.248, 53.481);
        let cell = HexCell::from_wgs84(&point, 12, ConversionMethod::default())?;

        assert_eq!(cell.zoom_level, 12);
        assert!(!cell.id.is_empty());
        assert!(cell.easting() > 380000.0 && cell.easting() < 390000.0);
        assert!(cell.northing() > 390000.0 && cell.northing() < 400000.0);
        Ok(())
    }

    #[test]
    fn test_same_point_same_cell() -> Result<(), N3gbError> {
        // The same point should always return the same cell
        let cell1 = HexCell::from_bng(&(383640.0, 398260.0), 10)?;
        let cell2 = HexCell::from_bng(&(383640.0, 398260.0), 10)?;

        assert_eq!(cell1.id, cell2.id);
        assert_eq!(cell1.row, cell2.row);
        assert_eq!(cell1.col, cell2.col);

        // A point very close to center should be in the same cell
        let cell3 = HexCell::from_bng(&(cell1.easting() + 1.0, cell1.northing() + 1.0), 10)?;
        assert_eq!(cell1.id, cell3.id);
        Ok(())
    }

    #[test]
    fn test_tuple_and_point_same_result() -> Result<(), N3gbError> {
        let from_tuple = HexCell::from_bng(&(383640.0, 398260.0), 12)?;
        let from_point = HexCell::from_bng(&Point::new(383640.0, 398260.0), 12)?;

        assert_eq!(from_tuple.id, from_point.id);
        assert_eq!(from_tuple.row, from_point.row);
        assert_eq!(from_tuple.col, from_point.col);
        Ok(())
    }

    #[test]
    fn test_from_geometry_point_bng() -> Result<(), N3gbError> {
        let geom = Geometry::Point(Point::new(530000.0, 180000.0));
        let cells = HexCell::from_geometry(geom, 12, Crs::Bng, ConversionMethod::default())?;

        assert_eq!(cells.len(), 1);
        assert_eq!(cells[0].zoom_level, 12);
        assert!(!cells[0].id.is_empty());
        Ok(())
    }

    #[test]
    fn test_from_geometry_point_wgs84() -> Result<(), N3gbError> {
        let geom = Geometry::Point(Point::new(-0.1, 51.5));
        let cells = HexCell::from_geometry(geom, 12, Crs::Wgs84, ConversionMethod::default())?;

        assert_eq!(cells.len(), 1);
        assert_eq!(cells[0].zoom_level, 12);
        Ok(())
    }

    #[test]
    fn test_from_geometry_point_matches_from_bng() -> Result<(), N3gbError> {
        let coord = (530000.0, 180000.0);
        let direct = HexCell::from_bng(&coord, 12)?;
        let via_geom = HexCell::from_geometry(
            Geometry::Point(Point::new(coord.0, coord.1)),
            12,
            Crs::Bng,
            ConversionMethod::default(),
        )?;

        assert_eq!(via_geom.len(), 1);
        assert_eq!(via_geom[0].id, direct.id);
        Ok(())
    }

    #[test]
    fn test_from_geometry_linestring() -> Result<(), N3gbError> {
        let line = LineString::from(vec![(530000.0, 180000.0), (531000.0, 181000.0)]);
        let cells = HexCell::from_geometry(
            Geometry::LineString(line),
            12,
            Crs::Bng,
            ConversionMethod::default(),
        )?;

        assert!(!cells.is_empty());
        assert!(cells.len() > 1);
        for cell in &cells {
            assert_eq!(cell.zoom_level, 12);
        }
        Ok(())
    }

    #[test]
    fn test_from_geometry_polygon_uses_centroid() -> Result<(), N3gbError> {
        use geo_types::polygon;

        let poly = polygon![
            (x: 530000.0, y: 180000.0),
            (x: 531000.0, y: 180000.0),
            (x: 531000.0, y: 181000.0),
            (x: 530000.0, y: 181000.0),
            (x: 530000.0, y: 180000.0),
        ];
        let cells = HexCell::from_geometry(
            Geometry::Polygon(poly),
            12,
            Crs::Bng,
            ConversionMethod::default(),
        )?;

        assert_eq!(cells.len(), 1);
        // Centroid should be roughly at (530500, 180500)
        assert!((cells[0].easting() - 530500.0).abs() < 100.0);
        assert!((cells[0].northing() - 180500.0).abs() < 100.0);
        Ok(())
    }

    #[test]
    fn test_from_geometry_multipoint() -> Result<(), N3gbError> {
        use geo_types::MultiPoint;

        let mp = MultiPoint::new(vec![
            Point::new(530000.0, 180000.0),
            Point::new(540000.0, 190000.0),
        ]);
        let cells = HexCell::from_geometry(
            Geometry::MultiPoint(mp),
            12,
            Crs::Bng,
            ConversionMethod::default(),
        )?;

        assert_eq!(cells.len(), 2);
        Ok(())
    }

    #[test]
    fn test_from_geometry_multilinestring() -> Result<(), N3gbError> {
        use geo_types::MultiLineString;

        let mls = MultiLineString::new(vec![
            LineString::from(vec![(530000.0, 180000.0), (530500.0, 180500.0)]),
            LineString::from(vec![(540000.0, 190000.0), (540500.0, 190500.0)]),
        ]);
        let cells = HexCell::from_geometry(
            Geometry::MultiLineString(mls),
            12,
            Crs::Bng,
            ConversionMethod::default(),
        )?;

        assert!(cells.len() >= 2);
        Ok(())
    }

    #[test]
    fn test_from_geometry_multipolygon() -> Result<(), N3gbError> {
        use geo_types::{MultiPolygon, polygon};

        let mp = MultiPolygon::new(vec![
            polygon![
                (x: 530000.0, y: 180000.0),
                (x: 531000.0, y: 180000.0),
                (x: 531000.0, y: 181000.0),
                (x: 530000.0, y: 180000.0),
            ],
            polygon![
                (x: 540000.0, y: 190000.0),
                (x: 541000.0, y: 190000.0),
                (x: 541000.0, y: 191000.0),
                (x: 540000.0, y: 190000.0),
            ],
        ]);
        let cells = HexCell::from_geometry(
            Geometry::MultiPolygon(mp),
            12,
            Crs::Bng,
            ConversionMethod::default(),
        )?;

        assert_eq!(cells.len(), 2);
        Ok(())
    }

    #[test]
    fn test_from_geometry_collection() -> Result<(), N3gbError> {
        use geo_types::GeometryCollection;

        let gc = GeometryCollection::new_from(vec![
            Geometry::Point(Point::new(530000.0, 180000.0)),
            Geometry::Point(Point::new(540000.0, 190000.0)),
        ]);
        let cells = HexCell::from_geometry(
            Geometry::GeometryCollection(gc),
            12,
            Crs::Bng,
            ConversionMethod::default(),
        )?;

        assert_eq!(cells.len(), 2);
        Ok(())
    }

    #[test]
    fn test_wgs84_same_cell_both_methods() -> Result<(), N3gbError> {
        let coord = (-2.248, 53.481);
        let cell_proj = HexCell::from_wgs84(&coord, 10, ConversionMethod::Proj)?;
        let cell_ostn15 = HexCell::from_wgs84(&coord, 10, ConversionMethod::Ostn15)?;

        assert_eq!(cell_proj.id, cell_ostn15.id);
        Ok(())
    }
}