You are viewing the latest unreleased documentation 3.10.0.dev18. You can switch to a stable version.

iris.cube#

Classes for representing multi-dimensional data with metadata.

class iris.cube.Cube(data, standard_name=None, long_name=None, var_name=None, units=None, attributes=None, cell_methods=None, dim_coords_and_dims=None, aux_coords_and_dims=None, aux_factories=None, cell_measures_and_dims=None, ancillary_variables_and_dims=None)[source]#

Bases: CFVariableMixin

A single Iris cube of data and metadata.

Typically obtained from iris.load(), iris.load_cube(), iris.load_cubes(), or from the manipulation of existing cubes.

For example:

>>> cube = iris.load_cube(iris.sample_data_path('air_temp.pp'))
>>> print(cube)
air_temperature / (K)               (latitude: 73; longitude: 96)
    Dimension coordinates:
        latitude                             x              -
        longitude                            -              x
    Scalar coordinates:
        forecast_period             6477 hours, bound=(-28083.0, 6477.0) hours
        forecast_reference_time     1998-03-01 03:00:00
        pressure                    1000.0 hPa
        time                        1998-12-01 00:00:00, bound=(1994-12-01 00:00:00, 1998-12-01 00:00:00)
    Cell methods:
        0                           time: mean within years
        1                           time: mean over years
    Attributes:
        STASH                       m01s16i203
        source                      'Data from Met Office Unified Model'

See the user guide for more information.

Create 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.

Parameters:
  • data

    This object defines the shape of the cube and the phenomenon value in each cell.

    data can be a dask.array.Array, a numpy.ndarray, a NumPy array subclass (such as numpy.ma.MaskedArray), or array_like (as described in numpy.asarray()).

    See Cube.data.

  • standard_name (optional) – The standard name for the Cube’s data.

  • long_name (optional) – An unconstrained description of the cube.

  • var_name (optional) – The NetCDF variable name for the cube.

  • units (optional) – The unit of the cube, e.g. "m s-1" or "kelvin".

  • attributes (optional) – A dictionary of cube attributes.

  • cell_methods (optional) – A tuple of CellMethod objects, generally set by Iris, e.g. (CellMethod("mean", coords='latitude'), ).

  • dim_coords_and_dims (optional) – A list of coordinates with scalar dimension mappings, e.g [(lat_coord, 0), (lon_coord, 1)].

  • aux_coords_and_dims (optional) – 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 (optional) – A list of auxiliary coordinate factories. See iris.aux_factory.

  • cell_measures_and_dims (optional) – A list of CellMeasures with dimension mappings.

  • ancillary_variables_and_dims (optional) – A list of AncillaryVariables with dimension mappings.

Examples

>>> from iris.coords import DimCoord
>>> from iris.cube import Cube
>>> latitude = DimCoord(np.linspace(-90, 90, 4),
...                     standard_name='latitude',
...                     units='degrees')
>>> longitude = DimCoord(np.linspace(45, 360, 8),
...                      standard_name='longitude',
...                      units='degrees')
>>> cube = Cube(np.zeros((4, 8), np.float32),
...             dim_coords_and_dims=[(latitude, 0),
...                                  (longitude, 1)])
__copy__()[source]#

Shallow copying is disallowed for Cubes.

__getitem__(keys)[source]#

Cube indexing has been implemented at the data level.

Cube indexing (through use of square bracket notation) has been implemented at the data level. That is, the indices provided to this method should be aligned to the data of the cube, and thus the indices requested must be applicable directly to the cube.data attribute. All metadata will be subsequently indexed appropriately.

add_ancillary_variable(ancillary_variable, data_dims=None)[source]#

Add a CF ancillary variable to the cube.

Parameters:
  • ancillary_variable – The iris.coords.AncillaryVariable instance to be added to the cube.

  • data_dims (optional) – Integer or iterable of integers giving the data dimensions spanned by the ancillary variable.

Raises:

ValueError – Raises a ValueError if an ancillary variable with identical metadata already exists on the cube.

add_aux_coord(coord, data_dims=None)[source]#

Add a CF auxiliary coordinate to the cube.

Parameters:
  • coord – The iris.coords.DimCoord or iris.coords.AuxCoord instance to add to the cube.

  • data_dims (optional) – Integer or iterable of integers giving the data dimensions spanned by the coordinate.

Raises:

ValueError – Raises a ValueError if a coordinate with identical metadata already exists on the cube.

See also

remove_coord

Remove a coordinate from the cube.

add_aux_factory(aux_factory)[source]#

Add an auxiliary coordinate factory to the cube.

Parameters:

aux_factory – The iris.aux_factory.AuxCoordFactory instance to add.

add_cell_measure(cell_measure, data_dims=None)[source]#

Add a CF cell measure to the cube.

Parameters:
  • cell_measure – The iris.coords.CellMeasure instance to add to the cube.

  • data_dims (optional) – Integer or iterable of integers giving the data dimensions spanned by the coordinate.

Raises:

ValueError – Raises a ValueError if a cell_measure with identical metadata already exists on the cube.

See also

remove_cell_measure

Remove a cell measure from the cube.

add_cell_method(cell_method)[source]#

Add a CellMethod to the Cube.

add_dim_coord(dim_coord, data_dim)[source]#

Add a CF coordinate to the cube.

Parameters:
Raises:

ValueError – 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

remove_coord

Remove a coordinate from the cube.

aggregated_by(coords, aggregator, climatological=False, **kwargs)[source]#

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. Repeated values will form a group even if they are not consecutive.

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.

Weighted aggregations (iris.analysis.WeightedAggregator) may also be supplied. These include MEAN and SUM.

Weighted aggregations support an optional weights keyword argument. If set, this can be supplied as an array, cube, or (names of) coords(), cell_measures(), or ancillary_variables(). In all cases, the weights should be 1d or match the shape of the cube. When weights are not given as arrays, units are correctly handled for weighted sums, i.e., the original unit of the cube is multiplied by the units of the weights.

