Skip to content

Commit 41f9fd6

Browse files
committed
Speed up CFGrid2D polygon generation
1 parent 888d378 commit 41f9fd6

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

src/emsarray/conventions/grid.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -526,6 +526,9 @@ def _get_or_make_bounds(self, coordinate: xarray.DataArray) -> xarray.DataArray:
526526
bound_by_nan = j_bound_by_nan | i_bound_by_nan
527527
coordinate_values[bound_by_nan] = numpy.nan
528528

529+
# grid is a (x+1, y+1) shape array built by averaging the cell centres.
530+
# Cells on the outside have been padded with `nan` neighbours.
531+
#
529532
# numpy.nanmean will return nan for an all-nan column.
530533
# This is the exact behaviour that we want.
531534
# numpy emits a warning that can not be silenced when this happens,
@@ -539,23 +542,21 @@ def _get_or_make_bounds(self, coordinate: xarray.DataArray) -> xarray.DataArray:
539542
], axis=0)
540543

541544
y_size, x_size = self.shape
542-
bounds = numpy.array([
543-
[
544-
[grid[y, x], grid[y, x + 1], grid[y + 1, x + 1], grid[y + 1, x]]
545-
for x in range(x_size)
546-
]
547-
for y in range(y_size)
548-
])
545+
bounds = numpy.stack([
546+
grid[:-1, :-1], grid[:-1, 1:], grid[1:, 1:], grid[1:, :-1],
547+
], axis=-1)
549548

550549
# Set nan bounds for all cells that have any `nan` in its bounds.
551550
cells_with_nans = numpy.isnan(bounds).any(axis=2)
552551
bounds[cells_with_nans] = numpy.nan
553552

554-
return xarray.DataArray(
553+
data_array = xarray.DataArray(
555554
bounds,
556555
dims=[self.y_dimension, self.x_dimension, 'bounds'],
557556
)
558557

558+
return data_array
559+
559560
@cached_property
560561
def longitude_bounds(self) -> xarray.DataArray:
561562
return self._get_or_make_bounds(self.longitude)

0 commit comments

Comments
 (0)