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

Add region selection from file #981

Merged
merged 8 commits into from
Sep 18, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
34 changes: 34 additions & 0 deletions pcmdi_metrics/io/region_from_file.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import geopandas as gpd
import regionmask
import xarray as xr
import xcdat

def region_from_file(data,rgn_path,attr,feature):
# Return data masked from a feature in input file.
# Arguments:
# data: xcdat dataset
# feature: str, name of region
# rgn_path: str, path to file
# attr: str, attribute name

lon = data["lon"].data
lat = data["lat"].data

print("Reading region from file.")
try:
regions_df = gpd.read_file(rgn_path)
regions = regionmask.from_geopandas(regions_df,names=attr)
mask = regions.mask(lon, lat)
# Can't match mask by name, rather index of name
val = list(regions_df[attr]).index(feature)
except Exception as e:
print("Error in creating region subset from file:")
raise e

try:
masked_data = data.where(mask == val)
except Exception as e:
print("Error: Region selection failed.")
raise e

return masked_data