Python Jupyter notebook API example¶
In [3]:
Copied!
# This is the only package actually required to make a request:
import requests
# The remaining packages are useful in displaying or using the response data.
import json
import getpass
from collections import namedtuple
import base64
import rasterio
from rasterio import MemoryFile
from rasterio.session import AWSSession
from matplotlib import pyplot as plt
import folium
import branca
import geopandas as gpd
import numpy as np
from matplotlib import cm
from matplotlib import pyplot as plt
import pandas as pd
from IPython.core.display import display, HTML
from PIL import Image
from io import BytesIO
import base64
import re, os
from pathlib import Path
%matplotlib inline
# This is the only package actually required to make a request:
import requests
# The remaining packages are useful in displaying or using the response data.
import json
import getpass
from collections import namedtuple
import base64
import rasterio
from rasterio import MemoryFile
from rasterio.session import AWSSession
from matplotlib import pyplot as plt
import folium
import branca
import geopandas as gpd
import numpy as np
from matplotlib import cm
from matplotlib import pyplot as plt
import pandas as pd
from IPython.core.display import display, HTML
from PIL import Image
from io import BytesIO
import base64
import re, os
from pathlib import Path
%matplotlib inline
Set up¶
In [4]:
Copied!
url = "https://api.looc-b.farm"
token = getpass.getpass()
url = "https://api.looc-b.farm"
token = getpass.getpass()
Create a feature¶
In [5]:
Copied!
feature = {"type":"FeatureCollection", "features": [
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[144.27287356885532,-37.64955948737578],[144.27146513389454,-37.64844433430535],[144.2700566989338,-37.64459185850357],[144.26826414534747,-37.64484531699941],[144.26788002672177,-37.64514946605291],[144.26967258030817,-37.65042118509808],[144.26775198717982,-37.651181498314806],[144.2668557103867,-37.65067462370187],[144.266471591761,-37.650674623701896],[144.2671758092414,-37.651992490499424],[144.26295050435914,-37.65133356002399],[144.26141402985658,-37.65706099099198],[144.25750882382906,-37.65787191896435],[144.25520411207518,-37.6565034728732],[144.25385969688529,-37.657365090019546],[144.2596214762702,-37.663953596430915],[144.2595574564992,-37.66425766722557],[144.2522592026118,-37.66339613007215],[144.2507867478801,-37.6612169032267],[144.24777781864574,-37.659240339833346],[144.24732968024918,-37.6590882943156],[144.24726566047826,-37.65944306670585],[144.2466894825398,-37.65954442993453],[144.2464974232269,-37.66141962470176],[144.24726566047826,-37.66238254414847],[144.24726566047832,-37.66283865952678],[144.24521702780805,-37.66238254414845],[144.2438726126184,-37.66689289526888],[144.2345257260607,-37.66577800251491],[144.23497386445732,-37.66973072852797],[144.22882796644674,-37.66907195547822],[144.2251788395031,-37.69324002946069],[144.21704832859342,-37.69227751042105],[144.21653617042585,-37.69703932472337],[144.22411490907842,-37.69808709676632],[144.22257764281488,-37.7098442397424],[144.2320289549939,-37.71309552886318],[144.23081257934598,-37.72038804995129],[144.22063343576616,-37.71937524272531],[144.2181366646994,-37.73451526676643],[144.21864882286692,-37.73593290316538],[144.22281010797818,-37.740691912547184],[144.22293814752007,-37.741350049338216],[144.2275475710279,-37.74200818027777],[144.22799570942456,-37.74038815513155],[144.23971132750702,-37.74155255178905],[144.23798279369163,-37.75238562522827],[144.24246417765752,-37.75284118702674],[144.2413758415515,-37.76007918147898],[144.25033860948344,-37.761192656234165],[144.25072272810922,-37.759421211245304],[144.26026167397958,-37.76043347071921],[144.26096589146,-37.75511895394572],[144.25072272810917,-37.75390415364863],[144.2514269455895,-37.750360872188736],[144.24957037223217,-37.7494497152455],[144.24969841177406,-37.746260577593794],[144.25238724215367,-37.745197501169464],[144.2522592026118,-37.744741892313165],[144.2429763358251,-37.74357754582716],[144.24329643467988,-37.74145130063287],[144.24464084986965,-37.74140067500286],[144.2446408498697,-37.74226130600406],[144.2561003888683,-37.74408378568038],[144.25661254703593,-37.743121926998725],[144.25834108085135,-37.74286880421552],[144.2596854960411,-37.7412487979051],[144.26058177283437,-37.74089441679842],[144.26167010894034,-37.74089441679847],[144.26301452413006,-37.74003376990457],[144.26621551267732,-37.74064128639778],[144.26877630351495,-37.740489407741904],[144.27076091641416,-37.739426248425495],[144.2705048373305,-37.738312446098014],[144.27248945022964,-37.73750239751598],[144.27517828060925,-37.73694548397431],[144.27581847831866,-37.73714799847421],[144.2804279018265,-37.73400896147415],[144.28241251472573,-37.73436337554227],[144.2819643763292,-37.736591082266465],[144.2827326135805,-37.73679359773579],[144.28433310785402,-37.735274718212956],[144.28548546373102,-37.73492030850734],[144.2868938986917,-37.733705176637045],[144.28849439296528,-37.73304697188071],[144.2916953815124,-37.732692551511406],[144.29214351990896,-37.73264191989162],[144.29291175716025,-37.726869688291366],[144.298865595858,-37.724641689088024],[144.29905765517083,-37.72312256029457],[144.29035096632256,-37.722160429276975],[144.29111920357394,-37.71658995145543],[144.29156734197053,-37.713753910937285],[144.28650978006607,-37.713196818793854],[144.28702193823352,-37.71031000151101],[144.28836635342336,-37.70798020731534],[144.2900308674679,-37.70813215264767],[144.29111920357388,-37.70261127227757],[144.2906710651773,-37.701902138575115],[144.29111920357388,-37.70038254351181],[144.29611274570746,-37.70088907866076],[144.29752118066816,-37.70250996787827],[144.2985454970033,-37.70286453267003],[144.29867353654515,-37.70139561034853],[144.29937775402547,-37.70093973198531],[144.2991216749418,-37.70028123606662],[144.2984174574614,-37.70043319718243],[144.2974571608972,-37.700635811518886],[144.29700902250065,-37.69987600490165],[144.29617676547835,-37.69957208007418],[144.29611274570743,-37.698862917297966],[144.29732912135535,-37.69840702335954],[144.29720108181345,-37.697444571394165],[144.29464029097574,-37.69790047125106],[144.2938080339535,-37.69729260415218],[144.29310381647315,-37.69663407583754],[144.29188744082523,-37.69592488495728],[144.29073508494827,-37.696228824736586],[144.29015890700978,-37.695519629980026],[144.28939066975846,-37.69364529689742],[144.2881742941106,-37.69374661341057],[144.28817429411052,-37.69278410094669],[144.2872780173174,-37.69232816962929],[144.28759811617212,-37.69096035885732],[144.28644576029515,-37.69020045308219],[144.28759811617206,-37.68888326462581],[144.28657379983693,-37.68832598554383],[144.287662135943,-37.68797135122044],[144.28708595800455,-37.68731274012087],[144.2874060568592,-37.68700876379457],[144.28606164166945,-37.68645147062726],[144.2861256614404,-37.68574218235809],[144.28689389869172,-37.685184879673926],[144.28606164166945,-37.684931558887676],[144.2866378196079,-37.68407026174309],[144.28478124625062,-37.683563611692044],[144.28388496945738,-37.68280363012679],[144.28286065312238,-37.683462281266536],[144.2824765344967,-37.683208954597234],[144.28292467289327,-37.681942308273335],[144.28785419525585,-37.680219634563315],[144.29592068639462,-37.676672827433066],[144.29752118066816,-37.6753047279398],[144.30507551363942,-37.6726697985808],[144.3050114938685,-37.6701867987522],[144.30641992882923,-37.67059219215409],[144.307764344019,-37.6709469095641],[144.30834052195746,-37.67094690956413],[144.3098769964601,-37.671352298813765],[144.31154151050455,-37.67079488802455],[144.31173356981736,-37.668919930097864],[144.3091727789797,-37.66770371584392],[144.30789238356087,-37.66745033536571],[144.30488345432656,-37.66765303981749],[144.30283482165643,-37.66724763036036],[144.3037310984496,-37.66451105860298],[144.3035403326963,-37.66237348198768],[144.29697492469563,-37.65393049219204],[144.29492523634423,-37.654564383619594],[144.29204286209995,-37.650558098826686],[144.2734675614152,-37.65887470181589],[144.27421798404512,-37.6522459237408],[144.2737698456485,-37.65255004248885],[144.27287356885532,-37.64955948737578]]]},"properties":{"PROJ_ID":"EOP101120", "fill": "#ff0000", "fill-opacity": 1.0, "stroke": "#ff0000", "stroke-opacity": 1.0}}
]}
gdf = gpd.GeoDataFrame.from_features(feature)
gdf.plot()
feature = {"type":"FeatureCollection", "features": [
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[144.27287356885532,-37.64955948737578],[144.27146513389454,-37.64844433430535],[144.2700566989338,-37.64459185850357],[144.26826414534747,-37.64484531699941],[144.26788002672177,-37.64514946605291],[144.26967258030817,-37.65042118509808],[144.26775198717982,-37.651181498314806],[144.2668557103867,-37.65067462370187],[144.266471591761,-37.650674623701896],[144.2671758092414,-37.651992490499424],[144.26295050435914,-37.65133356002399],[144.26141402985658,-37.65706099099198],[144.25750882382906,-37.65787191896435],[144.25520411207518,-37.6565034728732],[144.25385969688529,-37.657365090019546],[144.2596214762702,-37.663953596430915],[144.2595574564992,-37.66425766722557],[144.2522592026118,-37.66339613007215],[144.2507867478801,-37.6612169032267],[144.24777781864574,-37.659240339833346],[144.24732968024918,-37.6590882943156],[144.24726566047826,-37.65944306670585],[144.2466894825398,-37.65954442993453],[144.2464974232269,-37.66141962470176],[144.24726566047826,-37.66238254414847],[144.24726566047832,-37.66283865952678],[144.24521702780805,-37.66238254414845],[144.2438726126184,-37.66689289526888],[144.2345257260607,-37.66577800251491],[144.23497386445732,-37.66973072852797],[144.22882796644674,-37.66907195547822],[144.2251788395031,-37.69324002946069],[144.21704832859342,-37.69227751042105],[144.21653617042585,-37.69703932472337],[144.22411490907842,-37.69808709676632],[144.22257764281488,-37.7098442397424],[144.2320289549939,-37.71309552886318],[144.23081257934598,-37.72038804995129],[144.22063343576616,-37.71937524272531],[144.2181366646994,-37.73451526676643],[144.21864882286692,-37.73593290316538],[144.22281010797818,-37.740691912547184],[144.22293814752007,-37.741350049338216],[144.2275475710279,-37.74200818027777],[144.22799570942456,-37.74038815513155],[144.23971132750702,-37.74155255178905],[144.23798279369163,-37.75238562522827],[144.24246417765752,-37.75284118702674],[144.2413758415515,-37.76007918147898],[144.25033860948344,-37.761192656234165],[144.25072272810922,-37.759421211245304],[144.26026167397958,-37.76043347071921],[144.26096589146,-37.75511895394572],[144.25072272810917,-37.75390415364863],[144.2514269455895,-37.750360872188736],[144.24957037223217,-37.7494497152455],[144.24969841177406,-37.746260577593794],[144.25238724215367,-37.745197501169464],[144.2522592026118,-37.744741892313165],[144.2429763358251,-37.74357754582716],[144.24329643467988,-37.74145130063287],[144.24464084986965,-37.74140067500286],[144.2446408498697,-37.74226130600406],[144.2561003888683,-37.74408378568038],[144.25661254703593,-37.743121926998725],[144.25834108085135,-37.74286880421552],[144.2596854960411,-37.7412487979051],[144.26058177283437,-37.74089441679842],[144.26167010894034,-37.74089441679847],[144.26301452413006,-37.74003376990457],[144.26621551267732,-37.74064128639778],[144.26877630351495,-37.740489407741904],[144.27076091641416,-37.739426248425495],[144.2705048373305,-37.738312446098014],[144.27248945022964,-37.73750239751598],[144.27517828060925,-37.73694548397431],[144.27581847831866,-37.73714799847421],[144.2804279018265,-37.73400896147415],[144.28241251472573,-37.73436337554227],[144.2819643763292,-37.736591082266465],[144.2827326135805,-37.73679359773579],[144.28433310785402,-37.735274718212956],[144.28548546373102,-37.73492030850734],[144.2868938986917,-37.733705176637045],[144.28849439296528,-37.73304697188071],[144.2916953815124,-37.732692551511406],[144.29214351990896,-37.73264191989162],[144.29291175716025,-37.726869688291366],[144.298865595858,-37.724641689088024],[144.29905765517083,-37.72312256029457],[144.29035096632256,-37.722160429276975],[144.29111920357394,-37.71658995145543],[144.29156734197053,-37.713753910937285],[144.28650978006607,-37.713196818793854],[144.28702193823352,-37.71031000151101],[144.28836635342336,-37.70798020731534],[144.2900308674679,-37.70813215264767],[144.29111920357388,-37.70261127227757],[144.2906710651773,-37.701902138575115],[144.29111920357388,-37.70038254351181],[144.29611274570746,-37.70088907866076],[144.29752118066816,-37.70250996787827],[144.2985454970033,-37.70286453267003],[144.29867353654515,-37.70139561034853],[144.29937775402547,-37.70093973198531],[144.2991216749418,-37.70028123606662],[144.2984174574614,-37.70043319718243],[144.2974571608972,-37.700635811518886],[144.29700902250065,-37.69987600490165],[144.29617676547835,-37.69957208007418],[144.29611274570743,-37.698862917297966],[144.29732912135535,-37.69840702335954],[144.29720108181345,-37.697444571394165],[144.29464029097574,-37.69790047125106],[144.2938080339535,-37.69729260415218],[144.29310381647315,-37.69663407583754],[144.29188744082523,-37.69592488495728],[144.29073508494827,-37.696228824736586],[144.29015890700978,-37.695519629980026],[144.28939066975846,-37.69364529689742],[144.2881742941106,-37.69374661341057],[144.28817429411052,-37.69278410094669],[144.2872780173174,-37.69232816962929],[144.28759811617212,-37.69096035885732],[144.28644576029515,-37.69020045308219],[144.28759811617206,-37.68888326462581],[144.28657379983693,-37.68832598554383],[144.287662135943,-37.68797135122044],[144.28708595800455,-37.68731274012087],[144.2874060568592,-37.68700876379457],[144.28606164166945,-37.68645147062726],[144.2861256614404,-37.68574218235809],[144.28689389869172,-37.685184879673926],[144.28606164166945,-37.684931558887676],[144.2866378196079,-37.68407026174309],[144.28478124625062,-37.683563611692044],[144.28388496945738,-37.68280363012679],[144.28286065312238,-37.683462281266536],[144.2824765344967,-37.683208954597234],[144.28292467289327,-37.681942308273335],[144.28785419525585,-37.680219634563315],[144.29592068639462,-37.676672827433066],[144.29752118066816,-37.6753047279398],[144.30507551363942,-37.6726697985808],[144.3050114938685,-37.6701867987522],[144.30641992882923,-37.67059219215409],[144.307764344019,-37.6709469095641],[144.30834052195746,-37.67094690956413],[144.3098769964601,-37.671352298813765],[144.31154151050455,-37.67079488802455],[144.31173356981736,-37.668919930097864],[144.3091727789797,-37.66770371584392],[144.30789238356087,-37.66745033536571],[144.30488345432656,-37.66765303981749],[144.30283482165643,-37.66724763036036],[144.3037310984496,-37.66451105860298],[144.3035403326963,-37.66237348198768],[144.29697492469563,-37.65393049219204],[144.29492523634423,-37.654564383619594],[144.29204286209995,-37.650558098826686],[144.2734675614152,-37.65887470181589],[144.27421798404512,-37.6522459237408],[144.2737698456485,-37.65255004248885],[144.27287356885532,-37.64955948737578]]]},"properties":{"PROJ_ID":"EOP101120", "fill": "#ff0000", "fill-opacity": 1.0, "stroke": "#ff0000", "stroke-opacity": 1.0}}
]}
gdf = gpd.GeoDataFrame.from_features(feature)
gdf.plot()
Out[5]:
<AxesSubplot:>
Monitoring endpoint¶
In [20]:
Copied!
%%time
endpoint = 'monitoring'
params = {"polygon": json.dumps(feature), # GeoJSON
"mode": endpoint, # Which mode: monitoring or planning
"start_year": 2012, # Start of the assessment. The earliest possible is 2012.
"end_year": 2020, # End of the assessment. The latest possible is 2020.
"action_year": 2015, # In which year an action was implemented (optional).
"dataset": ["habitat-condition"], # Which metric to asses.
"download_geotiff": False # Whether or not to save derived maps in GeoTIFF format
}
header = {
'Authorization': 'Bearer {}'.format(token) # Format the token for authorization
}
response = requests.post(f'{url}/{endpoint}', # Make the request
json = params,
headers=header)
print(response.status_code) # All going well, the returned HTTP code should be 200
%%time
endpoint = 'monitoring'
params = {"polygon": json.dumps(feature), # GeoJSON
"mode": endpoint, # Which mode: monitoring or planning
"start_year": 2012, # Start of the assessment. The earliest possible is 2012.
"end_year": 2020, # End of the assessment. The latest possible is 2020.
"action_year": 2015, # In which year an action was implemented (optional).
"dataset": ["habitat-condition"], # Which metric to asses.
"download_geotiff": False # Whether or not to save derived maps in GeoTIFF format
}
header = {
'Authorization': 'Bearer {}'.format(token) # Format the token for authorization
}
response = requests.post(f'{url}/{endpoint}', # Make the request
json = params,
headers=header)
print(response.status_code) # All going well, the returned HTTP code should be 200
200 CPU times: user 25 ms, sys: 9.95 ms, total: 34.9 ms Wall time: 4.39 s
In [7]:
Copied!
data = response.json()
data.keys()
data = response.json()
data.keys()
Out[7]:
dict_keys(['assessment_area', 'datasets'])
Response data¶
Walk through the various items returned in the reponse json:
In [8]:
Copied!
data['assessment_area'] # area of polygon in ha
data['assessment_area'] # area of polygon in ha
Out[8]:
5741.671426094147
In [9]:
Copied!
len(data['datasets']) # data for a single dataset (i.e. habitat-condition)
len(data['datasets']) # data for a single dataset (i.e. habitat-condition)
Out[9]:
1
In [10]:
Copied!
data['datasets'][0].keys() # the following data is returned
data['datasets'][0].keys() # the following data is returned
Out[10]:
dict_keys(['name', 'summary', 'annual_averages', 'figure', 'geotiff', 'units', 'attribution', 'mode'])
In [11]:
Copied!
data['datasets'][0]['name']
data['datasets'][0]['name']
Out[11]:
'habitat-condition'
In [12]:
Copied!
data['datasets'][0]['summary']
data['datasets'][0]['summary']
Out[12]:
{'mean_percent_changes': {'values': {'starting_estimate': 36, 'latest_estimate': 42, 'expected_change': 14}, 'units': 'percent'}, 'potential_change_habitat_area': {'values': {'potential_change_ha': 819}, 'units': 'ha'}}
In [13]:
Copied!
data['datasets'][0]['annual_averages'] # summary data
data['datasets'][0]['annual_averages'] # summary data
Out[13]:
{'mean': {'2012': 0.3685349814381611, '2013': 0.33665712882679005, '2014': 0.31464855668989017, '2015': 0.28385356409555534, '2016': 0.2881668873003967, '2017': 0.3043787981844996, '2018': 0.32366209348301467, '2019': 0.3982214881890765, '2020': 0.4264946014925753}, 'fifth_percentile': {'2012': 0.12931382060050964, '2013': 0.13048578500747682, '2014': 0.12763504981994628, '2015': 0.1259802758693695, '2016': 0.12419400066137314, '2017': 0.1254882127046585, '2018': 0.13024066984653473, '2019': 0.15146154761314393, '2020': 0.15404867827892305}, 'ninety_fifth_percentile': {'2012': 0.853738832473754, '2013': 0.8010057568550105, '2014': 0.7763315320014949, '2015': 0.7773002028465268, '2016': 0.8122637391090384, '2017': 0.8584174990653989, '2018': 0.9129437088966369, '2019': 0.9810299515724175, '2020': 1.0}}
In [14]:
Copied!
pd.DataFrame(data['datasets'][0]['annual_averages']) # as table
pd.DataFrame(data['datasets'][0]['annual_averages']) # as table
Out[14]:
mean | fifth_percentile | ninety_fifth_percentile | |
---|---|---|---|
2012 | 0.368535 | 0.129314 | 0.853739 |
2013 | 0.336657 | 0.130486 | 0.801006 |
2014 | 0.314649 | 0.127635 | 0.776332 |
2015 | 0.283854 | 0.125980 | 0.777300 |
2016 | 0.288167 | 0.124194 | 0.812264 |
2017 | 0.304379 | 0.125488 | 0.858417 |
2018 | 0.323662 | 0.130241 | 0.912944 |
2019 | 0.398221 | 0.151462 | 0.981030 |
2020 | 0.426495 | 0.154049 | 1.000000 |
In [15]:
Copied!
display(HTML(data['datasets'][0]['figure']))
display(HTML(data['datasets'][0]['figure']))
In [16]:
Copied!
images_base64 = data['datasets'][0]['geotiff']
print(images_base64.keys())
l, b, r, t = list(images_base64['bounds'].values())
images_base64 = data['datasets'][0]['geotiff']
print(images_base64.keys())
l, b, r, t = list(images_base64['bounds'].values())
dict_keys(['bounds', 'images', 'url'])
In [18]:
Copied!
# Plot images on map
l, b, r, t = gdf.total_bounds
x, y = list(*gdf.loc[0, 'geometry'].centroid.coords)
m = folium.Map([y, x], zoom_start=13)#, width = 800, height = 400)
esri_img_url = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}.png'
imagery = folium.TileLayer(esri_img_url,
overlay = True, control = True,
show = False, attr='CSIRO')
imagery.layer_name = "Esri World Imagery"
imagery.add_to(m)
cmap = cm.get_cmap("RdYlGn").copy()
cmap = plt.get_cmap('RdYlGn')
# add legend
colormap = branca.colormap.linear.RdYlGn_11.scale(0, 100)
colormap = colormap.to_step(index=np.arange(0, 110, 10))
colormap.caption = 'Habitat condition (%)'
colormap.add_to(m)
l, b, r, t = list(images_base64['bounds'].values())
ll = (b, l)
ur = (t, r)
for t, img in images_base64['images'].items():
# decode
image = Image.open(BytesIO(base64.b64decode(img)))
img = np.array(image)
condition = folium.raster_layers.ImageOverlay(
image=img,
bounds=[ll, ur]
)
condition.layer_name = f'Condition: {t}'
condition.add_to(m)
control = folium.LayerControl().add_to(m)
m
# Plot images on map
l, b, r, t = gdf.total_bounds
x, y = list(*gdf.loc[0, 'geometry'].centroid.coords)
m = folium.Map([y, x], zoom_start=13)#, width = 800, height = 400)
esri_img_url = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}.png'
imagery = folium.TileLayer(esri_img_url,
overlay = True, control = True,
show = False, attr='CSIRO')
imagery.layer_name = "Esri World Imagery"
imagery.add_to(m)
cmap = cm.get_cmap("RdYlGn").copy()
cmap = plt.get_cmap('RdYlGn')
# add legend
colormap = branca.colormap.linear.RdYlGn_11.scale(0, 100)
colormap = colormap.to_step(index=np.arange(0, 110, 10))
colormap.caption = 'Habitat condition (%)'
colormap.add_to(m)
l, b, r, t = list(images_base64['bounds'].values())
ll = (b, l)
ur = (t, r)
for t, img in images_base64['images'].items():
# decode
image = Image.open(BytesIO(base64.b64decode(img)))
img = np.array(image)
condition = folium.raster_layers.ImageOverlay(
image=img,
bounds=[ll, ur]
)
condition.layer_name = f'Condition: {t}'
condition.add_to(m)
control = folium.LayerControl().add_to(m)
m
Out[18]:
Make this Notebook Trusted to load map: File -> Trust Notebook
Map data¶
Getting the GeoTiff data
The simplest route to accessing the data is to access the provided url, which will download the associated GeoTIFF file:
In [175]:
Copied!
# The simplest route to accessing the data is to access the provided url, which will download the associated GeoTIFF file:
data['datasets'][0]['geotiff']['url']
# The simplest route to accessing the data is to access the provided url, which will download the associated GeoTIFF file:
data['datasets'][0]['geotiff']['url']
Out[175]:
'https://biodiversity-data.s3.amazonaws.com/user-data/a34bbd5f-42bb-4e50-8973-bd0fde67edf4.tif?AWSAccessKeyId=ASIARZGLS5YROFUYDBW4&Signature=0cd4Xj4mMzPGs66i0zW9AesLDRI%3D&x-amz-security-token=IQoJb3JpZ2luX2VjEDAaDmFwLXNvdXRoZWFzdC0yIkYwRAIgVa%2Fc4DykK2JCmMOzQHmTx%2Bdp3oa5xTAla%2FTaYVwL%2FDICIEULdnRMPTGH6mD9X4wT4J1eAhobIjnEKmvCGbP8e4uDKogDCGkQABoMMTIyODMzNTMwNDAyIgz2HILi5dvdzJ4JVTsq5QL3XSQCMPK3Vo%2F%2F5IczZFqDfyYwy%2F%2B0MjpB7AlMK2qy%2FGph1J6liWxBdK5IXk2RpqYP2lJCTET8PKB6Vm9sEjYJwxfvk122b8Jw1Tw9QzyhdOt%2Bei%2BYXQFA3RVgHiJ5zKpuc22gP7rxZBr%2Bxim2mbB9lPxFm0YHcW84793EkyKTy31rZqJFcyqL9Qqk%2FUhb53Cr2ePy0D60DzByeeOZqOxLCa%2FW8mZh3jJxq22Vxz47Krokd05jrE7QHLJMqeJlUkg4nPL0lZwB6UCBU5wWteCHD5yVRnFRTDlnPPJk01%2BS9xJF9knwZ4izyI4%2BunNQssuyddcrpfTH5h1pEgxK%2FGR2wZLUtP5cvqh3mG2C%2BWTtHSnYkYQAv3oSEZhppoOrUoT9KilJpZzHDecEnADvMwG%2FuS4rrPDg8xKcDSDRpj5MTGgXmNMZRi%2FnDLblTZeHOqXH1Do0GnQwOaU%2F32SQmHcpm4atGPAwwLHsjwY6pwFguQgE6UqSUlw230aE7dU1p4uLxCSQa1Mlcn5O0yCXseYxwPLyFhWL71D91CqqTT%2FPXH7vXTOtQdoknnV5jgrSKvimMamSEGqEfA1R8KQekJpsjViIFIV0pxeGv4OuJkkfaX15HgPPWB47Uufg8xXYKrIf48GNlrvb6zGUxn9gyj2S5dyUCuLtK3yBUVfuyIxxDLgnwopuen%2BFo55f13JpAcDVbor29g%3D%3D&Expires=1643953858'
Reading the GeoTiff dataset
To avoid downloading the data to file, and instead simply consume the data, it's possible to read the data directly. This takes a little (a lot of ?!) munging of the presigned URL returned via the API call:
In [214]:
Copied!
url, credentials = data['datasets'][0]['geotiff']['url'].split('?')
credentials = credentials.split('&')
# Extract the relevant credentials
aws_access_key_id = re.sub('AWSAccessKeyId=', '', credentials[0])
aws_secret_access_key = re.sub('Signature=', '', credentials[1])
aws_session_token = re.sub('x-amz-security-token=', '', credentials[2])
# Create a filepath
p = Path(url)
_, bucket, folder, file = p.parts
gdal_path = f's3://{bucket.split(".s3")[0]}/{folder}/{file}'
# Create a rasterio AWS session
session = AWSSession(aws_access_key_id = aws_access_key_id,
aws_secret_access_key = aws_secret_access_key,
aws_session_token = aws_session_token)
# Now we can access the data
with rasterio.Env(session):
with rasterio.open(gdal_path) as src:
print(src.profile)
url, credentials = data['datasets'][0]['geotiff']['url'].split('?')
credentials = credentials.split('&')
# Extract the relevant credentials
aws_access_key_id = re.sub('AWSAccessKeyId=', '', credentials[0])
aws_secret_access_key = re.sub('Signature=', '', credentials[1])
aws_session_token = re.sub('x-amz-security-token=', '', credentials[2])
# Create a filepath
p = Path(url)
_, bucket, folder, file = p.parts
gdal_path = f's3://{bucket.split(".s3")[0]}/{folder}/{file}'
# Create a rasterio AWS session
session = AWSSession(aws_access_key_id = aws_access_key_id,
aws_secret_access_key = aws_secret_access_key,
aws_session_token = aws_session_token)
# Now we can access the data
with rasterio.Env(session):
with rasterio.open(gdal_path) as src:
print(src.profile)
{'driver': 'GTiff', 'dtype': 'float32', 'nodata': -9999.0, 'width': 187, 'height': 143, 'count': 9, 'crs': CRS.from_epsg(4326), 'transform': Affine(0.0009767256956049466, 0.0, 147.62603759765625, 0.0, -0.0009676267117016805, -42.58443313755392), 'tiled': False, 'interleave': 'pixel'}
In [208]:
Copied!
# And read the data
with rasterio.Env(session):
with rasterio.open(gdal_path) as src:
arr = src.read(masked = True)
l, b, r, t = src.bounds
band_names = src.descriptions
# And read the data
with rasterio.Env(session):
with rasterio.open(gdal_path) as src:
arr = src.read(masked = True)
l, b, r, t = src.bounds
band_names = src.descriptions
In [213]:
Copied!
# And display the time series
fig, axes = plt.subplots(nrows = 1, ncols = arr.shape[0], figsize = (36, 24))
for idx, ax in enumerate(axes):
ax.imshow(arr[idx, :, :], extent = [l, r, b, t], cmap = 'RdYlGn')
ax.set_title(band_names[idx])
# And display the time series
fig, axes = plt.subplots(nrows = 1, ncols = arr.shape[0], figsize = (36, 24))
for idx, ax in enumerate(axes):
ax.imshow(arr[idx, :, :], extent = [l, r, b, t], cmap = 'RdYlGn')
ax.set_title(band_names[idx])
Planning¶
In [21]:
Copied!
%%time
endpoint = 'planning'
params = {"polygon": json.dumps(feature),
"mode": 'planning',
# "start_year": 2020,
# "end_year": 2020,
# "action_year": 2015,
"action_type": "environmental_planting",
"dataset": ["habitat-condition"]
}
auth = {'Authorization': 'Bearer {}'.format(token)}
response = requests.post(f'{url}/{endpoint}?',
json = params,
headers=auth)
print(response.status_code)
%%time
endpoint = 'planning'
params = {"polygon": json.dumps(feature),
"mode": 'planning',
# "start_year": 2020,
# "end_year": 2020,
# "action_year": 2015,
"action_type": "environmental_planting",
"dataset": ["habitat-condition"]
}
auth = {'Authorization': 'Bearer {}'.format(token)}
response = requests.post(f'{url}/{endpoint}?',
json = params,
headers=auth)
print(response.status_code)
200 CPU times: user 28 ms, sys: 7.11 ms, total: 35.1 ms Wall time: 4.61 s
Response data¶
In [22]:
Copied!
data = response.json()
data.keys()
data = response.json()
data.keys()
Out[22]:
dict_keys(['assessment_area', 'datasets'])
In [23]:
Copied!
display(HTML(data['datasets'][0]['figure']))
display(HTML(data['datasets'][0]['figure']))
In [24]:
Copied!
# the response is the same as the monitoring example
# the response is the same as the monitoring example
In [ ]:
Copied!