cf.Space

class cf.Space(**kwargs)

Bases: cf.space.Variable

Represent a space construct according to the CF data model.

Refer to the cf module for details on data access by indexing and data storage.

Slicing a space instance with call arguments

A space is callable and keyword arguments may be used to define slices of the space’s data based on conditions on the space’s coordinate values, creating a new space whose data and grid are a subset of the original.

The keyword arguments are exactly as for the space’s slice() method, i.e. for a space, s, s(...) is exactly equivalent to s.slice(...). Refer to the slice() method for details and examples.

Overloaded operators

Refer to Variable.

Parameters:**kwargs

The new instance is given attributes named by the keywords, whose values are deep copies the keyword values.

Attribute (type) Description
ancillary_variables (SpaceList) Optional. Contains other spaces comprising the variables described by a CF ancillary_variables string.
array (numpy.ndarray) A numpy array deep copy of the data.
bounds (CoordinateBounds) Optional The coordinate’s cell boundaries.
cell_methods (CellMethods) Optional. Contains the information from a CF cell_methods string parsed into a data structure. Refer to CellMethods for more details.
dtype (numpy.dtype) Describes the format of the elements in the data array (refer to numpy.ndarray.dtype).
grid (Grid) Optional. Describes the space’s dimensionality and contains the space’s dimension coordinates, auxiliary coordinates and cell measures. Refer to Grid for more details.
ncvar (str) Optional. Contains the name of the variable in the original netCDF file. If present when the space is written to a netCDF file, then used for the output netCDF variable name.
ndim (int) The data array’s number of dimensions (refer to numpy.ndarray.ndim).
shape (tuple) The shape of the data array (refer to numpy.ndarray.shape).
size (int) The number of elements in the data array (refer to numpy.ndarray.size).
transform (str) Optional. The key of a grid’s transform attribute which contains a transformation for this coordinate.
type (type) The type of the data object, which is either a numpy array or a file pointer.
varray (numpy.ndarray) A numpy view of the data.
_atol (NoneType or float) Optional. Absolute tolerance for numeric equality. Unset is equivalent to None, which implies a default value. Refer to cf.
_rtol (NoneType or float) Optional. Relative tolerance for numeric equality. Unset is equivalent to None, which implies a default value. Refer to cf.
Method Description
coord() Return a coordinate identified by its name.
copy() Create a copy.
dump() Return a string containing a full description of the instances.
equals() Determine whether two instances are congruent with each other.
extract() Determine whether an instance matches phenomena criteria.
first_datum() Return the first element of the data without replacing a file pointer with a numpy array.
last_datum() Return the last element of the data without replacing a file pointer with a numpy array.
name() Return the name (standard_name, long_name or ncvar).
ncatts() Return the set of attributes which are netCDF attributes.
properties() Return a set of writable, public attributes.
repoint() Revert the data to a file pointer.
slice() Slice a space with conditions on coordinate values.
array

Create a numpy array deep copy of the data.

If the data was stored as a file pointer then it will be changed in-place to be stored as a numpy array.

Returns:A numpy array.

Examples

>>> a = x.array
>>> type(a)
<type 'numpy.ndarray'>
>>> a = x.array[[0,1]]
>>> type(a)
<type 'numpy.ndarray'>
>>> a.shape
(2,)
coord(name, role=None, key=False, exact=False)

Find a coordinate of the space’s grid by name.

The given name argument is an abbreviation for (or equal to if the exact parameter is True) its standard_name attribute. If the key parameter is True then return the coordinate’s grid key name. If a coordinate does not have standard_name attribute, then its :att`ncvar` attribute is used.

Note that the returned coordinate is an object identity to the coordinate stored in the grid so, for example, a coordinate’s attributes may be changed in-place as follows:

>>> s.coord('height').long_name
AttributeError: 'Coordinate' object has no attribute 'long_name'
>>> s.coord('hei').long_name = 'HEIGHT'
>>> s.coord('heigh').long_name
'HEIGHT'

Or a deep copy may be made with the coordinate’s copy() method:

