from siphon.catalog import TDSCatalog
cat = TDSCatalog('http://thredds-aws.unidata.ucar.edu/thredds/radarServer/catalog.xml')
list(cat.catalog_refs)

"""
Explanation: Using Siphon to get NEXRAD Level 2 data from a TDS
Objectives:

Learn more about Siphon
Use the RadarServer class to retrieve radar data from a TDS
Plot this data using numpy arrays and matplotlib

In this example, we'll focus on interacting with the Radar Query Service to retrieve radar data.
But first!
Bookmark these resources for when you want to use Siphon later!
+ latest Siphon documentation
+ Siphon github repo
+ TDS documentation
Querying the server
First, we point at the top level of the Radar Query Service (the "Radar Server") to see what radar collections are available:
End of explanation
"""


from siphon.radarserver import RadarServer
rs = RadarServer(cat.catalog_refs['S3 NEXRAD Level II'].href)

"""
Explanation: Next we create an instance of the RadarServer object to point at one of these collections. This downloads some top level metadata and sets things up so we can easily query the server.
End of explanation
"""


print(sorted(rs.variables))

"""
Explanation: We can use rs.variables to see a list of radar products available to view from this access URL.
End of explanation
"""


print(sorted(rs.stations))

rs.stations['KTLX']

"""
Explanation: We can also see a list of the stations. Each station has associated location information.
End of explanation
"""


from datetime import datetime
query = rs.query()
query.stations('KTLX').time(datetime.utcnow())

"""
Explanation: Next, we'll create a new query object to help request the data. Using the chaining methods, let's ask for the volume from radar TLX (Oklahoma City) for the current time. We see that when the query is represented as a string, it shows the encoded URL.
End of explanation
"""


rs.validate_query(query)

"""
Explanation: The query also supports time range queries, queries for closest to a lon/lat point, or getting all radars within a lon/lat box.
We can use the RadarServer instance to check our query, to make sure we have required parameters and that we have chosen valid station(s) and variable(s).
End of explanation
"""


catalog = rs.get_catalog(query)

"""
Explanation: Make the request, which returns an instance of TDSCatalog. This handles parsing the catalog
End of explanation
"""


catalog.datasets

"""
Explanation: We can look at the datasets on the catalog to see what data we found by the query. We find one volume file in the return
End of explanation
"""


ds = list(catalog.datasets.values())[0]
ds.access_urls

"""
Explanation: Exercise: Querying the radar server
We'll work through doing some more queries on the radar server. Some useful links:
- RadarQuery documentation
- Documentation on Python's datetime.timedelta
See if you can write Python code for the following queries:
Get the volume for 3 days ago from the radar nearest to Hays, KS (lon -99.324403, lat 38.874929). No map necessary!
Get the volumes the last two hours from all of the radars in Wyoming (call it the bounding box with lower left corner 41.008717, -111.056360 and upper right corner 44.981008, -104.042719)
Pulling out the data
We can pull that dataset out of the dictionary and look at the available access URLs. We see URLs for OPeNDAP, CDMRemote, and HTTPServer (direct download).
End of explanation
"""


import matplotlib.pyplot as plt
import pyart
%matplotlib inline

radar = pyart.io.read_nexrad_cdm(ds.access_urls['OPENDAP'])
display = pyart.graph.RadarDisplay(radar)
fig = plt.figure(figsize=(6, 5))

# plot super resolution reflectivity
ax = fig.add_subplot(111)
display.plot('reflectivity', 0, title='NEXRAD Reflectivity',
             vmin=-32, vmax=64, colorbar_label='', ax=ax)
display.plot_range_ring(radar.range['data'][-1]/1000., ax=ax)
display.set_limits(xlim=(-500, 500), ylim=(-500, 500), ax=ax)

"""
Explanation: We need the OPENDAP link to feed to pyart:
We pull out the variables we need for azimuth and range, as well as the data itself.
End of explanation
"""


