Skip to content

Commit

Permalink
Merge pull request #981 from PCMDI/add_shapefile_region_ao
Browse files Browse the repository at this point in the history
Add region selection from file
  • Loading branch information
acordonez committed Sep 18, 2023
2 parents db92c9b + cad4b7e commit d628fc1
Showing 1 changed file with 34 additions and 0 deletions.
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

0 comments on commit d628fc1

Please sign in to comment.