parmed.utils.netcdf module

NetCDF reader/writer module.

This module is used to read and create NetCDF files. NetCDF files are accessed through the netcdf_file object. Data written to and from NetCDF files are contained in netcdf_variable objects. Attributes are given as member variables of the netcdf_file and netcdf_variable objects.

This module implements the Scientific.IO.NetCDF API to read and create NetCDF files. The same API is also used in the PyNIO and pynetcdf modules, allowing these modules to be used interchangeably when working with NetCDF files.

Only NetCDF3 is supported here; for NetCDF4 see netCDF4-python, which has a similar API.

class parmed.utils.netcdf.netcdf_file(filename, mode='r', mmap=None, version=1, maskandscale=False)[source]

Bases: object

A file object for NetCDF data.

A netcdf_file object has two standard attributes: dimensions and variables. The values of both are dictionaries, mapping dimension names to their associated lengths and variable names to variables, respectively. Application programs should never modify these dictionaries.

All other attributes correspond to global attributes defined in the NetCDF file. Global file attributes are created by assigning to an attribute of the netcdf_file object.

Parameters
filenamestring or file-like

string -> filename

mode{‘r’, ‘w’, ‘a’}, optional

read-write-append mode, default is ‘r’

mmapNone or bool, optional

Whether to mmap filename when reading. Default is True when filename is a file name, False when filename is a file-like object. Note that when mmap is in use, data arrays returned refer directly to the mmapped data on disk, and the file cannot be closed as long as references to it exist.

version{1, 2}, optional

version of netcdf to read / write, where 1 means Classic format and 2 means 64-bit offset format. Default is 1. See here for more info.

maskandscalebool, optional

Whether to automatically scale and/or mask data based on attributes. Default is False.

Notes

The major advantage of this module over other modules is that it doesn’t require the code to be linked to the NetCDF libraries. This module is derived from pupynere.

NetCDF files are a self-describing binary data format. The file contains metadata that describes the dimensions and variables in the file. More details about NetCDF files can be found here. There are three main sections to a NetCDF data structure:

  1. Dimensions

  2. Variables

  3. Attributes

The dimensions section records the name and length of each dimension used by the variables. The variables would then indicate which dimensions it uses and any attributes such as data units, along with containing the data values for the variable. It is good practice to include a variable that is the same name as a dimension to provide the values for that axes. Lastly, the attributes section would contain additional information such as the name of the file creator or the instrument used to collect the data.

When writing data to a NetCDF file, there is often the need to indicate the ‘record dimension’. A record dimension is the unbounded dimension for a variable. For example, a temperature variable may have dimensions of latitude, longitude and time. If one wants to add more temperature data to the NetCDF file as time progresses, then the temperature variable should have the time dimension flagged as the record dimension.

In addition, the NetCDF file header contains the position of the data in the file, so access can be done in an efficient manner without loading unnecessary data into memory. It uses the mmap module to create Numpy arrays mapped to the data on disk, for the same purpose.

Note that when netcdf_file is used to open a file with mmap=True (default for read-only), arrays returned by it refer to data directly on the disk. The file should not be closed, and cannot be cleanly closed when asked, if such arrays are alive. You may want to copy data arrays obtained from mmapped Netcdf file if they are to be processed after the file is closed, see the example below.

Examples

To create a NetCDF file:

>>> from scipy.io import netcdf
>>> f = netcdf.netcdf_file('simple.nc', 'w')
>>> f.history = 'Created for a test'
>>> f.createDimension('time', 10)
>>> time = f.createVariable('time', 'i', ('time',))
>>> time[:] = np.arange(10)
>>> time.units = 'days since 2008-01-01'
>>> f.close()

Note the assignment of arange(10) to time[:]. Exposing the slice of the time variable allows for the data to be set in the object, rather than letting arange(10) overwrite the time variable.

To read the NetCDF file we just created:

>>> from scipy.io import netcdf
>>> f = netcdf.netcdf_file('simple.nc', 'r')
>>> print(f.history)
b'Created for a test'
>>> time = f.variables['time']
>>> print(time.units)
b'days since 2008-01-01'
>>> print(time.shape)
(10,)
>>> print(time[-1])
9

NetCDF files, when opened read-only, return arrays that refer directly to memory-mapped data on disk:

>>> data = time[:]
>>> data.base.base
<mmap.mmap object at 0x7fe753763180>

If the data is to be processed after the file is closed, it needs to be copied to main memory:

>>> data = time[:].copy()
>>> f.close()
>>> data.mean()
4.5

A NetCDF file can also be used as context manager:

>>> from scipy.io import netcdf
>>> with netcdf.netcdf_file('simple.nc', 'r') as f:
...     print(f.history)
b'Created for a test'

