diff --git a/environment.yaml b/environment.yaml index ff13fd47..12e652d2 100644 --- a/environment.yaml +++ b/environment.yaml @@ -19,6 +19,7 @@ dependencies: - xlrd - scikit-learn - pytables + - pycountry # Include ipython so that one does not inadvertently drop out of the conda # environment by calling ipython @@ -41,4 +42,4 @@ dependencies: - git+https://github.com/FRESNA/atlite.git #- git+https://github.com/FRESNA/powerplantmatching.git #- https://software.ecmwf.int/wiki/download/attachments/56664858/ecmwf-api-client-python.tgz - - countrycode + diff --git a/scripts/build_shapes.py b/scripts/build_shapes.py index b56deccd..e2f83874 100644 --- a/scripts/build_shapes.py +++ b/scripts/build_shapes.py @@ -9,10 +9,14 @@ import geopandas as gpd from shapely.geometry import MultiPolygon, Polygon from shapely.ops import cascaded_union -try: - from countrycode.countrycode import countrycode -except ImportError: - from countrycode import countrycode +import pycountry as pyc + +def _get_country(target, **keys): + assert len(keys) == 1 + try: + return getattr(pyc.countries.get(**keys), target) + except KeyError: + return np.nan def _simplify_polys(polys, minarea=0.1, tolerance=0.01, filterremote=True): if isinstance(polys, MultiPolygon): @@ -44,11 +48,9 @@ def countries(): return s def eez(country_shapes): - cntries = snakemake.config['countries'] - cntries3 = frozenset(countrycode(cntries, origin='iso2c', target='iso3c')) df = gpd.read_file(snakemake.input.eez) - df = df.loc[df['ISO_3digit'].isin(cntries3)] - df['name'] = countrycode(df['ISO_3digit'], origin='iso3c', target='iso2c') + df = df.loc[df['ISO_3digit'].isin([_get_country('alpha_3', alpha_2=c) for c in snakemake.config['countries']])] + df['name'] = df['ISO_3digit'].map(lambda c: _get_country('alpha_2', alpha_3=c)) s = df.set_index('name').geometry.map(lambda s: _simplify_polys(s, filterremote=False)) return gpd.GeoSeries({k:v for k,v in s.iteritems() if v.distance(country_shapes[k]) < 1e-3})