@@ -456,20 +456,32 @@ def wrapper(obj: DataArray | Dataset, key: str):
456
456
}
457
457
458
458
459
- def _guess_bounds_dim (da ):
459
+ def _guess_bounds_dim (da , dim = None ):
460
460
"""
461
461
Guess bounds values given a 1D coordinate variable.
462
462
Assumes equal spacing on either side of the coordinate label.
463
463
"""
464
- assert da .ndim == 1
464
+ if dim is None :
465
+ if da .ndim != 1 :
466
+ raise ValueError (
467
+ f"If dim is None, variable { da .name } must be 1D. Received { da .ndim } D variable instead."
468
+ )
469
+ (dim ,) = da .dims
470
+ if dim not in da .dims :
471
+ (dim ,) = da .cf .axes [dim ]
472
+ if dim not in da .coords :
473
+ raise NotImplementedError (
474
+ "Adding bounds for unindexed dimensions is not supported currently."
475
+ )
465
476
466
- dim = da .dims [0 ]
467
477
diff = da .diff (dim )
468
478
lower = da - diff / 2
469
479
upper = da + diff / 2
470
480
bounds = xr .concat ([lower , upper ], dim = "bounds" )
471
481
472
- first = (bounds .isel ({dim : 0 }) - diff [0 ]).assign_coords ({dim : da [dim ][0 ]})
482
+ first = (bounds .isel ({dim : 0 }) - diff .isel ({dim : 0 })).assign_coords (
483
+ {dim : da [dim ][0 ]}
484
+ )
473
485
result = xr .concat ([first , bounds ], dim = dim )
474
486
475
487
return result
@@ -2144,7 +2156,7 @@ def get_bounds_dim_name(self, key: str) -> str:
2144
2156
assert self ._obj .sizes [bounds_dim ] in [2 , 4 ]
2145
2157
return bounds_dim
2146
2158
2147
- def add_bounds (self , keys : str | Iterable [str ]):
2159
+ def add_bounds (self , keys : str | Iterable [str ], * , dim = None ):
2148
2160
"""
2149
2161
Returns a new object with bounds variables. The bounds values are guessed assuming
2150
2162
equal spacing on either side of a coordinate label.
@@ -2153,6 +2165,9 @@ def add_bounds(self, keys: str | Iterable[str]):
2153
2165
----------
2154
2166
keys : str or Iterable[str]
2155
2167
Either a single variable name or a list of variable names.
2168
+ dim : str, optional
2169
+ Core dimension along whch to estimate bounds. If None, ``keys``
2170
+ must refer to 1D variables only.
2156
2171
2157
2172
Returns
2158
2173
-------
@@ -2198,7 +2213,9 @@ def add_bounds(self, keys: str | Iterable[str]):
2198
2213
bname = f"{ var } _bounds"
2199
2214
if bname in obj .variables :
2200
2215
raise ValueError (f"Bounds variable name { bname !r} will conflict!" )
2201
- obj .coords [bname ] = _guess_bounds_dim (obj [var ].reset_coords (drop = True ))
2216
+ obj .coords [bname ] = _guess_bounds_dim (
2217
+ obj [var ].reset_coords (drop = True ), dim = dim
2218
+ )
2202
2219
obj [var ].attrs ["bounds" ] = bname
2203
2220
2204
2221
return self ._maybe_to_dataarray (obj )
0 commit comments