import xarray as xr
import pandas as pd
import os
import geopandas as gpd
import numpy as np
import matplotlib.pyplot as plt
import regionmask
era_data_path="C:/Users/dboateng/Desktop/Datasets/ERA5/monthly_1950_2021/"
path_shapefile="C:/Users/dboateng/Desktop/Datasets/Station/Ghana/Ghana_ShapeFile/gh_wgs16dregions.shp"
afr_shape = "C:/Users/dboateng/Desktop/Datasets/Station/Ghana/Africa_shapefile/afr_g2014_2013_0.shp"
from1979to2012 = pd.date_range(start="1979-01-01", end="2012-12-31", freq="MS")
tp_monthly= xr.open_dataset(os.path.join(era_data_path, "tp_monthly.nc"))
tp_monthly = tp_monthly["tp"].sel(time=from1979to2012).mean(dim="time")
ghana_shape = gpd.read_file(path_shapefile)
np.array(ghana_shape.geometry[0])
array(<POLYGON ((-3.088 6.975, -3.086 6.974, -3.084 6.974, -3.084 6.974, -3.084 6....>, dtype=object)
poly = regionmask.Regions(np.array(ghana_shape.geometry[0]))
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [16], in <cell line: 1>() ----> 1 poly = regionmask.Regions(np.array(ghana_shape.geometry[0])) File ~\Anaconda3\envs\regionmask_env\lib\site-packages\regionmask\core\regions.py:95, in Regions.__init__(self, outlines, numbers, names, abbrevs, name, source, overlap) 83 def __init__( 84 self, 85 outlines, (...) 91 overlap=False, 92 ): 94 if numbers is None: ---> 95 numbers = range(len(outlines)) 97 if not _is_numeric(numbers): 98 raise ValueError("'numbers' must be numeric") TypeError: len() of unsized object
poly
<regionmask.Regions> Name: unnamed overlap: False Regions: 0 r0 Region0 1 r1 Region1 2 r2 Region2 3 r3 Region3 4 r4 Region4 .. .. ... 11 r11 Region11 12 r12 Region12 13 r13 Region13 14 r14 Region14 15 r15 Region15 [16 regions]
mask = poly.mask(tp_monthly, lat_name="latitude", lon_name="longitude", wrap_lon=True)
mask
<xarray.DataArray 'mask' (latitude: 721, longitude: 1440)> array([[nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan], ..., [nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan]]) Coordinates: expver float64 1.0 * latitude (latitude) float32 90.0 89.75 89.5 89.25 ... -89.5 -89.75 -90.0 * longitude (longitude) float32 0.0 0.25 0.5 0.75 ... 359.0 359.2 359.5 359.8
pr_mask = tp_monthly.where(mask==0)
pr_mask
<xarray.DataArray 'tp' (latitude: 721, longitude: 1440)> array([[nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan], ..., [nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan]], dtype=float32) Coordinates: expver float64 1.0 * longitude (longitude) float32 0.0 0.25 0.5 0.75 ... 359.0 359.2 359.5 359.8 * latitude (latitude) float32 90.0 89.75 89.5 89.25 ... -89.5 -89.75 -90.0