def extractVerticalSection(nc,dataVar,vertSection,tIndex,coordVal):
    """ Takes five arguments; the NetCDF dataset, the variable object, the 
    string reprenting verticle setion, the index along the time axis and the 
    index along the latitude/longitude. Using the arguments it extracts returns
    the data, from a NetCDF file"""
    
    import netcdfUtils
    # Find the number of dimensions for the data variable
    numDims = len(dataVar.dimensions)
    
    # check number of dimensions and raise error if they are not 2,or 3,or 4  
    if numDims < 3 or numDims > 4:
        raise ValueError("Cannot extract data from variable with %d dimensions" % numDims)
    # Check if the longitude, latitude and vertical dimensions are present
    lonVar = netcdfUtils.findLongitudeVar(nc, dataVar)
    latVar = netcdfUtils.findLatitudeVar(nc, dataVar)
    zVar=netcdfUtils.findVerticalVar(nc,dataVar)
    #raise error if the longitude, latitude and vertical dimensions are abscent
    if lonVar is None or latVar is None or zVar is None:
        raise ValueError("Cannot extract map data if longitude, latitude and Vertical dimensios are abscent")
    # change longitutude value from range (-180 to 180) into (0 to 360)
    if vertSection=='NS':
        #Map the slicing longitude from -180-to-180 to 0-360
        if min(lonVar[:])>=0:
            if coordVal<=0:
                coordVal=coordVal+180
            else:
                coordVal=coordVal+180        
     #the dimensions present are time, vertical, latitude or longitude
    if vertSection=='NS'and numDims == 4:
        coordVar=netcdfUtils.findLongitudeVar(nc, dataVar) 
        coordIndex=utils.findNearestIndex(coordVar,coordVal)
        return dataVar[tIndex,:,:,coordIndex]
    # the dimensions present must be vertical, latitude or longitude
    elif vertSection=='NS'and numDims == 3: 
        coordVar=netcdfUtils.findLongitudeVar(nc, dataVar) 
        coordIndex=utils.findNearestIndex(coordVar,coordVal)          
        return dataVar[:,:,coordIndex]
    # the dimensions present are time, vertical, latitude & longitude in that order
    if vertSection=='EW'and numDims == 4:
        coordVar=netcdfUtils.findLatitudeVar(nc, dataVar) 
        coordIndex=utils.findNearestIndex(coordVar,coordVal)       
        return dataVar[tIndex,:,coordIndex,:]
    # the dimensions present must be vertical, latitude & longitude in that order
    elif vertSection=='EW'and numDims == 3:
        coordVar=netcdfUtils.findLatitudeVar(nc, dataVar) 
        coordIndex=utils.findNearestIndex(coordVar,coordVal)  
        return dataVar[:,coordIndex,:]
def findNearestLonIndex(nc,dataVar,lonval):
    """ Searches through longitude values for the target value, returning the index
    of the longitude value that is closest numerically to the target value.
    If more than one longitude value is equally close to the target, the index
    of the first value will be returned. """
    import utils
    import netcdfUtils
    # map the longitutude value from range (-180 to 180) onto (0 to 360) in the data file
    coordval=netcdfUtils.findLongitudeVar(nc,dataVar)
    if min(coordval[:])>=0:
        #check if the latitude value is within the latitude range
       if lonval<=0:
           lonval=lonval+180
       else:
           lonval=lonval+180  
    # check if the Variable object representing the latitude axis exists in the netcdf file  
    if coordval is None:
        raise ValueError("No Variable object for the longitude axis exists in the netcdf file")
    #create an array of longitude values from where to search
    lonvals=coordval[:]
    #find the index of the given longitudevalue and check if it exists
    lonIndex=utils.findNearestIndex(lonvals,lonval) 
    #if no index is found
    if lonIndex is None:
        raise ValueError("No index value found for the longitude value entered")
    #longitude index value   
    return lonIndex 
def plotMap(vfile,ufile,varnameV,varnameU, tIndex, zIndex):
    """ TODO: add a docstring! """
    lonValues=[]
    ncV = netCDF4.Dataset(vfile)
    ncU = netCDF4.Dataset(ufile)
    dataVarV = ncV.variables[varnameV]
    dataVarU = ncU.variables[varnameU]
    # Extract the required data
    dataV = extract.extractMapData(ncV, dataVarV, tIndex, zIndex)
    dataU = extract.extractMapData(ncU, dataVarU, tIndex, zIndex)
    
    # Find the longitude and latitude values
    lonVar = netcdfUtils.findLongitudeVar(ncV, dataVarV)
    lonVals = lonVar[:]
    if (lonVals>180).all():
        lonValues.append(lonVals-360)
    lonValues.append(lonVals)
    latVar = netcdfUtils.findLatitudeVar(ncV, dataVarV)
    latVals = latVar[:]
    
    
    
    #title = "Plot of %s" % netcdfUtils.getTitle(dataVarV)
    
    #plotting.displayMapPlot(dataV, lonVals, latVals, title)
    plotting.displayWindMapPlot(dataV,dataU, lonVals, latVals)
