Skip to content

Commit 481272c

Browse files
committed
Update bounds_to_vertices to handle descending arrays
Add `_get_ordered_vertices()` to handle extraction of unique vertex values in ascending order
1 parent 3829d0c commit 481272c

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

cf_xarray/helpers.py

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,11 +211,49 @@ def _bounds_helper(values, n_core_dims, nbounds, order):
211211
vertex_vals = np.block([[bot_left, bot_right], [top_left, top_right]])
212212
elif n_core_dims == 1 and nbounds == 2:
213213
# Middle points case (1D lat/lon)
214-
vertex_vals = np.concatenate((values[..., :, 0], values[..., -1:, 1]), axis=-1)
214+
vertex_vals = _get_ordered_vertices(values)
215215

216216
return vertex_vals
217217

218218

219+
def _get_ordered_vertices(bounds: xr.DataArray) -> np.ndarray:
220+
"""Extracts the sorted unique vertices from a bounds DataArray.
221+
222+
This function flattens the bounds to pairs, finds all unique values, and
223+
returns them sorted. This ensures that the vertices are in ascending order,
224+
regardless of the original order in the bounds DataArray.
225+
226+
Parameters
227+
----------
228+
bounds : xr.DataArray
229+
A DataArray containing bounds information, typically with shape (..., 2),
230+
where the last dimension represents the lower and upper bounds for each
231+
interval.
232+
233+
Returns
234+
-------
235+
np.ndarray
236+
A 1D NumPy array of sorted unique vertex values extracted from the
237+
bounds.
238+
239+
Examples
240+
--------
241+
>>> import numpy as np
242+
>>> import xarray as xr
243+
>>> bounds = xr.DataArray(np.array([[0, 1], [1, 2], [2, 3]]))
244+
>>> _get_ordered_vertices(bounds)
245+
array([0, 1, 2, 3])
246+
>>> # Unordered bounds (left is upper bound)
247+
>>> bounds = xr.DataArray(np.array([[1, 0], [2, 1], [3, 2]]))
248+
>>> _get_ordered_vertices(bounds)
249+
array([0, 1, 2, 3])
250+
"""
251+
flat = bounds.reshape(-1, 2)
252+
vertices = np.unique(flat)
253+
254+
return np.sort(vertices)
255+
256+
219257
def vertices_to_bounds(
220258
vertices: DataArray, out_dims: Sequence[str] = ("bounds", "x", "y")
221259
) -> DataArray:

0 commit comments

Comments
 (0)