Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

landmask generation for non-regular lat/lon grid #1010

Merged
merged 1 commit into from
Dec 21, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions pcmdi_metrics/utils/create_land_sea_mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,21 @@


def create_land_sea_mask(
obj: Union[xr.Dataset, xr.DataArray], as_boolean: bool = False
obj: Union[xr.Dataset, xr.DataArray],
lon_key: str = None,
lat_key: str = None,
as_boolean: bool = False,
) -> xr.DataArray:
"""Generate a land-sea mask (1 for land, 0 for sea) for a given xarray Dataset or DataArray.

Parameters
----------
obj : Union[xr.Dataset, xr.DataArray]
The Dataset or DataArray object.
lon_key : str, optional
Name of DataArray for longitude, by default None
lat_key : str, optional
Name of DataArray for latitude, by default None
as_boolean : bool, optional
Set mask value to True (land) or False (ocean), by default False, thus 1 (land) and 0 (ocean).

Expand All @@ -41,14 +48,16 @@ def create_land_sea_mask(
land_mask = regionmask.defined_regions.natural_earth_v5_0_0.land_110

# Get the longitude and latitude from the xarray dataset
key_lon = xc.axis.get_dim_keys(obj, axis="X")
key_lat = xc.axis.get_dim_keys(obj, axis="Y")
if lon_key is None:
lon_key = xc.axis.get_dim_keys(obj, axis="X")
if lat_key is None:
lat_key = xc.axis.get_dim_keys(obj, axis="Y")

lon = obj[key_lon]
lat = obj[key_lat]
lon = obj[lon_key]
lat = obj[lat_key]

# Mask the land-sea mask to match the dataset's coordinates
land_sea_mask = land_mask.mask(lon, lat)
land_sea_mask = land_mask.mask(lon, lat=lat)

if not as_boolean:
# Convert the land-sea mask to a boolean mask
Expand Down
Loading