#----------------------------------------------------------------------
# Read and plot the given 2D variable read off a GRIB2 file 
# using PyNIO and matplotlib.
#
# See grib2_plot_var_ngl.py for a PyNGL example.
#----------------------------------------------------------------------
import numpy as np
import Nio
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

# Read data
dir      = "../Data/"
filename = "gdas1.t18z.sfluxgrbf03.grib2"
a   = Nio.open_file("%s/%s" %(dir,filename))

var_name = "TMP_P0_L103_GGA0"
var = a.variables[var_name][:]
lat = a.variables["lat_0"][:]
lon = a.variables["lon_0"][:]

title = ("%s : %s") % (filename,var_name)

#  print var.min(),var.max()

# create figure, add axes
fig = plt.figure(figsize=(8,10))
ax  = fig.add_axes([0.1,0.1,0.8,0.8])
ax.set_title(title)

map = Basemap(projection='cyl',llcrnrlat=lat.min(),urcrnrlat=lat.max(),
              resolution='l',  llcrnrlon=lon.min(),urcrnrlon=lon.max())

#-- convert latitude/longitude 1D arrays to 2D.
lon2d, lat2d = map(*np.meshgrid(lon,lat))

map.drawcoastlines()
cf = map.contourf(lon2d,lat2d,var)
cb = map.colorbar(cf,"bottom", size="7%", pad="10%")

#   plt.show()
plt.savefig("grib2_plot_%s_mpl.png" % var_name)
plt.close(fig)
