@@ -315,15 +315,22 @@ def grid_to_polygons(ds: xr.Dataset) -> xr.DataArray:
315
315
"""
316
316
import shapely
317
317
318
- grid = ds .cf [["latitude" , "longitude" ]].load ().reset_coords ()
319
- bounds = ds .cf .bounds
318
+ grid = ds .cf [["latitude" , "longitude" ]].load ()
319
+ bounds = grid .cf .bounds
320
+ dims = grid .cf .dims
321
+
322
+ if "latitude" in dims or "longitude" in dims :
323
+ # for 1D lat, lon, this allows them to be
324
+ # broadcast against each other
325
+ grid = grid .reset_coords ()
320
326
321
327
assert "latitude" in bounds
322
328
assert "longitude" in bounds
323
329
(lon_bounds ,) = bounds ["longitude" ]
324
330
(lat_bounds ,) = bounds ["latitude" ]
325
331
326
- (points ,) = xr .broadcast (grid )
332
+ with xr .set_options (keep_attrs = True ):
333
+ (points ,) = xr .broadcast (grid )
327
334
328
335
bounds_dim = grid .cf .get_bounds_dim_name ("latitude" )
329
336
points = points .transpose (..., bounds_dim )
@@ -337,14 +344,14 @@ def grid_to_polygons(ds: xr.Dataset) -> xr.DataArray:
337
344
lonbnd [mask , :] = lonbnd [mask , :] - 360
338
345
latbnd = latbnd [..., [0 , 1 , 1 , 0 ]]
339
346
340
- elif points .sizes [bounds_dim ] == 4 :
341
- raise NotImplementedError
342
- else :
347
+ elif points .sizes [bounds_dim ] != 4 :
343
348
raise ValueError (
344
349
f"The size of the detected bounds or vertex dimension { bounds_dim } is not 2 or 4."
345
350
)
346
351
347
352
polyarray = shapely .polygons (shapely .linearrings (lonbnd , latbnd ))
348
- boxes = points [lon_bounds ][..., 0 ].copy (data = polyarray )
353
+
354
+ # 'geometry' is a blessed name in geopandas.
355
+ boxes = points [lon_bounds ][..., 0 ].copy (data = polyarray ).rename ("geometry" )
349
356
350
357
return boxes
0 commit comments