Skip to content

Commit 2433a09

Browse files
authored
use geoarrow instead of shapely to construct polygons (#16)
1 parent d9cf203 commit 2433a09

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

python/grid_indexing/grids.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
from typing import Literal
22

33
import cf_xarray # noqa: F401
4+
import geoarrow.rust.core as geoarrow
45
import numpy as np
5-
import shapely
66
import xarray as xr
77
from numpy.typing import ArrayLike
88

@@ -13,6 +13,18 @@ def is_meshgrid(coord1: ArrayLike, coord2: ArrayLike):
1313
) or (np.all(coord1[:, 0] == coord1[:, 1]) and np.all(coord2[0, :] == coord2[1, :]))
1414

1515

16+
def as_components(boundaries):
17+
vertices = np.concatenate([boundaries, boundaries[..., :1, :]], axis=-2)
18+
19+
coords = np.reshape(vertices, (-1, 2))
20+
21+
coords_per_pixel = vertices.shape[-2]
22+
geom_offsets = np.arange(np.prod(vertices.shape[:-2]) + 1, dtype="int32")
23+
ring_offsets = geom_offsets * coords_per_pixel
24+
25+
return coords, geom_offsets, ring_offsets
26+
27+
1628
def infer_grid_type(ds: xr.Dataset):
1729
# grid types (all geographic):
1830
# - 2d crs (affine transform)
@@ -99,4 +111,4 @@ def infer_cell_geometries(
99111
bound_names = [with_bounds.cf.bounds[name][0] for name in coords]
100112
boundaries = np.stack([with_bounds.variables[n].data for n in bound_names], axis=-1)
101113

102-
return shapely.polygons(boundaries)
114+
return geoarrow.polygons(*as_components(boundaries), crs=4326)

python/tests/test_grids.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import geoarrow.rust.core as geoarrow
12
import numpy as np
23
import pytest
34
import shapely
@@ -186,4 +187,5 @@ def test_infer_geoms(self, grid_type):
186187

187188
actual = grids.infer_cell_geometries(ds, grid_type=grid_type)
188189

189-
shapely.testing.assert_geometries_equal(actual, expected)
190+
actual_geoms = np.reshape(geoarrow.to_shapely(actual), expected.shape)
191+
shapely.testing.assert_geometries_equal(actual_geoms, expected)

0 commit comments

Comments
 (0)