Largely from https://github.com/ODM2/ODM2PythonAPI/blob/master/Examples/Sample.py
odm2
conda channel, based on the new 0.5.0-alpha
odm2api release. See my odm2api_odm2channel
env. Ran into problems b/c the SQLite database needed to be updated to have a SamplingFeature.FeatureGeometryWKT
field; so I added and populated it manually with SQLite Manager
.sfgeometry_em_1
branch, with my overhauls. Using odm2api_dev
env.odm2api_jan31test
). The code also fails the same way with the odm2api
env, but it does still run fine with the odm2api_jan21
env! I'm investigating the differences between those two envs.Author: Emilio Mayorga
In [1]:
import os
from odm2api.ODMconnection import dbconnection
odm2db_fpth = os.path.join('data', 'ODM2.sqlite')
session_factory = dbconnection.createConnection('sqlite', odm2db_fpth, 2.0)
In [2]:
from odm2api.ODM2.services.readService import ReadODM2
read = ReadODM2(session_factory)
In [3]:
allVars = read.getVariables()
for x in allVars:
print('{}: {}'.format(x.VariableCode, x.VariableNameCV))
In [4]:
allPeople = read.getPeople()
if allPeople:
for x in allPeople:
print('{} {}'.format(x.PersonFirstName, x.PersonLastName))
allaff = read.getAffiliations()
if allaff:
for x in allaff:
print('{}: {}'.format(x.PersonObj.PersonFirstName, x.OrganizationID))
In [5]:
try:
siteFeatures = read.getSamplingFeatures(type='Site')
numSites = len(siteFeatures)
for x in siteFeatures:
print(': '.format(x.SamplingFeatureCode, x.SamplingFeatureName))
except Exception as e:
print('Unable to demo getSamplingFeatures(type="Site")\n{}'.format(e))
In [6]:
read.getSamplingFeatures()
Out[6]:
In [7]:
read.getSamplingFeatures(codes=['USU-LBR-Mendon'])
Out[7]:
In [8]:
sf_lst = read.getSamplingFeatures(codes=['USU-LBR-Mendon'])
vars(sf_lst[0])
Out[8]:
In [9]:
sf = sf_lst[0]
sf
Out[9]:
In [10]:
print(type(sf))
print(type(sf.FeatureGeometryWKT), sf.FeatureGeometryWKT)
In [11]:
table = """
<!DOCTYPE html>
<html>
<head>
<style>
table {{
width:100%;
}}
table, th, td {{
border: 1px solid black;
border-collapse: collapse;
}}
th, td {{
padding: 5px;
text-align: left;
}}
table#t01 tr:nth-child(odd) {{
background-color: #eee;
}}
table#t01 tr:nth-child(even) {{
background-color:#fff;
}}
</style>
</head>
<body>
<table id="t01">
<tr>
<td>Code</td>
<td>{}</td>
</tr>
<tr>
<td>TypeCV</td>
<td>{}</td>
</tr>
<tr>
<td>Name</td>
<td>{}</td>
</tr>
</table>
</body>
</html>
""".format
In [12]:
import folium
lon, lat = sf.Longitude, sf.Latitude
m = folium.Map(location=[lat, lon], zoom_start=16)
icon = folium.Icon(color='orange', icon='info-sign', prefix='glyphicon')
width, height = 310, 130
html = table(sf.SamplingFeatureCode, sf.SamplingFeatureTypeCV, sf.SamplingFeatureName)
iframe = folium.IFrame(html, width=width, height=height)
popup = folium.Popup(iframe)
folium.Marker(location=[lat, lon], icon=icon, popup=popup).add_to(m)
m
Out[12]:
In [13]:
read.getResults()
Out[13]:
In [14]:
firstResult = read.getResults()[0]
firstResult.FeatureActionObj.ActionObj
Out[14]:
In [15]:
try:
# Call getResults, but return only the first result.
firstResult = read.getResults()[0]
action_firstResult = firstResult.FeatureActionObj.ActionObj
print('The FeatureAction object for the Result is: {}'.format(firstResult.FeatureActionObj))
print('The Action object for the Result is: {}'.format(action_firstResult))
print(
'\nThe following are some of the attributes for the Action that created the Result: \n' +
'ActionTypeCV: ' + action_firstResult.ActionTypeCV + '\n' +
'ActionDescription: ' + action_firstResult.ActionDescription + '\n' +
'BeginDateTime: ' + str(action_firstResult.BeginDateTime) + '\n' +
'EndDateTime: ' + str(action_firstResult.EndDateTime) + '\n' +
'MethodName: ' + action_firstResult.MethodObj.MethodName + '\n' +
'MethodDescription: ' + action_firstResult.MethodObj.MethodDescription
)
except Exception as e:
print('Unable to demo Foreign Key Example: {}'.format(e))
In [16]:
tsResult = read.getResults(ids=[1])[0]
type(tsResult), vars(tsResult)
Out[16]:
Why are ProcessingLevelObj
, VariableObj
and UnitsObj
objects not shown in the above vars()
listing!? They are actually available, as demonstrated in much of the code below.
In [17]:
try:
tsResult = read.getResults(ids=[1])[0]
# Get the site information by drilling down.
sf_tsResult = tsResult.FeatureActionObj.SamplingFeatureObj
print('Some of the attributes for the TimeSeriesResult retrieved using getResults(ids=[]): \n' +
'ResultTypeCV: ' + tsResult.ResultTypeCV + '\n' +
# Get the ProcessingLevel from the TimeSeriesResult's ProcessingLevel object.
'ProcessingLevel: ' + tsResult.ProcessingLevelObj.Definition + '\n' +
'SampledMedium: ' + tsResult.SampledMediumCV + '\n' +
# Get the variable information from the TimeSeriesResult's Variable object.
'Variable: ' + tsResult.VariableObj.VariableCode + ': ' + tsResult.VariableObj.VariableNameCV + '\n' +
'AggregationStatistic: ' + tsResult.AggregationStatisticCV + '\n' +
# Get the site information by drilling down.
'Elevation_m: ' + str(sf_tsResult.Elevation_m) + '\n' +
'SamplingFeature: ' + sf_tsResult.SamplingFeatureCode + ' - ' +
sf_tsResult.SamplingFeatureName)
except Exception as e:
print('Unable to demo Example of retrieving Attributes of a time Series Result: {}'.format(e))
In [18]:
tsValues = read.getResultValues(resultids=[1]) # Get the values for a particular TimeSeriesResult.
tsValues.set_index('valuedatetime', inplace=True)
tsValues.head() # Return type is a pandas dataframe.
Out[18]:
In [19]:
%matplotlib inline
import matplotlib.pyplot as plt
from matplotlib import dates
fig, ax = plt.subplots(figsize=(11, 2.25))
tsValues['datavalue'].plot(ax=ax)
ax.set_ylabel('{} ({})'.format(
tsResult.VariableObj.VariableNameCV,
tsResult.UnitsObj.UnitsAbbreviation))
ax.set_xlabel('')
ax.xaxis.set_minor_locator(dates.MonthLocator())
ax.xaxis.set_minor_formatter(dates.DateFormatter('%b'))
ax.xaxis.set_major_locator(dates.YearLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n%Y'))
ax.grid(which='major', axis='y')
ax.grid(which='minor', axis='x')