Iris 0.9
Classes for representing multi-dimensional data with metadata.
In this module:
A single Iris cube of data and metadata.
Typically obtained from iris.load(), iris.load_strict(), or from the manipulation of existing cubes.
For example:
>>> cube = iris.load_strict(iris.sample_data_path('air_temp.pp'))
>>> print cube
air_temperature (latitude: 73; longitude: 96)
Dimension coordinates:
latitude x -
longitude - x
Scalar coordinates:
forecast_period: 6477 hours
pressure: 1000.0 hPa
source: Data from Met Office Unified Model
time: Cell(point=232560.0, bound=(215280.0, 249840.0)) hours since 1970-01-01 00:00:00
Attributes:
STASH: m01s16i203
Cell methods:
mean: time
See the user guide for more information.
- class iris.cube.Cube(data, standard_name=None, long_name=None, units=None, attributes=None, cell_methods=None, dim_coords_and_dims=None, aux_coords_and_dims=None, aux_factories=None, data_manager=None)¶
Creates a cube with data and optional metadata.
Not typically used - normally cubes are obtained by loading data (e.g. iris.load()) or from manipulating existing cubes.
Args:
- data
A numpy array containing the phenomenon values or a data manager object. This object defines the shape of the cube and the value in each cell.
Kwargs:
- standard_name
The standard name for the Cube’s data.
- long_name
An unconstrained description of the cube.
- units
The unit of the cube, e.g. "m s-1" or "kelvin"
- attributes
A dictionary of cube attributes
- cell_methods
A tuple of CellMethod objects, generally set by Iris, e.g. (CellMethod("mean", coords='latitude'), )
- dim_coords_and_dims
A list of coordinates with scalar dimension mappings, e.g [(lat_coord, 0), (lon_coord, 1)].
- aux_coords_and_dims
A list of coordinates with dimension mappings, e.g [(lat_coord, [0]), (lon_coord, [0,1])]. See also Cube.add_dim_coord() and Cube.add_aux_coord().
- aux_factories
A list of auxiliary coordinate factories. See iris.aux_factory.
- data_manager
A iris.fileformats.manager.DataManager instance. If a data manager is provided, then the data should be a numpy array of data proxy instances. See iris.fileformats.pp.PPDataProxy or iris.fileformats.netcdf.NetCDFDataProxy.
For example:
latitude = DimCoord(range(-85, 105, 10), standard_name='latitude', units='degrees') longitude = DimCoord(range(0, 360, 10), standard_name='longitude', units='degrees', 'x', 0, 10, 36) cube = Cube(numpy.zeros((18, 36), numpy.float32), dim_coords_and_dims=[(latitude, 0), (longitude, 1)])
- add_aux_coord(coord, data_dims=None)¶
Adds a CF auxiliary coordinate to the cube.
Args:
- coord
The iris.coords.DimCoord or iris.coords.AuxCoord instance to add to the cube.
Kwargs:
- data_dims
Integer/list of integers giving the data dimensions spanned by the coordinate.
Raises a ValueError if a coordinate with identical metadata already exists on the cube.
See also Cube.remove_coord().
- add_aux_factory(aux_factory)¶
Adds an auxiliary coordinate factory to the cube.
Args:
- aux_factory
The iris.aux_factory.AuxCoordFactory instance to add.
- add_cell_method(cell_method)¶
Add a CellMethod to the Cube.
- add_dim_coord(dim_coord, data_dim=None)¶
Add a CF coordinate to the cube.
Args:
- dim_coord
The iris.coords.DimCoord instance to add to the cube.
Kwargs:
- data_dim
Integer giving the data dimension spanned by the coordinate.
Raises a ValueError if a coordinate with identical metadata already exists on the cube or if a coord already exists for the given dimension.
See also Cube.remove_coord().
- add_history(string)¶
Add the given string to the cube’s history. If the history coordinate does not exist, then one will be created.
- aggregated_by(coords, aggregator, **kwargs)¶
Perform aggregation over the cube given one or more “group coordinates”.
A “group coordinate” is a coordinate where repeating values represent a single group, such as a month coordinate on a daily time slice. TODO: It is not clear if repeating values must be consecutive to form a group.
The group coordinates must all be over the same cube dimension. Each common value group identified over all the group-by coordinates is collapsed using the provided aggregator.
Args:
- coords (list of either coord names or iris.coords.Coord instances):
One or more coordinates over which group aggregation is to be performed.
- aggregator (iris.analysis.Aggregator):
Aggregator to be applied to each group.
Kwargs:
- kwargs:
Aggregator and aggregation function keyword arguments.
- Returns:
- iris.cube.Cube.
For example:
>>> import iris >>> import iris.analysis >>> import iris.coord_categorisation as cat >>> fname = iris.sample_data_path('ostia_monthly.nc') >>> cube = iris.load_strict(fname, 'surface_temperature') >>> cat.add_year(cube, 'time', name='year') >>> new_cube = cube.aggregated_by('year', iris.analysis.MEAN) >>> print new_cube surface_temperature (*ANONYMOUS*: 5; latitude: 18; longitude: 432) Dimension coordinates: latitude - x - longitude - - x Auxiliary coordinates: forecast_reference_time x - - time x - - year x - - Scalar coordinates: forecast_period: 0 hours Attributes: Conventions: CF-1.5 STASH: m01s00i024 history: Mean of surface_temperature aggregated over month, year Mean of surface_temperature... Cell methods: mean: month, year mean: year
- assert_valid()¶
Raise an exception if the cube is invalid; otherwise return None.
- aux_factory(name=None, standard_name=None, long_name=None)¶
Returns the single coordinate factory that matches the criteria, or raises an error if not found.
Kwargs:
- name
If not None, matches against factory.name().
- standard_name
The CF standard name of the desired coordinate factory. If None, does not check for standard name.
- long_name
An unconstrained description of the coordinate factory. If None, does not check for long_name.
Note
If the arguments given do not result in precisely 1 coordinate factory being matched, an iris.exceptions.CoordinateNotFoundError is raised.
- collapsed(coords, aggregator, **kwargs)¶
Collapse one or more dimensions over the cube given the coordinate/s and an aggregation.
Args:
- coords (string, coord or a list of strings/coords) :
Coordinate names/coordinates over which the cube should be collapsed.
- aggregator (iris.analysis.Aggregator):
Aggregator to be applied for collapse operation.
Kwargs:
- kwargs:
Aggregation function keyword arguments.
- Returns:
- Collapsed cube.
For example:
>>> import iris >>> import iris.analysis >>> cube = iris.load_strict(iris.sample_data_path('ostia_monthly.nc')) >>> new_cube = cube.collapsed('longitude', iris.analysis.MEAN) >>> print new_cube surface_temperature (time: 54; latitude: 18) Dimension coordinates: time x - latitude - x Auxiliary coordinates: forecast_reference_time x - Scalar coordinates: forecast_period: 0 hours longitude: Cell(point=180.0, bound=(0.0, 360.0)) degrees Attributes: Conventions: CF-1.5 STASH: m01s00i024 history: Mean of surface_temperature aggregated over month, year Mean of surface_temperature... Cell methods: mean: month, year mean: longitudeNote
Some aggregations are not commutative and hence the order of processing is important i.e.:
cube.collapsed('realization', iris.analysis.VARIANCE).collapsed('height', iris.analysis.VARIANCE)is not necessarily the same result as:
result2 = cube.collapsed('height', iris.analysis.VARIANCE).collapsed('realization', iris.analysis.VARIANCE)Conversely operations which operate on more than one coordinate at the same time are commutative as they are combined internally into a single operation. Hence the order of the coordinates supplied in the list does not matter:
cube.collapsed(['longitude', 'latitude'], iris.analysis.VARIANCE)is the same (apart from the logically equivalent cell methods that may be created etc.) as:
cube.collapsed(['latitude', 'longitude'], iris.analysis.VARIANCE)
- coord(name=None, standard_name=None, long_name=None, attributes=None, axis=None, contains_dimension=None, dimensions=None, coord=None, coord_system=None, dim_coords=None)¶
Return a single coord given the same arguments as Cube.coords().
Note
If the arguments given do not result in precisely 1 coordinate being matched, an iris.exceptions.CoordinateNotFoundError is raised.
See also
Cube.coords() for full keyword documentation.
- coord_dims(coord)¶
Returns the list of data dimensions relevant to the given coordinate.
When searching for the given coordinate in the cube the comparison is made using coordinate metadata equality. Hence the given coordinate instance need not exist on the cube, and may contain different coordinate values.
Args:
- coord
The iris.coords.Coord instance to look for.
- coord_system(spec)¶
Return the CoordSystem of the given type - or None.
Args:
- spec
- The the name or type of a CoordSystem subclass. E.g
cube.coord_system(“LatLonCS”) cube.coord_system(iris.coord_systems.LatLonCS)
If spec is provided as a type it can be a superclass of any CoordSystems found.
- coords(name=None, standard_name=None, long_name=None, attributes=None, axis=None, contains_dimension=None, dimensions=None, coord=None, coord_system=None, dim_coords=None)¶
Return a list of coordinates in this cube fitting the given criteria.
Kwargs:
- name
The standard name or long name or default name of the desired coordinate. If None, does not check for name. Also see, Cube.name.
- standard_name
The CF standard name of the desired coordinate. If None, does not check for standard name.
- long_name
An unconstrained description of the coordinate. If None, does not check for long_name.
- attributes
A dictionary of attributes desired on the coordinates. If None, does not check for attributes.
- axis
The desired coordinate axis, see iris.util.guess_coord_axis(). If None, does not check for axis. Accepts the values ‘X’, ‘Y’, ‘Z’ and ‘T’ (case-insensitive).
- contains_dimension
The desired coordinate contains the data dimension. If None, does not check for the dimension.
- dimensions
The exact data dimensions of the desired coordinate. Coordinates with no data dimension can be found with an empty list (i.e. []). If None, does not check for dimensions.
- coord
Whether the desired coordinates have metadata equal to the given coordinate instance. If None, no check is done. Accepts either a :class:’iris.coords.DimCoord`, iris.coords.AuxCoord or iris.coords.CoordDefn.
- coord_system
Whether the desired coordinates have coordinate systems equal to the given coordinate system. If None, no check is done.
- dim_coords
Set to True to only return coordinates that are the cube’s dimension coordinates. Set to False to only return coordinates that are the cube’s auxiliary and derived coordinates. If None, returns all coordinates.
See also Cube.coord().
- copy(data=None)¶
Returns a deep copy of this cube.
Kwargs:
- data:
Replace the data of the cube copy with provided data payload.
- Returns:
- A copy instance of the Cube.
- extract(constraint)¶
Filter the cube by the given constraint using iris.Constraint.extract() method.
- extract_by_trajectory(points)¶
Extract a sub-cube at the given n-dimensional points.
Deprecated since version Please: use iris.analysis.trajectory.interpolate() instead of this method.
Args:
- points
Either Array of dicts with identical keys, for example: [ {'latitude':0, 'longitude':0}, {'latitude':1, 'longitude':1} ] Or a iris.analysis.trajectory.Trajectory instance.
The coordinates specified by the points will be boiled down into a single data dimension. (This is so we can make a cube from points [(0, 0), (1, 0), (1, 1)] for example)
- name(default='unknown')¶
Returns a human-readable name.
First it tries standard_name, then it tries the ‘long_name’ attributes, before falling back to the value of default (which itself defaults to ‘unknown’).
- regridded(grid_cube, mode='bilinear', **kwargs)¶
Returns a new cube with values derived from this cube on the horizontal grid specified by the grid_cube.
- remove_aux_factory(aux_factory)¶
Removes the given auxiliary coordinate factory from the cube.
- remove_coord(coord)¶
Removes a coordinate from the cube.
Args:
- coord (string or coord)
The (name of the) coordinate to remove from the cube.
See also Cube.add_coord().
- rename(name)¶
- replace_coord(new_coord)¶
Replace the coordinate whose metadata matches the given coordinate.
- rolling_window(coord, aggregator, window, **kwargs)¶
Perform rolling window aggregation on a cube given a coordinate, an aggregation method and a window size.
Args:
- coord (string/iris.coords.Coord):
The coordinate over which to perform the rolling window aggregation.
- aggregator (iris.analysis.Aggregator):
Aggregator to be applied to the data.
- window (int):
Size of window to use.
Kwargs:
- kwargs:
Aggregator and aggregation function keyword arguments.
- Returns:
- iris.cube.Cube.
For example:
>>> import iris, iris.analysis >>> fname = iris.sample_data_path('GloSea4', 'ensemble_010.pp') >>> air_press = iris.load_strict(fname, 'surface_temperature') >>> print air_press surface_temperature (time: 6; latitude: 145; longitude: 192) Dimension coordinates: time x - - latitude - x - longitude - - x Auxiliary coordinates: forecast_period x - - Scalar coordinates: forecast_reference_time: 364272.0 hours since 1970-01-01 00:00:00 realization: 10 source: Data from Met Office Unified Model 7.06 Attributes: STASH: m01s00i024 Cell methods: mean: time (1 hour)>>> print air_press.rolling_window('time', iris.analysis.MEAN, 3) surface_temperature (time: 4; latitude: 145; longitude: 192) Dimension coordinates: time x - - latitude - x - longitude - - x Auxiliary coordinates: forecast_period x - - Scalar coordinates: forecast_reference_time: 364272.0 hours since 1970-01-01 00:00:00 realization: 10 source: Data from Met Office Unified Model 7.06 Attributes: STASH: m01s00i024 history: Mean of surface_temperature with a rolling window of length 3 over tim... Cell methods: mean: time (1 hour) mean: timeNotice that the forecast_period dimension now represents the 4 possible windows of size 3 from the original cube.
- slices(coords_to_slice, ordered=True)¶
Return an iterator of all cubes given the coordinates desired.
Parameters:
- coords_to_slice (string, coord or a list of strings/coords) :
Coordinate names/coordinates to iterate over. They must all be orthogonal (i.e. point to different dimensions).
Kwargs:
- ordered: if True, the order which the coords to slice are given will be the order in which
they represent the data in the resulting cube slices
- Returns:
- An iterator of sub cubes.
For example, to get all 2d longitude/latitude cubes from a multi-dimensional cube:
for sub_cube in cube.slices(['longitude', 'latitude']): print sub_cube
- subset(coord)¶
Get a subset of the cube by providing the desired resultant coordinate.
- summary(shorten=False, name_padding=35)¶
String summary of the Cube with name, a list of dim coord names versus length and optionally relevant coordinate information.
- transpose(new_order=None)¶
Re-order the data dimensions of the cube in-place.
- new_order - list of ints, optional
- By default, reverse the dimensions, otherwise permute the axes according to the values given.
Note
If defined, new_order must span all of the data dimensions.
Example usage:
# put the second dimension first, followed by the third dimension, and finally put the first dimension third cube.transpose([1, 2, 0])
- xml(checksum=False)¶
Returns a fully valid CubeML string representation of the Cube.
- attributes¶
A dictionary, with a few restricted keys, for arbitrary Cube metadata.
- aux_coords¶
Return a tuple of all the aux_coords, ordered by dimension(s)
- aux_factories¶
Return a tuple of all the coordinate factories.
- cell_methods¶
Tuple of iris.coords.CellMethod representing the processing done on the phenomenon.
- data¶
The numpy.ndarray representing the multi-dimensional data of the cube.
Note
Cubes obtained from netCDF, PP, and FieldsFile files will only populate this attribute on its first use.
To obtain the shape of the data without causing it to be loaded, use the Cube.shape attribute.
- Example::
>>> fname = iris.sample_data_path('air_temp.pp') >>> cube = iris.load_strict(fname, 'air_temperature') # cube.data does not yet have a value. >>> print cube.shape # cube.data still does not have a value. (73, 96) >>> cube = cube[:10, :20] # cube.data still does not have a value. >>> data = cube.data # Only now is the data loaded. >>> print data.shape (10, 20)
- derived_coords¶
Returns a tuple of all the AuxCoords generated from the coordinate factories.
- dim_coords¶
Return a tuple of all the dim_coords, ordered by dimension
- long_name = None¶
The “long name” for the Cube’s phenomenon.
- metadata¶
An instance of CubeMetadata describing the phenomenon.
- This property can be updated with any of:
- another CubeMetadata instance,
- a tuple/dict which can be used to make a CubeMetadata,
- or any object providing the attributes exposed by CubeMetadata.
- ndim¶
The number of dimensions in the data of this cube.
- shape¶
The shape of the data of this cube.
- standard_name¶
The “standard name” for the Cube’s phenomenon.
- title¶
- unit¶
The iris.unit.Unit instance representing the unit of the phenomenon.
Deprecated since version 0.9.
- units¶
An instance of iris.unit.Unit describing the Cube’s data.
All the functionality of a standard list with added “Cube” context.
- class iris.cube.CubeList(list_of_cubes=None)¶
Given a list of cubes, return a CubeList instance.
- append()¶
L.append(object) – append object to end
- count(value) → integer -- return number of occurrences of value¶
- extend()¶
L.extend(iterable) – extend list by appending elements from the iterable
- extract(constraints, strict=False)¶
Filter each of the cubes which can be filtered by the given constraints.
This method iterates over each constraint given, and subsets each of the cubes in this CubeList where possible. Thus, a CubeList of length n when filtered with m constraints can generate a maximum of m * n cubes.
Keywords:
- strict - boolean
If strict is True, then there must be exactly one cube which is filtered per constraint.
- extract_strict(constraints)¶
Calls CubeList.extract() with the strict keyword set to True.
- index(value[, start[, stop]]) → integer -- return first index of value.¶
Raises ValueError if the value is not present.
- insert()¶
L.insert(index, object) – insert object before index
- merge(unique=True)¶
Returns the CubeList resulting from merging this CubeList.
Kwargs:
- unique:
If True, raises iris.exceptions.DuplicateDataError if duplicate cubes are detected.
- pop([index]) → item -- remove and return item at index (default last).¶
Raises IndexError if list is empty or index is out of range.
- remove()¶
L.remove(value) – remove first occurrence of value. Raises ValueError if the value is not present.
- reverse()¶
L.reverse() – reverse IN PLACE
- sort()¶
L.sort(cmp=None, key=None, reverse=False) – stable sort IN PLACE; cmp(x, y) -> -1, 0, 1
- xml(checksum=False)¶
Return a string of the XML that this list of cubes represents.
Represents the phenomenon metadata for a single Cube.
- class iris.cube.CubeMetadata(_cls, standard_name, long_name, units, attributes, cell_methods)¶
Create new instance of CubeMetadata(standard_name, long_name, units, attributes, cell_methods)
- count(value) → integer -- return number of occurrences of value¶
- index(value[, start[, stop]]) → integer -- return first index of value.¶
Raises ValueError if the value is not present.
- name(default='unknown')¶
Returns a human-readable name.
First it tries self.standard_name, then it tries the ‘long_name’ attributes, before falling back to the value of default (which itself defaults to ‘unknown’).
- attributes¶
Alias for field number 3
- cell_methods¶
Alias for field number 4
- long_name¶
Alias for field number 1
- standard_name¶
Alias for field number 0
- units¶
Alias for field number 2