#----------------------------------------------------------------------
# Read and plot a variable read off the cfdda_1985013123.v2.nc NetCDF 
# file using PyNIO and matplotlib/basemap.
#
# This example was coded to plot "Temp", which is a "packed" variable.
# You must unpack it before plotting it.
#
# Data is rectilinear, 1 x 28 x 450 x 900   (time x lev x lat x lon)
#
# See cfdda_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 = "cfdda_1985013123.v2.nc"
a        = Nio.open_file("%s/%s" %(dir,filename))

var_name = "Temp"
var = a.variables[var_name]    # var will be a 'NioVariable'
lat = a.variables["y0"][:]
lon = a.variables["x0"][:]

# Unpack the variable
var_unpack =  var.scale_factor * (var[:] - var.add_offset)

# Verify that the min/max of the variable looks good.
print("var_unpack: %g / %g" % (var_unpack.min(),var_unpack.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(("%s : %s") % (filename,var_name))

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()

nt = 0     # "Temp" is a 4D array. Only plot first 
nl = 0     # time step and level
cf = map.contourf(lon2d,lat2d,var_unpack[nt,nl,:,:])
cb = map.colorbar(cf,"bottom", size="7%", pad="10%")

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