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 (np.typing.ArrayLike) –
This object defines the shape of the cube and the phenomenon value in each cell.
data
can be adask.array.Array
, anumpy.ndarray
, a NumPy array subclass (such asnumpy.ma.MaskedArray
), or array_like (as described innumpy.asarray()
).See
Cube.data
.standard_name (str | None) – The standard name for the Cube’s data.
long_name (str | None) – An unconstrained description of the cube.
var_name (str | None) – The NetCDF variable name for the cube.
units (Unit | str | None) – The unit of the cube, e.g.
"m s-1"
or"kelvin"
.attributes (Mapping | None) – A dictionary of cube attributes.
cell_methods (Iterable[CellMethod] | None) – A tuple of CellMethod objects, generally set by Iris, e.g.
(CellMethod("mean", coords='latitude'), )
.dim_coords_and_dims (Iterable[tuple[DimCoord, int]] | None) – A list of coordinates with scalar dimension mappings, e.g
[(lat_coord, 0), (lon_coord, 1)]
.aux_coords_and_dims (Iterable[tuple[AuxCoord, int | Iterable[int]]] | None) – A list of coordinates with dimension mappings, e.g
[(lat_coord, 0), (lon_coord, (0, 1))]
. See alsoCube.add_dim_coord()
andCube.add_aux_coord()
.aux_factories (Iterable[AuxCoordFactory] | None) – A list of auxiliary coordinate factories. See
iris.aux_factory
.cell_measures_and_dims (Iterable[tuple[CellMeasure, int]] | None) – A list of CellMeasures with dimension mappings.
ancillary_variables_and_dims (Iterable[tuple[AncillaryVariable, int]] | None) – 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)])
- __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.
- Return type:
- add_ancillary_variable(ancillary_variable, data_dims=None)[source]#
Add a CF ancillary variable to the cube.
- Parameters:
ancillary_variable (AncillaryVariable) – The
iris.coords.AncillaryVariable
instance to be added to the cube.data_dims (Iterable[int] | int | None) – 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.
- Return type:
None
- add_aux_coord(coord, data_dims=None)[source]#
Add a CF auxiliary coordinate to the cube.
- Parameters:
coord (AuxCoord | DimCoord) – The
iris.coords.DimCoord
oriris.coords.AuxCoord
instance to add to the cube.data_dims (Iterable[int] | int | None) – 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.
- Return type:
None
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 (AuxCoordFactory) – The
iris.aux_factory.AuxCoordFactory
instance to add.- Return type:
None
- add_cell_measure(cell_measure, data_dims=None)[source]#
Add a CF cell measure to the cube.
- Parameters:
cell_measure (CellMeasure) – The
iris.coords.CellMeasure
instance to add to the cube.data_dims (Iterable[int] | int | None) – 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.
- Return type:
None
See also
remove_cell_measure
Remove a cell measure from the cube.
- add_cell_method(cell_method)[source]#
Add a
CellMethod
to the Cube.- Parameters:
cell_method (CellMethod)
- Return type:
None
- add_dim_coord(dim_coord, data_dim)[source]#
Add a CF coordinate to the cube.
- Parameters:
dim_coord (DimCoord) – The
iris.coords.DimCoord
instance to add to the cube.data_dim (int | tuple[int]) – Integer giving the data dimension spanned by the coordinate.
- 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.
- Return type:
None
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 includeMEAN
andSUM
.Weighted aggregations support an optional weights keyword argument. If set, this can be supplied as an array, cube, or (names of)
coords()
,cell_measures()
, orancillary_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 (str | AuxCoord | DimCoord | Iterable[str | AuxCoord | DimCoord]) – One or more coordinates over which group aggregation is to be performed.
aggregator (Aggregator) – Aggregator to be applied to each group.
climatological (bool) – 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 – Aggregator and aggregation function keyword arguments.
- Return type:
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.- Returns:
A single ancillary variable in this cube fitting the given criteria.
- Return type:
- Parameters:
name_or_ancillary_variable (str | AncillaryVariable | None)
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.
- Returns:
A tuple of the data dimensions relevant to the given ancillary variable.
- Return type:
- 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 (str | AncillaryVariable | None) –
Either
(a) a
standard_name
,long_name
, orvar_name
. Defaults to value of default (which itself defaults to unknown) as defined iniris.common.CFVariableMixin
.(b) a ancillary_variable instance with metadata equal to that of the desired ancillary_variables.
- Returns:
List of ancillary variables in this cube fitting the given criteria.
- Return type:
See also
ancillary_variable
Return a ancillary_variable.
- property attributes: CubeAttrsDict#
- property aux_coords: tuple[AuxCoord | DimCoord, ...]#
Return a tuple of all the auxiliary coordinates, ordered by dimension(s).
- property aux_factories: tuple[AuxCoordFactory, ...]#
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 (str | None) – If not None, matches against factory.name().
standard_name (str | None) – The CF standard name of the desired coordinate factory. If None, does not check for standard name.
long_name (str | None) – An unconstrained description of the coordinate factory. If None, does not check for long_name.
var_name (str | None) – The NetCDF variable name of the desired coordinate factory. If None, does not check for var_name.
- Returns:
The single coordinate factory that matches the criteria.
- Return type:
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.- Returns:
A single cell measure in this cube fitting the given criteria.
- Return type:
- Parameters:
name_or_cell_measure (str | CellMeasure | None)
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 | CellMeasure) – The (name of the) cell measure to look for.
- Returns:
A tuple of the data dimensions relevant to the given cell measure.
- Return type:
- 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 (str | CellMeasure | None) –
Either
(a) a
standard_name
,long_name
, orvar_name
. Defaults to value of default (which itself defaults to unknown) as defined iniris.common.CFVariableMixin
.(b) a cell_measure instance with metadata equal to that of the desired cell_measures.
- Returns:
List of cell measures in this cube fitting the given criteria.
- Return type:
See also
cell_measure
Return a single cell_measure.
- property cell_methods: tuple[CellMethod, ...]#
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
andMAX
.Weighted aggregations (
iris.analysis.WeightedAggregator
) may also be supplied. These includeMEAN
and sumSUM
.Weighted aggregations support an optional weights keyword argument. If set, this can be supplied as an array, cube, or (names of)
coords()
,cell_measures()
, orancillary_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 usingiris.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
oriris.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:
- 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 indata
.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 (str | DimCoord | AuxCoord | AuxCoordFactory | CoordMetadata | None) –
Either,
a
standard_name
,long_name
, orvar_name
which is compared against thename()
.a coordinate or metadata instance equal to that of the desired coordinate e.g.,
DimCoord
orCoordMetadata
.
standard_name (str | None) – The CF standard name of the desired coordinate. If
None
, does not check forstandard name
.long_name (str | None) – An unconstrained description of the coordinate. If
None
, does not check forlong_name
.var_name (str | None) – The NetCDF variable name of the desired coordinate. If
None
, does not check forvar_name
.attributes (Mapping | None) – A dictionary of attributes desired on the coordinates. If
None
, does not check forattributes
.axis (Literal['X', 'Y', 'Z', 'T'] | None) – The desired coordinate axis, see
iris.util.guess_coord_axis()
. IfNone
, does not check foraxis
. Accepts the valuesX
,Y
,Z
andT
(case-insensitive).contains_dimension – The desired coordinate contains the data dimension. If
None
, does not check for the dimension.dimensions (Iterable[int] | int | None) – The exact data dimensions of the desired coordinate. Coordinates with no data dimension can be found with an empty
tuple
orlist
i.e.,()
or[]
. IfNone
, does not check for dimensions.coord_system – Whether the desired coordinates have a coordinate system equal to the given coordinate system. If
None
, no check is done.dim_coords (bool | None) – Set to
True
to only return coordinates that are the cube’s dimension coordinates. Set toFalse
to only return coordinates that are the cube’s auxiliary, mesh and derived coordinates. IfNone
, returns all coordinates.mesh_coords (bool | None) – Set to
True
to return only coordinates which areMeshCoord
's. Set toFalse
to return only non-mesh coordinates. IfNone
, 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 | DimCoord | AuxCoord | AuxCoordFactory) – The (name of the) coord to look for.
- Returns:
A tuple of the data dimensions relevant to the given coordinate.
- Return type:
- 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 (str | type[CoordSystem] | None) –
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 (str | DimCoord | AuxCoord | AuxCoordFactory | CoordMetadata | None) –
Either,
a
standard_name
,long_name
, orvar_name
which is compared against thename()
.a coordinate or metadata instance equal to that of the desired coordinate e.g.,
DimCoord
orCoordMetadata
.
standard_name (str | None) – The CF standard name of the desired coordinate. If
None
, does not check forstandard name
.long_name (str | None) – An unconstrained description of the coordinate. If
None
, does not check forlong_name
.var_name (str | None) – The NetCDF variable name of the desired coordinate. If
None
, does not check forvar_name
.attributes (Mapping | None) – A dictionary of attributes desired on the coordinates. If
None
, does not check forattributes
.axis (Literal['X', 'Y', 'Z', 'T'] | None) – The desired coordinate axis, see
iris.util.guess_coord_axis()
. IfNone
, does not check foraxis
. Accepts the valuesX
,Y
,Z
andT
(case-insensitive).contains_dimension – The desired coordinate contains the data dimension. If
None
, does not check for the dimension.dimensions (Iterable[int] | int | None) – The exact data dimensions of the desired coordinate. Coordinates with no data dimension can be found with an empty
tuple
orlist
i.e.,()
or[]
. IfNone
, does not check for dimensions.coord_system – Whether the desired coordinates have a coordinate system equal to the given coordinate system. If
None
, no check is done.dim_coords (bool | None) – Set to
True
to only return coordinates that are the cube’s dimension coordinates. Set toFalse
to only return coordinates that are the cube’s auxiliary, mesh and derived coordinates. IfNone
, returns all coordinates.mesh_coords (bool | None) – Set to
True
to return only coordinates which areMeshCoord
's. Set toFalse
to return only non-mesh coordinates. IfNone
, 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 (Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | None) – 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: ndarray#
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: tuple[AuxCoord, ...]#
Return a tuple of all the coordinates generated by the coordinate factories.
- property dim_coords: tuple[DimCoord, ...]#
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 theCube.coord()
method with thedimensions
anddim_coords
keyword arguments.
- extract(constraint)[source]#
Filter cube by the given constraint using
iris.Constraint.extract()
.- Parameters:
constraint (Constraint | str | None)
- Return type:
- 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 (Iterable[tuple[AuxCoord | DimCoord | str, Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]]]) – 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 (InterpolationScheme) –
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 iniris.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.
- Return type:
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 ]
- 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
andiris.cube.Cube.attributes
that are present in both objects.- Parameters:
other (Cube | CubeMetadata) – An instance of
iris.cube.Cube
oriris.cube.CubeMetadata
.ignore (Iterable[str] | str | None) – 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:
Notes
See also
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: Literal['edge', 'node', 'face'] | None#
Return the mesh “location” of the cube data.
Return the mesh “location” of the cube data, if the cube has any
MeshCoord
, orNone
if it has none.- Returns:
The mesh location of the cube
MeshCoords
(i.e. one of ‘face’ / ‘edge’ / ‘node’), orNone
.- Return type:
str or None
- property mesh: MeshXY | None#
Return the unstructured
MeshXY
associated with the cube.Return the unstructured
MeshXY
associated with the cube, if the cube has anyMeshCoord
, orNone
if it has none.- Returns:
The mesh of the cube
MeshCoord
’s, orNone
.- Return type:
iris.mesh.MeshXY
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
, orNone
if it has 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 (str | None) – The fall-back string representing the default name. Defaults to the string ‘unknown’.
token (bool) – 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:
- 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:
scheme (RegriddingScheme) –
An instance of the type of regridding to use to regrid this cube onto the target grid. The regridding schemes in Iris currently include:
* Supports lazy regridding.
- 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:
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 | AncillaryVariable) – The (name of the) AncillaryVariable to remove from the cube.
- Return type:
None
- remove_aux_factory(aux_factory)[source]#
Remove the given auxiliary coordinate factory from the cube.
- Parameters:
aux_factory (AuxCoordFactory)
- Return type:
None
- remove_cell_measure(cell_measure)[source]#
Remove a cell measure from the cube.
- Parameters:
cell_measure (str | CellMeasure) –
The (name of the) cell measure to remove from the cube. As either
(a) a
standard_name
,long_name
, orvar_name
. Defaults to value of default (which itself defaults to unknown) as defined iniris.common.CFVariableMixin
.(b) a cell_measure instance with metadata equal to that of the desired cell_measures.
- Return type:
None
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 | DimCoord | AuxCoord | AuxCoordFactory) – The (name of the) coordinate to remove from the cube.
- Return type:
None
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 tolong_name
.- Parameters:
name (str | None)
- Return type:
None
- 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 | AuxCoord | DimCoord) – The coordinate over which to perform the rolling window aggregation.
aggregator (Aggregator) – Aggregator to be applied to the data.
window (int) – Size of window to use.
**kwargs – 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()
, orancillary_variables()
with the same length as the chosen window.
- Return type:
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.
- 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 | AuxCoord | DimCoord | int | Iterable[str | AuxCoord | DimCoord | int]) – 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) – 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 | AuxCoord | DimCoord | int | Iterable[str | AuxCoord | DimCoord | int]) – 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.
- 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) – 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) – Control the minimum width of the cube name + units, i.e. the indent of the dimension map section.
- Return type:
- transpose(new_order=None)[source]#
Re-order the data dimensions of the cube in-place.
- Parameters:
new_order (list[int] | None) – By default, reverse the dimensions, otherwise permute the axes according to the values given.
- Return type:
None
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: Unit#
An instance of
cf_units.Unit
describing the Cube’s data.
- class iris.cube.CubeAttrsDict(combined=None, locals=None, globals=None)[source]#
Bases:
MutableMapping
A
dict
-like object foriris.cube.Cube.attributes
.A
dict
-like object foriris.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
andlocals
are regularLimitedAttributeDict
, which can be accessed and modified separately. TheCubeAttrsDict
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)
isTrue
, butissubclass(CubeAttrsDict, dict)
isFalse
.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 thelocals
andglobals
args, or via acombined
arg which has its own.globals
and.locals
properties – so this allows passing an existingCubeAttrsDict
, 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})
- __getitem__(key)[source]#
Fetch an item from the “combined attributes”.
If the name is present in both
self.locals
andself.globals
, then the local value is returned.
- __iter__()[source]#
Define the combined iteration order.
Result is: all global keys, then all local ones, but omitting duplicates.
- __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
orself.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. #
- 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: LimitedAttributeDict#
- 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: LimitedAttributeDict#
- 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.
- __getslice__(start, stop)[source]#
x.__getslice__(i, j) <==> x[i:j].
Use of negative indices is not supported.
- __str__()[source]#
Run short
Cube.summary()
on every 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 concatenatediris.cube.Cube
instances.- Return type:
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 singleCube
.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.
- 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.
- index(value, start=0, stop=9223372036854775807, /)#
Return first index of value.
Raises ValueError if the value is not present.
- merge(unique=True)[source]#
Return the
CubeList
resulting from merging thisCubeList
.- 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 singleCube
.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.