Loading a field from a netCDF file

Useful hints
Post Reply
User avatar
joleenf
Posts: 1123
Joined: Mon Jan 19, 2009 7:16 pm

Loading a field from a netCDF file

Post by joleenf »

I am putting this unofficial version of loading a netCDF file from a script on the forum because a number of my colleagues have found this useful. Right now, I have this function in my jython library and it allows me to repeatedly display data, load data, without having to use the click and point architecture. Documentation is at the top, access using ?getGridFlatField.__doc__ from the jython shell or just read it. Main point is that this returns a FlatField (2D Grid) for display and a description of the field that can be used for a label.

Code: Select all

#=======================================================================================
def getGridFlatField(fileName,fieldLongName,dataSelection=None, sourceType = 'netcdf.grid'):
   """
     Simplistic reading of netCDF file.  Extra functionality can be added as
     needed.

     myField, dataDescription = readHDFnetCDF(fileName, fieldLongName, sourceType='netcdf.grid')

     inputFileName - full user path and name of grid file
     fieldLongName - found using ncdump or hover over field in Field Selector
     dataSelection - an object constructed before calling getGridFlatField which defines a bounding box or data stride
        that reduces size of data loaded.
            for instance
               dataSelection = dataSelection()
               dataSelection.setXStride(10)
               https://www.unidata.ucar.edu/software/idv/docs/javadoc/ucar/unidata/data/DataSelection.html
        Default:  No Special dataSelection, entire grid is loaded.
   
     dataType - netcdf.grid works for files loaded via Grid File(netCDF/GRIB/OpenDAP/GEMPAK)
                data handler
     
     original code from McV forum: 
     http://mcidas.ssec.wisc.edu/forums/viewtopic.php?f=31&t=894&hilit=managedDataSource&sid=1cb1e033255bb28ae0afc9124a69871a
   """

   from os.path import exists

   if exists(fileName):
      try:
         dataSource1 = makeDataSource(fileName, sourceType)
      except:
         raise Exception(sys.exec_info[0])

      if not (dataSource1):
         errorMessage = "Read error loading file:  " + fileName
         raise Exception(errorMessage)
      else:
         dataChoice1 = dataSource1.findDataChoice(fieldLongName)
         if not (dataChoice1):
            errorMessage = "Field not found:  " + fieldLongName
            raise Exception(errorMessage)
         else:
            flatField1 = dataSource1.getData(dataChoice1,None,dataSelection,None)
            dataDescription1 = dataChoice1.getDescription()
   else:
      errorMessage = "File Not Found:  " + fileName
      raise Exception(errorMessage)

   return flatField1, dataDescription1
Post Reply