@@ -217,11 +217,13 @@ def _bounds_helper(values, n_core_dims, nbounds, order):
217217
218218
219219def _get_ordered_vertices (bounds : xr .DataArray ) -> np .ndarray :
220- """Extracts the sorted unique vertices from a bounds DataArray.
220+ """Extracts a sorted 1D array of unique vertex values from a bounds DataArray.
221221
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.
222+ This function takes a DataArray (or array-like) containing bounds information,
223+ typically as pairs of values along the last dimension. It flattens the
224+ bounds into pairs, extracts all unique vertex values, and returns them in
225+ sorted order. The sorting order (ascending or descending) is determined by
226+ inspecting the direction of the first non-equal bounds pair.
225227
226228 Parameters
227229 ----------
@@ -233,23 +235,28 @@ def _get_ordered_vertices(bounds: xr.DataArray) -> np.ndarray:
233235 np.ndarray
234236 A 1D NumPy array of sorted unique vertex values extracted from the
235237 bounds.
236-
237- Examples
238- --------
239- >>> import numpy as np
240- >>> import xarray as xr
241- >>> bounds = xr.DataArray(np.array([[0, 1], [1, 2], [2, 3]]))
242- >>> _get_ordered_vertices(bounds)
243- array([0, 1, 2, 3])
244- >>> # Unordered bounds (left is upper bound)
245- >>> bounds = xr.DataArray(np.array([[1, 0], [2, 1], [3, 2]]))
246- >>> _get_ordered_vertices(bounds)
247- array([0, 1, 2, 3])
248238 """
249- flat = bounds .reshape (- 1 , 2 )
250- vertices = np .unique (flat )
251-
252- return np .sort (vertices )
239+ # Convert to array if needed
240+ arr = bounds .values if isinstance (bounds , xr .DataArray ) else bounds
241+ arr = np .asarray (arr )
242+
243+ # Flatten to (N, 2) pairs and get all unique values.
244+ pairs = arr .reshape (- 1 , 2 )
245+ vertices = np .unique (pairs )
246+
247+ # Determine order: find the first pair with different values
248+ ascending = True
249+ for left , right in pairs :
250+ if left != right :
251+ ascending = right > left
252+ break
253+
254+ # Sort vertices in ascending or descending order as needed.
255+ vertices = np .sort (vertices )
256+ if not ascending :
257+ vertices = vertices [::- 1 ]
258+
259+ return vertices
253260
254261
255262def vertices_to_bounds (
0 commit comments