def extractMapData(nc, dataVar, tIndex, zIndex):
    """ TODO: add a docstring! """
    # Find the number of dimensions for the data variable
    numDims = len(dataVar.dimensions)
    if numDims < 2 or numDims > 4:
        raise ValueError("Cannot extract data from variable with %d dimensions" % numDims)
    
    # Check that longitude and latitude variables are present
    lonVar = netcdfUtils.findLongitudeVar(nc, dataVar)
    latVar = netcdfUtils.findLatitudeVar(nc, dataVar)
    if lonVar is None or latVar is None:
        raise ValueError("Cannot extract map data if longitude and latitude are not present")
    
    # If this is a four-dimensional variable, assume that there are t,z,y,x axes, in this order
    if numDims == 4:
        return dataVar[tIndex,zIndex]
    elif numDims == 3:
        # We don't know if the first dimension is t or z
        tVar = netcdfUtils.findTimeVar(nc, dataVar)
        if tVar is None:
            # We assume the first dimension is z
            return dataVar[zIndex]
        else:
            # We assume the first dimension is t
            return dataVar[tIndex]
    else:
        # numDims must be 2
        return dataVar[:]
def plotTimeseries(filename,varIdentifier,lonVal,latVal,zVal):
    """Takes five aruguments i.e. a string representing location of NetCDF file,
    variable identifier, the longitude and latitude values in degress as well as
    the value of the vertical axis in the units used in the data file
    (this is ignored if the data variable has no vertical dimension). Uses
    the extractTimeseries() function in the extract module and plot using the 
    displayTimeseriesPlot() function in the plotting module."""
    import netcdfUtils
    import netCDF4 
    import plotting
    #A netCDF4 dataset Object
    nc=netCDF4.Dataset(filename) 
    # A varible object representing a data variable (e.g. sst)
    dataVar=nc.variables[varIdentifier] 
    # Check that longitude,latitude, vertical and time variables are present
    lonVar = netcdfUtils.findLongitudeVar(nc, dataVar)
    latVar = netcdfUtils.findLatitudeVar(nc, dataVar)
    timeVar=netcdfUtils.findTimeVar(nc,dataVar)
    
    #check if the file has latitude, longitude and time dimensions
    if lonVar is None or latVar is None or timeVar is None:
        raise ValueError("Cannot extract map data if longitude, latitude & time are abscent")
   
    #extract data as well as the vertical and longitude/latitude coordinates      
    data=extract.extractTimeseries(nc,dataVar,lonVal,latVal,zVal) 
    # get the title of the plot
    title=netcdfUtils.getTitle(dataVar)
    #plot the data against time
    plotting.displayTimeseriesPlot(nc,dataVar,data[0],data[1],title)
       
    return
#### Here are some test functions.
#### Simply run this script to run them.

#if __name__ == '__main__':
    #plotMap("POLCOMS.nc", "POT", 0,0)
     #plotMap("C:/Users/Developer202/Desktop/MWR/Data/Reanalysis/Surface/vwnd.mon.mean.nc","vwnd",800,0)
     #plotMap("C:/Users/Developer202/Desktop/MWR/Data/Reanalysis/Surface/uwnd.mon.mean.nc","uwnd",800,0)
    #plotMap("GlobModel_temp.nc", "ta", 0,5)
    #plotMap("GlobModel_ozone.nc", "colo3", 0,5)
    #plotMap("rfe2015_02_seas_anom.nc","rfe",0,5)
    #plotMap("sst.day.mean.2014.v2.nc","sst",0,5)
    #plotMap("FOAM_Natl.nc", "ssh", 0,0)
    #plotMap("HadCEM.nc", "salinity", 0,10)
    # The OSTIA dataset is large, so this test can be slow.  Uncomment
    # this line to run it
    #plotMap("OSTIA.nc", "analysed_sst", 0,0)
    