>>> h = s.coord('height').copy()
Parameters:
  • name (str) – The string to identify a coordinate by name.
  • exact (bool) – Optional. If True then assume that the value of the name argument is equal to exactly one coordinate’s name.
  • key (str) – Optional. Return the grid key name instead of the coordinate.
  • role (str or None) – Optional. Restrict the search to coordinates of the given role. Valid values are ‘dim’ and ‘aux’, for dimension and auxiliary coordinate types respectively. If None then both types of coordinates will be searched.
Returns:

If a coordinate has been identified, return either a Coordinate instance or, if the keys parameter is True, a grid key name string. otherwise, return None.

Examples

>>> s.coord('lon')
<CF Coordinate: longitude(128)>
>>> s.coord('lon', key=True)
'dim2'
>>> s.coord('lonX', key=True)
None
>>> s.coord('lon', exact=True)
None
>>> s.coord('longitude', exact=True)
<CF Coordinate: longitude(128)>
copy(shallow=(), omit=())

Create a deep copy of the variable, but with shallow copies of selected attributes.

If a deep copy of a variable’s attribute raises an exception then a shallow copy is attempted. If the shallow copy also raises an exception then the variable’s attribute is assigned to the returned copy.

In particular, netCDF4.Variable instances are copied by assignment.

Parameters:
  • omit (sequence) – Optional. A collection of the variable’s attribute names which are not to be copied to the new variable. Supersedes duplicate entries in the shallow sequence.
  • shallow (sequence) – Optional. A collection of the variable’s attribute names which are to be shallow copied, as opposed to deep copied.
Returns:

A deep copy of the variable with the exceptions of those attributes given by the shallow argument.

dtype

Data-type of the data’s elements.

Returns:A numpy dtype object.
dump(id=None, nc=False, omit=())

Return a string containing a full description of the space.

Parameters:
  • idOptional. Set the common prefix of variable component names. If None then defaults to the class name.
  • id – str
  • nc (bool) – Optional. If True then include attributes whose names begin “nc”.
  • omit (sequence) – Optional. Omit the given attributes the description.
Returns:

A string containing the description of the space.

See also

cf.dump()

equals(other, rtol=None, atol=None, override=True)

Return True if the variable is congruent to another variable in that they have identical data, property names (as returned by the properties() method) and corresponding property values.

Equality of numbers is to within a tolerance. Refer to cf for details.

Parameters:
  • other (object) – The variable to compare against for equality.
  • atol (None or float) – Optional. If None then use the default method for setting the absolute tolerance for equality of real numbers (refer to cf for details). If a float then set the absolute tolerance to this value for all comparisons (refer to the override parameter).
  • override (bool) – Optional. If False then only use a float value of the rtol or atol parameters if it can not be set from attributes of the objects being compared.
  • rtol (None or float) – Optional. If None then use the default method for setting the relative tolerance for equality of real numbers (refer to cf for details). If a float then set the relative tolerance to this value for all comparisons (refer to the override parameter).
Returns:

True if the two objects are congruent, False otherwise.

Examples

>>> y = x
>>> x.equals(y)
True
>>> y =x()
>>> y[...] = y.varray + 1
>>> x.equals(y)
False
>>> y[...] = y.varray - 1
>>> x.equals(y)
True
>>> y.standard_name += '_different'
>>> x.equals(y)
False
extract(exact=False, **kwargs)

Determine whether or not the variable matches conditions on its phenomena.

The variable’s phenomena are its attributes and, if it has any, its size 1 coordinates.

The phenomenon and its conditions are specified with **kwargs parameters.

The variable matches the conditions if and only if it contains all of the specified phenomena and they pass all of their given criteria. A variable always matches no criteria.

