Skip to content

Commit

Permalink
Merge pull request #1010 from PCMDI/bug/1009_lee1043_landmask
Browse files Browse the repository at this point in the history
landmask generation for non-regular lat/lon grid
  • Loading branch information
lee1043 committed Dec 21, 2023
2 parents 090df28 + 554372d commit 8d7d16c
Showing 1 changed file with 15 additions and 6 deletions.
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

0 comments on commit 8d7d16c

Please sign in to comment.