datafile = "~/CMEMS_INSTAC/INSITU_MED_NRT_OBSERVATIONS_013_035/history/mooring/IR_TS_MO_61198.nc"

import os
datafile = os.path.expanduser(datafile)

"""
Explanation: The goal is to see how we can read the data contained in a netCDF file. Several possibilities will be examined.
Reading a local file
Let's assume we have downlowded a file from CMEMS. We define the directory and the file name. datafile have to be adapted according to your case.
End of explanation
"""


import netCDF4
ds = netCDF4.Dataset(datafile, 'r')

"""
Explanation: To read the file we need the netCDF4 interface for python.
End of explanation
"""


ds

"""
Explanation: where the first argurment of the files and 'r' indicates that it's open for reading ('w' would be used for writing).<br/> 
ds contains all the information about the dataset:
* Metadata (global attributes)
* Dimensions
* Variables
Metadata
End of explanation
"""


print 'Institution: ' + ds.institution
print 'Reference: ' + ds.institution_references

"""
Explanation: We can access the global attributes individually:
End of explanation
"""


time = ds.variables['TIME']
temperature = ds.variables['TEMP']

"""
Explanation: Data
Now we want to load some of the variables: we use the ds.variables
End of explanation
"""


temperature

"""
Explanation: Let's examine the variable temperature
End of explanation
"""


temperature_values = temperature[:]
time_values = time[:]

"""
Explanation: This means that the variable depends on two dimensions: time and depth. We also know the long_name, standard_name, units, and other useful pieces of information concerning the temperature.
To get the values corresponding to the variables, the synthax is:
End of explanation
"""


print 'Time units: ' + time.units
print 'Temperature units: ' + temperature.units

"""
Explanation: To get the variable attributes:
End of explanation
"""


%matplotlib inline
import matplotlib.pyplot as plt
plt.plot(temperature)
plt.show()

"""
Explanation: Quality flags
Just a quick plot to see everything is fine. More details about the plots will be given later.
End of explanation
"""


temperatureQC = ds.variables['TEMP_QC']
plt.plot(temperatureQC[:])
plt.show()

"""
Explanation: It seems that we have not taken into accound the quality flags of the data. We can load the corresponding variable TEMP_QC.
End of explanation
"""


print 'Flag values: ' + str(temperatureQC.flag_values)
print 'Flag meanings: ' + temperatureQC.flag_meanings

"""
Explanation: The meaning of the quality flags is also stored in the file.
End of explanation
"""


plt.plot(temperature[(temperatureQC[:, 0] == 1), 0])
plt.show()

"""
Explanation: Now we will generate a new plot of the time series using only data with QF = 1.
End of explanation
"""


nc.close()

"""
Explanation: The resulting plot now seems correct, with values ranging roughly between 10 and 28ºC.
Last thing to remember: close the netCDF file!
End of explanation
"""


