xarray_regrid.utils

Exceptions

InvalidBoundsError

Common base class for all non-exit exceptions.

Classes

CoordHandler

dict() -> new empty dictionary

Grid

Object storing grid information.

Functions

create_lat_lon_coords(→ tuple[numpy.ndarray, ...)

Create latitude and longitude coordinates based on the provided grid parameters.

create_regridding_dataset(→ xarray.Dataset)

Create a dataset to use for regridding.

to_intervalindex(→ pandas.IntervalIndex)

Convert a 1-d coordinate array to a pandas IntervalIndex. Take

overlap(→ numpy.ndarray)

Calculate the overlap between two sets of intervals.

normalize_overlap(→ numpy.ndarray)

Normalize overlap values so they sum up to 1.0 along the first axis.

create_dot_dataarray(→ xarray.DataArray)

Create a DataArray to be used at dot product compatible with xr.dot.

common_coords(→ list[collections.abc.Hashable])

Return a set of coords which two dataset/arrays have in common.

call_on_dataset(→ xarray.DataArray | xarray.Dataset)

Use to call a function that expects a Dataset on either a Dataset or

format_for_regrid(…)

Apply any pre-formatting to the input dataset to prepare for regridding.

format_lat(→ xarray.DataArray | xarray.Dataset)

If the latitude coordinate is inferred to be global, defined as having

format_lon(→ xarray.DataArray | xarray.Dataset)

Format the longitude coordinate by shifting the source grid to line up with

coord_is_covered(→ bool)

Check if the source coord fully covers the target coord.

ensure_monotonic(…)

Ensure that an object has monotonically increasing indexes for a

update_coord(…)

Update the values of a coordinate, ensuring indexes stay in sync.

Module Contents

exception xarray_regrid.utils.InvalidBoundsError[source]

Bases: Exception

Common base class for all non-exit exceptions.

class xarray_regrid.utils.CoordHandler[source]

Bases: TypedDict

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s

(key, value) pairs

dict(iterable) -> new dictionary initialized as if via:

d = {} for k, v in iterable:

d[k] = v

dict(**kwargs) -> new dictionary initialized with the name=value pairs

in the keyword argument list. For example: dict(one=1, two=2)

names: list[str][source]
func: collections.abc.Callable[source]
class xarray_regrid.utils.Grid[source]

Object storing grid information.

north: float[source]
east: float[source]
south: float[source]
west: float[source]
resolution_lat: float[source]
resolution_lon: float[source]
__post_init__() None[source]

Validate the initialized SpatialBounds class.

create_regridding_dataset(lat_name: str = 'latitude', lon_name: str = 'longitude') xarray.Dataset[source]

Create a dataset to use for regridding.

Parameters:
  • grid – Grid object containing the bounds and resolution of the cartesian grid.

  • lat_name – Name for the latitudinal coordinate and dimension. Defaults to “latitude”.

  • lon_name – Name for the longitudinal coordinate and dimension. Defaults to “longitude”.

Returns:

A dataset with the latitude and longitude coordinates corresponding to the

specified grid. Contains no data variables.

xarray_regrid.utils.create_lat_lon_coords(grid: Grid) tuple[numpy.ndarray, numpy.ndarray][source]

Create latitude and longitude coordinates based on the provided grid parameters.

Parameters:

grid – Grid object.

Returns:

Latititude coordinates, longitude coordinates.

xarray_regrid.utils.create_regridding_dataset(grid: Grid, lat_name: str = 'latitude', lon_name: str = 'longitude') xarray.Dataset[source]

Create a dataset to use for regridding.

Parameters:
  • grid – Grid object containing the bounds and resolution of the cartesian grid.

  • lat_name – Name for the latitudinal coordinate and dimension. Defaults to “latitude”.

  • lon_name – Name for the longitudinal coordinate and dimension. Defaults to “longitude”.

Returns:

A dataset with the latitude and longitude coordinates corresponding to the

specified grid. Contains no data variables.

xarray_regrid.utils.to_intervalindex(coords: numpy.ndarray) pandas.IntervalIndex[source]

Convert a 1-d coordinate array to a pandas IntervalIndex. Take the midpoints between the coordinates as the interval boundaries.

Parameters:

coords – 1-d array containing the coordinate values.

Returns:

A pandas IntervalIndex containing the intervals corresponding to the input

coordinates.

xarray_regrid.utils.overlap(a: pandas.IntervalIndex, b: pandas.IntervalIndex) numpy.ndarray[source]

Calculate the overlap between two sets of intervals.

Parameters:
  • a – Pandas IntervalIndex containing the first set of intervals.

  • b – Pandas IntervalIndex containing the second set of intervals.

Returns:

2D numpy array containing overlap (as a fraction) between the intervals of a

and b. If there is no overlap, the value will be 0.

xarray_regrid.utils.normalize_overlap(overlap: numpy.ndarray) numpy.ndarray[source]

Normalize overlap values so they sum up to 1.0 along the first axis.

xarray_regrid.utils.create_dot_dataarray(weights: numpy.ndarray, coord: str, target_coords: numpy.ndarray, source_coords: numpy.ndarray) xarray.DataArray[source]

Create a DataArray to be used at dot product compatible with xr.dot.

xarray_regrid.utils.common_coords(data1: xarray.DataArray | xarray.Dataset, data2: xarray.DataArray | xarray.Dataset, remove_coord: str | None = None) list[collections.abc.Hashable][source]

Return a set of coords which two dataset/arrays have in common.

xarray_regrid.utils.call_on_dataset(func: collections.abc.Callable[Ellipsis, xarray.Dataset], obj: xarray.DataArray | xarray.Dataset, *args: Any, **kwargs: Any) xarray.DataArray | xarray.Dataset[source]

Use to call a function that expects a Dataset on either a Dataset or DataArray, round-tripping to a temporary dataset.

xarray_regrid.utils.format_for_regrid(obj: xarray.Dataset, target: xarray.Dataset, stats: bool = False) xarray.Dataset[source]
xarray_regrid.utils.format_for_regrid(obj: xarray.DataArray, target: xarray.Dataset, stats: bool = False) xarray.DataArray

Apply any pre-formatting to the input dataset to prepare for regridding. Currently handles padding of spherical geometry if lat/lon coordinates can be inferred and the domain size requires boundary padding.

xarray_regrid.utils.format_lat(obj: xarray.DataArray | xarray.Dataset, target: xarray.Dataset, formatted_coords: dict[str, str]) xarray.DataArray | xarray.Dataset[source]

If the latitude coordinate is inferred to be global, defined as having a value within one grid spacing of the poles, and the grid does not natively have values at -90 and 90, add a single value at each pole computed as the mean of the first and last latitude bands. This should be roughly equivalent to the Pole=”all” option in ESMF.

For example, with a grid spacing of 1 degree, and a source grid ranging from -89.5 to 89.5, the poles would be padded with values at -90 and 90. A grid ranging from -88 to 88 would not be padded because coverage does not extend all the way to the poles. A grid ranging from -90 to 90 would also not be padded because the poles will already be covered in the regridding weights.

xarray_regrid.utils.format_lon(obj: xarray.DataArray | xarray.Dataset, target: xarray.Dataset, formatted_coords: dict[str, str]) xarray.DataArray | xarray.Dataset[source]

Format the longitude coordinate by shifting the source grid to line up with the target anywhere in the range of -360 to 360, and then add a single wraparound padding column if the domain is inferred to be global and the east or west edges of the target lie outside the source grid centers.

For example, with a source grid ranging from 0.5 to 359.5 and a target grid ranging from -180 to 180, the source grid would be shifted to -179.5 to 179.5 and then padded on both the left and right with wraparound values at -180.5 and 180.5 to provide full coverage for the target edge cells at -180 and 180.

xarray_regrid.utils.coord_is_covered(obj: xarray.DataArray | xarray.Dataset, target: xarray.Dataset, coord: collections.abc.Hashable) bool[source]

Check if the source coord fully covers the target coord.

xarray_regrid.utils.ensure_monotonic(obj: xarray.DataArray, coord: collections.abc.Hashable) xarray.DataArray[source]
xarray_regrid.utils.ensure_monotonic(obj: xarray.Dataset, coord: collections.abc.Hashable) xarray.Dataset

Ensure that an object has monotonically increasing indexes for a given coordinate. Only sort and drop duplicates if needed because this requires reindexing which can be expensive.

xarray_regrid.utils.update_coord(obj: xarray.DataArray, coord: collections.abc.Hashable, coord_vals: numpy.ndarray) xarray.DataArray[source]
xarray_regrid.utils.update_coord(obj: xarray.Dataset, coord: collections.abc.Hashable, coord_vals: numpy.ndarray) xarray.Dataset

Update the values of a coordinate, ensuring indexes stay in sync.