from awips.dataaccess import DataAccessLayer
DataAccessLayer.changeEDEXHost("edex-cloud.unidata.ucar.edu")
dataTypes = DataAccessLayer.getSupportedDatatypes()
list(dataTypes)

"""
Explanation: This example covers the callable methods of the Python AWIPS DAF when working with gridded data.  We start with a connection to an EDEX server, then query data types, then grid names, parameters, levels, and other information. Finally the gridded data is plotted for its domain using Matplotlib and Cartopy.
DataAccessLayer.getSupportedDatatypes()
getSupportedDatatypes() returns a list of available data types offered by the EDEX server defined above.
End of explanation
"""


request = DataAccessLayer.newDataRequest()
request.setDatatype("grid")
available_grids = DataAccessLayer.getAvailableLocationNames(request)
available_grids.sort()
list(available_grids)

"""
Explanation: DataAccessLayer.getAvailableLocationNames()
Now create a new data request, and set the data type to grid to request all available grids with getAvailableLocationNames()
End of explanation
"""


request.setLocationNames("RAP13")
availableParms = DataAccessLayer.getAvailableParameters(request)
availableParms.sort()
list(availableParms)

"""
Explanation: DataAccessLayer.getAvailableParameters()
After datatype and model name (locationName) are set, you can query all available parameters with getAvailableParameters()
End of explanation
"""


request.setParameters("T")
availableLevels = DataAccessLayer.getAvailableLevels(request)
for level in availableLevels:
    print(level)

"""
Explanation: DataAccessLayer.getAvailableLevels()
Selecting "T" for temperature.
End of explanation
"""


request.setLevels("2.0FHAG")

"""
Explanation: 0.0SFC is the Surface level
FHAG stands for Fixed Height Above Ground (in meters)
NTAT stands for Nominal Top of the ATmosphere
BL stands for Boundary Layer, where 0.0_30.0BL reads as 0-30 mb above ground level  
TROP is the Tropopause level

request.setLevels()
For this example we will use Surface Temperature
End of explanation
"""


cycles = DataAccessLayer.getAvailableTimes(request, True)
times = DataAccessLayer.getAvailableTimes(request)
fcstRun = DataAccessLayer.getForecastRun(cycles[-1], times)

"""
Explanation: DataAccessLayer.getAvailableTimes()

getAvailableTimes(request, True) will return an object of run times - formatted as YYYY-MM-DD HH:MM:SS
getAvailableTimes(request) will return an object of all times - formatted as YYYY-MM-DD HH:MM:SS (F:ff)
getForecastRun(cycle, times) will return a DataTime array for a single forecast cycle.
End of explanation
"""


response = DataAccessLayer.getGridData(request, [fcstRun[-1]])
for grid in response:
    data = grid.getRawData()
    lons, lats = grid.getLatLonCoords()
    print('Time :', str(grid.getDataTime()))

print('Model:', str(grid.getLocationName()))
print('Parm :', str(grid.getParameter()))
print('Unit :', str(grid.getUnit()))
print(data.shape)

"""
Explanation: DataAccessLayer.getGridData()
Now that we have our request and DataTime fcstRun arrays ready, it's time to request the data array from EDEX.
End of explanation
"""


%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
import numpy as np
import numpy.ma as ma
from scipy.io import loadmat
def make_map(bbox, projection=ccrs.PlateCarree()):
    fig, ax = plt.subplots(figsize=(16, 9),
                           subplot_kw=dict(projection=projection))
    ax.set_extent(bbox)
    ax.coastlines(resolution='50m')
    gl = ax.gridlines(draw_labels=True)
    gl.xlabels_top = gl.ylabels_right = False
    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER
    return fig, ax

cmap = plt.get_cmap('rainbow')
bbox = [lons.min(), lons.max(), lats.min(), lats.max()]
fig, ax = make_map(bbox=bbox)
cs = ax.pcolormesh(lons, lats, data, cmap=cmap)
cbar = fig.colorbar(cs, extend='both', shrink=0.5, orientation='horizontal')
cbar.set_label(grid.getLocationName().decode('UTF-8')  +" " \
               + grid.getLevel().decode('UTF-8') + " " \
               + grid.getParameter().decode('UTF-8') \
               + " (" + grid.getUnit().decode('UTF-8') + ") " \
               + "valid " + str(grid.getDataTime().getRefTime()))

"""
Explanation: Plotting with Matplotlib and Cartopy
1. pcolormesh
End of explanation
"""


fig2, ax2 = make_map(bbox=bbox)
cs2 = ax2.contourf(lons, lats, data, 80, cmap=cmap,
                  vmin=data.min(), vmax=data.max())
cbar2 = fig2.colorbar(cs2, extend='both', shrink=0.5, orientation='horizontal')
cbar2.set_label(grid.getLocationName().decode('UTF-8')  +" " \
               + grid.getLevel().decode('UTF-8') + " " \
               + grid.getParameter().decode('UTF-8') \
               + " (" + grid.getUnit().decode('UTF-8') + ") " \
               + "valid " + str(grid.getDataTime().getRefTime()))

"""
Explanation: 2. contourf
End of explanation
"""


