From b7825ba6c1efe084b926964c1987c36fc3746dd9 Mon Sep 17 00:00:00 2001 From: Tremain Knight <2108488+tkknight@users.noreply.github.com> Date: Wed, 20 Dec 2023 19:21:24 +0000 Subject: [PATCH 01/21] ruff compliance D405. --- .ruff.toml | 1 - lib/iris/cube.py | 6 ++++-- lib/iris/fileformats/dot.py | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.ruff.toml b/.ruff.toml index 9451023469..106809f3c0 100644 --- a/.ruff.toml +++ b/.ruff.toml @@ -39,7 +39,6 @@ lint.ignore = [ "D205", # 1 blank line required between summary line and description "D401", # First line of docstring should be in imperative mood: ... "D404", # First word of the docstring should not be "This" - "D405", # Section name should be properly capitalized "D406", # Section name should end with a newline "D407", # Missing dashed underline after section diff --git a/lib/iris/cube.py b/lib/iris/cube.py index 1199831b7b..de590ef29a 100644 --- a/lib/iris/cube.py +++ b/lib/iris/cube.py @@ -1621,7 +1621,8 @@ def add_cell_measure(self, cell_measure, data_dims=None): Raises a ValueError if a cell_measure with identical metadata already exists on the cube. - See also + See Also + -------- :meth:`Cube.remove_cell_measure()`. """ @@ -2513,7 +2514,8 @@ def ancillary_variables(self, name_or_ancillary_variable=None): (b) a ancillary_variable instance with metadata equal to that of the desired ancillary_variables. - See also + See Also + -------- :meth:`Cube.ancillary_variable()`. """ diff --git a/lib/iris/fileformats/dot.py b/lib/iris/fileformats/dot.py index 3c24145073..83336a2249 100644 --- a/lib/iris/fileformats/dot.py +++ b/lib/iris/fileformats/dot.py @@ -343,7 +343,7 @@ def _dot_node(indent, id, name, attributes): The ID of the node. name : The visual name of the node. - attributes: + attributes : An iterable of (name, value) attribute pairs. """ # noqa: D410, D411 attributes = r"\n".join("%s: %s" % item for item in attributes) From 7ebd5e006638e5899aaa6c8b1df334df0fa3d3da Mon Sep 17 00:00:00 2001 From: Tremain Knight <2108488+tkknight@users.noreply.github.com> Date: Tue, 26 Dec 2023 13:11:10 +0000 Subject: [PATCH 02/21] ruff complliance with D407. --- .ruff.toml | 2 +- docs/src/Makefile | 2 +- .../documenting/docstrings_attribute.py | 20 +- .../documenting/docstrings_sample_routine.py | 19 +- lib/iris/_concatenate.py | 325 ++++---- lib/iris/_data_manager.py | 87 +- lib/iris/_lazy_data.py | 141 ++-- lib/iris/_merge.py | 452 +++++----- lib/iris/_representation/cube_printout.py | 30 +- lib/iris/analysis/_area_weighted.py | 37 +- lib/iris/analysis/_interpolation.py | 100 +-- lib/iris/analysis/_regrid.py | 183 ++-- lib/iris/analysis/cartography.py | 309 ++++--- lib/iris/analysis/maths.py | 301 ++++--- lib/iris/analysis/stats.py | 20 +- lib/iris/analysis/trajectory.py | 105 ++- lib/iris/common/lenient.py | 113 +-- lib/iris/common/metadata.py | 308 ++++--- lib/iris/common/resolve.py | 371 ++++----- lib/iris/coord_categorisation.py | 90 +- lib/iris/coords.py | 398 ++++----- lib/iris/cube.py | 787 +++++++++--------- lib/iris/experimental/regrid.py | 131 +-- lib/iris/experimental/regrid_conservative.py | 27 +- lib/iris/experimental/ugrid/mesh.py | 398 +++++---- lib/iris/experimental/ugrid/metadata.py | 99 ++- lib/iris/fileformats/_ff.py | 124 +-- lib/iris/fileformats/cf.py | 119 +-- lib/iris/fileformats/name.py | 16 +- lib/iris/fileformats/name_loaders.py | 142 ++-- lib/iris/fileformats/nimrod.py | 19 +- lib/iris/fileformats/pp_load_rules.py | 152 ++-- lib/iris/fileformats/pp_save_rules.py | 124 ++- lib/iris/fileformats/rules.py | 26 +- lib/iris/fileformats/um/_fast_load.py | 28 +- .../um/_fast_load_structured_fields.py | 48 +- lib/iris/fileformats/um/_ff_replacement.py | 48 +- .../um/_optimal_array_structuring.py | 59 +- lib/iris/iterate.py | 23 +- lib/iris/palette.py | 59 +- lib/iris/tests/__init__.py | 97 +-- .../integration/test_netcdf__loadsaveattrs.py | 7 +- lib/iris/tests/stock/mesh.py | 48 +- lib/iris/tests/test_concatenate.py | 88 +- lib/iris/tests/test_cube_to_pp.py | 6 +- .../netcdf/saver/test_Saver__ugrid.py | 73 +- lib/iris/util.py | 368 ++++---- 47 files changed, 3302 insertions(+), 3227 deletions(-) diff --git a/.ruff.toml b/.ruff.toml index 106809f3c0..c8341acac4 100644 --- a/.ruff.toml +++ b/.ruff.toml @@ -40,7 +40,7 @@ lint.ignore = [ "D401", # First line of docstring should be in imperative mood: ... "D404", # First word of the docstring should not be "This" "D406", # Section name should end with a newline - "D407", # Missing dashed underline after section + #"D407", # Missing dashed underline after section # pyupgrade (UP) # https://docs.astral.sh/ruff/rules/#pyupgrade-up diff --git a/docs/src/Makefile b/docs/src/Makefile index 8d652878f6..e260b7a2ed 100644 --- a/docs/src/Makefile +++ b/docs/src/Makefile @@ -72,4 +72,4 @@ show: @python -c "import webbrowser; webbrowser.open_new_tab('file://$(shell pwd)/$(BUILDDIR)/html/index.html')" livehtml: - sphinx-autobuild "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) --ignore generated $(O) \ No newline at end of file + sphinx-autobuild "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) --ignore generated $(O) diff --git a/docs/src/developers_guide/documenting/docstrings_attribute.py b/docs/src/developers_guide/documenting/docstrings_attribute.py index 9485ca5af7..61c29b71b0 100644 --- a/docs/src/developers_guide/documenting/docstrings_attribute.py +++ b/docs/src/developers_guide/documenting/docstrings_attribute.py @@ -4,17 +4,20 @@ class ExampleClass: def __init__(self, arg1, arg2): """Purpose section description. + TREMTEST where is this used? + Description section text. - Args: - - * arg1 (int): + Parameters + ---------- + arg1 : int First argument description. - * arg2 (float): + arg2 : float Second argument description. - Returns: - Boolean. + Returns + ------- + bool """ self.a = arg1 @@ -26,8 +29,9 @@ def __init__(self, arg1, arg2): def square(self): """*(read-only)* Purpose section description. - Returns: - int. + Returns + ------- + int """ return self.a * self.a diff --git a/docs/src/developers_guide/documenting/docstrings_sample_routine.py b/docs/src/developers_guide/documenting/docstrings_sample_routine.py index 65a312c027..d80e0f952b 100644 --- a/docs/src/developers_guide/documenting/docstrings_sample_routine.py +++ b/docs/src/developers_guide/documenting/docstrings_sample_routine.py @@ -3,22 +3,23 @@ def sample_routine(arg1, arg2, kwarg1="foo", kwarg2=None): Description section longer text goes here. - Args: + TREMTEST where is this used? - * arg1 (numpy.ndarray): + Parameters + ---------- + arg1 : numpy.ndarray First argument description. - * arg2 (numpy.ndarray): + arg2 : numpy.ndarray Second argument description. - - Kwargs: - - * kwarg1 (string): + kwarg1: str, optional The first keyword argument. This argument description can be multi-lined. - * kwarg2 (Boolean or None): + kwarg2 : bool or None, optional The second keyword argument. - Returns: + Returns + ------- + numpy.ndarray numpy.ndarray of arg1 * arg2 """ diff --git a/lib/iris/_concatenate.py b/lib/iris/_concatenate.py index 049222953f..fcb72489bd 100644 --- a/lib/iris/_concatenate.py +++ b/lib/iris/_concatenate.py @@ -2,9 +2,7 @@ # # This file is part of Iris and is released under the BSD license. # See LICENSE in the root of the repository for full licensing details. -"""Automatic concatenation of multiple cubes over one or more existing dimensions. - -""" +"""Automatic concatenation of multiple cubes over one or more existing dimensions.""" from collections import defaultdict, namedtuple import warnings @@ -39,13 +37,10 @@ class _CoordAndDims(namedtuple("CoordAndDims", ["coord", "dims"])): """Container for a coordinate and the associated data dimension(s) spanned over a :class:`iris.cube.Cube`. - Args: - - * coord: - A :class:`iris.coords.DimCoord` or :class:`iris.coords.AuxCoord` - coordinate instance. - - * dims: + Parameters + ---------- + coord : :class:`iris.coords.DimCoord` or :class:`iris.coords.AuxCoord` + dims : tuple A tuple of the data dimension(s) spanned by the coordinate. """ @@ -62,22 +57,18 @@ class _CoordMetaData( """Container for the metadata that defines a dimension or auxiliary coordinate. - Args: - - * defn: + Parameters + ---------- + defn : :class:`iris.common.CoordMetadata` The :class:`iris.common.CoordMetadata` metadata that represents a coordinate. - - * dims: + dims : The dimension(s) associated with the coordinate. - - * points_dtype: + points_dtype : :class:`np.dtype` The points data :class:`np.dtype` of an associated coordinate. - - * bounds_dtype: + bounds_dtype : :class:`np.dtype` The bounds data :class:`np.dtype` of an associated coordinate. - - * kwargs: + **kwargs : A dictionary of key/value pairs required to define a coordinate. """ @@ -85,16 +76,15 @@ class _CoordMetaData( def __new__(mcs, coord, dims): """Create a new :class:`_CoordMetaData` instance. - Args: - - * coord: - The :class:`iris.coord.DimCoord` or :class:`iris.coord.AuxCoord`. - - * dims: + Parameters + ---------- + coord : :class:`iris.coord.DimCoord` or :class:`iris.coord.AuxCoord` + dims : The dimension(s) associated with the coordinate. - Returns: - The new class instance. + Returns + ------- + The new class instance. """ defn = coord.metadata @@ -163,17 +153,12 @@ class _DerivedCoordAndDims( """Container for a derived coordinate, the associated AuxCoordFactory, and the associated data dimension(s) spanned over a :class:`iris.cube.Cube`. - Args: - - * coord: - A :class:`iris.coords.DimCoord` or :class:`iris.coords.AuxCoord` - coordinate instance. - - * dims: + Parameters + ---------- + coord : :class:`iris.coord.DimCoord` or :class:`iris.coord.AuxCoord` + dims: tuple A tuple of the data dimension(s) spanned by the coordinate. - - * aux_factory: - A :class:`iris.aux_factory.AuxCoordFactory` instance. + aux_factory : :class:`iris.aux_factory.AuxCoordFactory` """ @@ -193,13 +178,12 @@ class _OtherMetaData(namedtuple("OtherMetaData", ["defn", "dims"])): """Container for the metadata that defines a cell measure or ancillary variable. - Args: - - * defn: + Parameters + ---------- + defn : :class:`iris.coords._DMDefn` or :class:`iris.coords._CellMeasureDefn` The :class:`iris.coords._DMDefn` or :class:`iris.coords._CellMeasureDefn` metadata that represents a coordinate. - - * dims: + dims : The dimension(s) associated with the coordinate. """ @@ -207,17 +191,15 @@ class _OtherMetaData(namedtuple("OtherMetaData", ["defn", "dims"])): def __new__(cls, ancil, dims): """Create a new :class:`_OtherMetaData` instance. - Args: - - * ancil: - The :class:`iris.coord.CellMeasure` or - :class:`iris.coord.AncillaryVariable`. - - * dims: + Parameters + ---------- + ancil : :class:`iris.coord.CellMeasure` or :class:`iris.coord.AncillaryVariable`. + dims : The dimension(s) associated with ancil. - Returns: - The new class instance. + Returns + ------- + The new class instance. """ defn = ancil.metadata @@ -250,12 +232,11 @@ class _SkeletonCube(namedtuple("SkeletonCube", ["signature", "data"])): """Basis of a source-cube, containing the associated coordinate metadata, coordinates and cube data payload. - Args: - - * signature: + Parameters + ---------- + signature : :class:`_CoordSignature` The :class:`_CoordSignature` of an associated source-cube. - - * data: + data : The data payload of an associated :class:`iris.cube.Cube` source-cube. """ @@ -266,12 +247,11 @@ class _SkeletonCube(namedtuple("SkeletonCube", ["signature", "data"])): class _Extent(namedtuple("Extent", ["min", "max"])): """Container representing the limits of a one-dimensional extent/range. - Args: - - * min: + Parameters + ---------- + min : The minimum value of the extent. - - * max: + max : The maximum value of the extent. """ @@ -283,12 +263,12 @@ class _CoordExtent(namedtuple("CoordExtent", ["points", "bounds"])): """Container representing the points and bounds extent of a one dimensional coordinate. - Args: - - * points: + Parameters + ---------- + points : :class:`_Extent` The :class:`_Extent` of the coordinate point values. - * bounds: + bounds : A list containing the :class:`_Extent` of the coordinate lower bound and the upper bound. Defaults to None if no associated bounds exist for the coordinate. @@ -308,34 +288,27 @@ def concatenate( ): """Concatenate the provided cubes over common existing dimensions. - Args: - - * cubes: + Parameters + ---------- + cubes : iter or :class:`iris.cube.Cube` An iterable containing one or more :class:`iris.cube.Cube` instances to be concatenated together. - - Kwargs: - - * error_on_mismatch: + error_on_mismatch: bool, optional If True, raise an informative :class:`~iris.exceptions.ContatenateError` if registration fails. - - * check_aux_coords + check_aux_coords : bool, optional 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 + check_cell_measures : bool, optional 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 + check_ancils : bool, optional 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 + check_derived_coords : bool, optional 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 @@ -344,9 +317,9 @@ def concatenate( derive the coordinates can be ignored with `check_aux_coords`. Defaults to True. - Returns: - A :class:`iris.cube.CubeList` of concatenated :class:`iris.cube.Cube` - instances. + Returns + ------- + A :class:`iris.cube.CubeList` of concatenated :class:`iris.cube.Cube` instances. """ proto_cubes_by_name = defaultdict(list) @@ -409,9 +382,9 @@ def __init__(self, cube): """Represents the cube metadata and associated coordinate metadata that allows suitable cubes for concatenation to be identified. - Args: - - * cube: + Parameters + ---------- + cube : :class:`iris.cube.Cube` The :class:`iris.cube.Cube` source-cube. """ @@ -501,20 +474,20 @@ def _coordinate_differences(self, other, attr, reason="metadata"): """Determine the names of the coordinates that differ between `self` and `other` for a coordinate attribute on a _CubeSignature. - Args: - - * other (_CubeSignature): + Parameters + ---------- + other : _CubeSignature The _CubeSignature to compare against. - - * attr (string): + attr : str The _CubeSignature attribute within which differences exist between `self` and `other`. - - * reason (string): + reason : str The reason to give for mismatch (function is normally, but not always, testing metadata) - Returns: + Returns + ------- + tuple Tuple of a descriptive error message and the names of attributes that differ between `self` and `other`. @@ -550,24 +523,25 @@ def match(self, other, error_on_mismatch): This is the first step to determine if two "cubes" (either a real Cube or a ProtoCube) can be concatenated, by considering: - - data dimensions - - dimensions metadata - - aux coords metadata - - scalar coords - - attributes - - dtype - Args: + * data dimensions + * aux coords metadata + * scalar coords + * attributes + * dtype - * other (_CubeSignature): + Parameters + ---------- + other : _CubeSignature The _CubeSignature to compare against. - - * error_on_mismatch (bool): + error_on_mismatch : bool If True, raise a :class:`~iris.exceptions.MergeException` with a detailed explanation if the two do not match. - Returns: - Boolean. True if and only if this _CubeSignature matches the other. + Returns + ------- + bool + True if and only if this _CubeSignature matches the other. """ msg_template = "{}{} differ: {} != {}" @@ -634,9 +608,9 @@ def __init__(self, cube_signature): non-overlapping :class:`iris.cube.Cube` source-cubes for concatenation over a common single dimension. - Args: - - * cube_signature: + Parameters + ---------- + cube_signature : :class:`_CubeSignature` The :class:`_CubeSignature` that defines the source-cube. """ @@ -658,7 +632,9 @@ def __init__(self, cube_signature): def _cmp(coord, other): """Compare the coordinates for concatenation compatibility. - Returns: + Returns + ------- + bool tuple A boolean tuple pair of whether the coordinates are compatible, and whether they represent a candidate axis of concatenation. @@ -686,14 +662,15 @@ def candidate_axis(self, other): If a candidate axis is found, then the coordinate signatures are compatible. - Args: - - * other: - The :class:`_CoordSignature` + Parameters + ---------- + other : :class:`_CoordSignature` - Returns: - None if no single candidate axis exists, otherwise - the candidate axis of concatenation. + Returns + ------- + result : + None if no single candidate axis exists, otherwise the candidate + axis of concatenation. """ result = False @@ -754,9 +731,9 @@ def __init__(self, cube): """Create a new _ProtoCube from the given cube and record the cube as a source-cube. - Args: - - * cube: + Parameters + ---------- + cube : Source :class:`iris.cube.Cube` of the :class:`_ProtoCube`. """ @@ -788,8 +765,9 @@ def concatenate(self): """Concatenates all the source-cubes registered with the :class:`_ProtoCube` over the nominated common dimension. - Returns: - The concatenated :class:`iris.cube.Cube`. + Returns + ------- + The concatenated :class:`iris.cube.Cube`. """ if len(self._skeletons) > 1: @@ -860,41 +838,35 @@ def register( check_ancils=False, check_derived_coords=False, ): - """Determine whether the given source-cube is suitable for concatenation - with this :class:`_ProtoCube`. + """Determine if the given source-cube is suitable for concatenation. - Args: + Determine if the given source-cube is suitable for concatenation + with this :class:`_ProtoCube`. - * cube: + Parameters + ---------- + cube : :class:`iris.cube.Cube` The :class:`iris.cube.Cube` source-cube candidate for concatenation. - - Kwargs: - - * axis: + axis : optional Seed the dimension of concatenation for the :class:`_ProtoCube` rather than rely on negotiation with source-cubes. - - * error_on_mismatch: + error_on_mismatch : bool, optional If True, raise an informative error if registration fails. - - * check_aux_coords + check_aux_coords : bool, optional 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 False. - - * check_cell_measures + check_cell_measures : bool, optional 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 False. - - * check_ancils + check_ancils : bool, optional 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 False. - - * check_derived_coords + check_derived_coords : bool, optional 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 @@ -903,8 +875,9 @@ def register( coordinates used to derive the coordinates can be ignored with `check_aux_coords`. Defaults to False. - Returns: - Boolean. + Returns + ------- + bool """ # Verify and assert the nominated axis. @@ -1021,13 +994,13 @@ def _add_skeleton(self, coord_signature, data): """Create and add the source-cube skeleton to the :class:`_ProtoCube`. - Args: - - * coord_signature: + Parameters + ---------- + coord_signature : :`_CoordSignature` The :class:`_CoordSignature` of the associated given source-cube. - * data: + data : :class:`iris.cube.Cube` The data payload of an associated :class:`iris.cube.Cube` source-cube. @@ -1039,8 +1012,9 @@ def _build_aux_coordinates(self): """Generate the auxiliary coordinates with associated dimension(s) mapping for the new concatenated cube. - Returns: - A list of auxiliary coordinates and dimension(s) tuple pairs. + Returns + ------- + A list of auxiliary coordinates and dimension(s) tuple pairs. """ # Setup convenience hooks. @@ -1095,8 +1069,9 @@ def _build_aux_coordinates(self): def _build_scalar_coordinates(self): """Generate the scalar coordinates for the new concatenated cube. - Returns: - A list of scalar coordinates. + Returns + ------- + A list of scalar coordinates. """ scalar_coords = [] @@ -1109,8 +1084,9 @@ def _build_cell_measures(self): """Generate the cell measures with associated dimension(s) mapping for the new concatenated cube. - Returns: - A list of cell measures and dimension(s) tuple pairs. + Returns + ------- + A list of cell measures and dimension(s) tuple pairs. """ # Setup convenience hooks. @@ -1146,8 +1122,9 @@ def _build_ancillary_variables(self): """Generate the ancillary variables with associated dimension(s) mapping for the new concatenated cube. - Returns: - A list of ancillary variables and dimension(s) tuple pairs. + Returns + ------- + A list of ancillary variables and dimension(s) tuple pairs. """ # Setup convenience hooks. @@ -1184,21 +1161,20 @@ def _build_aux_factories( ): """Generate the aux factories for the new concatenated cube. - Args: - - * dim_coords_and_dims: + Parameters + ---------- + dim_coords_and_dims : A list of dimension coordinate and dimension tuple pairs from the concatenated cube. - - * aux_coords_and_dims: + aux_coords_and_dims : A list of auxiliary coordinates and dimension(s) tuple pairs from the concatenated cube. - - * scalar_coords: + scalar_coords : A list of scalar coordinates from the concatenated cube. - Returns: - A list of :class:`iris.aux_factory.AuxCoordFactory`. + Returns + ------- + list of :class:`iris.aux_factory.AuxCoordFactory` """ # Setup convenience hooks. @@ -1253,8 +1229,9 @@ def _build_aux_factories( def _build_data(self): """Generate the data payload for the new concatenated cube. - Returns: - The concatenated :class:`iris.cube.Cube` data payload. + Returns + ------- + The concatenated :class:`iris.cube.Cube` data payload. """ skeletons = self._skeletons @@ -1318,16 +1295,16 @@ def _sequence(self, extent, axis): this :class:`_ProtoCube` into non-overlapping segments for the given axis. - Args: - - * extent: + Parameters + ---------- + extent : :class:`_CoordExtent` The :class:`_CoordExtent` of the candidate source-cube. - - * axis: + axis : The candidate axis of concatenation. - Returns: - Boolean. + Returns + ------- + bool """ result = True diff --git a/lib/iris/_data_manager.py b/lib/iris/_data_manager.py index 601066630c..527f9920d1 100644 --- a/lib/iris/_data_manager.py +++ b/lib/iris/_data_manager.py @@ -20,9 +20,9 @@ class DataManager: def __init__(self, data): """Create a data manager for the specified data. - Args: - - * data: + Parameters + ---------- + data : The :class:`~numpy.ndarray` or :class:`~numpy.ma.core.MaskedArray` real data, or :class:`~dask.array.core.Array` lazy data to be managed. @@ -54,9 +54,9 @@ def __deepcopy__(self, memo): """Allow :class:`~iris._data_manager.DataManager` instance deepcopy support. - Args: - - * memo: + Parameters + ---------- + memo : :class:`copy` :class:`copy` memo dictionary. """ @@ -71,14 +71,15 @@ def __eq__(self, other): the realised_dtype, the dtype of the payload, the fill-value and the payload content. - Args: - - * other: + Parameters + ---------- + other : :class:`~iris._data_manager.DataManager` The :class:`~iris._data_manager.DataManager` instance to compare with. - Returns: - Boolean. + Returns + ------- + bool """ from iris.util import array_equal @@ -99,14 +100,15 @@ def __ne__(self, other): Note that, this is explicitly not a lazy operation and will load any lazy payload to determine the inequality result. - Args: - - * other: + Parameters + ---------- + other : :class:`~iris._data_manager.DataManager` The :class:`~iris._data_manager.DataManager` instance to compare with. - Returns: - Boolean. + Returns + ------- + bool """ result = self.__eq__(other) @@ -136,19 +138,17 @@ def _deepcopy(self, memo, data=None): """Perform a deepcopy of the :class:`~iris._data_manager.DataManager` instance. - Args: - - * memo: + Parameters + ---------- + memo : :class:`copy` :class:`copy` memo dictionary. - - Kwargs: - - * data: + data : optional Replacement data to substitute the currently managed data with. - Returns: - :class:`~iris._data_manager.DataManager` instance. + Returns + ------- + :class:`~iris._data_manager.DataManager` instance. """ try: @@ -176,8 +176,9 @@ def _deepcopy(self, memo, data=None): def data(self): """Returns the real data. Any lazy data being managed will be realised. - Returns: - :class:`~numpy.ndarray` or :class:`numpy.ma.core.MaskedArray`. + Returns + ------- + :class:`~numpy.ndarray` or :class:`numpy.ma.core.MaskedArray`. """ if self.has_lazy_data(): @@ -211,9 +212,9 @@ def data(self, data): Note that, the only shape promotion permitted is for 0-dimensional scalar data to be replaced with a single item 1-dimensional data. - Args: - - * data: + Parameters + ---------- + data : The :class:`~numpy.ndarray` or :class:`~numpy.ma.core.MaskedArray` real data, or :class:`~dask.array.core.Array` lazy data to be managed. @@ -272,13 +273,14 @@ def copy(self, data=None): """Returns a deep copy of this :class:`~iris._data_manager.DataManager` instance. - Kwargs: - - * data: + Parameters + ---------- + data : Replace the data of the copy with this data. - Returns: - A copy :class:`~iris._data_manager.DataManager` instance. + Returns + ------- + A copy :class:`~iris._data_manager.DataManager` instance. """ memo = {} @@ -289,8 +291,9 @@ def core_data(self): or :class:`numpy.ma.core.MaskedArray`. Otherwise, return the lazy :class:`~dask.array.core.Array`. - Returns: - The real or lazy data. + Returns + ------- + The real or lazy data. """ if self.has_lazy_data(): @@ -303,8 +306,9 @@ def core_data(self): def has_lazy_data(self): """Determine whether lazy data is being managed. - Returns: - Boolean. + Returns + ------- + bool """ return self._lazy_array is not None @@ -315,8 +319,9 @@ def lazy_data(self): If only real data is being managed, then return a lazy representation of that real data. - Returns: - :class:`~dask.array.core.Array` + Returns + ------- + :class:`~dask.array.core.Array` .. note:: This method will never realise any lazy data. diff --git a/lib/iris/_lazy_data.py b/lib/iris/_lazy_data.py index 5cfa08a7de..81af368203 100644 --- a/lib/iris/_lazy_data.py +++ b/lib/iris/_lazy_data.py @@ -62,40 +62,42 @@ def _optimum_chunksize_internals( size, while prioritising the splitting of the earlier (outer) dimensions and keeping intact the later (inner) ones. - Args: - - * chunks (tuple of int): + Parameters + ---------- + chunks : tuple of int Pre-existing chunk shape of the target data. - * shape (tuple of int): + shape : tuple of int The full array shape of the target data. - * limit (int): + limit : int The 'ideal' target chunk size, in bytes. Default from :mod:`dask.config`. - * dtype (np.dtype): + dtype : np.dtype Numpy dtype of target data. - * dims_fixed (list of bool): + dims_fixed : list of bool If set, a list of values equal in length to 'chunks' or 'shape'. 'True' values indicate a dimension that can not be changed, i.e. that element of the result must equal the corresponding value in 'chunks' or data.shape. - Returns: - * chunk (tuple of int): + Returns + ------- + tuple of int The proposed shape of one full chunk. - .. note:: - The purpose of this is very similar to - :func:`dask.array.core.normalize_chunks`, when called as - `(chunks='auto', shape, dtype=dtype, previous_chunks=chunks, ...)`. - Except, the operation here is optimised specifically for a 'c-like' - dimension order, i.e. outer dimensions first, as for netcdf variables. - So if, in future, this policy can be implemented in dask, then we would - prefer to replace this function with a call to that one. - Accordingly, the arguments roughly match 'normalize_chunks', except - that we don't support the alternative argument forms of that routine. - The return value, however, is a single 'full chunk', rather than a - complete chunking scheme : so an equivalent code usage could be - "chunks = [c[0] for c in normalise_chunks('auto', ...)]". + Notes + ----- + The purpose of this is very similar to + :func:`dask.array.core.normalize_chunks`, when called as + `(chunks='auto', shape, dtype=dtype, previous_chunks=chunks, ...)`. + Except, the operation here is optimised specifically for a 'c-like' + dimension order, i.e. outer dimensions first, as for netcdf variables. + So if, in future, this policy can be implemented in dask, then we would + prefer to replace this function with a call to that one. + Accordingly, the arguments roughly match 'normalize_chunks', except + that we don't support the alternative argument forms of that routine. + The return value, however, is a single 'full chunk', rather than a + complete chunking scheme : so an equivalent code usage could be + "chunks = [c[0] for c in normalise_chunks('auto', ...)]". """ @@ -220,40 +222,37 @@ def as_lazy_data( ): """Convert the input array `data` to a :class:`dask.array.Array`. - Args: - - * data (array-like): + Parameters + ---------- + data : array-like An indexable object with 'shape', 'dtype' and 'ndim' properties. This will be converted to a :class:`dask.array.Array`. - - Kwargs: - - * chunks (list of int): + chunks : list of int, optional If present, a source chunk shape, e.g. for a chunked netcdf variable. - - * asarray (bool): + asarray : bool, optional If True, then chunks will be converted to instances of `ndarray`. Set to False (default) to pass passed chunks through unchanged. - - * dims_fixed (list of bool): + dims_fixed : list of bool, optional If set, a list of values equal in length to 'chunks' or data.ndim. 'True' values indicate a dimension which can not be changed, i.e. the result for that index must equal the value in 'chunks' or data.shape. - - * dask_chunking (bool): + dask_chunking : bool, optional If True, Iris chunking optimisation will be bypassed, and dask's default chunking will be used instead. Including a value for chunks while dask_chunking is set to True will result in a failure. - Returns: + Returns + ------- + :class:`dask.array.Array` The input array converted to a :class:`dask.array.Array`. - .. note:: - The result chunk size is a multiple of 'chunks', if given, up to the - dask default chunksize, i.e. `dask.config.get('array.chunk-size'), - or the full data shape if that is smaller. - If 'chunks' is not given, the result has chunks of the full data shape, - but reduced by a factor if that exceeds the dask default chunksize. + Notes + ----- + The result chunk size is a multiple of 'chunks', if given, up to the + dask default chunksize, i.e. `dask.config.get('array.chunk-size'), + or the full data shape if that is smaller. + If 'chunks' is not given, the result has chunks of the full data shape, + but reduced by a factor if that exceeds the dask default chunksize. """ if dask_chunking: @@ -331,13 +330,14 @@ def as_concrete_data(data): If the input data is lazy, return the realised result. - Args: - - * data: + Parameters + ---------- + data : A dask array, NumPy `ndarray` or masked array - Returns: - A NumPy `ndarray` or masked array. + Returns + ------- + NumPy `ndarray` or masked array. """ if is_lazy_data(data): @@ -352,13 +352,14 @@ def multidim_lazy_stack(stack): This is needed because :meth:`dask.array.Array.stack` only accepts a 1-dimensional list. - Args: - - * stack: + Parameters + ---------- + stack : An ndarray of :class:`dask.array.Array`. - Returns: - The input array converted to a lazy :class:`dask.array.Array`. + Returns + ------- + The input array converted to a lazy :class:`dask.array.Array`. """ if stack.ndim == 0: @@ -380,12 +381,14 @@ def co_realise_cubes(*cubes): However, lazy calculations and data fetches can be shared between the computations, improving performance. - Args: - - * cubes (list of :class:`~iris.cube.Cube`): + Parameters + ---------- + cubes : list of :class:`~iris.cube.Cube` Arguments, each of which is a cube to be realised. - For example:: + Examples + -------- + :: # Form stats. a_std = cube_a.collapsed(['x', 'y'], iris.analysis.STD_DEV) @@ -398,9 +401,9 @@ def co_realise_cubes(*cubes): co_realise_cubes(a_std, b_std, ab_mean_diff, std_err) - .. Note:: + .. note:: - Cubes with non-lazy data may also be passed, with no ill effect. + Cubes with non-lazy data may also be passed, with no ill effect. """ results = _co_realise_lazy_arrays([cube.core_data() for cube in cubes]) @@ -414,13 +417,15 @@ def lazy_elementwise(lazy_array, elementwise_op): Elementwise means that it performs a independent calculation at each point of the input, producing a result array of the same shape. - Args: - - * lazy_array: + Parameters + ---------- + lazy_array : The lazy array object to operate on. - * elementwise_op: + elementwise_op : The elementwise operation, a function operating on numpy arrays. + Notes + ----- .. note: A single-point "dummy" call is made to the operation function, to @@ -445,15 +450,15 @@ def map_complete_blocks(src, func, dims, out_sizes): Complete means that the data is not chunked along the chosen dimensions. - Args: - - * src (:class:`~iris.cube.Cube` or array-like): + Parameters + ---------- + src : :class:`~iris.cube.Cube` or array-like Source cube that function is applied to. - * func: + func : Function to apply. - * dims (tuple of int): + dims : tuple of int Dimensions that cannot be chunked. - * out_sizes (tuple of int): + out_sizes : tuple of int Output size of dimensions that cannot be chunked. """ diff --git a/lib/iris/_merge.py b/lib/iris/_merge.py index 19848ff244..3bed7ef5ee 100644 --- a/lib/iris/_merge.py +++ b/lib/iris/_merge.py @@ -36,21 +36,18 @@ class _Template(namedtuple("Template", ["dims", "points", "bounds", "kwargs"])): """Common framework from which to build a dimension or auxiliary coordinate. - Args: - - * dims: + Parameters + ---------- + dims : Tuple of the associated :class:`iris.cube.Cube` data dimension/s spanned by this coordinate template. - - * points: + points : A :mod:`numpy` array representing the coordinate point data. No points data is represented by None. - - * bounds: + bounds : A :mod:`numpy` array representing the coordinate bounds data. No bounds data is represented by None. - - * kwargs: + kwargs : A dictionary of key/value pairs required to create a coordinate. """ @@ -63,17 +60,15 @@ class _CoordMetaData( ): """Bespoke metadata required to build a dimension or auxiliary coordinate. - Args: - - * points_dtype: + Parameters + ---------- + points_dtype : The points data :class:`numpy.dtype` of an associated coordinate. None otherwise. - - * bounds_dtype: + bounds_dtype : The bounds data :class:`numpy.dtype` of an associated coordinate. None otherwise. - - * kwargs: + kwargs: A dictionary of key/value pairs required to create a coordinate. """ @@ -85,13 +80,12 @@ class _CoordAndDims(namedtuple("CoordAndDims", ["coord", "dims"])): """Container for a coordinate and the associated data dimension/s spanned over a :class:`iris.cube.Cube`. - Args: - - * coord: + Parameters + ---------- + coord : A :class:`iris.coords.DimCoord` or :class:`iris.coords.AuxCoord` coordinate instance. - - * dims: + dims : A tuple of the data dimension/s spanned by the coordinate. """ @@ -108,18 +102,16 @@ class _ScalarCoordPayload( All scalar coordinate related data is sorted into ascending order of the associated coordinate definition. - Args: - - * defns: + Parameters + ---------- + defns : A list of scalar coordinate metadata :class:`iris.common.CoordMetadata` belonging to a :class:`iris.cube.Cube`. - - * values: + values : A list of scalar coordinate values belonging to a :class:`iris.cube.Cube`. Each scalar coordinate value is typically an :class:`iris.coords.Cell`. - - * metadata: + metadata : A list of :class:`_CoordMetaData` instances belonging to a :class:`iris.cube.Cube`. @@ -134,15 +126,14 @@ class _VectorCoordPayload( """Container for all vector coordinate data and metadata represented within a :class:`iris.cube.Cube`. - Args: - - * dim_coords_and_dims: + Parameters + ---------- + dim_coords_and_dims : A list of :class:`_CoordAndDim` instances containing non-scalar (i.e. multi-valued) :class:`iris.coords.DimCoord` instances and the associated data dimension spanned by them for a :class:`iris.cube.Cube`. - - * aux_coords_and_dims: + aux_coords_and_dims : A list of :class:`_CoordAndDim` instances containing non-scalar (i.e. multi-valued) :class:`iris.coords.DimCoord` and/or :class:`iris.coords.AuxCoord` instances and the associated data @@ -161,15 +152,13 @@ class _CoordPayload(namedtuple("CoordPayload", ["scalar", "vector", "factory_def All scalar coordinate and factory related data is sorted into ascending order of the associated coordinate definition. - Args: - - * scalar: + Parameters + ---------- + scalar: A :class:`_ScalarCoordPayload` instance. - - * vector: + vector: A :class:`_VectorCoordPayload` instance. - - * factory_defns: + factory_defns: A list of :class:`_FactoryDefn` instances. """ @@ -215,17 +204,18 @@ def match_signature(self, signature, error_on_mismatch): """Return whether this _CoordPayload matches the corresponding aspects of a _CoordSignature. - Args: - - * signature (_CoordSignature): + Parameters + ---------- + signature : _CoordSignature The _CoordSignature to compare against. - - * error_on_mismatch (bool): + error_on_mismatch : bool If True, raise an Exception with detailed explanation. - Returns: - Boolean. True if and only if this _CoordPayload matches - the corresponding aspects `other`. + Returns + ------- + bool + True if and only if this _CoordPayload matches + the corresponding aspects `other`. """ @@ -288,24 +278,21 @@ class _CoordSignature( based on its scalar and vector coordinate data and metadata, and auxiliary coordinate factories. - Args: - - * scalar_defns: + Parameters + ---------- + scalar_defns : A list of scalar coordinate definitions sorted into ascending order. - - * vector_dim_coords_and_dims: + vector_dim_coords_and_dims : A list of :class:`_CoordAndDim` instances containing non-scalar (i.e. multi-valued) :class:`iris.coords.DimCoord` instances and the associated data dimension spanned by them for a :class:`iris.cube.Cube`. - - * vector_aux_coords_and_dims: + vector_aux_coords_and_dims : A list of :class:`_CoordAndDim` instances containing non-scalar (i.e. multi-valued) :class:`iris.coords.DimCoord` and/or :class:`iris.coords.AuxCoord` instances and the associated data dimension/s spanned by them for a :class:`iris.cube.Cube`. - - * factory_defns: + factory_defns : A list of :class:`_FactoryDefn` instances. """ @@ -328,21 +315,17 @@ class _CubeSignature( """Criterion for identifying a specific type of :class:`iris.cube.Cube` based on its metadata. - Args: - - * defn: + Parameters + ---------- + defn : A cube definition tuple. - - * data_shape: + data_shape : The data payload shape of a :class:`iris.cube.Cube`. - - * data_type: + data_type : The data payload :class:`numpy.dtype` of a :class:`iris.cube.Cube`. - - * cell_measures_and_dims: + cell_measures_and_dims : A list of cell_measures and dims for the cube. - - * ancillary_variables_and_dims: + ancillary_variables_and_dims : A list of ancillary variables and dims for the cube. """ @@ -410,23 +393,25 @@ def match(self, other, error_on_mismatch): This is the first step to determine if two "cubes" (either a real Cube or a ProtoCube) can be merged, by considering: - - standard_name, long_name, var_name - - units - - attributes - - cell_methods - - shape, dtype - Args: + * standard_name, long_name, var_name + * units + * attributes + * cell_methods + * shape, dtype - * other (_CubeSignature): + Parameters + ---------- + other : _CubeSignature The _CubeSignature to compare against. - - * error_on_mismatch (bool): + error_on_mismatch : bool If True, raise a :class:`~iris.exceptions.MergeException` with a detailed explanation if the two do not match. - Returns: - Boolean. True if and only if this _CubeSignature matches `other`. + Returns + ------- + bool + True if and only if this _CubeSignature matches `other`. """ msgs = self._defn_msgs(other.defn) @@ -454,15 +439,14 @@ class _Skeleton(namedtuple("Skeleton", ["scalar_values", "data"])): """Basis of a source-cube, containing the associated scalar coordinate values and data payload of a :class:`iris.cube.Cube`. - Args: - - * scalar_values: + Parameters + ---------- + scalar_values : A list of scalar coordinate values belonging to a :class:`iris.cube.Cube` sorted into ascending order of the associated coordinate definition. Each scalar coordinate value is typically an :class:`iris.coords.Cell`. - - * data: + data : The data payload of a :class:`iris.cube.Cube`. """ @@ -473,12 +457,11 @@ class _Skeleton(namedtuple("Skeleton", ["scalar_values", "data"])): class _FactoryDefn(namedtuple("_FactoryDefn", ["class_", "dependency_defns"])): """The information required to identify and rebuild a single AuxCoordFactory. - Args: - - * class_: + Parameters + ---------- + class_ : The class of the AuxCoordFactory. - - * dependency_defns: + dependency_defns : A list of pairs, where each pair contains a dependency key and its corresponding coordinate definition. Sorted on dependency key. @@ -492,12 +475,11 @@ class _Relation(namedtuple("Relation", ["separable", "inseparable"])): :class:`ProtoCube` into separable 'independent' dimensions, and inseparable dependent dimensions. - Args: - - * separable: + Parameters + ---------- + separable : A set of independent candidate dimension names. - - * inseparable: + inseparable : A set of dependent candidate dimension names. """ @@ -512,13 +494,14 @@ def _is_combination(name): """Determine whether the candidate dimension is an 'invented' combination of candidate dimensions. - Args: - - * name: + Parameters + ---------- + name : The candidate dimension. - Returns: - Boolean. + Returns + ------- + bool """ return _COMBINATION_JOIN in str(name) @@ -557,14 +540,15 @@ def build_indexes(positions): 200: 'a': set([1]) 'b': set([10]) 300: 'a': set([2]) 'b': set([20]) - Args: - - * positions: + Parameters + ---------- + positions : A list containing a dictionary of candidate dimension key to scalar value pairs for each source-cube. - Returns: - The cross-reference dictionary for each candidate dimension. + Returns + ------- + The cross-reference dictionary for each candidate dimension. """ names = positions[0].keys() @@ -595,20 +579,19 @@ def _separable_pair(name, index): A candidate dimension X and Y are separable if each scalar value of X maps to the same set of scalar values of Y. - Args: - - * name1: + Parameters + ---------- + name1 : The first candidate dimension to be compared. - - * name2: + name2 : The second candidate dimension to be compared. - - * index: + index : The cross-reference dictionary for the first candidate dimension. - Returns: - Boolean. + Returns + ------- + bool """ items = iter(index.values()) @@ -624,16 +607,17 @@ def _separable(name, indexes): A candidate dimension X and Y are separable if each scalar value of X maps to the same set of scalar values of Y. - Args: - - * name: + Parameters + ---------- + name : The candidate dimension that requires its separable and inseparable relationship to be determined. - - * indexes: + indexes : The cross-reference dictionary for each candidate dimension. - Returns: + Returns + ------- + tupl A tuple containing the set of separable and inseparable candidate dimensions. @@ -676,13 +660,14 @@ def derive_relation_matrix(indexes): 'c': Relation(separable=set([]), inseparable=set(['a', 'b'])) 'b': Relation(separable=set([]), inseparable=set(['a', 'c'])) - Args: - - * indexes: + Parameters + ---------- + indexes : The cross-reference dictionary for each candidate dimension. - Returns: - The relation dictionary for each candidate dimension. + Returns + ------- + The relation dictionary for each candidate dimension. """ # TODO: This takes twice as long as it could do because it doesn't @@ -698,13 +683,14 @@ def derive_groups(relation_matrix): If candidate dimension A is inseparable for B and C, and B is inseparable from D, and E is inseparable from F. Then the groups are ABCD and EF. - Args: - - * relation_matrix: + Parameters + ---------- + relation_matrix : The relation dictionary for each candidate dimension. - Returns: - A list of all related (chained) inseparable candidate dimensions. + Returns + ------- + A list of all related (chained) inseparable candidate dimensions. """ names = set(relation_matrix) @@ -730,17 +716,16 @@ def derive_groups(relation_matrix): def _derive_separable_group(relation_matrix, group): """Determine which candidate dimensions in the group are separable. - Args: - - * relation_matrix: + Parameters + ---------- + relation_matrix : The relation dictionary for each candidate dimension. - - * group: + group : A set of related (chained) inseparable candidate dimensions. - Returns: - The set of candidate dimensions within the group that are - separable. + Returns + ------- + The set of candidate dimensions within the group that are separable. """ result = set() @@ -757,29 +742,25 @@ def _is_dependent(dependent, independent, positions, function_mapping=None): between the independent candidate dimension/s and the dependent candidate dimension. - Args: - - * dependent: + Parameters + ---------- + dependent : A candidate dimension that requires to be functionally dependent on all the independent candidate dimensions. - - * independent: + independent : A list of candidate dimension/s that require to act as the independent variables in a functional relationship. - - * positions: + positions : A list containing a dictionary of candidate dimension key to scalar value pairs for each source-cube. - - Kwargs: - - * function_mapping: + function_mapping : optional, default=None A dictionary that enumerates a valid functional relationship between the dependent candidate dimension and the independent candidate dimension/s. - Returns: - Boolean. + Returns + ------- + bool """ valid = True @@ -809,16 +790,16 @@ def _derive_consistent_groups(relation_matrix, separable_group): B and C. Then the candidate dimension group ABC is a separable consistent group if B is separable from A and C, and C is separable from A and B. - Args: - - * relation_matrix: + Parameters + ---------- + relation_matrix : The relation dictionary for each candidate dimension. - - * separable_group: + separable_group : The set of candidate dimensions that are separable. - Returns: - A list of candidate dimension groups that are consistently separable. + Returns + ------- + A list of candidate dimension groups that are consistently separable. """ result = [] @@ -861,28 +842,25 @@ def _build_separable_group( and D, and "C: None" means that this candidate dimension is independent. - Args: - - * space: + Parameters + ---------- + space : A dictionary defining for each candidate dimension its dependency on any other candidate dimensions within the space. - - * group: + group : A set of related (chained) inseparable candidate dimensions. - - * separable_consistent_groups: + separable_consistent_groups: A list of candidate dimension groups that are consistently separable. - - * positions: + positions : A list containing a dictionary of candidate dimension key to scalar value pairs for each source-cube. - - * function_matrix: + function_matrix : The function mapping dictionary for each candidate dimension that participates in a functional relationship. - Returns: - Boolean. + Returns + ------- + bool """ valid = False @@ -929,25 +907,23 @@ def _build_inseparable_group(space, group, positions, function_matrix): and all others in the group, as the group is considered inseparable in this context. - Args: - - * space: + Parameters + ---------- + space : A dictionary defining for each candidate dimension its dependency on any other candidate dimensions within the space. - - * group: + group : A set of related (chained) inseparable candidate dimensions. - - * positions: + positions : A list containing a dictionary of candidate dimension key to scalar value pairs for each source-cube. - - * function_matrix: + function_matrix : The function mapping dictionary for each candidate dimension that participates in a functional relationship. - Returns: - Boolean. + Returns + ------- + bool """ scalar = False @@ -989,25 +965,23 @@ def _build_combination_group(space, group, positions, function_matrix): coordinate associated with it. Rather, it is simply an enumeration of the group members for each of the positions (source-cubes). - Args: - - * space: + Parameters + ---------- + space : A dictionary defining for each candidate dimension its dependency on any other candidate dimensions within the space. - - * group: + group : A set of related (chained) inseparable candidate dimensions. - - * positions: + positions : A list containing a dictionary of candidate dimension key to scalar value pairs for each source-cube. - - * function_matrix: + function_matrix : The function mapping dictionary for each candidate dimension that participates in a functional relationship. - Returns: - None. + Returns + ------- + None """ combination = _COMBINATION_JOIN.join(sorted(map(str, group))) @@ -1037,25 +1011,22 @@ def _build_combination_group(space, group, positions, function_matrix): def derive_space(groups, relation_matrix, positions, function_matrix=None): """Determine the relationship between all the candidate dimensions. - Args: - * groups: - A list of all related (chained) inseparable candidate dimensions. - - * relation_matrix: - The relation dictionary for each candidate dimension. - - * positions: - A list containing a dictionary of candidate dimension key to - scalar value pairs for each source-cube. - - Kwargs: - * function_matrix: + Parameters + ---------- + groups : + A list of all related (chained) inseparable candidate dimensions. + relation_matrix: + The relation dictionary for each candidate dimension. + positions : + A list containing a dictionary of candidate dimension key to + scalar value pairs for each source-cube. + function_matrix : optional, default=None The function mapping dictionary for each candidate dimension that participates in a functional relationship. - Returns: - A space dictionary describing the relationship between each - candidate dimension. + Returns + ------- + A space dictionary describing the relationship between each candidate dimension. """ space = {} @@ -1184,14 +1155,15 @@ def merge(self, unique=True): """Returns the list of cubes resulting from merging the registered source-cubes. - Kwargs: - - * unique: + Parameters + ---------- + unique : If True, raises `iris.exceptions.DuplicateDataError` if duplicate cubes are detected. - Returns: - A :class:`iris.cube.CubeList` of merged cubes. + Returns + ------- + A :class:`iris.cube.CubeList` of merged cubes. """ positions = [ @@ -1286,20 +1258,19 @@ def register(self, cube, error_on_mismatch=False): cube and the signature of its scalar coordinates and vector coordinates being identical to that of the ProtoCube. - Args: - - * cube: + Parameters + ---------- + cube : Candidate :class:`iris.cube.Cube` to be associated with this :class:`ProtoCube`. - - Kwargs: - - * error_on_mismatch: + error_on_mismatch :bool, optional, default=False If True, raise an informative :class:`~iris.exceptions.MergeError` if registration fails. - Returns: - True iff the :class:`iris.cube.Cube` is compatible with + Returns + ------- + bool + True if the :class:`iris.cube.Cube` is compatible with this :class:`ProtoCube`. """ @@ -1326,13 +1297,14 @@ def _guess_axis(self, name): Based on the associated scalar coordinate definition rather than the scalar coordinate itself. - Args: - - * name: + Parameters + ---------- + name : The candidate dimension. - Returns: - 'T', 'Z', 'Y', 'X', or None. + Returns + ------- + axis : {'T', 'Z', 'Y', 'X'} or None. """ axis = None @@ -1348,20 +1320,17 @@ def _define_space(self, space, positions, indexes, function_matrix): terms of its dimensionality, shape, coordinates and associated coordinate to space dimension mappings. - Args: - - * space: + Parameters + ---------- + space : A dictionary defining for each candidate dimension its dependency on any other candidate dimensions within the space. - - * positions: + positions : A list containing a dictionary of candidate dimension key to scalar value pairs for each source-cube. - - * indexes: + indexes : A cross-reference dictionary for each candidate dimension. - - * function_matrix: + function_matrix : The function mapping dictionary for each candidate dimension that participates in a functional relationship. @@ -1655,13 +1624,14 @@ def _build_coordinates(self): def _build_signature(self, cube): """Generate the signature that defines this cube. - Args: - - * cube: + Parameters + ---------- + cube : The source cube to create the cube signature from. - Returns: - The cube signature. + Returns + ------- + The cube signature. """ diff --git a/lib/iris/_representation/cube_printout.py b/lib/iris/_representation/cube_printout.py index 81f60e595d..b1e5238eb0 100644 --- a/lib/iris/_representation/cube_printout.py +++ b/lib/iris/_representation/cube_printout.py @@ -52,12 +52,13 @@ def __init__(self, cols, aligns, i_col_unlimited=None): def add_row(self, cols, aligns, i_col_unlimited=None): """Create a new row at the bottom. - Args: - * cols (list of string): + Parameters + ---------- + cols : list of str Per-column content. Length must match the other rows (if any). - * aligns (list of {'left', 'right'}): + aligns : list of {'left', 'right'} Per-column alignments. Length must match 'cols'. - * i_col_unlimited (int or None): + i_col_unlimited : int or None, optional Column beyond which content does not affect the column widths. ( meaning contents will print without limit ). @@ -133,12 +134,13 @@ class CubePrinter: def __init__(self, cube_or_summary): """An object that provides a printout of a cube. - Args: - - * cube_or_summary (Cube or CubeSummary): + Parameters + ---------- + cube_or_summary : Cube or CubeSummary If a cube, first create a CubeSummary from it. - + Notes + ----- .. note:: The CubePrinter is based on a digest of a CubeSummary, but does not reference or store it. @@ -320,15 +322,17 @@ def _multiline_summary(self, name_padding): def to_string(self, oneline=False, name_padding=35): """Produce a printable summary. - Args: - * oneline (bool): + Parameters + ---------- + oneline : bool, optional, default=False If set, produce a one-line summary. Default is False = produce full (multiline) summary. - * name_padding (int): + name_padding int, optional, default=35 The minimum width for the "name" (#0) column. - Returns: - result (string) + Returns + ------- + str """ if oneline: diff --git a/lib/iris/analysis/_area_weighted.py b/lib/iris/analysis/_area_weighted.py index f882860d25..007050008b 100644 --- a/lib/iris/analysis/_area_weighted.py +++ b/lib/iris/analysis/_area_weighted.py @@ -24,16 +24,13 @@ def __init__(self, src_grid_cube, target_grid_cube, mdtol=1): """Create an area-weighted regridder for conversions between the source and target grids. - Args: - - * src_grid_cube: + Parameters + ---------- + src_grid_cube : :class:`~iris.cube.Cube` The :class:`~iris.cube.Cube` providing the source grid. - * target_grid_cube: + target_grid_cube : :class:`~iris.cube.Cube` The :class:`~iris.cube.Cube` providing the target grid. - - Kwargs: - - * mdtol (float): + mdtol : float, optional Tolerance of missing data. The value returned in each element of the returned array will be masked if the fraction of masked data exceeds mdtol. mdtol=0 means no missing data is tolerated while @@ -41,6 +38,8 @@ def __init__(self, src_grid_cube, target_grid_cube, mdtol=1): if all the contributing elements of data are masked. Defaults to 1. + Notes + ----- .. Note:: Both source and target cubes must have an XY grid defined by @@ -85,17 +84,21 @@ def __call__(self, cube): If the source cube has lazy data, the returned cube will also have lazy data. - Args: - - * cube: + Parameters + ---------- + cube : :class:`~iris.cube.Cube` A :class:`~iris.cube.Cube` to be regridded. - Returns: + Returns + ------- + :class:`~iris.cube.Cube` A cube defined with the horizontal dimensions of the target and the other dimensions from this cube. The data values of this cube will be converted to values on the new grid using area-weighted regridding. + Notes + ----- .. note:: If the source cube has lazy data, @@ -146,12 +149,14 @@ def _get_xy_coords(cube): have equal coordinate systems and that they do not occupy the same dimension on the cube. - Args: - - * cube: + Parameters + ---------- + cube : :class:`iris.cube.Cube` An instance of :class:`iris.cube.Cube`. - Returns: + Returns + ------- + tuple A tuple containing the cube's x and y coordinates. """ diff --git a/lib/iris/analysis/_interpolation.py b/lib/iris/analysis/_interpolation.py index b6e443c95c..15f5ba7893 100644 --- a/lib/iris/analysis/_interpolation.py +++ b/lib/iris/analysis/_interpolation.py @@ -94,12 +94,14 @@ def get_xy_dim_coords(cube): if the identified x and y coordinates do not have coordinate systems that are equal. - Args: - - * cube: + Parameters + ---------- + cube : :class:`iris.cube.Cube` An instance of :class:`iris.cube.Cube`. - Returns: + Returns + ------- + tuple A tuple containing the cube's x and y dimension coordinates. """ @@ -114,18 +116,17 @@ def get_xy_coords(cube, dim_coords=False): if the identified x and y coordinates do not have coordinate systems that are equal. - Args: - - * cube: + Parameters + ---------- + cube : :class:`iris.cube.Cube` An instance of :class:`iris.cube.Cube`. - - Kwargs: - - * dim_coords: + dim_coords : bool, optional, default=False Set this to True to only return dimension coordinates. Defaults to False. - Returns: + Returns + ------- + tuple A tuple containing the cube's x and y dimension coordinates. """ @@ -171,30 +172,30 @@ class RectilinearInterpolator: def __init__(self, src_cube, coords, method, extrapolation_mode): """Perform interpolation over one or more orthogonal coordinates. - Args: - - * src_cube: + Parameters + ---------- + src_cube : :class:`iris.cube.Cube` The :class:`iris.cube.Cube` which is to be interpolated. - * coords: + coords : The names or coordinate instances which are to be interpolated over - * method: + method : Either 'linear' or 'nearest'. - * extrapolation_mode: + extrapolation_mode : str Must be one of the following strings: - * 'extrapolate' - The extrapolation points will be calculated - according to the method. The 'linear' method extends the - gradient of the closest two points. The 'nearest' method - uses the value of the closest point. - * 'nan' - The extrapolation points will be be set to NaN. - * 'error' - A ValueError exception will be raised, notifying an - attempt to extrapolate. - * 'mask' - The extrapolation points will always be masked, even - if the source data is not a MaskedArray. - * 'nanmask' - If the source data is a MaskedArray the - extrapolation points will be masked. Otherwise they will be - set to NaN. + * 'extrapolate' - The extrapolation points will be calculated + according to the method. The 'linear' method extends the + gradient of the closest two points. The 'nearest' method + uses the value of the closest point. + * 'nan' - The extrapolation points will be be set to NaN. + * 'error' - A ValueError exception will be raised, notifying an + attempt to extrapolate. + * 'mask' - The extrapolation points will always be masked, even + if the source data is not a MaskedArray. + * 'nanmask' - If the source data is a MaskedArray the + extrapolation points will be masked. Otherwise they will be + set to NaN. """ # Trigger any deferred loading of the source cube's data and snapshot @@ -284,10 +285,11 @@ def _interpolate(self, data, interp_points): it to perform interpolation over the data at the given coordinate point values. - * data (ndarray): + Parameters + ---------- + data : ndarray A data array, to be interpolated in its first 'N' dimensions. - - * interp_points (ndarray): + interp_points : ndarray An array of interpolation coordinate values. Its shape is (..., N) where N is the number of interpolation dimensions. @@ -468,26 +470,25 @@ def _points(self, sample_points, data, data_dims=None): """Interpolate the given data values at the specified list of orthogonal (coord, points) pairs. - Args: - - * sample_points: + Parameters + ---------- + sample_points : A list of N iterables, where N is the number of coordinates passed to the constructor. [sample_values_for_coord_0, sample_values_for_coord_1, ...] - * data: + data : The data to interpolate - not necessarily the data from the cube that was used to construct this interpolator. If the data has fewer dimensions, then data_dims must be defined. - - Kwargs: - - * data_dims: + data_dims : optional, default=None The dimensions of the given data array in terms of the original cube passed through to this interpolator's constructor. If None, the data dimensions must map one-to-one onto the increasing dimension order of the cube. - Returns: + Returns + ------- + :class:`~numpy.ndarray` or :class:`~numpy.ma.MaskedArray` An :class:`~numpy.ndarray` or :class:`~numpy.ma.MaskedArray` instance of the interpolated data. @@ -565,20 +566,19 @@ def _points(self, sample_points, data, data_dims=None): def __call__(self, sample_points, collapse_scalar=True): """Construct a cube from the specified orthogonal interpolation points. - Args: - - * sample_points: + Parameters + ---------- + sample_points : A list of N iterables, where N is the number of coordinates passed to the constructor. [sample_values_for_coord_0, sample_values_for_coord_1, ...] - - Kwargs: - - * collapse_scalar: + collapse_scalar : bool, optional Whether to collapse the dimension of the scalar sample points in the resulting cube. Default is True. - Returns: + Returns + ------- + :class:`iris.cube.Cube` A cube interpolated at the given sample points. The dimensionality of the cube will be the number of original cube dimensions minus the number of scalar coordinates, if collapse_scalar is True. diff --git a/lib/iris/analysis/_regrid.py b/lib/iris/analysis/_regrid.py index b2ce99ee7a..5f339ea4ca 100644 --- a/lib/iris/analysis/_regrid.py +++ b/lib/iris/analysis/_regrid.py @@ -28,15 +28,16 @@ def _transform_xy_arrays(crs_from, x, y, crs_to): NOTE: copied private function from iris.analysis.cartography. - Args: - - * crs_from, crs_to (:class:`cartopy.crs.Projection`): + Parameters + ---------- + crs_from, crs_to : :class:`cartopy.crs.Projection` The coordinate reference systems. - * x, y (arrays): + x, y : arrays point locations defined in 'crs_from'. - Returns: - x, y : Arrays of locations defined in 'crs_to'. + Returns + ------- + x, y : Arrays of locations defined in 'crs_to'. """ pts = crs_to.transform_points(crs_from, x, y) @@ -377,16 +378,13 @@ def __init__(self, src_grid_cube, target_grid_cube, weights=None): """Create a regridder for conversions between the source and target grids. - Args: - - * src_grid_cube: + Parameters + ---------- + src_grid_cube : :class:`~iris.cube.Cube` The :class:`~iris.cube.Cube` providing the source grid. - * tgt_grid_cube: + tgt_grid_cube : :class:`~iris.cube.Cube` The :class:`~iris.cube.Cube` providing the target grid. - - Optional Args: - - * weights: + weights : optional, default=None A :class:`numpy.ndarray` instance that defines the weights for the grid cells of the source grid. Must have the same shape as the data of the source grid. @@ -412,16 +410,16 @@ def _get_horizontal_coord(cube, axis): """Gets the horizontal coordinate on the supplied cube along the specified axis. - Args: - - * cube: + Parameters + ---------- + cube : :class:`iris.cube.Cube` An instance of :class:`iris.cube.Cube`. - * axis: + axis : Locate coordinates on `cube` along this axis. - Returns: - The horizontal coordinate on the specified axis of the supplied - cube. + Returns + ------- + The horizontal coordinate on the specified axis of the supplied cube. """ coords = cube.coords(axis=axis, dim_coords=False) @@ -443,12 +441,14 @@ def __call__(self, src): If the source cube has lazy data, it will be realized before regridding and the returned cube will also have realized data. - Args: - - * src: + Parameters + ---------- + src : :class:`~iris.cube.Cube` A :class:`~iris.cube.Cube` to be regridded. - Returns: + Returns + ------- + :class:`~iris.cube.Cube` A cube defined with the horizontal dimensions of the target and the other dimensions from this cube. The data values of this cube will be converted to values on the new grid using @@ -494,28 +494,28 @@ def __init__(self, src_grid_cube, tgt_grid_cube, method, extrapolation_mode): """Create a regridder for conversions between the source and target grids. - Args: - - * src_grid_cube: + Parameters + ---------- + src_grid_cube : :class:`~iris.cube.Cube` The :class:`~iris.cube.Cube` providing the source grid. - * tgt_grid_cube: + tgt_grid_cube : :class:`~iris.cube.Cube` The :class:`~iris.cube.Cube` providing the target grid. - * method: + method : Either 'linear' or 'nearest'. - * extrapolation_mode: + extrapolation_mode : str Must be one of the following strings: - * 'extrapolate' - The extrapolation points will be - calculated by extending the gradient of the closest two - points. - * 'nan' - The extrapolation points will be be set to NaN. - * 'error' - An exception will be raised, notifying an - attempt to extrapolate. - * 'mask' - The extrapolation points will always be masked, even - if the source data is not a MaskedArray. - * 'nanmask' - If the source data is a MaskedArray the - extrapolation points will be masked. Otherwise they will be - set to NaN. + * 'extrapolate' - The extrapolation points will be + calculated by extending the gradient of the closest two + points. + * 'nan' - The extrapolation points will be be set to NaN. + * 'error' - An exception will be raised, notifying an + attempt to extrapolate. + * 'mask' - The extrapolation points will always be masked, even + if the source data is not a MaskedArray. + * 'nanmask' - If the source data is a MaskedArray the + extrapolation points will be masked. Otherwise they will be + set to NaN. """ from iris.cube import Cube @@ -559,17 +559,19 @@ def _sample_grid(src_coord_system, grid_x_coord, grid_y_coord): The `grid_x_coord` and `grid_y_coord` must share a common coordinate system. - Args: - - * src_coord_system: + Parameters + ---------- + src_coord_system : :class:`iris.coord_system.CoordSystem` The :class:`iris.coord_system.CoordSystem` for the grid of the source Cube. - * grid_x_coord: + grid_x_coord : :class:`iris.coords.DimCoord` The :class:`iris.coords.DimCoord` for the X coordinate. - * grid_y_coord: + grid_y_coord : :class:`iris.coords.DimCoord` The :class:`iris.coords.DimCoord` for the Y coordinate. - Returns: + Returns + ------- + tuple A tuple of the X and Y coordinate values as 2-dimensional arrays. @@ -602,54 +604,55 @@ def _regrid( """Regrid the given data from the src grid to the sample grid. The result will be a MaskedArray if either/both of: - - the source array is a MaskedArray, - - the extrapolation_mode is 'mask' and the result requires - extrapolation. + + * the source array is a MaskedArray, + * the extrapolation_mode is 'mask' and the result requires + extrapolation. If the result is a MaskedArray the mask for each element will be set if either/both of: - - there is a non-zero contribution from masked items in the input data - - the element requires extrapolation and the extrapolation_mode - dictates a masked value. - - Args: - - * src_data: + + * there is a non-zero contribution from masked items in the input data + * the element requires extrapolation and the extrapolation_mode + dictates a masked value. + + Parameters + ---------- + src_data : An N-dimensional NumPy array or MaskedArray. - * x_dim: + x_dim : The X dimension within `src_data`. - * y_dim: + y_dim : The Y dimension within `src_data`. - * src_x_coord: + src_x_coord : :class:`iris.coords.DimCoord` The X :class:`iris.coords.DimCoord`. - * src_y_coord: + src_y_coord : :class:`iris.coords.DimCoord` The Y :class:`iris.coords.DimCoord`. - * sample_grid_x: + sample_grid_x : A 2-dimensional array of sample X values. - * sample_grid_y: + sample_grid_y : A 2-dimensional array of sample Y values. - - Kwargs: - - * method: + method: str, optional Either 'linear' or 'nearest'. The default method is 'linear'. - * extrapolation_mode: + extrapolation_mode : str, optional Must be one of the following strings: - * 'linear' - The extrapolation points will be calculated by - extending the gradient of the closest two points. - * 'nan' - The extrapolation points will be be set to NaN. - * 'error' - A ValueError exception will be raised, notifying an - attempt to extrapolate. - * 'mask' - The extrapolation points will always be masked, even - if the source data is not a MaskedArray. - * 'nanmask' - If the source data is a MaskedArray the - extrapolation points will be masked. Otherwise they will be - set to NaN. + * 'linear' - The extrapolation points will be calculated by + extending the gradient of the closest two points. + * 'nan' - The extrapolation points will be be set to NaN. + * 'error' - A ValueError exception will be raised, notifying an + attempt to extrapolate. + * 'mask' - The extrapolation points will always be masked, even + if the source data is not a MaskedArray. + * 'nanmask' - If the source data is a MaskedArray the + extrapolation points will be masked. Otherwise they will be + set to NaN. The default mode of extrapolation is 'nanmask'. - Returns: + Returns + ------- + NumPu array The regridded data as an N-dimensional NumPy array. The lengths of the X and Y dimensions will now match those of the sample grid. @@ -854,17 +857,21 @@ def __call__(self, src): If the source cube has lazy data, the returned cube will also have lazy data. - Args: - - * src: + Parameters + ---------- + src : :class:`~iris.cube.Cube` A :class:`~iris.cube.Cube` to be regridded. - Returns: + Returns + ------- + :class:`~iris.cube.Cube` A cube defined with the horizontal dimensions of the target and the other dimensions from this cube. The data values of this cube will be converted to values on the new grid using either nearest-neighbour or linear interpolation. + Notes + ----- .. note:: If the source cube has lazy data, @@ -962,13 +969,15 @@ def regrid_callback(*args, **kwargs): def _create_cube(data, src, src_dims, tgt_coords, num_tgt_dims, regrid_callback): r"""Return a new cube for the result of regridding. + Returned cube represents the result of regridding the source cube onto the horizontal coordinates (e.g. latitude) of the target cube. All the metadata and coordinates of the result cube are copied from the source cube, with two exceptions: - - Horizontal coordinates are copied from the target cube. - - Auxiliary coordinates which span the grid dimensions are - ignored. + + * Horizontal coordinates are copied from the target cube. + * Auxiliary coordinates which span the grid dimensions are + ignored. Parameters ---------- diff --git a/lib/iris/analysis/cartography.py b/lib/iris/analysis/cartography.py index c0613028e3..219e9c7557 100644 --- a/lib/iris/analysis/cartography.py +++ b/lib/iris/analysis/cartography.py @@ -55,12 +55,21 @@ def wrap_lons(lons, base, period): """Wrap longitude values into the range between base and base+period. + Parameters + ---------- + lons : + base : + period : + + Examples + -------- .. testsetup:: import numpy as np from iris.analysis.cartography import wrap_lons - For example: + :: + >>> print(wrap_lons(np.array([185, 30, -200, 75]), -180, 360)) [-175. 30. 160. 75.] @@ -85,29 +94,31 @@ def unrotate_pole(rotated_lons, rotated_lats, pole_lon, pole_lat): rectilinear grid, the arrays of rotated-pole longitudes and latitudes must be of the same shape as each other. - Example:: - - lons, lats = unrotate_pole(rotated_lons, rotated_lats, \ - pole_lon, pole_lat) - .. note:: Uses proj.4 to perform the conversion. - Args: + Parameters + ---------- + rotated_lons : + An array of rotated-pole longitude values. + rotated_lats : + An array of rotated-pole latitude values. + pole_lon : + The longitude of the rotated pole that describes the arrays of + rotated-pole longitudes and latitudes. + pole_lat : + The latitude of the rotated pole that describes the arrays of + rotated-pole longitudes and latitudes. + + Returns + ------- + An array of unrotated longitudes and an array of unrotated latitudes. - * rotated_lons: - An array of rotated-pole longitude values. - * rotated_lats: - An array of rotated-pole latitude values. - * pole_lon: - The longitude of the rotated pole that describes the arrays of - rotated-pole longitudes and latitudes. - * pole_lat: - The latitude of the rotated pole that describes the arrays of - rotated-pole longitudes and latitudes. - - Returns: - An array of unrotated longitudes and an array of unrotated latitudes. + Examples + -------- + :: + lons, lats = unrotate_pole(rotated_lons, rotated_lats, pole_lon, pole_lat) + """ src_proj = ccrs.RotatedGeodetic(pole_longitude=pole_lon, pole_latitude=pole_lat) target_proj = ccrs.Geodetic() @@ -128,29 +139,30 @@ def rotate_pole(lons, lats, pole_lon, pole_lat): the arrays of rotated-pole longitudes and latitudes must be of the same shape as each other. - Example:: - - rotated_lons, rotated_lats = rotate_pole(lons, lats,\ - pole_lon, pole_lat) - .. note:: Uses proj.4 to perform the conversion. - Args: + Parameters + ---------- + lons : + An array of longitude values. + lats : + An array of latitude values. + pole_lon : + The longitude of the rotated pole that the arrays of longitudes and + latitudes are to be rotated onto. + pole_lat : + The latitude of the rotated pole that the arrays of longitudes and + latitudes are to be rotated onto. + + Returns + ------- + An array of rotated-pole longitudes and an array of rotated-pole latitudes. - * lons: - An array of longitude values. - * lats: - An array of latitude values. - * pole_lon: - The longitude of the rotated pole that the arrays of longitudes and - latitudes are to be rotated onto. - * pole_lat: - The latitude of the rotated pole that the arrays of longitudes and - latitudes are to be rotated onto. + Examples + -------- + :: - Returns: - An array of rotated-pole longitudes and an array of rotated-pole - latitudes. + rotated_lons, rotated_lats = rotate_pole(lons, lats, pole_lon, pole_lat) """ src_proj = ccrs.Geodetic() @@ -185,15 +197,14 @@ def search_for_coord(coord_iterable, coord_name): def _xy_range(cube, mode=None): """Return the x & y range of this Cube. - Args: - - * cube - The cube for which to calculate xy extents. - - Kwargs: - - * mode - If the coordinate has bounds, set this to specify the - min/max calculation. - Set to iris.coords.POINT_MODE or iris.coords.BOUND_MODE. + Parameters + ---------- + cube : + The cube for which to calculate xy extents. + mode : optional, default=None + If the coordinate has bounds, set this to specify the + min/max calculation. + Set to iris.coords.POINT_MODE or iris.coords.BOUND_MODE. """ # Helpful error if we have an inappropriate CoordSystem @@ -249,11 +260,14 @@ def _xy_range(cube, mode=None): def get_xy_grids(cube): """Return 2D X and Y points for a given cube. - Args: - - * cube - The cube for which to generate 2D X and Y points. + Parameters + ---------- + cube : + The cube for which to generate 2D X and Y points. - Example:: + Examples + -------- + :: x, y = get_xy_grids(cube) @@ -261,6 +275,7 @@ def get_xy_grids(cube): ----- This function maintains laziness when called; it does not realise data. See more at :doc:`/userguide/real_and_lazy_data`. + """ x_coord, y_coord = cube.coord(axis="X"), cube.coord(axis="Y") @@ -284,7 +299,13 @@ def get_xy_contiguous_bounded_grids(cube): Returns array of shape (n+1, m+1). - Example:: + Parameters + ---------- + cube : :class:`iris.cube.Cube` + + Examples + -------- + :: xs, ys = get_xy_contiguous_bounded_grids(cube) @@ -306,16 +327,11 @@ def get_xy_contiguous_bounded_grids(cube): def _quadrant_area(radian_lat_bounds, radian_lon_bounds, radius_of_earth): """Calculate spherical segment areas. - - radian_lat_bounds -- [n,2] array of latitude bounds (radians) - - radian_lon_bounds -- [n,2] array of longitude bounds (radians) - - radius_of_earth -- radius of the earth - (currently assumed spherical) - Area weights are calculated for each lat/lon cell as: - .. math:: + .. math:: - r^2 (lon_1 - lon_0) ( sin(lat_1) - sin(lat_0)) + r^2 (lon_1 - lon_0) ( sin(lat_1) - sin(lat_0)) The resulting array will have a shape of *(radian_lat_bounds.shape[0], radian_lon_bounds.shape[0])* @@ -323,6 +339,15 @@ def _quadrant_area(radian_lat_bounds, radian_lon_bounds, radius_of_earth): The calculations are done at 64 bit precision and the returned array will be of type numpy.float64. + Parameters + ---------- + radian_lat_bounds : + [n,2] array of latitude bounds (radians) + radian_lon_bounds : + [n,2] array of longitude bounds (radians) + radius_of_earth : + radius of the earth (currently assumed spherical) + """ # ensure pairs of bounds if ( @@ -352,28 +377,29 @@ def area_weights(cube, normalize=False): This is a 2D lat/lon area weights array, repeated over the non lat/lon dimensions. - Args: - - * cube (:class:`iris.cube.Cube`): - The cube to calculate area weights for. - - Kwargs: - - * normalize (False/True): - If False, weights are grid cell areas. If True, weights are grid - cell areas divided by the total grid area. - The cube must have coordinates 'latitude' and 'longitude' with bounds. Area weights are calculated for each lat/lon cell as: - .. math:: + .. math:: - r^2 (lon_1 - lon_0) (\sin(lat_1) - \sin(lat_0)) + r^2 (lon_1 - lon_0) (\sin(lat_1) - \sin(lat_0)) Currently, only supports a spherical datum. Uses earth radius from the cube, if present and spherical. - Defaults to iris.analysis.cartography.DEFAULT_SPHERICAL_EARTH_RADIUS. + Defaults to iris.analysis.cartography.DEFAULT_SPHERICAL_EARTH_RADIUS. + + Parameters + ---------- + cube : :class:`iris.cube.Cube` + The cube to calculate area weights for. + normalize : bool, optional, default=False + If False, weights are grid cell areas. If True, weights are grid + cell areas divided by the total grid area. + + Returns + ------- + broad_weights : """ # Get the radius of the earth @@ -478,10 +504,14 @@ def cosine_latitude_weights(cube): Weights are calculated for each latitude as: - .. math:: + .. math:: - w_l = \cos \phi_l + w_l = \cos \phi_l + Parameters + ---------- + cube : :class:`iris.cube.Cube` + Examples -------- Compute weights suitable for averaging type operations:: @@ -561,25 +591,29 @@ def project(cube, target_proj, nx=None, ny=None): prevent one from directly visualising the data, e.g. when the longitude and latitude are two dimensional and do not make up a regular grid. - Args: - * cube - An instance of :class:`iris.cube.Cube`. - * target_proj - An instance of the Cartopy Projection class, or an instance of - :class:`iris.coord_systems.CoordSystem` from which a projection - will be obtained. - Kwargs: - * nx - Desired number of sample points in the x direction for a domain - covering the globe. - * ny - Desired number of sample points in the y direction for a domain - covering the globe. - - Returns: + Parameters + ---------- + cube : :class:`iris.cube.Cube` + An instance of :class:`iris.cube.Cube`. + target_proj : :class:`iris.coord_systems.CoordSystem` + An instance of the Cartopy Projection class, or an instance of + :class:`iris.coord_systems.CoordSystem` from which a projection + will be obtained. + nx : optional, default=None + Desired number of sample points in the x direction for a domain + covering the globe. + ny : optional, default=None + Desired number of sample points in the y direction for a domain + covering the globe. + + Returns + ------- + :class:`iris.cube.Cube` An instance of :class:`iris.cube.Cube` and a list describing the extent of the projection. + Notes + ----- .. note:: If there are both dim and aux latitude-longitude coordinates, only @@ -852,15 +886,17 @@ def _transform_xy(crs_from, x, y, crs_to): """Shorthand function to transform 2d points between coordinate reference systems. - Args: - - * crs_from, crs_to (:class:`cartopy.crs.Projection`): + Parameters + ---------- + crs_from, crs_to : :class:`cartopy.crs.Projection` The coordinate reference systems. - * x, y (arrays): + x, y : array point locations defined in 'crs_from'. - Returns: - x, y : Arrays of locations defined in 'crs_to'. + Returns + ------- + x, y + Arrays of locations defined in 'crs_to'. """ pts = crs_to.transform_points(crs_from, x, y) @@ -872,14 +908,16 @@ def _inter_crs_differentials(crs1, x, y, crs2): Returns dx2/dx1, dy2/dx1, dx2/dy1 and dy2/dy1, at given locations. - Args: - - * crs1, crs2 (`cartopy.crs.Projection`): + Parameters + ---------- + crs1, crs2 : `cartopy.crs.Projection` The coordinate systems, "from" and "to". - * x, y (array): + x, y : array Point locations defined in 'crs1'. - Returns: + Returns + ------- + arrays (dx2/dx1, dy2/dx1, dx2/dy1, dy2/dy1) at given locations. Each element of this tuple will be the same shape as the 'x' and 'y' arrays and will be the partial differentials between the two systems. @@ -918,19 +956,22 @@ def _inter_crs_differentials(crs1, x, y, crs2): def _crs_distance_differentials(crs, x, y): - """Calculate d(distance) / d(x) and ... / d(y) for a coordinate - reference system at specified locations. + """Calculate d(distance) / d(x) and ... / d(y). - Args: + Calculate d(distance) / d(x) and ... / d(y) for a coordinate + reference system at specified locations. - * crs (:class:`cartopy.crs.Projection`): + Parameters + ---------- + crs : :class:`cartopy.crs.Projection` The coordinate reference system. - * x, y (array): + x, y : array Locations at which to calculate the differentials, defined in 'crs' coordinate reference system. - Returns: - (abs(ds/dx), abs(ds/dy)). + Returns + ------- + (abs(ds/dx), abs(ds/dy)) Numerically approximated partial differentials, i.e. scaling factors between changes in distance and changes in coordinate values. @@ -953,18 +994,20 @@ def _transform_distance_vectors(u_dist, v_dist, ds, dx2, dy2): """Transform distance vectors from one coordinate reference system to another, preserving magnitude and physical direction. - Args: - - * u_dist, v_dist (array): + Parameters + ---------- + u_dist, v_dist : array Components of each vector along the x and y directions of the source crs at each location. - * ds (`DistanceDifferential`): + ds : `DistanceDifferential` Distance differentials for the source and the target crs at specified locations. - * dx2, dy2 (`PartialDifferential`): + dx2, dy2 : `PartialDifferential` Partial differentials from the source to the target crs. - Returns: + Returns + ------- + tuple (ut_dist, vt_dist): Tuple of arrays containing the vector components along the x and y directions of the target crs at each location. @@ -986,20 +1029,22 @@ def _transform_distance_vectors_tolerance_mask(src_crs, x, y, tgt_crs, ds, dx2, where the magnitude of vectors are not preserved due to numerical errors introduced by the transformation between coordinate systems. - Args: - * src_crs (`cartopy.crs.Projection`): + Parameters + ---------- + src_crs : `cartopy.crs.Projection` The source coordinate reference systems. - * x, y (array): + x, y : array Locations of each vector defined in 'src_crs'. - * tgt_crs (`cartopy.crs.Projection`): + tgt_crs : `cartopy.crs.Projection` The target coordinate reference systems. - * ds (`DistanceDifferential`): + ds : `DistanceDifferential` Distance differentials for src_crs and tgt_crs at specified locations - * dx2, dy2 (`PartialDifferential`): + dx2, dy2 : `PartialDifferential` Partial differentials from src_crs to tgt_crs. - Returns: - 2d boolean array that is the same shape as x and y. + Returns + ------- + 2d boolean array that is the same shape as x and y. """ if x.shape != y.shape: @@ -1040,23 +1085,27 @@ def rotate_winds(u_cube, v_cube, target_cs): also have two 2-dimensional auxiliary coordinates containing the X and Y locations in the target coordinate system. - Args: - - * u_cube + Parameters + ---------- + u_cube : An instance of :class:`iris.cube.Cube` that contains the x-component of the vector. - * v_cube + v_cube : An instance of :class:`iris.cube.Cube` that contains the y-component of the vector. - * target_cs + target_cs : An instance of :class:`iris.coord_systems.CoordSystem` that specifies the new grid directions. - Returns: + Returns + ------- + (u', v') tuple of :class:`iris.cube.Cube` A (u', v') tuple of :class:`iris.cube.Cube` instances that are the u and v components in the requested target coordinate system. The units are the same as the inputs. + Notes + ----- .. note:: The U and V values relate to distance, with units such as 'm s-1'. diff --git a/lib/iris/analysis/maths.py b/lib/iris/analysis/maths.py index 3d1df8d66f..c35b0e6d70 100644 --- a/lib/iris/analysis/maths.py +++ b/lib/iris/analysis/maths.py @@ -35,23 +35,20 @@ def _output_dtype(op, first_dtype, second_dtype=None, in_place=False): """Get the numpy dtype corresponding to the result of applying a unary or binary operation to arguments of specified dtype. - Args: - - * op: + Parameters + ---------- + op : A unary or binary operator which can be applied to array-like objects. - * first_dtype: + first_dtype : The dtype of the first or only argument to the operator. - - Kwargs: - - * second_dtype: + second_dtype : optional, default=None The dtype of the second argument to the operator. - - * in_place: + in_place : optional, default=None Whether the operation is to be performed in place. - Returns: - An instance of :class:`numpy.dtype` + Returns + ------- + :class:`numpy.dtype` .. note:: @@ -74,17 +71,17 @@ def _output_dtype(op, first_dtype, second_dtype=None, in_place=False): def _get_dtype(operand): - """Get the numpy dtype corresponding to the numeric data in the object - provided. + """Get the numpy dtype corresponding to the numeric data in the object provided. - Args: - - * operand: + Parameters + ---------- + operand : An instance of :class:`iris.cube.Cube` or :class:`iris.coords.Coord`, or a number or :class:`numpy.ndarray`. - Returns: - An instance of :class:`numpy.dtype` + Returns + ------- + :class:`numpy.dtype` """ return np.min_scalar_type(operand) if np.isscalar(operand) else operand.dtype @@ -93,18 +90,16 @@ def _get_dtype(operand): def abs(cube, in_place=False): """Calculate the absolute values of the data in the Cube provided. - Args: - - * cube: + Parameters + ---------- + cube : An instance of :class:`iris.cube.Cube`. - - Kwargs: - - * in_place: + in_place : bool, default=False Whether to create a new Cube, or alter the given "cube". - Returns: - An instance of :class:`iris.cube.Cube`. + Returns + ------- + :class:`iris.cube.Cube`. Notes ----- @@ -124,17 +119,21 @@ def intersection_of_cubes(cube, other_cube): .. note:: The intersection of cubes function will ignore all single valued coordinates in checking the intersection. - Args: - - * cube: + Parameters + ---------- + cube : An instance of :class:`iris.cube.Cube`. - * other_cube: + other_cube : An instance of :class:`iris.cube.Cube`. - Returns: + Returns + ------- + A paired tuple of :class:`iris.cube.Cube` A pair of :class:`iris.cube.Cube` instances in a tuple corresponding to the original cubes restricted to their intersection. + Notes + ----- .. deprecated:: 3.2.0 Instead use :meth:`iris.cube.CubeList.extract_overlapping`. For example, @@ -323,19 +322,25 @@ def _add_subtract_common( """Function which shares common code between addition and subtraction of cubes. - operation_function - function which does the operation - (e.g. numpy.subtract) - operation_name - the public name of the operation (e.g. 'divide') - cube - the cube whose data is used as the first argument - to `operation_function` - other - the cube, coord, ndarray, dask array or number whose - data is used as the second argument - new_dtype - the expected dtype of the output. Used in the - case of scalar masked arrays - dim - dimension along which to apply `other` if it's a - coordinate that is not found in `cube` - in_place - whether or not to apply the operation in place to - `cube` and `cube.data` + Parameters + ---------- + operation_function : + function which does the operation (e.g. numpy.subtract) + operation_name : + The public name of the operation (e.g. 'divide') + cube : + The cube whose data is used as the first argument to `operation_function` + other : + The cube, coord, ndarray, dask array or number whose + data is used as the second argument + new_dtype : + The expected dtype of the output. Used in the case of scalar + masked arrays + dim : optional, default=None + Dimension along which to apply `other` if it's a coordinate that is not + found in `cube` + in_place : bool, default=False + Whether or not to apply the operation in place to `cube` and `cube.data` """ _assert_is_cube(cube) @@ -520,11 +525,11 @@ def divide(cube, other, dim=None, in_place=False): def exponentiate(cube, exponent, in_place=False): """Returns the result of the given cube to the power of a scalar. - Args: - - * cube: + Parameters + ---------- + cube : An instance of :class:`iris.cube.Cube`. - * exponent: + exponent : The integer or floating point exponent. .. note:: When applied to the cube's unit, the exponent must @@ -532,14 +537,12 @@ def exponentiate(cube, exponent, in_place=False): powers of the basic units. e.g. Unit('meter^-2 kilogram second^-1') - - Kwargs: - - * in_place: + in_place : bool, optional=False Whether to create a new Cube, or alter the given "cube". - Returns: - An instance of :class:`iris.cube.Cube`. + Returns + ------- + :class:`iris.cube.Cube`. Notes ----- @@ -575,25 +578,21 @@ def power(data, out=None): def exp(cube, in_place=False): """Calculate the exponential (exp(x)) of the cube. - Args: - - * cube: + Parameters + ---------- + cube : An instance of :class:`iris.cube.Cube`. - - .. note:: - - Taking an exponential will return a cube with dimensionless units. - - Kwargs: - - * in_place: + in_place : bool, default=False Whether to create a new Cube, or alter the given "cube". - Returns: - An instance of :class:`iris.cube.Cube`. + Returns + ------- + :class:`iris.cube.Cube`. Notes ----- + Taking an exponential will return a cube with dimensionless units. + This function maintains laziness when called; it does not realise data. See more at :doc:`/userguide/real_and_lazy_data`. @@ -609,18 +608,16 @@ def exp(cube, in_place=False): def log(cube, in_place=False): """Calculate the natural logarithm (base-e logarithm) of the cube. - Args: - - * cube: + Parameters + ---------- + cube : An instance of :class:`iris.cube.Cube`. - - Kwargs: - - * in_place: + in_place : bool, optional, default=False Whether to create a new Cube, or alter the given "cube". - Returns: - An instance of :class:`iris.cube.Cube`. + Returns + ------- + :class:`iris.cube.Cube` Notes ----- @@ -643,18 +640,16 @@ def log(cube, in_place=False): def log2(cube, in_place=False): """Calculate the base-2 logarithm of the cube. - Args: - - * cube: + Parameters + ---------- + cube : An instance of :class:`iris.cube.Cube`. - - Kwargs:lib/iris/tests/unit/analysis/maths/test_subtract.py - - * in_place: + in_place : bool, optional, default=False Whether to create a new Cube, or alter the given "cube". - Returns: - An instance of :class:`iris.cube.Cube`. + Returns + ------- + :class:`iris.cube.Cube` Notes ----- @@ -673,18 +668,16 @@ def log2(cube, in_place=False): def log10(cube, in_place=False): """Calculate the base-10 logarithm of the cube. - Args: - - * cube: + Parameters + ---------- + cube : An instance of :class:`iris.cube.Cube`. - - Kwargs: - - * in_place: + in_place : bool, optional, default=None Whether to create a new Cube, or alter the given "cube". - Returns: - An instance of :class:`iris.cube.Cube`. + Returns + ------- + :class:`iris.cube.Cube`. Notes ----- @@ -711,34 +704,33 @@ def apply_ufunc(ufunc, cube, other=None, new_unit=None, new_name=None, in_place= It is usually preferable to use these functions rather than :func:`iris.analysis.maths.apply_ufunc` where possible. - Args: - - * ufunc: + Parameters + ---------- + ufunc : An instance of :func:`numpy.ufunc` e.g. :func:`numpy.sin`, :func:`numpy.mod`. - - * cube: + cube : An instance of :class:`iris.cube.Cube`. Kwargs: - * other: + other ::class:`iris.cube.Cube`, optional, default=False An instance of :class:`iris.cube.Cube` to be given as the second argument to :func:`numpy.ufunc`. - - * new_unit: + new_unit : optional, default=False Unit for the resulting Cube. - - * new_name: + new_name : optional, default=False Name for the resulting Cube. - - * in_place: + in_place : bool, optional, default=False Whether to create a new Cube, or alter the given "cube". - Returns: - An instance of :class:`iris.cube.Cube`. + Returns + ------- + :class:`iris.cube.Cube`. - Example:: + Examples + -------- + :: cube = apply_ufunc(numpy.sin, cube, in_place=True) @@ -821,22 +813,29 @@ def _binary_op_common( ): """Function which shares common code between binary operations. - operation_function - function which does the operation - (e.g. numpy.divide) - operation_name - the public name of the operation (e.g. 'divide') - cube - the cube whose data is used as the first argument - to `operation_function` - other - the cube, coord, ndarray, dask array or number whose - data is used as the second argument - new_dtype - the expected dtype of the output. Used in the - case of scalar masked arrays - new_unit - unit for the resulting quantity - dim - dimension along which to apply `other` if it's a - coordinate that is not found in `cube` - in_place - whether or not to apply the operation in place to - `cube` and `cube.data` - sanitise_metadata - whether or not to remove metadata using - _sanitise_metadata function + Parameters + ---------- + operation_function : + Function which does the operation (e.g. numpy.divide) + operation_name : + The public name of the operation (e.g. 'divide') + cube : + The cube whose data is used as the first argument to `operation_function` + other : + The cube, coord, ndarray, dask array or number whose data is used + as the second argument + new_dtype : + The expected dtype of the output. Used in the case of scalar masked arrays + new_unit : optional, default=None + Unit for the resulting quantity + dim : optional, default=None + Dimension along which to apply `other` if it's a coordinate that is + not found in `cube` + in_place : bool, optional, default=False + whether or not to apply the operation in place to `cube` and `cube.data` + sanitise_metadata : bool, optional, default=True + Whether or not to remove metadata using _sanitise_metadata function + """ from iris.cube import Cube @@ -1041,25 +1040,24 @@ class IFunc: def __init__(self, data_func, units_func): """Create an ifunc from a data function and units function. - Args: - - * data_func: - + Parameters + ---------- + data_func : Function to be applied to one or two data arrays, which are given as positional arguments. Should return another data array, with the same shape as the first array. - May also have keyword arguments. - - * units_func: - + units_func : Function to calculate the units of the resulting cube. Should take the cube/s as input and return an instance of :class:`cf_units.Unit`. - Returns: - An ifunc. + Returns + ------- + ifunc + Examples + -------- **Example usage 1** Using an existing numpy ufunc, such as numpy.sin for the data function and a simple lambda function for the units function:: @@ -1090,6 +1088,7 @@ def ws_units_func(u_cube, v_cube): cs_ifunc = iris.analysis.maths.IFunc(numpy.cumsum, lambda a: a.units) cs_cube = cs_ifunc(cube, axis=1) + """ self._data_func_name = getattr( @@ -1164,33 +1163,27 @@ def __call__( ): """Applies the ifunc to the cube(s). - Args: - - * cube + Parameters + ---------- + cube : An instance of :class:`iris.cube.Cube`, whose data is used as the first argument to the data function. - - Kwargs: - - * other + * other : optional, default=None A cube, coord, ndarray, dask array or number whose data is used as the second argument to the data function. - - * new_name: + * new_name : optional, default=None Name for the resulting Cube. - - * in_place: + * in_place : bool, optional, default=False Whether to create a new Cube, or alter the given "cube". - - * dim: + * dim : optional, default=None Dimension along which to apply `other` if it's a coordinate that is not found in `cube` - - * kwargs_data_func: + ** kwargs_data_func : Keyword arguments that get passed on to the data_func. - Returns: - An instance of :class:`iris.cube.Cube`. + Returns + ------- + :class:`iris.cube.Cube` """ _assert_is_cube(cube) diff --git a/lib/iris/analysis/stats.py b/lib/iris/analysis/stats.py index e3a01f6933..fcadaebe1f 100644 --- a/lib/iris/analysis/stats.py +++ b/lib/iris/analysis/stats.py @@ -24,34 +24,36 @@ def pearsonr( """Calculate the Pearson's r correlation coefficient over specified dimensions. - Args: - - * cube_a, cube_b (cubes): + Parameters + ---------- + cube_a, cube_b : cubes Cubes between which the correlation will be calculated. The cubes should either be the same shape and have the same dimension coordinates or one cube should be broadcastable to the other. - * corr_coords (str or list of str): + corr_coords : str or list of str The cube coordinate name(s) over which to calculate correlations. If no names are provided then correlation will be calculated over all common cube dimensions. - * weights (numpy.ndarray, optional): + weights : numpy.ndarray, optional Weights array of same shape as (the smaller of) cube_a and cube_b. Note that latitude/longitude area weights can be calculated using :func:`iris.analysis.cartography.area_weights`. - * mdtol (float, optional): + mdtol : float, optional, default=1.0 Tolerance of missing data. The missing data fraction is calculated based on the number of grid cells masked in both cube_a and cube_b. If this fraction exceed mdtol, the returned value in the corresponding cell is masked. mdtol=0 means no missing data is tolerated while mdtol=1 means the resulting element will be masked if and only if all contributing elements are masked in cube_a or cube_b. Defaults to 1. - * common_mask (bool): + common_mask : bool, optional, default=False If True, applies a common mask to cube_a and cube_b so only cells which are unmasked in both cubes contribute to the calculation. If False, the variance for each cube is calculated from all available cells. Defaults to False. - Returns: + Returns + ------- + cube A cube of the correlation between the two input cubes along the specified dimensions, at each point in the remaining dimensions of the cubes. @@ -61,6 +63,8 @@ def pearsonr( time/altitude cube describing the latitude/longitude (i.e. pattern) correlation at each time/altitude point. + Notes + ----- Reference: https://en.wikipedia.org/wiki/Pearson_correlation_coefficient diff --git a/lib/iris/analysis/trajectory.py b/lib/iris/analysis/trajectory.py index ed5b911b0c..8c3be237f7 100644 --- a/lib/iris/analysis/trajectory.py +++ b/lib/iris/analysis/trajectory.py @@ -42,7 +42,16 @@ class Trajectory: def __init__(self, waypoints, sample_count=10): """Defines a trajectory using a sequence of waypoints. - For example:: + Parameters + ---------- + waypoints : + A sequence of dictionaries, mapping coordinate names to values. + sample_count : int, optional, default=10 + The number of sample positions to use along the trajectory. + + Examples + -------- + :: waypoints = [{'latitude': 45, 'longitude': -60}, {'latitude': 45, 'longitude': 0}] @@ -50,17 +59,7 @@ def __init__(self, waypoints, sample_count=10): .. note:: All the waypoint dictionaries must contain the same coordinate names. - - Args: - - * waypoints - A sequence of dictionaries, mapping coordinate names to values. - - Kwargs: - - * sample_count - The number of sample positions to use along the trajectory. - + """ self.waypoints = waypoints self.sample_count = sample_count @@ -75,6 +74,7 @@ def __init__(self, waypoints, sample_count=10): self.length = sum([seg.length for seg in segments]) # generate our sampled points + # TREMTEST: the below comment looks weird when rendered #: The trajectory points, as dictionaries of {coord_name: value}. self.sampled_points = [] sample_step = self.length / (self.sample_count - 1) @@ -119,7 +119,9 @@ def _get_interp_points(self): """Translate `self.sampled_points` to the format expected by the interpolator. - Returns: + Returns + ------- + `self.sampled points` `self.sampled points` in the format required by `:func:`~iris.analysis.trajectory.interpolate`. @@ -134,8 +136,9 @@ def _src_cube_anon_dims(self, cube): """A helper method to locate the index of anonymous dimensions on the interpolation target, ``cube``. - Returns: - The index of any anonymous dimensions in ``cube``. + Returns + ------- + The index of any anonymous dimensions in ``cube``. """ named_dims = [cube.coord_dims(c)[0] for c in cube.dim_coords] @@ -150,14 +153,11 @@ def interpolate(self, cube, method=None): supplied in the same coord_system as in `cube`, where appropriate (i.e. for horizontal coordinate points). - Args: - - * cube + Parameters + ---------- + cube : The source Cube to interpolate. - - Kwargs: - - * method: + method : The interpolation method to use; "linear" (default) or "nearest". Only nearest is available when specifying multi-dimensional coordinates. @@ -186,23 +186,20 @@ def interpolate(self, cube, method=None): def interpolate(cube, sample_points, method=None): """Extract a sub-cube at the given n-dimensional points. - Args: - - * cube + Parameters + ---------- + cube : The source Cube. - - * sample_points + sample_points : A sequence of coordinate (name) - values pairs. - - Kwargs: - - * method + method : optional, default=None Request "linear" interpolation (default) or "nearest" neighbour. Only nearest neighbour is available when specifying multi-dimensional coordinates. - - For example:: + Examples + -------- + :: sample_points = [('latitude', [45, 45, 45]), ('longitude', [-60, -50, -40])] @@ -487,17 +484,17 @@ def _cartesian_sample_points(sample_points, sample_point_coord_names): Generates coords suitable for nearest point calculations with `scipy.spatial.cKDTree`. - Args: + Parameters + ---------- + sample_points : + [coord][datum] list of sample_positions for each datum, formatted for + fast use of :func:`_ll_to_cart()`. + sample_point_coord_names : + [coord] list of n coord names - * sample_points[coord][datum]: - list of sample_positions for each datum, formatted for fast use of - :func:`_ll_to_cart()`. - - * sample_point_coord_names[coord]: - list of n coord names - - Returns: - list of [x,y,z,t,etc] positions, formatted for kdtree. + Returns + ------- + list of [x,y,z,t,etc] positions, formatted for kdtree. """ # Find lat and lon coord indices @@ -717,29 +714,31 @@ def __init__(self, src_cube, target_grid_cube): This can then be applied to any source data with the same structure as the original 'src_cube'. - Args: - - * src_cube: + Parameters + ---------- + src_cube : :class:`~iris.cube.Cube` The :class:`~iris.cube.Cube` defining the source grid. The X and Y coordinates can have any shape, but must be mapped over the same cube dimensions. - - * target_grid_cube: + target_grid_cube : :class:`~iris.cube.Cube` A :class:`~iris.cube.Cube`, whose X and Y coordinates specify a desired target grid. The X and Y coordinates must be one-dimensional dimension coordinates, mapped to different dimensions. All other cube components are ignored. - Returns: - regridder : (object) - - A callable object with the interface: - `result_cube = regridder(data)` + Returns + ------- + regridder (object) + A callable object with the interface:: + + result_cube = regridder(data) where `data` is a cube with the same grid as the original `src_cube`, that is to be regridded to the `target_grid_cube`. + Notes + ----- .. Note:: For latitude-longitude coordinates, the nearest-neighbour distances diff --git a/lib/iris/common/lenient.py b/lib/iris/common/lenient.py index 614060b9bf..bece97835e 100644 --- a/lib/iris/common/lenient.py +++ b/lib/iris/common/lenient.py @@ -53,22 +53,20 @@ def func() def func(): pass - Args: - - * dargs (tuple of callable): + Parameters + ---------- + dargs : tuple of callable A tuple containing the callable lenient client function/method to be wrapped by the decorator. This is automatically populated by Python through the decorator interface. No argument requires to be manually provided. - - Kwargs: - - * services (callable or str or iterable of callable/str) + services : callable or str or iterable of callable/str, optional, default=None Zero or more function/methods, or equivalent fully qualified string names, of lenient service function/methods. - Returns: - Closure wrapped function/method. + Returns + ------- + Closure wrapped function/method. """ ndargs = len(dargs) @@ -144,16 +142,17 @@ def func(): def func(): pass - Args: - - * dargs (tuple of callable): + Parameters + ---------- + dargs : tuple of callable A tuple containing the callable lenient service function/method to be wrapped by the decorator. This is automatically populated by Python through the decorator interface. No argument requires to be manually provided. - Returns: - Closure wrapped function/method. + Returns + ------- + Closure wrapped function/method. """ ndargs = len(dargs) @@ -195,12 +194,14 @@ def lenient_service_outer(func): def _qualname(func): """Return the fully qualified function/method string name. - Args: - - * func (callable): + Parameters + ---------- + func : callable Callable function/method. Non-callable arguments are simply passed through. + Notes + ----- .. note:: Inherited methods will be qualified with the base class that defines the method. @@ -218,14 +219,16 @@ class Lenient(threading.local): def __init__(self, **kwargs): """A container for managing the run-time lenient features and options. - Kwargs: - - * kwargs (dict) + Parameters + ---------- + **kwargs : dict Mapping of lenient key/value options to enable/disable. Note that, only the lenient "maths" options is available, which controls lenient/strict cube arithmetic. - For example:: + Examples + -------- + :: Lenient(maths=False) @@ -287,12 +290,13 @@ def context(self, **kwargs): applied. On exit from the context manager, the previous lenient option state is restored. + For example:: + with iris.common.Lenient.context(maths=False): pass """ - def configure_state(state): for feature, value in state.items(): self[feature] = value @@ -320,20 +324,19 @@ def __init__(self, *args, **kwargs): """A container for managing the run-time lenient services and client options for pre-defined functions/methods. - Args: - - * args (callable or str or iterable of callable/str) + Parameters + ---------- + *args : callable or str or iterable of callable/str A function/method or fully qualified string name of the function/method acting as a lenient service. - - Kwargs: - - * kwargs (dict of callable/str or iterable of callable/str) + **kwargs : dict of callable/str or iterable of callable/str, optional Mapping of lenient client function/method, or fully qualified string name of the function/method, to one or more lenient service function/methods or fully qualified string name of function/methods. - For example:: + Examples + -------- + :: _Lenient(service1, service2, client1=service1, client2=(service1, service2)) @@ -355,13 +358,14 @@ def __call__(self, func): """Determine whether it is valid for the function/method to provide a lenient service at runtime to the actively executing lenient client. - Args: - - * func (callable or str): + Parameters + ---------- + func : callable or str A function/method or fully qualified string name of the function/method. - Returns: - Boolean. + Returns + ------- + bool """ result = False @@ -438,6 +442,7 @@ def context(self, *args, **kwargs): state is restored. For example:: + with iris._LENIENT.context(example_lenient_flag=False): # ... code that expects some non-lenient behaviour @@ -509,9 +514,9 @@ def enable(self, state): Setting the state to `False` disables all lenient services, and setting the state to `True` enables all lenient services. - Args: - - * state (bool): + Parameters + ---------- + state : bool Activate state for lenient services. """ @@ -525,19 +530,15 @@ def register_client(self, func, services, append=False): """Add the provided mapping of lenient client function/method to required lenient service function/methods. - Args: - - * func (callable or str): + Parameters + ---------- + func : callable or str A client function/method or fully qualified string name of the client function/method. - - * services (callable or str or iterable of callable/str): + services : callable or str or iterable of callable/str One or more service function/methods or fully qualified string names of the required service function/method. - - Kwargs: - - * append (bool): + append : bool, optional If True, append the lenient services to any pre-registered lenient services for the provided lenient client. Default is False. @@ -568,9 +569,9 @@ def register_service(self, func): """Add the provided function/method as providing a lenient service and activate it. - Args: - - * func (callable or str): + Parameters + ---------- + func : callable or str A service function/method or fully qualified string name of the service function/method. @@ -588,9 +589,9 @@ def register_service(self, func): def unregister_client(self, func): """Remove the provided function/method as a lenient client using lenient services. - Args: - - * func (callable or str): + Paramters + --------- + func : callable or str A function/method of fully qualified string name of the function/method. """ @@ -614,9 +615,9 @@ def unregister_client(self, func): def unregister_service(self, func): """Remove the provided function/method as providing a lenient service. - Args: - - * func (callable or str): + Parameters + ---------- + func : callable or str A function/method or fully qualified string name of the function/method. """ diff --git a/lib/iris/common/metadata.py b/lib/iris/common/metadata.py index 691e427aa5..212691e046 100644 --- a/lib/iris/common/metadata.py +++ b/lib/iris/common/metadata.py @@ -59,12 +59,14 @@ def hexdigest(item): This provides a means to compare large and/or complex objects through simple string hexdigest comparison. - Args: - - * item (object): + Parameters + ---------- + item : object The item that requires to have its hexdigest calculated. - Returns: + Returns + ------- + str The string hexadecimal representation of the item's 64-bit hash. """ @@ -154,13 +156,14 @@ class BaseMetadata(metaclass=_NamedTupleMeta): def __eq__(self, other): """Determine whether the associated metadata members are equivalent. - Args: - - * other (metadata): + Parameters + ---------- + other : metadata A metadata instance of the same type. - Returns: - Boolean. + Returns + ------- + bool """ result = NotImplemented @@ -240,28 +243,23 @@ def __str__(self): def _api_common(self, other, func_service, func_operation, action, lenient=None): """Common entry-point for lenient metadata API methods. - Args: - - * other (metadata): + Parameters + ---------- + other : metadata A metadata instance of the same type. - - * func_service (callable): + func_service : callable The parent service method offering the API entry-point to the service. - - * func_operation (callable): + func_operation : callable The parent service method that provides the actual service. - - * action (str): + action : str The verb describing the service operation. - - Kwargs: - - * lenient (boolean): + lenient : bool, optional Enable/disable the lenient service operation. The default is to automatically detect whether this lenient service operation is enabled. - Returns: - The result of the service operation to the parent service caller. + Returns + ------- + The result of the service operation to the parent service caller. """ # Ensure that we have similar class instances. @@ -312,13 +310,14 @@ def func(field): def _combine_lenient(self, other): """Perform lenient combination of metadata members. - Args: - - * other (BaseMetadata): + Parameters + ---------- + other : BaseMetadata The other metadata participating in the lenient combination. - Returns: - A list of combined metadata member values. + Returns + ------- + A list of combined metadata member values. """ @@ -393,13 +392,14 @@ def _combine_strict_attributes(left, right): def _compare_lenient(self, other): """Perform lenient equality of metadata members. - Args: - - * other (BaseMetadata): + Parameters + ---------- + other : BaseMetadata The other metadata participating in the lenient comparison. - Returns: - Boolean. + Returns + ------- + bool """ result = False @@ -484,13 +484,14 @@ def func(field): def _difference_lenient(self, other): """Perform lenient difference of metadata members. - Args: - - * other (BaseMetadata): + Parameters + ---------- + other : BaseMetadata The other metadata participating in the lenient difference. - Returns: - A list of difference metadata member values. + Returns + ------- + A list of difference metadata member values. """ @@ -579,19 +580,17 @@ def combine(self, other, lenient=None): """Return a new metadata instance created by combining each of the associated metadata members. - Args: - - * other (metadata): + Parameters + ---------- + other : metadata A metadata instance of the same type. - - Kwargs: - - * lenient (boolean): + lenient : bool Enable/disable lenient combination. The default is to automatically detect whether this lenient operation is enabled. - Returns: - Metadata instance. + Returns + ------- + Metadata instance. """ result = self._api_common( @@ -608,19 +607,17 @@ def difference(self, other, lenient=None): is no difference between the members being compared. Otherwise, a tuple of the different values is returned. - Args: - - * other (metadata): + Parameters + ---------- + other : metadata A metadata instance of the same type. - - Kwargs: - - * lenient (boolean): + lenient : bool, optional Enable/disable lenient difference. The default is to automatically detect whether this lenient operation is enabled. - Returns: - Metadata instance of member differences or None. + Returns + ------- + Metadata instance of member differences or None. """ result = self._api_common( @@ -635,19 +632,17 @@ def difference(self, other, lenient=None): def equal(self, other, lenient=None): """Determine whether the associated metadata members are equivalent. - Args: - - * other (metadata): + Parameters + ---------- + other : metadata A metadata instance of the same type. - - Kwargs: - - * lenient (boolean): + lenient : bool, optional Enable/disable lenient equivalence. The default is to automatically detect whether this lenient operation is enabled. - Returns: - Boolean. + Returns + ------- + bool """ result = self._api_common( @@ -662,13 +657,14 @@ def from_metadata(cls, other): Non-common metadata members are set to ``None``. - Args: - - * other (metadata): + Parameters + ---------- + other : metadata A metadata instance of any type. - Returns: - New metadata instance. + Returns + ------- + New metadata instance. """ result = None @@ -690,19 +686,20 @@ def name(self, default=None, token=False): the NetCDF variable name, before falling-back to a default value, which itself defaults to the string 'unknown'. - Kwargs: - - * default: + Parameters + ---------- + default : optional The fall-back string representing the default name. Defaults to the string 'unknown'. - * token: + token : bool, optional 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. - Returns: - String. + Returns + ------- + str """ @@ -729,13 +726,14 @@ def token(cls, name): """Determine whether the provided name is a valid NetCDF name and thus safe to represent a single parsable token. - Args: - - * name: + Parameters + ---------- + name : str The string name to verify - Returns: - The provided name if valid, otherwise None. + Returns + ------- + The provided name if valid, otherwise None. """ if name is not None: @@ -786,14 +784,15 @@ def __eq__(self, other): def _combine_lenient(self, other): """Perform lenient combination of metadata members for cell measures. - Args: - - * other (CellMeasureMetadata): + Parameters + ---------- + other : CellMeasureMetadata The other cell measure metadata participating in the lenient combination. - Returns: - A list of combined metadata member values. + Returns + ------- + A list of combined metadata member values. """ # Perform "strict" combination for "measure". @@ -807,14 +806,15 @@ def _combine_lenient(self, other): def _compare_lenient(self, other): """Perform lenient equality of metadata members for cell measures. - Args: - - * other (CellMeasureMetadata): + Parameters + ---------- + other : CellMeasureMetadata The other cell measure metadata participating in the lenient comparison. - Returns: - Boolean. + Returns + ------- + bool """ # Perform "strict" comparison for "measure". @@ -828,14 +828,15 @@ def _compare_lenient(self, other): def _difference_lenient(self, other): """Perform lenient difference of metadata members for cell measures. - Args: - - * other (CellMeasureMetadata): + Parameters + ---------- + other : CellMeasureMetadata The other cell measure metadata participating in the lenient difference. - Returns: - A list of difference metadata member values. + Returns + ------- + A list of difference metadata member values. """ # Perform "strict" difference for "measure". @@ -908,14 +909,15 @@ def _sort_key(item): def _combine_lenient(self, other): """Perform lenient combination of metadata members for coordinates. - Args: - - * other (CoordMetadata): + Parameters + ---------- + other : CoordMetadata The other coordinate metadata participating in the lenient combination. - Returns: - A list of combined metadata member values. + Returns + ------- + A list of combined metadata member values. """ @@ -936,14 +938,15 @@ def func(field): def _compare_lenient(self, other): """Perform lenient equality of metadata members for coordinates. - Args: - - * other (CoordMetadata): + Parameters + ---------- + other : CoordMetadata The other coordinate metadata participating in the lenient comparison. - Returns: - Boolean. + Returns + ------- + bool """ # Perform "strict" comparison for "coord_system" and "climatological". @@ -962,14 +965,15 @@ def _compare_lenient(self, other): def _difference_lenient(self, other): """Perform lenient difference of metadata members for coordinates. - Args: - - * other (CoordMetadata): + Parameters + ---------- + other : CoordMetadata The other coordinate metadata participating in the lenient difference. - Returns: - A list of difference metadata member values. + Returns + ------- + A list of difference metadata member values. """ @@ -1057,13 +1061,14 @@ def _sort_key(item): def _combine_lenient(self, other): """Perform lenient combination of metadata members for cubes. - Args: - - * other (CubeMetadata): + Parameters + ---------- + other : CubeMetadata The other cube metadata participating in the lenient combination. - Returns: - A list of combined metadata member values. + Returns + ------- + A list of combined metadata member values. """ # Perform "strict" combination for "cell_methods". @@ -1077,13 +1082,14 @@ def _combine_lenient(self, other): def _compare_lenient(self, other): """Perform lenient equality of metadata members for cubes. - Args: - - * other (CubeMetadata): + Parameters + ---------- + other : CubeMetadata The other cube metadata participating in the lenient comparison. - Returns: - Boolean. + Returns + ------- + bool """ # Perform "strict" comparison for "cell_methods". @@ -1096,13 +1102,14 @@ def _compare_lenient(self, other): def _difference_lenient(self, other): """Perform lenient difference of metadata members for cubes. - Args: - - * other (CubeMetadata): + Parameters + ---------- + other : CubeMetadata The other cube metadata participating in the lenient difference. - Returns: - A list of difference metadata member values. + Returns + ------- + A list of difference metadata member values. """ # Perform "strict" difference for "cell_methods". @@ -1336,47 +1343,40 @@ def metadata_filter( Criteria can be either specific properties or other objects with metadata to be matched. - Args: - - * instances: + Parameters + ---------- + instances : One or more objects to be filtered. - - Kwargs: - - * item: + item : optional Either, * a :attr:`~iris.common.mixin.CFVariableMixin.standard_name`, :attr:`~iris.common.mixin.CFVariableMixin.long_name`, or :attr:`~iris.common.mixin.CFVariableMixin.var_name` which is compared against the :meth:`~iris.common.mixin.CFVariableMixin.name`. - * a coordinate or metadata instance equal to that of the desired objects e.g., :class:`~iris.coords.DimCoord` or :class:`CoordMetadata`. - - * standard_name: + standard_name : optional The CF standard name of the desired object. If ``None``, does not check for ``standard_name``. - - * long_name: + long_name : optional An unconstrained description of the object. If ``None``, does not check for ``long_name``. - - * var_name: + var_name : optional The NetCDF variable name of the desired object. If ``None``, does not check for ``var_name``. - - * attributes: + attributes : dict, optional A dictionary of attributes desired on the object. If ``None``, does not check for ``attributes``. - - * axis: + axis : optional The desired object's axis, see :func:`~iris.util.guess_coord_axis`. If ``None``, does not check for ``axis``. Accepts the values ``X``, ``Y``, ``Z`` and ``T`` (case-insensitive). - Returns: + Returns + ------- + list of the objects A list of the objects supplied in the ``instances`` argument, limited to only those that matched the given criteria. @@ -1559,20 +1559,18 @@ def metadata_manager_factory(cls, **kwargs): The factory instances returned by the factory are capable of managing their metadata state, which can be proxied by the owning container. - Args: - - * cls: + Parameters + ---------- + cls : A subclass of :class:`~iris.common.metadata.BaseMetadata`, defining the metadata to be managed. - - Kwargs: - - * kwargs: + **kwargs : Initial values for the manufactured metadata instance. Unspecified fields will default to a value of 'None'. - Returns: - A manager instance for the provided metadata ``cls``. + Returns + ------- + A manager instance for the provided metadata ``cls``. """ # Check whether kwargs have valid fields for the specified metadata. diff --git a/lib/iris/common/resolve.py b/lib/iris/common/resolve.py index 84ea6eed24..ea0d67e110 100644 --- a/lib/iris/common/resolve.py +++ b/lib/iris/common/resolve.py @@ -205,7 +205,7 @@ class Resolve: >>> resolver = Resolve(cube1, cube2) >>> results = [resolver.cube(data) for data in payload] - """ # noqa: D214, D410, D411 + """ # noqa: D214, D407, D410, D411 def __init__(self, lhs=None, rhs=None): """Resolve the provided ``lhs`` :class:`~iris.cube.Cube` operand and @@ -236,8 +236,16 @@ def __init__(self, lhs=None, rhs=None): but this may not be possible when auto-transposition or extended broadcasting is involved during the operation. - For example: + Parameters + ---------- + lhs : :class:`~iris.cube.Cube` + The left-hand-side :class:`~iris.cube.Cube` operand. + rhs : :class:`~iris.cube.Cube` + The right-hand-side :class:`~iris.cube.Cube` operand. + + Examples + -------- .. doctest:: >>> cube1 @@ -249,14 +257,6 @@ def __init__(self, lhs=None, rhs=None): >>> result1 == result2 True - Kwargs: - - * lhs: - The left-hand-side :class:`~iris.cube.Cube` operand. - - * rhs: - The right-hand-side :class:`~iris.cube.Cube` operand. - """ #: The ``lhs`` operand to be resolved into the resultant :class:`~iris.cube.Cube`. self.lhs_cube = None # set in __call__ @@ -332,12 +332,11 @@ def __call__(self, lhs, rhs): :class:`~iris.cube.Cube`, which may be auto-transposed, can be determined. - Args: - - * lhs: + Parameters + ---------- + lhs : :class:`~iris.cube.Cube` The left-hand-side :class:`~iris.cube.Cube` operand. - - * rhs: + rhs : :class:`~iris.cube.Cube` The right-hand-side :class:`~iris.cube.Cube` operand. """ @@ -496,29 +495,26 @@ def _aux_coverage( The scalar coordinates local to the cube are also determined. - Args: - - * cube: + Parameters + ---------- + cube : :class:`~iris.cube.Cube` The :class:`~iris.cube.Cube` to be analysed for coverage. - - * cube_items_aux: + cube_items_aux : The list of associated :class:`~iris.common.resolve._Item` metadata for each auxiliary coordinate owned by the cube. - - * cube_items_scalar: + cube_items_scalar : The list of associated :class:`~iris.common.resolve._Item` metadata for each scalar coordinate owned by the cube. - - * common_aux_metadata: + common_aux_metadata : The list of common auxiliary coordinate metadata shared by both the LHS and RHS cube operands being resolved. - - * common_scalar_metadata: + common_scalar_metadata : The list of common scalar coordinate metadata shared by both the LHS and RHS cube operands being resolved. - Returns: - :class:`~iris.common.resolve._AuxCoverage` + Returns + ------- + :class:`~iris.common.resolve._AuxCoverage` """ common_items_aux = [] @@ -565,20 +561,20 @@ def _aux_mapping(src_coverage, tgt_coverage): The ``src`` to ``tgt`` common auxiliary coordinate mapping is held by the :attr:`~iris.common.resolve.Resolve.mapping`. - Args: - - * src_coverage: + Parameters + ---------- + src_coverage : The :class:`~iris.common.resolve._DimCoverage` of the ``src`` :class:`~iris.cube.Cube` i.e., map from the common ``src`` dimensions. - - * tgt_coverage: + tgt_coverage : The :class:`~iris.common.resolve._DimCoverage` of the ``tgt`` :class:`~iris.cube.Cube` i.e., map to the common ``tgt`` dimensions. - Returns: - Dictionary of ``src`` to ``tgt`` dimension mapping. + Returns + ------- + dict of ``src`` to ``tgt`` dimension mapping. """ mapping = {} @@ -628,15 +624,16 @@ def _categorise_items(cube): coordinates and associated metadata into dimension, auxiliary and scalar categories. - Args: - - * cube: + Parameters + ---------- + cube : :class:`~iris.cube.Cube` The :class:`~iris.cube.Cube` that will have its coordinates and metadata grouped into their associated dimension, auxiliary and scalar categories. - Returns: - :class:`~iris.common.resolve._CategoryItems` + Returns + ------- + :class:`~iris.common.resolve._CategoryItems` """ category = _CategoryItems(items_dim=[], items_aux=[], items_scalar=[]) @@ -675,35 +672,32 @@ def _create_prepared_item( containing the data and metadata required to construct and attach a coordinate to the resultant resolved cube. - Args: - - * coord: + Parameters + ---------- + coord : The coordinate with the ``points`` and ``bounds`` to be extracted. - - * dims (int or tuple): + dims : int or tuple The dimensions that the ``coord`` spans on the resulting resolved :class:`~iris.cube.Cube`. (Can also be a single dimension number). - - * src_metadata: + src_metadata : The coordinate metadata from the ``src`` :class:`~iris.cube.Cube`. - - * tgt_metadata: + tgt_metadata : The coordinate metadata from the ``tgt`` :class:`~iris.cube.Cube`. - - * points: + points : Override points array. When not given, use coord.points. - - * bounds: + bounds : Override bounds array. When not given, use coord.bounds. - - * container: + container : Override coord type (class constructor). When not given, use type(coord). - Returns: - The :class:`~iris.common.resolve._PreparedItem`. + Returns + ------- + :class:`~iris.common.resolve._PreparedItem`. + Notes + ----- .. note:: If container or type(coord) is DimCoord/AuxCoord (i.e. not @@ -802,21 +796,20 @@ def _dim_coverage(cube, cube_items_dim, common_dim_metadata): The cube dimensions not covered by any of the dimension coordinates is also determined; these are known as `free` dimensions. - Args: - - * cube: + Parameters + ---------- + cube : :class:`~iris.cube.Cube` The :class:`~iris.cube.Cube` to be analysed for coverage. - - * cube_items_dim: + cube_items_dim : The list of associated :class:`~iris.common.resolve._Item` metadata for each dimension coordinate owned by the cube. - - * common_dim_metadata: + common_dim_metadata : The list of common dimension coordinate metadata shared by both the LHS and RHS cube operands being resolved. - Returns: - :class:`~iris.common.resolve._DimCoverage` + Returns + ------- + :class:`~iris.common.resolve._DimCoverage` """ ndim = cube.ndim @@ -854,20 +847,20 @@ def _dim_mapping(src_coverage, tgt_coverage): The ``src`` to ``tgt`` common dimension coordinate mapping is held by the :attr:`~iris.common.resolve.Resolve.mapping`. - Args: - - * src_coverage: + Parameters + ---------- + src_coverage : The :class:`~iris.common.resolve._DimCoverage` of the ``src`` :class:`~iris.cube.Cube` i.e., map from the common ``src`` dimensions. - - * tgt_coverage: + tgt_coverage : The :class:`~iris.common.resolve._DimCoverage` of the ``tgt`` :class:`~iris.cube.Cube` i.e., map to the common ``tgt`` dimensions. - Returns: - Dictionary of ``src`` to ``tgt`` dimension mapping. + Returns + ------- + dict of ``src`` to ``tgt`` dimension mapping. """ mapping = {} @@ -919,24 +912,23 @@ def _free_mapping( An exception will be raised if there are any ``src`` :class:`~iris.cube.Cube` dimensions not mapped to an associated ``tgt`` dimension. - Args: - - * src_dim_coverage: + Parameters + ---------- + src_dim_coverage : The :class:`~iris.common.resolve.._DimCoverage` of the ``src`` :class:`~iris.cube.Cube`. - - * tgt_dim_coverage: + tgt_dim_coverage : The :class:`~iris.common.resolve.._DimCoverage` of the ``tgt`` :class:`~iris.cube.Cube`. - - * src_aux_coverage: + src_aux_coverage : The :class:`~iris.common.resolve._AuxCoverage` of the ``src`` :class:`~iris.cube.Cube`. - - * tgt_aux_coverage: + tgt_aux_coverage : The :class:`~iris.common.resolve._AuxCoverage` of the ``tgt`` :class:`~iris.cube.Cube`. + Notes + ----- .. note:: All unmapped dimensions with an extend >1 are mapped before those @@ -1411,24 +1403,19 @@ def _prepare_common_aux_payload( For mixed ``src`` and ``tgt`` coordinate types with matching metadata, an :class:`~iris.coords.AuxCoord` will be nominated for construction. - Args: - - * src_common_items: + Parameters + ---------- + src_common_items : The list of :attr:`~iris.common.resolve._AuxCoverage.common_items_aux` metadata for the ``src`` :class:`~iris.cube.Cube`. - - * tgt_common_items: + tgt_common_items : The list of :attr:`~iris.common.resolve._AuxCoverage.common_items_aux` metadata for the ``tgt`` :class:`~iris.cube.Cube`. - - * prepared_items: + prepared_items : The list of :class:`~iris.common.resolve._PreparedItem` metadata that will be used to construct the auxiliary coordinates that will be attached to the resulting resolved :class:`~iris.cube.Cube`. - - Kwargs: - - * ignore_mismatch: + ignore_mismatch : optional When ``False``, an exception will be raised if a difference is detected between corresponding ``src`` and ``tgt`` coordinate ``points`` and/or ``bounds``. When ``True``, the coverage metadata is ignored i.e., a coordinate will not be constructed and @@ -1535,17 +1522,15 @@ def _prepare_common_dim_payload( each :class:`~iris.coords.DimCoord` to be constructed and attached to the resulting resolved :class:`~iris.cube.Cube`. - Args: - - * src_coverage: - The :class:`~iris.common.resolve._DimCoverage` metadata for the ``src`` :class:`~iris.cube.Cube`. - - * tgt_coverage: - The :class:`~iris.common.resolve._DimCoverage` metadata for the ``tgt`` :class:`~iris.cube.Cube`. - - Kwargs: - - * ignore_mismatch: + Parameters + ---------- + src_coverage : + The :class:`~iris.common.resolve._DimCoverage` metadata for the + ``src`` :class:`~iris.cube.Cube`. + tgt_coverage : + The :class:`~iris.common.resolve._DimCoverage` metadata for the + ``tgt`` :class:`~iris.cube.Cube`. + ignore_mismatch : optional When ``False``, an exception will be raised if a difference is detected between corresponding ``src`` and ``tgt`` :class:`~iris.coords.DimCoord` ``points`` and/or ``bounds``. When ``True``, the coverage metadata is ignored i.e., a :class:`~iris.coords.DimCoord` will not @@ -1599,29 +1584,26 @@ def _get_prepared_item( If a match is found, then a new `~iris.common.resolve._PreparedItem` is created and added to :attr:`~iris.common.resolve.Resolve.prepared_category` and returned. See ``from_local``. - Args: - - * metadata: + Parameters + ---------- + metadata : The target metadata of the prepared (or local) item to retrieve. - - * category_local: + category_local : The :class:`~iris.common.resolve._CategoryItems` containing the local metadata of either the ``src`` or ``tgt`` :class:`~iris.cube.Cube`. See ``from_local``. - - Kwargs: - - * from_src: + from_src : bool, optional Boolean stating whether the ``metadata`` is from the ``src`` (``True``) or ``tgt`` :class:`~iris.cube.Cube`. Defaults to ``True``. - - * from_local: + from_local: bool, optional Boolean controlling whether the ``metadata`` is used to search the ``category_local`` (``True``) or the :attr:`~iris.common.resolve.Resolve.prepared_category`. Defaults to ``False``. - Returns: + Returns + ------- + :class:`~iris.common.resolve._PreparedItem` The :class:`~iris.common.resolve._PreparedItem` matching the provided ``metadata``. """ @@ -1680,17 +1662,15 @@ def _prepare_factory_payload(self, cube, category_local, from_src=True): :attr:`~iris.common.resolve.Resolve.prepared_category` and therefore this is a legitimate reason to add the associated metadata of the local dependency to the ``prepared_category``. - Args: - - * cube: - The :class:`~iris.cube.Cube` that may contain an auxiliary factory to be prepared. - - * category_local: - The :class:`~iris.common.resolve._CategoryItems` of all metadata local to the provided ``cube``. - - Kwargs: - - * from_src: + Parameters + ---------- + cube : :class:`~iris.cube.Cube` + The :class:`~iris.cube.Cube` that may contain an auxiliary factory + to be prepared. + category_local : :class:`~iris.common.resolve._CategoryItems` + The :class:`~iris.common.resolve._CategoryItems` of all metadata + local to the provided ``cube``. + from_src : bool, optional, default=True Boolean stating whether the provided ``cube`` is either a ``src`` or ``tgt`` :class:`~iris.cube.Cube` - used to retrieve the appropriate metadata from a :class:`~iris.common.resolve._PreparedMetadata`. @@ -1755,19 +1735,22 @@ def _prepare_local_payload_aux(self, src_aux_coverage, tgt_aux_coverage): .. note:: - In general, lenient behaviour subscribes to the philosophy that it is easier to remove - metadata than it is to find then add metadata. To those ends, lenient behaviour supports - metadata richness by adding both local ``src`` and ``tgt`` auxiliary coordinates. - Alternatively, strict behaviour will only add a ``tgt`` local auxiliary coordinate that - spans dimensions not mapped to by the ``src`` e.g., extra ``tgt`` dimensions. - - Args: - - * src_aux_coverage: - The :class:`~iris.common.resolve.Resolve._AuxCoverage` for the ``src`` :class:`~iris.cube.Cube`. - - * tgt_aux_coverage: - The :class:~iris.common.resolve.Resolve._AuxCoverage` for the ``tgt`` :class:`~iris.cube.Cube`. + In general, lenient behaviour subscribes to the philosophy that + it is easier to remove metadata than it is to find then add + metadata. To those ends, lenient behaviour supports metadata + richness by adding both local ``src`` and ``tgt`` auxiliary + coordinates. Alternatively, strict behaviour will only add a + ``tgt`` local auxiliary coordinate that spans dimensions not + mapped to by the ``src`` e.g., extra ``tgt`` dimensions. + + Parameters + ---------- + src_aux_coverage : + The :class:`~iris.common.resolve.Resolve._AuxCoverage` for the + ``src`` :class:`~iris.cube.Cube`. + tgt_aux_coverage : + The :class:~iris.common.resolve.Resolve._AuxCoverage` for the + ``tgt`` :class:`~iris.cube.Cube`. """ # Determine whether there are tgt dimensions not mapped to by an @@ -1832,13 +1815,14 @@ def _prepare_local_payload_dim(self, src_dim_coverage, tgt_dim_coverage): is more liberal, whereas strict behaviour will only add a local ``tgt`` coordinate covering an unmapped "extra" ``tgt`` dimension/s. - Args: - - * src_dim_coverage: - The :class:`~iris.common.resolve.Resolve._DimCoverage` for the ``src`` :class:`~iris.cube.Cube`. - - * tgt_dim_coverage: - The :class:`~iris.common.resolve.Resolve._DimCoverage` for the ``tgt`` :class:`~iris.cube.Cube`. + Parameters + ---------- + src_dim_coverage : + The :class:`~iris.common.resolve.Resolve._DimCoverage` for the + ``src`` :class:`~iris.cube.Cube`. + tgt_dim_coverage : + The :class:`~iris.common.resolve.Resolve._DimCoverage` for the + ``tgt`` :class:`~iris.cube.Cube`. """ mapped_tgt_dims = self.mapping.values() @@ -1909,13 +1893,14 @@ def _prepare_local_payload_scalar(self, src_aux_coverage, tgt_aux_coverage): Alternatively, strict behaviour will only add a ``tgt`` local scalar coordinate when the ``src`` is a scalar :class:`~iris.cube.Cube` with no local scalar coordinates. - Args: - - * src_aux_coverage: - The :class:`~iris.common.resolve.Resolve._AuxCoverage` for the ``src`` :class:`~iris.cube.Cube`. - - * tgt_aux_coverage: - The :class:~iris.common.resolve.Resolve._AuxCoverage` for the ``tgt`` :class:`~iris.cube.Cube`. + Parameters + ---------- + src_aux_coverage : + The :class:`~iris.common.resolve.Resolve._AuxCoverage` for the + ``src`` :class:`~iris.cube.Cube`. + tgt_aux_coverage : + The :class:~iris.common.resolve.Resolve._AuxCoverage` for the + ``tgt`` :class:`~iris.cube.Cube`. """ # Add all local tgt scalar coordinates iff the src cube is a @@ -1954,19 +1939,20 @@ def _prepare_local_payload( and/or ``tgt`` :class:`~iris.cube.Cube` for each coordinate to be constructed and attached to the resulting resolved :class:`~iris.cube.Cube`. - Args: - - * src_dim_coverage: - The :class:`~iris.common.resolve.Resolve._DimCoverage` for the ``src`` :class:`~iris.cube.Cube`. - - * src_aux_coverage: - The :class:`~iris.common.resolve.Resolve._AuxCoverage` for the ``src`` :class:`~iris.cube.Cube`. - - * tgt_dim_coverage: - The :class:`~iris.common.resolve.Resolve._DimCoverage` for the ``tgt`` :class:`~iris.cube.Cube`. - - * tgt_aux_coverage: - The :class:~iris.common.resolve.Resolve._AuxCoverage` for the ``tgt`` :class:`~iris.cube.Cube`. + Parameters + ---------- + src_dim_coverage : + The :class:`~iris.common.resolve.Resolve._DimCoverage` for the + ``src`` :class:`~iris.cube.Cube`. + src_aux_coverage : + The :class:`~iris.common.resolve.Resolve._AuxCoverage` for the + ``src`` :class:`~iris.cube.Cube`. + tgt_dim_coverage : + The :class:`~iris.common.resolve.Resolve._DimCoverage` for the + ``tgt`` :class:`~iris.cube.Cube`. + tgt_aux_coverage : + The :class:~iris.common.resolve.Resolve._AuxCoverage` for the + ``tgt`` :class:`~iris.cube.Cube`. """ # Add local src/tgt dim coordinates. @@ -1994,31 +1980,26 @@ def _prepare_points_and_bounds( An exception will be raised if either the points or bounds are different, however appropriate lenient behaviour concessions are applied. - Args: - - * src_coord: + Parameters + ---------- + src_coord : The ``src`` :class:`~iris.cube.Cube` coordinate with metadata matching the ``tgt_coord``. - - * tgt_coord: + tgt_coord : The ``tgt`` :class`~iris.cube.Cube` coordinate with metadata matching the ``src_coord``. - - * src_dims: + src_dims : The dimension/s of the ``src_coord`` attached to the ``src`` :class:`~iris.cube.Cube`. - - * tgt_dims: + tgt_dims : The dimension/s of the ``tgt_coord`` attached to the ``tgt`` :class:`~iris.cube.Cube`. - - Kwargs: - - * ignore_mismatch: + ignore_mismatch : bool, optional For lenient behaviour only, don't raise an exception if there is a difference between the ``src`` and ``tgt`` coordinate points or bounds. Defaults to ``False``. - Returns: - Tuple of equivalent ``points`` and ``bounds``, otherwise ``None``. + Returns + ------- + Tuple of equivalent ``points`` and ``bounds``, otherwise ``None``. """ from iris.util import array_equal @@ -2262,16 +2243,13 @@ def cube(self, data, in_place=False): and ``rhs`` :class:`~iris.cube.Cube` operands, using the provided ``data``. - Args: - - * data: + Parameters + ---------- + data : The data payload for the resultant :class:`~iris.cube.Cube`, which **must match** the expected resolved :attr:`~iris.common.resolve.Resolve.shape`. - - Kwargs: - - * in_place: + in_place : optional If ``True``, the ``data`` is inserted into the ``tgt`` :class:`~iris.cube.Cube`. The existing metadata of the ``tgt`` :class:`~iris.cube.Cube` is replaced with the resolved metadata from @@ -2279,9 +2257,12 @@ def cube(self, data, in_place=False): a **new** :class:`~iris.cube.Cube` instance is returned. Default is ``False``. - Returns: - :class:`~iris.cube.Cube` + Returns + ------- + :class:`~iris.cube.Cube` + Notes + ----- .. note:: :class:`~iris.common.resolve.Resolve` will determine whether the @@ -2301,8 +2282,8 @@ def cube(self, data, in_place=False): match** the expected resolved :attr:`~iris.common.resolve.Resolve.shape`. - For example: - + Examples + -------- .. testsetup:: in-place import iris @@ -2493,7 +2474,7 @@ def mapped(self): >>> resolver.map_rhs_to_lhs False - """ # noqa: D214, D410, D411 + """ # noqa: D214, D407, D410, D411 result = None if self.mapping is not None: result = self._src_cube.ndim == len(self.mapping) @@ -2554,5 +2535,5 @@ def shape(self): >>> Resolve(cube2, cube1).shape (240, 37, 49) - """ # noqa: D214, D410, D411 + """ # noqa: D214, D407, D410, D411 return self._broadcast_shape diff --git a/lib/iris/coord_categorisation.py b/lib/iris/coord_categorisation.py index dbf27ea86e..84eb038269 100644 --- a/lib/iris/coord_categorisation.py +++ b/lib/iris/coord_categorisation.py @@ -5,12 +5,13 @@ """Cube functions for coordinate categorisation. All the functions provided here add a new coordinate to a cube. - * The function :func:`add_categorised_coord` performs a generic - coordinate categorisation. - * The other functions all implement specific common cases - (e.g. :func:`add_day_of_month`). - Currently, these are all calendar functions, so they only apply to - "Time coordinates". + +* The function :func:`add_categorised_coord` performs a generic + coordinate categorisation. +* The other functions all implement specific common cases + (e.g. :func:`add_day_of_month`). + Currently, these are all calendar functions, so they only apply to + "Time coordinates". """ @@ -28,21 +29,18 @@ def add_categorised_coord(cube, name, from_coord, category_function, units="1"): Make a new :class:`iris.coords.AuxCoord` from mapped values, and add it to the cube. - Args: - - * cube (:class:`iris.cube.Cube`): - the cube containing 'from_coord'. The new coord will be added into it. - * name (string): + Parameters + ---------- + cube : :class:`iris.cube.Cube` + The cube containing 'from_coord'. The new coord will be added into it. + name : str name of the created coordinate - * from_coord (:class:`iris.coords.Coord` or string): + from_coord : :class:`iris.coords.Coord` or str coordinate in 'cube', or the name of one - * category_function (callable): + category_function : callable function(coordinate, value), returning a category value for a coordinate point-value - - Kwargs: - - * units: + units : str, optional, default="1" units of the category value, typically 'no_unit' or '1'. """ # Interpret coord, if given as a name @@ -90,15 +88,16 @@ def vectorised_fn(*args): def _pt_date(coord, time): """Return the datetime of a time-coordinate point. - Args: - - * coord (Coord): + Parameters + ---------- + coord : Coord coordinate (must be Time-type) - * time (float): + time : float value of a coordinate point - Returns: - cftime.datetime + Returns + ------- + cftime.datetime """ # NOTE: All of the currently defined categorisation functions are @@ -304,19 +303,16 @@ def add_season(cube, coord, name="season", seasons=("djf", "mam", "jja", "son")) """Add a categorical season-of-year coordinate, with user specified seasons. - Args: - - * cube (:class:`iris.cube.Cube`): + Parameters + ---------- + cube : :class:`iris.cube.Cube` The cube containing 'coord'. The new coord will be added into it. - * coord (:class:`iris.coords.Coord` or string): + coord : :class:`iris.coords.Coord` or str Coordinate in 'cube', or its name, representing time. - - Kwargs: - - * name (string): + name : str, optional Name of the created coordinate. Defaults to "season". - * seasons (:class:`list` of strings): + seasons : :class:`list` of str, optional List of seasons defined by month abbreviations. Each month must appear once and only once. Defaults to standard meteorological seasons ('djf', 'mam', 'jja', 'son'). @@ -343,19 +339,16 @@ def add_season_number( """Add a categorical season-of-year coordinate, values 0..N-1 where N is the number of user specified seasons. - Args: - - * cube (:class:`iris.cube.Cube`): + Parameters + ---------- + cube : :class:`iris.cube.Cube` The cube containing 'coord'. The new coord will be added into it. - * coord (:class:`iris.coords.Coord` or string): + coord : :class:`iris.coords.Coord` or str Coordinate in 'cube', or its name, representing time. - - Kwargs: - - * name (string): + name : str, optional Name of the created coordinate. Defaults to "season_number". - * seasons (:class:`list` of strings): + seasons : :class:`list` of str, optional List of seasons defined by month abbreviations. Each month must appear once and only once. Defaults to standard meteorological seasons ('djf', 'mam', 'jja', 'son'). @@ -429,19 +422,16 @@ def add_season_membership(cube, coord, season, name="season_membership"): The coordinate has the value True for every time that is within the given season, and the value False otherwise. - Args: - - * cube (:class:`iris.cube.Cube`): + Parameters + ---------- + cube : :class:`iris.cube.Cube` The cube containing 'coord'. The new coord will be added into it. - * coord (:class:`iris.coords.Coord` or string): + coord : :class:`iris.coords.Coord` or str Coordinate in 'cube', or its name, representing time. - * season (string): + season : str Season defined by month abbreviations. - - Kwargs: - - * name (string): + name : str, optinal Name of the created coordinate. Defaults to "season_membership". """ diff --git a/lib/iris/coords.py b/lib/iris/coords.py index 9336f1f4c7..b08e61ac02 100644 --- a/lib/iris/coords.py +++ b/lib/iris/coords.py @@ -70,24 +70,24 @@ def __init__( attributes=None, ): """Constructs a single dimensional metadata object. - - Args: - - * values: + + Parameters + ---------- + values : The values of the dimensional metadata. Kwargs: - * standard_name: + standard_name : optional, default=None CF standard name of the dimensional metadata. - * long_name: + long_name : optional, default=None Descriptive name of the dimensional metadata. - * var_name: + var_name : optional, default=None The netCDF variable name for the dimensional metadata. - * units + units : optional, default=None The :class:`~cf_units.Unit` of the dimensional metadata's values. Can be a string, which will be converted to a Unit object. - * attributes + attributes : optional, default=None A dictionary containing other cf and user-defined attributes. """ @@ -164,9 +164,9 @@ def __getitem__(self, keys): def copy(self, values=None): """Returns a copy of this dimensional metadata object. - Kwargs: - - * values + Parameters + ---------- + values : optional An array of values for the new dimensional metadata object. This may be a different shape to the original values array being copied. @@ -287,7 +287,7 @@ def summary( linewidth : int or None, default = None Character-width controlling line splitting of array outputs. If unset, defaults to ``numpy.get_printoptions['linewidth']``\ . - edgeitems : int = 2 + edgeitems : int, default=2 Controls truncated array output. Overrides ``numpy.getprintoptions['edgeitems']``\ . precision : int or None, default = None @@ -303,7 +303,8 @@ def summary( result : str Output text, with embedded newlines when :attr:`shorten`\ =False. - + Notes + ----- .. note:: Arrays are formatted using :meth:`numpy.array2string`. Some aspects of the array formatting are controllable in the usual way, via @@ -809,13 +810,15 @@ def xml_element(self, doc): """Create the :class:`xml.dom.minidom.Element` that describes this :class:`_DimensionalMetadata`. - Args: - - * doc: + Parameters + ---------- + doc : The parent :class:`xml.dom.minidom.Document`. - Returns: - The :class:`xml.dom.minidom.Element` that will describe this + Returns + ------- + :class:`xml.dom.minidom.Element` + :class:`xml.dom.minidom.Element` that will describe this :class:`_DimensionalMetadata`. """ @@ -929,23 +932,20 @@ def __init__( ): """Constructs a single ancillary variable. - Args: - - * data: + Parameters + ---------- + data : The values of the ancillary variable. - - Kwargs: - - * standard_name: + standard_name : optional, default=None CF standard name of the ancillary variable. - * long_name: + long_name : optional, default=None Descriptive name of the ancillary variable. - * var_name: + var_name : optional, default=None The netCDF variable name for the ancillary variable. - * units + units : optional, default=None The :class:`~cf_units.Unit` of the ancillary variable's values. Can be a string, which will be converted to a Unit object. - * attributes + attributes : optional, default=None A dictionary containing other cf and user-defined attributes. """ @@ -980,8 +980,9 @@ def lazy_data(self): If the data have already been loaded for the ancillary variable, the returned Array will be a new lazy array wrapper. - Returns: - A lazy array, representing the ancillary variable data array. + Returns + ------- + A lazy array, representing the ancillary variable data array. """ return super()._lazy_values() @@ -1028,27 +1029,24 @@ def __init__( ): """Constructs a single cell measure. - Args: - - * data: + Parameters + ---------- + data : The values of the measure for each cell. Either a 'real' array (:class:`numpy.ndarray`) or a 'lazy' array (:class:`dask.array.Array`). - - Kwargs: - - * standard_name: + standard_name : optional, default=None CF standard name of the coordinate. - * long_name: + long_name : optional, default=None Descriptive name of the coordinate. - * var_name: + var_name : optional, default=None The netCDF variable name for the coordinate. - * units + units : optional, default=None The :class:`~cf_units.Unit` of the coordinate's values. Can be a string, which will be converted to a Unit object. - * attributes + attributes : optional, default=None A dictionary containing other CF and user-defined attributes. - * measure + measure : optional A string describing the type of measure. Supported values are 'area' and 'volume'. The default is 'area'. @@ -1094,12 +1092,14 @@ def xml_element(self, doc): """Create the :class:`xml.dom.minidom.Element` that describes this :class:`CellMeasure`. - Args: - - * doc: + Parameters + ---------- + doc : The parent :class:`xml.dom.minidom.Document`. - Returns: + Returns + ------- + :class:`xml.dom.minidom.Element` The :class:`xml.dom.minidom.Element` that describes this :class:`CellMeasure`. @@ -1139,25 +1139,19 @@ def __new__( """Create a CoordExtent for the specified coordinate and range of values. - Args: - - * name_or_coord + Parameters + ---------- + name_or_coord : Either a coordinate name or a coordinate, as defined in :meth:`iris.cube.Cube.coords()`. - - * minimum + minimum : The minimum value of the range to select. - - * maximum + maximum : The maximum value of the range to select. - - Kwargs: - - * min_inclusive + min_inclusive : optional If True, coordinate values equal to `minimum` will be included in the selection. Default is True. - - * max_inclusive + max_inclusive : optional If True, coordinate values equal to `maximum` will be included in the selection. Default is True. @@ -1193,12 +1187,14 @@ def _get_2d_coord_bound_grid(bounds): # 0-0-0-0-1 # 3-3-3-3-2 - Args: - * bounds: (array) + Parameters + ---------- + bounds : array Coordinate bounds array of shape (Y, X, 4) - Returns: - * grid: (array) + Returns + ------- + array Grid of shape (Y+1, X+1) """ @@ -1471,26 +1467,25 @@ def __init__( coord_system=None, climatological=False, ): - """Coordinate abstract base class. As of ``v3.0.0`` you **cannot** create an instance of :class:`Coord`. - - Args: + """Coordinate abstract base class. + + As of ``v3.0.0`` you **cannot** create an instance of :class:`Coord`. - * points: + Parameters + ---------- + points : The values (or value in the case of a scalar coordinate) for each cell of the coordinate. - - Kwargs: - - * standard_name: + standard_name : optional, default=None CF standard name of the coordinate. - * long_name: + long_name : optional, default=None Descriptive name of the coordinate. - * var_name: + var_name : optional, default=None The netCDF variable name for the coordinate. - * units + units : optional, default=None The :class:`~cf_units.Unit` of the coordinate's values. Can be a string, which will be converted to a Unit object. - * bounds + bounds : optional, default=None An array of values describing the bounds of each cell. Given n bounds for each cell, the shape of the bounds array should be points.shape + (n,). For example, a 1D coordinate with 100 points @@ -1498,13 +1493,13 @@ def __init__( (100, 2) Note if the data is a climatology, `climatological` should be set. - * attributes + attributes : optional, default=None A dictionary containing other CF and user-defined attributes. - * coord_system + coord_system : optional, default=None A :class:`~iris.coord_systems.CoordSystem` representing the coordinate system of the coordinate, e.g., a :class:`~iris.coord_systems.GeogCS` for a longitude coordinate. - * climatological (bool): + climatological : bool, optional, default=False When True: the coordinate is a NetCDF climatological time axis. When True: saving in NetCDF will give the coordinate variable a 'climatology' attribute and will create a boundary variable called @@ -1541,18 +1536,19 @@ def __init__( def copy(self, points=None, bounds=None): """Returns a copy of this coordinate. - Kwargs: - - * points: A points array for the new coordinate. - This may be a different shape to the points of the coordinate - being copied. - - * bounds: A bounds array for the new coordinate. - Given n bounds for each cell, the shape of the bounds array - should be points.shape + (n,). For example, a 1d coordinate - with 100 points and two bounds per cell would have a bounds - array of shape (100, 2). - + points : + A points array for the new coordinate. + This may be a different shape to the points of the coordinate + being copied. + bounds : + A bounds array for the new coordinate. + Given n bounds for each cell, the shape of the bounds array + should be points.shape + (n,). For example, a 1d coordinate + with 100 points and two bounds per cell would have a bounds + array of shape (100, 2). + + Notes + ----- .. note:: If the points argument is specified and bounds are not, the resulting coordinate will have no bounds. @@ -1709,8 +1705,9 @@ def lazy_points(self): If the data have already been loaded for the coord, the returned Array will be a new lazy array wrapper. - Returns: - A lazy array, representing the coord points array. + Returns + ------- + A lazy array, representing the coord points array. """ return super()._lazy_values() @@ -1725,7 +1722,9 @@ def lazy_bounds(self): If the data have already been loaded for the coord, the returned Array will be a new lazy array wrapper. - Returns: + Returns + ------- + lazy array A lazy array representing the coord bounds array or `None` if the coord does not have bounds. @@ -1860,18 +1859,18 @@ def _sanity_check_bounds(self): def _discontiguity_in_bounds(self, rtol=1e-5, atol=1e-8): """Checks that the bounds of the coordinate are contiguous. - Kwargs: - * rtol: (float) + rtol : float, optional Relative tolerance that is used when checking contiguity. Defaults to 1e-5. - * atol: (float) + atol : float, optional Absolute tolerance that is used when checking contiguity. Defaults to 1e-8. - Returns: - * contiguous: (boolean) + Returns + ------- + contiguous : bool True if there are no discontiguities. - * diffs: (array or tuple of arrays) + diffs : array or tuple of arrays A boolean array or tuple of boolean arrays which are true where there are discontiguities between neighbouring bounds. If self is a 2D coord of shape (Y, X), a pair of arrays is returned, where @@ -1959,15 +1958,16 @@ def is_contiguous(self, rtol=1e-05, atol=1e-08): it, and the upper left corner of each cell aligns with the lower left corner of the cell above it. - Args: - - * rtol: + Parameters + ---------- + rtol : optional The relative tolerance parameter (default is 1e-05). - * atol: + atol : optional The absolute tolerance parameter (default is 1e-08). - Returns: - Boolean. + Returns + ------- + bool """ if self.has_bounds(): @@ -2048,19 +2048,20 @@ def is_compatible(self, other, ignore=None): :attr:`iris.coords.Coord.coord_system` and :attr:`iris.coords.Coord.attributes` that are present in both objects. - Args: - - * other: + Parameters + ---------- + other : An instance of :class:`iris.coords.Coord`, :class:`iris.common.CoordMetadata` or :class:`iris.common.DimCoordMetadata`. - * ignore: + ignore : optional A single attribute key or iterable of attribute keys to ignore when comparing the coordinates. Default is None. To ignore all attributes, set this to other.attributes. - Returns: - Boolean. + Returns + ------- + bool """ compatible = False @@ -2216,15 +2217,18 @@ def serialize(x): def _guess_bounds(self, bound_position=0.5): """Return bounds for this coordinate based on its points. - Kwargs: - - * bound_position: + Parameters + ---------- + bound_position : optional, default=0.5 The desired position of the bounds relative to the position of the points. - Returns: - A numpy array of shape (len(self.points), 2). + Returns + ------- + A numpy array of shape (len(self.points), 2). + Notes + ----- .. note:: This method only works for coordinates with ``coord.ndim == 1``. @@ -2285,12 +2289,14 @@ def guess_bounds(self, bound_position=0.5): With irregular points, the first and last cells are given the same widths as the ones next to them. - Kwargs: - - * bound_position: + Parameters + ---------- + bound_position : optional, default=0.5 The desired position of the bounds relative to the position of the points. + Notes + ----- .. note:: An error is raised if the coordinate already has bounds, is not @@ -2311,9 +2317,9 @@ def intersect(self, other, return_indices=False): Both coordinates must be compatible as defined by :meth:`~iris.coords.Coord.is_compatible`. - Kwargs: - - * return_indices: + Parameters + ---------- + return_indices : optional, default=False If True, changes the return behaviour to return the intersection indices for the "self" coordinate. @@ -2449,12 +2455,14 @@ def xml_element(self, doc): """Create the :class:`xml.dom.minidom.Element` that describes this :class:`Coord`. - Args: - - * doc: + Parameters + ---------- + doc : The parent :class:`xml.dom.minidom.Document`. - Returns: + Returns + ------- + :class:`xml.dom.minidom.Element` The :class:`xml.dom.minidom.Element` that will describe this :class:`DimCoord`. @@ -2480,7 +2488,9 @@ def _xml_id_extra(self, unique_value): class DimCoord(Coord): - """A coordinate that is 1D, and numeric, with values that have a strict monotonic ordering. Missing values are not + """A coordinate that is 1D, and numeric. + + With values that have a strict monotonic ordering. Missing values are not permitted in a :class:`DimCoord`. """ @@ -2507,18 +2517,15 @@ def from_regular( The majority of the arguments are defined as for :class:`Coord`, but those which differ are defined below. - Args: - - * zeroth: + Parameters + ---------- + zeroth : The value *prior* to the first point value. - * step: + step : The numeric difference between successive point values. - * count: + count : The number of point values. - - Kwargs: - - * with_bounds: + with_bounds : optional If True, the resulting DimCoord will possess bound values which are equally spaced around the points. Otherwise no bounds values will be defined. Defaults to False. @@ -2566,25 +2573,22 @@ def __init__( Missing values are not permitted. - Args: - - * points: + Parameters + ---------- + points : 1D numpy array-like of values (or single value in the case of a scalar coordinate) for each cell of the coordinate. The values must be strictly monotonic and masked values are not allowed. - - Kwargs: - - * standard_name: + standard_name : optional, default=None CF standard name of the coordinate. - * long_name: + long_name : optional, default=None Descriptive name of the coordinate. - * var_name: + var_name : optional, default=None The netCDF variable name for the coordinate. - * units: + units : :class:`~cf_units.Unit`, optional, default=None The :class:`~cf_units.Unit` of the coordinate's values. Can be a string, which will be converted to a Unit object. - * bounds: + bounds : optional, default=None An array of values describing the bounds of each cell. Given n bounds and m cells, the shape of the bounds array should be (m, n). For each bound, the values must be strictly monotonic along @@ -2595,16 +2599,16 @@ def __init__( in the same direction. Masked values are not allowed. Note if the data is a climatology, `climatological` should be set. - * attributes: + attributes : optional, default=None A dictionary containing other CF and user-defined attributes. - * coord_system: + coord_system : :class:`~iris.coord_systems.CoordSystem`, optional, default=None A :class:`~iris.coord_systems.CoordSystem` representing the coordinate system of the coordinate, e.g., a :class:`~iris.coord_systems.GeogCS` for a longitude coordinate. - * circular (bool): + circular : bool, optional, default=False Whether the coordinate wraps by the :attr:`~iris.coords.DimCoord.units.modulus` i.e., the longitude coordinate wraps around the full great circle. - * climatological (bool): + climatological : bool, optional, default=False When True: the coordinate is a NetCDF climatological time axis. When True: saving in NetCDF will give the coordinate variable a 'climatology' attribute and will create a boundary variable called @@ -2698,12 +2702,15 @@ def collapsed(self, dims_to_collapse=None): return coord def _new_points_requirements(self, points): - """Confirm that a new set of coord points adheres to the requirements for + """Confirm that a new set of coord points adheres to the requirements. + + Confirm that a new set of coord points adheres to the requirements for :class:`~iris.coords.DimCoord` points, being: - * points are scalar or 1D, - * points are numeric, - * points are not masked, and - * points are monotonic. + + * points are scalar or 1D, + * points are numeric, + * points are not masked, and + * points are monotonic. """ if points.ndim not in (0, 1): @@ -2744,12 +2751,15 @@ def _values(self, points): points.flags.writeable = False def _new_bounds_requirements(self, bounds): - """Confirm that a new set of coord bounds adheres to the requirements for + """Confirm that a new set of coord bounds adheres to the requirements. + + Confirm that a new set of coord bounds adheres to the requirements for :class:`~iris.coords.DimCoord` bounds, being: - * bounds are compatible in shape with the points - * bounds are numeric, - * bounds are not masked, and - * bounds are monotonic in the first dimension. + + * bounds are compatible in shape with the points + * bounds are numeric, + * bounds are not masked, and + * bounds are monotonic in the first dimension. Also reverse the order of the second dimension if necessary to match the first dimension's direction. I.e. both should increase or both should @@ -2840,12 +2850,14 @@ def xml_element(self, doc): """Create the :class:`xml.dom.minidom.Element` that describes this :class:`DimCoord`. - Args: - - * doc: + Parameters + ---------- + doc : The parent :class:`xml.dom.minidom.Document`. - Returns: + Returns + ------- + :class:`xml.dom.minidom.Element` The :class:`xml.dom.minidom.Element` that describes this :class:`DimCoord`. @@ -2862,24 +2874,21 @@ class AuxCoord(Coord): def __init__(self, *args, **kwargs): """Create a coordinate with **mutable** points and bounds. - Args: - - * points: + Parameters + ---------- + points : The values (or value in the case of a scalar coordinate) for each cell of the coordinate. - - Kwargs: - - * standard_name: + standard_name : optional CF standard name of the coordinate. - * long_name: + long_name : optional Descriptive name of the coordinate. - * var_name: + var_name : optional The netCDF variable name for the coordinate. - * units + unit : :class:`~cf_units.Unit`, optional The :class:`~cf_units.Unit` of the coordinate's values. Can be a string, which will be converted to a Unit object. - * bounds + bounds : optional An array of values describing the bounds of each cell. Given n bounds for each cell, the shape of the bounds array should be points.shape + (n,). For example, a 1D coordinate with 100 points @@ -2887,13 +2896,13 @@ def __init__(self, *args, **kwargs): (100, 2) Note if the data is a climatology, `climatological` should be set. - * attributes + attributes : optional A dictionary containing other CF and user-defined attributes. - * coord_system + coord_system : :class:`~iris.coord_systems.CoordSystem`, optional A :class:`~iris.coord_systems.CoordSystem` representing the coordinate system of the coordinate, e.g., a :class:`~iris.coord_systems.GeogCS` for a longitude coordinate. - * climatological (bool): + climatological bool, optional When True: the coordinate is a NetCDF climatological time axis. When True: saving in NetCDF will give the coordinate variable a 'climatology' attribute and will create a boundary variable called @@ -2936,22 +2945,17 @@ class CellMethod(iris.util._OrderedHashable): def __init__(self, method, coords=None, intervals=None, comments=None): """Call Method initialise. - Args: - - * method: + Parameters + ---------- + method : The name of the operation. - - Kwargs: - - * coords: + coords : :class:`.Coord` instances, optional A single instance or sequence of :class:`.Coord` instances or coordinate names. - - * intervals: + intervals : optional A single string, or a sequence strings, describing the intervals within the cell method. - - * comments: + comments : optional A single string, or a sequence strings, containing any additional comments. @@ -3023,12 +3027,14 @@ def xml_element(self, doc): """Create the :class:`xml.dom.minidom.Element` that describes this :class:`CellMethod`. - Args: - - * doc: + Parameters + ---------- + doc : The parent :class:`xml.dom.minidom.Document`. - Returns: + Returns + ------- + :class:`xml.dom.minidom.Element` The :class:`xml.dom.minidom.Element` that describes this :class:`CellMethod`. diff --git a/lib/iris/cube.py b/lib/iris/cube.py index de590ef29a..9944a9a912 100644 --- a/lib/iris/cube.py +++ b/lib/iris/cube.py @@ -80,9 +80,9 @@ def merged(self, unique=False): """Returns a new :class:`_CubeFilter` by merging the list of cubes. - Kwargs: - - * unique: + Parameters + ---------- + unique : bool, optional, default=False If True, raises `iris.exceptions.DuplicateDataError` if duplicate cubes are detected. @@ -131,9 +131,9 @@ def merged(self, unique=False): """Returns a new :class:`_CubeFilterCollection` by merging all the cube lists of this collection. - Kwargs: - - * unique: + Parameters + ---------- + unique : bool, optional, default=False If True, raises `iris.exceptions.DuplicateDataError` if duplicate cubes are detected. @@ -227,10 +227,11 @@ def append(self, cube): def extend(self, other_cubes): """Extend cubelist by appending the cubes contained in other_cubes. - Args: - - * other_cubes: + Parameters + ---------- + other_cubes : A cubelist or other sequence of cubes. + """ super(CubeList, self).extend(CubeList(other_cubes)) @@ -268,9 +269,9 @@ def extract(self, constraints): **n** when filtered with **m** constraints can generate a maximum of **m * n** cubes. - Args: - - * constraints (:class:`~iris.Constraint` or iterable of constraints): + Parameters + ---------- + constraints : :class:`~iris.Constraint` or iterable of constraints A single constraint or an iterable. """ @@ -280,13 +281,14 @@ def extract_cube(self, constraint): """Extract a single cube from a CubeList, and return it. Raise an error if the extract produces no cubes, or more than one. - Args: - - * constraint (:class:`~iris.Constraint`): + Parameters + ---------- + constraint : :class:`~iris.Constraint` The constraint to extract with. - .. see also:: - :meth:`~iris.cube.CubeList.extract` + See Also + -------- + :meth:`~iris.cube.CubeList.extract` """ # Just validate this, so we can accept strings etc, but not multiples. @@ -300,13 +302,14 @@ def extract_cubes(self, constraints): Each constraint must produce exactly one cube, otherwise an error is raised. - Args: - - * constraints (iterable of, or single, :class:`~iris.Constraint`): + Parameters + ---------- + constraints : iter of, or single, :class:`~iris.Constraint` The constraints to extract with. - .. see also:: - :meth:`~iris.cube.CubeList.extract` + See Also + -------- + :meth:`~iris.cube.CubeList.extract` """ return self._extract_and_merge( @@ -355,9 +358,9 @@ def extract_overlapping(self, coord_names): where the coordinates overlap, for the coordinates in coord_names. - Args: - - * 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. @@ -417,12 +420,14 @@ def merge(self, unique=True): """Returns the :class:`CubeList` resulting from merging this :class:`CubeList`. - Kwargs: - - * unique: + Parameters + ---------- + unique : bool, optional, 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. @@ -436,7 +441,7 @@ def merge(self, unique=True): c2 = c1.copy() c2.coord('y_vals').points = [200] - For example:: + :: >>> print(c1) some_parameter / (unknown) (x_vals: 3) @@ -522,25 +527,22 @@ def concatenate_cube( `Cube`, a :class:`~iris.exceptions.ConcatenateError` will be raised describing the reason for the failure. - Kwargs: - - * check_aux_coords + Parameters + ---------- + check_aux_coords : bool, optional, 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 + check_cell_measures : bool, optional, 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 + check_ancils : bool, optional, 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 + check_derived_coords : bool, optional, 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 @@ -549,6 +551,8 @@ def concatenate_cube( 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. @@ -596,25 +600,22 @@ def concatenate( ): """Concatenate the cubes over their common dimensions. - Kwargs: - - * check_aux_coords + Parameters + ---------- + check_aux_coords : bool, optional, 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 + check_cell_measures : bool, optional, 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 + check_ancils : bool, optional, 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 + check_derived_coords : bool, optional, 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 @@ -623,10 +624,14 @@ def concatenate( coordinates used to derive the coordinates can be ignored with `check_aux_coords`. Defaults to True. - Returns: + Returns + ------- + :class:`iris.cube.CubeList` A new :class:`iris.cube.CubeList` of concatenated :class:`iris.cube.Cube` instances. + Notes + ----- This combines cubes with a common dimension coordinate, but occupying different regions of the coordinate value. The cubes are joined across that dimension. @@ -1132,12 +1137,13 @@ def _sort_xml_attrs(cls, doc): This is a private utility method required by iris to maintain legacy xml behaviour beyond python 3.7. - Args: - - * doc: - The :class:`xml.dom.minidom.Document`. + Parameters + ---------- + doc : :class:`xml.dom.minidom.Document`. - Returns: + Returns + ------- + :class:`xml.dom.minidom.Document` The :class:`xml.dom.minidom.Document` with sorted element attributes. @@ -1196,9 +1202,9 @@ def __init__( Not typically used - normally cubes are obtained by loading data (e.g. :func:`iris.load`) or from manipulating existing cubes. - Args: - - * data + Parameters + ---------- + data : This object defines the shape of the cube and the phenomenon value in each cell. @@ -1208,39 +1214,39 @@ def __init__( array_like (as described in :func:`numpy.asarray`). See :attr:`Cube.data`. - - Kwargs: - - * standard_name + standard_name : optional, default=None The standard name for the Cube's data. - * long_name + long_name : optional, default=None An unconstrained description of the cube. - * var_name + var_name : optional, default=None The NetCDF variable name for the cube. - * units + units : optional, default=None The unit of the cube, e.g. ``"m s-1"`` or ``"kelvin"``. - * attributes + attributes : optional, default=None A dictionary of cube attributes - * cell_methods + cell_methods : optional, default=None A tuple of CellMethod objects, generally set by Iris, e.g. ``(CellMethod("mean", coords='latitude'), )``. - * dim_coords_and_dims + dim_coords_and_dims : optional, default=None A list of coordinates with scalar dimension mappings, e.g ``[(lat_coord, 0), (lon_coord, 1)]``. - * aux_coords_and_dims + aux_coords_and_dims : optional, default=None A list of coordinates with dimension mappings, e.g ``[(lat_coord, 0), (lon_coord, (0, 1))]``. See also :meth:`Cube.add_dim_coord()` and :meth:`Cube.add_aux_coord()`. - * aux_factories + aux_factories : optional, default=None A list of auxiliary coordinate factories. See :mod:`iris.aux_factory`. - * cell_measures_and_dims + cell_measures_and_dims : optional, default=None A list of CellMeasures with dimension mappings. - * ancillary_variables_and_dims + ancillary_variables_and_dims : optional, default=None A list of AncillaryVariables with dimension mappings. - For example:: + Examples + -------- + :: + >>> from iris.coords import DimCoord >>> from iris.cube import Cube >>> latitude = DimCoord(np.linspace(-90, 90, 4), @@ -1379,19 +1385,22 @@ def is_compatible(self, other, ignore=None): :attr:`iris.cube.Cube.units`, :attr:`iris.cube.Cube.cell_methods` and :attr:`iris.cube.Cube.attributes` that are present in both objects. - Args: - - * other: + Parameters + ---------- + other : An instance of :class:`iris.cube.Cube` or :class:`iris.cube.CubeMetadata`. - * ignore: + ignore : optional, default=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. - Returns: - Boolean. + Returns + ------- + bool + Notes + ----- .. seealso:: :meth:`iris.util.describe_diff()` @@ -1467,22 +1476,24 @@ def add_cell_method(self, cell_method): def add_aux_coord(self, coord, data_dims=None): """Adds a CF auxiliary coordinate to the cube. - Args: - - * coord + Parameters + ---------- + coord : The :class:`iris.coords.DimCoord` or :class:`iris.coords.AuxCoord` instance to add to the cube. - - Kwargs: - - * data_dims + data_dims : optional, default=None Integer or iterable of integers giving the data dimensions spanned by the coordinate. - Raises a ValueError if a coordinate with identical metadata already - exists on the cube. + Raises + ------ + ValueError + Raises a ValueError if a coordinate with identical metadata already + exists on the cube. - See also :meth:`Cube.remove_coord()`. + See Also + -------- + :meth:`Cube.remove_coord()`. """ if self.coords(coord): # TODO: just fail on duplicate object @@ -1574,9 +1585,9 @@ def _add_unique_aux_coord(self, coord, data_dims): def add_aux_factory(self, aux_factory): """Adds an auxiliary coordinate factory to the cube. - Args: - - * aux_factory + Parameters + ---------- + aux_factory : The :class:`iris.aux_factory.AuxCoordFactory` instance to add. """ @@ -1606,20 +1617,20 @@ def coordsonly(coords_and_dims): def add_cell_measure(self, cell_measure, data_dims=None): """Adds a CF cell measure to the cube. - Args: - - * cell_measure + Parameters + ---------- + cell_measure : The :class:`iris.coords.CellMeasure` instance to add to the cube. - - Kwargs: - - * data_dims + data_dims : optional, default=None Integer or iterable of integers giving the data dimensions spanned by the coordinate. - Raises a ValueError if a cell_measure with identical metadata already - exists on the cube. + Raises + ------ + ValueError + Raises a ValueError if a cell_measure with identical metadata already + exists on the cube. See Also -------- @@ -1639,20 +1650,20 @@ def add_cell_measure(self, cell_measure, data_dims=None): def add_ancillary_variable(self, ancillary_variable, data_dims=None): """Adds a CF ancillary variable to the cube. - Args: - - * ancillary_variable + Parameters + ---------- + ancillary_variable : The :class:`iris.coords.AncillaryVariable` instance to be added to the cube - - Kwargs: - - * data_dims + data_dims : optional, default=None Integer or iterable of integers giving the data dimensions spanned by the ancillary variable. - Raises a ValueError if an ancillary variable with identical metadata - already exists on the cube. + Raises + ------ + ValueError + Raises a ValueError if an ancillary variable with identical metadata + already exists on the cube. """ if self.ancillary_variables(ancillary_variable): @@ -1669,17 +1680,22 @@ def add_ancillary_variable(self, ancillary_variable, data_dims=None): def add_dim_coord(self, dim_coord, data_dim): """Add a CF coordinate to the cube. - Args: - - * dim_coord + Parameters + ---------- + dim_coord : :class:`iris.coords.DimCoord` The :class:`iris.coords.DimCoord` instance to add to the cube. - * data_dim + data_dim : Integer giving the data dimension spanned by the coordinate. - Raises a ValueError if a coordinate with identical metadata already - exists on the cube or if a coord already exists for the - given dimension. + 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 + -------- See also :meth:`Cube.remove_coord()`. """ @@ -1753,13 +1769,15 @@ def _remove_coord(self, coord): def remove_coord(self, coord): """Removes a coordinate from the cube. - Args: - - * coord (string or coord) + Parameters + ---------- + coord : str or coord The (name of the) coordinate to remove from the cube. - See also :meth:`Cube.add_dim_coord()` - and :meth:`Cube.add_aux_coord()`. + See Also + -------- + :meth:`Cube.add_dim_coord()` + :meth:`Cube.add_aux_coord()` """ coord = self.coord(coord) @@ -1771,28 +1789,30 @@ def remove_coord(self, coord): def remove_cell_measure(self, cell_measure): """Removes a cell measure from the cube. - Args: - - * cell_measure (string or cell_measure) + Parameters + ---------- + cell_measure : str or cell_measure The (name of the) cell measure to remove from the cube. As either - (a) a :attr:`standard_name`, :attr:`long_name`, or - :attr:`var_name`. Defaults to value of `default` - (which itself defaults to `unknown`) as defined in - :class:`iris.common.CFVariableMixin`. + * (a) a :attr:`standard_name`, :attr:`long_name`, or + :attr:`var_name`. Defaults to value of `default` + (which itself defaults to `unknown`) as defined in + :class:`iris.common.CFVariableMixin`. - (b) a cell_measure instance with metadata equal to that of - the desired cell_measures. + * (b) a cell_measure instance with metadata equal to that of + the desired cell_measures. + Notes + ----- .. note:: If the argument given does not represent a valid cell_measure on the cube, an :class:`iris.exceptions.CellMeasureNotFoundError` is raised. - .. seealso:: - - :meth:`Cube.add_cell_measure()` + See Also + -------- + :meth:`Cube.add_cell_measure()` """ cell_measure = self.cell_measure(cell_measure) @@ -1806,9 +1826,9 @@ def remove_cell_measure(self, cell_measure): def remove_ancillary_variable(self, ancillary_variable): """Removes an ancillary variable from the cube. - Args: - - * ancillary_variable (string or AncillaryVariable) + Parameters + ---------- + ancillary_variable : str or AncillaryVariable The (name of the) AncillaryVariable to remove from the cube. """ @@ -1843,9 +1863,9 @@ def coord_dims(self, coord): instance need not exist on the cube, and may contain different coordinate values. - Args: - - * coord (string or coord) + Parameters + ---------- + coord : str or coord The (name of the) coord to look for. """ @@ -1899,7 +1919,9 @@ def cell_measure_dims(self, cell_measure): """Returns a tuple of the data dimensions relevant to the given CellMeasure. - * cell_measure (string or CellMeasure) + Parameters + ---------- + cell_measure : str or CellMeasure The (name of the) cell measure to look for. """ @@ -1920,7 +1942,9 @@ def ancillary_variable_dims(self, ancillary_variable): """Returns a tuple of the data dimensions relevant to the given AncillaryVariable. - * ancillary_variable (string or AncillaryVariable) + Parameters + ---------- + ancillary_variable : str or AncillaryVariable The (name of the) AncillaryVariable to look for. """ @@ -1945,20 +1969,22 @@ def aux_factory(self, name=None, standard_name=None, long_name=None, var_name=No """Returns the single coordinate factory that matches the criteria, or raises an error if not found. - Kwargs: - - * name + Parameters + ---------- + name : optional, default=None If not None, matches against factory.name(). - * standard_name + standard_name : optional, default=None The CF standard name of the desired coordinate factory. If None, does not check for standard name. - * long_name + long_name : optional, default=None An unconstrained description of the coordinate factory. If None, does not check for long_name. - * var_name + var_name : optional, default=None 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 @@ -2020,13 +2046,9 @@ def coords( r"""Return a list of coordinates from the :class:`Cube` that match the provided criteria. - .. seealso:: - - :meth:`Cube.coord` for matching exactly one coordinate. - - Kwargs: - - * name_or_coord: + Parameters + ---------- + name_or_coord : optional, default=None Either, * a :attr:`~iris.common.mixin.CFVariableMixin.standard_name`, @@ -2037,58 +2059,53 @@ def coords( * a coordinate or metadata instance equal to that of the desired coordinate e.g., :class:`~iris.coords.DimCoord` or :class:`~iris.common.metadata.CoordMetadata`. - - * standard_name: + standard_name : optional, default=None The CF standard name of the desired coordinate. If ``None``, does not check for ``standard name``. - - * long_name: + long_name : optional, default=None An unconstrained description of the coordinate. If ``None``, does not check for ``long_name``. - - * var_name: + var_name : optional, default=None The NetCDF variable name of the desired coordinate. If ``None``, does not check for ``var_name``. - - * attributes: + attributes : optional, default=None A dictionary of attributes desired on the coordinates. If ``None``, does not check for ``attributes``. - - * axis: + axis : optional, default=None The desired coordinate axis, see :func:`iris.util.guess_coord_axis`. If ``None``, does not check for ``axis``. Accepts the values ``X``, ``Y``, ``Z`` and ``T`` (case-insensitive). - - * contains_dimension: + contains_dimension : optional, default=None The desired coordinate contains the data dimension. If ``None``, does not check for the dimension. - - * dimensions: + dimensions : optional, default=None 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: + coord_system : optional, default=None Whether the desired coordinates have a coordinate system equal to the given coordinate system. If ``None``, no check is done. - - * dim_coords: + dim_coords : optional, default=None 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: + mesh_coords : optional, default=None Set to ``True`` to return only coordinates which are - :class:`~iris.experimental.ugrid.MeshCoord`\\ s. + :class:`~iris.experimental.ugrid.MeshCoord`\'s. Set to ``False`` to return only non-mesh coordinates. If ``None``, returns all coordinates. - Returns: - A list containing zero or more coordinates matching the provided - criteria. + Returns + ------- + A list containing zero or more coordinates matching the provided criteria. + + See Also + -------- + :meth:`Cube.coord` for matching exactly one coordinate. + """ coords_and_factories = [] @@ -2186,18 +2203,9 @@ def coord( r"""Return a single coordinate from the :class:`Cube` that matches the provided criteria. - .. note:: - - If the arguments given do not result in **precisely one** coordinate, - then a :class:`~iris.exceptions.CoordinateNotFoundError` is raised. - - .. seealso:: - - :meth:`Cube.coords` for matching zero or more coordinates. - - Kwargs: - - * name_or_coord: + Parameters + ---------- + name_or_coord : optional, default=None Either, * a :attr:`~iris.common.mixin.CFVariableMixin.standard_name`, @@ -2208,57 +2216,58 @@ def coord( * a coordinate or metadata instance equal to that of the desired coordinate e.g., :class:`~iris.coords.DimCoord` or :class:`~iris.common.metadata.CoordMetadata`. - - * standard_name: + standard_name : optional, default=None The CF standard name of the desired coordinate. If ``None``, does not check for ``standard name``. - - * long_name: + long_name : optional, default=None An unconstrained description of the coordinate. If ``None``, does not check for ``long_name``. - - * var_name: + var_name : optional, default=None The NetCDF variable name of the desired coordinate. If ``None``, does not check for ``var_name``. - - * attributes: + attributes : optional, default=None A dictionary of attributes desired on the coordinates. If ``None``, does not check for ``attributes``. - - * axis: + axis : optional, default=None The desired coordinate axis, see :func:`iris.util.guess_coord_axis`. If ``None``, does not check for ``axis``. Accepts the values ``X``, ``Y``, ``Z`` and ``T`` (case-insensitive). - - * contains_dimension: + contains_dimension : optional, default=None The desired coordinate contains the data dimension. If ``None``, does not check for the dimension. - - * dimensions: + dimensions : optional, default=None 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: + coord_system : optional, default=None Whether the desired coordinates have a coordinate system equal to the given coordinate system. If ``None``, no check is done. - - * dim_coords: + dim_coords : optional, default=None 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: + mesh_coords : optional, default=None Set to ``True`` to return only coordinates which are - :class:`~iris.experimental.ugrid.MeshCoord`\\ s. + :class:`~iris.experimental.ugrid.MeshCoord`\'s. Set to ``False`` to return only non-mesh coordinates. If ``None``, returns all coordinates. - Returns: - The coordinate that matches the provided criteria. + Returns + ------- + The coordinate that matches the provided criteria. + + Notes + ----- + .. note:: + + If the arguments given do not result in **precisely one** coordinate, + then a :class:`~iris.exceptions.CoordinateNotFoundError` is raised. + See Also + -------- + :meth:`Cube.coords` for matching zero or more coordinates. """ coords = self.coords( name_or_coord=name_or_coord, @@ -2305,9 +2314,9 @@ def coord_system(self, spec=None): If no target coordinate system is provided then find any available coordinate system. - Kwargs: - - * spec: + Parameters + ---------- + spec : optional, default=None The the name or type of a coordinate system subclass. E.g. :: @@ -2320,8 +2329,9 @@ def coord_system(self, spec=None): If spec is None, then find any available coordinate systems within the :class:`iris.cube.Cube`. - Returns: - The :class:`iris.coord_systems.CoordSystem` or None. + Returns + ------- + :class:`iris.coord_systems.CoordSystem` or None. """ if isinstance(spec, str) or spec is None: @@ -2416,20 +2426,22 @@ def mesh_dim(self): def cell_measures(self, name_or_cell_measure=None): """Return a list of cell measures in this cube fitting the given criteria. - Kwargs: - - * name_or_cell_measure + Parameters + ---------- + name_or_cell_measure : optional, default=None Either - (a) a :attr:`standard_name`, :attr:`long_name`, or - :attr:`var_name`. Defaults to value of `default` - (which itself defaults to `unknown`) as defined in - :class:`iris.common.CFVariableMixin`. + * (a) a :attr:`standard_name`, :attr:`long_name`, or + :attr:`var_name`. Defaults to value of `default` + (which itself defaults to `unknown`) as defined in + :class:`iris.common.CFVariableMixin`. - (b) a cell_measure instance with metadata equal to that of - the desired cell_measures. + * (b) a cell_measure instance with metadata equal to that of + the desired cell_measures. - See also :meth:`Cube.cell_measure()`. + See Also + -------- + :meth:`Cube.cell_measure()`. """ name = None @@ -2454,16 +2466,18 @@ def cell_measure(self, name_or_cell_measure=None): """Return a single cell_measure given the same arguments as :meth:`Cube.cell_measures`. + Notes + ----- .. note:: If the arguments given do not result in precisely 1 cell_measure being matched, an :class:`iris.exceptions.CellMeasureNotFoundError` is raised. - .. seealso:: - - :meth:`Cube.cell_measures()` - for full keyword documentation. + See Also + -------- + :meth:`Cube.cell_measures()` + For full keyword documentation. """ cell_measures = self.cell_measures(name_or_cell_measure) @@ -2501,18 +2515,18 @@ def ancillary_variables(self, name_or_ancillary_variable=None): """Return a list of ancillary variable in this cube fitting the given criteria. - Kwargs: - - * name_or_ancillary_variable + Parameters + ---------- + name_or_ancillary_variable : optional, default=None Either - (a) a :attr:`standard_name`, :attr:`long_name`, or - :attr:`var_name`. Defaults to value of `default` - (which itself defaults to `unknown`) as defined in - :class:`iris.common.CFVariableMixin`. + * (a) a :attr:`standard_name`, :attr:`long_name`, or + :attr:`var_name`. Defaults to value of `default` + (which itself defaults to `unknown`) as defined in + :class:`iris.common.CFVariableMixin`. - (b) a ancillary_variable instance with metadata equal to that of - the desired ancillary_variables. + * (b) a ancillary_variable instance with metadata equal to that of + the desired ancillary_variables. See Also -------- @@ -2541,16 +2555,18 @@ def ancillary_variable(self, name_or_ancillary_variable=None): """Return a single ancillary_variable given the same arguments as :meth:`Cube.ancillary_variables`. + Notes + ----- .. note:: If the arguments given do not result in precisely 1 ancillary_variable being matched, an :class:`iris.exceptions.AncillaryVariableNotFoundError` is raised. - .. seealso:: - - :meth:`Cube.ancillary_variables()` - for full keyword documentation. + See Also + -------- + :meth:`Cube.ancillary_variables()` + For full keyword documentation. """ ancillary_variables = self.ancillary_variables(name_or_ancillary_variable) @@ -2659,8 +2675,9 @@ def lazy_data(self): does _not_ make the Cube data lazy again; the Cube data remains loaded in memory. - Returns: - A lazy array, representing the Cube data. + Returns + ------- + A lazy array, representing the Cube data. """ return self._data_manager.lazy_data() @@ -2670,6 +2687,8 @@ def data(self): """The :class:`numpy.ndarray` representing the multi-dimensional data of the cube. + Notes + ----- .. note:: Cubes obtained from NetCDF, PP, and FieldsFile files will only @@ -2706,8 +2725,9 @@ def data(self, data): def has_lazy_data(self): """Details whether this :class:`~iris.cube.Cube` has lazy data. - Returns: - Boolean. + Returns + ------- + bool """ return self._data_manager.has_lazy_data() @@ -2774,13 +2794,13 @@ def summary(self, shorten=False, name_padding=35): """String summary of the Cube with name+units, a list of dim coord names versus length and, optionally, a summary of all other components. - Kwargs: - - * shorten (bool): + 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): + name_padding : int Control the *minimum* width of the cube name + units, i.e. the indent of the dimension map section. @@ -2964,8 +2984,7 @@ def subset(self, coord): return result def extract(self, constraint): - """Filter the cube by the given constraint using - :meth:`iris.Constraint.extract` method. + """Filter cube by the given constraint using :meth:`iris.Constraint.extract`. """ # Cast the constraint into a proper constraint if it is not so already @@ -2976,44 +2995,42 @@ def intersection(self, *args, **kwargs): """Return the intersection of the cube with specified coordinate ranges. - Coordinate ranges can be specified as: - - (a) positional arguments: instances of :class:`iris.coords.CoordExtent`, - or equivalent tuples of 3-5 items: - - * coord - Either a :class:`iris.coords.Coord`, or coordinate name - (as defined in :meth:`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. + TREMTEST: check this still reads ok compared to the original. - * max_inclusive - If True, coordinate values equal to `maximum` will be included - in the selection. Default is True. + Coordinate ranges can be specified as: - (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. + * (a) positional arguments: instances of :class:`iris.coords.CoordExtent`, + or equivalent tuples of 3-5 items: - Kwargs: + * (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. - * ignore_bounds: + Parameters + ---------- + coord : + Either a :class:`iris.coords.Coord`, or coordinate name + (as defined in :meth:`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: + 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 @@ -3022,10 +3039,10 @@ def intersection(self, *args, **kwargs): 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.) + Warnings + -------- + Currently this routine only works with "circular" + coordinates (as defined in the previous note.) For example:: @@ -3034,7 +3051,7 @@ def intersection(self, *args, **kwargs): >>> print(cube.coord('longitude').points[::10]) [ 0. 37.49999237 74.99998474 112.49996948 \ 149.99996948 - 187.49995422 224.99993896 262.49993896 299.99993896 \ + 187.49995422 224.99993896 262.49993896 299.99993896 \ 337.49990845] >>> subset = cube.intersection(longitude=(30, 50)) >>> print(subset.coord('longitude').points) @@ -3043,7 +3060,9 @@ def intersection(self, *args, **kwargs): >>> print(subset.coord('longitude').points) [-7.50012207 -3.75012207 0. 3.75 7.5 ] - Returns: + Returns + ------- + :class:`~iris.cube.Cube` A new :class:`~iris.cube.Cube` giving the subset of the cube which intersects with the requested coordinate intervals. @@ -3366,32 +3385,41 @@ def _as_list_of_coords(self, names_or_coords): return coords def slices_over(self, ref_to_slice): - """Return an iterator of all subcubes along a given coordinate or - dimension index, or multiple of these. + """Return an iterator of all subcubes. - Args: + Return an iterator of all subcubes along a given coordinate or + dimension index, or multiple of these. - * ref_to_slice (string, coord, dimension index or a list 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. - Returns: - An iterator of subcubes. + Returns + ------- + An iterator of subcubes. + Examples + -------- For example, to get all subcubes along the time dimension:: for sub_cube in cube.slices_over('time'): print(sub_cube) - .. seealso:: :meth:`iris.cube.Cube.slices`. - + 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 + -------- + :meth:`iris.cube.Cube.slices`. + """ # Required to handle a mix between types. if _is_single_item(ref_to_slice): @@ -3424,31 +3452,34 @@ def slices(self, ref_to_slice, ordered=True): """Return an iterator of all subcubes given the coordinates or dimension indices desired to be present in each subcube. - Args: - - * ref_to_slice (string, coord, dimension index or a list of these): + 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). - - Kwargs: - - * ordered: if True, the order which the coords to slice or data_dims + ordered : bool, optional + if True, the order which the coords to slice or data_dims are given will be the order in which they represent the data in the resulting cube slices. If False, the order will follow that of the source cube. Default is True. - Returns: - An iterator of subcubes. + Returns + ------- + An iterator of subcubes. + Examples + -------- For example, to get all 2d longitude/latitude subcubes from a multi-dimensional cube:: for sub_cube in cube.slices(['longitude', 'latitude']): print(sub_cube) - .. seealso:: :meth:`iris.cube.Cube.slices_over`. + See Also + -------- + :meth:`iris.cube.Cube.slices_over`. """ if not isinstance(ordered, bool): @@ -3505,13 +3536,19 @@ def slices(self, ref_to_slice, ordered=True): def transpose(self, new_order=None): """Re-order the data dimensions of the cube in-place. - new_order - list of ints, optional - By default, reverse the dimensions, otherwise permute the - axes according to the values given. + 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. - Example usage:: + Examples + -------- + :: # put the second dimension first, followed by the third dimension, # and finally put the first dimension third:: @@ -3736,13 +3773,14 @@ def _order(array): def copy(self, data=None): """Returns a deep copy of this cube. - Kwargs: - - * data: + Parameters + ---------- + data : optional, default=None Replace the data of the cube copy with provided data payload. - Returns: - A copy instance of the :class:`Cube`. + Returns + ------- + A copy instance of the :class:`Cube`. """ memo = {} @@ -3929,25 +3967,22 @@ def collapsed(self, coords, aggregator, **kwargs): it will be used wherever possible when this cube's data is itself a deferred array. - Args: - - * coords (string, coord or a list of strings/coords): + Parameters + ---------- + coords : str, coord or a list of strings/coords Coordinate names/coordinates over which the cube should be collapsed. - - * aggregator (:class:`iris.analysis.Aggregator`): + aggregator : :class:`iris.analysis.Aggregator` Aggregator to be applied for collapse operation. - - Kwargs: - - * kwargs: + **kwargs : Aggregation function keyword arguments. - Returns: - Collapsed cube. - - For example: + Returns + ------- + Collapsed cube. + Examples + -------- >>> import iris >>> import iris.analysis >>> path = iris.sample_data_path('ostia_monthly.nc') @@ -3971,7 +4006,8 @@ def collapsed(self, coords, aggregator, **kwargs): Conventions 'CF-1.5' STASH m01s00i024 - + Notes + ----- .. note:: Some aggregations are not commutative and hence the order of @@ -4178,15 +4214,12 @@ def aggregated_by(self, coords, aggregator, climatological=False, **kwargs): 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 : optional + Aggregator and aggregation function keyword arguments. Returns ------- - :class:`iris.cube.Cube` - - Other Parameters - ---------------- - kwargs: - Aggregator and aggregation function keyword arguments. + :class:`iris.cube.Cube` Examples -------- @@ -4434,19 +4467,16 @@ def rolling_window(self, coord, aggregator, window, **kwargs): """Perform rolling window aggregation on a cube given a coordinate, an aggregation method and a window size. - Args: - - * coord (string/:class:`iris.coords.Coord`): + Parameters + ---------- + coord : str or :class:`iris.coords.Coord` The coordinate over which to perform the rolling window aggregation. - * aggregator (:class:`iris.analysis.Aggregator`): + aggregator : :class:`iris.analysis.Aggregator` Aggregator to be applied to the data. - * window (int): + window : int Size of window to use. - - Kwargs: - - * kwargs: + **kwargs : optional Aggregator and aggregation function keyword arguments. The weights argument to the aggregator, if any, should be a 1d array, cube, or (names of) :meth:`~iris.cube.Cube.coords`, @@ -4454,15 +4484,18 @@ def rolling_window(self, coord, aggregator, window, **kwargs): :meth:`~iris.cube.Cube.ancillary_variables` with the same length as the chosen window. - Returns: - :class:`iris.cube.Cube`. + Returns + ------- + :class:`iris.cube.Cube`. + Notes + ----- .. note:: This operation does not yet have support for lazy evaluation. - For example: - + Examples + -------- >>> import iris, iris.analysis >>> fname = iris.sample_data_path('GloSea4', 'ensemble_010.pp') >>> air_press = iris.load_cube(fname, 'surface_temperature') @@ -4490,7 +4523,6 @@ def rolling_window(self, coord, aggregator, window, **kwargs): 'Data from Met Office Unified Model' um_version '7.6' - >>> print(air_press.rolling_window('time', iris.analysis.MEAN, 3)) surface_temperature / (K) \ (time: 4; latitude: 145; longitude: 192) @@ -4519,7 +4551,7 @@ def rolling_window(self, coord, aggregator, window, **kwargs): Notice that the forecast_period dimension now represents the 4 possible windows of size 3 from the original cube. - """ # noqa: D214, D410, D411 + """ # noqa: D214, D407, D410, D411 # Update weights kwargs (if necessary) to handle different types of # weights @@ -4641,37 +4673,36 @@ def interpolate(self, sample_points, scheme, collapse_scalar=True): """Interpolate from this :class:`~iris.cube.Cube` to the given sample points using the given interpolation scheme. - Args: - - * sample_points: + 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: + scheme : An instance of the type of interpolation to use to interpolate from this :class:`~iris.cube.Cube` to the given sample points. The interpolation schemes currently available in Iris are: - * :class:`iris.analysis.Linear`, and - * :class:`iris.analysis.Nearest`. - - Kwargs: - - * collapse_scalar: + * :class:`iris.analysis.Linear`, and + * :class:`iris.analysis.Nearest`. + collapse_scalar : bool, optional Whether to collapse the dimension of scalar sample points in the resulting cube. Default is True. - Returns: + Returns + ------- + cube 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. - For example: - + Examples + -------- >>> import datetime >>> import iris >>> path = iris.sample_data_path('uk_hires.pp') @@ -4727,23 +4758,25 @@ def regrid(self, grid, scheme): r"""Regrid this :class:`~iris.cube.Cube` on to the given target `grid` using the given regridding `scheme`. - Args: - - * grid: + Parameters + ---------- + grid : A :class:`~iris.cube.Cube` that defines the target grid. - * scheme: + scheme : An instance of the type of regridding to use to regrid this cube onto the target grid. The regridding schemes in Iris currently include: - * :class:`iris.analysis.Linear`\*, - * :class:`iris.analysis.Nearest`\*, - * :class:`iris.analysis.AreaWeighted`\*, - * :class:`iris.analysis.UnstructuredNearest`, - * :class:`iris.analysis.PointInCell`, + * :class:`iris.analysis.Linear`\*, + * :class:`iris.analysis.Nearest`\*, + * :class:`iris.analysis.AreaWeighted`\*, + * :class:`iris.analysis.UnstructuredNearest`, + * :class:`iris.analysis.PointInCell`, \* Supports lazy regridding. - Returns: + Returns + ------- + :class:`~iris.cube` 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 @@ -4752,6 +4785,8 @@ def regrid(self, grid, scheme): The returned cube will have lazy data if the original cube has lazy data and the regridding scheme supports lazy regridding. + Notes + ----- .. note:: Both the source and target cubes must have a CoordSystem, otherwise diff --git a/lib/iris/experimental/regrid.py b/lib/iris/experimental/regrid.py index b0ebfc5679..aa37d76fe0 100644 --- a/lib/iris/experimental/regrid.py +++ b/lib/iris/experimental/regrid.py @@ -82,18 +82,15 @@ def regrid_area_weighted_rectilinear_src_and_grid(src_cube, grid_cube, mdtol=0): or entirely outside of the horizontal extent of the src_cube will be masked irrespective of the value of mdtol. - Args: - - * src_cube: + Parameters + ---------- + src_cube : :class:`iris.cube.Cube` An instance of :class:`iris.cube.Cube` that supplies the data, metadata and coordinates. - * grid_cube: + grid_cube : :class:`iris.cube.Cube` An instance of :class:`iris.cube.Cube` that supplies the desired horizontal grid definition. - - Kwargs: - - * mdtol: + mdtol : int, optional, default=0 Tolerance of missing data. The value returned in each element of the returned cube's data array will be masked if the fraction of masked data in the overlapping cells of the source cube exceeds mdtol. This @@ -102,8 +99,9 @@ def regrid_area_weighted_rectilinear_src_and_grid(src_cube, grid_cube, mdtol=0): will mean the resulting element will be masked if and only if all the overlapping cells of the source cube are masked. Defaults to 0. - Returns: - A new :class:`iris.cube.Cube` instance. + Returns + ------- + A new :class:`iris.cube.Cube` instance. """ wmsg = ( @@ -165,24 +163,25 @@ def regrid_weighted_curvilinear_to_rectilinear(src_cube, weights, grid_cube): .. warning:: - * All coordinates that span the :data:`src_cube` that don't define - the horizontal curvilinear grid will be ignored. + All coordinates that span the :data:`src_cube` that don't define + the horizontal curvilinear grid will be ignored. - Args: - - * src_cube: + Parameters + ---------- + src_cube : :class:`iris.cube.Cube` A :class:`iris.cube.Cube` instance that defines the source variable grid to be regridded. - * weights (array or None): + weights : array or None A :class:`numpy.ndarray` instance that defines the weights for the source variable grid cells. Must have the same shape as the X and Y coordinates. If weights is None, all-ones will be used. - * grid_cube: + grid_cube : :class:`iris.cube.Cube` A :class:`iris.cube.Cube` instance that defines the target rectilinear grid. - Returns: - A :class:`iris.cube.Cube` instance. + Returns + ------- + A :class:`iris.cube.Cube` instance. """ wmsg = ( @@ -241,15 +240,15 @@ def __init__(self, src_cube, tgt_grid_cube, method, projection=None): """Create a regridder for conversions between the source and target grids. - Args: - - * src_cube: + Parameters + ---------- + src_cube : :class:`~iris.cube.Cube` The :class:`~iris.cube.Cube` providing the source points. - * tgt_grid_cube: + tgt_grid_cube : :class:`~iris.cube.Cube` The :class:`~iris.cube.Cube` providing the target grid. - * method: + method : Either 'linear' or 'nearest'. - * projection: + projection : optional The projection in which the interpolation is performed. If None, a PlateCarree projection is used. Defaults to None. @@ -397,37 +396,39 @@ def _create_cube( All the metadata and coordinates of the result Cube are copied from the source Cube, with two exceptions: - - Grid dimension coordinates are copied from the grid Cube. - - Auxiliary coordinates which span the grid dimensions are - ignored, except where they provide a reference surface for an - :class:`iris.aux_factory.AuxCoordFactory`. - Args: + * Grid dimension coordinates are copied from the grid Cube. + * Auxiliary coordinates which span the grid dimensions are + ignored, except where they provide a reference surface for an + :class:`iris.aux_factory.AuxCoordFactory`. - * data: + Parameters + ---------- + data : The regridded data as an N-dimensional NumPy array. - * src: + src : :class:`~iris.cube.Cube` The source Cube. - * src_xy_dim: + src_xy_dim : The dimension the X and Y coord span within the source Cube. - * src_x_coord: + src_x_coord : The X coordinate (either :class:`iris.coords.AuxCoord` or :class:`iris.coords.DimCoord`). - * src_y_coord: + src_y_coord : The Y coordinate (either :class:`iris.coords.AuxCoord` or :class:`iris.coords.DimCoord`). - * grid_x_coord: + grid_x_coord : The :class:`iris.coords.DimCoord` for the new grid's X coordinate. - * grid_y_coord: + grid_y_coord : The :class:`iris.coords.DimCoord` for the new grid's Y coordinate. - * regrid_callback: + regrid_callback : The routine that will be used to calculate the interpolated values of any reference surfaces. - Returns: - The new, regridded Cube. + Returns + ------- + The new, regridded Cube. """ # Create a result cube with the appropriate metadata @@ -523,12 +524,14 @@ def __call__(self, src_cube): The given cube must be defined with the same grid as the source grid used to create this :class:`UnstructuredProjectedRegridder`. - Args: - - * src_cube: + Parameters + ---------- + src_cube : :class:`~iris.cube.Cube` A :class:`~iris.cube.Cube` to be regridded. - Returns: + Returns + ------- + :class:`~iris.cube.Cube` A cube defined with the horizontal dimensions of the target and the other dimensions from this cube. The data values of this cube will be converted to values on the new grid using @@ -620,9 +623,9 @@ def __init__(self, projection=None): Developers to discuss how to retain it (which could include reversing the deprecation). - Optional Args: - - * projection: `cartopy.crs instance` + Parameters + ---------- + projection : `cartopy.crs instance`, optional The projection that the scipy calculation is performed in. If None is given, a PlateCarree projection is used. Defaults to None. @@ -649,16 +652,18 @@ def regridder(self, src_cube, target_grid): Does not support lazy regridding. - Args: - - * src_cube: + Parameters + ---------- + src_cube : :class:`~iris.cube.Cube` The :class:`~iris.cube.Cube` defining the unstructured source points. - * target_grid: + target_grid : :class:`~iris.cube.Cube` The :class:`~iris.cube.Cube` defining the target grid. - Returns: - A callable with the interface: + Returns + ------- + callable + A callable with the interface:: `callable(cube)` @@ -701,9 +706,9 @@ def __init__(self, projection=None): contact the Iris Developers to discuss how to retain it (which could include reversing the deprecation). - Optional Args: - - * projection: `cartopy.crs instance` + Parameters + ---------- + projection : `cartopy.crs instance`, optional The projection that the scipy calculation is performed in. If None is given, a PlateCarree projection is used. Defaults to None. @@ -731,16 +736,18 @@ def regridder(self, src_cube, target_grid): Does not support lazy regridding. - Args: - - * src_cube: + Parameters + ---------- + src_cube : :class:`~iris.cube.Cube` The :class:`~iris.cube.Cube` defining the unstructured source points. - * target_grid: + target_grid : :class:`~iris.cube.Cube` The :class:`~iris.cube.Cube` defining the target grid. - Returns: - A callable with the interface: + Returns + ------- + callable + A callable with the interface:: `callable(cube)` diff --git a/lib/iris/experimental/regrid_conservative.py b/lib/iris/experimental/regrid_conservative.py index 45ac0505ed..a424038772 100644 --- a/lib/iris/experimental/regrid_conservative.py +++ b/lib/iris/experimental/regrid_conservative.py @@ -60,17 +60,14 @@ def _make_esmpy_field(x_coord, y_coord, ref_name="field", data=None, mask=None): Add a grid mask if provided. Create and return a Field mapped on this Grid, setting data if provided. - Args: - - * x_coord, y_coord (:class:`iris.coords.Coord`): + Parameters + ---------- + x_coord, y_coord : :class:`iris.coords.Coord` One-dimensional coordinates of shape (nx,) and (ny,). Their contiguous bounds define an ESMF.Grid of shape (nx, ny). - - Kwargs: - - * data (:class:`numpy.ndarray`, shape (nx,ny)): + data : :class:`numpy.ndarray`, shape (nx,ny), optional Set the Field data content. - * mask (:class:`numpy.ndarray`, boolean, shape (nx,ny)): + mask : :class:`numpy.ndarray`, boolean, shape (nx,ny), optional Add a mask item to the grid, assigning it 0/1 where mask=False/True. """ @@ -164,19 +161,23 @@ def regrid_conservative_via_esmpy(source_cube, grid_cube): Regrids the data of a source cube onto a new grid defined by a destination cube. - Args: - - * source_cube (:class:`iris.cube.Cube`): + Parameters + ---------- + source_cube : :class:`iris.cube.Cube` Source data. Must have two identifiable horizontal dimension coordinates. - * grid_cube (:class:`iris.cube.Cube`): + grid_cube : :class:`iris.cube.Cube` Define the target horizontal grid: Only the horizontal dimension coordinates are actually used. - Returns: + Returns + ------- + :class:`iris.cube.Cube` A new cube derived from source_cube, regridded onto the specified horizontal grid. + Notes + ----- Any additional coordinates which map onto the horizontal dimensions are removed, while all other metadata is retained. If there are coordinate factories with 2d horizontal reference surfaces, diff --git a/lib/iris/experimental/ugrid/mesh.py b/lib/iris/experimental/ugrid/mesh.py index 14bb313474..6325c41572 100644 --- a/lib/iris/experimental/ugrid/mesh.py +++ b/lib/iris/experimental/ugrid/mesh.py @@ -119,9 +119,9 @@ def __init__( ): """Constructs a single connectivity. - Args: - - * indices (:class:`numpy.ndarray` or :class:`numpy.ma.core.MaskedArray` or :class:`dask.array.Array`): + Parameters + ---------- + indices : :class:`numpy.ndarray` or :class:`numpy.ma.core.MaskedArray` or :class:`dask.array.Array` 2D array giving the topological connection relationship between :attr:`location` elements and :attr:`connected` elements. The :attr:`location_axis` dimension indexes over the @@ -135,34 +135,31 @@ def __init__( elements: use a :class:`numpy.ma.core.MaskedArray` and mask the :attr:`location` elements' unused index 'slots'. Use a :class:`dask.array.Array` to keep indices 'lazy'. - * cf_role (str): + cf_role : str Denotes the topological relationship that this connectivity describes. Made up of this array's :attr:`location`, and the :attr:`connected` element type that is indexed by the array. See :attr:`UGRID_CF_ROLES` for valid arguments. - - Kwargs: - - * standard_name (str): + standard_name : str, optional CF standard name of the connectivity. (NOTE: this is not expected by the UGRID conventions, but will be handled in Iris' standard way if provided). - * long_name (str): + long_name : str, optional Descriptive name of the connectivity. - * var_name (str): + var_name : str, optional The NetCDF variable name for the connectivity. - * units (cf_units.Unit): + units : cf_units.Unit, optional The :class:`~cf_units.Unit` of the connectivity's values. Can be a string, which will be converted to a Unit object. (NOTE: this is not expected by the UGRID conventions, but will be handled in Iris' standard way if provided). - * attributes (dict): + attributes : dict, optional A dictionary containing other cf and user-defined attributes. - * start_index (int): + start_index : int, optional Either ``0`` or ``1``. Default is ``0``. Denotes whether :attr:`indices` uses 0-based or 1-based indexing (allows support for Fortran and legacy NetCDF files). - * location_axis (int): + location_axis : int, optional Either ``0`` or ``1``. Default is ``0``. Denotes which axis of :attr:`indices` varies over the :attr:`location` elements (the alternate axis therefore varying over :attr:`connected` elements). @@ -294,19 +291,23 @@ def indices(self): return self._values def indices_by_location(self, indices=None): - """Return a view of the indices array with :attr:`location_axis` **always** as + """Return a view of the indices array. + + Return a view of the indices array with :attr:`location_axis` **always** as the first axis - transposed if necessary. Can optionally pass in an identically shaped array on which to perform this operation (e.g. the output from :meth:`core_indices` or :meth:`lazy_indices`). - - Kwargs: - - * indices (array): + + Parameters + ---------- + indices : array The array on which to operate. If ``None``, will operate on :attr:`indices`. Default is ``None``. - Returns: - A view of the indices array, transposed - if necessary - to put + Returns + ------- + result : + A view of the indices array Transposed - if necessary - to put :attr:`location_axis` first. """ @@ -438,7 +439,9 @@ def transpose(self): """Create a new :class:`Connectivity`, identical to this one but with the :attr:`indices` array transposed and the :attr:`location_axis` value flipped. - Returns: + Returns + ------- + :class:`Connectivity` A new :class:`Connectivity` that is the transposed equivalent of the original. @@ -466,8 +469,9 @@ def lazy_indices(self): If the :attr:`indices` have already been loaded for the connectivity, the returned Array will be a new lazy array wrapper. - Returns: - A lazy array, representing the connectivity indices array. + Returns + ------- + A lazy array, representing the connectivity indices array. """ return super()._lazy_values() @@ -476,8 +480,9 @@ def core_indices(self): """The indices array at the core of this connectivity, which may be a NumPy array or a Dask array. - Returns: - :class:`numpy.ndarray` or :class:`numpy.ma.core.MaskedArray` or :class:`dask.array.Array` + Returns + ------- + :class:`numpy.ndarray` or :class:`numpy.ma.core.MaskedArray` or :class:`dask.array.Array` """ return super()._core_values() @@ -486,8 +491,9 @@ def has_lazy_indices(self): """Return a boolean indicating whether the connectivity's :attr:`indices` array is a lazy Dask array or not. - Returns: - boolean + Returns + ------- + bool """ return super()._has_lazy_values() @@ -504,9 +510,11 @@ def lazy_location_lengths(self): The returned Array will be lazy regardless of whether the :attr:`indices` have already been loaded. - Returns: + Returns + ------- + lazy array A lazy array, representing the number of :attr:`connected` - elements associated with each :attr:`location` element. + elements associated with each :attr:`location` element. """ location_mask_counts = da.sum( @@ -520,9 +528,11 @@ def location_lengths(self): elements associated with each of the connectivity's :attr:`location` elements, accounting for masks if present. - Returns: + Returns + ------- + NumPy array A NumPy array, representing the number of :attr:`connected` - elements associated with each :attr:`location` element. + elements associated with each :attr:`location` element. """ return self.lazy_location_lengths().compute() @@ -668,14 +678,12 @@ def from_coords(cls, *coords): * ``None`` or ``(n, <2)``: Not supported - * ``(n, 2)``: :attr:`~Mesh.topology_dimension` = ``1``. :attr:`~Mesh.node_coords` and :attr:`~Mesh.edge_node_connectivity` constructed from :attr:`~iris.coords.Coord.bounds`. :attr:`~Mesh.edge_coords` constructed from :attr:`~iris.coords.Coord.points`. - * ``(n, >=3)``: :attr:`~Mesh.topology_dimension` = ``2``. :attr:`~Mesh.node_coords` and :attr:`~Mesh.face_node_connectivity` @@ -683,17 +691,20 @@ def from_coords(cls, *coords): :attr:`~Mesh.face_coords` constructed from :attr:`~iris.coords.Coord.points`. - Args: - - * \\*coords (Iterable of :class:`~iris.coords.Coord`): + Parameters + ---------- + *coords : Iterable of :class:`~iris.coords.Coord` Coordinates to pass into the :class:`Mesh`. All :attr:`~iris.coords.Coord.points` must have the same shapes; all :attr:`~iris.coords.Coord.bounds` must have the same shapes, and must not be ``None``. - Returns: - :class:`Mesh` + Returns + ------- + :class:`Mesh` + Notes + ----- .. note:: Any resulting duplicate nodes are not currently removed, due to the computational intensity. @@ -717,7 +728,9 @@ def from_coords(cls, *coords): with PARSE_UGRID_ON_LOAD.context(): cube_w_mesh = load_cube(file_path) - For example:: + Examples + -------- + :: # Reconstruct a cube-with-mesh after subsetting it. @@ -891,7 +904,7 @@ def summary(self, shorten=False): Parameters ---------- - shorten : bool, default = False + shorten : bool, default=False If True, produce a oneline string form of the form . If False, produce a multi-line detailed print output. @@ -1207,9 +1220,9 @@ def node_dimension(self, name): def add_connectivities(self, *connectivities): """Add one or more :class:`~iris.experimental.ugrid.mesh.Connectivity` instances to the :class:`Mesh`. - Args: - - * connectivities (iterable of object): + Parameters + ---------- + *connectivities : iterable of object A collection of one or more :class:`~iris.experimental.ugrid.mesh.Connectivity` instances to add to the :class:`Mesh`. @@ -1228,24 +1241,19 @@ def add_coords( ): """Add one or more :class:`~iris.coords.AuxCoord` coordinates to the :class:`Mesh`. - Kwargs: - - * node_x (object): + Parameters + ---------- + node_x (object) : optional, default=None The ``x-axis`` like ``node`` :class:`~iris.coords.AuxCoord`. - - * node_y (object): + node_y (object): optional, default=None The ``y-axis`` like ``node`` :class:`~iris.coords.AuxCoord`. - - * edge_x (object): + edge_x (object): optional, default=None The ``x-axis`` like ``edge`` :class:`~iris.coords.AuxCoord`. - - * edge_y (object): + edge_y (object): optional, default=None The ``y-axis`` like ``edge`` :class:`~iris.coords.AuxCoord`. - - * face_x (object): + face_x (object): optional, default=None The ``x-axis`` like ``face`` :class:`~iris.coords.AuxCoord`. - - * face_y (object): + face_y (object): optional, default=None The ``y-axis`` like ``face`` :class:`~iris.coords.AuxCoord`. """ @@ -1285,9 +1293,9 @@ def connectivities( :meth:`Mesh.connectivity` for matching exactly one connectivity. - Kwargs: - - * item (str or object): + Parameters + ---------- + item : str or object Either, * a :attr:`~iris.common.mixin.CFVariableMixin.standard_name`, @@ -1299,47 +1307,41 @@ def connectivities( the desired objects e.g., :class:`~iris.experimental.ugrid.mesh.Connectivity` or :class:`~iris.experimental.ugrid.metadata.ConnectivityMetadata`. - - * standard_name (str): + standard_name : str, optional, default=None The CF standard name of the desired :class:`~iris.experimental.ugrid.mesh.Connectivity`. If ``None``, does not check for ``standard_name``. - - * long_name (str): + long_name : str, optional, default=None An unconstrained description of the :class:`~iris.experimental.ugrid.mesh.Connectivity`. If ``None``, does not check for ``long_name``. - - * var_name (str): + var_name : str, optional, default=None The NetCDF variable name of the desired :class:`~iris.experimental.ugrid.mesh.Connectivity`. If ``None``, does not check for ``var_name``. - - * attributes (dict): + attributes : dict, optional, default=None A dictionary of attributes desired on the :class:`~iris.experimental.ugrid.mesh.Connectivity`. If ``None``, does not check for ``attributes``. - - * cf_role (str): + cf_role : str, optional, default=None The UGRID ``cf_role`` of the desired :class:`~iris.experimental.ugrid.mesh.Connectivity`. - - * contains_node (bool): + contains_node : bool, optional Contains the ``node`` element as part of the :attr:`~iris.experimental.ugrid.metadata.ConnectivityMetadata.cf_role` in the list of objects to be matched. - - * contains_edge (bool): + contains_edge : bool, optional Contains the ``edge`` element as part of the :attr:`~iris.experimental.ugrid.metadata.ConnectivityMetadata.cf_role` in the list of objects to be matched. - - * contains_face (bool): + contains_face : bool, optional Contains the ``face`` element as part of the :attr:`~iris.experimental.ugrid.metadata.ConnectivityMetadata.cf_role` in the list of objects to be matched. - Returns: + Returns + ------- + list of :class:`~iris.experimental.ugrid.mesh.Connectivity` A list of :class:`~iris.experimental.ugrid.mesh.Connectivity` instances from the :class:`Mesh` that matched the given criteria. @@ -1385,9 +1387,9 @@ def connectivity( :meth:`Mesh.connectivities` for matching zero or more connectivities. - Kwargs: - - * item (str or object): + Parameters + ---------- + item : str or object Either, * a :attr:`~iris.common.mixin.CFVariableMixin.standard_name`, @@ -1399,47 +1401,41 @@ def connectivity( the desired object e.g., :class:`~iris.experimental.ugrid.mesh.Connectivity` or :class:`~iris.experimental.ugrid.metadata.ConnectivityMetadata`. - - * standard_name (str): + standard_name : str, optional, default=None The CF standard name of the desired :class:`~iris.experimental.ugrid.mesh.Connectivity`. If ``None``, does not check for ``standard_name``. - - * long_name (str): + long_name : str, optional, default=None An unconstrained description of the :class:`~iris.experimental.ugrid.mesh.Connectivity`. If ``None``, does not check for ``long_name``. - - * var_name (str): + var_name : str, optional, default=None The NetCDF variable name of the desired :class:`~iris.experimental.ugrid.mesh.Connectivity`. If ``None``, does not check for ``var_name``. - - * attributes (dict): + attributes : dict, optional, default=None A dictionary of attributes desired on the :class:`~iris.experimental.ugrid.mesh.Connectivity`. If ``None``, does not check for ``attributes``. - - * cf_role (str): + cf_role : str, optional, default=None The UGRID ``cf_role`` of the desired :class:`~iris.experimental.ugrid.mesh.Connectivity`. - - * contains_node (bool): + contains_node : bool, optional Contains the ``node`` element as part of the :attr:`~iris.experimental.ugrid.metadata.ConnectivityMetadata.cf_role` in the list of objects to be matched. - - * contains_edge (bool): + contains_edge : bool, optional Contains the ``edge`` element as part of the :attr:`~iris.experimental.ugrid.metadata.ConnectivityMetadata.cf_role` in the list of objects to be matched. - - * contains_face (bool): + contains_face : bool, optional Contains the ``face`` element as part of the :attr:`~iris.experimental.ugrid.metadata.ConnectivityMetadata.cf_role` in the list of objects to be matched. - Returns: + Returns + ------- + :class:`~iris.experimental.ugrid.mesh.Connectivity` The :class:`~iris.experimental.ugrid.mesh.Connectivity` from the :class:`Mesh` that matched the given criteria. @@ -1485,9 +1481,9 @@ def coord( :meth:`Mesh.coords` for matching zero or more coordinates. - Kwargs: - - * item (str or object): + Parameters + ---------- + item : str or object, optional, default=None Either, * a :attr:`~iris.common.mixin.CFVariableMixin.standard_name`, @@ -1498,38 +1494,32 @@ def coord( * a coordinate or metadata instance equal to that of the desired coordinate e.g., :class:`~iris.coords.AuxCoord` or :class:`~iris.common.metadata.CoordMetadata`. - - * standard_name (str): + standard_name : str, optional, default=None The CF standard name of the desired coordinate. If ``None``, does not check for ``standard_name``. - - * long_name (str): + long_name : str, optional, default=None An unconstrained description of the coordinate. If ``None``, does not check for ``long_name``. - - * var_name (str): + var_name : str, optional, default=None The NetCDF variable name of the desired coordinate. If ``None``, does not check for ``var_name``. - - * attributes (dict): + attributes : dict, optional, default=None A dictionary of attributes desired on the coordinates. If ``None``, does not check for ``attributes``. - - * axis (str): + axis : str, optional, default=None The desired coordinate axis, see :func:`~iris.util.guess_coord_axis`. If ``None``, does not check for ``axis``. Accepts the values ``X``, ``Y``, ``Z`` and ``T`` (case-insensitive). - - * include_node (bool): + include_node : bool, optional Include all ``node`` coordinates in the list of objects to be matched. - - * include_edge (bool): + include_edge : bool, optional Include all ``edge`` coordinates in the list of objects to be matched. - - * include_face (bool): + include_face : bool, optional Include all ``face`` coordinates in the list of objects to be matched. - Returns: + Returns + ------- + :class:`~iris.coords.AuxCoord` The :class:`~iris.coords.AuxCoord` coordinate from the :class:`Mesh` that matched the given criteria. @@ -1569,9 +1559,9 @@ def coords( :meth:`Mesh.coord` for matching exactly one coordinate. - Kwargs: - - * item (str or object): + Parameters + ---------- + item : str or object, optional, default=None Either, * a :attr:`~iris.common.mixin.CFVariableMixin.standard_name`, @@ -1582,38 +1572,32 @@ def coords( * a coordinate or metadata instance equal to that of the desired coordinates e.g., :class:`~iris.coords.AuxCoord` or :class:`~iris.common.metadata.CoordMetadata`. - - * standard_name (str): + standard_name : str, optional, default=None The CF standard name of the desired coordinate. If ``None``, does not check for ``standard_name``. - - * long_name (str): + long_name : str, optional, default=None An unconstrained description of the coordinate. If ``None``, does not check for ``long_name``. - - * var_name (str): + var_name : str, optional, default=None The NetCDF variable name of the desired coordinate. If ``None``, does not check for ``var_name``. - - * attributes (dict): + attributes : dict, optional, default=None A dictionary of attributes desired on the coordinates. If ``None``, does not check for ``attributes``. - - * axis (str): + axis : str, optional, default=None The desired coordinate axis, see :func:`~iris.util.guess_coord_axis`. If ``None``, does not check for ``axis``. Accepts the values ``X``, ``Y``, ``Z`` and ``T`` (case-insensitive). - - * include_node (bool): + include_node : bool, optional Include all ``node`` coordinates in the list of objects to be matched. - - * include_edge (bool): + include_edge : bool, optional Include all ``edge`` coordinates in the list of objects to be matched. - - * include_face (bool): + include_face : bool, optional Include all ``face`` coordinates in the list of objects to be matched. - Returns: + Returns + ------- + list of :class:`~iris.coords.AuxCoord` A list of :class:`~iris.coords.AuxCoord` coordinates from the :class:`Mesh` that matched the given criteria. @@ -1649,9 +1633,9 @@ def remove_connectivities( Criteria can be either specific properties or other objects with metadata to be matched. - Kwargs: - - * item (str or object): + Parameters + ---------- + item : str or object, optional, default=None Either, * a :attr:`~iris.common.mixin.CFVariableMixin.standard_name`, @@ -1663,47 +1647,41 @@ def remove_connectivities( the desired objects e.g., :class:`~iris.experimental.ugrid.mesh.Connectivity` or :class:`~iris.experimental.ugrid.metadata.ConnectivityMetadata`. - - * standard_name (str): + standard_name : str, optional, default=None The CF standard name of the desired :class:`~iris.experimental.ugrid.mesh.Connectivity`. If ``None``, does not check for ``standard_name``. - - * long_name (str): + long_name : str, optional, default=None An unconstrained description of the - :class:`~iris.experimental.ugrid.mesh.Connectivity. If ``None``, + :class:`~iris.experimental.ugrid.mesh.Connectivity`. If ``None``, does not check for ``long_name``. - - * var_name (str): + var_name : str, optional, default=None The NetCDF variable name of the desired :class:`~iris.experimental.ugrid.mesh.Connectivity`. If ``None``, does not check for ``var_name``. - - * attributes (dict): + attributes : dict, optional, default=None A dictionary of attributes desired on the :class:`~iris.experimental.ugrid.mesh.Connectivity`. If ``None``, does not check for ``attributes``. - - * cf_role (str): + cf_role : str, optional, default=None The UGRID ``cf_role`` of the desired :class:`~iris.experimental.ugrid.mesh.Connectivity`. - - * contains_node (bool): + contains_node : bool, optional Contains the ``node`` element as part of the :attr:`~iris.experimental.ugrid.metadata.ConnectivityMetadata.cf_role` in the list of objects to be matched for potential removal. - - * contains_edge (bool): + contains_edge : bool, optional Contains the ``edge`` element as part of the :attr:`~iris.experimental.ugrid.metadata.ConnectivityMetadata.cf_role` in the list of objects to be matched for potential removal. - - * contains_face (bool): + contains_face : bool, optional Contains the ``face`` element as part of the :attr:`~iris.experimental.ugrid.metadata.ConnectivityMetadata.cf_role` in the list of objects to be matched for potential removal. - Returns: + Returns + ------- + list of :class:`~iris.experimental.ugrid.mesh.Connectivity` A list of :class:`~iris.experimental.ugrid.mesh.Connectivity` instances removed from the :class:`Mesh` that matched the given criteria. @@ -1739,9 +1717,9 @@ def remove_coords( Criteria can be either specific properties or other objects with metadata to be matched. - Kwargs: - - * item (str or object): + Parameters + ---------- + item : str or object, optional, default=None Either, * a :attr:`~iris.common.mixin.CFVariableMixin.standard_name`, @@ -1752,41 +1730,35 @@ def remove_coords( * a coordinate or metadata instance equal to that of the desired coordinates e.g., :class:`~iris.coords.AuxCoord` or :class:`~iris.common.metadata.CoordMetadata`. - - * standard_name (str): + standard_name : str, optional, default=None The CF standard name of the desired coordinate. If ``None``, does not check for ``standard_name``. - - * long_name (str): + long_name : str, optional, default=None An unconstrained description of the coordinate. If ``None``, does not check for ``long_name``. - - * var_name (str): + var_name : str, optional, default=None The NetCDF variable name of the desired coordinate. If ``None``, does not check for ``var_name``. - - * attributes (dict): + attributes : dict, optional, default=None A dictionary of attributes desired on the coordinates. If ``None``, does not check for ``attributes``. - - * axis (str): + axis : str, optional, default=None The desired coordinate axis, see :func:`~iris.util.guess_coord_axis`. If ``None``, does not check for ``axis``. Accepts the values ``X``, ``Y``, ``Z`` and ``T`` (case-insensitive). - - * include_node (bool): + include_node : bool, optional Include all ``node`` coordinates in the list of objects to be matched for potential removal. - - * include_edge (bool): + include_edge : bool, optional Include all ``edge`` coordinates in the list of objects to be matched for potential removal. - - * include_face (bool): + include_face : bool, optional Include all ``face`` coordinates in the list of objects to be matched for potential removal. - Returns: + Returns + ------- + list of :class:`~iris.coords.AuxCoord` A list of :class:`~iris.coords.AuxCoord` coordinates removed from the :class:`Mesh` that matched the given criteria. @@ -1812,12 +1784,14 @@ def xml_element(self, doc): """Create the :class:`xml.dom.minidom.Element` that describes this :class:`Mesh`. - Args: - - * doc (object): + Parameters + ---------- + doc : object The parent :class:`xml.dom.minidom.Document`. - Returns: + Returns + ------- + :class:`xml.dom.minidom.Element` The :class:`xml.dom.minidom.Element` that will describe this :class:`Mesh`, and the dictionary of attributes that require to be added to this element. @@ -1847,17 +1821,18 @@ def to_MeshCoord(self, location, axis): :meth:`to_MeshCoords` for generating a series of mesh coords. - Args: - - * location (str) + Parameters + ---------- + location : str The ``location`` argument for :class:`~iris.experimental.ugrid.mesh.MeshCoord` instantiation. - - * axis (str) + axis : str The ``axis`` argument for :class:`~iris.experimental.ugrid.mesh.MeshCoord` instantiation. - Returns: + Returns + ------- + :class:`~iris.experimental.ugrid.mesh.MeshCoord` A :class:`~iris.experimental.ugrid.mesh.MeshCoord` referencing the current :class:`Mesh`. @@ -1874,13 +1849,15 @@ def to_MeshCoords(self, location): :meth:`to_MeshCoord` for generating a single mesh coord. - Args: - - * location (str) + Parameters + ---------- + location : str The ``location`` argument for :class:`MeshCoord` instantiation. - Returns: - tuple of :class:`~iris.experimental.ugrid.mesh.MeshCoord`\\ s + Returns + ------- + tuple of :class:`~iris.experimental.ugrid.mesh.MeshCoord` + tuple of :class:`~iris.experimental.ugrid.mesh.MeshCoord` referencing the current :class:`Mesh`. One for each value in :attr:`AXES`, using the value for the ``axis`` argument. @@ -1893,17 +1870,15 @@ def dimension_names_reset(self, node=False, edge=False, face=False): """Reset the name used for the NetCDF variable representing the ``node``, ``edge`` and/or ``face`` dimension to ``None``. - Kwargs: - - * node (bool): + Parameters + ---------- + node : bool, optional, default=False Reset the name of the ``node`` dimension if ``True``. Default is ``False``. - - * edge (bool): + edge : bool, optional, default=False Reset the name of the ``edge`` dimension if ``True``. Default is ``False``. - - * face (bool): + face : bool, optional, default=False Reset the name of the ``face`` dimension if ``True``. Default is ``False``. @@ -1918,17 +1893,15 @@ def dimension_names(self, node=None, edge=None, face=None): associated ``node``, ``edge`` or ``face``. Instead use :meth:`Mesh.dimension_names_reset`. - Kwargs: - - * node (str): + Parameters + ---------- + node : str, optional, default=None The name to be used for the NetCDF variable representing the ``node`` dimension. - - * edge (str): + edge : str, optional, default=None The name to be used for the NetCDF variable representing the ``edge`` dimension. - - * face (str): + face : str, optional, default=None The name to be used for the NetCDF variable representing the ``face`` dimension. @@ -2827,9 +2800,9 @@ def __getitem__(self, keys): def copy(self, points=None, bounds=None): """Make a copy of the MeshCoord. - Kwargs: - - * points, bounds (array): + Parameters + ---------- + points, bounds : array) Provided solely for signature compatibility with other types of :class:`~iris.coords.Coord`. In this case, if either is not 'None', an error is raised. @@ -2939,8 +2912,9 @@ def _construct_access_arrays(self): """Build lazy points and bounds arrays, providing dynamic access via the Mesh, according to the location and axis. - Returns: - * points, bounds (array or None): + Returns + ------- + points, bounds : array or None lazy arrays which calculate the correct points and bounds from the Mesh data, based on the location and axis. The Mesh coordinates accessed are not identified on construction, diff --git a/lib/iris/experimental/ugrid/metadata.py b/lib/iris/experimental/ugrid/metadata.py index 153f71bfcb..8969ab72a1 100644 --- a/lib/iris/experimental/ugrid/metadata.py +++ b/lib/iris/experimental/ugrid/metadata.py @@ -37,14 +37,15 @@ def __eq__(self, other): def _combine_lenient(self, other): """Perform lenient combination of metadata members for connectivities. - Args: - - * other (ConnectivityMetadata): + Parameters + ---------- + other : ConnectivityMetadata The other connectivity metadata participating in the lenient combination. - Returns: - A list of combined metadata member values. + Returns + ------- + A list of combined metadata member values. """ @@ -65,14 +66,15 @@ def func(field): def _compare_lenient(self, other): """Perform lenient equality of metadata members for connectivities. - Args: - - * other (ConnectivityMetadata): + Parameters + ---------- + other : ConnectivityMetadata The other connectivity metadata participating in the lenient comparison. - Returns: - Boolean. + Returns + ------- + bool """ # Perform "strict" comparison for "cf_role", "start_index". @@ -93,14 +95,15 @@ def _compare_lenient(self, other): def _difference_lenient(self, other): """Perform lenient difference of metadata members for connectivities. - Args: - - * other (ConnectivityMetadata): + Parameters + ---------- + other : ConnectivityMetadata The other connectivity metadata participating in the lenient difference. - Returns: - A list of difference metadata member values. + Returns + ------- + A list of difference metadata member values. """ @@ -156,14 +159,15 @@ def __eq__(self, other): def _combine_lenient(self, other): """Perform lenient combination of metadata members for meshes. - Args: - - * other (MeshMetadata): + Parameters + ---------- + other : MeshMetadata The other mesh metadata participating in the lenient combination. - Returns: - A list of combined metadata member values. + Returns + ------- + A list of combined metadata member values. """ @@ -185,14 +189,15 @@ def func(field): def _compare_lenient(self, other): """Perform lenient equality of metadata members for meshes. - Args: - - * other (MeshMetadata): + Parameters + ---------- + other : MeshMetadata The other mesh metadata participating in the lenient comparison. - Returns: - Boolean. + Returns + ------- + bool """ # Perform "strict" comparison for "topology_dimension". @@ -208,14 +213,15 @@ def _compare_lenient(self, other): def _difference_lenient(self, other): """Perform lenient difference of metadata members for meshes. - Args: - - * other (MeshMetadata): + Parameters + ---------- + other : MeshMetadata The other mesh metadata participating in the lenient difference. - Returns: - A list of difference metadata member values. + Returns + ------- + A list of difference metadata member values. """ @@ -271,13 +277,14 @@ def __eq__(self, other): def _combine_lenient(self, other): """Perform lenient combination of metadata members for MeshCoord. - Args: - - * other (MeshCoordMetadata): + Parameters + ---------- + other : MeshCoordMetadata The other metadata participating in the lenient combination. - Returns: - A list of combined metadata member values. + Returns + ------- + A list of combined metadata member values. """ @@ -298,13 +305,14 @@ def func(field): def _compare_lenient(self, other): """Perform lenient equality of metadata members for MeshCoord. - Args: - - * other (MeshCoordMetadata): + Parameters + ---------- + other : MeshCoordMetadata The other metadata participating in the lenient comparison. - Returns: - Boolean. + Returns + ------- + bool """ # Perform "strict" comparison for the MeshCoord specific members @@ -321,14 +329,15 @@ def _compare_lenient(self, other): def _difference_lenient(self, other): """Perform lenient difference of metadata members for MeshCoord. - Args: - - * other (MeshCoordMetadata): + Parameters + ---------- + other : MeshCoordMetadata The other MeshCoord metadata participating in the lenient difference. - Returns: - A list of different metadata member values. + Returns + ------- + A list of different metadata member values. """ diff --git a/lib/iris/fileformats/_ff.py b/lib/iris/fileformats/_ff.py index 88bbfd45d5..dfc05f014d 100644 --- a/lib/iris/fileformats/_ff.py +++ b/lib/iris/fileformats/_ff.py @@ -141,18 +141,15 @@ def __init__( ): """Create a Grid from the relevant sections of the FFHeader. - Args: - - * column_dependent_constants (numpy.ndarray): + Parameters + ---------- + column_dependent_constants : numpy.ndarray The `column_dependent_constants` from a FFHeader. - - * row_dependent_constants (numpy.ndarray): + row_dependent_constants : numpy.ndarray The `row_dependent_constants` from a FFHeader. - - * real_constants (numpy.ndarray): + real_constants : numpy.ndarray The `real_constants` from a FFHeader. - - * horiz_grid_type (integer): + horiz_grid_type : int `horiz_grid_type` from a FFHeader. """ @@ -186,12 +183,13 @@ def vectors(self, subgrid): """Return the X and Y coordinate vectors for the given sub-grid of this grid. - Args: - - * subgrid (integer): + Parameters + ---------- + subgrid : int A "grid type code" as described in UM documentation paper C4. - Returns: + Returns + ------- A 2-tuple of X-vector, Y-vector. """ @@ -225,12 +223,13 @@ def regular_x(self, subgrid): """Return the "zeroth" value and step for the X coordinate on the given sub-grid of this grid. - Args: - - * subgrid (integer): + Parameters + ---------- + subgrid : int A "grid type code" as described in UM documentation paper C4. - Returns: + Returns + ------- A 2-tuple of BZX, BDX. """ @@ -244,12 +243,13 @@ def regular_y(self, subgrid): """Return the "zeroth" value and step for the Y coordinate on the given sub-grid of this grid. - Args: - - * subgrid (integer): + Parameters + ---------- + subgrid : int A "grid type code" as described in UM documentation paper C4. - Returns: + Returns + ------- A 2-tuple of BZY, BDY. """ @@ -306,13 +306,14 @@ def __init__(self, filename, word_depth=DEFAULT_FF_WORD_DEPTH): FIXED_LENGTH_HEADER section of the FieldsFile, making the names defined in FF_HEADER available as attributes of a FFHeader instance. - Args: - - * filename (string): + Parameters + ---------- + filename : str Specify the name of the FieldsFile. - Returns: - FFHeader object. + Returns + ------- + FFHeader object. """ @@ -400,13 +401,14 @@ def shape(self, name): """Return the dimension shape of the FieldsFile FIXED_LENGTH_HEADER pointer attribute. - Args: - - * name (string): + Parameters + ---------- + name : str Specify the name of the FIXED_LENGTH_HEADER attribute. - Returns: - Dimension tuple. + Returns + ------- + Dimension tuple. """ @@ -443,21 +445,21 @@ def __init__(self, filename, read_data=False, word_depth=DEFAULT_FF_WORD_DEPTH): """Create a FieldsFile to Post Process instance that returns a generator of PPFields contained within the FieldsFile. - Args: - - * filename (string): + Parameters + ---------- + filename : str Specify the name of the FieldsFile. - - Kwargs: - - * read_data (boolean): + read_data : boolean, optional Specify whether to read the associated PPField data within the FieldsFile. Default value is False. - Returns: - PPField generator. + Returns + ------- + PPField generator. - For example:: + Examples + -------- + :: >>> for field in ff.FF2PP(filename): ... print(field) @@ -809,15 +811,14 @@ def __iter__(self): def _parse_binary_stream(file_like, dtype=np.float64, count=-1): """Replacement :func:`numpy.fromfile` due to python3 performance issues. - Args: - - * file_like - Standard python file_like object. - - Kwargs: - - * dtype - Data type to be parsed out, used to work out bytes read in. - - * count - The number of values required to be generated from the parsing. + Parameters + ---------- + file_like : + Standard python file_like object. + dtype : no.float64, optional + Data type to be parsed out, used to work out bytes read in. + count : optional, default=-1 + The number of values required to be generated from the parsing. The default is -1, which will read the entire contexts of the file_like object and generate as many values as possible. @@ -842,15 +843,15 @@ def _parse_binary_stream(file_like, dtype=np.float64, count=-1): def load_cubes(filenames, callback, constraints=None): """Loads cubes from a list of fields files filenames. - Args: - - * filenames - list of fields files filenames to load - - Kwargs: - - * callback - a function which can be passed on to - :func:`iris.io.run_callback` + Parameters + ---------- + filenames : + List of fields files filenames to load + callback : + A function which can be passed on to :func:`iris.io.run_callback` + Notes + ----- .. note:: The resultant cubes may not be in the order that they are in the @@ -866,9 +867,10 @@ def load_cubes(filenames, callback, constraints=None): def load_cubes_32bit_ieee(filenames, callback, constraints=None): """Loads cubes from a list of 32bit ieee converted fieldsfiles filenames. - .. seealso:: - - :func:`load_cubes` for keyword details + See Also + -------- + :func:`load_cubes` + For keyword details """ return pp._load_cubes_variable_loader( diff --git a/lib/iris/fileformats/cf.py b/lib/iris/fileformats/cf.py index 737955b9a7..7bba1442da 100644 --- a/lib/iris/fileformats/cf.py +++ b/lib/iris/fileformats/cf.py @@ -5,7 +5,8 @@ """Provides the capability to load netCDF files and interpret them according to the 'NetCDF Climate and Forecast (CF) Metadata Conventions'. -References: +References +---------- [CF] NetCDF Climate and Forecast (CF) Metadata conventions. [NUG] NetCDF User's Guide, https://www.unidata.ucar.edu/software/netcdf/documentation/NUG/ @@ -112,22 +113,20 @@ def _identify_common(variables, ignore, target): def identify(self, variables, ignore=None, target=None, warn=True): """Identify all variables that match the criterion for this CF-netCDF variable class. - Args: - - * variables: + Parameters + ---------- + variables : Dictionary of netCDF4.Variable instance by variable name. - - Kwargs: - - * ignore: + ignore : optional, default=None List of variable names to ignore. - * target: + target : optional, default=None Name of a single variable to check. - * warn: + warn : optional, default=None Issue a warning if a missing variable is referenced. - Returns: - Dictionary of CFVariable instance by variable name. + Returns + ------- + Dictionary of CFVariable instance by variable name. """ pass @@ -139,13 +138,14 @@ def spans(self, cf_variable): Note that, by default scalar variables always span the dimensionality of the target variable. - Args: - - * cf_variable: + Parameters + ---------- + cf_variable : Compare dimensionality with the :class:`CFVariable`. - Returns: - Boolean. + Returns + ------- + bool """ result = set(self.dimensions).issubset(cf_variable.dimensions) @@ -215,15 +215,18 @@ def cf_attrs_reset(self): def add_formula_term(self, root, term): """Register the participation of this CF-netCDF variable in a CF-netCDF formula term. - Args: - - * root (string): - The name of CF-netCDF variable that defines the CF-netCDF formula_terms attribute. - * term (string): - The associated term name of this variable in the formula_terms definition. + Parameters + ---------- + root : str + The name of CF-netCDF variable that defines the CF-netCDF + formula_terms attribute. + term : str + The associated term name of this variable in the formula_terms + definition. - Returns: - None. + Returns + ------- + None """ self.cf_terms_by_root[root] = term @@ -231,8 +234,9 @@ def add_formula_term(self, root, term): def has_formula_terms(self): """Determine whether this CF-netCDF variable participates in a CF-netcdf formula term. - Returns: - Boolean. + Returns + ------- + bool """ return bool(self.cf_terms_by_root) @@ -375,13 +379,14 @@ def spans(self, cf_variable): Note that, by default scalar variables always span the dimensionality of the target variable. - Args: - - * cf_variable: + Parameters + ---------- + cf_variable : Compare dimensionality with the :class:`CFVariable`. - Returns: - Boolean. + Returns + ------- + bool """ # Scalar variables always span the target variable. @@ -446,13 +451,14 @@ def spans(self, cf_variable): Note that, by default scalar variables always span the dimensionality of the target variable. - Args: - - * cf_variable: + Parameters + ---------- + cf_variable : :class:`CFVariable` Compare dimensionality with the :class:`CFVariable`. - Returns: - Boolean. + Returns + ------- + bool """ # Scalar variables always span the target variable. @@ -678,13 +684,15 @@ def identify(cls, variables, ignore=None, target=None, warn=True): def cf_label_data(self, cf_data_var): """Return the associated CF-netCDF label variable strings. - Args: - - * cf_data_var (:class:`iris.fileformats.cf.CFDataVariable`): - The CF-netCDF data variable which the CF-netCDF label variable describes. + Parameters + ---------- + cf_data_var : :class:`iris.fileformats.cf.CFDataVariable` + The CF-netCDF data variable which the CF-netCDF label variable + describes. - Returns: - String labels. + Returns + ------- + str labels """ @@ -744,13 +752,15 @@ def cf_label_data(self, cf_data_var): def cf_label_dimensions(self, cf_data_var): """Return the name of the associated CF-netCDF label variable data dimensions. - Args: + Parameters + ---------- + cf_data_var : :class:`iris.fileformats.cf.CFDataVariable` + The CF-netCDF data variable which the CF-netCDF label variable + describes. - * cf_data_var (:class:`iris.fileformats.cf.CFDataVariable`): - The CF-netCDF data variable which the CF-netCDF label variable describes. - - Returns: - Tuple of label data dimension names. + Returns + ------- + Tuple of label data dimension names. """ @@ -775,13 +785,14 @@ def spans(self, cf_variable): Note that, by default scalar variables always span the dimensionality of the target variable. - Args: - - * cf_variable: + Parameters + ---------- + cf_variable : Compare dimensionality with the :class:`CFVariable`. - Returns: - Boolean. + Returns + ------- + bool """ # Scalar variables always span the target variable. diff --git a/lib/iris/fileformats/name.py b/lib/iris/fileformats/name.py index 4742ec9001..3d01b07dee 100644 --- a/lib/iris/fileformats/name.py +++ b/lib/iris/fileformats/name.py @@ -46,18 +46,16 @@ def load_cubes(filenames, callback): """Return a generator of cubes given one or more filenames and an optional callback. - Args: - - * filenames (string/list): + Parameters + ---------- + filenames : str or list One or more NAME filenames to load. - - Kwargs: - - * callback (callable function): + callback : callable function, optional A function which can be passed on to :func:`iris.io.run_callback`. - Returns: - A generator of :class:`iris.cubes.Cube` instances. + Returns + ------- + A generator of :class:`iris.cubes.Cube` instances. """ from iris.io import run_callback diff --git a/lib/iris/fileformats/name_loaders.py b/lib/iris/fileformats/name_loaders.py index e6acb6aa66..66dcf8c422 100644 --- a/lib/iris/fileformats/name_loaders.py +++ b/lib/iris/fileformats/name_loaders.py @@ -45,16 +45,19 @@ def _split_name_and_units(name): def read_header(file_handle): - """Return a dictionary containing the header information extracted - from the the provided NAME file object. + """Return a dictionary containing the header information. - Args: + Return a dictionary containing the header information extracted + from the the provided NAME file object. - * file_handle (file-like object): + Parameters + ---------- + file_handle : file-like object A file-like object from which to read the header information. - Returns: - A dictionary containing the extracted header information. + Returns + ------- + A dictionary containing the extracted header information. """ header = {} @@ -221,13 +224,14 @@ def _parse_units(units): * Units where the characters used are non-standard (i.e. 'mc' for micro instead of 'u') - Args: - - * units (string): + Parameters + ---------- + units : str NAME units. - Returns: - An instance of :class:`cf_units.Unit`. + Returns + ------- + An instance of :class:`cf_units.Unit`. """ @@ -268,12 +272,14 @@ def _cf_height_from_name(z_coord, lower_bound=None, upper_bound=None): and flight level etc. This function returns an iris coordinate representing this field heading. - Args: - - * z_coord (list): + Parameters + ---------- + z_coord : list A field heading, specifically the z component. - Returns: + Returns + ------- + :class:`iris.coords.AuxCoord` An instance of :class:`iris.coords.AuxCoord` representing the interpretation of the supplied field heading. @@ -551,16 +557,18 @@ def _build_cell_methods(av_or_ints, coord): associated coordinate. If a given entry does not correspond to a cell method (e.g. "No time averaging"), a value of None is inserted. - Args: - - * av_or_ints (iterable of strings): + Parameters + ---------- + av_or_ints : iterable of str An iterable of strings containing the column heading entries to be parsed. - * coord (string or :class:`iris.coords.Coord`): + coord : str or :class:`iris.coords.Coord` The coordinate name (or :class:`iris.coords.Coord` instance) to which the column heading entries refer. - Returns: + Returns + ------- + list of :class:`iris.coords.CellMethod` or None. A list that is the same length as `av_or_ints` containing :class:`iris.coords.CellMethod` instances or values of None. @@ -586,13 +594,14 @@ def load_NAMEIII_field(filename): """Load a NAME III grid output file returning a generator of :class:`iris.cube.Cube` instances. - Args: - - * filename (string): + Parameters + ---------- + filename : str Name of file to load. - Returns: - A generator :class:`iris.cube.Cube` instances. + Returns + ------- + A generator :class:`iris.cube.Cube` instances. """ # Loading a file gives a generator of lines which can be progressed using @@ -677,16 +686,19 @@ def load_NAMEIII_field(filename): def load_NAMEII_field(filename): - """Load a NAME II grid output file returning a - generator of :class:`iris.cube.Cube` instances. + """Load a NAME II grid output file. - Args: + Load a NAME II grid output file returning a generator of + :class:`iris.cube.Cube` instances. - * filename (string): + Parameters + ---------- + filename : str Name of file to load. - Returns: - A generator :class:`iris.cube.Cube` instances. + Returns + ------- + A generator :class:`iris.cube.Cube` instances. """ with open(filename, "r") as file_handle: @@ -764,16 +776,19 @@ def load_NAMEII_field(filename): def load_NAMEIII_timeseries(filename): - """Load a NAME III time series file returning a - generator of :class:`iris.cube.Cube` instances. + """Load a NAME III time series file. - Args: + Load a NAME III time series file returning a generator of + :class:`iris.cube.Cube` instances. - * filename (string): + Parameters + ---------- + filename : str Name of file to load. - Returns: - A generator :class:`iris.cube.Cube` instances. + Returns + ------- + A generator :class:`iris.cube.Cube` instances. """ with open(filename, "r") as file_handle: @@ -852,16 +867,19 @@ def load_NAMEIII_timeseries(filename): def load_NAMEII_timeseries(filename): - """Load a NAME II Time Series file returning a - generator of :class:`iris.cube.Cube` instances. - - Args: - - * filename (string): + """Load a NAME III time series file. + + Load a NAME II Time Series file returning a generator of + :class:`iris.cube.Cube` instances. + + Parameters + ---------- + filename : str Name of file to load. - Returns: - A generator :class:`iris.cube.Cube` instances. + Returns + ------- + A generator :class:`iris.cube.Cube` instances. """ with open(filename, "r") as file_handle: @@ -922,16 +940,19 @@ def load_NAMEII_timeseries(filename): def load_NAMEIII_version2(filename): - """Load a NAME III version 2 file returning a - generator of :class:`iris.cube.Cube` instances. + """Load a NAME III version 2 file. - Args: + Load a NAME III version 2 file returning a generator of + :class:`iris.cube.Cube` instances. - * filename (string): + Parameters + ---------- + filename : str Name of file to load. - Returns: - A generator :class:`iris.cube.Cube` instances. + Returns + ------- + A generator :class:`iris.cube.Cube` instances. """ @@ -1141,16 +1162,19 @@ def load_NAMEIII_version2(filename): def load_NAMEIII_trajectory(filename): - """Load a NAME III trajectory file returning a - generator of :class:`iris.cube.Cube` instances. - - Args: - - * filename (string): + """Load a NAME III trajectory file. + + Load a NAME III trajectory file returning a generator of + :class:`iris.cube.Cube` instances. + + Parameters + ---------- + filename : str Name of file to load. - Returns: - A generator :class:`iris.cube.Cube` instances. + Returns + ------- + A generator :class:`iris.cube.Cube` instances. """ time_unit = cf_units.Unit("hours since epoch", calendar=cf_units.CALENDAR_STANDARD) diff --git a/lib/iris/fileformats/nimrod.py b/lib/iris/fileformats/nimrod.py index 3aea8b8b81..54c09c91ab 100644 --- a/lib/iris/fileformats/nimrod.py +++ b/lib/iris/fileformats/nimrod.py @@ -169,7 +169,8 @@ class NimrodField: Capable of converting itself into a :class:`~iris.cube.Cube` - References: + References + ---------- Met Office (2003): Met Office Rain Radar Data from the NIMROD System. NCAS British Atmospheric Data Centre, date of citation. https://catalogue.ceda.ac.uk/uuid/82adec1f896af6169112d09cc1174499 @@ -292,15 +293,15 @@ def _read_data(self, infile): def load_cubes(filenames, callback=None): """Loads cubes from a list of NIMROD filenames. - Args: - - * filenames - list of NIMROD filenames to load - - Kwargs: - - * callback - a function which can be passed on to - :func:`iris.io.run_callback` + Parameters + ---------- + filenames : + List of NIMROD filenames to load + callback : + A function which can be passed on to :func:`iris.io.run_callback` + Notes + ----- .. note:: The resultant cubes may not be in the same order as in the files. diff --git a/lib/iris/fileformats/pp_load_rules.py b/lib/iris/fileformats/pp_load_rules.py index 10da402520..e128ff0ad8 100644 --- a/lib/iris/fileformats/pp_load_rules.py +++ b/lib/iris/fileformats/pp_load_rules.py @@ -61,45 +61,34 @@ def _convert_vertical_coords( """Encode scalar or vector vertical level values from PP headers as CM data components. - Args: - - * lbcode: + Parameters + ---------- + lbcode : :class:`iris.fileformats.pp.SplittableInt` Scalar field :class:`iris.fileformats.pp.SplittableInt` value. - - * lbvc: + lbvc : Scalar field value. - - * blev: + blev : Scalar field value or :class:`numpy.ndarray` vector of field values. - - * lblev: + lblev : Scalar field value or :class:`numpy.ndarray` vector of field values. - - * stash: + stash : Scalar field :class:`iris.fileformats.pp.STASH` value. - - * bhlev: + bhlev : Scalar field value or :class:`numpy.ndarray` vector of field values. - - * bhrlev: + bhrlev : Scalar field value or :class:`numpy.ndarray` vector of field values. - - * brsvd1: + brsvd1 : Scalar field value or :class:`numpy.ndarray` vector of field values. - - * brsvd2: + brsvd2 : Scalar field value or :class:`numpy.ndarray` vector of field values. - - * brlev: + brlev : Scalar field value or :class:`numpy.ndarray` vector of field values. - - Kwargs: - - * dim: + dim : optional Associated dimension of the vertical coordinate. Defaults to None. - Returns: - A tuple containing a list of coords_and_dims, and a list of factories. + Returns + ------- + A tuple containing a list of coords_and_dims, and a list of factories. """ factories = [] @@ -311,9 +300,9 @@ def _reshape_vector_args(values_and_dims): can combine without broadcasting errors (provided that all inputs mapping to a dimension define the same associated length). - Args: - - * values_and_dims (iterable of (array-like, iterable of int)): + Parameters + ---------- + values_and_dims : iterable of (array-like, iterable of int) Input arrays with associated mapping dimension numbers. The length of each 'dims' must match the ndims of the 'value'. @@ -359,17 +348,15 @@ def _collapse_degenerate_points_and_bounds(points, bounds=None, rtol=1.0e-7): numbers from cftime.date2num, which has limited precision because of the way it calculates with floats of days. - Args: - - * points (:class:`numpy.ndarray`)): + Parameters + ---------- + points : :class:`numpy.ndarray` Array of points values. - - Kwargs: - - * bounds (:class:`numpy.ndarray`) + bounds : :class:`numpy.ndarray`, optional, default=None Array of bounds values. This array should have an additional vertex dimension (typically of length 2) when compared to the points array i.e. bounds.shape = points.shape + (nvertex,) + rtol : optional, default=1.0e-7 Returns ------- @@ -406,19 +393,16 @@ def _reduce_points_and_bounds(points, lower_and_upper_bounds=None): If the bounds arrays are also passed in, then all three arrays must have the same shape or be capable of being broadcast to match. - Args: - - * points (array-like): + Parameters + ---------- + points : array-like Coordinate point values. - - Kwargs: - - * lower_and_upper_bounds (pair of array-like, or None): + lower_and_upper_bounds : pair of array-like or None, optional Corresponding bounds values (lower, upper), if any. - Returns: - dims (iterable of ints), points(array), bounds(array) - + Returns + ------- + dims (iterable of ints), points(array), bounds(array) * 'dims' is the mapping from the result array dimensions to the original dimensions. However, when 'array' is scalar, 'dims' will be None (rather than an empty tuple). @@ -466,26 +450,21 @@ def _new_coord_and_dims( * the result coordinate may be an AuxCoord if a DimCoord cannot be made (e.g. if values are non-monotonic). - Args: - - * is_vector_operation (bool): + Parameters + ---------- + is_vector_operation : bool If True, perform 'vector' style operation. - - * points (array-like): + points : array-like Coordinate point values. - - * name (string): + name : str Standard name of coordinate. - - * units (string or cf_unit.Unit): + units : str or cf_unit.Unit Units of coordinate. - - Kwargs: - - * lower_and_upper_bounds (pair of array-like, or None): + lower_and_upper_bounds : pair of array-like or None, optional, default=None Corresponding bounds values (lower, upper), if any. - Returns: + Returns + ------- a new (coordinate, dims) pair. """ @@ -504,12 +483,15 @@ def _new_coord_and_dims( def _epoch_date_hours_internals(epoch_hours_unit, datetime): """Return an 'hours since epoch' number for a date. - Args: - * epoch_hours_unit (:class:`cf_unit.Unit'): + Parameters + ---------- + epoch_hours_unit : :class:`cf_unit.Unit' Unit defining the calendar and zero-time of conversion. - * datetime (:class:`datetime.datetime`-like): + datetime : :class:`datetime.datetime`-like Date object containing year / month / day attributes. + Notes + ----- This routine can also handle dates with a zero year, month or day : such dates were valid inputs to 'date2num' up to cftime version 1.0.1, but are now illegal : This routine interprets any zeros as being "1 year/month/day @@ -612,24 +594,21 @@ def _convert_time_coords( ): """Make time coordinates from the time metadata. - Args: - - * lbcode(:class:`iris.fileformats.pp.SplittableInt`): + Parameters + ---------- + lbcode : :class:`iris.fileformats.pp.SplittableInt` Scalar field value. - * lbtim (:class:`iris.fileformats.pp.SplittableInt`): + lbtim : :class:`iris.fileformats.pp.SplittableInt` Scalar field value. - * epoch_hours_unit (:class:`cf_units.Unit`): + epoch_hours_unit : :class:`cf_units.Unit` Epoch time reference unit. - * t1 (array-like or scalar): + t1 : array-like or scalar Scalar field value or an array of values. - * t2 (array-like or scalar): + t2 : array-like or scalar Scalar field value or an array of values. - * lbft (array-like or scalar): + lbft : array-like or scalar Scalar field value or an array of values. - - Kwargs: - - * t1_dims, t2_dims, lbft_dims (tuples of int): + t1_dims, t2_dims, lbft_dims : tuples of int, optional Cube dimension mappings for the array metadata. Each default to to (). The length of each dims tuple should equal the dimensionality of the corresponding array of values. @@ -824,13 +803,14 @@ def date2year(t_in): def _model_level_number(lblev): """Return model level number for an LBLEV value. - Args: - - * lblev (int): + Parameters + ---------- + lblev : int PP field LBLEV value. Returns: - Model level number (integer). + ------- + Model level number (int). """ # See Word no. 33 (LBLEV) in section 4 of UM Model Docs (F3). @@ -876,13 +856,13 @@ def _convert_scalar_pseudo_level_coords(lbuser5): def convert(f): """Converts a PP field into the corresponding items of Cube metadata. - Args: - - * f: - A :class:`iris.fileformats.pp.PPField` object. + Parameters + ---------- + f : :class:`iris.fileformats.pp.PPField` - Returns: - A :class:`iris.fileformats.rules.ConversionMetadata` object. + Returns + ------- + :class:`iris.fileformats.rules.ConversionMetadata` object. """ factories = [] diff --git a/lib/iris/fileformats/pp_save_rules.py b/lib/iris/fileformats/pp_save_rules.py index 60eef7ad96..ab9d1c9545 100644 --- a/lib/iris/fileformats/pp_save_rules.py +++ b/lib/iris/fileformats/pp_save_rules.py @@ -26,12 +26,16 @@ def _basic_coord_system_rules(cube, pp): """Rules for setting the coord system of the PP field. - Args: - cube: the cube being saved as a series of PP fields. + Parameters + ---------- + cube : + The cube being saved as a series of PP fields. pp: the current PP field having save rules applied. + pp : - Returns: - The PP field with updated metadata. + Returns + ------- + The PP field with updated metadata. """ if cube.coord_system("GeogCS") is not None or cube.coord_system(None) is None: @@ -76,12 +80,16 @@ def _um_version_rules(cube, pp): def _stash_rules(cube, pp): """Attributes rules for setting the STASH attribute of the PP field. - Args: - cube: the cube being saved as a series of PP fields. - pp: the current PP field having save rules applied. + Parameters + ---------- + cube : + The cube being saved as a series of PP fields. + pp : + The current PP field having save rules applied. - Returns: - The PP field with updated metadata. + Returns + ------- + The PP field with updated metadata. """ if "STASH" in cube.attributes: @@ -95,12 +103,16 @@ def _stash_rules(cube, pp): def _general_time_rules(cube, pp): """Rules for setting time metadata of the PP field. - Args: - cube: the cube being saved as a series of PP fields. - pp: the current PP field having save rules applied. + Parameters + ---------- + cube : + The cube being saved as a series of PP fields. + pp : + The current PP field having save rules applied. - Returns: - The PP field with updated metadata. + Returns + ------- + The PP field with updated metadata. """ time_coord = scalar_coord(cube, "time") @@ -365,12 +377,16 @@ def _general_time_rules(cube, pp): def _calendar_rules(cube, pp): """Rules for setting the calendar of the PP field. - Args: - cube: the cube being saved as a series of PP fields. - pp: the current PP field having save rules applied. + Parameters + ---------- + cube : + The cube being saved as a series of PP fields. + pp : + The current PP field having save rules applied. - Returns: - The PP field with updated metadata. + Returns + ------- + The PP field with updated metadata. """ time_coord = scalar_coord(cube, "time") @@ -387,12 +403,16 @@ def _calendar_rules(cube, pp): def _grid_and_pole_rules(cube, pp): """Rules for setting the horizontal grid and pole location of the PP field. - Args: - cube: the cube being saved as a series of PP fields. - pp: the current PP field having save rules applied. + Parameters + ---------- + cube : + The cube being saved as a series of PP fields. + pp : + The current PP field having save rules applied. - Returns: - The PP field with updated metadata. + Returns + ------- + The PP field with updated metadata. """ lon_coord = vector_coord(cube, "longitude") @@ -465,12 +485,16 @@ def _grid_and_pole_rules(cube, pp): def _non_std_cross_section_rules(cube, pp): """Rules for applying non-standard cross-sections to the PP field. - Args: - cube: the cube being saved as a series of PP fields. - pp: the current PP field having save rules applied. + Parameters + ---------- + cube: + The cube being saved as a series of PP fields. + pp: + The current PP field having save rules applied. - Returns: - The PP field with updated metadata. + Returns + ------- + The PP field with updated metadata. """ # Define commonly-used coords. @@ -594,12 +618,16 @@ def _lbproc_rules(cube, pp): Note: `pp.lbproc` must be set to 0 before these rules are run. - Args: - cube: the cube being saved as a series of PP fields. - pp: the current PP field having save rules applied. + Parameters + ---------- + cube: + The cube being saved as a series of PP fields. + pp: + The current PP field having save rules applied. - Returns: - The PP field with updated metadata. + Returns + ------- + The PP field with updated metadata. """ # Basic setting (this may be overridden by subsequent rules). @@ -636,12 +664,16 @@ def _lbproc_rules(cube, pp): def _vertical_rules(cube, pp): """Rules for setting vertical levels for the PP field. - Args: - cube: the cube being saved as a series of PP fields. - pp: the current PP field having save rules applied. + Parameters + ---------- + cube : + The cube being saved as a series of PP fields. + pp : + The current PP field having save rules applied. - Returns: - The PP field with updated metadata. + Returns + ------- + The PP field with updated metadata. """ # Define commonly-used coords. @@ -820,12 +852,16 @@ def _all_other_rules(cube, pp): * lbfc (field code) * lbrsvd[3] (ensemble member number) - Args: - cube: the cube being saved as a series of PP fields. - pp: the current PP field having save rules applied. + Parameters + ---------- + cube : + The cube being saved as a series of PP fields. + pp : + The current PP field having save rules applied. - Returns: - The PP field with updated metadata. + Returns + ------- + The PP field with updated metadata. """ # "CFNAME mega-rule." diff --git a/lib/iris/fileformats/rules.py b/lib/iris/fileformats/rules.py index e2bfd250fd..45132794ed 100644 --- a/lib/iris/fileformats/rules.py +++ b/lib/iris/fileformats/rules.py @@ -253,16 +253,14 @@ class Loader(collections.namedtuple("Loader", _loader_attrs)): def __new__(cls, field_generator, field_generator_kwargs, converter): """Create a definition of a field-based Cube loader. - Args: - - * field_generator + Parameters + ---------- + field_generator : A callable that accepts a filename as its first argument and returns an iterable of field objects. - - * field_generator_kwargs + field_generator_kwargs : Additional arguments to be passed to the field_generator. - - * converter + converter : A callable that converts a field object into a Cube. """ @@ -388,17 +386,17 @@ def load_pairs_from_fields(fields, converter): """Convert an iterable of fields into an iterable of Cubes using the provided converter. - Args: - - * fields: + Parameters + ---------- + fields : An iterable of fields. - - * converter: + converter : An Iris converter function, suitable for use with the supplied fields. See the description in :class:`iris.fileformats.rules.Loader`. - Returns: - An iterable of (:class:`iris.cube.Cube`, field) pairs. + Returns + ------- + An iterable of (:class:`iris.cube.Cube`, field) pairs. """ return _load_pairs_from_fields_and_filenames( diff --git a/lib/iris/fileformats/um/_fast_load.py b/lib/iris/fileformats/um/_fast_load.py index 477a221727..f7b62af143 100644 --- a/lib/iris/fileformats/um/_fast_load.py +++ b/lib/iris/fileformats/um/_fast_load.py @@ -49,12 +49,11 @@ class FieldCollation(BasicFieldCollation): def __init__(self, fields, filepath): """FieldCollation initialise. - Args: - - * fields (iterable of :class:`iris.fileformats.pp.PPField`): + Parameters + ---------- + fields : iterable of :class:`iris.fileformats.pp.PPField` The fields in the collation. - - * filepath (string): + filepath : str The path of the file the collation is loaded from. """ @@ -72,8 +71,9 @@ def data_field_indices(self): This records the original file location of the individual data fields contained, within the input datafile. - Returns: - An integer array of shape `self.vector_dims_shape`. + Returns + ------- + An integer array of shape `self.vector_dims_shape`. """ # Get shape : N.B. this calculates (and caches) the structure. @@ -157,15 +157,19 @@ def _convert_collation(collation): """Converts a FieldCollation into the corresponding items of Cube metadata. - Args: - - * collation: + Parameters + ---------- + collation : A FieldCollation object. - Returns: - A :class:`iris.fileformats.rules.ConversionMetadata` object. + Returns + ------- + A :class:`iris.fileformats.rules.ConversionMetadata` object. + Notes + ----- .. note: + This is the 'loader.converter', in the control structure passed to the generic rules code, :meth:`iris.fileformats.rules.load_cubes`. diff --git a/lib/iris/fileformats/um/_fast_load_structured_fields.py b/lib/iris/fileformats/um/_fast_load_structured_fields.py index 41ec8720bc..b1bbdf40b3 100644 --- a/lib/iris/fileformats/um/_fast_load_structured_fields.py +++ b/lib/iris/fileformats/um/_fast_load_structured_fields.py @@ -47,9 +47,9 @@ class BasicFieldCollation: def __init__(self, fields): """BasicFieldCollation initialise. - Args: - - * fields (iterable of :class:`iris.fileformats.pp.PPField`): + Parameters + ---------- + fields : iterable of :class:`iris.fileformats.pp.PPField` The fields in the collation. """ @@ -267,37 +267,39 @@ def group_structured_fields( """Collect structured fields into identified groups whose fields can be combined to form a single cube. - Args: - - * field_iterator (iterator of :class:`iris.fileformats.pp.PPField`): + Parameters + ---------- + field_iterator : iterator of :class:`iris.fileformats.pp.PPField` A source of PP or FF fields. N.B. order is significant. - - Kwargs: - - * collation_class (class): + collation_class : class, optional, default=BasicFieldCollation Type of collation wrapper to create from each group of fields. - * collation_kwargs (dict): + **collation_kwargs : dict Additional constructor keywords for collation creation. - The function sorts and collates on phenomenon-relevant metadata only, - defined as the field components: 'lbuser[3]' (stash), 'lbproc' (statistic), - 'lbuser[6]' (model). - Each distinct combination of these defines a specific phenomenon (or - statistical aggregation of one), and those fields appear as a single - iteration result. - Implicitly, within each result group, *all* other metadata components should be either: - * the same for all fields, - * completely irrelevant, or - * used by a vectorised rule function (such as - :func:`iris.fileformats.pp_load_rules._convert_time_coords`). + * the same for all fields, + * completely irrelevant, or + * used by a vectorised rule function (such as + :func:`iris.fileformats.pp_load_rules._convert_time_coords`). - Returns: + Returns + ------- + Generator of 'collation_class' objects A generator of 'collation_class' objects, each of which contains a single collated group from the input fields. + Notes + ----- + The function sorts and collates on phenomenon-relevant metadata only, + defined as the field components: 'lbuser[3]' (stash), 'lbproc' (statistic), + 'lbuser[6]' (model). + + Each distinct combination of these defines a specific phenomenon (or + statistical aggregation of one), and those fields appear as a single + iteration result. + .. note:: At present, fields with different values of 'lbuser[4]' (pseudo-level) diff --git a/lib/iris/fileformats/um/_ff_replacement.py b/lib/iris/fileformats/um/_ff_replacement.py index d726f63a10..d9a774b934 100644 --- a/lib/iris/fileformats/um/_ff_replacement.py +++ b/lib/iris/fileformats/um/_ff_replacement.py @@ -19,21 +19,22 @@ def um_to_pp(filename, read_data=False, word_depth=None): Returns an iterator over the fields contained within the FieldsFile, returned as :class:`iris.fileformats.pp.PPField` instances. - Args: - - * filename (string): + Parameters + ---------- + filename : str Specify the name of the FieldsFile. - - Kwargs: - - * read_data (boolean): + read_data : bool, optional, default=read_data Specify whether to read the associated PPField data within the FieldsFile. Default value is False. + word_depth : optional, default=None - Returns: - Iteration of :class:`iris.fileformats.pp.PPField`. + Returns + ------- + Iteration of :class:`iris.fileformats.pp.PPField`. - For example:: + Examples + -------- + :: >>> for field in um.um_to_pp(filename): ... print(field) @@ -52,15 +53,17 @@ def um_to_pp(filename, read_data=False, word_depth=None): def load_cubes(filenames, callback, constraints=None, _loader_kwargs=None): """Loads cubes from filenames of UM fieldsfile-like files. - Args: - - * filenames - list of filenames to load - - Kwargs: - - * callback - a function which can be passed on to - :func:`iris.io.run_callback` - + Parameters + ---------- + filenames : + list of filenames to load + callback : + A function which can be passed on to :func:`iris.io.run_callback` + constraints : optional, default=None + _loader_kwargs : optional, default=None + + Notes + ----- .. note:: The resultant cubes may not be in the order that they are in the @@ -81,9 +84,10 @@ def load_cubes_32bit_ieee(filenames, callback, constraints=None): """Loads cubes from filenames of 32bit ieee converted UM fieldsfile-like files. - .. seealso:: - - :func:`load_cubes` for keyword details + See Also + -------- + :func:`load_cubes` + For keyword details """ return load_cubes( diff --git a/lib/iris/fileformats/um/_optimal_array_structuring.py b/lib/iris/fileformats/um/_optimal_array_structuring.py index ce2cba7d5c..392edf9241 100644 --- a/lib/iris/fileformats/um/_optimal_array_structuring.py +++ b/lib/iris/fileformats/um/_optimal_array_structuring.py @@ -18,13 +18,12 @@ def _optimal_dimensioning_structure(structure, element_priorities): in more than one structure options then dimension priorities as specified by `element_priorities` are used to determine optimal structure. - Args: - - * structure: + Parameters + ---------- + structure : A set of structure options, as provided by :class:\ `~iris.fileformats._structured_array_identification.GroupStructure`. - - * element_priorities: + element_priorities : A dictionary mapping structure element names to their priority as defined by their input order to :func:`~optimal_array_structure`. @@ -52,37 +51,41 @@ def _optimal_dimensioning_structure(structure, element_priorities): def optimal_array_structure(ordering_elements, actual_values_elements=None): """Calculate an optimal array replication structure for a set of vectors. - Args: - - * ordering_elements (iterable of (name, 1-d array)): + Parameters + ---------- + ordering_elements : iterable of (name, 1-d array) Input element names and value-vectors. Must all be the same length (but not necessarily type). Must have at least one. - Kwargs: + .. note:: - * actual_values_elements (iterable of (name, 1-d array)): + The 'ordering_elements' arg contains the pattern used to deduce a + structure. The order of this is significant, in that earlier + elements get priority when associating dimensions with specific + elements. + + actual_values_elements : iterable of (name, 1-d array), optional, default=None The 'real' values used to construct the result arrays, if different from 'ordering_elements'. Must contain all the same names (but not necessarily in the same order). - The 'ordering_elements' arg contains the pattern used to deduce a - structure. The order of this is significant, in that earlier elements get - priority when associating dimensions with specific elements. - - Returns: - dims_shape, primary_elements, element_arrays_and_dims, where: - - * 'dims_shape' is the shape of the vector dimensions chosen. - - * 'primary_elements' is a set of dimension names; the names of input - elements that are identified as dimensions. At most one for each - dimension. - - * 'element_arrays_and_dims' is a dictionary [name: (array, dims)], - for all elements that are not dimensionless. Each array is reduced - to the shape of its mapped dimension. - - For example:: + + Returns + ------- + dims_shape + Shape of the vector dimensions chosen. + primary_elements + Set of dimension names; the names of input + elements that are identified as dimensions. At most one for each + dimension. + element_arrays_and_dims + A dictionary [name: (array, dims)], + for all elements that are not dimensionless. Each array is reduced + to the shape of its mapped dimension. + + Examples + -------- + :: >>> import iris.fileformats.um._optimal_array_structuring as optdims >>> elements_structure = [('a', np.array([1, 1, 1, 2, 2, 2])), diff --git a/lib/iris/iterate.py b/lib/iris/iterate.py index 41b3929464..12e619b79f 100644 --- a/lib/iris/iterate.py +++ b/lib/iris/iterate.py @@ -25,30 +25,28 @@ def izip(*cubes, **kwargs): resulting iterator will step through combinations of the associated coordinates. - Args: - - * cubes (:class:`iris.cube.Cube`): + Parameters + ---------- + cubes : :class:`iris.cube.Cube` One or more :class:`iris.cube.Cube` instances over which to iterate in step. Each cube should be provided as a separate argument e.g. ``iris.iterate.izip(cube_a, cube_b, cube_c, ...)``. - - Kwargs: - - * coords (string, coord or a list of strings/coords): + coords : str, coord or a list of strings/coords Coordinate names/coordinates of the desired subcubes (i.e. those that are not iterated over). They must all be orthogonal (i.e. point to different dimensions). - * ordered (Boolean): + ordered : bool, optional If True (default), the order of the coordinates in the resulting subcubes will match the order of the coordinates in the coords keyword argument. If False, the order of the coordinates will be preserved and will match that of the input cubes. - Returns: - An iterator over a collection of tuples that contain the resulting - subcubes. + Returns + ------- + An iterator over a collection of tuples that contain the resulting subcubes. - For example: + Examples + -------- >>> e_content, e_density = iris.load_cubes( ... iris.sample_data_path('space_weather.nc'), ... ['total electron content', 'electron density']) @@ -61,6 +59,7 @@ def izip(*cubes, **kwargs): ----- This function maintains laziness when called; it does not realise data. See more at :doc:`/userguide/real_and_lazy_data`. + """ if not cubes: raise TypeError("Expected one or more cubes.") diff --git a/lib/iris/palette.py b/lib/iris/palette.py index 3180f1e02a..95c8879b68 100644 --- a/lib/iris/palette.py +++ b/lib/iris/palette.py @@ -2,9 +2,10 @@ # # This file is part of Iris and is released under the BSD license. # See LICENSE in the root of the repository for full licensing details. -"""Load, configure and register color map palettes and initialise -color map meta-data mappings. +"""Color map pallettes management. +Load, configure and register color map palettes and initialise +color map meta-data mappings. """ from functools import wraps @@ -37,13 +38,14 @@ def is_brewer(cmap): """Determine whether the color map is a Cynthia Brewer color map. - Args: - - * cmap: + Parameters + ---------- + cmap : The color map instance. - Returns: - Boolean. + Returns + ------- + bool """ result = False @@ -53,8 +55,11 @@ def is_brewer(cmap): def _default_cmap_norm(args, kwargs): - """This function injects default cmap and norm behaviour into the keyword + """Injects default cmap and norm behaviour into the keyword arguments. + + This function injects default cmap and norm behaviour into the keyword arguments, based on the cube referenced within the positional arguments. + """ cube = None @@ -103,16 +108,20 @@ def _default_cmap_norm(args, kwargs): def cmap_norm(cube): - """Determine the default :class:`matplotlib.colors.LinearSegmentedColormap` + """Determine the default. + + Determine the default :class:`matplotlib.colors.LinearSegmentedColormap` and :class:`iris.palette.SymmetricNormalize` instances associated with the cube. - Args: - - * cube (:class:`iris.cube.Cube`): + Parameters + ---------- + cube : :class:`iris.cube.Cube` Source cube to generate default palette from. - Returns: + Returns + ------- + tuple Tuple of :class:`matplotlib.colors.LinearSegmentedColormap` and :class:`iris.palette.SymmetricNormalize` @@ -127,25 +136,25 @@ def cmap_norm(cube): def auto_palette(func): - """Decorator wrapper function to control the default behaviour of the + """Decorator wrapper function to control the default behaviour. + + Decorator wrapper function to control the default behaviour of the matplotlib cmap and norm keyword arguments. - Args: - - * func (callable): + Parameters + ---------- + func : callable Callable function to be wrapped by the decorator. - Returns: - Closure wrapper function. + Returns + ------- + Closure wrapper function. """ @wraps(func) def wrapper_func(*args, **kwargs): - """Closure wrapper function to provide default keyword argument - behaviour. - - """ + """Closure wrapper function to provide default keyword argument behaviour.""" # Update the keyword arguments with defaults. args, kwargs = _default_cmap_norm(args, kwargs) # Call the wrapped function and return its result. @@ -211,7 +220,9 @@ def vmax(self, val): def _load_palette(): - """Load, configure and register color map palettes and initialise + """Load pallette. + + Load, configure and register color map palettes and initialise color map metadata mappings. """ diff --git a/lib/iris/tests/__init__.py b/lib/iris/tests/__init__.py index 94c26ef45f..cd3a8adb16 100644 --- a/lib/iris/tests/__init__.py +++ b/lib/iris/tests/__init__.py @@ -155,14 +155,11 @@ def assert_masked_array_equal(a, b, strict=False): """Check that masked arrays are equal. This requires the unmasked values and masks to be identical. - Args: - - * a, b (array-like): + Parameters + ---------- + a, b : array-like Two arrays to compare. - - Kwargs: - - * strict (bool): + strict : bool, optional If True, perform a complete mask and data array equality check. If False (default), the data array equality considers only unmasked elements. @@ -176,19 +173,15 @@ def assert_masked_array_almost_equal(a, b, decimal=6, strict=False): masks to be identical, and the unmasked values to be almost equal. - Args: - - * a, b (array-like): + Parameters + ---------- + a, b : array-like Two arrays to compare. - - Kwargs: - - * strict (bool): + strict : bool, optional If True, perform a complete mask and data array equality check. If False (default), the data array equality considers only unmasked elements. - - * decimal (int): + decimal : int, optional, default=6 Equality tolerance level for :meth:`numpy.testing.assert_array_almost_equal`, with the meaning 'abs(desired-actual) < 0.5 * 10**(-decimal)' @@ -278,11 +271,12 @@ def result_path(self, basename=None, ext=""): """Return the full path to a test result, generated from the \ calling file, class and, optionally, method. - Optional kwargs : - - * basename - File basename. If omitted, this is \ - generated from the calling method. - * ext - Appended file extension. + Parameters + ---------- + basename : optional, default=None + File basename. If omitted, this is generated from the calling method. + ext : str, optional, default="" + Appended file extension. """ if ext and not ext.startswith("."): @@ -333,20 +327,16 @@ def assertCDL(self, netcdf_filename, reference_filename=None, flags="-h"): If the environment variable IRIS_TEST_CREATE_MISSING is non-empty, the reference file is created if it doesn't exist. - Args: - - * netcdf_filename: + Parameters + ---------- + netcdf_filename : The path to the netCDF file. - - Kwargs: - - * reference_filename: + reference_filename : optional, default=None The relative path (relative to the test results directory). If omitted, the result is generated from the calling method's name, class, and module using :meth:`iris.tests.IrisTest.result_path`. - - * flags: + flags : str, optional Command-line flags for `ncdump`, as either a whitespace separated string or an iterable. Defaults to '-h'. @@ -401,20 +391,16 @@ def assertCML(self, cubes, reference_filename=None, checksum=True): If the environment variable IRIS_TEST_CREATE_MISSING is non-empty, the reference file is created if it doesn't exist. - Args: - - * cubes: + Parameters + ---------- + cubes : Either a Cube or a sequence of Cubes. - - Kwargs: - - * reference_filename: + reference_filename : optional, default=None The relative path (relative to the test results directory). If omitted, the result is generated from the calling method's name, class, and module using :meth:`iris.tests.IrisTest.result_path`. - - * checksum: + checksum : bool, optional When True, causes the CML to include a checksum for each Cube's data. Defaults to True. @@ -514,14 +500,11 @@ def assertString(self, string, reference_filename=None): If the environment variable IRIS_TEST_CREATE_MISSING is non-empty, the reference file is created if it doesn't exist. - Args: - - * string: + Parameters + ---------- + string : str The string to check. - - Kwargs: - - * reference_filename: + reference_filename : optional, default=None The relative path (relative to the test results directory). If omitted, the result is generated from the calling method's name, class, and module using @@ -630,16 +613,15 @@ def assertArrayAlmostEqual(self, a, b, decimal=6): def assertArrayAllClose(self, a, b, rtol=1.0e-7, atol=1.0e-8, **kwargs): """Check arrays are equal, within given relative + absolute tolerances. - Args: - - * a, b (array-like): + Parameters + ---------- + a, b : array-like Two arrays to compare. - - Kwargs: - - * rtol, atol (float): + rtol, atol : float, optional Relative and absolute tolerances to apply. + Other Parameters + ---------------- Any additional kwargs are passed to numpy.testing.assert_allclose. Performs pointwise toleranced comparison, and raises an assertion if @@ -776,10 +758,13 @@ def patch(self, *args, **kwargs): The patch is created with mock.patch(*args, **kwargs). - Returns: - The substitute object returned by patch.start(). + Returns + ------- + The substitute object returned by patch.start(). - For example:: + Examples + -------- + :: mock_call = self.patch('module.Class.call', return_value=1) module_Class_instance.call(3, 4) diff --git a/lib/iris/tests/integration/test_netcdf__loadsaveattrs.py b/lib/iris/tests/integration/test_netcdf__loadsaveattrs.py index dcf61a947f..226babc9fb 100644 --- a/lib/iris/tests/integration/test_netcdf__loadsaveattrs.py +++ b/lib/iris/tests/integration/test_netcdf__loadsaveattrs.py @@ -4,7 +4,8 @@ # See LICENSE in the root of the repository for full licensing details. """Integration tests for loading and saving netcdf file attributes. -Notes: +Notes +----- (1) attributes in netCDF files can be either "global attributes", or variable ("local") type. @@ -178,6 +179,7 @@ def make_tempdir(self, tmp_path_factory): N.B. "tmp_path_factory" is a standard PyTest fixture, which provides a dirpath *shared* by all tests. This is a bit quicker and more debuggable than having a directory per-testcase. + """ # Store the temporary directory path on the test instance self.tmpdir = str(tmp_path_factory.getbasetemp()) @@ -220,6 +222,7 @@ def create_testcase_files_or_cubes( Note: 'var_values_file' args are dictionaries. The named variables are created, with an attribute = the dictionary value, *except* that a dictionary value of None means that a local attribute is _not_ created on the variable. + """ # save attribute on the instance self.attrname = attr_name @@ -307,6 +310,8 @@ def run_testcase( create_cubes_or_files : str, default "files" create either cubes or testfiles. + Notes + ----- If ``create_cubes_or_files`` == "files", create one temporary netCDF file per values-list, and record in ``self.input_filepaths``. Else if ``create_cubes_or_files`` == "cubes", create sets of cubes with common diff --git a/lib/iris/tests/stock/mesh.py b/lib/iris/tests/stock/mesh.py index aafd8b6c20..3520436f66 100644 --- a/lib/iris/tests/stock/mesh.py +++ b/lib/iris/tests/stock/mesh.py @@ -27,16 +27,17 @@ def sample_mesh(n_nodes=None, n_faces=None, n_edges=None, lazy_values=False): Mesh has nodes, plus faces and/or edges, with face-coords and edge-coords, numbers of which can be controlled. - Args: - * n_nodes (int or None): + Parameters + ---------- + n_nodes : int or None Number of nodes in mesh. Default is 15. Cannot be 0. - * n_edges (int or None): + n_edges : int or None Number of edges in mesh. Default is 5. If not 0, edge coords and an 'edge_node_connectivity' are included. - * n_faces (int or None): + n_faces : int or None Number of faces in mesh. Default is 3. If not 0, face coords and a 'face_node_connectivity' are included. - * lazy_values (bool): + lazy_values : bool, default=False If True, all content values of coords and connectivities are lazy. """ @@ -124,25 +125,34 @@ def sample_meshcoord(mesh=None, location="face", axis="x", **extra_kwargs): def sample_mesh_cube(nomesh_faces=None, n_z=2, with_parts=False, **meshcoord_kwargs): """Create a 2d test cube with 1 'normal' and 1 unstructured dimension (with a Mesh). - Result contains : dimcoords for both dims; an auxcoord on the unstructured dim; 2 mesh-coords. - By default, the mesh is provided by :func:`sample_mesh`, so coordinates and connectivity are not realistic. + Result contains : dimcoords for both dims; an auxcoord on the unstructured + dim; 2 mesh-coords. - Kwargs: - * nomesh_faces (int or None): + By default, the mesh is provided by :func:`sample_mesh`, so coordinates + and connectivity are not realistic. + + Parameters + ---------- + nomesh_faces : int or None, optional, default=None If set, don't add MeshCoords, so dim 1 is just a plain anonymous dim. Set its length to the given value. - * n_z (int): + n_z : int, optional, default=2 Length of the 'normal' dim. If 0, it is *omitted*. - * with_parts (bool): + with_parts : bool, optional, default=False If set, return all the constituent component coords - * meshcoord_kwargs (dict): - Extra controls passed to :func:`sample_meshcoord` for MeshCoord creation, to allow user-specified - location/mesh. The 'axis' key is not available, as we always add both an 'x' and 'y' MeshCOord. - - Returns: - * cube : if with_parts not set - * (cube, parts) : if with_parts is set - 'parts' is (mesh, dim0-dimcoord, dim1-dimcoord, dim1-auxcoord, x-meshcoord [or None], y-meshcoord [or None]). + **meshcoord_kwargs : dict, optional + Extra controls passed to :func:`sample_meshcoord` for MeshCoord + creation, to allow user-specified location/mesh. The 'axis' key is + not available, as we always add both an 'x' and 'y' MeshCOord. + + Returns + ------- + cube + if with_parts not set + (cube, parts) + if with_parts is set + 'parts' is (mesh, dim0-dimcoord, dim1-dimcoord, dim1-auxcoord, + x-meshcoord [or None], y-meshcoord [or None]). """ nomesh = nomesh_faces is not None diff --git a/lib/iris/tests/test_concatenate.py b/lib/iris/tests/test_concatenate.py index f08680c698..0d13b17cf3 100644 --- a/lib/iris/tests/test_concatenate.py +++ b/lib/iris/tests/test_concatenate.py @@ -35,48 +35,37 @@ def _make_cube( ): """A convenience test function that creates a custom 2D cube. - Args: - - * x: - A (start, stop, step) tuple for specifying the - x-axis dimensional coordinate points. Bounds are - automatically guessed. - - * y: - A (start, stop, step) tuple for specifying the - y-axis dimensional coordinate points. Bounds are - automatically guessed. - - * data: + Parameters + ---------- + x : + A (start, stop, step) tuple for specifying the x-axis dimensional + coordinate points. Bounds are automatically guessed. + y : + A (start, stop, step) tuple for specifying the y-axis dimensional + coordinate points. Bounds are automatically guessed. + data : The data payload for the cube. - - Kwargs: - - * aux: + aux : optional, default=None A CSV string specifying which points only auxiliary coordinates to create. Accepts either of 'x', 'y', 'xy'. - - * cell_measure: + cell_measure : optional, default=None A CSV string specifying which points only cell measures coordinates to create. Accepts either of 'x', 'y', 'xy'. - - * ancil: + ancil : optional, default=None A CSV string specifying which points only ancillary variables coordinates to create. Accepts either of 'x', 'y', 'xy'. - - * derived: + derived : optional, default=None A CSV string specifying which points only derived coordinates coordinates to create. Accepts either of 'x', 'y', 'xy'. - - * offset: + offset : int, optional, default=0 Offset value to be added to the 'xy' auxiliary coordinate points. - - * scalar: + scalar : optional, default=None Create a 'height' scalar coordinate with the given value. - Returns: - The newly created 2D :class:`iris.cube.Cube`. + Returns + ------- + The newly created 2D :class:`iris.cube.Cube`. """ x_range = np.arange(*x, dtype=np.float32) @@ -170,39 +159,30 @@ def _make_cube( def _make_cube_3d(x, y, z, data, aux=None, offset=0): """A convenience test function that creates a custom 3D cube. - Args: - - * x: - A (start, stop, step) tuple for specifying the - x-axis dimensional coordinate points. Bounds are - automatically guessed. - - * y: - A (start, stop, step) tuple for specifying the - y-axis dimensional coordinate points. Bounds are - automatically guessed. - - * z: - A (start, stop, step) tuple for specifying the - z-axis dimensional coordinate points. Bounds are - automatically guessed. - - * data: + Parameters + ---------- + x : + A (start, stop, step) tuple for specifying the x-axis dimensional + coordinate points. Bounds are automatically guessed. + y : + A (start, stop, step) tuple for specifying the y-axis dimensional + coordinate points. Bounds are automatically guessed. + z : + A (start, stop, step) tuple for specifying the z-axis dimensional + coordinate points. Bounds are automatically guessed. + data : The data payload for the cube. - - Kwargs: - - * aux: + aux : optional, default=None A CSV string specifying which points only auxiliary coordinates to create. Accepts either of 'x', 'y', 'z', 'xy', 'xz', 'yz', 'xyz'. - - * offset: + offset : int, optional, default=0 Offset value to be added to non-1D auxiliary coordinate points. Returns: - The newly created 3D :class:`iris.cube.Cube`. + ------- + The newly created 3D :class:`iris.cube.Cube`. """ x_range = np.arange(*x, dtype=np.float32) diff --git a/lib/iris/tests/test_cube_to_pp.py b/lib/iris/tests/test_cube_to_pp.py index 704e82539b..e75edee9cd 100644 --- a/lib/iris/tests/test_cube_to_pp.py +++ b/lib/iris/tests/test_cube_to_pp.py @@ -268,8 +268,10 @@ class FakePPEnvironment: def geog_cs(self): """Return a GeogCS for this PPField. - Returns: - A GeogCS with the appropriate earth shape, meridian and pole position. + Returns + ------- + A GeogCS with the appropriate earth shape, meridian and pole position. + """ return iris.coord_systems.GeogCS(6371229.0) diff --git a/lib/iris/tests/unit/fileformats/netcdf/saver/test_Saver__ugrid.py b/lib/iris/tests/unit/fileformats/netcdf/saver/test_Saver__ugrid.py index 070cdcaf8b..ba5e18d8d4 100644 --- a/lib/iris/tests/unit/fileformats/netcdf/saver/test_Saver__ugrid.py +++ b/lib/iris/tests/unit/fileformats/netcdf/saver/test_Saver__ugrid.py @@ -45,21 +45,20 @@ def build_mesh( Mesh has faces edges, face-coords and edge-coords, numbers of which can be controlled. - Args: - - * n_nodes, n_faces, n_edges (int): + Parameters + ---------- + n_nodes, n_faces, n_edges : int Basic dimensions of mesh components. Zero means no such location. - * nodecoord_xyargs, edgecoord_xyargs, facecoord_xyargs (pair of dict): + nodecoord_xyargs, edgecoord_xyargs, facecoord_xyargs : pair of dict Pairs (x,y) of settings kwargs, applied after initial creation the relevant location coordinates. - * conn_role_kwargs (dict of string:dict): + conn_role_kwargs : dict of str Mapping from cf_role name to settings kwargs for connectivities, applied after initially creating them. - * mesh_kwargs (dict): + mesh_kwargs : dict Dictionary of key settings to apply to the Mesh, after creating it. """ - def applyargs(coord, kwargs): if kwargs: for key, val in kwargs.items(): @@ -129,11 +128,11 @@ def apply_xyargs(coords, xyargs): def make_mesh(basic=True, **kwargs): """Create a test mesh, with some built-in 'standard' settings. - Kwargs: - - * basic (bool): + Parameters + ---------- + basic : bool If true (default), create with 'standard' set of test properties. - * kwargs (dict): + **kwargs : dict Additional kwargs, passed through to 'build_mesh'. Items here override the 'standard' settings. @@ -193,13 +192,13 @@ def default_mesh(): def make_cube(mesh=None, location="face", **kwargs): """Create a test cube, based on a given mesh + location. - Kwargs: - - * mesh (:class:`iris.experimental.ugrid.mesh.Mesh` or None): + Parameters + ---------- + mesh : :class:`iris.experimental.ugrid.mesh.Mesh` or None, optional If None, use 'default_mesh()' - * location (string): + location : str, optional, default="face" Which mesh element to map the cube to. - * kwargs (dict): + **kwargs : dict, optional Additional property settings to apply to the cube (after creation). """ @@ -234,15 +233,15 @@ def add_height_dim(cube): def scan_dataset(filepath): """Snapshot a netcdf dataset (the key metadata). - Returns: - dimsdict, varsdict - * dimsdict (dict): - A map of dimension-name: length. - * varsdict (dict): - A map of each variable's properties, {var_name: propsdict} - Each propsdict is {attribute-name: value} over the var's ncattrs(). - Each propsdict ALSO contains a [_VAR_DIMS] entry listing the - variable's dims. + Returns + ------- + dimsdict : dict + A map of dimension-name: length. + varsdict : dict + A map of each variable's properties, {var_name: propsdict} + Each propsdict is {attribute-name: value} over the var's ncattrs(). + Each propsdict ALSO contains a [_VAR_DIMS] entry listing the + variable's dims. """ ds = _thread_safe_nc.DatasetWrapper(filepath) @@ -299,19 +298,23 @@ def vars_meshnames(vars): def vars_meshdim(vars, location, mesh_name=None): """Extract a dim-name for a given element location. - Args: - * vars (varsdict): - file varsdict, as returned from 'snapshot_dataset'. - * location (string): - a mesh location : 'node' / 'edge' / 'face' - * mesh_name (string or None): - If given, identifies the mesh var. - Otherwise, find a unique mesh var (i.e. there must be exactly 1). + Parameters + ---------- + vars : varsdict + file varsdict, as returned from 'snapshot_dataset'. + location : string + a mesh location : 'node' / 'edge' / 'face' + mesh_name : str or None, optional, default=None + If given, identifies the mesh var. + Otherwise, find a unique mesh var (i.e. there must be exactly 1). Returns: - dim_name (string) - The dim-name of the mesh dim for the given location. + ------- + dim_name : str + The dim-name of the mesh dim for the given location. + Notes + ----- TODO: relies on the element having coordinates, which in future will not always be the case. This can be fixed diff --git a/lib/iris/util.py b/lib/iris/util.py index 59a171fa04..f612eb3d7e 100644 --- a/lib/iris/util.py +++ b/lib/iris/util.py @@ -34,15 +34,13 @@ def broadcast_to_shape(array, shape, dim_map): given shape. The result is a read-only view (see :func:`numpy.broadcast_to`). If you need to write to the resulting array, make a copy first. - Args: - - * array (:class:`numpy.ndarray`-like) + Parameters + ---------- + array : :class:`numpy.ndarray`-like An array to broadcast. - - * shape (:class:`list`, :class:`tuple` etc.): + shape : :class:`list`, :class:`tuple` etc The shape the array should be broadcast to. - - * dim_map (:class:`list`, :class:`tuple` etc.): + dim_map : :class:`list`, :class:`tuple` etc A mapping of the dimensions of *array* to their corresponding element in *shape*. *dim_map* must be the same length as the number of dimensions in *array*. Each element of *dim_map* @@ -101,15 +99,13 @@ def broadcast_to_shape(array, shape, dim_map): def delta(ndarray, dimension, circular=False): """Calculates the difference between values along a given dimension. - Args: - - * ndarray: + Parameters + ---------- + ndarray : The array over which to do the difference. - - * dimension: + dimension : The dimension over which to do the difference on ndarray. - - * circular: + circular : bool, optional, default=False If not False then return n results in the requested dimension with the delta between the last and first element included in the result otherwise the result will be of length n-1 (where n @@ -125,6 +121,8 @@ def delta(ndarray, dimension, circular=False): original array -180, -90, 0, 90 delta (with circular=360): 90, 90, 90, -270+360 + Notes + ----- .. note:: The difference algorithm implemented is forward difference: @@ -137,10 +135,10 @@ def delta(ndarray, dimension, circular=False): >>> iris.util.delta(original, 0, circular=360) array([90, 90, 90, 90]) - Notes - ----- - This function maintains laziness when called; it does not realise data. - See more at :doc:`/userguide/real_and_lazy_data`. + .. note:: + + This function maintains laziness when called; it does not realise data. + See more at :doc:`/userguide/real_and_lazy_data`. """ if circular is not False: @@ -165,23 +163,22 @@ def describe_diff(cube_a, cube_b, output_file=None): """Prints the differences that prevent compatibility between two cubes, as defined by :meth:`iris.cube.Cube.is_compatible()`. - Args: - - * cube_a: + Parameters + ---------- + cube_a : An instance of :class:`iris.cube.Cube` or :class:`iris.cube.CubeMetadata`. - - * cube_b: + cube_b : An instance of :class:`iris.cube.Cube` or :class:`iris.cube.CubeMetadata`. - - * output_file: + output_file : A :class:`file` or file-like object to receive output. Defaults to sys.stdout. - - .. seealso:: - - :meth:`iris.cube.Cube.is_compatible()` + + Notes + ----- + This function maintains laziness when called; it does not realise data. + See more at :doc:`/userguide/real_and_lazy_data`. .. note:: @@ -191,11 +188,10 @@ def describe_diff(cube_a, cube_b, output_file=None): two cubes will merge requires additional logic that is beyond the scope of this function. - Notes - ----- - This function maintains laziness when called; it does not realise data. - See more at :doc:`/userguide/real_and_lazy_data`. - + See Also + -------- + :meth:`iris.cube.Cube.is_compatible()` + """ if output_file is None: @@ -239,21 +235,22 @@ def guess_coord_axis(coord): Heuristic categorisation of the coordinate into either label 'T', 'Z', 'Y', 'X' or None. - Args: - - * coord: + Parameters + ---------- + coord : The :class:`iris.coords.Coord`. - Returns: - 'T', 'Z', 'Y', 'X', or None. + Returns + ------- + {'T', 'Z', 'Y', 'X'} or None. Notes ----- This function maintains laziness when called; it does not realise data. See more at :doc:`/userguide/real_and_lazy_data`. - The ``guess_coord_axis`` behaviour can be skipped by setting the coordinate property ``ignore_axis`` - to ``False``. + The ``guess_coord_axis`` behaviour can be skipped by setting the coordinate + property ``ignore_axis`` to ``False``. """ @@ -288,25 +285,26 @@ def guess_coord_axis(coord): def rolling_window(a, window=1, step=1, axis=-1): """Make an ndarray with a rolling window of the last dimension. - Args: - - * a : array_like + Parameters + ---------- + a : array_like Array to add rolling window to - - Kwargs: - - * window : int + window : int, optional Size of rolling window - * step : int + step : int, optional Size of step between rolling windows - * axis : int + axis : int, optional Axis to take the rolling window over - Returns: + Returns + ------- + array Array that is a view of the original array with an added dimension of the size of the given window at axis + 1. - Examples:: + Examples + -------- + :: >>> x = np.arange(10).reshape((2, 5)) >>> rolling_window(x, 3) @@ -359,24 +357,21 @@ def rolling_window(a, window=1, step=1, axis=-1): def array_equal(array1, array2, withnans=False): """Returns whether two arrays have the same shape and elements. - Args: - - * array1, array2 (arraylike): + Parameters + ---------- + array1, array2 : arraylike args to be compared, normalised if necessary with :func:`np.asarray`. - - Kwargs: - - * withnans (bool): + withnans : bool, optional, default=False When unset (default), the result is False if either input contains NaN points. This is the normal floating-point arithmetic result. When set, return True if inputs contain the same value in all elements, - _including_ any NaN values. + _including_ any NaN values. + Notes + ----- This provides much the same functionality as :func:`numpy.array_equal`, but with additional support for arrays of strings and NaN-tolerant operation. - Notes - ----- This function maintains laziness when called; it does not realise data. See more at :doc:`/userguide/real_and_lazy_data`. """ @@ -436,23 +431,21 @@ def between(lh, rh, lh_inclusive=True, rh_inclusive=True): """Provides a convenient way of defining a 3 element inequality such as ``a < number < b``. - Arguments: - - * lh + Parameters + ---------- + lh : The left hand element of the inequality - * rh + rh : The right hand element of the inequality - - Keywords: - - * lh_inclusive - boolean + lh_inclusive : bool, optional Affects the left hand comparison operator to use in the inequality. True for ``<=`` false for ``<``. Defaults to True. - * rh_inclusive - boolean + rh_inclusive : bool, default=True Same as lh_inclusive but for right hand operator. - - For example:: + Examples + -------- + :: between_3_and_6 = between(3, 6) for i in range(10): @@ -482,16 +475,18 @@ def between(lh, rh, lh_inclusive=True, rh_inclusive=True): def reverse(cube_or_array, coords_or_dims): """Reverse the cube or array along the given dimensions. - Args: - - * cube_or_array: :class:`iris.cube.Cube` or :class:`numpy.ndarray` + Parameters + ---------- + cube_or_array : :class:`iris.cube.Cube` or :class:`numpy.ndarray` The cube or array to reverse. - * coords_or_dims: int, str, :class:`iris.coords.Coord` or sequence of these + coords_or_dims : int, str, :class:`iris.coords.Coord` or sequence of these Identify one or more dimensions to reverse. If cube_or_array is a numpy array, use int or a sequence of ints, as in the examples below. If cube_or_array is a Cube, a Coord or coordinate name (or sequence of these) may be specified instead. + Examples + -------- :: >>> import numpy as np @@ -579,11 +574,11 @@ def monotonic(array, strict=False, return_direction=False): Note that, the array must not contain missing data. - Kwargs: - - * strict (boolean) + Parameters + ---------- + strict : boolean, optional, default=False Flag to enable strict monotonic checking - * return_direction (boolean) + return_direction : bool, optional, default=False Flag to change return behaviour to return (monotonic_status, direction). Direction will be 1 for positive or -1 for negative. The direction is meaningless if the array is @@ -777,27 +772,27 @@ def _build_full_slice_given_keys(keys, ndim): def _slice_data_with_keys(data, keys): """Index an array-like object as "data[keys]", with orthogonal indexing. - Args: - - * data (array-like): + Parameters + ---------- + data : array-like array to index. - - * keys (list): + keys : list list of indexes, as received from a __getitem__ call. - This enforces an orthogonal interpretation of indexing, which means that - both 'real' (numpy) arrays and other array-likes index in the same way, - instead of numpy arrays doing 'fancy indexing'. - - Returns (dim_map, data_region), where : - - * dim_map (dict) : + Returns + ------- + dim_map : dict A dimension map, as returned by :func:`column_slices_generator`. i.e. "dim_map[old_dim_index]" --> "new_dim_index" or None. - - * data_region (array-like) : + data_region : array-like The sub-array. + Notes + ----- + This enforces an orthogonal interpretation of indexing, which means that + both 'real' (numpy) arrays and other array-likes index in the same way, + instead of numpy arrays doing 'fancy indexing'. + .. Note:: Avoids copying the data, where possible. @@ -987,9 +982,10 @@ def __lt__(self, other): def create_temp_filename(suffix=""): """Return a temporary file name. - Args: - - * suffix - Optional filename extension. + Parameters + ---------- + suffix : str, optional, default="" + Filename extension. """ temp_file = tempfile.mkstemp(suffix) @@ -1010,19 +1006,21 @@ def clip_string(the_str, clip_length=70, rider="..."): rider is added. If no graceful point can be found, then the string is clipped exactly where the user requested and the rider is added. - Args: - - * the_str + Parameters + ---------- + the_str : str The string to be clipped - * clip_length + clip_length : The length in characters that the input string should be clipped to. Defaults to a preconfigured value if not specified. - * rider + rider : str, optional, default="..." A series of characters appended at the end of the returned string to show it has been clipped. Defaults to a preconfigured value if not specified. - Returns: + Returns + ------- + str The string clipped to the required length with a rider appended. If the clip length was greater than the original string, the original string is returned unaltered. @@ -1083,28 +1081,28 @@ def new_axis(src_cube, scalar_coord=None, expand_extras=()): # maybe not lazy """Create a new axis as the leading dimension of the cube, promoting a scalar coordinate if specified. - Args: - - * src_cube (:class:`iris.cube.Cube`) + Parameters + ---------- + src_cube : :class:`iris.cube.Cube` Source cube on which to generate a new axis. - - Kwargs: - - * scalar_coord (:class:`iris.coord.Coord` or 'string') + scalar_coord : :class:`iris.coord.Coord` or 'string', optional, default=None Scalar coordinate to promote to a dimension coordinate. - - * expand_extras (iterable) + expand_extras : iterable, optional Auxiliary coordinates, ancillary variables and cell measures which will be expanded so that they map to the new dimension as well as the existing dimensions. - Returns: + Returns + ------- + :class:`iris.cube.Cube` A new :class:`iris.cube.Cube` instance with one extra leading dimension (length 1). Chosen auxiliary coordinates, cell measures and ancillary variables will also be given an additional dimension, associated with the leading dimension of the cube. - For example:: + Examples + -------- + :: >>> cube.shape (360, 360) @@ -1207,15 +1205,19 @@ def squeeze(cube): """Removes any dimension of length one. If it has an associated DimCoord or AuxCoord, this becomes a scalar coord. - Args: - - * cube (:class:`iris.cube.Cube`) + Parameters + ---------- + cube : :class:`iris.cube.Cube` Source cube to remove length 1 dimension(s) from. - Returns: + Returns + ------- + :class:`iris.cube.Cube` A new :class:`iris.cube.Cube` instance without any dimensions of length 1. + Examples + -------- For example:: >>> cube.shape @@ -1246,21 +1248,24 @@ def file_is_newer_than(result_path, source_paths): re-built when one of them changes. This function can be used to test that by comparing file timestamps. - Args: - - * result_path (string): + Parameters + ---------- + result_path : str The filepath of a file containing some derived result data. - * source_paths (string or iterable of strings): + source_paths : str or iterable of str The path(s) to the original datafiles used to make the result. May include wildcards and '~' expansions (like Iris load paths), but not URIs. - Returns: + Returns + ------- + bool True if all the sources are older than the result, else False. - If any of the file paths describes no existing files, an exception will be raised. + Notes + ----- .. note:: There are obvious caveats to using file timestamps for this, as correct usage depends on how the sources might change. For example, a file @@ -1373,8 +1378,8 @@ def points_step(points): Returns ------- numeric, bool - A tuple containing the average difference between values, and whether the difference is regular. - + A tuple containing the average difference between values, and whether + the difference is regular. Notes ----- @@ -1404,9 +1409,9 @@ def unify_time_units(cubes): Each epoch is defined from the first suitable time coordinate found in the input cubes. - Arg: - - * cubes: + Parameters + ---------- + cubes : An iterable containing :class:`iris.cube.Cube` instances. Notes @@ -1437,21 +1442,18 @@ def _is_circular(points, modulus, bounds=None): If the bounds are provided then these are checked for circularity rather than the points. - Args: - - * points: + Parameters + ---------- + points : :class:`numpy.ndarray` :class:`numpy.ndarray` of point values. - - * modulus: + modulus : Circularity modulus value. - - Kwargs: - - * bounds: + bounds : :class:`numpy.ndarray`, optional :class:`numpy.ndarray` of bound values. - Returns: - Boolean. + Returns + ------- + bool """ circular = False @@ -1503,24 +1505,20 @@ def promote_aux_coord_to_dim_coord(cube, name_or_coord): with a dimension that already has a DimCoord, that DimCoord gets demoted to an AuxCoord. - Args: - - * cube + Parameters + ---------- + cube : An instance of :class:`iris.cube.Cube` + name_or_coord : + Either: TREMTEST: indent looks weird - * name_or_coord: - Either - - (a) An instance of :class:`iris.coords.AuxCoord` - - or - - (b) the :attr:`standard_name`, :attr:`long_name`, or - :attr:`var_name` of an instance of an instance of - :class:`iris.coords.AuxCoord`. - - For example, + * (a) An instance of :class:`iris.coords.AuxCoord` + * (b) the :attr:`standard_name`, :attr:`long_name`, or + :attr:`var_name` of an instance of an instance of + :class:`iris.coords.AuxCoord`. + Examples + -------- .. testsetup:: promote import iris @@ -1560,7 +1558,6 @@ def promote_aux_coord_to_dim_coord(cube, name_or_coord): This function maintains laziness when called; it does not realise data. See more at :doc:`/userguide/real_and_lazy_data`. - """ from iris.coords import Coord, DimCoord @@ -1632,24 +1629,20 @@ def demote_dim_coord_to_aux_coord(cube, name_or_coord): anonymous. The class of the coordinate is left as DimCoord, it is not recast as an AuxCoord instance. - Args: - - * cube + Parameters + ---------- + cube : An instance of :class:`iris.cube.Cube` + name_or_coord : + Either: TREMTEST: indent looks weird - * name_or_coord: - Either - - (a) An instance of :class:`iris.coords.DimCoord` - - or - - (b) the :attr:`standard_name`, :attr:`long_name`, or - :attr:`var_name` of an instance of an instance of - :class:`iris.coords.DimCoord`. - - For example, + * (a) An instance of :class:`iris.coords.DimCoord` + * (b) the :attr:`standard_name`, :attr:`long_name`, or + :attr:`var_name` of an instance of an instance of + :class:`iris.coords.DimCoord`. + Examples + -------- .. testsetup:: demote import iris @@ -1742,19 +1735,15 @@ def find_discontiguities(cube, rel_tol=1e-5, abs_tol=1e-8): bounds array, returned as a boolean array (True for all cells which are discontiguous with the cell immediately above them or to their right). - Args: - - * cube (`iris.cube.Cube`): + Parameters + ---------- + cube : `iris.cube.Cube` The cube to be checked for discontinuities in its 'x' and 'y' coordinates. These coordinates must be 2D. - - Kwargs: - - * rel_tol (float): + rel_tol : float, optional, default=1e-5 The relative equality tolerance to apply in coordinate bounds checking. - - * abs_tol (float): + abs_tol : float, optional, default=1e-8 The absolute value tolerance to apply in coordinate bounds checking. @@ -1899,15 +1888,16 @@ def mask_cube(cube, points_to_mask, in_place=False, dim=None): Cube containing data that requires masking. points_to_mask : numpy.ndarray, dask.array.Array, iris.coords.Coord or iris.cube.Cube - Specifies booleans (or ones and zeros) indicating which points will be masked. + Specifies booleans (or ones and zeros) indicating which points will + be masked. in_place : bool, default=False - If `True`, masking is applied to the input cube. Otherwise a copy is masked - and returned. + If `True`, masking is applied to the input cube. Otherwise a copy is + masked and returned. dim : int, optional - If `points_to_mask` is a coord which does not exist on the cube, specify the - dimension to which it should be mapped. + If `points_to_mask` is a coord which does not exist on the cube, + specify the dimension to which it should be mapped. Returns ------- @@ -1957,9 +1947,9 @@ def equalise_attributes(cubes): given cubes. The cubes will then have identical attributes, and the removed attributes are returned. The given cubes are modified in-place. - Args: - - * cubes (iterable of :class:`iris.cube.Cube`): + Parameters + ---------- + cubes : iterable of :class:`iris.cube.Cube` A collection of cubes to compare and adjust. Returns From 1c5cb4be4bad12760e5f410ef976fe27d19b94db Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 26 Dec 2023 13:16:18 +0000 Subject: [PATCH 03/21] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- .../documenting/docstrings_attribute.py | 2 +- lib/iris/_concatenate.py | 4 +-- lib/iris/_data_manager.py | 2 +- lib/iris/analysis/_regrid.py | 4 +-- lib/iris/analysis/cartography.py | 24 ++++++++--------- lib/iris/analysis/maths.py | 2 +- lib/iris/analysis/trajectory.py | 8 +++--- lib/iris/common/lenient.py | 1 + lib/iris/common/resolve.py | 4 +-- lib/iris/coords.py | 18 ++++++------- lib/iris/cube.py | 26 +++++++++---------- lib/iris/experimental/ugrid/mesh.py | 4 +-- lib/iris/fileformats/_ff.py | 2 +- lib/iris/fileformats/name_loaders.py | 6 ++--- lib/iris/fileformats/nimrod.py | 2 +- lib/iris/fileformats/rules.py | 2 +- lib/iris/fileformats/um/_fast_load.py | 2 +- .../um/_fast_load_structured_fields.py | 4 +-- lib/iris/fileformats/um/_ff_replacement.py | 4 +-- lib/iris/palette.py | 4 +-- lib/iris/tests/__init__.py | 2 +- .../netcdf/saver/test_Saver__ugrid.py | 1 + lib/iris/util.py | 12 ++++----- 23 files changed, 70 insertions(+), 70 deletions(-) diff --git a/docs/src/developers_guide/documenting/docstrings_attribute.py b/docs/src/developers_guide/documenting/docstrings_attribute.py index 61c29b71b0..89a0f42c31 100644 --- a/docs/src/developers_guide/documenting/docstrings_attribute.py +++ b/docs/src/developers_guide/documenting/docstrings_attribute.py @@ -5,7 +5,7 @@ def __init__(self, arg1, arg2): """Purpose section description. TREMTEST where is this used? - + Description section text. Parameters diff --git a/lib/iris/_concatenate.py b/lib/iris/_concatenate.py index fcb72489bd..6a097b8963 100644 --- a/lib/iris/_concatenate.py +++ b/lib/iris/_concatenate.py @@ -668,8 +668,8 @@ def candidate_axis(self, other): Returns ------- - result : - None if no single candidate axis exists, otherwise the candidate + result : + None if no single candidate axis exists, otherwise the candidate axis of concatenation. """ diff --git a/lib/iris/_data_manager.py b/lib/iris/_data_manager.py index 527f9920d1..286c3abefb 100644 --- a/lib/iris/_data_manager.py +++ b/lib/iris/_data_manager.py @@ -22,7 +22,7 @@ def __init__(self, data): Parameters ---------- - data : + data : The :class:`~numpy.ndarray` or :class:`~numpy.ma.core.MaskedArray` real data, or :class:`~dask.array.core.Array` lazy data to be managed. diff --git a/lib/iris/analysis/_regrid.py b/lib/iris/analysis/_regrid.py index 5f339ea4ca..3beada7131 100644 --- a/lib/iris/analysis/_regrid.py +++ b/lib/iris/analysis/_regrid.py @@ -611,7 +611,7 @@ def _regrid( If the result is a MaskedArray the mask for each element will be set if either/both of: - + * there is a non-zero contribution from masked items in the input data * the element requires extrapolation and the extrapolation_mode dictates a masked value. @@ -969,7 +969,7 @@ def regrid_callback(*args, **kwargs): def _create_cube(data, src, src_dims, tgt_coords, num_tgt_dims, regrid_callback): r"""Return a new cube for the result of regridding. - + Returned cube represents the result of regridding the source cube onto the horizontal coordinates (e.g. latitude) of the target cube. All the metadata and coordinates of the result cube are copied from diff --git a/lib/iris/analysis/cartography.py b/lib/iris/analysis/cartography.py index 219e9c7557..d16f395214 100644 --- a/lib/iris/analysis/cartography.py +++ b/lib/iris/analysis/cartography.py @@ -57,9 +57,9 @@ def wrap_lons(lons, base, period): Parameters ---------- - lons : - base : - period : + lons : + base : + period : Examples -------- @@ -118,7 +118,7 @@ def unrotate_pole(rotated_lons, rotated_lats, pole_lon, pole_lat): :: lons, lats = unrotate_pole(rotated_lons, rotated_lats, pole_lon, pole_lat) - + """ src_proj = ccrs.RotatedGeodetic(pole_longitude=pole_lon, pole_latitude=pole_lat) target_proj = ccrs.Geodetic() @@ -199,7 +199,7 @@ def _xy_range(cube, mode=None): Parameters ---------- - cube : + cube : The cube for which to calculate xy extents. mode : optional, default=None If the coordinate has bounds, set this to specify the @@ -262,7 +262,7 @@ def get_xy_grids(cube): Parameters ---------- - cube : + cube : The cube for which to generate 2D X and Y points. Examples @@ -341,11 +341,11 @@ def _quadrant_area(radian_lat_bounds, radian_lon_bounds, radius_of_earth): Parameters ---------- - radian_lat_bounds : + radian_lat_bounds : [n,2] array of latitude bounds (radians) - radian_lon_bounds : + radian_lon_bounds : [n,2] array of longitude bounds (radians) - radius_of_earth : + radius_of_earth : radius of the earth (currently assumed spherical) """ @@ -387,7 +387,7 @@ def area_weights(cube, normalize=False): Currently, only supports a spherical datum. Uses earth radius from the cube, if present and spherical. - Defaults to iris.analysis.cartography.DEFAULT_SPHERICAL_EARTH_RADIUS. + Defaults to iris.analysis.cartography.DEFAULT_SPHERICAL_EARTH_RADIUS. Parameters ---------- @@ -399,7 +399,7 @@ def area_weights(cube, normalize=False): Returns ------- - broad_weights : + broad_weights : """ # Get the radius of the earth @@ -511,7 +511,7 @@ def cosine_latitude_weights(cube): Parameters ---------- cube : :class:`iris.cube.Cube` - + Examples -------- Compute weights suitable for averaging type operations:: diff --git a/lib/iris/analysis/maths.py b/lib/iris/analysis/maths.py index c35b0e6d70..36a34c0beb 100644 --- a/lib/iris/analysis/maths.py +++ b/lib/iris/analysis/maths.py @@ -592,7 +592,7 @@ def exp(cube, in_place=False): Notes ----- Taking an exponential will return a cube with dimensionless units. - + This function maintains laziness when called; it does not realise data. See more at :doc:`/userguide/real_and_lazy_data`. diff --git a/lib/iris/analysis/trajectory.py b/lib/iris/analysis/trajectory.py index 8c3be237f7..88b1b69ba0 100644 --- a/lib/iris/analysis/trajectory.py +++ b/lib/iris/analysis/trajectory.py @@ -59,7 +59,7 @@ def __init__(self, waypoints, sample_count=10): .. note:: All the waypoint dictionaries must contain the same coordinate names. - + """ self.waypoints = waypoints self.sample_count = sample_count @@ -486,10 +486,10 @@ def _cartesian_sample_points(sample_points, sample_point_coord_names): Parameters ---------- - sample_points : + sample_points : [coord][datum] list of sample_positions for each datum, formatted for fast use of :func:`_ll_to_cart()`. - sample_point_coord_names : + sample_point_coord_names : [coord] list of n coord names Returns @@ -731,7 +731,7 @@ def __init__(self, src_cube, target_grid_cube): ------- regridder (object) A callable object with the interface:: - + result_cube = regridder(data) where `data` is a cube with the same grid as the original diff --git a/lib/iris/common/lenient.py b/lib/iris/common/lenient.py index bece97835e..ed75189d47 100644 --- a/lib/iris/common/lenient.py +++ b/lib/iris/common/lenient.py @@ -297,6 +297,7 @@ def context(self, **kwargs): pass """ + def configure_state(state): for feature, value in state.items(): self[feature] = value diff --git a/lib/iris/common/resolve.py b/lib/iris/common/resolve.py index ea0d67e110..3885a94a14 100644 --- a/lib/iris/common/resolve.py +++ b/lib/iris/common/resolve.py @@ -1525,10 +1525,10 @@ def _prepare_common_dim_payload( Parameters ---------- src_coverage : - The :class:`~iris.common.resolve._DimCoverage` metadata for the + The :class:`~iris.common.resolve._DimCoverage` metadata for the ``src`` :class:`~iris.cube.Cube`. tgt_coverage : - The :class:`~iris.common.resolve._DimCoverage` metadata for the + The :class:`~iris.common.resolve._DimCoverage` metadata for the ``tgt`` :class:`~iris.cube.Cube`. ignore_mismatch : optional When ``False``, an exception will be raised if a difference is detected between corresponding diff --git a/lib/iris/coords.py b/lib/iris/coords.py index b08e61ac02..993d2a27a7 100644 --- a/lib/iris/coords.py +++ b/lib/iris/coords.py @@ -70,7 +70,7 @@ def __init__( attributes=None, ): """Constructs a single dimensional metadata object. - + Parameters ---------- values : @@ -287,7 +287,7 @@ def summary( linewidth : int or None, default = None Character-width controlling line splitting of array outputs. If unset, defaults to ``numpy.get_printoptions['linewidth']``\ . - edgeitems : int, default=2 + edgeitems : int, default=2 Controls truncated array output. Overrides ``numpy.getprintoptions['edgeitems']``\ . precision : int or None, default = None @@ -1468,7 +1468,7 @@ def __init__( climatological=False, ): """Coordinate abstract base class. - + As of ``v3.0.0`` you **cannot** create an instance of :class:`Coord`. Parameters @@ -1536,11 +1536,11 @@ def __init__( def copy(self, points=None, bounds=None): """Returns a copy of this coordinate. - points : + points : A points array for the new coordinate. This may be a different shape to the points of the coordinate being copied. - bounds : + bounds : A bounds array for the new coordinate. Given n bounds for each cell, the shape of the bounds array should be points.shape + (n,). For example, a 1d coordinate @@ -1548,7 +1548,7 @@ def copy(self, points=None, bounds=None): array of shape (100, 2). Notes - ----- + ----- .. note:: If the points argument is specified and bounds are not, the resulting coordinate will have no bounds. @@ -2489,7 +2489,7 @@ def _xml_id_extra(self, unique_value): class DimCoord(Coord): """A coordinate that is 1D, and numeric. - + With values that have a strict monotonic ordering. Missing values are not permitted in a :class:`DimCoord`. @@ -2706,7 +2706,7 @@ def _new_points_requirements(self, points): Confirm that a new set of coord points adheres to the requirements for :class:`~iris.coords.DimCoord` points, being: - + * points are scalar or 1D, * points are numeric, * points are not masked, and @@ -3034,7 +3034,7 @@ def xml_element(self, doc): Returns ------- - :class:`xml.dom.minidom.Element` + :class:`xml.dom.minidom.Element` The :class:`xml.dom.minidom.Element` that describes this :class:`CellMethod`. diff --git a/lib/iris/cube.py b/lib/iris/cube.py index 9944a9a912..7a563f8f6a 100644 --- a/lib/iris/cube.py +++ b/lib/iris/cube.py @@ -1204,7 +1204,7 @@ def __init__( Parameters ---------- - data : + data : This object defines the shape of the cube and the phenomenon value in each cell. @@ -1478,7 +1478,7 @@ def add_aux_coord(self, coord, data_dims=None): Parameters ---------- - coord : + coord : The :class:`iris.coords.DimCoord` or :class:`iris.coords.AuxCoord` instance to add to the cube. data_dims : optional, default=None @@ -1587,7 +1587,7 @@ def add_aux_factory(self, aux_factory): Parameters ---------- - aux_factory : + aux_factory : The :class:`iris.aux_factory.AuxCoordFactory` instance to add. """ @@ -1619,7 +1619,7 @@ def add_cell_measure(self, cell_measure, data_dims=None): Parameters ---------- - cell_measure : + cell_measure : The :class:`iris.coords.CellMeasure` instance to add to the cube. data_dims : optional, default=None @@ -1652,7 +1652,7 @@ def add_ancillary_variable(self, ancillary_variable, data_dims=None): Parameters ---------- - ancillary_variable : + ancillary_variable : The :class:`iris.coords.AncillaryVariable` instance to be added to the cube data_dims : optional, default=None @@ -1684,7 +1684,7 @@ def add_dim_coord(self, dim_coord, data_dim): ---------- dim_coord : :class:`iris.coords.DimCoord` The :class:`iris.coords.DimCoord` instance to add to the cube. - data_dim : + data_dim : Integer giving the data dimension spanned by the coordinate. Raises @@ -1920,7 +1920,7 @@ def cell_measure_dims(self, cell_measure): CellMeasure. Parameters - ---------- + ---------- cell_measure : str or CellMeasure The (name of the) cell measure to look for. @@ -1943,7 +1943,7 @@ def ancillary_variable_dims(self, ancillary_variable): AncillaryVariable. Parameters - ---------- + ---------- ancillary_variable : str or AncillaryVariable The (name of the) AncillaryVariable to look for. @@ -2100,12 +2100,12 @@ def coords( Returns ------- A list containing zero or more coordinates matching the provided criteria. - + See Also -------- :meth:`Cube.coord` for matching exactly one coordinate. - + """ coords_and_factories = [] @@ -2263,7 +2263,7 @@ def coord( .. note:: If the arguments given do not result in **precisely one** coordinate, - then a :class:`~iris.exceptions.CoordinateNotFoundError` is raised. + then a :class:`~iris.exceptions.CoordinateNotFoundError` is raised. See Also -------- @@ -2984,9 +2984,7 @@ def subset(self, coord): return result def extract(self, constraint): - """Filter cube by the given constraint using :meth:`iris.Constraint.extract`. - - """ + """Filter cube by the given constraint using :meth:`iris.Constraint.extract`.""" # Cast the constraint into a proper constraint if it is not so already constraint = iris._constraints.as_constraint(constraint) return constraint.extract(self) diff --git a/lib/iris/experimental/ugrid/mesh.py b/lib/iris/experimental/ugrid/mesh.py index 6325c41572..dfd0d74552 100644 --- a/lib/iris/experimental/ugrid/mesh.py +++ b/lib/iris/experimental/ugrid/mesh.py @@ -297,7 +297,7 @@ def indices_by_location(self, indices=None): the first axis - transposed if necessary. Can optionally pass in an identically shaped array on which to perform this operation (e.g. the output from :meth:`core_indices` or :meth:`lazy_indices`). - + Parameters ---------- indices : array @@ -306,7 +306,7 @@ def indices_by_location(self, indices=None): Returns ------- - result : + result : A view of the indices array Transposed - if necessary - to put :attr:`location_axis` first. diff --git a/lib/iris/fileformats/_ff.py b/lib/iris/fileformats/_ff.py index dfc05f014d..e0a1064b98 100644 --- a/lib/iris/fileformats/_ff.py +++ b/lib/iris/fileformats/_ff.py @@ -869,7 +869,7 @@ def load_cubes_32bit_ieee(filenames, callback, constraints=None): See Also -------- - :func:`load_cubes` + :func:`load_cubes` For keyword details """ diff --git a/lib/iris/fileformats/name_loaders.py b/lib/iris/fileformats/name_loaders.py index 66dcf8c422..3f4b2d13c6 100644 --- a/lib/iris/fileformats/name_loaders.py +++ b/lib/iris/fileformats/name_loaders.py @@ -779,7 +779,7 @@ def load_NAMEIII_timeseries(filename): """Load a NAME III time series file. Load a NAME III time series file returning a generator of - :class:`iris.cube.Cube` instances. + :class:`iris.cube.Cube` instances. Parameters ---------- @@ -868,7 +868,7 @@ def load_NAMEIII_timeseries(filename): def load_NAMEII_timeseries(filename): """Load a NAME III time series file. - + Load a NAME II Time Series file returning a generator of :class:`iris.cube.Cube` instances. @@ -1163,7 +1163,7 @@ def load_NAMEIII_version2(filename): def load_NAMEIII_trajectory(filename): """Load a NAME III trajectory file. - + Load a NAME III trajectory file returning a generator of :class:`iris.cube.Cube` instances. diff --git a/lib/iris/fileformats/nimrod.py b/lib/iris/fileformats/nimrod.py index 54c09c91ab..8cf109eed5 100644 --- a/lib/iris/fileformats/nimrod.py +++ b/lib/iris/fileformats/nimrod.py @@ -297,7 +297,7 @@ def load_cubes(filenames, callback=None): ---------- filenames : List of NIMROD filenames to load - callback : + callback : A function which can be passed on to :func:`iris.io.run_callback` Notes diff --git a/lib/iris/fileformats/rules.py b/lib/iris/fileformats/rules.py index 45132794ed..e092fa2b9b 100644 --- a/lib/iris/fileformats/rules.py +++ b/lib/iris/fileformats/rules.py @@ -255,7 +255,7 @@ def __new__(cls, field_generator, field_generator_kwargs, converter): Parameters ---------- - field_generator : + field_generator : A callable that accepts a filename as its first argument and returns an iterable of field objects. field_generator_kwargs : diff --git a/lib/iris/fileformats/um/_fast_load.py b/lib/iris/fileformats/um/_fast_load.py index f7b62af143..6940bfed9c 100644 --- a/lib/iris/fileformats/um/_fast_load.py +++ b/lib/iris/fileformats/um/_fast_load.py @@ -169,7 +169,7 @@ def _convert_collation(collation): Notes ----- .. note: - + This is the 'loader.converter', in the control structure passed to the generic rules code, :meth:`iris.fileformats.rules.load_cubes`. diff --git a/lib/iris/fileformats/um/_fast_load_structured_fields.py b/lib/iris/fileformats/um/_fast_load_structured_fields.py index b1bbdf40b3..81bec94f79 100644 --- a/lib/iris/fileformats/um/_fast_load_structured_fields.py +++ b/lib/iris/fileformats/um/_fast_load_structured_fields.py @@ -295,11 +295,11 @@ def group_structured_fields( The function sorts and collates on phenomenon-relevant metadata only, defined as the field components: 'lbuser[3]' (stash), 'lbproc' (statistic), 'lbuser[6]' (model). - + Each distinct combination of these defines a specific phenomenon (or statistical aggregation of one), and those fields appear as a single iteration result. - + .. note:: At present, fields with different values of 'lbuser[4]' (pseudo-level) diff --git a/lib/iris/fileformats/um/_ff_replacement.py b/lib/iris/fileformats/um/_ff_replacement.py index d9a774b934..8ceb30bb92 100644 --- a/lib/iris/fileformats/um/_ff_replacement.py +++ b/lib/iris/fileformats/um/_ff_replacement.py @@ -55,12 +55,12 @@ def load_cubes(filenames, callback, constraints=None, _loader_kwargs=None): Parameters ---------- - filenames : + filenames : list of filenames to load callback : A function which can be passed on to :func:`iris.io.run_callback` constraints : optional, default=None - _loader_kwargs : optional, default=None + _loader_kwargs : optional, default=None Notes ----- diff --git a/lib/iris/palette.py b/lib/iris/palette.py index 95c8879b68..acdc9f4e46 100644 --- a/lib/iris/palette.py +++ b/lib/iris/palette.py @@ -56,7 +56,7 @@ def is_brewer(cmap): def _default_cmap_norm(args, kwargs): """Injects default cmap and norm behaviour into the keyword arguments. - + This function injects default cmap and norm behaviour into the keyword arguments, based on the cube referenced within the positional arguments. @@ -137,7 +137,7 @@ def cmap_norm(cube): def auto_palette(func): """Decorator wrapper function to control the default behaviour. - + Decorator wrapper function to control the default behaviour of the matplotlib cmap and norm keyword arguments. diff --git a/lib/iris/tests/__init__.py b/lib/iris/tests/__init__.py index cd3a8adb16..bcf42d9be9 100644 --- a/lib/iris/tests/__init__.py +++ b/lib/iris/tests/__init__.py @@ -621,7 +621,7 @@ def assertArrayAllClose(self, a, b, rtol=1.0e-7, atol=1.0e-8, **kwargs): Relative and absolute tolerances to apply. Other Parameters - ---------------- + ---------------- Any additional kwargs are passed to numpy.testing.assert_allclose. Performs pointwise toleranced comparison, and raises an assertion if diff --git a/lib/iris/tests/unit/fileformats/netcdf/saver/test_Saver__ugrid.py b/lib/iris/tests/unit/fileformats/netcdf/saver/test_Saver__ugrid.py index ba5e18d8d4..a9f8a9b16d 100644 --- a/lib/iris/tests/unit/fileformats/netcdf/saver/test_Saver__ugrid.py +++ b/lib/iris/tests/unit/fileformats/netcdf/saver/test_Saver__ugrid.py @@ -59,6 +59,7 @@ def build_mesh( Dictionary of key settings to apply to the Mesh, after creating it. """ + def applyargs(coord, kwargs): if kwargs: for key, val in kwargs.items(): diff --git a/lib/iris/util.py b/lib/iris/util.py index f612eb3d7e..fa8dcccc3a 100644 --- a/lib/iris/util.py +++ b/lib/iris/util.py @@ -174,7 +174,7 @@ def describe_diff(cube_a, cube_b, output_file=None): output_file : A :class:`file` or file-like object to receive output. Defaults to sys.stdout. - + Notes ----- This function maintains laziness when called; it does not realise data. @@ -191,7 +191,7 @@ def describe_diff(cube_a, cube_b, output_file=None): See Also -------- :meth:`iris.cube.Cube.is_compatible()` - + """ if output_file is None: @@ -365,7 +365,7 @@ def array_equal(array1, array2, withnans=False): When unset (default), the result is False if either input contains NaN points. This is the normal floating-point arithmetic result. When set, return True if inputs contain the same value in all elements, - _including_ any NaN values. + _including_ any NaN values. Notes ----- @@ -792,7 +792,7 @@ def _slice_data_with_keys(data, keys): This enforces an orthogonal interpretation of indexing, which means that both 'real' (numpy) arrays and other array-likes index in the same way, instead of numpy arrays doing 'fancy indexing'. - + .. Note:: Avoids copying the data, where possible. @@ -1010,7 +1010,7 @@ def clip_string(the_str, clip_length=70, rider="..."): ---------- the_str : str The string to be clipped - clip_length : + clip_length : The length in characters that the input string should be clipped to. Defaults to a preconfigured value if not specified. rider : str, optional, default="..." @@ -1631,7 +1631,7 @@ def demote_dim_coord_to_aux_coord(cube, name_or_coord): Parameters ---------- - cube : + cube : An instance of :class:`iris.cube.Cube` name_or_coord : Either: TREMTEST: indent looks weird From 9846d883fb38963836672b01f60898a628f2c0de Mon Sep 17 00:00:00 2001 From: Tremain Knight <2108488+tkknight@users.noreply.github.com> Date: Tue, 26 Dec 2023 13:24:32 +0000 Subject: [PATCH 04/21] fix typos --- lib/iris/common/lenient.py | 4 ++-- lib/iris/coord_categorisation.py | 2 +- lib/iris/cube.py | 6 +++--- lib/iris/fileformats/um/_optimal_array_structuring.py | 1 - lib/iris/palette.py | 2 +- 5 files changed, 7 insertions(+), 8 deletions(-) diff --git a/lib/iris/common/lenient.py b/lib/iris/common/lenient.py index ed75189d47..821559c44b 100644 --- a/lib/iris/common/lenient.py +++ b/lib/iris/common/lenient.py @@ -590,8 +590,8 @@ def register_service(self, func): def unregister_client(self, func): """Remove the provided function/method as a lenient client using lenient services. - Paramters - --------- + Parameters + ---------- func : callable or str A function/method of fully qualified string name of the function/method. diff --git a/lib/iris/coord_categorisation.py b/lib/iris/coord_categorisation.py index 84eb038269..a17dba6519 100644 --- a/lib/iris/coord_categorisation.py +++ b/lib/iris/coord_categorisation.py @@ -431,7 +431,7 @@ def add_season_membership(cube, coord, season, name="season_membership"): Coordinate in 'cube', or its name, representing time. season : str Season defined by month abbreviations. - name : str, optinal + name : str, optional Name of the created coordinate. Defaults to "season_membership". """ diff --git a/lib/iris/cube.py b/lib/iris/cube.py index 7a563f8f6a..d5b692e32b 100644 --- a/lib/iris/cube.py +++ b/lib/iris/cube.py @@ -3008,14 +3008,14 @@ def intersection(self, *args, **kwargs): Parameters ---------- - coord : + coord : Either a :class:`iris.coords.Coord`, or coordinate name (as defined in :meth:`iris.cube.Cube.coords()`) minimum : The minimum value of the range to select. maximum : The maximum value of the range to select. - min_inclusive: + min_inclusive : If True, coordinate values equal to `minimum` will be included in the selection. Default is True. max_inclusive: @@ -3026,7 +3026,7 @@ def intersection(self, *args, **kwargs): threshold : optional Minimum proportion of a bounded cell that must overlap with the specified range. Default 0. - + Notes ----- .. note:: diff --git a/lib/iris/fileformats/um/_optimal_array_structuring.py b/lib/iris/fileformats/um/_optimal_array_structuring.py index 392edf9241..1e58a33f41 100644 --- a/lib/iris/fileformats/um/_optimal_array_structuring.py +++ b/lib/iris/fileformats/um/_optimal_array_structuring.py @@ -69,7 +69,6 @@ def optimal_array_structure(ordering_elements, actual_values_elements=None): from 'ordering_elements'. Must contain all the same names (but not necessarily in the same order). - Returns ------- dims_shape diff --git a/lib/iris/palette.py b/lib/iris/palette.py index acdc9f4e46..078d9b73ba 100644 --- a/lib/iris/palette.py +++ b/lib/iris/palette.py @@ -220,7 +220,7 @@ def vmax(self, val): def _load_palette(): - """Load pallette. + """Load palette. Load, configure and register color map palettes and initialise color map metadata mappings. From 9eafc418455006e8cf94d6fa204150a57762a896 Mon Sep 17 00:00:00 2001 From: Tremain Knight <2108488+tkknight@users.noreply.github.com> Date: Tue, 26 Dec 2023 13:25:14 +0000 Subject: [PATCH 05/21] remove comment --- .ruff.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/.ruff.toml b/.ruff.toml index c8341acac4..2562e18b16 100644 --- a/.ruff.toml +++ b/.ruff.toml @@ -40,7 +40,6 @@ lint.ignore = [ "D401", # First line of docstring should be in imperative mood: ... "D404", # First word of the docstring should not be "This" "D406", # Section name should end with a newline - #"D407", # Missing dashed underline after section # pyupgrade (UP) # https://docs.astral.sh/ruff/rules/#pyupgrade-up From dbd238d0ab432c3edefc6639a8edf480cda559ce Mon Sep 17 00:00:00 2001 From: Tremain Knight <2108488+tkknight@users.noreply.github.com> Date: Tue, 26 Dec 2023 13:46:09 +0000 Subject: [PATCH 06/21] minor tweaks --- docs/src/Makefile | 1 + docs/src/developers_guide/documenting/docstrings_attribute.py | 2 -- .../developers_guide/documenting/docstrings_sample_routine.py | 2 -- lib/iris/analysis/trajectory.py | 3 +-- lib/iris/coords.py | 3 --- lib/iris/experimental/regrid_conservative.py | 2 +- lib/iris/fileformats/_ff.py | 2 +- 7 files changed, 4 insertions(+), 11 deletions(-) diff --git a/docs/src/Makefile b/docs/src/Makefile index e260b7a2ed..dbcd337b6e 100644 --- a/docs/src/Makefile +++ b/docs/src/Makefile @@ -73,3 +73,4 @@ show: livehtml: sphinx-autobuild "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) --ignore generated $(O) + diff --git a/docs/src/developers_guide/documenting/docstrings_attribute.py b/docs/src/developers_guide/documenting/docstrings_attribute.py index 89a0f42c31..3044145b20 100644 --- a/docs/src/developers_guide/documenting/docstrings_attribute.py +++ b/docs/src/developers_guide/documenting/docstrings_attribute.py @@ -4,8 +4,6 @@ class ExampleClass: def __init__(self, arg1, arg2): """Purpose section description. - TREMTEST where is this used? - Description section text. Parameters diff --git a/docs/src/developers_guide/documenting/docstrings_sample_routine.py b/docs/src/developers_guide/documenting/docstrings_sample_routine.py index d80e0f952b..85ccd9ca40 100644 --- a/docs/src/developers_guide/documenting/docstrings_sample_routine.py +++ b/docs/src/developers_guide/documenting/docstrings_sample_routine.py @@ -3,8 +3,6 @@ def sample_routine(arg1, arg2, kwarg1="foo", kwarg2=None): Description section longer text goes here. - TREMTEST where is this used? - Parameters ---------- arg1 : numpy.ndarray diff --git a/lib/iris/analysis/trajectory.py b/lib/iris/analysis/trajectory.py index 88b1b69ba0..c46fa2ebea 100644 --- a/lib/iris/analysis/trajectory.py +++ b/lib/iris/analysis/trajectory.py @@ -74,8 +74,7 @@ def __init__(self, waypoints, sample_count=10): self.length = sum([seg.length for seg in segments]) # generate our sampled points - # TREMTEST: the below comment looks weird when rendered - #: The trajectory points, as dictionaries of {coord_name: value}. + # The trajectory points, as dictionaries of {coord_name: value}. self.sampled_points = [] sample_step = self.length / (self.sample_count - 1) diff --git a/lib/iris/coords.py b/lib/iris/coords.py index 993d2a27a7..a1595530f9 100644 --- a/lib/iris/coords.py +++ b/lib/iris/coords.py @@ -75,9 +75,6 @@ def __init__( ---------- values : The values of the dimensional metadata. - - Kwargs: - standard_name : optional, default=None CF standard name of the dimensional metadata. long_name : optional, default=None diff --git a/lib/iris/experimental/regrid_conservative.py b/lib/iris/experimental/regrid_conservative.py index a424038772..07b076b57e 100644 --- a/lib/iris/experimental/regrid_conservative.py +++ b/lib/iris/experimental/regrid_conservative.py @@ -67,7 +67,7 @@ def _make_esmpy_field(x_coord, y_coord, ref_name="field", data=None, mask=None): Their contiguous bounds define an ESMF.Grid of shape (nx, ny). data : :class:`numpy.ndarray`, shape (nx,ny), optional Set the Field data content. - mask : :class:`numpy.ndarray`, boolean, shape (nx,ny), optional + mask : :class:`numpy.ndarray`, bool, shape (nx,ny), optional Add a mask item to the grid, assigning it 0/1 where mask=False/True. """ diff --git a/lib/iris/fileformats/_ff.py b/lib/iris/fileformats/_ff.py index e0a1064b98..336c4aa699 100644 --- a/lib/iris/fileformats/_ff.py +++ b/lib/iris/fileformats/_ff.py @@ -449,7 +449,7 @@ def __init__(self, filename, read_data=False, word_depth=DEFAULT_FF_WORD_DEPTH): ---------- filename : str Specify the name of the FieldsFile. - read_data : boolean, optional + read_data : bool, optional Specify whether to read the associated PPField data within the FieldsFile. Default value is False. From 83f38c3832e0578e88391c496638022456a3ed8e Mon Sep 17 00:00:00 2001 From: Tremain Knight <2108488+tkknight@users.noreply.github.com> Date: Tue, 26 Dec 2023 13:47:28 +0000 Subject: [PATCH 07/21] undo changes --- docs/src/Makefile | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/src/Makefile b/docs/src/Makefile index dbcd337b6e..8d652878f6 100644 --- a/docs/src/Makefile +++ b/docs/src/Makefile @@ -72,5 +72,4 @@ show: @python -c "import webbrowser; webbrowser.open_new_tab('file://$(shell pwd)/$(BUILDDIR)/html/index.html')" livehtml: - sphinx-autobuild "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) --ignore generated $(O) - + sphinx-autobuild "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) --ignore generated $(O) \ No newline at end of file From f86588ee55ecd4fe418af9db2ec77bfa978fa312 Mon Sep 17 00:00:00 2001 From: Tremain Knight <2108488+tkknight@users.noreply.github.com> Date: Tue, 26 Dec 2023 13:55:55 +0000 Subject: [PATCH 08/21] fix typo in comment --- .ruff.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.ruff.toml b/.ruff.toml index 2562e18b16..f9770a18bd 100644 --- a/.ruff.toml +++ b/.ruff.toml @@ -31,7 +31,7 @@ lint.ignore = [ "D102", # Missing docstring in public method "D104", # Missing docstring in public package "D106", # Missing docstring in public nested class - # (D-3) Temporary, before an initial review, either fix ocurrenvces or move to (2). + # (D-3) Temporary, before an initial review, either fix ocurrences or move to (2). "D100", # Missing docstring in public module "D103", # Missing docstring in public function "D200", # One-line docstring should fit on one line From f223b2ecd33249030241757c85ab4a441c8c2705 Mon Sep 17 00:00:00 2001 From: Tremain Knight <2108488+tkknight@users.noreply.github.com> Date: Wed, 27 Dec 2023 16:02:12 +0000 Subject: [PATCH 09/21] remove comments --- lib/iris/cube.py | 2 -- lib/iris/util.py | 12 ++++-------- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/lib/iris/cube.py b/lib/iris/cube.py index d5b692e32b..d414cc3e09 100644 --- a/lib/iris/cube.py +++ b/lib/iris/cube.py @@ -2993,8 +2993,6 @@ def intersection(self, *args, **kwargs): """Return the intersection of the cube with specified coordinate ranges. - TREMTEST: check this still reads ok compared to the original. - Coordinate ranges can be specified as: * (a) positional arguments: instances of :class:`iris.coords.CoordExtent`, diff --git a/lib/iris/util.py b/lib/iris/util.py index fa8dcccc3a..bd7d4686df 100644 --- a/lib/iris/util.py +++ b/lib/iris/util.py @@ -1510,10 +1510,8 @@ def promote_aux_coord_to_dim_coord(cube, name_or_coord): cube : An instance of :class:`iris.cube.Cube` name_or_coord : - Either: TREMTEST: indent looks weird - - * (a) An instance of :class:`iris.coords.AuxCoord` - * (b) the :attr:`standard_name`, :attr:`long_name`, or + * \(a) An instance of :class:`iris.coords.AuxCoord` + * \(b) the :attr:`standard_name`, :attr:`long_name`, or :attr:`var_name` of an instance of an instance of :class:`iris.coords.AuxCoord`. @@ -1634,10 +1632,8 @@ def demote_dim_coord_to_aux_coord(cube, name_or_coord): cube : An instance of :class:`iris.cube.Cube` name_or_coord : - Either: TREMTEST: indent looks weird - - * (a) An instance of :class:`iris.coords.DimCoord` - * (b) the :attr:`standard_name`, :attr:`long_name`, or + * \(a) An instance of :class:`iris.coords.DimCoord` + * \(b) the :attr:`standard_name`, :attr:`long_name`, or :attr:`var_name` of an instance of an instance of :class:`iris.coords.DimCoord`. From 6e318c0af597949431ee4d64756f8702198e4b32 Mon Sep 17 00:00:00 2001 From: Tremain Knight <2108488+tkknight@users.noreply.github.com> Date: Wed, 27 Dec 2023 16:03:19 +0000 Subject: [PATCH 10/21] string update --- lib/iris/util.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/iris/util.py b/lib/iris/util.py index bd7d4686df..686238fa61 100644 --- a/lib/iris/util.py +++ b/lib/iris/util.py @@ -1500,7 +1500,7 @@ def _is_circular(points, modulus, bounds=None): def promote_aux_coord_to_dim_coord(cube, name_or_coord): - """Promotes an AuxCoord on the cube to a DimCoord. This AuxCoord must be + r"""Promotes an AuxCoord on the cube to a DimCoord. This AuxCoord must be associated with a single cube dimension. If the AuxCoord is associated with a dimension that already has a DimCoord, that DimCoord gets demoted to an AuxCoord. @@ -1620,7 +1620,7 @@ def promote_aux_coord_to_dim_coord(cube, name_or_coord): def demote_dim_coord_to_aux_coord(cube, name_or_coord): - """Demotes a dimension coordinate on the cube to an auxiliary coordinate. + r"""Demotes a dimension coordinate on the cube to an auxiliary coordinate. The DimCoord is demoted to an auxiliary coordinate on the cube. The dimension of the cube that was associated with the DimCoord becomes From 54f378086f34832157cec3d699c2a5ae2e7ab3c3 Mon Sep 17 00:00:00 2001 From: Tremain Knight <2108488+tkknight@users.noreply.github.com> Date: Tue, 2 Jan 2024 16:23:10 +0000 Subject: [PATCH 11/21] review comments (None use) --- .../documenting/docstrings_sample_routine.py | 2 +- lib/iris/analysis/maths.py | 20 +++++++++---------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/src/developers_guide/documenting/docstrings_sample_routine.py b/docs/src/developers_guide/documenting/docstrings_sample_routine.py index 85ccd9ca40..d565e6a8df 100644 --- a/docs/src/developers_guide/documenting/docstrings_sample_routine.py +++ b/docs/src/developers_guide/documenting/docstrings_sample_routine.py @@ -12,7 +12,7 @@ def sample_routine(arg1, arg2, kwarg1="foo", kwarg2=None): kwarg1: str, optional The first keyword argument. This argument description can be multi-lined. - kwarg2 : bool or None, optional + kwarg2 : bool, optional The second keyword argument. Returns diff --git a/lib/iris/analysis/maths.py b/lib/iris/analysis/maths.py index 36a34c0beb..0d865952ce 100644 --- a/lib/iris/analysis/maths.py +++ b/lib/iris/analysis/maths.py @@ -43,7 +43,7 @@ def _output_dtype(op, first_dtype, second_dtype=None, in_place=False): The dtype of the first or only argument to the operator. second_dtype : optional, default=None The dtype of the second argument to the operator. - in_place : optional, default=None + in_place : bool, optional, default=False Whether the operation is to be performed in place. Returns @@ -94,7 +94,7 @@ def abs(cube, in_place=False): ---------- cube : An instance of :class:`iris.cube.Cube`. - in_place : bool, default=False + in_place : bool, optional, default=False Whether to create a new Cube, or alter the given "cube". Returns @@ -227,7 +227,7 @@ def add(cube, other, dim=None, in_place=False): If `other` is a coord which does not exist on the cube, specify the dimension to which it should be mapped. - in_place : bool, default=False + in_place : bool, optional, default=False If `True`, alters the input cube. Otherwise a new cube is created. Returns @@ -280,7 +280,7 @@ def subtract(cube, other, dim=None, in_place=False): If `other` is a coord which does not exist on the cube, specify the dimension to which it should be mapped. - in_place : bool, default=False + in_place : bool, optional, default=False If `True`, alters the input cube. Otherwise a new cube is created. Returns @@ -339,7 +339,7 @@ def _add_subtract_common( dim : optional, default=None Dimension along which to apply `other` if it's a coordinate that is not found in `cube` - in_place : bool, default=False + in_place : bool, optional, default=False Whether or not to apply the operation in place to `cube` and `cube.data` """ @@ -389,7 +389,7 @@ def multiply(cube, other, dim=None, in_place=False): If `other` is a coord which does not exist on the cube, specify the dimension to which it should be mapped. - in_place : bool, default=False + in_place : bool, optional, default=False If `True`, alters the input cube. Otherwise a new cube is created. Returns @@ -473,7 +473,7 @@ def divide(cube, other, dim=None, in_place=False): If `other` is a coord which does not exist on the cube, specify the dimension to which it should be mapped. - in_place : bool, default=False + in_place : bool, optional, default=False If `True`, alters the input cube. Otherwise a new cube is created. Returns @@ -537,7 +537,7 @@ def exponentiate(cube, exponent, in_place=False): powers of the basic units. e.g. Unit('meter^-2 kilogram second^-1') - in_place : bool, optional=False + in_place : bool, optional, default=False Whether to create a new Cube, or alter the given "cube". Returns @@ -582,7 +582,7 @@ def exp(cube, in_place=False): ---------- cube : An instance of :class:`iris.cube.Cube`. - in_place : bool, default=False + in_place : bool, optional, default=False Whether to create a new Cube, or alter the given "cube". Returns @@ -672,7 +672,7 @@ def log10(cube, in_place=False): ---------- cube : An instance of :class:`iris.cube.Cube`. - in_place : bool, optional, default=None + in_place : bool, optional, default=False Whether to create a new Cube, or alter the given "cube". Returns From 4a44ff824ceb7d1a74770a43d676876c759c35c3 Mon Sep 17 00:00:00 2001 From: tkknight <2108488+tkknight@users.noreply.github.com> Date: Tue, 2 Jan 2024 16:30:31 +0000 Subject: [PATCH 12/21] Update lib/iris/analysis/stats.py Co-authored-by: Patrick Peglar --- lib/iris/analysis/stats.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/iris/analysis/stats.py b/lib/iris/analysis/stats.py index fcadaebe1f..7791283b30 100644 --- a/lib/iris/analysis/stats.py +++ b/lib/iris/analysis/stats.py @@ -53,7 +53,7 @@ def pearsonr( Returns ------- - cube + :class:`~iris.cube.Cube` A cube of the correlation between the two input cubes along the specified dimensions, at each point in the remaining dimensions of the cubes. From 2792cfa924f778977ccccf242afab06900def181 Mon Sep 17 00:00:00 2001 From: Tremain Knight <2108488+tkknight@users.noreply.github.com> Date: Tue, 2 Jan 2024 16:46:39 +0000 Subject: [PATCH 13/21] reivew fix. --- lib/iris/_concatenate.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/iris/_concatenate.py b/lib/iris/_concatenate.py index 6a097b8963..4e36db5d4b 100644 --- a/lib/iris/_concatenate.py +++ b/lib/iris/_concatenate.py @@ -293,22 +293,22 @@ def concatenate( cubes : iter or :class:`iris.cube.Cube` An iterable containing one or more :class:`iris.cube.Cube` instances to be concatenated together. - error_on_mismatch: bool, optional + error_on_mismatch: bool, default=False If True, raise an informative :class:`~iris.exceptions.ContatenateError` if registration fails. - check_aux_coords : bool, optional + 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, optional + 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, optional + 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, optional + 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 From 22a77d2ed19038eb7b2d02a6bde4105d16687949 Mon Sep 17 00:00:00 2001 From: tkknight <2108488+tkknight@users.noreply.github.com> Date: Tue, 2 Jan 2024 16:51:57 +0000 Subject: [PATCH 14/21] Update lib/iris/analysis/stats.py Co-authored-by: Patrick Peglar --- lib/iris/analysis/stats.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/iris/analysis/stats.py b/lib/iris/analysis/stats.py index 7791283b30..d679e853e1 100644 --- a/lib/iris/analysis/stats.py +++ b/lib/iris/analysis/stats.py @@ -45,7 +45,7 @@ def pearsonr( cell is masked. mdtol=0 means no missing data is tolerated while mdtol=1 means the resulting element will be masked if and only if all contributing elements are masked in cube_a or cube_b. Defaults to 1. - common_mask : bool, optional, default=False + common_mask : bool, default=False If True, applies a common mask to cube_a and cube_b so only cells which are unmasked in both cubes contribute to the calculation. If False, the variance for each cube is calculated from all available cells. Defaults From 180384d611515173ef462aa87f3dc67174e4c6c5 Mon Sep 17 00:00:00 2001 From: tkknight <2108488+tkknight@users.noreply.github.com> Date: Tue, 2 Jan 2024 16:52:56 +0000 Subject: [PATCH 15/21] Update lib/iris/analysis/stats.py Co-authored-by: Patrick Peglar --- lib/iris/analysis/stats.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/iris/analysis/stats.py b/lib/iris/analysis/stats.py index d679e853e1..d93bd6c574 100644 --- a/lib/iris/analysis/stats.py +++ b/lib/iris/analysis/stats.py @@ -38,7 +38,7 @@ def pearsonr( Weights array of same shape as (the smaller of) cube_a and cube_b. Note that latitude/longitude area weights can be calculated using :func:`iris.analysis.cartography.area_weights`. - mdtol : float, optional, default=1.0 + mdtol : float, default=1.0 Tolerance of missing data. The missing data fraction is calculated based on the number of grid cells masked in both cube_a and cube_b. If this fraction exceed mdtol, the returned value in the corresponding From b519196b27404f236fd10958e951dd7ff5ca886b Mon Sep 17 00:00:00 2001 From: tkknight <2108488+tkknight@users.noreply.github.com> Date: Tue, 2 Jan 2024 16:53:54 +0000 Subject: [PATCH 16/21] Update lib/iris/analysis/cartography.py Co-authored-by: Patrick Peglar --- lib/iris/analysis/cartography.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/iris/analysis/cartography.py b/lib/iris/analysis/cartography.py index d16f395214..01c71b177a 100644 --- a/lib/iris/analysis/cartography.py +++ b/lib/iris/analysis/cartography.py @@ -910,7 +910,7 @@ def _inter_crs_differentials(crs1, x, y, crs2): Parameters ---------- - crs1, crs2 : `cartopy.crs.Projection` + crs1, crs2 : :class:`cartopy.crs.Projection` The coordinate systems, "from" and "to". x, y : array Point locations defined in 'crs1'. From 5676cc70527fffdf6743f74cf724427cc82ec176 Mon Sep 17 00:00:00 2001 From: tkknight <2108488+tkknight@users.noreply.github.com> Date: Tue, 2 Jan 2024 16:54:21 +0000 Subject: [PATCH 17/21] Update lib/iris/analysis/stats.py Co-authored-by: Patrick Peglar --- lib/iris/analysis/stats.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/iris/analysis/stats.py b/lib/iris/analysis/stats.py index d93bd6c574..2f5b125e06 100644 --- a/lib/iris/analysis/stats.py +++ b/lib/iris/analysis/stats.py @@ -34,7 +34,7 @@ def pearsonr( The cube coordinate name(s) over which to calculate correlations. If no names are provided then correlation will be calculated over all common cube dimensions. - weights : numpy.ndarray, optional + weights : :class:`numpy.ndarray`, optional Weights array of same shape as (the smaller of) cube_a and cube_b. Note that latitude/longitude area weights can be calculated using :func:`iris.analysis.cartography.area_weights`. From 39fb4bf8f7e5c463c5ddc144a5b7a85e69599ec6 Mon Sep 17 00:00:00 2001 From: tkknight <2108488+tkknight@users.noreply.github.com> Date: Tue, 2 Jan 2024 16:54:39 +0000 Subject: [PATCH 18/21] Update lib/iris/_concatenate.py Co-authored-by: Patrick Peglar --- lib/iris/_concatenate.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/iris/_concatenate.py b/lib/iris/_concatenate.py index 4e36db5d4b..10ab2ec907 100644 --- a/lib/iris/_concatenate.py +++ b/lib/iris/_concatenate.py @@ -319,7 +319,8 @@ def concatenate( Returns ------- - A :class:`iris.cube.CubeList` of concatenated :class:`iris.cube.Cube` instances. + :class:`iris.cube.CubeList` + A :class:`iris.cube.CubeList` of concatenated :class:`iris.cube.Cube` instances. """ proto_cubes_by_name = defaultdict(list) From 1153f5463905ec4d76c2328c40017911b14334f8 Mon Sep 17 00:00:00 2001 From: tkknight <2108488+tkknight@users.noreply.github.com> Date: Tue, 2 Jan 2024 16:56:28 +0000 Subject: [PATCH 19/21] Update lib/iris/_concatenate.py Co-authored-by: Patrick Peglar --- lib/iris/_concatenate.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/iris/_concatenate.py b/lib/iris/_concatenate.py index 10ab2ec907..dd031ed45f 100644 --- a/lib/iris/_concatenate.py +++ b/lib/iris/_concatenate.py @@ -768,7 +768,8 @@ def concatenate(self): Returns ------- - The concatenated :class:`iris.cube.Cube`. + :class:`iris.cube.Cube` + The concatenated :class:`iris.cube.Cube`. """ if len(self._skeletons) > 1: From dda4ac230ac1af310b10c9309eb9cb007794a499 Mon Sep 17 00:00:00 2001 From: tkknight <2108488+tkknight@users.noreply.github.com> Date: Tue, 2 Jan 2024 16:57:43 +0000 Subject: [PATCH 20/21] Update lib/iris/_concatenate.py Co-authored-by: Patrick Peglar --- lib/iris/_concatenate.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/iris/_concatenate.py b/lib/iris/_concatenate.py index dd031ed45f..97c2840958 100644 --- a/lib/iris/_concatenate.py +++ b/lib/iris/_concatenate.py @@ -290,7 +290,7 @@ def concatenate( Parameters ---------- - cubes : iter or :class:`iris.cube.Cube` + cubes : iterable of :class:`iris.cube.Cube` An iterable containing one or more :class:`iris.cube.Cube` instances to be concatenated together. error_on_mismatch: bool, default=False From e30a65200e15334a59a4949d285274afe1e063a2 Mon Sep 17 00:00:00 2001 From: Tremain Knight <2108488+tkknight@users.noreply.github.com> Date: Tue, 2 Jan 2024 17:06:56 +0000 Subject: [PATCH 21/21] review actions --- lib/iris/_data_manager.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/iris/_data_manager.py b/lib/iris/_data_manager.py index 286c3abefb..785440d094 100644 --- a/lib/iris/_data_manager.py +++ b/lib/iris/_data_manager.py @@ -56,8 +56,8 @@ def __deepcopy__(self, memo): Parameters ---------- - memo : :class:`copy` - :class:`copy` memo dictionary. + memo : :func:`copy` + :func:`copy` memo dictionary. """ return self._deepcopy(memo) @@ -140,8 +140,8 @@ def _deepcopy(self, memo, data=None): Parameters ---------- - memo : :class:`copy` - :class:`copy` memo dictionary. + memo : :func:`copy` + :func:`copy` memo dictionary. data : optional Replacement data to substitute the currently managed data with.