Parameters:
  • coords ((list of 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.

  • climatological (bool, default=False) – Indicates whether the output is expected to be climatological. For any aggregated time coord(s), this causes the climatological flag to be set and the point for each cell to equal its first bound, thereby preserving the time of year.

  • **kwargs (dict, optional) – Aggregator and aggregation function keyword arguments.

Return type:

iris.cube.Cube

Examples

>>> import iris
>>> import iris.analysis
>>> import iris.coord_categorisation as cat
>>> fname = iris.sample_data_path('ostia_monthly.nc')
>>> cube = iris.load_cube(fname, 'surface_temperature')
>>> cat.add_year(cube, 'time', name='year')
>>> new_cube = cube.aggregated_by('year', iris.analysis.MEAN)
>>> print(new_cube)
surface_temperature / (K)           (time: 5; latitude: 18; longitude: 432)
    Dimension coordinates:
        time                             x            -              -
        latitude                         -            x              -
        longitude                        -            -              x
    Auxiliary coordinates:
        forecast_reference_time          x            -              -
        year                             x            -              -
    Scalar coordinates:
        forecast_period             0 hours
    Cell methods:
        0                           month: year: mean
        1                           year: mean
    Attributes:
        Conventions                 'CF-1.5'
        STASH                       m01s00i024
ancillary_variable(name_or_ancillary_variable=None)[source]#

Return a single ancillary_variable given the same arguments as Cube.ancillary_variables().

Notes

Note

If the arguments given do not result in precisely 1 ancillary_variable being matched, an iris.exceptions.AncillaryVariableNotFoundError is raised.

See also

ancillary_variables

For full keyword documentation.

ancillary_variable_dims(ancillary_variable)[source]#

Return a tuple of the data dimensions relevant to the given AncillaryVariable.

Parameters:

ancillary_variable (str or AncillaryVariable) – The (name of the) AncillaryVariable to look for.

ancillary_variables(name_or_ancillary_variable=None)[source]#

Return a list of ancillary variable in this cube fitting the given criteria.

Parameters:

name_or_ancillary_variable (optional) –

Either

  • (a) a standard_name, long_name, or var_name. Defaults to value of default (which itself defaults to unknown) as defined in iris.common.CFVariableMixin.

  • (b) a ancillary_variable instance with metadata equal to that of the desired ancillary_variables.

See also

ancillary_variable

Return a single ancillary_variable.

property attributes#

A dictionary for arbitrary Cube metadata. A few keys are restricted - see CubeAttrsDict.

property aux_coords#

Return a tuple of all the auxiliary coordinates, ordered by dimension(s).

property aux_factories#

Return a tuple of all the coordinate factories.

aux_factory(name=None, standard_name=None, long_name=None, var_name=None)[source]#

Return the single coordinate factory that matches the criteria.

Return the single coordinate factory that matches the criteria, or raises an error if not found.

Parameters:
  • name (optional) – If not None, matches against factory.name().

  • standard_name (optional) – The CF standard name of the desired coordinate factory. If None, does not check for standard name.

  • long_name (optional) – An unconstrained description of the coordinate factory. If None, does not check for long_name.

  • var_name (optional) – The NetCDF variable name of the desired coordinate factory. If None, does not check for var_name.

Notes

Note

If the arguments given do not result in precisely 1 coordinate factory being matched, an iris.exceptions.CoordinateNotFoundError is raised.

cell_measure(name_or_cell_measure=None)[source]#

Return a single cell_measure given the same arguments as Cube.cell_measures().

Notes

Note

If the arguments given do not result in precisely 1 cell_measure being matched, an iris.exceptions.CellMeasureNotFoundError is raised.

See also

cell_measures

For full keyword documentation.

cell_measure_dims(cell_measure)[source]#

Return a tuple of the data dimensions relevant to the given CellMeasure.

Parameters:

cell_measure (str or CellMeasure) – The (name of the) cell measure to look for.

cell_measures(name_or_cell_measure=None)[source]#

Return a list of cell measures in this cube fitting the given criteria.

Parameters:

name_or_cell_measure (optional) –

Either

  • (a) a standard_name, long_name, or var_name. Defaults to value of default (which itself defaults to unknown) as defined in iris.common.CFVariableMixin.

  • (b) a cell_measure instance with metadata equal to that of the desired cell_measures.

See also

cell_measure

Return a single cell_measure.

property cell_methods#

Tuple of iris.coords.CellMethod.

Tuple of iris.coords.CellMethod representing the processing done on the phenomenon.

collapsed(coords, aggregator, **kwargs)[source]#

Collapse one or more dimensions over the cube given the coordinate/s and an aggregation.

Examples of aggregations that may be used include COUNT and MAX.

Weighted aggregations (iris.analysis.WeightedAggregator) may also be supplied. These include MEAN and sum SUM.

Weighted aggregations support an optional weights keyword argument. If set, this can be supplied as an array, cube, or (names of) coords(), cell_measures(), or ancillary_variables(). In all cases, the weights should be 1d (for collapsing over a 1d coordinate) or match the shape of the cube. When weights are not given as arrays, units are correctly handled for weighted sums, i.e., the original unit of the cube is multiplied by the units of the weights. Values for latitude-longitude area weights may be calculated using iris.analysis.cartography.area_weights().

Some Iris aggregators support “lazy” evaluation, meaning that cubes resulting from this method may represent data arrays which are not computed until the data is requested (e.g. via cube.data or iris.save). If lazy evaluation exists for the given aggregator it will be used wherever possible when this cube’s data is itself a deferred array.

Parameters:
  • coords (str, 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 (dict, optional) – Aggregation function keyword arguments.

Return type:

Collapsed cube.

Examples

>>> import iris
>>> import iris.analysis
>>> path = iris.sample_data_path('ostia_monthly.nc')
>>> cube = iris.load_cube(path)
>>> new_cube = cube.collapsed('longitude', iris.analysis.MEAN)
>>> print(new_cube)
surface_temperature / (K)           (time: 54; latitude: 18)
    Dimension coordinates:
        time                             x             -
        latitude                         -             x
    Auxiliary coordinates:
        forecast_reference_time          x             -
    Scalar coordinates:
        forecast_period             0 hours
        longitude                   180.0 degrees, bound=(0.0, 360.0) degrees
    Cell methods:
        0                           month: year: mean
        1                           longitude: mean
    Attributes:
        Conventions                 'CF-1.5'
        STASH                       m01s00i024

Notes

Note

Some aggregations are not commutative and hence the order of processing is important i.e.:

tmp = cube.collapsed('realization', iris.analysis.VARIANCE)
result = tmp.collapsed('height', iris.analysis.VARIANCE)

is not necessarily the same result as:

tmp = cube.collapsed('height', iris.analysis.VARIANCE)
result2 = tmp.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)
convert_units(unit)[source]#

Change the cube’s units, converting the values in the data array.

For example, if a cube’s units are kelvin then:

cube.convert_units('celsius')

will change the cube’s units attribute to celsius and subtract 273.15 from each value in data.

Full list of supported units can be found in the UDUNITS-2 documentation https://docs.unidata.ucar.edu/udunits/current/#Database

This operation preserves lazy data.

coord(name_or_coord=None, standard_name=None, long_name=None, var_name=None, attributes=None, axis=None, contains_dimension=None, dimensions=None, coord_system=None, dim_coords=None, mesh_coords=None)[source]#

Return a single coordinate from the Cube that matches the provided criteria.

Parameters:
  • name_or_coord (optional) –

    Either,

  • standard_name (optional) – The CF standard name of the desired coordinate. If None, does not check for standard name.

  • long_name (optional) – An unconstrained description of the coordinate. If None, does not check for long_name.

  • var_name (optional) – The NetCDF variable name of the desired coordinate. If None, does not check for var_name.

  • attributes (optional) – A dictionary of attributes desired on the coordinates. If None, does not check for attributes.

  • axis (optional) – 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 (optional) – The desired coordinate contains the data dimension. If None, does not check for the dimension.

  • dimensions (optional) – The exact data dimensions of the desired coordinate. Coordinates with no data dimension can be found with an empty tuple or list i.e., () or []. If None, does not check for dimensions.

  • coord_system (optional) – Whether the desired coordinates have a coordinate system equal to the given coordinate system. If None, no check is done.

  • dim_coords (optional) – 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, mesh and derived coordinates. If None, returns all coordinates.

  • mesh_coords (optional) – Set to True to return only coordinates which are MeshCoord's. Set to False to return only non-mesh coordinates. If None, returns all coordinates.

Return type:

The coordinate that matches the provided criteria.

Notes

Note

If the arguments given do not result in precisely one coordinate, then a CoordinateNotFoundError is raised.

See also

coords

For matching zero or more coordinates.

coord_dims(coord)[source]#

Return a tuple of the 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.

Parameters:

coord (str or coord) – The (name of the) coord to look for.

coord_system(spec=None)[source]#

Find the coordinate system of the given type.

If no target coordinate system is provided then find any available coordinate system.

Parameters:

spec (optional) –

The the name or type of a coordinate system subclass. E.g.

cube.coord_system("GeogCS")
cube.coord_system(iris.coord_systems.GeogCS)

If spec is provided as a type it can be a superclass of any coordinate system found.

If spec is None, then find any available coordinate systems within the iris.cube.Cube.

Return type:

iris.coord_systems.CoordSystem or None.

coords(name_or_coord=None, standard_name=None, long_name=None, var_name=None, attributes=None, axis=None, contains_dimension=None, dimensions=None, coord_system=None, dim_coords=None, mesh_coords=None)[source]#

Return a list of coordinates from the Cube that match the provided criteria.

Parameters:
  • name_or_coord (optional) –

    Either,

  • standard_name (optional) – The CF standard name of the desired coordinate. If None, does not check for standard name.

  • long_name (optional) – An unconstrained description of the coordinate. If None, does not check for long_name.

  • var_name (optional) – The NetCDF variable name of the desired coordinate. If None, does not check for var_name.

  • attributes (optional) – A dictionary of attributes desired on the coordinates. If None, does not check for attributes.

  • axis (optional) – 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 (optional) – The desired coordinate contains the data dimension. If None, does not check for the dimension.

  • dimensions (optional) – The exact data dimensions of the desired coordinate. Coordinates with no data dimension can be found with an empty tuple or list i.e., () or []. If None, does not check for dimensions.

  • coord_system (optional) – Whether the desired coordinates have a coordinate system equal to the given coordinate system. If None, no check is done.

  • dim_coords (optional) – 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, mesh and derived coordinates. If None, returns all coordinates.

  • mesh_coords (optional) – Set to True to return only coordinates which are MeshCoord's. Set to False to return only non-mesh coordinates. If None, returns all coordinates.

Return type:

A list containing zero or more coordinates matching the provided criteria.

See also

coord

For matching exactly one coordinate.

copy(data=None)[source]#

Return a deep copy of this cube.

Parameters:

data (optional) – Replace the data of the cube copy with provided data payload.

Return type:

A copy instance of the Cube.

core_data()[source]#

Retrieve the data array of this Cube.

Retrieve the data array of this Cube in its current state, which will either be real or lazy.

If this Cube has lazy data, accessing its data array via this method will not realise the data array. This means you can perform operations using this method that work equivalently on real or lazy data, and will maintain lazy data if present.

property data#

The numpy.ndarray representing the multi-dimensional data of the cube.

Notes

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_cube(fname, 'air_temperature')
>>> # cube.data does not yet have a value.
...
>>> print(cube.shape)
(73, 96)
>>> # cube.data still does not have a value.
...
>>> 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)
property derived_coords#

Return a tuple of all the coordinates generated by the coordinate factories.

property dim_coords#

Return a tuple of all the dimension coordinates, ordered by dimension.

Note

The length of the returned tuple is not necessarily the same as Cube.ndim as there may be dimensions on the cube without dimension coordinates. It is therefore unreliable to use the resulting tuple to identify the dimension coordinates for a given dimension - instead use the Cube.coord() method with the dimensions and dim_coords keyword arguments.

property dtype#

The data type of the values in the data array of this Cube.

extract(constraint)[source]#

Filter cube by the given constraint using iris.Constraint.extract().

has_lazy_data()[source]#

Detail whether this Cube has lazy data.

Return type:

bool

interpolate(sample_points, scheme, collapse_scalar=True)[source]#

Interpolate from this Cube to the given sample points.

Interpolate from this Cube to the given sample points using the given interpolation scheme.

Parameters:
  • sample_points – A sequence of (coordinate, points) pairs over which to interpolate. The values for coordinates that correspond to dates or times may optionally be supplied as datetime.datetime or cftime.datetime instances. The N pairs supplied will be used to create an N-d grid of points that will then be sampled (rather than just N points).

  • scheme

    An instance of the type of interpolation to use to interpolate from this Cube to the given sample points. The interpolation schemes currently available in Iris are:

  • collapse_scalar (bool, default=True) – Whether to collapse the dimension of scalar sample points in the resulting cube. Default is True.

Returns:

A cube interpolated at the given sample points. If collapse_scalar is True then the dimensionality of the cube will be the number of original cube dimensions minus the number of scalar coordinates.

Return type:

cube

Examples

>>> import datetime
>>> import iris
>>> path = iris.sample_data_path('uk_hires.pp')
>>> cube = iris.load_cube(path, 'air_potential_temperature')
>>> print(cube.summary(shorten=True))
air_potential_temperature / (K)     (time: 3; model_level_number: 7; grid_latitude: 204; grid_longitude: 187)
>>> print(cube.coord('time'))
DimCoord :  time / (hours since 1970-01-01 00:00:00, standard calendar)
    points: [2009-11-19 10:00:00, 2009-11-19 11:00:00, 2009-11-19 12:00:00]
    shape: (3,)
    dtype: float64
    standard_name: 'time'
>>> print(cube.coord('time').points)
[349618. 349619. 349620.]
>>> samples = [('time', 349618.5)]
>>> result = cube.interpolate(samples, iris.analysis.Linear())
>>> print(result.summary(shorten=True))
air_potential_temperature / (K)     (model_level_number: 7; grid_latitude: 204; grid_longitude: 187)
>>> print(result.coord('time'))
DimCoord :  time / (hours since 1970-01-01 00:00:00, standard calendar)
    points: [2009-11-19 10:30:00]
    shape: (1,)
    dtype: float64
    standard_name: 'time'
>>> print(result.coord('time').points)
[349618.5]
>>> # For datetime-like coordinates, we can also use
>>> # datetime-like objects.
>>> samples = [('time', datetime.datetime(2009, 11, 19, 10, 30))]
>>> result2 = cube.interpolate(samples, iris.analysis.Linear())
>>> print(result2.summary(shorten=True))
air_potential_temperature / (K)     (model_level_number: 7; grid_latitude: 204; grid_longitude: 187)
>>> print(result2.coord('time'))
DimCoord :  time / (hours since 1970-01-01 00:00:00, standard calendar)
    points: [2009-11-19 10:30:00]
    shape: (1,)
    dtype: float64
    standard_name: 'time'
>>> print(result2.coord('time').points)
[349618.5]
>>> print(result == result2)
True
intersection(*args, **kwargs)[source]#

Return the intersection of the cube with specified coordinate ranges.

Coordinate ranges can be specified as:

  • (a) positional arguments: instances of iris.coords.CoordExtent, or equivalent tuples of 3-5 items:

  • (b) keyword arguments, where the keyword name specifies the name of the coordinate, and the value defines the corresponding range of coordinate values as a tuple. The tuple must contain two, three, or four items, corresponding to (minimum, maximum, min_inclusive, max_inclusive) as defined above.

Parameters:
  • coord – Either a iris.coords.Coord, or coordinate name (as defined in iris.cube.Cube.coords()).

  • minimum – The minimum value of the range to select.

  • maximum – The maximum value of the range to select.

  • min_inclusive – If True, coordinate values equal to minimum will be included in the selection. Default is True.

  • max_inclusive – If True, coordinate values equal to maximum will be included in the selection. Default is True.

  • ignore_bounds (optional) – Intersect based on points only. Default False.

  • threshold (optional) – Minimum proportion of a bounded cell that must overlap with the specified range. Default 0.

Notes

Note

For ranges defined over “circular” coordinates (i.e. those where the units attribute has a modulus defined) the cube will be “rolled” to fit where necessary. When requesting a range that covers the entire modulus, a split cell will preferentially be placed at the minimum end.

Warning

Currently this routine only works with “circular” coordinates (as defined in the previous note.)

For example:

>>> import iris
>>> cube = iris.load_cube(iris.sample_data_path('air_temp.pp'))
>>> print(cube.coord('longitude').points[::10])
[   0.           37.49999237   74.99998474  112.49996948  149.99996948
187.49995422  224.99993896  262.49993896  299.99993896  337.49990845]
>>> subset = cube.intersection(longitude=(30, 50))
>>> print(subset.coord('longitude').points)
[ 33.74999237  37.49999237  41.24998856  44.99998856  48.74998856]
>>> subset = cube.intersection(longitude=(-10, 10))
>>> print(subset.coord('longitude').points)
[-7.50012207 -3.75012207  0.          3.75        7.5       ]
Returns:

A new Cube giving the subset of the cube which intersects with the requested coordinate intervals.

Return type:

Cube

is_compatible(other, ignore=None)[source]#

Return whether the cube is compatible with another.

Compatibility is determined by comparing iris.cube.Cube.name(), iris.cube.Cube.units, iris.cube.Cube.cell_methods and iris.cube.Cube.attributes that are present in both objects.

Parameters:
  • other – An instance of iris.cube.Cube or iris.cube.CubeMetadata.

  • ignore (optional) – A single attribute key or iterable of attribute keys to ignore when comparing the cubes. Default is None. To ignore all attributes set this to other.attributes.

Return type:

bool

Notes

Note

This function does not indicate whether the two cubes can be merged, instead it checks only the four items quoted above for equality. Determining whether two cubes will merge requires additional logic that is beyond the scope of this method.

lazy_data()[source]#

Return a “lazy array” representing the Cube data.

Return a “lazy array” representing the Cube data. A lazy array describes an array whose data values have not been loaded into memory from disk.

Accessing this method will never cause the Cube data to be loaded. Similarly, calling methods on, or indexing, the returned Array will not cause the Cube data to be loaded.

If the Cube data have already been loaded (for example by calling data()), the returned Array will be a view of the loaded cube data represented as a lazy array object. Note that this does _not_ make the Cube data lazy again; the Cube data remains loaded in memory.

Return type:

A lazy array, representing the Cube data.

property location#

Return the mesh “location” of the cube data.

Return the mesh “location” of the cube data, if the cube has any MeshCoord, or None if it has none.

Returns:

The mesh location of the cube MeshCoords (i.e. one of ‘face’ / ‘edge’ / ‘node’), or None.

Return type:

str or None

property long_name#

The “long name” for the Cube’s phenomenon.

property mesh#

Return the unstructured Mesh associated with the cube.

Return the unstructured Mesh associated with the cube, if the cube has any MeshCoord, or None if it has none.

Returns:

The mesh of the cube MeshCoord’s, or None.

Return type:

iris.experimental.ugrid.mesh.Mesh or None

mesh_dim()[source]#

Return the cube dimension of the mesh.

Return the cube dimension of the mesh, if the cube has any MeshCoord, or None if it has none.

Returns:

The cube dimension which the cube MeshCoord map to, or None.

Return type:

int or None

property metadata#
name(default=None, token=False)#

Return a string name representing the identity of the metadata.

First it tries standard name, then it tries the long name, then the NetCDF variable name, before falling-back to a default value, which itself defaults to the string ‘unknown’.

Parameters:
  • default (optional) – The fall-back string representing the default name. Defaults to the string ‘unknown’.

  • token (bool, default=False) – If True, ensures that the name returned satisfies the criteria for the characters required by a valid NetCDF name. If it is not possible to return a valid name, then a ValueError exception is raised. Defaults to False.

Return type:

str

property ndim#

The number of dimensions in the data of this cube.

regrid(grid, scheme)[source]#

Regrid this Cube on to the given target grid.

Regrid this Cube on to the given target grid using the given regridding scheme.

Parameters:
Returns:

A cube defined with the horizontal dimensions of the target grid and the other dimensions from this cube. The data values of this cube will be converted to values on the new grid according to the given regridding scheme.

The returned cube will have lazy data if the original cube has lazy data and the regridding scheme supports lazy regridding.

Return type:

cube

Notes

Note

Both the source and target cubes must have a CoordSystem, otherwise this function is not applicable.

remove_ancillary_variable(ancillary_variable)[source]#

Remove an ancillary variable from the cube.

Parameters:

ancillary_variable (str or AncillaryVariable) – The (name of the) AncillaryVariable to remove from the cube.

remove_aux_factory(aux_factory)[source]#

Remove the given auxiliary coordinate factory from the cube.

remove_cell_measure(cell_measure)[source]#

Remove a cell measure from the cube.

Parameters:

cell_measure (str or cell_measure) –

The (name of the) cell measure to remove from the cube. As either

  • (a) a standard_name, long_name, or var_name. Defaults to value of default (which itself defaults to unknown) as defined in iris.common.CFVariableMixin.

  • (b) a cell_measure instance with metadata equal to that of the desired cell_measures.

Notes

If the argument given does not represent a valid cell_measure on the cube, an iris.exceptions.CellMeasureNotFoundError is raised.

See also

add_cell_measure

Add a CF cell measure to the cube.

remove_coord(coord)[source]#

Remove a coordinate from the cube.

Parameters:

coord (str or coord) – The (name of the) coordinate to remove from the cube.

See also

add_dim_coord

Add a CF coordinate to the cube.

add_aux_coord

Add a CF auxiliary coordinate to the cube.

rename(name)#

Change the human-readable name.

If ‘name’ is a valid standard name it will assign it to standard_name, otherwise it will assign it to long_name.

replace_coord(new_coord)[source]#

Replace the coordinate whose metadata matches the given coordinate.

rolling_window(coord, aggregator, window, **kwargs)[source]#

Perform rolling window aggregation on a cube.

Perform rolling window aggregation on a cube given a coordinate, an aggregation method and a window size.

Parameters:
  • coord (str or 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 (dict, optional) – Aggregator and aggregation function keyword arguments. The weights argument to the aggregator, if any, should be a 1d array, cube, or (names of) coords(), cell_measures(), or ancillary_variables() with the same length as the chosen window.

Return type:

iris.cube.Cube.

Notes

Note

This operation does not yet have support for lazy evaluation.

Examples

>>> import iris, iris.analysis
>>> fname = iris.sample_data_path('GloSea4', 'ensemble_010.pp')
>>> cube = iris.load_cube(fname, 'surface_temperature')
>>> print(cube)
surface_temperature / (K)           (time: 6; latitude: 145; longitude: 192)
    Dimension coordinates:
        time                             x            -               -
        latitude                         -            x               -
        longitude                        -            -               x
    Auxiliary coordinates:
        forecast_period                  x            -               -
    Scalar coordinates:
        forecast_reference_time     2011-07-23 00:00:00
        realization                 10
    Cell methods:
        0                           time: mean (interval: 1 hour)
    Attributes:
        STASH                       m01s00i024
        source                      'Data from Met Office Unified Model'
        um_version                  '7.6'
>>> print(cube.rolling_window('time', iris.analysis.MEAN, 3))
surface_temperature / (K)           (time: 4; latitude: 145; longitude: 192)
    Dimension coordinates:
        time                             x            -               -
        latitude                         -            x               -
        longitude                        -            -               x
    Auxiliary coordinates:
        forecast_period                  x            -               -
    Scalar coordinates:
        forecast_reference_time     2011-07-23 00:00:00
        realization                 10
    Cell methods:
        0                           time: mean (interval: 1 hour)
        1                           time: mean
    Attributes:
        STASH                       m01s00i024
        source                      'Data from Met Office Unified Model'
        um_version                  '7.6'

Notice that the forecast_period dimension now represents the 4 possible windows of size 3 from the original cube.

property shape#

The shape of the data of this cube.

slices(ref_to_slice, ordered=True)[source]#

Return an iterator of all subcubes given the coordinates or dimension indices.

Return an iterator of all subcubes given the coordinates or dimension indices desired to be present in each subcube.

Parameters:
  • ref_to_slice (str, coord, dimension index or a list of these) – Determines which dimensions will be returned in the subcubes (i.e. the dimensions that are not iterated over). A mix of input types can also be provided. They must all be orthogonal (i.e. point to different dimensions).

  • ordered (bool, default=True) – If True, subcube dimensions are ordered to match the dimension order in ref_to_slice. If False, the order will follow that of the source cube.

Return type:

An iterator of subcubes.

Examples

For example, for a cube with dimensions realization, time, latitude and longitude:

>>> fname = iris.sample_data_path('GloSea4', 'ensemble_01[01].pp')
>>> cube = iris.load_cube(fname, 'surface_temperature')
>>> print(cube.summary(shorten=True))
surface_temperature / (K)           (realization: 2; time: 6; latitude: 145; longitude: 192)

To get all 12x2D longitude/latitude subcubes:

>>> for sub_cube in cube.slices(['longitude', 'latitude']):
...     print(sub_cube.summary(shorten=True))
surface_temperature / (K)           (longitude: 192; latitude: 145)
surface_temperature / (K)           (longitude: 192; latitude: 145)
surface_temperature / (K)           (longitude: 192; latitude: 145)
surface_temperature / (K)           (longitude: 192; latitude: 145)
surface_temperature / (K)           (longitude: 192; latitude: 145)
surface_temperature / (K)           (longitude: 192; latitude: 145)
surface_temperature / (K)           (longitude: 192; latitude: 145)
surface_temperature / (K)           (longitude: 192; latitude: 145)
surface_temperature / (K)           (longitude: 192; latitude: 145)
surface_temperature / (K)           (longitude: 192; latitude: 145)
surface_temperature / (K)           (longitude: 192; latitude: 145)
surface_temperature / (K)           (longitude: 192; latitude: 145)

Warning

Note that the dimension order returned in the sub_cubes matches the order specified in the cube.slices call, not the order of the dimensions in the original cube.

To get all realizations as 2x3D separate subcubes, using the time, latitude and longitude dimensions’ indices:

>>> for sub_cube in cube.slices([1, 2, 3]):
...     print(sub_cube.summary(shorten=True))
surface_temperature / (K)           (time: 6; latitude: 145; longitude: 192)
surface_temperature / (K)           (time: 6; latitude: 145; longitude: 192)

See also

iris.cube.Cube.slices_over

Return an iterator of all subcubes along a given coordinate or dimension index.

slices_over(ref_to_slice)[source]#

Return an iterator of all subcubes.

Return an iterator of all subcubes along a given coordinate or dimension index, or multiple of these.

Parameters:

ref_to_slice (str, coord, dimension index or a list of these) – Determines which dimensions will be iterated along (i.e. the dimensions that are not returned in the subcubes). A mix of input types can also be provided.

Return type:

An iterator of subcubes.

Examples

For example, for a cube with dimensions realization, time, latitude and longitude:

>>> fname = iris.sample_data_path('GloSea4', 'ensemble_01[01].pp')
>>> cube = iris.load_cube(fname, 'surface_temperature')
>>> print(cube.summary(shorten=True))
surface_temperature / (K)           (realization: 2; time: 6; latitude: 145; longitude: 192)

To get all 12x2D longitude/latitude subcubes:

>>> for sub_cube in cube.slices_over(['realization', 'time']):
...     print(sub_cube.summary(shorten=True))
surface_temperature / (K)           (latitude: 145; longitude: 192)
surface_temperature / (K)           (latitude: 145; longitude: 192)
surface_temperature / (K)           (latitude: 145; longitude: 192)
surface_temperature / (K)           (latitude: 145; longitude: 192)
surface_temperature / (K)           (latitude: 145; longitude: 192)
surface_temperature / (K)           (latitude: 145; longitude: 192)
surface_temperature / (K)           (latitude: 145; longitude: 192)
surface_temperature / (K)           (latitude: 145; longitude: 192)
surface_temperature / (K)           (latitude: 145; longitude: 192)
surface_temperature / (K)           (latitude: 145; longitude: 192)
surface_temperature / (K)           (latitude: 145; longitude: 192)
surface_temperature / (K)           (latitude: 145; longitude: 192)

To get realizations as 2x3D separate subcubes, using the realization dimension index:

>>> for sub_cube in cube.slices_over(0):
...     print(sub_cube.summary(shorten=True))
surface_temperature / (K)           (time: 6; latitude: 145; longitude: 192)
surface_temperature / (K)           (time: 6; latitude: 145; longitude: 192)

Notes

Note

The order of dimension references to slice along does not affect the order of returned items in the iterator; instead the ordering is based on the fastest-changing dimension.

See also

iris.cube.Cube.slices

Return an iterator of all subcubes given the coordinates or dimension indices.

property standard_name#

The “standard name” for the Cube’s phenomenon.

subset(coord)[source]#

Get a subset of the cube by providing the desired resultant coordinate.

Get a subset of the cube by providing the desired resultant coordinate. If the coordinate provided applies to the whole cube; the whole cube is returned. As such, the operation is not strict.

summary(shorten=False, name_padding=35)[source]#

Summary of the Cube.

String summary of the Cube with name+units, a list of dim coord names versus length and, optionally, a summary of all other components.

Parameters:
  • shorten (bool, default=False) – If set, produce a one-line summary of minimal width, showing only the cube name, units and dimensions. When not set (default), produces a full multi-line summary string.

  • name_padding (int, default=35) – Control the minimum width of the cube name + units, i.e. the indent of the dimension map section.

transpose(new_order=None)[source]#

Re-order the data dimensions of the cube in-place.

Parameters:

new_order (list of ints, optional) – By default, reverse the dimensions, otherwise permute the axes according to the values given.

Notes

Note

If defined, new_order must span all of the data dimensions.

Examples

# put the second dimension first, followed by the third dimension,
# and finally put the first dimension third::

    >>> cube.transpose([1, 2, 0])
property units#

An instance of cf_units.Unit describing the Cube’s data.

property var_name#

The NetCDF variable name for the Cube.

xml(checksum=False, order=True, byteorder=True)[source]#

Return a fully valid CubeML string representation of the Cube.

class iris.cube.CubeAttrsDict(combined='__unspecified', locals=None, globals=None)[source]#

Bases: MutableMapping

A dict-like object for iris.cube.Cube.attributes.

A dict-like object for iris.cube.Cube.attributes, providing unified user access to combined cube “local” and “global” attributes dictionaries, with the access behaviour of an ordinary (single) dictionary.

Properties globals and locals are regular LimitedAttributeDict, which can be accessed and modified separately. The CubeAttrsDict itself contains no additional state, but simply provides a ‘combined’ view of both global + local attributes.

All the read- and write-type methods, such as get(), update(), values(), behave according to the logic documented for : __getitem__(), __setitem__() and __iter__().

Notes

For type testing, issubclass(CubeAttrsDict, Mapping) is True, but issubclass(CubeAttrsDict, dict) is False.

Examples

>>> from iris.cube import Cube
>>> cube = Cube([0])
>>> # CF defines 'history' as global by default.
>>> cube.attributes.update({"history": "from test-123", "mycode": 3})
>>> print(cube.attributes)
{'history': 'from test-123', 'mycode': 3}
>>> print(repr(cube.attributes))
CubeAttrsDict(globals={'history': 'from test-123'}, locals={'mycode': 3})
>>> cube.attributes['history'] += ' +added'
>>> print(repr(cube.attributes))
CubeAttrsDict(globals={'history': 'from test-123 +added'}, locals={'mycode': 3})
>>> cube.attributes.locals['history'] = 'per-variable'
>>> print(cube.attributes)
{'history': 'per-variable', 'mycode': 3}
>>> print(repr(cube.attributes))
CubeAttrsDict(globals={'history': 'from test-123 +added'}, locals={'mycode': 3, 'history': 'per-variable'})

Create a cube attributes dictionary.

We support initialisation from a single generic mapping input, using the default global/local assignment rules explained at __setattr__(), or from two separate mappings. Two separate dicts can be passed in the locals and globals args, or via a combined arg which has its own .globals and .locals properties – so this allows passing an existing CubeAttrsDict, which will be copied.

Parameters:
  • combined (dict) – Values to init both ‘self.globals’ and ‘self.locals’. If ‘combined’ itself has attributes named ‘locals’ and ‘globals’, these are used to update the respective content (after initially setting the individual ones). Otherwise, ‘combined’ is treated as a generic mapping, applied as self.update(combined), i.e. it will set locals and/or globals with the same logic as __setitem__() .

  • locals (dict) – Initial content for ‘self.locals’.

  • globals (dict) – Initial content for ‘self.globals’.

Examples

>>> from iris.cube import CubeAttrsDict
>>> # CF defines 'history' as global by default.
>>> CubeAttrsDict({'history': 'data-story', 'comment': 'this-cube'})
CubeAttrsDict(globals={'history': 'data-story'}, locals={'comment': 'this-cube'})
>>> CubeAttrsDict(locals={'history': 'local-history'})
CubeAttrsDict(globals={}, locals={'history': 'local-history'})
>>> CubeAttrsDict(globals={'x': 'global'}, locals={'x': 'local'})
CubeAttrsDict(globals={'x': 'global'}, locals={'x': 'local'})
>>> x1 = CubeAttrsDict(globals={'x': 1}, locals={'y': 2})
>>> x2 = CubeAttrsDict(x1)
>>> x2
CubeAttrsDict(globals={'x': 1}, locals={'y': 2})
__delitem__(key)[source]#

Remove an attribute.

Delete from both local + global.

__getitem__(key)[source]#

Fetch an item from the “combined attributes”.

If the name is present in both self.locals and self.globals, then the local value is returned.

__ior__(arg)[source]#

Implement ‘ior’ via ‘update’.

__iter__()[source]#

Define the combined iteration order.

Result is: all global keys, then all local ones, but omitting duplicates.

__or__(arg)[source]#

Implement ‘or’ via ‘update’.

__ror__(arg)[source]#

Implement ‘ror’ via ‘update’.

This needs to promote, such that the result is a CubeAttrsDict.

__setitem__(key, value)[source]#

Assign an attribute value.

This may be assigned in either self.locals or self.globals, chosen as follows:

  • If there is an existing setting in either .locals or .globals, then that is updated (i.e. overwritten).

  • If it is present in both, only .locals is updated.

  • If there is no existing attribute, it is usually created in .locals. However a handful of “known normally global” cases, as defined by CF, go into .globals instead. At present these are : (‘conventions’, ‘featureType’, ‘history’, ‘title’). See CF Conventions, Appendix A: .

clear() None.  Remove all items from D.#
copy()[source]#

Return a copy.

Implemented with deep copying, consistent with general Iris usage.

classmethod fromkeys(iterable, value=None)[source]#

Create a new object with keys taken from an argument, all set to one value.

If the argument is a split dictionary, preserve the local/global nature of its keys.

get(k[, d]) D[k] if k in D, else d.  d defaults to None.#
property globals#
items() a set-like object providing a view on D's items#
keys() a set-like object providing a view on D's keys#
property locals#
pop(k[, d]) v, remove specified key and return the corresponding value.#

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() (k, v), remove and return some (key, value) pair#

as a 2-tuple; but raise KeyError if D is empty.

setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D#
update(*args, **kwargs)[source]#

Update by adding items from a mapping arg, or keyword-values.

If the argument is a split dictionary, preserve the local/global nature of its keys.

values() an object providing a view on D's values#
class iris.cube.CubeList(*args, **kwargs)[source]#

Bases: list

All the functionality of a standard list with added “Cube” context.

Given an iterable of cubes, return a CubeList instance.

__getitem__(keys)[source]#

x.__getitem__(y) <==> x[y].

__getslice__(start, stop)[source]#

x.__getslice__(i, j) <==> x[i:j].

Use of negative indices is not supported.

__iadd__(other_cubes)[source]#

Add a sequence of cubes to the cubelist in place.

__repr__()[source]#

Run repr on every cube.

__setitem__(key, cube_or_sequence)[source]#

Set self[key] to cube or sequence of cubes.

__str__()[source]#

Run short Cube.summary() on every cube.

append(cube)[source]#

Append a cube.

clear()#

Remove all items from list.

concatenate(check_aux_coords=True, check_cell_measures=True, check_ancils=True, check_derived_coords=True)[source]#

Concatenate the cubes over their common dimensions.

Parameters:
  • check_aux_coords (bool, default=True) – Checks if the points and bounds of auxiliary coordinates of the cubes match. This check is not applied to auxiliary coordinates that span the dimension the concatenation is occurring along. Defaults to True.

  • check_cell_measures (bool, default=True) – Checks if the data of cell measures of the cubes match. This check is not applied to cell measures that span the dimension the concatenation is occurring along. Defaults to True.

  • check_ancils (bool, default=True) – Checks if the data of ancillary variables of the cubes match. This check is not applied to ancillary variables that span the dimension the concatenation is occurring along. Defaults to True.

  • check_derived_coords (bool, default=True) – Checks if the points and bounds of derived coordinates of the cubes match. This check is not applied to derived coordinates that span the dimension the concatenation is occurring along. Note that differences in scalar coordinates and dimensional coordinates used to derive the coordinate are still checked. Checks for auxiliary coordinates used to derive the coordinates can be ignored with check_aux_coords. Defaults to True.

Returns:

A new iris.cube.CubeList of concatenated iris.cube.Cube instances.

Return type:

iris.cube.CubeList

Notes

This combines cubes with a common dimension coordinate, but occupying different regions of the coordinate value. The cubes are joined across that dimension.

For example:

>>> print(c1)
some_parameter / (unknown)          (y_vals: 2; x_vals: 4)
     Dimension coordinates:
          y_vals                           x          -
          x_vals                           -          x
>>> print(c1.coord('y_vals').points)
[4 5]
>>> print(c2)
some_parameter / (unknown)          (y_vals: 3; x_vals: 4)
     Dimension coordinates:
          y_vals                           x          -
          x_vals                           -          x
>>> print(c2.coord('y_vals').points)
[ 7  9 10]
>>> cube_list = iris.cube.CubeList([c1, c2])
>>> new_cube = cube_list.concatenate()[0]
>>> print(new_cube)
some_parameter / (unknown)          (y_vals: 5; x_vals: 4)
     Dimension coordinates:
          y_vals                           x          -
          x_vals                           -          x
>>> print(new_cube.coord('y_vals').points)
[ 4  5  7  9 10]
>>>

Contrast this with iris.cube.CubeList.merge(), which makes a new dimension from values of an auxiliary scalar coordinate.

Note

Cubes may contain ‘extra’ dimensional elements such as auxiliary coordinates, cell measures or ancillary variables. For a group of similar cubes to concatenate together into one output, all such elements which do not map to the concatenation axis must be identical in every input cube : these then appear unchanged in the output. Similarly, those elements which do map to the concatenation axis must have matching properties, but may have different data values : these then appear, concatenated, in the output cube. If any cubes in a group have dimensional elements which do not match correctly, the group will not concatenate to a single output cube.

Note

If time coordinates in the list of cubes have differing epochs then the cubes will not be able to be concatenated. If this occurs, use iris.util.unify_time_units() to normalise the epochs of the time coordinates so that the cubes can be concatenated.

Note

Concatenation cannot occur along an anonymous dimension.

concatenate_cube(check_aux_coords=True, check_cell_measures=True, check_ancils=True, check_derived_coords=True)[source]#

Return the concatenated contents of the CubeList as a single Cube.

If it is not possible to concatenate the CubeList into a single Cube, a ConcatenateError will be raised describing the reason for the failure.

Parameters:
  • check_aux_coords (bool, default=True) – Checks if the points and bounds of auxiliary coordinates of the cubes match. This check is not applied to auxiliary coordinates that span the dimension the concatenation is occurring along. Defaults to True.

  • check_cell_measures (bool, default=True) – Checks if the data of cell measures of the cubes match. This check is not applied to cell measures that span the dimension the concatenation is occurring along. Defaults to True.

  • check_ancils (bool, default=True) – Checks if the data of ancillary variables of the cubes match. This check is not applied to ancillary variables that span the dimension the concatenation is occurring along. Defaults to True.

  • check_derived_coords (bool, default=True) – Checks if the points and bounds of derived coordinates of the cubes match. This check is not applied to derived coordinates that span the dimension the concatenation is occurring along. Note that differences in scalar coordinates and dimensional coordinates used to derive the coordinate are still checked. Checks for auxiliary coordinates used to derive the coordinates can be ignored with check_aux_coords. Defaults to True.

Notes

Note

Concatenation cannot occur along an anonymous dimension.

copy()[source]#

Return a CubeList when CubeList.copy() is called.

count(value, /)#

Return number of occurrences of value.

extend(other_cubes)[source]#

Extend cubelist by appending the cubes contained in other_cubes.

Parameters:

other_cubes – A cubelist or other sequence of cubes.

extract(constraints)[source]#

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.

Parameters:

constraints (Constraint or iterable of constraints) – A single constraint or an iterable.

extract_cube(constraint)[source]#

Extract a single cube from a CubeList, and return it.

Extract a single cube from a CubeList, and return it. Raise an error if the extract produces no cubes, or more than one.

Parameters:

constraint (Constraint) – The constraint to extract with.

See also

iris.cube.CubeList.extract

Filter each of the cubes which can be filtered by the given constraints.

extract_cubes(constraints)[source]#

Extract specific cubes from a CubeList, one for each given constraint.

Extract specific cubes from a CubeList, one for each given constraint. Each constraint must produce exactly one cube, otherwise an error is raised.

Parameters:

constraints (iter of, or single, Constraint) – The constraints to extract with.

See also

iris.cube.CubeList.extract

Filter each of the cubes which can be filtered by the given constraints.

extract_overlapping(coord_names)[source]#

Return a CubeList of cubes extracted over regions.

Return a CubeList of cubes extracted over regions where the coordinates overlap, for the coordinates in coord_names.

Parameters:

coord_names (str or list of str) – A string or list of strings of the names of the coordinates over which to perform the extraction.

index(value, start=0, stop=9223372036854775807, /)#

Return first index of value.

Raises ValueError if the value is not present.

insert(index, cube)[source]#

Insert a cube before index.

merge(unique=True)[source]#

Return the CubeList resulting from merging this CubeList.

Parameters:

unique (bool, default=True) – If True, raises iris.exceptions.DuplicateDataError if duplicate cubes are detected.

Examples

This combines cubes with different values of an auxiliary scalar coordinate, by constructing a new dimension.

>>> print(c1)
some_parameter / (unknown)          (x_vals: 3)
     Dimension coordinates:
          x_vals                           x
     Scalar coordinates:
          y_vals: 100
>>> print(c2)
some_parameter / (unknown)          (x_vals: 3)
     Dimension coordinates:
          x_vals                           x
     Scalar coordinates:
          y_vals: 200
>>> cube_list = iris.cube.CubeList([c1, c2])
>>> new_cube = cube_list.merge()[0]
>>> print(new_cube)
some_parameter / (unknown)          (y_vals: 2; x_vals: 3)
     Dimension coordinates:
          y_vals                           x          -
          x_vals                           -          x
>>> print(new_cube.coord('y_vals').points)
[100 200]
>>>

Contrast this with iris.cube.CubeList.concatenate(), which joins cubes along an existing dimension.

Note

Cubes may contain additional dimensional elements such as auxiliary coordinates, cell measures or ancillary variables. A group of similar cubes can only merge to a single result if all such elements are identical in every input cube : they are then present, unchanged, in the merged output cube.

Note

If time coordinates in the list of cubes have differing epochs then the cubes will not be able to be merged. If this occurs, use iris.util.unify_time_units() to normalise the epochs of the time coordinates so that the cubes can be merged.

merge_cube()[source]#

Return the merged contents of the CubeList as a single Cube.

If it is not possible to merge the CubeList into a single Cube, a MergeError will be raised describing the reason for the failure.

For example:

>>> cube_1 = iris.cube.Cube([1, 2])
>>> cube_1.add_aux_coord(iris.coords.AuxCoord(0, long_name='x'))
>>> cube_2 = iris.cube.Cube([3, 4])
>>> cube_2.add_aux_coord(iris.coords.AuxCoord(1, long_name='x'))
>>> cube_2.add_dim_coord(
...     iris.coords.DimCoord([0, 1], long_name='z'), 0)
>>> single_cube = iris.cube.CubeList([cube_1, cube_2]).merge_cube()
Traceback (most recent call last):
...
iris.exceptions.MergeError: failed to merge into a single cube.
  Coordinates in cube.dim_coords differ: z.
  Coordinate-to-dimension mapping differs for cube.dim_coords.
pop(index=-1, /)#

Remove and return item at index (default last).

Raises IndexError if list is empty or index is out of range.

realise_data()[source]#

Fetch ‘real’ data for all cubes, in a shared calculation.

This computes any lazy data, equivalent to accessing each cube.data. However, lazy calculations and data fetches can be shared between the computations, improving performance.

For example:

# Form stats.
a_std = cube_a.collapsed(['x', 'y'], iris.analysis.STD_DEV)
b_std = cube_b.collapsed(['x', 'y'], iris.analysis.STD_DEV)
ab_mean_diff = (cube_b - cube_a).collapsed(['x', 'y'],
                                           iris.analysis.MEAN)
std_err = (a_std * a_std + b_std * b_std) ** 0.5

# Compute these stats together (avoiding multiple data passes).
CubeList([a_std, b_std, ab_mean_diff, std_err]).realise_data()

Note

Cubes with non-lazy data are not affected.

remove(value, /)#

Remove first occurrence of value.

Raises ValueError if the value is not present.

reverse()#

Reverse IN PLACE.

sort(*, key=None, reverse=False)#

Sort the list in ascending order and return None.

The sort is in-place (i.e. the list itself is modified) and stable (i.e. the order of two equal elements is maintained).

If a key function is given, apply it once to each list item and sort them, ascending or descending, according to their function values.

The reverse flag can be set to sort in descending order.

xml(checksum=False, order=True, byteorder=True)[source]#

Return a string of the XML that this list of cubes represents.