Parameters:
  • exact (bool) – Optional If True then the remaining keyword arguments given by **kwargs are assumed to be unambiguous exact matches for a phenomenon names, as opposed to an unambiguous abbreviations.
  • **kwargs

    The remaining keyword arguments may be any unambiguous abbreviation of any phenomenon name, either an attribute name or the standard_name of a coordinate. This behaviour is modified by the exact keyword.

    A keyword argument’s value may be one of the following:

    1. A number. A match requires that a numeric phenomenon equals the number using the variable’s == operator.
    2. A string. A match requires that a string-valued phenomenon passes a regular expression match on the string. The string may contain regular expression special characters. To avoid ambiguities, it is assumed that the regular expression string matches the whole of the phenomenon string, i.e. the regular expression special characters ^ and $ are assumed if not given.
    3. A sequence of numbers or strings. A match requires that a numeric phenomenon equals at least one of the sequence’s elements (as in 1.) or a string-valued phenomenon passes a regular expression match for at least one string in the sequence (as in 2.).
    4. A Comparison object. A match requires that the comparison for the phenomenon evaluates to True.
Returns:

True if the variable matches the criteria, False otherwise.

Examples

>>> S
<CF Space: air_temperature(19, 30, 24)>
>>> s.standard_name
'air_temperature'
>>> s.extract(standard_name = 'air_temperature')
True
>>> s.extract(standard = '^air.*')
True
>>> s.extract(standard_name = lt('b'))
True
>>> s.extract(standard_name = outside('b', 'p'))
True
>>> s.extract(standard = ['.*temp.*', 'pressure'])
True
>>> s.extract(exact=True, standard_name = 'air_temperature')
True
>>> s.extract(exact=True, standard_ = 'air_temperature')
False
>>> s.extract(standard = ['temp', 'pressure'])
False
>>> s.extract(standard_name = inside('o', 'p'))
False
first_datum

Return the first element of the data without replacing a file pointer with a numpy array.

Returns:The scalar value of the first element of the data.
last_datum

Return the last element of the data without replacing a file pointer with a numpy array.

Returns:The scalar value of the last element of the data.
name(long=False, ncvar=False, default=None)

Return the standard_name attribute of the variable.

If there is no standard_name attribute then return one of the long_name attribute, the ncvar attribute or the value of the default parameter, depending on the values of the parameters.

Parameters:
  • long (bool) – Optional. If True, return the long_name if standard_name does not exist.
  • ncvar (bool) – Optional If True, return ncvar if neither standard_name not long_name have already been returned.
  • default (None or object) – Optional. Return default if standard_name, long_name nor ncvar have already been returned.
Returns:

The name of the variable.

ncatts()

Return a set of attributes which are netCDF attributes suitable for writing to a netCDF file.

All writable attributes are considered netCDF attributes except those starting with an underscore, (with the exception of ‘_FillValue’), those starting with “nc” and the grid attribute.

To create an attribute which will not be in the set of netCDF attributes, assign directly to the __dict__ dictionary as opposed to using setattr.

Returns:A set of attributes which are netCDF attributes.
ndim

Number of data dimensions.

Equivalent to the number of elements in shape tuple.

Returns:A non-negative integer
properties(nc=False)

Return a set of writable, public attribute names, excluding methods.

An attribute created by assigning directly to the __dict__ dictionary (as opposed to using setattr()) will not appear in this set.

Parameters:nc (bool) – If False then exclude attributes whose names begin “nc”.
Returns:A set of attribute names.
repoint(test=False)

Reset the data of all space components to a file pointers if they are all available, regardless of of whether the data are currently stored as a numpy arrays or not.

This may free memory, but any changes to data stored as a numpy arrays will be lost.

Parameters:test (bool) – Optional. If True then do not reinstate a file pointer if it exists.
Returns:True if all file pointers of all space components exist, False otherwise.
shape

Tuple of the data’s dimension sizes.

If the data originates from a file, the returned data dimensions may differ from the dimensions of the array on disk in that size one dimendef slicesions are not represented in the space’s data, unless the space’s data would otherwise be a scalar, in which case the shape is (1,).

Returns:A tuple of the data’s dimension sizes.
size

Number of elements in the data.

Equivalent to the product of the data’s dimension sizes.

Returns:A non-negative integer
slice(exact=False, **kwargs)

Return a new space whose data and grid are a subset of the original by slicing the space where conditions on coordinate data values are met.

