NOAA

Geophysical Fluid
Dynamics Laboratory

Skip to: [content] [navigation]
If you are using Navigator 4.x or Internet Explorer 4.x or Omni Web 4.x , this site will not render correctly!

Vis > data > netcdf > NetCDF Utilities

NetCDF Utilities

W R D E X C V (alphabetically)
cfchecker Climate & Forecast (CF) compliance checker
DDI data extraction/combination, metadata editing, conversion
gennet given a netCDF file, generates FORTRAN program to read it
grads2nc a GrADS to netCDF converter
gribtonc a GRIB to netCDF converter (part of Unidata's " decoders")
MexCDF interface for MATLAB (for MATLAB 4, MATLAB 5, MATLAB 6)
MexEPS interface for MATLAB
ncap (NCO) Arithmetic Processor
ncatted (NCO) Attribute Editor
ncbo (NCO) Binary Operator (includes ncadd, ncsubtract, ncmultiply, ncdivide)
nccat utility to concatenate like files along the "record" dimension
nccatm same as nccat, but will concatenate multiple files
nccmp compare metadata and data between two files quickly
ncdiff extract, difference variable(s) from two files
ncdump / ncgen netcdf <--> ASCII translators
ncea (NCO) Ensemble Averager
W R D E X C V
ncecat (NCO) Ensemble Concatenator
ncextr extract a subset of a netCDF file
ncflint (NCO) File Interpolator
NCIR high level (FORTRAN) NetCDFInterface Routines (shells)
ncks (NCO) "Kitchen Sink" to print, extract, crop, combine netCDF data
ncpdq (NCO) Permute Permute Dimensions Quickly
ncra (NCO) Record Averager
ncrcat (NCO) Record Concatenator
ncrename (NCO) variable/dimension/attribute renamer
ncstat calculate min/max, mean along any or all dimensions
nctools stand-alone programs that mimic netCDF routines
ncclamp clamps values in-place using comparison operators
nc_to_vis5d script that converts NetCDF to Vis5d via Ferret
ncwa (NCO) Weighted Averager
ncx.py Python script that extracts arbitrary slices for a single dimension
ncymdhms from filename and time-index, get year, month, day, etc
nrecreset forcibly reset the number of records in a file
ReadNC module for SGI/NAG Iris Explorer
ScientificPython a collection of Python modules with NetCDF support
W R D E X C V

Key
W write
R read
D dump
E edit
X extract / calculate
C combine
V convert


If you need addtional functionality (perhaps something you see in Unidata's collection of user-contributed software), let us know and we will try to accomodate you.

NetCDF Interface Routines

DESCRIPTION :
This is a set of locally (GFDL) written FORTRAN "shell" routines intended to minimize the work required to read and write netCDF files. The "surface area" of contact between the user and netCDF is reduced to a limited number of FORTRAN routines for which the user need only satisfy an argument list. There is no need to make the (many) low-level netCDF API calls. In addition, the use of these routines helps insure a consistent structure which also complies with the COARDS conventions for writing netCDF files, including the use of the Unidata UDUNITS package to ensure a standard representation of units for all coordinate axes and data variables.
Also included are 2 prototype scripts which go through all the motions for compiling and linking some test/demo programs. These scripts work on a T90, T3E, and our SGI's.
(deprecated) Performance can be an issue on the Cray platforms. Beginning with netCDF version 2.4, the use has control over the Cray FFIO layer. Some guidelines for optimizing performance on Crays is available.

In some cases NetCDF files are limited to 2 GB in size. Read more about it at Unidata.

PLUSES :
- insulates the user from the details of the netCDF API
- performs many error checks on metadata to insure COARDS compliance
- insures a level of consistency among files produced
MINUSES :
- obviously, not as flexible, complete, or efficient as one could make it with pure API calls for a specific application

HOW TO INVOKE :

HINTS :

INFO / DOCUMENTATION:

ncdump

DESCRIPTION :
ncdump generates an ASCII representation of a specified netCDFfile on standard output. The ASCII representation is in a language called CDL ("CDF Description Language'") that is quite readable and can serve as input to ncgen, a program that can generate a binary netCDF file from a CDL file. Hence ncgen and ncdump can be used as inverses to transform the data representation between binary and ASCII representations. See the ncgen man page for a description of CDL and netCDF representations.
PLUSES :
- fastest/easiest way to find out what a netCDF file contains
MINUSES :
- dumping data (optional) this way can result in a lot of output (ASCII)

HOW TO INVOKE :

HINTS :

INFO / DOCUMENTATION:

ncgen

DESCRIPTION :
ncgen generates either a netCDF file, or C or Fortran source code to create a netCDF file. The input to ncgen is a description of a netCDF file in CDL ("CDF Description Language'"), perhaps output by ncdump.
PLUSES :
- may be used with ncdump to perform some simple operations on netCDF files
MINUSES :
- dumping data (optional) this way can result in a lot of output (ASCII)

HOW TO INVOKE :

HINTS :

As an example, to rename a dimension in a netCDF file, use ncdump to get a CDL version of the netCDF file, edit the CDL file to change the name of the dimensions, and use ncgen to generate the corresponding netCDF file from the edited CDL file.

INFO / DOCUMENTATION:

gennet

DESCRIPTION :
gennet examines a specified netCDF file and generates a FORTRAN program to read it.
PLUSES :
- a very quick way to create a code to read almost any file
MINUSES :
- kind of mindless:
- defines massive arrays, as if you will read in everything at once
- reading in anything less than an entire variable requires understanding of the netCDF API
- obviously, you have to add code to actually do something with the data
- no error/consistency checks, as in readnc.F (part of the locally written shell routines in the directory /home/jps/pub/netcdf/ )

HINTS :

INFO / DOCUMENTATION:

ncks

DESCRIPTION :
ncks extracts a subset of the data from in.nc and either prints it as ASCII-readable text to the screen, or writes (or pastes) it to out.nc, or both. ncks combines a generic netCDF printer (like a formatted ncdump),extractor (like ncextr), hyperslabber (the nccut specification), and combiner (partial ncpaste implementation) into one command. ncks and ncrename (available from the same FTP site) are intended to perform many common tasks for the rapid manipulation and analysis of netCDF data.
ncks will append variables and attributes from the input file to the output file if the output file is a pre-existing netCDF file whose relevent dimensions conform to dimension sizes of in.nc. The append features of ncks are intented to provide a rudimentary means of adding data from one netCDF file to another, conforming, netCDF file.
PLUSES :
- Can be used to merge data into a file (but - must be conformal)
MINUSES :
* outgoing data is assembled in memory first, so big/long datasets will likely crash; try ncrcat if this is a problem for you -->
- dumping data (optional) this way can result in a lot of output (ASCII)
- When naming conflicts exists between the two files, data in out.nc is usually overwritten by the corresponding data from in.nc. Thus it is recommended that the user backup out.nc in case valuable data is accidentally overwritten.
- output isn't very pretty, but the appearance is partially under user's control of the user with -s switch
HOW TO INVOKE :

INFO / DOCUMENTATION:

ncymdhms

DESCRIPTION :
One common problem with netCDF files is determining the time, in a useful format, corresponding to a given slab of data. This is because netCDF time is generally stored with units such as "hours since 01-01-1970 00:00:00.0" and values like "34,244". Given a netCDF filename and a time index (ie, slice), the utility ncymdhms returns a message translating the time of that slice into year, month, day, hour, minute, second (get it? YMDHMS?).
A FORTRAN-callable version of ncymdhms is also available.
PLUSES :
- handy one liner useful at the command line
MINUSES :
- if a file has more than one time-dimension, the first one encountered which is REAL*8 and has legitimate units for "time" is used

HOW TO INVOKE :

HINTS :
The source code for ncymdhms is in /home/jps/pub/netcdf/util/src/ncymdhms.F, which could be useful in constructing time-stamps within your own application. See the comments at the top for the other code modules needed.

INFO / DOCUMENTATION :

nctools

DESCRIPTION :
The nctools are a collection of stand-alone C programs that allow netCDF users to manipulate netCDF files from the command line. Each nctool mimics a subroutine in the netCDF library in usage and function. The usage syntax follows the netCDF Users Guide - if you type the program name with no arguments, you get the usage and an example. You will need to be familiar with the terminology/components of a netCDF file in order to make the most of these tools. The changes made by any of the tools are applied "in place"; ie, changes are made to the file specified - there is no "output" file.

Here is the list of the (29) tools :
          ncattcopy            ncdimdef         ncvardef

          ncattdel             ncdimid          ncvarget

          ncattget             ncdiminq         ncvarget1

          ncattinq             ncdimrename      ncvargeta

          ncattname                             ncvargetm

          ncattput             ncinquire        ncvarid

          ncattrename          nctypelen        ncvarinq

                                                ncvarput

          nccat                                 ncvarput1

          ncclose                               ncvarputa

          nccopy                                ncvarputm

          nccreate                              ncvarrename
PLUSES :
- handy one liners useful at the command line (and for scripts), especially for renaming or deleting items, and for concatenating files
- (see also nccat, another incarnation of the same concatenation tool, unfortunately by the same name)
MINUSES :
- output of variable values is ASCII, one element per line, which can get voluminous
- concatenation works only for file which are identical in variable names and dimensions and
have a leftmost (C-wise and CDL-wise) unlimited dimension
- most tools will require making a copy of the file, so can be ponderous, especially if several operations are required; see ncrename for a utility which will do multiple rename's at once

HOW TO INVOKE :

HINTS :
  • Beware: many tools overwrite one of the files specified on the command line.
  • Renaming of file components can also be done with ncrename

INFO / DOCUMENTATION :

ncrename

DESCRIPTION :
This utility, part of the NCO utilities written by Charlie Zender at UCAR, renames dimensions, variables, and attributes of a netCDF file. A number of objects can be renamed with one invocation, thus saving reopening and making a new copy of the file for each instance, such as would be necessary with the nctools. You will need to be at least minimally familiar with the terminology/components of a netCDF file in order to make the most of this utility.

PLUSES :
MINUSES :

HOW TO INVOKE :

If "out.nc" is the same as "in.nc", changes are made "in place".
HINTS :
- ncrename will not rename an attribute if an attribute by that name is already attached to the variable.
- If you want to rename an axis, be sure to rename both the dimension and the associated coordinate variable (eg, "-d xx,lon -v xx,lon")
- See also nctools

INFO / DOCUMENTATION :

DDI

DESCRIPTION :

The Data and Dimensions Interface (DDI) transfers data between files, formats, and visualization environments. It works within the specifications of each supported format to promote compatibility. DDI provides the following capabilities:

DDI can also execute as an integrated module in IRIS Explorer or AVS, but we have noticed some problems with that incarnation (can't handle the "record" dimension), and we have a fairly robust netCDF module for Explorer which is a little easier to use (ReadNC).

PLUSES :
- fairly robust ability to select variables, sample/crop, combine with others, output to a file
MINUSES :
- does not transfer the global metadata to the output file
- does not preserve the "record" dimension - "record" axis is output as a non-record axis
- DDI does not seem to be under very active development - little progress since 2000

INFO / DOCUMENTATION :

ncextr

DESCRIPTION :
This netCDF operator extracts a subset of the data from in.cdf and writes it to out.cdf. One can specify either the subset to appear in the output, or the subset to exclude from the output. If no options are specified, then this operator copies the input netCDF to the output netCDF, deleting superfluous dimensions.
ncextr is largely a subset of ncks's functionality.
PLUSES :
-
MINUSES :
-

HOW TO INVOKE :

HINTS :

INFO / DOCUMENTATION :

ncstat

DESCRIPTION :
This netCDF operator computes a statistical summary over one or more dimensions an input netCDF file and writes the result to a new output netCDF file. The statistics inlclude min, max, and mean.

PLUSES :
- easy way to get averages (vertical, zonal, time, etc.)
- calculation is done for all variables employing the selected axis(axes)
MINUSES :
- the axis along which the average is taken is removed; ie, the resultant field has no coordinate location along the averaged axis, so you won't be able to distinguish averages over different ranges (eg, 90-180 deg_E vs. 180-270 deg_E)
- A bug causes spurious bulls-eyes at intervals along left edge of rows of points.
  • Workaround: time averages which account for unevenly spaced time coordinates can be obtained using ncra
- Does not assign any "weighting" to the points; ie, all points are weighted equally, even if they are unevenly spaced
  • Workaround: time averages which account for unevenly spaced time coordinates can be obtained using ncra
- Does not account for "missing_value"'s when computing statistics;
  • Workaround: unless you actually utilize the '_FillValue' feature, add the following argument to the ncstat invocation line: "-f 'missing_value'"

HOW TO INVOKE :

HINTS :

INFO / DOCUMENTATION :

nrecreset

DESCRIPTION :
This netCDF operator allows the user to forcibly reset the number of records in a netCDF file. The main use for this utility is when a job terminates abnormally and does not close the file properly, in which case the data may be present in the file, but the metadata will indicate too few (or no) actual records.

PLUSES :
MINUSES :
HOW TO INVOKE :
HINTS :

INFO / DOCUMENTATION :

ncra

DESCRIPTION :
This netCDF utility computes an average along the record (time) dimension of one or more input netCDF files and writes the result to an output netCDF file. It is part of the NCO utilities written by Charlie Zender at UCAR. There are a number of options, but some of them seem more specific to NCAR's computing facility. Those that are more generally useful are described below.

PLUSES :
MINUSES :

HOW TO INVOKE :

HINTS :
              setenv NETCDF_FFIOSPEC cachea:112:2

INFO / DOCUMENTATION :

ncdiff

DESCRIPTION :
This netCDF operator subtracts the variables in one netCDF file from those in another file. It is part of the NCO utilities written by Charlie Zender at UCAR. There are a number of options, but some of them seem more specific to NCAR's computing facility. Those that are more generally useful are described below.
PLUSES :
- Right now, this is one of the few utilities available for performing mathematical operations on netCDF files/data
MINUSES :
  • Bug: the "-d" option to operate on specific hyperslabs sometimes works incorrectly
  • ncdiff uses the same core as the other NCO utilities, which is optimized to work on one file at a time. This means that ncdiff (and ncea, an ensemble averager) try to ingest the entire first file before performing any operations , which will typically run you out of memory rather quickly, resulting in a "could not malloc" error on the Cray. Two possible workarounds are
    1. to work on a subset of the variables (or just one) and then use ncks to combine them into one file, or
    2. use the -d option to select one time-level at a time, then use ncrcat to concatenate the resulting files
  • Like all the NCO utilities which perform mathematical operations, arithmetic with packed data (ie, 8- or 16-bit binning) is not supported. The operation will proceed, but will be performed on the packed data, not their appropriate expanded representation. The result is not meaningful.

HOW TO INVOKE :

  • The latest build is located in
            /net2/rsz/{linux, irix}/nco/bin
    
  • To get a usage message, type ncdiff with no arguments; an abbreviated version is shown below (Note: "Append" appends variable to file - it does not append to the end of the record dimension):
  • ncdiff [-A] [-O] [-F] [-c] [-D lev] \ 
    
           [-d ...] [-p path] [-r] \ 
    
           [-v ...] [-x] \ 
    
           in_1.nc in_2.nc \ 
    
           out.nc
    
    
    
    -A                   Append to existing output file, if any
    
    -O                   Overwrite existing output file, if any
    
    -F                   Fortran indexing conventions (1-based) for I/O
    
    -v var1[,var2[...]]  Variables to process
    
    -x                   Extract all vars EXCEPT those specified with -v
    
    -d dim,[min][,[max]] Dimension's limits in hyperslab
    
    -p path              Path prefix for all input filenames
    
    -r                   Program version and copyright notice
    
    -c                   Coordinate variables will all be processed
    
    -D lev               Debugging level
    
    in_1.nc in_2.nc      Input files
    
    out.nc               Output file name
    
    
    
    
HINTS :
- To get a usage message at any time, type ncdiff with no arguments
- Note: the "Append" option does not append along the record axis - it is intended to append variables to an existing file

INFO / DOCUMENTATION :

nccat / nccatm

DESCRIPTION :
Concatenate netCDF files along the "record" (or "unlimited") dimension. nccat is an older utility written at the USGS to concatenate 2 files. nccatm is a newer version written here at GFDL which will concatenate multiple files and handle time-coordinate "units" changes between files, and which will run more efficiently on the Cray. The NetCDF files must be identical in variable names and dimensions. Each variable must have a leftmost NC_UNLIMITED record dimension (C-style dimension ordering).

Please use nccatm instead of nccat, or tell us why you must use nccat.
PLUSES :
- very simple, convenient at UNIX command line
MINUSES :
- CAUTION: Both nccat and nccatm write over the first filename listed ! (See ncrcat)

HOW TO INVOKE :

  • First, create a more convenient alias:
  • 
            alias nccatm ~hnv/pub/{linux,irix}/nccatm
    
    
  • Or, add the following directory to your path:
    
            set path=(  ~hnv/pub/{linux,irix}/ )
    
    
  • To get a usage message, type nccatm with no arguments:
  • nccatm [-n] [-v] [-q] infile1 infile2 ... 
           -n   : Use the shell's setting for "NETCDF_FFIOSPEC", otherwise
    
                  it will use the built-in default of "cachea:896:2" (Cray only)
           -v   : Verbose mode; print extensive progress information
           -q   : Quiet mode; no progress output
      infile1   : NetCDF filename for input and output
    infile2 ... : NetCDF filenames for input
    
    
    HINTS :
    - Copy the first file to a new filename, then concatenate the rest onto the end
    - If the input files have different time "units", nccatm will convert to the units of the first file in the sequence
  • For example, if file 1 units="days since 1980-01-01" and file 2 units="days since 1981-01-01", the time-coordinates of file 2 will be adjusted to be consistent with the "units" of file 1. Thus, where blind concatenation would yield time coordinates of "1,2,3,...365,1,2,3,...365", nccatm would instead yield coordinates of "1,2,3...365,366,367,...730".
  • - (deprecated) If you get an error message opening a file on a Cray, this is likely because of the memory usage for cache pages, specified via the NETCDF_FFIOSPEC environment variable. See the "Cray Optimization" page.

    INFO / DOCUMENTATION :

  • URL/Web info : N/A (deprecated)

ncrcat

DESCRIPTION :
This netCDF operator extracts and concatenates record variables across an arbitrary number of netCDF files. It is part of the NCO utilities written by Charlie Zender at UCAR. There are a number of options, but some of them seem more specific to NCAR's computing facility. Those that are more generally useful are described below.
PLUSES :
  • Performs the same concatenation function as nccat / nccatm, but has the added options:
    • output goes to specified filename rather than to first file in list
    • you can select specific variables to process (eg, just "Temperature")
    • you can select specific hyperslabs to process (eg, just the 850 mb level)
  • Performs the same extraction function as ncks, but handles large datasets without running out of memory
MINUSES :
-

HOW TO INVOKE :

  • The latest build is located in
            /net2/rsz/{linux, irix}/nco/bin
    
  • To get a usage message, type ncrcat with no arguments; an abbreviated version is shown below (Note: "Append" appends variable to file - it does not append to the end of the record dimension):
  • ncrcat [-A] [-O] [-F] [-c] [-D lev] \ 
    
           [-d ...] [-p path] [-r] \ 
    
           [-v ...] [-x] \ 
    
           in.nc [...] out.nc
    
    
    
    -A                   Append to existing output file, if any
    
    -O                   Overwrite existing output file, if any
    
    -F                   Fortran indexing conventions (1-based) for I/O
    
    -c                   Coordinate variables will all be processed
    
    -D lev               Debugging level
    
    -d dim,[min][,[max]] Dimension's limits in hyperslab
    
    -p path              Path prefix for all input filenames
    
    -r                   Program version and copyright notice
    
    -v var1[,var2[...]]  Variables to process
    
    -x                   Extract all vars EXCEPT those specified with -v
    
    in.nc...             Input file name(s)
    
    out.nc               Output file name
    
    
    
    
HINTS :
- To get a usage message at any time, type ncrcat with no arguments
- Note: the "Append" option does not append along the record axis - it is intended to append variables to an existing file

INFO / DOCUMENTATION :

gribtonc

DESCRIPTION :
This program decodes GRIB products (embedded in WMO product envelopes) on the NWS High-Resolution Data Service (HRS) feed, writing the decoded products into a single netCDF output file, specified by netCDF_path. In case the output netCDF file does not already exist, the CDL_path must be supplied to specify the structure for the desired netCDF file, which gribtonc creates. The default parame­ ter translation is made according to a definition by UCAR, but the user may supply specific translations in a sepa­ rate file by the -g tabfile option. The user-supplied translations will override the default ones. GRIB prod­ ucts are converted to the units specified for the appro­ priate netCDF variable, if this differs from the units used for the GRIB parameter. A set of CDL files for all the model outputs appearing on the HRS data stream is pro­ vided with gribtonc for use in decoding HRS GRIB data.

PLUSES :
  • very simple to use, just copy the 2 line example below

HOW TO INVOKE :
  • With IRIX or Altix, use the binaries in
        /home/rsz/pub/{irix, altix}/netcdf/decoders-3.0.6/bin
    
  • First, create the conversion table:
  •     gribtocdl -v data.grib > data.cdl
    
  • Then do the actual conversion:
  •     gribtonc -v data.cdl data.nc < data.grib
    

INFO / DOCUMENTATION :

grads2nc

DESCRIPTION :
Converts data files in GrADS format to netCDF format. This provides a means for users with GrADS data to take advantage of the many tools for handling and visualizing netCDF data. Makes an effort to create a NetCDF file that conforms to the COARDS conventions, though GrADS files lack some information to do this.
PLUSES :
- simple to use
MINUSES :
- Does not support :
    • multi-file templates
    • station data
    • GRIB data
    • sequential data, or
    • initial file headers.
- Since GrADS files have no mechanism for documenting "units", assumed values will be forced on the output netCDF file
    • "degrees_E", "degrees_N", and "level" for the X, Y, and Z axes
    • "unknown" for data variables
- Assumes the GrADS 1.5.x control file format ; older or newer versions may or may not parse correctly.

HOW TO INVOKE :

  •     /usr/local/bin/grads2nc (Linux)
        /home/hnv/pub/irix/grads2nc (IRIX)   
    
  • To get a usage message, type grads2nc with no arguments:
  • grads2nc  infile.ctl  outfile.nc  [-n] [-r] [-v | -q]
    -n   Use the shell's setting for "NETCDF_FFIOSPEC", otherwise it 
    
         will use the built-in default of "cachea:896:2" (Cray only). 
    -r   Finds the actual minimum and maximum values for each variable 
    
         instead of using the default "valid_range" of -1e+37 to 1e+37. 
    -v   Verbose mode; print extensive progress information. 
    -q   Quiet mode; no progress output. 
HINTS :

INFO / DOCUMENTATION :

MEXCDF for MATLAB 4 (for MATLAB 5, see below)

DESCRIPTION

MexCDF is a mex-file interface between netCDF and MATLAB that invokes the complete C-Language netCDF interface, as described in the NetCDF Users Guide. This allows MATLAB users to read, write, and manipulate netCDF data files in an efficient manner.

Here are some functions (MATLAB M-files) that are included with MexCDF:

  • whatcdf - lists the netCDF files that are in the current directory and the common data area.
  • inqcdf - an interactive function for finding information about the netCDF file (e.g. dimensions, variables, attributes, etc.).
  • getcdf - an interactive function for extracting data from the netCDF file into the MATLAB workspace.
  • getcdf_batch - a non-interactive version of getcdf.

and then there is the actual mexcdf function which implements all the low-level netCDF calls. The functions listed above use it to provide a higher-level interface.

PLUSES

It's relatively easy to use and supports packed data as well as missing values.
MINUSES

The whatcdf, inqcdf, getcdf, and getcdf_batch functions do not like the ".nc" or ".cdf" extensions on path names. Leave them off when specifying parameters to those functions because they are automatically appended. Also, MexCDF has limited interpretation of the time axis (basically, it's just NOAA PMEL's EPIC conventions or the actual numbers stored with the dimension name). It doesn't seem to consider attributes such as time since some starting value.
HOW TO INVOKE

Add the following two paths to the MATLABPATH environment variable (change first if it doesn't already exist) in a shell (version 4 support only for IRIX):


        setenv MATLABPATH ${MATLABPATH}:/home/hnv/pub/irix/mexcdf-4

        setenv MATLABPATH ${MATLABPATH}:/home/hnv/pub/irix/mexcdf-4/tools

then just run matlab.

HINTS

The pos_data_cdf.m file in the tools directory contains the path to the common data area in which to look for netCDF files. This path is used by the whatcdf, inqcdf, getcdf, and getcdf_batch functions in addition to the current directory and whatever is specified as a path in a parameter. Try MexEPS if more sophisticated time manipulation is necessary, although it's not easy to use.
INFO / DOCUMENTATION

  • URL/Web info
  • Help for the functions from within MATLAB ("help mexcdf", etc.)
  • See the Readme file in the tools directory.

MexCDF and NetCDF Toolbox for MATLAB 5 (for MATLAB 6, see below)

DESCRIPTION

MexCDF for MATLAB 5 is a bit different than for MATLAB 4. It is now recommended to use the NetCDF Toolbox rather than the low-level MexCDF interfaces. The NetCDF Toolbox uses MexCDF to provide a high-level language taking full advantage of concepts introduced in MATLAB 5.

HOW TO INVOKE

Add the following two paths to the MATLABPATH environment variable (change first if it doesn't already exist, and select linux or irix) in a shell:

        setenv MATLABPATH ${MATLABPATH}:/home/hnv/pub/{linux,irix}/mexcdf-5

        setenv MATLABPATH ${MATLABPATH}:/home/hnv/pub/{linux,irix}/mexcdf-5/netcdf

then run matlab. To initialize the netCDF interface, run the following from the MATLAB prompt:


        ncstartup

INFO / DOCUMENTATION

  • URL/Web info
  • Help for the functions from within MATLAB ("help netcdf", "help mexcdf", etc.)

MexCDF and NetCDF Toolbox for MATLAB 6

DESCRIPTION

MexCDF for MATLAB 6 is a bit different than for MATLAB 5 and is still operational with MATLAB 7. It is recommended over previous versions.

HOW TO INVOKE

Add the following two paths to the MATLABPATH environment variable (select linux or irix) in a shell:

        setenv MATLABPATH ${MATLABPATH}:/home/rsz/matlab/{linux,irix}/mexcdf/mexcdf53/netcdf

then run matlab. To initialize the netCDF interface, run the following from the MATLAB prompt:


        ncstartup

For convenience, you can automate all this by modifying your ~/.cshrc file:
    if (! $?MATLABPATH) then
          setenv MATLABPATH
    endif

    if ( `uname` == IRIX64 ) then
        setenv MATLABPATH ${MATLABPATH}:/home/rsz/matlab/irix/mexcdf/mexcdf53/netcdf
    else
        setenv MATLABPATH ${MATLABPATH}:/home/rsz/matlab/linux/mexcdf/mexcdf53/netcdf    
    endif        
and your ~/matlab/startup.m file:
    
    ncstartup;
INFO / DOCUMENTATION

  • Project Webpage (http://mexcdf.sourceforge.net/)
  • User's Guide (http://mexcdf.sourceforge.net/netcdf_toolbox_guide.html)
  • Help for the functions from within MATLAB ("help netcdf", "help mexcdf", etc.)

MEXEPS

DESCRIPTION :
MexEPS is a mex-file interface which allows MATLAB to access EPIC System data. The EPIC System Library supports the netCDF (read/write/edit), classic EPIC (read/write), and generic formatted ASCII (read only) formats. MexEPS provides functions for:
  • Opening/closing files
  • Reading/writing variable information
  • Reading/writing axis information
  • Reading/writing attribute information
  • Manipulating time
PLUSES :
- supports a wider range of netCDF file conventions (esp. for the time dimension) than MEXCDF
MINUSES :
- More difficult to deal with than MexCDF. Since it relies on the EPIC System Library, it requires access to a file called epic.key. This file associates variable names that you want to use with numeric codes. These codes must then be used with the MexEPS functions instead of the variable names. Consequently, variable names that do not have a properly formatted entry in the epic.key file or are not in the proper format in the netCDF file will not be usable. See the ".cdf" files in the examples directory and the epic.key file itself for further illustration.

HOW TO INVOKE :

  • First, add the following three paths to the MATLABPATH environment variable (change first if it doesn't already exist) in a shell (IRIX only):
    
            setenv MATLABPATH ${MATLABPATH}:/home/hnv/pub/irix/mexeps
    
            setenv MATLABPATH ${MATLABPATH}:/home/hnv/pub/irix/mexeps/help-m
    
            setenv MATLABPATH ${MATLABPATH}:/home/hnv/pub/irix/mexeps/examples
    
    
  • Then, set the EPS_EPICKEY environment variable (the directory for the epic.key file):
  • 
            setenv EPS_EPICKEY /home/hnv/pub/mexeps
    
    
  • Then, just run matlab
HINTS :
- Unless time axis manipulation is extremely important, use MexCDF!
- Help for the commands is available from within MATLAB ("help mexeps", etc.)

INFO / DOCUMENTATION :

cfchecker

DESCRIPTION :
The checker was written at the Hadley Centre and can be accessed through a web form hosted at the British Atmospheric Data Centre. The form checks that a netCDF file which you supply complies with the CF comformance requirements and recommendations.

Current availability of this service via the online form may be intermittent, so you may not be able to access the online version, but we do have one locally.
PLUSES :
Easy to use.
MINUSES :
Still in test. Current version is 0.18.

HOW TO INVOKE :

    
    cfchecker netCDFfile
    
    
HINTS :

INFO / DOCUMENTATION :

nc_to_vis5d

DESCRIPTION :

This script was written locally at GFDL to allow Ferret users view their 3D data in Vis5d. The script primarily uses scripts developed for Ferret by PMEL, so there are limitations to its use. The main interface used in Ferret is the "writev5d" function.

PLUSES :
  • Easy to use.

MINUSES :
  • All variables in NetCDF file must have the same XYT axes.
  • There cannot be non-matching overlapping z-coordinates between different variables.
  • Works only on equally spaced grids.
  • Can't convert more than 8 variables.

HOW TO INVOKE :

    
    nc_to_vis5d netCDFfile
    
    
HINTS :

INFO / DOCUMENTATION :

Introspection Tools

DESCRIPTION :

A series of C programs have been written to facilitate shell scripting and file inspection, such as for comparing values & metadata. Refer to the full list of commands and their descriptions.

ncdims - lists names of all dimensions
ncdimvars - lists names of dimensions that are also variables
ncmetasize - returns byte size of file's header (metadata)
ncndimvars - returns the number of dimensions that are also variables
ncinqvar - returns id, type id, type, type length, # dims., dim. ids, dim. lengths, dim. names & # attributes
ncnondimvars - lists names of variables that are not dimensions
ncnonrecvars - lists names of variables that don't use a record dimension
ncnrec - returns the number of records
ncnnondimvars - returns the number of variables that aren't dimensions
ncrec - returns the record dimension name
ncrecoffset - returns byte offset for the record data section
ncrecsize - returns byte size of a single record
ncrecvars - lists names of variables that use a record dimension
ncnonrecoffset - returns byte offset to the non-record data section (same as ncmetasize)
ncvaroff - returns byte offset & length of a variable

PLUSES :
  • Easy to use.
  • Fast, with read-only access.
  • Retrieves information not available through the conventional NetCDF API library.

MINUSES :
  • Text returned may be comma-delimited, so you need to split it.
  • They must be compiled for your platform.

HOW TO INVOKE :

            command netCDFfile [variable]
    
HINTS :
  • If a comma-delimited list needs reformatting for your shell script, try the following. Assume that the shell variable W contains the returned list and you want to use it in a foreach contstruct, such as in tcsh. Split it with
            set words=`echo $W | perl -ne 's/,/\n/sg; chomp; print;'`
    

INFO / DOCUMENTATION :

nccmp

DESCRIPTION :
Compares 2 NetCDF files at the bit level. nccmp is optimally efficient because it doesn't rely on any temporary files or text dumps; all comparisons are done while traversing the data linearly. Options allow for comparing the metadata and/or data. Highly recommended for regression testing, especially for large datasets. MPI is also supported, so comparisons may be done in parallel. Refer to the usage instructions reproduced below and the project home page.

Compare two NetCDF files.
nccmp is silent when files are equivalent, otherwise it will echo to STDERR 
whether metadata or a specific variable differs.  By default, comparing stops 
after the first difference.

Exit code 0 is returned for identical files, 1 for different files, and 
2 for a fatal error.

Usage: nccmp [OPTION...] file1 file2

  -d, --data                 Compare data (variable values)
  -x, --exclude=var1[,...]   Exclude variable(s) var1[,...]
  -f, --force                Forcefully compare, do not stop after first difference
  -g, --global               Compare global attributes
                             (-m required)
  -h, --history              Compare global history attribute
                             (-mg required)
  -m, --metadata             Compare metadata, excluding global attributes
  -q, --quiet                Quiet mode, prints differences only
  -v, --variable=var1[,...]  Compare variable(s) var1[,...] only
  -b, --verbose              Print messages to show progress
  -H, --help                 Give a short usage message
      --usage                
  -V, --version              Print program version

PLUSES :
  • Easy to use.
  • Very fast.
  • Specific variables may be compared.
  • Specifies which record, variable, dimension or attribute differs.
  • Comparing the data or metadata only is allowed.
  • Global and history attributes may be ignored when comparing metadata.
  • Uses standard exit codes and streams for easy incorporation into your own scripts.
  • MPI enabled.
  • Generates flexible script to view values that differ.

MINUSES :
  • Won't create a view script to show every value difference, only the first for a variable. This will be addressed in a future version.

HOW TO INVOKE :

At GFDL, make the following alias, or build your own from the source distribution:
        alias nccmp  /net2/rsz/{altix,irix,linux}/nccmp/bin/nccmp
        alias nccmpi /net2/rsz/{altix,irix}/nccmp/bin/nccmpi        
HINTS :
  • To compare 2 entire files, excluding their history attributes, until the first difference:
            nccmp -mgd file1 file2
    
  • The same as above, but in parrallel:
            mpirun -np 24 nccmpi -mgd file1 file2
    
  • To compare the data only for 2 variables:
            nccmp -d -v time,lat file1 file2
    
  • To exclude 2 variables from a full (forced) comparison:
            nccmp -mghdfq -x time,lat file1 file2
    

INFO / DOCUMENTATION :

ScientificPython


DESCRIPTION :
ScientificPython is a collection of modules for the Python language. It's most important module to GFDL is Scientific.IO.NetCDF , which allows reading and writing NetCDF files. The interface is much simpler in every respect as compared to the NetCDF Toolbox for MATLAB. This includes modifying attributes, data, and dimensions. Plus, Python's local memory is only constrained by hardware, unlike MATLAB, which has a 1+ GB built-in limit, so even the largest NetCDF files can be manipulated.

PLUSES :
  • Complete read/write access of NetCDF files.
  • Probably the simplest NetCDF programming interface around.
  • Memory limited only by hardware, not software (like MATLAB).
  • Portable (ported to every platform at GFDL).
  • Uses the latest NetCDF library (at GFDL, only for Linux & Altix systems).
MINUSES :
  • In IRIX, can only be used with the NetCDF 3.4 library.

HOW TO INVOKE :

  1. Python needs to be aware of the module's location. At GFDL, use the following lines in your startup dot-file, such as ~/.cshrc.
    #
    # for LINUX 32-bit or Altix ia64     
    #   
    setenv PATH "/home/rsz/pub/{linux, altix}/python/bin/:${PATH}" 
    
    #
    # for IRIX (anc1 only)
    #   the python executable will be a system default, 
    #   so we must point to the additional modules
    #
    setenv PYTHONPATH ""
    setenv PYTHONPATH "/home/rsz/pub/irix/python/lib/python2.3/site-packages/:${PYTHONPATH}"
    setenv PYTHONPATH "/home/rsz/pub/irix/python/lib/python2.3/site-packages/Numeric:${PYTHONPATH}"
    
  2. You can now import the module into Python, with the command:
    from Scientific.IO.NetCDF import NetCDFFile
    
HINTS :
  • Open a file for reading:
    f = NetCDFFile('/home/me/file.nc')
    
  • Open an existing file for editing (append mode):
    f = NetCDFFile('/home/me/file.nc', 'a')
    
  • Create a new file (careful, this will overwrite any existing file!):
    f = NetCDFFile('/home/me/file.nc', 'w')
    
  • Create/modify a global attribute:
    f.history = 'new file created in python'
    f.author = 'GFDL User'
    
  • Create a record dimension, along with a simple variable and assign some data.
    f.createDimension('time', None)
    f.createDimension('z', 2)
    
    # must FIRST define number of records through a record variable
    f.createVariable('time', 'd', ('time',))   # double type
    f.variables['time'][0] = 1000              # arbitrary values as an example
    f.variables['time'][1] = 1001              # now record dimension length = 2
    
    f.createVariable('z', 'f', ('time', 'z',)) # float type
    f.variables['z'][0,:] = [1,2]
    f.variables['z'][1,:] = [3,4]
    f.variables['z'][:]   = [ [1,2], [3,4] ]   # same as 2 lines above
    
  • Create/modify a variable attribute:
    f.variables['time'].calendar = "JULIAN"
    
  • Synchronize or close a file:
    f.sync()   # updates file on disk and keeps file open for editing
    f.close()  # updates file on disk and closes it
    

INFO / DOCUMENTATION :

ncx.py


DESCRIPTION :
A Python script that extracts arbitrary slices for a single dimension for any number of variables in a NetCDF file. The dimensionality is preserved for every sliced variable. The input file's grid ranks can be arbitrary.

As an example, this can be used to extract only specific pressure levels for variables defined on a (time, level, lat, lon) grid.

PLUSES :
  • Easy to use from the command line.
  • Any dimension can be sliced, for any index, unlike ncks which supports only ranges and/or strides.
MINUSES :
  • Slice indices must be specified with non-negative integers. There is no support for specifying actual slice dimension values.
HOW TO INVOKE :
  • python must be able to find the ScientificPython module to have NetCDF support. See ScientificPython on how to do this. For example, on IRIX, modify your .login or .cshrc file to include
        setenv PYTHONPATH "/home/rsz/pub/irix/python/lib/python2.3/site-packages"
        setenv PYTHONPATH "/home/rsz/pub/irix/python/lib/python2.3/site-packages/Numeric:"
    
HINTS :
  • For help, do ncx.py --help
  • An example that slices out 4 pressure levels for every variable. The pressure level dimension is called 'level'.
    ncx.py -f in.nc -o out.nc -d level -i 0,3,4,9
    
INFO / DOCUMENTATION :
  • ncx.py Source Code
  • Usage instructions:
        usage: ncx.py [options]
    
        An arbitrary dimension slice extractor for NetCDF 3.x files.
        Dimensionality is preserved for all sliced variables.
    
        Version 0.0
        Remik.Lastname@noaa.gov where Lastname = Ziemlinski
    
        options:
          -h, --help            show this help message and exit
          -fFILE, --file=FILE   input filename
          -oFILE, --out=FILE    output filename
          -vVAR[,VARn], --var=VAR[,VARn]
                                comma-delimited list of variables to extract.  if not
                                given, processes all variables
          -dDIM, --dim=DIM      extracted dimension name
          -iINDEX[,INDEXn], --index=INDEX[,INDEXn]
                                comma-delimited list of dimension indices to extract
                                (0-based)
          -V, --verbose         shows progress
    

ncclamp


DESCRIPTION :
ncclamp is a command-line tool for NetCDF files that allows you to replace values in-place by specifying the variable, the old value to be replaced, the new value, and a comparison operator. The change is applied across all of the variable's dimensions, including the record dimension if any.

In a less than obvious way, the same could probably be achieved using mask conditions with NetCDF Operators, but this tool greatly simplifies the syntax and I/O.

PLUSES :
  • Easy to use from the command line with minimal code overhead.
  • Operates on a file in-place, thus avoiding unnecessary file copying.
  • Works with all Netcdf datatypes.
HOW TO INVOKE :
  • At GFDL you can access the platform dependent binaries as
        # Linux workstations.
        /home/rsz/pub/linux/ncclamp
        # IA64 IC nodes.
        /home/rsz/pub/ia64/bin/ncclamp
    
HINTS :
  • The following example would mask a variable "topography" to be Not-a-Number everywhere below sea level.
        ncclamp foo.nc topography 0 nan lt
    
  • This example would replace a value with -infinity.
        ncclamp foo.nc var1 -1e9 -inf eq
    
  • This would create a binary mask of a variable.
        ncclamp foo.nc veg -9999 0 '=='
        ncclamp foo.nc veg 0 1 '<>'
    
INFO / DOCUMENTATION :
  • Official project webpage
  • Usage instructions:
    ncclamp 0.1:
            Change values with another value using a comparison operator.
    Usage:
            ncclamp path varid oldvalue newvalue operator
                    path:   name of the NetCDF file.
                    varid:  id (or name) of the variable.
                    oldvalue: old value such as 1e-10, 1.234, nan, -inf, or inf.
                    newvalue: new value such as 1e-10, 1.234, nan, -inf, or inf.
                    operator: '==', '<>', '!=', '<', '<=', '>', '>=', eq, neq, lt, le, gt, ge.
    Examples:
            ncclamp ncfoo.nc land nan -1e9 eq
            ncclamp ncfoo.nc topo 0 0 le
    
smaller bigger reset
last modified: January 03 2007.