Last active
August 29, 2015 14:13
-
-
Save xrotwang/9f0377cfae9ee94ae31b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Python 2.7 script to determine WWF Ecoregions in which a given species has been observed. | |
Assumes you have downloaded the WWF Ecoregions shapefile. | |
Usage: | |
$ python ecoregions_for_species.py "Ursus maritimus" | |
PA1101 Arctic desert | |
NA0616 Southern Hudson Bay taiga | |
NA1113 Kalaallit Nunaat low arctic tundra | |
NA1112 Kalaallit Nunaat high arctic tundra | |
""" | |
import sys | |
import fiona | |
from shapely.geometry import shape, Point | |
import requests | |
def gbif_api(path, **params): | |
return requests.get('http://api.gbif.org/v1/' + path, params=params).json() | |
def occurrences(species): | |
kw = dict( | |
taxonKey=gbif_api('species/match', name=species)['speciesKey'], | |
basisOfRecord='HUMAN_OBSERVATION', | |
hasCoordinate='true', | |
limit=100) | |
return gbif_api('occurrence/search', **kw)['results'] | |
def get_ecoregions(species): | |
with fiona.collection('wwf_terr_ecos.shp', "r") as source: | |
ecoregions = [ | |
(feature['properties'], shape(feature['geometry'])) | |
for feature in source if feature['geometry']] | |
eco_codes = {} | |
for oc in occurrences(species): | |
point = Point(oc['decimalLongitude'], oc['decimalLatitude']) | |
for props, er in ecoregions: | |
eco_code = props['eco_code'] | |
try: | |
if er.contains(point): | |
if eco_code not in eco_codes: | |
eco_codes[eco_code] = props['ECO_NAME'] | |
break | |
except: | |
pass | |
return eco_codes | |
if __name__ == "__main__": | |
for code, name in get_ecoregions(sys.argv[1]).items(): | |
print code, name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment