Logo Iris 1.12

Previous topic

13. End of the user guide

Next topic

iris.analysis

This Page

Iris reference documentation

A package for handling multi-dimensional data and associated metadata.

Note

The Iris documentation has further usage information, including a user guide which should be the first port of call for new users.

The functions in this module provide the main way to load and/or save your data.

The load() function provides a simple way to explore data from the interactive Python prompt. It will convert the source data into Cubes, and combine those cubes into higher-dimensional cubes where possible.

The load_cube() and load_cubes() functions are similar to load(), but they raise an exception if the number of cubes is not what was expected. They are more useful in scripts, where they can provide an early sanity check on incoming data.

The load_raw() function is provided for those occasions where the automatic combination of cubes into higher-dimensional cubes is undesirable. However, it is intended as a tool of last resort! If you experience a problem with the automatic combination process then please raise an issue with the Iris developers.

To persist a cube to the file-system, use the save() function.

All the load functions share very similar arguments:

  • uris:

    Either a single filename/URI expressed as a string, or an iterable of filenames/URIs.

    Filenames can contain ~ or ~user abbreviations, and/or Unix shell-style wildcards (e.g. * and ?). See the standard library function os.path.expanduser() and module fnmatch for more details.

  • constraints:

    Either a single constraint, or an iterable of constraints. Each constraint can be either a string, an instance of iris.Constraint, or an instance of iris.AttributeConstraint. If the constraint is a string it will be used to match against cube.name().

    For example:

    # Load air temperature data.
    load_cube(uri, 'air_temperature')
    
    # Load data with a specific model level number.
    load_cube(uri, iris.Constraint(model_level_number=1))
    
    # Load data with a specific STASH code.
    load_cube(uri, iris.AttributeConstraint(STASH='m01s00i004'))
    
  • callback:

    A function to add metadata from the originating field and/or URI which obeys the following rules:

    1. Function signature must be: (cube, field, filename).
    2. Modifies the given cube inplace, unless a new cube is returned by the function.
    3. If the cube is to be rejected the callback must raise an iris.exceptions.IgnoreCubeException.

    For example:

    def callback(cube, field, filename):
        # Extract ID from filenames given as: <prefix>__<exp_id>
        experiment_id = filename.split('__')[1]
        experiment_coord = iris.coords.AuxCoord(
            experiment_id, long_name='experiment_id')
        cube.add_aux_coord(experiment_coord)
    

In this module:

iris.load(uris, constraints=None, callback=None)

Loads any number of Cubes for each constraint.

For a full description of the arguments, please see the module documentation for iris.

Args:

  • uris:

    One or more filenames/URIs.

Kwargs:

  • constraints:

    One or more constraints.

  • callback:

    A modifier/filter function.

Returns:
An iris.cube.CubeList.

↑ top ↑

iris.load_cube(uris, constraint=None, callback=None)

Loads a single cube.

For a full description of the arguments, please see the module documentation for iris.

Args:

  • uris:

    One or more filenames/URIs.

Kwargs:

  • constraints:

    A constraint.

  • callback:

    A modifier/filter function.

Returns:
An iris.cube.Cube.

↑ top ↑

iris.load_cubes(uris, constraints=None, callback=None)

Loads exactly one Cube for each constraint.

For a full description of the arguments, please see the module documentation for iris.

Args:

  • uris:

    One or more filenames/URIs.

Kwargs:

  • constraints:

    One or more constraints.

  • callback:

    A modifier/filter function.

Returns:
An iris.cube.CubeList.

↑ top ↑

iris.load_raw(uris, constraints=None, callback=None)

Loads non-merged cubes.

This function is provided for those occasions where the automatic combination of cubes into higher-dimensional cubes is undesirable. However, it is intended as a tool of last resort! If you experience a problem with the automatic combination process then please raise an issue with the Iris developers.

For a full description of the arguments, please see the module documentation for iris.

Args:

  • uris:

    One or more filenames/URIs.

Kwargs:

  • constraints:

    One or more constraints.

  • callback:

    A modifier/filter function.

Returns:
An iris.cube.CubeList.

↑ top ↑

iris.save(source, target, saver=None, **kwargs)

Save one or more Cubes to file (or other writable).

Iris currently supports three file formats for saving, which it can recognise by filename extension:

A custom saver can be provided to the function to write to a different file format.

Args:

  • source - A iris.cube.Cube, iris.cube.CubeList or

    sequence of cubes.

  • target - A filename (or writable, depending on file format).

    When given a filename or file, Iris can determine the file format.

Kwargs:

  • saver - Optional. Specifies the save function to use.

    If omitted, Iris will attempt to determine the format.

    This keyword can be used to implement a custom save format. Function form must be: my_saver(cube, target) plus any custom keywords. It is assumed that a saver will accept an append keyword if it’s file format can handle multiple cubes. See also iris.io.add_saver().

All other keywords are passed through to the saver function; see the relevant saver documentation for more information on keyword arguments.

Examples:

# Save a cube to PP
iris.save(my_cube, "myfile.pp")

# Save a cube list to a PP file, appending to the contents of the file
# if it already exists
iris.save(my_cube_list, "myfile.pp", append=True)

# Save a cube to netCDF, defaults to NETCDF4 file format
iris.save(my_cube, "myfile.nc")

# Save a cube list to netCDF, using the NETCDF3_CLASSIC storage option
iris.save(my_cube_list, "myfile.nc", netcdf_format="NETCDF3_CLASSIC")

Warning

Saving a cube whose data has been loaded lazily (if cube.has_lazy_data() returns True) to the same file it expects to load data from will cause both the data in-memory and the data on disk to be lost.

