Xarray
convert_ds_dtypes(ds, verbose=False)
Convert all float variables to float32 and all int variables to int32 in an xarray Dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ds
|
Dataset
|
Input xarray Dataset. |
required |
verbose
|
bool
|
Whether to print out variables converted |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
ds_out |
Dataset
|
Dataset with all float variables converted to float32 and all int variables to int32. |
Source code in isca_tools/utils/xarray.py
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | |
flatten_to_numpy(var, keep_dim=None)
Flattens var to a numpy array with at most 2 dimensions.
Examples:
If var has dims=(lat, lon, lev) and keep_dim=lev, it will return a numpy array of
size [n_lat*n_lon, n_lev].
If var has dims=(lat, lon) and keep_dim=None, it will return a numpy array of
size [n_lat*n_lon].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
var
|
DataArray
|
Variable to flatten. |
required |
keep_dim
|
Optional[str]
|
Dimension along which not to flatten. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
var_flatten |
ndarray
|
Numpy array with flattened dimension first, and |
Source code in isca_tools/utils/xarray.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | |
isel_float(var, ind_float, dim='lev')
Performs da.isel(dim=ind) but for a float index where interpolation is required.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
var
|
DataArray
|
Variable to find value of at index |
required |
ind_float
|
DataArray
|
Fractional index to find value of |
required |
dim
|
Dimension in which to perform |
'lev'
|
Returns:
| Type | Description |
|---|---|
DataArray
|
Value of |
Source code in isca_tools/utils/xarray.py
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 | |
periodic_rolling_mean(da, window, dim='dayofyear', *, center=True, min_periods=None)
Compute a rolling mean with periodic boundary conditions.
Pads the selected dimension using wrapped values before applying the rolling mean, then removes the padding. This allows windows near either boundary to include values from the opposite boundary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
Union[DataArray, Dataset]
|
Input DataArray or Dataset. |
required |
window
|
int
|
Number of points in the rolling window. For a centred rolling mean, an odd value is required. |
required |
dim
|
str
|
Dimension over which to calculate the rolling mean. |
'dayofyear'
|
center
|
bool
|
Whether to centre the rolling window on each coordinate. |
True
|
min_periods
|
Optional[int]
|
Minimum number of valid values required for each result.
Defaults to |
None
|
Returns:
| Type | Description |
|---|---|
Union[DataArray, Dataset]
|
DataArray or Dataset with the same size and coordinates as |
Union[DataArray, Dataset]
|
smoothed along |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ValueError
|
If |
Source code in isca_tools/utils/xarray.py
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 | |
print_ds_var_list(ds, phrase=None)
Prints all variables in ds which contain phrase in the variable name or variable long_name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ds
|
Dataset
|
Dataset to investigate variables of. |
required |
phrase
|
Optional[str]
|
Key phrase to search for in variable info. |
None
|
Source code in isca_tools/utils/xarray.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | |
raise_if_common_dims_not_identical(x, y, name_x='x', name_y='y')
Raise an error if the shared dimensions of two xarray objects differ in order.
This compares only the dimensions that appear in both x and y. It
extracts the subsequence of x.dims containing only shared dims and does
the same for y.dims, then checks the two subsequences are identical (same
dim names in the same order).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
An xarray object (DataArray or Dataset) with a |
required | |
y
|
An xarray object (DataArray or Dataset) with a |
required | |
name_x
|
Name to use for |
'x'
|
|
name_y
|
Name to use for |
'y'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the order (or names) of the dimensions shared by |
Example
If x.dims == ('time', 'lat', 'lon') and y.dims == ('lat', 'time'),
the shared dims are ('time', 'lat') for x and ('lat', 'time') for
y, so this function raises.
Source code in isca_tools/utils/xarray.py
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 | |
select_coord_window(ds, target, dim, n=1)
Select a clipped coordinate window around a target value.
Finds the coordinate value along dim nearest to target and selects
that grid cell plus up to n neighbouring cells on either side. The
selection is clipped at the dimension boundaries, so it may contain fewer
than 2 * n + 1 values near either endpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ds
|
Dataset
|
Dataset containing the coordinate and dimension. |
required |
target
|
float
|
Target coordinate value in the same units as
|
required |
dim
|
str
|
Name of the one-dimensional coordinate and dimension to
select along, for example |
required |
n
|
int
|
Number of neighbouring grid cells to retain on each side of the closest coordinate value. Defaults to 1. |
1
|
Returns:
| Type | Description |
|---|---|
|
xarray.Dataset: Dataset restricted to the selected coordinate window. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in isca_tools/utils/xarray.py
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 | |
set_attrs(var, overwrite=True, **kwargs)
Set attributes of a given variable.
Examples:
set_attrs(ds.plev, long_name='pressure', units='Pa')
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
var
|
DataArray
|
Variable to set attributes of. |
required |
overwrite
|
bool
|
If |
True
|
**kwargs
|
str
|
Attributes to set. Common ones include |
{}
|
Returns:
| Type | Description |
|---|---|
DataArray
|
|
Source code in isca_tools/utils/xarray.py
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | |
transpose_common_dims_like(y, x)
Reorder y so any dims shared with x follow x's dim order.
Dims that are not in x.dims are left in their original relative order and
appended after the reordered common dims.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
DataArray
|
Target xarray object (DataArray or Dataset) to reorder. |
required |
x
|
DataArray
|
Reference xarray object (DataArray or Dataset). Only |
required |
Returns:
| Type | Description |
|---|---|
DataArray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in isca_tools/utils/xarray.py
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 | |
unflatten_from_numpy(arr, var, keep_dim=None)
Reconstructs an xarray.DataArray from a flattened NumPy array created by flatten_to_numpy.
Examples:
If var had dims=(lat, lon, lev) and keep_dim='lev', and arr has shape (n_lat*n_lon, n_lev),
this will return a DataArray with dims (lat, lon, lev).
If var had dims=(lat, lon)andkeep_dim=None, andarr` has shape (n_lat*n_lon),
this will return a DataArray with dims (lat, lon).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
ndarray
|
Flattened NumPy array from |
required |
var
|
DataArray
|
The original DataArray used to determine dimension order, shape, and coordinates. |
required |
keep_dim
|
Optional[str]
|
Dimension that was kept unflattened in |
None
|
Returns:
| Type | Description |
|---|---|
DataArray
|
xr.DataArray: DataArray with the original dimensions and coordinates restored. |
Source code in isca_tools/utils/xarray.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | |
update_dim_slice(obj, dim, dim_val, var, var_name=None)
Update values at one coordinate along dim for a Dataset or DataArray.
If obj is a Dataset, updates obj[var_name] at dim=dim_val.
If obj is a DataArray, updates obj itself at dim=dim_val and ignores
var_name (unless you want to rename the returned DataArray).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Union[DataArray, Dataset]
|
xarray Dataset or DataArray to update. |
required |
dim
|
str
|
Dimension name to index (e.g. "fit_method"). |
required |
dim_val
|
Coordinate value along |
required | |
var
|
Union[DataArray, ndarray, float]
|
New values (DataArray/ndarray/scalar) broadcastable to the target slice. |
required |
var_name
|
Optional[str]
|
Variable name to update if |
None
|
Returns:
| Type | Description |
|---|---|
|
Updated object (same type as input). Note: this mutates data in place. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
Source code in isca_tools/utils/xarray.py
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 | |
wrap_with_apply_ufunc(func, input_core_dims=None, output_core_dims=None, dask='parallelized', vectorize=True, **ufunc_kwargs)
Wrap a function for use with xarray.apply_ufunc.
Usage:
func_xr = wrap_with_apply_ufunc(func_numpy, input_core_dims=[[], []]) # only 2 args, rest are kwarg
var_xr = func_xr(arg1, arg2, kwarg1=5, kwarg2=3) # where kwarg are key word arguments of the function
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable
|
The function to wrap. |
required |
input_core_dims
|
Optional[Sequence[Sequence[str]]]
|
Core dimensions for input parameters by the function. Defaults
to |
None
|
output_core_dims
|
Optional[Sequence[Sequence[str]]]
|
Core dimensions produced by the function. Defaults
to |
None
|
dask
|
Literal['forbidden', 'allowed', 'parallelized']
|
Dask handling mode. |
'parallelized'
|
vectorize
|
bool
|
Whether to auto-vectorize over non-core dims. |
True
|
**ufunc_kwargs
|
Any
|
Extra apply_ufunc keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
Callable
|
A callable that behaves like |
Source code in isca_tools/utils/xarray.py
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | |