<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 odm2api sample
Largely from https
Step1:  SamplingFeatures tests
Step2:  Back to the rest of the demo
<ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import sys
import os
import matplotlib.pyplot as plt
from matplotlib import dates
from odm2api.ODMconnection import dbconnection
from odm2api.ODM2.services.readService import *
# Create a connection to the ODM2 database
# ----------------------------------------
odm2db_fpth = '/home/mayorga/Desktop/TylerYeats/ODM2-LittleBear1.sqlite'
session_factory = dbconnection.createConnection('sqlite', odm2db_fpth, 2.0)
read = ReadODM2(session_factory)
# Run some basic sample queries.
# ------------------------------
# Get all of the variables from the database and print their names to the console
allVars = read.getVariables()
for x in allVars:
    print x.VariableCode + ": " + x.VariableNameCV
# Get all of the people from the database
allPeople = read.getPeople()
for x in allPeople:
    print x.PersonFirstName + " " + x.PersonLastName
try:
    print "\n-------- Information about an Affiliation ---------"
    allaff = read.getAllAffiliations()
    for x in allaff:
        print x.PersonObj.PersonFirstName + ": " + str(x.OrganizationID)
except Exception as e:
    print "Unable to demo getAllAffiliations", e
allaff = read.getAllAffiliations()
type(allaff)
Explanation: odm2api sample
Largely from https://github.com/ODM2/ODM2PythonAPI/blob/master/Examples/Sample.py 
- 2/7/2016. Tested successfully with sfgeometry_em_1 branch, with my overhauls. Using odm2api_dev env.
- 2/1 - 1/31. Errors with SamplingFeatures code, with latest odm2api from master (on 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.
- 1/22-20,9/2016.
Emilio Mayorga
End of explanation
from odm2api.ODM2.models import SamplingFeatures
read._session.query(SamplingFeatures).filter_by(SamplingFeatureTypeCV='Site').all()
read.getSamplingFeaturesByType('Site')
# Get all of the SamplingFeatures from the database that are Sites
try:
    siteFeatures = read.getSamplingFeaturesByType('Site')
    numSites = len(siteFeatures)
    for x in siteFeatures:
        print x.SamplingFeatureCode + ": " + x.SamplingFeatureName
except Exception as e:
    print "Unable to demo getSamplingFeaturesByType", e
read.getSamplingFeatures()
read.getSamplingFeatureByCode('USU-LBR-Mendon')
# Now get the SamplingFeature object for a SamplingFeature code
sf = read.getSamplingFeatureByCode('USU-LBR-Mendon')
# vars(sf)
# 1/31/2016: Leads to error with latest from odm2api master:
# "TypeError: vars() argument must have __dict__ attribute"
print sf, "\n"
print type(sf)
print type(sf.FeatureGeometry)
vars(sf.FeatureGeometry)
sf.FeatureGeometry.__doc__
sf.FeatureGeometry.geom_wkb, sf.FeatureGeometry.geom_wkt
type(sf.shape()), sf.shape().wkt
Explanation: SamplingFeatures tests
End of explanation
# Drill down and get objects linked by foreign keys
print "\n------------ Foreign Key Example --------- \n",
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: ", firstResult.FeatureActionObj
    print "The Action object for the Result is: ", 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: ", e
# Now get a particular Result using a ResultID
print "\n------- Example of Retrieving Attributes of a Time Series Result -------"
try:
    tsResult = read.getTimeSeriesResultByResultId(1)
    # Get the site information by drilling down
    sf_tsResult = tsResult.ResultObj.FeatureActionObj.SamplingFeatureObj
    print(
        "Some of the attributes for the TimeSeriesResult retrieved using getTimeSeriesResultByResultID(): \n" +
        "ResultTypeCV: " + tsResult.ResultObj.ResultTypeCV + "\n" +
        # Get the ProcessingLevel from the TimeSeriesResult's ProcessingLevel object
        "ProcessingLevel: " + tsResult.ResultObj.ProcessingLevelObj.Definition + "\n" +
        "SampledMedium: " + tsResult.ResultObj.SampledMediumCV + "\n" +
        # Get the variable information from the TimeSeriesResult's Variable object
        "Variable: " + tsResult.ResultObj.VariableObj.VariableCode + ": " + tsResult.ResultObj.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: ", e
tsResult = read.getTimeSeriesResultByResultId(1)
type(tsResult), vars(tsResult)
vars(tsResult.ResultObj)
# Get the values for a particular TimeSeriesResult
print "\n-------- Example of Retrieving Time Series Result Values ---------"
tsValues = read.getTimeSeriesResultValuesByResultId(1)  # Return type is a pandas dataframe
# Print a few Time Series Values to the console
# tsValues.set_index('ValueDateTime', inplace=True)
tsValues.head()
# Plot the time series
try:
    fig = plt.figure()
    ax = fig.add_subplot(111)
    tsValues.plot(x='ValueDateTime', y='DataValue', kind='line',
                  title=tsResult.ResultObj.VariableObj.VariableNameCV + " at " + 
                        tsResult.ResultObj.FeatureActionObj.SamplingFeatureObj.SamplingFeatureName,
                  ax=ax)
    ax.set_ylabel(tsResult.ResultObj.VariableObj.VariableNameCV + " (" + 
                  tsResult.ResultObj.UnitsObj.UnitsAbbreviation + ")")
    ax.set_xlabel("Date/Time")
    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(True)
except Exception as e:
    print "Unable to demo plotting of tsValues: ", e
Explanation: Back to the rest of the demo
End of explanation
<END_TASK>