Skip to content

Commit f9ce4e6

Browse files
committed
Speed up geometry encoding
Closes #534
1 parent acc1eb0 commit f9ce4e6

File tree

2 files changed

+18
-16
lines changed

2 files changed

+18
-16
lines changed

cf_xarray/geometry.py

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -459,11 +459,8 @@ def shapely_to_cf(
459459
"and set the grid mapping variable as a coordinate",
460460
)
461461

462-
# Get all types to call the appropriate translation function.
463-
types = {
464-
geom.item().geom_type if isinstance(geom, xr.DataArray) else geom.geom_type
465-
for geom in geometries
466-
}
462+
as_data = geometries.data if isinstance(geometries, xr.DataArray) else geometries
463+
type_ = as_data[0].geom_type
467464

468465
grid_mapping_varname = None
469466
if (
@@ -482,16 +479,21 @@ def shapely_to_cf(
482479
suffix=suffix, grid_mapping_name=grid_mapping, grid_mapping=grid_mapping_varname
483480
)
484481

485-
if types.issubset({"Point", "MultiPoint"}):
486-
ds = points_to_cf(geometries, names=names)
487-
elif types.issubset({"LineString", "MultiLineString"}):
488-
ds = lines_to_cf(geometries, names=names)
489-
elif types.issubset({"Polygon", "MultiPolygon"}):
490-
ds = polygons_to_cf(geometries, names=names)
491-
else:
482+
try:
483+
if type_ in ["Point", "MultiPoint"]:
484+
ds = points_to_cf(geometries, names=names)
485+
elif type_ in ["LineString", "MultiLineString"]:
486+
ds = lines_to_cf(geometries, names=names)
487+
elif type_ in ["Polygon", "MultiPolygon"]:
488+
ds = polygons_to_cf(geometries, names=names)
489+
else:
490+
raise ValueError(
491+
f"This geometry type is not supported in CF-compliant datasets. Got {type_}"
492+
)
493+
except NotImplementedError as e:
492494
raise ValueError(
493-
f"Mixed geometry types are not supported in CF-compliant datasets. Got {types}"
494-
)
495+
"Error converting geometries. Possibly you have provided mixed geometry types."
496+
) from e
495497

496498
return ds
497499

@@ -841,7 +843,7 @@ def polygons_to_cf(
841843
node_count = part_node_count
842844
elif len(offsets) >= 2:
843845
indices = np.take(offsets[0], offsets[1])
844-
interior_ring = np.isin(offsets[0], indices, invert=True)[:-1].astype(int)
846+
interior_ring = np.isin(offsets[0], indices, invert=True)[:-1].view(np.int8)
845847

846848
if len(offsets) == 3:
847849
indices = np.take(indices, offsets[2])

cf_xarray/tests/test_geometry.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -352,7 +352,7 @@ def test_shapely_to_cf_errors():
352352
Polygon([[1, 1, 4], [1, 3, 4], [3, 3, 3], [1, 1, 4]]),
353353
Point(1, 2),
354354
]
355-
with pytest.raises(ValueError, match="Mixed geometry types are not supported"):
355+
with pytest.raises(ValueError, match="Geometry type combination"):
356356
cfxr.shapely_to_cf(geoms)
357357

358358
encoded = cfxr.shapely_to_cf(

0 commit comments

Comments
 (0)