A coordinate and the conditions on its data are specified with **kwargs parameters.

If a coordinate is not specified, then its dimension is returned unchanged. A call with no parameters (kwargs = {}) is returns a deep copy of the space.

The order in which coordinates are given in the parameter list is irrelevant.

Unless the exact keyword is True, the coordinates identified in different space elements may vary. For example, the keyword ‘lon’ could identify the ‘longitude’ coordinate in one variable and ‘longwave’ in another.

Parameters:
  • exact (bool) – Optional. If True then the remaining keyword arguments given by **kwargs are assumed to be unambiguous exact matches for a coordinate names, as opposed to an unambiguous abbreviations.
  • **kwargs

    The keyword arguments to the call may be any unambiguous abbreviation of the standard_name of any one dimensional dimension or auxiliary coordinate which shares its dimension with the space’s data. This behaviour is modified by the exact keyword.

    A keyword argument’s value may be one of the following:

    1. A scalar. The dimension is sliced where coordinate equals (using the == operator) the scalar value.
    2. A sequence. The dimension is sliced where the coordinate equals (using the == operator) any of the sequence’s elements.
    3. A Comparison object (as, for example, returned by the lt() function). The dimension is sliced where the comparison for the coordinate evaluates to True.
    4. An array of booleans. The dimension is sliced where elements of this array are True.
Returns:

A space.

See also

__call__()

Examples

>>> s = cf.read1('surface_air_temperature.nc')
>>> print s
Data            : air_temperature(time, latitude, longitude)
Cell methods    : time: mean (interval: 1.0 month)
Dimensions      : time(7070) -> 450-11-16 00:00:00 to 1049-12-16 12:00:00
                : latitude(64) -> -87.8638 to 87.8638 degrees_north
                : longitude(128) -> 0 to 357.1875 degrees_east
                : height(1) -> 2 m
Auxiliary coords:
>>> s
<CF Space: air_temperature(7070, 64, 128)>
>>> s.slice(lon = 0)
<CF Space: air_temperature(7070, 64)>
>>> s.slice(lon = [0, 45, 45.1])
<CF Space: air_temperature(7070, 64, 2)>
>>> s.slice(lon = numpy.arange(128)*2.8125)
<CF Space: air_temperature(7070, 64, 128)>
>>> s.slice(lon = s.coord('lon')<90)
<CF Space: air_temperature(7070, 64, 64)>
>>> s.slice(lon = 0, lat = gt(0))
<CF Space: air_temperature(7070, 32)>
>>> s.slice(longitude = 0, exact=True)
<CF Space: air_temperature(7070, 32)>
>>> s.slice(lon = 0, exact=True)
RuntimeError: Can not find dimension from keyword: lon

The next two commands are equivalent:

>>> s.slice(lon = lt(180))
<CF Space: air_temperature(7070, 64, 64)>
>>> s.slice(long = s.coord('lon')<180)
<CF Space: air_temperature(7070, 64, 64)>

The next two commands are equivalent:

>>> s.slice(lon = inside(90,135))
<CF Space: air_temperature(7070, 64, 17)>
>>> lon = s.coord('lon') ; s.slice(lon = (lon>=90) & (lon<=135))
<CF Space: air_temperature(7070, 64, 17)>

The next three commands are equivalent:

>>> s.slice()
>>> s.slice(**{})
>>> copy.deepcopy(s)
>>> s.copy()
type

The type of the data object.

Returns:A type object, or None if the variable has no data.
varray

Create a numpy view of the data.

If the data was stored as a file pointer then it will be changed in-place to be stored as a numpy array.

Note that making changes to elements of the returned view changes the underlying data. Refer to numpy.ndarray.view().

Returns:A numpy view.

Examples

>>> a = x.varray
>>> print a
array([0, 1, 2, 3, 4])
>>> a[0] = 999
>>> print x.varray[0]
999
>>> a = 'a_different_object'
>>> print x.varray
array([999, 1, 2, 3, 4])

Previous topic

cf.Grid

Next topic

cf.SpaceList

This Page