def plotVerticalSection(filename,varIdentifier,vertSection,coordVal,tIndex):
    """Takes five aruguments i.e. a string representing location of NetCDF file,
    variable identifier, string indicating whether vertical section is 
    North-South (NS) or East-West (EW), the value of latitude/longitude depending
    on EW or NS, and the index along the time axis for which to get the data. Uses 
    the extractVerticalSection() function from the extract module to extract data.
    Plots using the displayVertSectionPlot() function from the plotting module."""
    import netCDF4
    import netcdfUtils
    import plotting
    nc=netCDF4.Dataset(filename) #A netCDF4 dataset Object
    dataVar=nc.variables[varIdentifier] # A varible object representing a data variable ('lat' or 'latitude')
    # Check that longitude,latitude, vertical and time variables are present
    lonVar = netcdfUtils.findLongitudeVar(nc, dataVar)
    latVar = netcdfUtils.findLatitudeVar(nc, dataVar)
    zVar=netcdfUtils.findVerticalVar(nc,dataVar)
    #check if string that indicate vertical section is EW or NS else raise error
    if vertSection!='NS'and vertSection!='EW':
        raise ValueError("Only NS or EW can be used to indicate Vertical section") 
    # if the vertical section identifier is North-South get latitudes
    if vertSection=='NS':
        #check if the slicing longitude is within the range of values
        if coordVal<-180 or coordVal>180:
            raise ValueError("The  Longitude values range from -180(180W) to 180(180E)") 
        #get the latitude values for the x axis   
        coordValues=latVar[:]
    # if the vertical section identifier is East-West get longitudes    
    elif vertSection=='EW':
        #check if the slicing latitude is within the range of values
        if coordVal<-90 or coordVal>90:
            raise ValueError("The Latitude values range from -90(90S) to +90(90N)") 
        #get the longitude values for the x axis    
        coordValues=lonVar[:]
    #check if the latitude, longitude and vertical dimesions are present in file    
    if lonVar is None or latVar is None :
        raise ValueError("Cannot extract map data if longitude and latitude are not present")
    if zVar is None:
        raise ValueError("Cannot extract map data if Vertical dimension is not present") 
    #extract data as well as the vertical and longitude/latitude coordinates      
    data=extract.extractVerticalSection(nc,dataVar,vertSection,tIndex,coordVal) 
    #get the title of the plot
    title=netcdfUtils.getTitle(dataVar)
    #plot the exrated data using the displayVertSectionPlot() from plotting module
    plotting.displayVertSectionPlot(data,zVar,coordValues,title,vertSection,coordVal)
    return  
def extractTimeseries(nc,dataVar,lonVal,latVal,zVal):
    """ Takes five arguments; the NetCDF dataset, the variable object, the 
    longitude value, the latitude value and the vertical value and use them to 
    extracts data and time values at the point described. It returns the data of 
    the  and variable represented by the variable object the time values for 
    each point described by the longitude, latitude and vertical values in the
    NetCDF file"""
    # Find the number of dimensions for the data variable
    numDims = len(dataVar.dimensions)
    
    # Check if the number of dimensions and raise error if they are not 3 or 4  
    if numDims < 3 or numDims > 4:
        raise ValueError("Cannot extract data from variable with %d dimensions" % numDims)
    # Check if longitude, latitude and vertical dimensions are present
    lonVar = netcdfUtils.findLongitudeVar(nc, dataVar)
    latVar = netcdfUtils.findLatitudeVar(nc, dataVar)
    timeVar=netcdfUtils.findTimeVar(nc,dataVar)
    zVar=netcdfUtils.findVerticalVar(nc,dataVar)
    timeVal=timeVar[:]
    # check if the longitude, latitude or the time dimension is abscent and raise error
    if lonVar is None or latVar is None or timeVar is None:
        raise ValueError("Cannot extract map data if longitude, latitude and time dimensios are abscent")
    
   # map the longitutude value from range (-180 to 180) onto (0 to 360) in the data file
    #lonVal=lonVal+180 
    if min(lonVar[:])>=0:
        if lonVal<0:
            lonVal=lonVal+180
    # if the dimensions are 4 i.e. time,vertical,latitude and longitude 
    if numDims == 4:
         #get the vertical,longitude and latitude indices
        lonIndex=utils.findNearestIndex(lonVar,lonVal)
        latIndex=utils.findNearestIndex(latVar,latVal)
        zIndex=utils.findNearestIndex(zVar,zVal)
        return dataVar[:,zIndex,latIndex,lonIndex],timeVal
    # if the dimensions are 3 ie time, latitude and longitude
    elif numDims == 3: 
        #get the longitude and latitude indices
        lonIndex=utils.findNearestIndex(lonVar,lonVal)
        latIndex=utils.findNearestIndex(latVar,latVal)         
        return dataVar[:,latIndex,lonIndex],timeVal