%pylab inline
import scipy.io.netcdf

"""
Explanation: We will use matplotlib.pyplot for plotting and scipy's netcdf package for reading the model output. The %pylab inline causes figures to appear in the page and conveniently alias pyplot to plt (which is becoming a widely used alias).
This analysis assumes you changed DAYMAX to some multiple of 5 so that there are multiple time records in the model output.
To see this notebook with figures, see https://gist.github.com/adcroft/2a2b91d66625fd534372.
End of explanation
"""


prog_file = scipy.io.netcdf_file('prog__0001_006.nc')
prog_file.variables

"""
Explanation: We first create a netcdf object, or "handle", to the netcdf file. We'll also list all the objects in the netcdf object.
End of explanation
"""


e_handle = prog_file.variables['e']
print('Description =', e_handle.long_name)
print('Shape =',e_handle.shape)

"""
Explanation: Now we will create a variable object for the "e" variable in the file. Again, I'm labelling it as a handle to distinguish it from a numpy array or raw data.
We'll also look at an "attribute" and print the shape of the data.
End of explanation
"""


plt.pcolormesh( e_handle[0,0] )

"""
Explanation: "e" is 4-dimensional. netcdf files and objects are index [n,k,j,i] for the time-, vertical-, meridional-, zonal-axes.
Let's take a quick look at the first record [n=0] of the top interface [k=0].
End of explanation
"""


plt.pcolormesh( e_handle[0,0], cmap=cm.seismic ); plt.colorbar();

"""
Explanation: The data looks OKish. No scale! And see that "&lt;matplotlib...&gt;" line? That's a handle returned by the matplotlib function. Hide it with a semicolon. Let's add a scale and change the colormap.
End of explanation
"""


import ipywidgets

"""
Explanation: We have 4D data but can only visualize by projecting on a 2D medium (the page). Let's solve that by going interactive!
End of explanation
"""


[e_handle[:,0].min(), e_handle[:,0].max()]

"""
Explanation: We'll need to know the range to fix the color scale...
End of explanation
"""


def plot_ssh(record):
    plt.pcolormesh( e_handle[record,0], cmap=cm.spectral )
    plt.clim(-.5,.8) # Fixed scale here
    plt.colorbar()

ipywidgets.interact(plot_ssh, record=(0,e_handle.shape[0]-1,1));

"""
Explanation: We define a simple function that takes the record number as an argument and then plots the top interface (k=0) for that record. We then use the interact() function to do some magic!
End of explanation
"""


from IPython import display

for n in range( e_handle.shape[0]):
    display.display(plt.gcf())
    plt.clf()
    plot_ssh(n)
    display.clear_output(wait=True)

"""
Explanation: Unable to scroll the slider steadily enough? We'll use a loop to redraw for us...
End of explanation
"""


