ants.utils package#
Submodules#
ants.utils.coord module#
- ants.utils.coord.guess_bounds(coord, strict=True)[source]#
Guess bounds wrapper around the iris guess bounds functionality.
Additional capability from iris includes sensible guessing of latitude bounds to ensure they remain contiguous and guessing of time bounds for any calendar where points are in the middle of a month.
- Parameters:
coord (
iris.coords.Coord) – Iris coordinate in which to guess its bounds.strict (bool) – Define whether an existing bounds on the coordinate should raise an exception (True - default iris/ants behaviour). When strict is False, coordinates with only one point should continue without failure.
- Raises:
ValueError – Raised if guessing time coordinate bounds isn’t possible. Currently, guessing time bounds is only supported for the case where points are the middle of each month.
- ants.utils.coord.relaxed_equality(coord1, coord2)[source]#
Return whether the provided coordinate is equal to the other provided.
Equality is performed with some tolerance as defined by ants.config.TOLERANCE, however in the case of bounds, a more relaxed independent arbitrary tolerance specified. Where bounds are present on one but not both coordinates, a temporary guess is made of these bounds where possible and a comparison made.
- Parameters:
coord1 (
iris.coords.Coord) –coord2 (
iris.coords.Coord) –
- Returns:
True if coord1 == coord2. False if coord1 != coord2
- Return type:
- ants.utils.coord.set_crs(coord, axis=None, crs=None)[source]#
Set coord coordinate system.
Set coordinate system of the coordinate, correcting and populating metadata where possible.
- Parameters:
coord (
iris.coords.Coord) – Coordinate object to infer a suitable coordinate_system.axis (
str, optional) – The desired coordinate axis. If not specified, it will be guessed, seeiris.util.guess_coord_axis().crs (
iris.coord_systems.CoordSystem, optional) – Defaults to a UM Sphere where unspecified and undefined by the coord (ants.coord_systems.UM_SPHERE).
- Returns:
Inplace operation
- Return type:
None
ants.utils.cube module#
- class ants.utils.cube.CubeBuilder(crs, shape=None, data=None, xlim=None, ylim=None, with_bounds=True, name=None, stash=None)[source]#
Bases:
object- __init__(crs, shape=None, data=None, xlim=None, ylim=None, with_bounds=True, name=None, stash=None)[source]#
Initialises a basic cube with the parameters passed in.
The cube must have a coordinate reference system specified and either a shape or data passed in.
By default, with a iris.coord_systems.GeogCS(6371229.0) and a shape of (2,2), CubeBuilder will create a cube with the cube.summary() of:
unknown / (unknown) (latitude: 2; longitude: 2) Dimension coordinates: latitude x - longitude - x
New in version 2.2.
- Parameters:
crs (A subclass of
iris.coord_systems.CoordSystem) –shape (
tuple, optional) – The shape of the cube to be created.data (
ndarrayoptional) – An array of data the cube will have.xlim (tuple) – A tuple(x0, x1) defining the upper and lower range for axis=’x’.
ylim (tuple) – A tuple(y0, y1) defining the upper and lower range for axis=’y’.
with_bounds (
bool, optional) – The option for the latitude and longitude coordinates on the cube to contain boundsname (
str, optional) – The name of the cube.
- Returns:
Inplace operation
- Return type:
None
- add_3d_time_coord(times)[source]#
Adds a time coordinate to the cube.
- Parameters:
times (int) –
- Returns:
Inplace operation
- Return type:
None
- add_hybrid_height_coordinate_factory(longitude)[source]#
Adds a hybrid height coordinate factory to the cube.
This is required to create a cube with hybrid heights.
- Parameters:
longitude (int) –
- Returns:
Inplace operation
- Return type:
None
- add_hybrid_pressure_coordinate_factory()[source]#
Adds a hybrid pressure coordinate factory to the cube.
This is required to create a cube with hybrid pressure. ANTS does not support hybrid pressure cubes. This should only be used to test exceptions.
- Parameters:
None –
- Returns:
Inplace operation
- Return type:
None
- add_model_level_coordinate(additional_attributes=None)[source]#
Adds a model level coordinate to the cube.
- Parameters:
additional_attributes (
dict, optional) – The default option for additional attributes is None.- Returns:
Inplace operation
- Return type:
None
- add_sigma_aux_coord()[source]#
Adds a sigma auxillary coordinate to the cube.
- Parameters:
None –
- Returns:
Inplace operation
- Return type:
None
- static derive_crs(ellipsoid, north_pole_latitude, north_pole_longitude)[source]#
Checks the north pole coordinates and updates crs accordingly.
- Parameters:
ellipsoid (A subclass of
iris.coord_systems.CoordSystem.) –north_pole_latitude (float) –
north_pole_longitude (float) –
- Return type:
A subclass of
iris.coord_systems.CoordSystem.
- make_cube_curvilinear(crs)[source]#
Generate curvilinear lat-lon cube by translating 1D cube on the specified coordinate system.
- Parameters:
crs (A subclass of
iris.coord_systems.CoordSystem.) –- Returns:
Inplace operation
- Return type:
None
- ants.utils.cube.as_cubelist(cubes)[source]#
Function for ensuring that we return a Cubelist, irrespective of whether a Cube or a CubeList has been provided.
- Parameters:
cubes (
iris.cube.Cubeoriris.cube.CubeList) –- Return type:
- ants.utils.cube.concatenate(cubes)[source]#
Concatenate cubes together.
Convenience wrapper around the iris concatentation functionality, allowing cubes with missing dimension coordinates to be concatenated where there are common aux coords.
- Parameters:
cubes (
iris.cube.CubeListobjects) – Cubes in which to concatenate.- Returns:
New CubeList object of concatenated cubes.
- Return type:
Warning
ants.utils.cube.concatenate()is deprecated as of ANTS 2.0 and will be removed in a future release. Please use the iris methodiris.cube.CubeList.concatenate().See also
iris.cube.CubeList.concatenate()for underlying iris function.
- ants.utils.cube.concatenate_cube(cubes)[source]#
As
concatenate(), only raise an exception on returning more than 1 cube.Warning
ants.utils.cube.concatenate_cube()is deprecated as of ANTS 2.0 and will be removed in a future release. Please use the iris methodiris.cube.CubeList.concatenate_cube().
- ants.utils.cube.create_time_constrained_cubes(cubes, begin_year, end_year)[source]#
Returns the cubes after constraining to the period between begin_year and end_year.
This includes both the begin_year and end_year in the result. Each cube is filtered in turn: this means this function returns the same number of cubes as was input, but each cube is constrained individually.
- Parameters:
cubes (
iris.cube.Cubeoriris.cube.CubeList) – The cubes to be constrained.begin_year (int) – The first year of data to return.
end_year (int) – The last year of data to return.
- Returns:
A CubeList from constraining each individual cube to the time range specified. Note that a
iris.cube.CubeListis always returned, even if the cubes argument is a singleiris.cube.Cube.- Return type:
- Raises:
TimeConstraintOutOfBoundsException – If a cube does not contain data in the specified time range.
DateRangeNotFullyAvailableException – If a cube does not contain all the years requested.
- ants.utils.cube.defer_cube(cube)[source]#
Defer the provided Cube or CubeList.
Write the cube data to disk and load back again resulting in a deferred cube. Automatically cleans up after itself when the python process completes normally. If the python process exits abnormally or is killed (e.g. by a job scheduler), temporary files may remain that need to be deleted manually.
- Parameters:
cube (
iris.cube.Cube) – Cube(s) to defer.- Returns:
Cube(s) with its data deferred to disk.
- Return type:
Note
The temporary file location for output files is determined by the ANTS_TEMPORARY_DIR environment variable.
See
ants.decomposition.See
tempfile.tempdirfor further information concerning temporary file locations.
- ants.utils.cube.derive_circular_status(cube)[source]#
Derive circular attribute of the provided cubes, setting to True where applicable.
- Parameters:
cube (
Cube) – Source cube(s).
- ants.utils.cube.extract_region_by_geometry(cube: Cube, geom: Polygon)[source]#
New in version 2.2: Relocated from the
proc_antspackage, which was removed in ANTS 2.2.Given a cube and a geometry, extract the cube sub-region corresponding to that geometry.
To get a generous bounding box for a geometry (for example, a lake), we buffer this geometry by a percentage of the region size. Two such bufferings are used, and both buffered geometries are returned:
The “extraction geometry” is the geometry we use to extract the cube sub region, using a buffer of 0.25 * region size
The “containment geometry” is the geometry we use to constrain the floodfill, using a buffer of 0.2 * region size
- Parameters:
cube (iris.cube.Cube) – A cube to extract a sub region from
geom (shapely.Polygon) – The geometry defining the area of the cube to extract
- Returns:
A tuple containing:
The extracted cube sub-region
The buffered extraction geometry
The buffered containment geometry
A tuple of slices which subset the source cube to the sub-region, as returned by
ants.utils.cube.get_slices()
- Return type:
tuple[iris.cube.Cube, shapely.Polygon, shapely.Polygon, tuple]
- ants.utils.cube.fetch_seed_index(cube, seed)[source]#
New in version 2.2: Relocated from the
proc_antspackage, which was removed in ANTS 2.2.Given seed value in lat-lon, return the corresponding index within the cube provided.
- Parameters:
cube (iris.cube.Cube) – Cube to find lat-lon seed point
seed (tuple[float, float]) – Latitude, longitude point to find within the provided cube
- Returns:
The x, y indices indentifying the position of the seed point within the cube
- Return type:
- Raises:
ValueError – If the provided seed point is not contained within the extent of the provided source cube domain
- ants.utils.cube.find_time_coordinates(cube)[source]#
Returns the time coodinates of the cube.
Returns the time coordinates of the cube. These are recognised by units, not name, as defined in the CF conventions. Coordinates ‘forecast_reference_time’ and ‘forecast_period’ are ignored for the purposes of this function as they are deleted on load in ANTS.
- Parameters:
cube (
iris.cube.Cube) – Cube to find the time coordinates of.- Returns:
The time coordinates of the cube.
- Return type:
list of
iris.coords.Coordinstances- Raises:
ValueError – If the cube has a coordinate with time units that is not called ‘time’ or if the cube has a coordinate called ‘time’ which does not have time units.
- ants.utils.cube.fix_mask(cube_input)[source]#
Helper routine used to adjust a cube’s mask so that it is of the same shape as the associated data.
Tests the input to see if it should be handled as a cube or cubelist and uses
`_fix_cube_mask(cube)`to carry out the work of adjusting the mask(s).- Parameters:
cube_input (
iris.cube.Cubeoriris.cube.CubeList) –- Returns:
In-place operation.
- Return type:
None
- ants.utils.cube.get_slices(source, ylim, xlim, pad_width=0)[source]#
Return slice objects representing the horizontal grid limits specified.
If cells even only partially overlap the limits, they are included in the slices returned. In the case where there are no bounds, these are inferred.
- Parameters:
source (
iris.cube.Cube) – Source cube to slice.ylim (tuple) – A tuple(y0, y1) defining the upper and lower range for axis=’y’.
xlim (tuple) – A tuple(x0, x1) defining the upper and lower range for axis=’x’.
pad_width (
int, optional) – Pad the slices by the specified number of cells.
- Returns:
Slice objects for slicing the provided cube. The order of the slices corresponds to the mapping to the source provided.
- Return type:
- Raises:
ants.exceptions.NoCoverageError – When no cells can be found within the grid limits specified.
Note
This function is wraparound aware.
- ants.utils.cube.guess_horizontal_bounds(cubes)[source]#
Guess the bounds on the horizontal grid coordinates of one or more cubes.
- Parameters:
cubes (One or more
Cube) – Source cubes on which to guess bounds.
- ants.utils.cube.horizontal_grid(cube, dim_coords=None)[source]#
Return the horizontal coordinates of the cube.
- Parameters:
- Returns:
Tuple of
Coordobjects: (x, y) corresponding to the horizontal grid of the provided cube.- Return type:
- ants.utils.cube.inherit_metadata(source, reference)[source]#
Inherit cube metadata from a provided reference.
Metadata from target is inherited to source from the following: 1. Name (cube.name()) 2. Units 3. cube.attributes[‘grid_staggering’]
- Parameters:
source (
iris.cube.Cube) – Source to have its metadata update.reference (
iris.cube.Cube) – Reference which defines the metadata to inherit from.
- ants.utils.cube.is_equal_hgrid(cubes)[source]#
Determine whether all cubes provided are defined on the same grid.
- ants.utils.cube.reverse_coordinate(cube, coordinate)[source]#
Reverse the direction of a coordinate in a cube.
- Parameters:
cube (
iris.cube.Cube) –coordinate (basestring or
iris.coords.Coordobject.) –
- Return type:
Note
The returned cube shares the same data.
- ants.utils.cube.sanitise_auxcoords(cube)[source]#
Enforce increasing dimension mappings for all coordinates.
Helper function to transpose multidimensional coordinates as necessary to enforce increasing order dimension mappings.
- Parameters:
cube (
Cube) –
Note
Common usage can be after using
iris.cube.Cube.transpose(), see SciTools/iris#2606.
- ants.utils.cube.set_crs(cube, crs=None)[source]#
Set cube coordinate system.
Set coordinate system of the cube, correcting and populating metadata where possible.
- Parameters:
cube (
iris.cube.Cube) – Cube to infer suitable coordinate_system.crs (iris.coord_systems.CoordSystem, optional) – Defaults to a UM Sphere where unspecified and undefined in the cube (ants.coord_systems.UM_SPHERE).
- ants.utils.cube.set_month_mean_for_year(cube, year)[source]#
Set metadata on a cube as if it were a single year of monthly mean data.
This function overrides the existing time coordinate on the cube. It also assumes that the time coordinate starts in January.
In ANTS, until we have better climatology support, this function should be used to set representative climatology times.
- Parameters:
cube (
iris.cube.Cube) –year (int) – year for the data.
- Returns:
In-place operation.
- Return type:
None
- Raises:
RuntimeError – If the cube does not have exactly one time based coordinate.
Warning
Correct representation of climatologies are subject to changes in both iris and ANTS.
Note
See Appendix A: F03 Ancillary file time metadata for further information.
- ants.utils.cube.sort_cubes(primary_sources, alternate_sources)[source]#
Sort the alternate sources to match the ordering of the primary set.
Sorting applies in the case where there is more than one primary and alternate source. The sorting key is firstly uses the STASH attribute, but a fall-back to the name is used where not present. The order of the primary sources will always be unchanged.
- Parameters:
primary_sources (Iterable of
Cubeobjects) – The primary dataset which has a highest priority i.e. overriding values in the alternate dataset.alternate_sources (Iterable of
Cubeobjects) – The alternate data set which is to be merged, taking a lower priority to values contained within the primary dataset.
- Returns:
iterable of
Cubeobjects) Return the primary and alternative sources respectively, sorted according to their STASH or cube.name- Return type:
tuple(iterable of
Cubeobjects,- Raises:
ValueError – When there is no stash/name pair between primary and alternative sources. This means an ambiguous relationship and sorting is not possible.
- ants.utils.cube.update_history(cube, string, date=None, add_date=True)[source]#
Generalised function for updating a cube history attribute.
ISO-format date stamped history attribute update.
- Parameters:
cube (
Cube) – Cube to modify its history attribute.string (str) – Content to populate the history attribute.
date (
datetime.datetime, optional) – ISO-format date stamp for the history atribute update. If not provided, the current date is determined.add_date (
bool, optional) – Boolean to determine whether the date should be prepended to the history content string. True by default.
ants.utils.dask module#
- ants.utils.dask.deferred_data_update(data, overwrite_data, slices)[source]#
Assign new data to the specified slices of data lazily.
With the benefits of dask, override ‘data’ with ‘overwrite_data’ at the specified slices without realising any data.
- Parameters:
data (array_like) – 2D array like object which includes numpy arrays or dask arrays. This represents the arrays which the other is transplanted onto.
new_data (array_like) – 2D array like object which includes numpy arrays or dask arrays. This represents the array which is transplanted into the other.
slices (tuple(slice, slice)) – Slices object representing the 2D slicing of ‘data’ to transplant the ‘overwrite_data’.
- Returns:
Lazy array representing the original array with the new data transplanted onto it.
- Return type:
Note
This function serves the purpose of replacing part of a dask array with some changes.
ants.utils.ndarray module#
- ants.utils.ndarray.allclose(x1, x2, tolerance=None)[source]#
Returns True if two arrays are element-wise equal within ants.config.TOLERANCE.
- ants.utils.ndarray.greater(x1, x2)[source]#
Return the truth value of (x1 > x2) element-wise with tolerance defined by ants.config.TOLERANCE.
- ants.utils.ndarray.group_indices(array)[source]#
Group an array representing indices into an iterable of slice objects.
- Parameters:
array (
numpy.ndarray) – Numpy array representing indices.- Returns:
iterable of slice objects
>>> indices = np.array([0, 1, 2, 4, 5, 6, 8, 9])
>>> group_indices(indices)
[slice(0, 3, None), slice(4, 7, None), slice(8, 10, None)]
- ants.utils.ndarray.in1d(array1, array2)[source]#
Return boolean array that is True where an element of array1 is in array2. The comparison of elements is within a tolerance defined by ants.config.TOLERANCE.
- ants.utils.ndarray.isclose(x1, x2)[source]#
Return the truth value of (x1 == x2) element-wise with tolerance defined by ants.config.TOLERANCE.
- ants.utils.ndarray.less(x1, x2)[source]#
Return the truth value of (x1 < x2) element-wise with tolerance defined by ants.config.TOLERANCE.
- ants.utils.ndarray.merge_array(array1, array2)[source]#
Merge overlapping arrays.
This strictly works by stitching compatible arrays together. Compatible arrays are those considered an extension or a subset of one another. Arrays must also be monotonically increasing/decreasing and currently in the same direction as one another.
- Parameters:
array1 (numpy.ndarray) – Input array.
array2 (numpy.ndarray) – Input array.
- Returns:
numpy.ndarray – Merged array containing the values of both supplied arrays.
>>> arr = np.array([4, 5, 6])
>>> arr2 = np.array([1, 2, 3, 4, 5])
>>> merge_array(arr, arr2)
array([1, 2, 3, 4, 5, 6])
- ants.utils.ndarray.transposed_view(array, axes=None)[source]#
Return a transposed view of the provided array.
A wrapper for numpy transpose which supports taking a transposed view of the mask where present (unlike with numpy transpose).
- Parameters:
array (
numpy.ndarray) –axes (
listofint, optional) – By default, reverse the dimensions, otherwise permute the axes according to the values given.
- Returns:
Data array and masked arrays with their axes permuted. A view is returned whenever possible.
- Return type:
Note
This wrapper exists to overcome the limitations of numpy when dealing with masked arrays, in that a masked array view is not returned but a copy within numpy. See numpy/numpy#7483 for further details.
- ants.utils.ndarray.wrap_lons(points, base, period, endpoint=True)[source]#
Wrap longitudinal points into the closed interval of base to base + period.
The interval includes base and base + period. This differs from
iris.analysis.cartography.wrap_lons()which wraps onto a longitude interval including the base but excluding base + period (in the iris version base + period are mapped to base). See examples.- Parameters:
points (
numpy.ndarray) – Points to wrap.
- Returns:
Points array wrapped to the specified [base, base+period] range at 64bit float.
- Return type:
Examples
This wrap_lons will not wrap points at base + period but will leave them as is:
>>> import numpy as np >>> wrap_lons(np.linspace(-180, 180, 4), -180, 360) array([-180., -60., 60., 180.])
This contrasts with iris’ wrap_lons which will wrap points at base + period to base:
>>> from iris.analysis.cartography import wrap_lons as iwrap_lons >>> iwrap_lons(np.linspace(-180, 180, 4), -180, 360) array([-180., -60., 60., -180.])