Methods

close()

Closes the NetCDF file.

createDimension(name, length)

Adds a dimension to the Dimension section of the NetCDF data structure.

createVariable(name, type, dimensions)

Create an empty variable for the netcdf_file object, specifying its data type and the dimensions it uses.

flush()

Perform a sync-to-disk flush if the netcdf_file object is in write mode.

sync()

Perform a sync-to-disk flush if the netcdf_file object is in write mode.

close()[source]

Closes the NetCDF file.

createDimension(name, length)[source]

Adds a dimension to the Dimension section of the NetCDF data structure.

Note that this function merely adds a new dimension that the variables can reference. The values for the dimension, if desired, should be added as a variable using createVariable, referring to this dimension.

Parameters
namestr

Name of the dimension (Eg, ‘lat’ or ‘time’).

lengthint

Length of the dimension.

See also

createVariable
createVariable(name, type, dimensions)[source]

Create an empty variable for the netcdf_file object, specifying its data type and the dimensions it uses.

Parameters
namestr

Name of the new variable.

typedtype or str

Data type of the variable.

dimensionssequence of str

List of the dimension names used by the variable, in the desired order.

Returns
variablenetcdf_variable

The newly created netcdf_variable object. This object has also been added to the netcdf_file object as well.

See also

createDimension

Notes

Any dimensions to be used by the variable should already exist in the NetCDF data structure or should be created by createDimension prior to creating the NetCDF variable.

flush()[source]

Perform a sync-to-disk flush if the netcdf_file object is in write mode.

See also

sync

Identical function

sync()

Perform a sync-to-disk flush if the netcdf_file object is in write mode.

See also

sync

Identical function

class parmed.utils.netcdf.netcdf_variable(data, typecode, size, shape, dimensions, attributes=None, maskandscale=False)[source]

Bases: object

A data object for netcdf files.

netcdf_variable objects are constructed by calling the method netcdf_file.createVariable on the netcdf_file object. netcdf_variable objects behave much like array objects defined in numpy, except that their data resides in a file. Data is read by indexing and written by assigning to an indexed subset; the entire array can be accessed by the index [:] or (for scalars) by using the methods getValue and assignValue. netcdf_variable objects also have attribute shape with the same meaning as for arrays, but the shape cannot be modified. There is another read-only attribute dimensions, whose value is the tuple of dimension names.

All other attributes correspond to variable attributes defined in the NetCDF file. Variable attributes are created by assigning to an attribute of the netcdf_variable object.

Parameters
dataarray_like

The data array that holds the values for the variable. Typically, this is initialized as empty, but with the proper shape.

typecodedtype character code

Desired data-type for the data array.

sizeint

Desired element size for the data array.

shapesequence of ints

The shape of the array. This should match the lengths of the variable’s dimensions.

dimensionssequence of strings

The names of the dimensions used by the variable. Must be in the same order of the dimension lengths given by shape.

attributesdict, optional

Attribute values (any type) keyed by string names. These attributes become attributes for the netcdf_variable object.

maskandscalebool, optional

Whether to automatically scale and/or mask data based on attributes. Default is False.

See also

isrec
shape
Attributes
dimensionslist of str

List of names of dimensions used by the variable object.

isrec

Returns whether the variable has a record dimension or not.

shape

Returns the shape tuple of the data variable.

Methods

assignValue(value)

Assign a scalar value to a netcdf_variable of length one.

getValue()

Retrieve a scalar value from a netcdf_variable of length one.

itemsize()

Return the itemsize of the variable.

typecode()

Return the typecode of the variable.

assignValue(value)[source]

Assign a scalar value to a netcdf_variable of length one.

Parameters
valuescalar

Scalar value (of compatible type) to assign to a length-one netcdf variable. This value will be written to file.

Raises
ValueError

If the input is not a scalar, or if the destination is not a length-one netcdf variable.

getValue()[source]

Retrieve a scalar value from a netcdf_variable of length one.

Raises
ValueError

If the netcdf variable is an array of length greater than one, this exception will be raised.

property isrec

Returns whether the variable has a record dimension or not.

A record dimension is a dimension along which additional data could be easily appended in the netcdf data structure without much rewriting of the data file. This attribute is a read-only property of the netcdf_variable.

itemsize()[source]

Return the itemsize of the variable.

Returns
itemsizeint

The element size of the variable (e.g., 8 for float64).

property shape

Returns the shape tuple of the data variable.

This is a read-only attribute and can not be modified in the same manner of other numpy arrays.

typecode()[source]

Return the typecode of the variable.

Returns
typecodechar

The character typecode of the variable (e.g., ‘i’ for int).