cube = iris.load_cube('somefile.nc')
# The next line causes data loss in 'somefile.nc' and the cube.
iris.save(cube, 'somefile.nc')

In general, overwriting a file which is the source for any lazily loaded data can result in corruption. Users should proceed with caution when attempting to overwrite an existing file.

↑ top ↑

Constraints are the mechanism by which cubes can be pattern matched and filtered according to specific criteria.

Once a constraint has been defined, it can be applied to cubes using the Constraint.extract() method.

class iris.Constraint(name=None, cube_func=None, coord_values=None, **kwargs)

Bases: object

Creates a new instance of a Constraint which can be used for filtering cube loading or cube list extraction.

Args:

  • name: string or None

    If a string, it is used as the name to match against Cube.name().

  • cube_func: callable or None

    If a callable, it must accept a Cube as its first and only argument and return either True or False.

  • coord_values: dict or None

    If a dict, it must map coordinate name to the condition on the associated coordinate.

  • **kwargs:

    The remaining keyword arguments are converted to coordinate constraints. The name of the argument gives the name of a coordinate, and the value of the argument is the condition to meet on that coordinate:

    Constraint(model_level_number=10)
    

    Coordinate level constraints can be of several types:

    • string, int or float - the value of the coordinate to match. e.g. model_level_number=10
    • list of values - the possible values that the coordinate may have to match. e.g. model_level_number=[10, 12]
    • callable - a function which accepts a iris.coords.Cell instance as its first and only argument returning True or False if the value of the Cell is desired. e.g. model_level_number=lambda cell: 5 < cell < 10

The user guide covers cube much of constraining in detail, however an example which uses all of the features of this class is given here for completeness:

Constraint(name='air_potential_temperature',
           cube_func=lambda cube: cube.units == 'kelvin',
           coord_values={'latitude':lambda cell: 0 < cell < 90},
           model_level_number=[10, 12])
           & Constraint(ensemble_member=2)

Constraint filtering is performed at the cell level. For further details on how cell comparisons are performed see iris.coords.Cell.

extract(cube)

Return the subset of the given cube which matches this constraint, else return None.

↑ top ↑

Provides a simple Cube-attribute based Constraint.

class iris.AttributeConstraint(**attributes)

Bases: iris._constraints.Constraint

Example usage:

iris.AttributeConstraint(STASH='m01s16i004')

iris.AttributeConstraint(
    STASH=lambda stash: stash.endswith('i005'))

Note

Attribute constraint names are case sensitive.

extract(cube)

Return the subset of the given cube which matches this constraint, else return None.

↑ top ↑

iris.sample_data_path(*path_to_join)

Given the sample data resource, returns the full path to the file.

Note

This function is only for locating files in the iris sample data collection (installed separately from iris). It is not needed or appropriate for general file access.

↑ top ↑

iris.site_configuration

Iris site configuration dictionary.

↑ top ↑

Run-time configuration controller.

class iris.Future(cell_datetime_objects=False, netcdf_promote=False, strict_grib_load=False, netcdf_no_unlimited=False, clip_latitudes=False)

Bases: thread._local

A container for run-time options controls.

To adjust the values simply update the relevant attribute from within your code. For example:

iris.FUTURE.cell_datetime_objects = True

If Iris code is executed with multiple threads, note the values of these options are thread-specific.

The option cell_datetime_objects controls whether the iris.coords.Coord.cell() method returns time coordinate values as simple numbers or as time objects with attributes for year, month, day, etc. In particular, this allows one to express certain time constraints using a simpler, more transparent syntax, such as:

# To select all data defined at midday.
Constraint(time=lambda cell: cell.point.hour == 12)

# To ignore the 29th of February.
Constraint(time=lambda cell: cell.point.day != 29 and
                             cell.point.month != 2)

For more details, see Constraining on Time.

The option netcdf_promote controls whether the netCDF loader will expose variables which define reference surfaces for dimensionless vertical coordinates as independent Cubes.

The option strict_grib_load controls whether GRIB files are loaded as Cubes using a new template-based conversion process. This new conversion process will raise an exception when it encounters a GRIB message which uses a template not supported by the conversion.

Note

Deprecated since version 1.10.

The ‘strict_grib_load’ option is now deprecated, as it affects only the internal grib module iris.fileformats.grib, which is now itself deprecated in favour of ‘iris_grib’. Please remove code which sets this, and instead install the ‘iris_grib’ package : <https://github.com/SciTools/iris-grib>.

The option netcdf_no_unlimited, when True, changes the behaviour of the netCDF saver, such that no dimensions are set to unlimited. The current default is that the leading dimension is unlimited unless otherwise specified.

The option clip_latitudes controls whether the iris.coords.Coord.guess_bounds() method limits the guessed bounds to [-90, 90] for latitudes.

context(*args, **kwds)

Return a context manager which allows temporary modification of the option values for the active thread.

On entry to the with statement, all keyword arguments are applied to the Future object. On exit from the with statement, the previous state is restored.

For example:

with iris.FUTURE.context():
    iris.FUTURE.cell_datetime_objects = True
    # ... code which expects time objects

Or more concisely:

with iris.FUTURE.context(cell_datetime_objects=True):
    # ... code which expects time objects
deprecated_options = {'strict_grib_load': 'This is because "iris.fileformats.grib" is now deprecated : Please install the "iris_grib" package instead.'}

↑ top ↑

iris.FUTURE

Object containing all the Iris run-time options.

↑ top ↑

An Iris deprecation warning.

class iris.IrisDeprecation

Bases: exceptions.UserWarning

An Iris deprecation warning.

args
message