Skip to content

Commit

Permalink
Categorise warnings (#5498)
Browse files Browse the repository at this point in the history
* Introduce IrisUserWarning.

* Align existing warning subcategories.

* Plant a flag for future DeprecationWarning use.

* Introduce test_categorised_warnings().

* Fix backwards compatibility of existing warnings classes.

* Categorise all Iris warnings.

* Fix test_categorised_warnings() by using ast module.

* Add missing warning category kwargs.

* Warnings combo experiment.

* Warnings combo finalise.

* Fix stray comma in coords.py.

* Fix failing tests.

* Categorise warning tests.

* What's New entry.
  • Loading branch information
trexfeathers authored Sep 22, 2023
1 parent b6e39d7 commit 4f126a0
Show file tree
Hide file tree
Showing 62 changed files with 930 additions and 205 deletions.
8 changes: 5 additions & 3 deletions docs/src/whatsnew/latest.rst
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,17 @@ This document explains the changes made to Iris for this release
✨ Features
===========

#. N/A
#. `@trexfeathers`_ and `@HGWright`_ (reviewer) sub-categorised all Iris'
:class:`UserWarning`\s for richer filtering. The full index of
sub-categories can be seen here: :mod:`iris.exceptions` . (:pull:`5498`)


🐛 Bugs Fixed
=============

#. `@scottrobinson02`_ fixed the output units when dividing a coordinate by a
cube. (:issue:`5305`, :pull:`5331`)

#. `@ESadek-MO`_ has updated :mod:`iris.tests.graphics.idiff` to stop duplicated file names
preventing acceptance. (:issue:`5098`, :pull:`5482`)

Expand Down Expand Up @@ -87,7 +89,7 @@ This document explains the changes made to Iris for this release

#. `@trexfeathers`_ replaced all uses of the ``logging.WARNING`` level, in
favour of using Python warnings, following team agreement. (:pull:`5488`)

#. `@trexfeathers`_ adapted benchmarking to work with ASV ``>=v0.6`` by no
longer using the ``--strict`` argument. (:pull:`5496`)

Expand Down
2 changes: 2 additions & 0 deletions lib/iris/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,8 @@ def __init__(self, datum_support=False, pandas_ndim=False):
# self.__dict__['example_future_flag'] = example_future_flag
self.__dict__["datum_support"] = datum_support
self.__dict__["pandas_ndim"] = pandas_ndim
# TODO: next major release: set IrisDeprecation to subclass
# DeprecationWarning instead of UserWarning.

def __repr__(self):
# msg = ('Future(example_future_flag={})')
Expand Down
3 changes: 2 additions & 1 deletion lib/iris/_concatenate.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import iris.coords
import iris.cube
import iris.exceptions
from iris.util import array_equal, guess_coord_axis

#
Expand Down Expand Up @@ -998,7 +999,7 @@ def register(
raise iris.exceptions.ConcatenateError([msg])
elif not match:
msg = f"Found cubes with overlap on concatenate axis {candidate_axis}, skipping concatenation for these cubes"
warnings.warn(msg)
warnings.warn(msg, category=iris.exceptions.IrisUserWarning)

# Check for compatible AuxCoords.
if match:
Expand Down
10 changes: 8 additions & 2 deletions lib/iris/_deprecation.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,13 @@


class IrisDeprecation(UserWarning):
"""An Iris deprecation warning."""
"""
An Iris deprecation warning.
Note this subclasses UserWarning for backwards compatibility with Iris'
original deprection warnings. Should subclass DeprecationWarning at the
next major release.
"""

pass

Expand Down Expand Up @@ -44,7 +50,7 @@ def warn_deprecated(msg, stacklevel=2):
>>>
"""
warnings.warn(msg, IrisDeprecation, stacklevel=stacklevel)
warnings.warn(msg, category=IrisDeprecation, stacklevel=stacklevel)


# A Mixin for a wrapper class that copies the docstring of the wrapped class
Expand Down
3 changes: 2 additions & 1 deletion lib/iris/analysis/_regrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
snapshot_grid,
)
from iris.analysis._scipy_interpolate import _RegularGridInterpolator
from iris.exceptions import IrisImpossibleUpdateWarning
from iris.util import _meshgrid, guess_coord_axis


Expand Down Expand Up @@ -1136,6 +1137,6 @@ def regrid_reference_surface(
"Cannot update aux_factory {!r} because of dropped"
" coordinates.".format(factory.name())
)
warnings.warn(msg)
warnings.warn(msg, category=IrisImpossibleUpdateWarning)

return result
6 changes: 5 additions & 1 deletion lib/iris/analysis/calculus.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import iris.analysis.maths
import iris.coord_systems
import iris.coords
from iris.exceptions import IrisUserWarning
from iris.util import delta

__all__ = ["cube_delta", "curl", "differentiate"]
Expand Down Expand Up @@ -85,7 +86,10 @@ def _construct_midpoint_coord(coord, circular=None):
"Construction coordinate midpoints for the '{}' coordinate, "
"though it has the attribute 'circular'={}."
)
warnings.warn(msg.format(circular, coord.circular, coord.name()))
warnings.warn(
msg.format(circular, coord.circular, coord.name()),
category=IrisUserWarning,
)

if coord.ndim != 1:
raise iris.exceptions.CoordinateMultiDimError(coord)
Expand Down
23 changes: 17 additions & 6 deletions lib/iris/analysis/cartography.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,16 +401,25 @@ def area_weights(cube, normalize=False):
cs = cube.coord_system("CoordSystem")
if isinstance(cs, iris.coord_systems.GeogCS):
if cs.inverse_flattening != 0.0:
warnings.warn("Assuming spherical earth from ellipsoid.")
warnings.warn(
"Assuming spherical earth from ellipsoid.",
category=iris.exceptions.IrisDefaultingWarning,
)
radius_of_earth = cs.semi_major_axis
elif isinstance(cs, iris.coord_systems.RotatedGeogCS) and (
cs.ellipsoid is not None
):
if cs.ellipsoid.inverse_flattening != 0.0:
warnings.warn("Assuming spherical earth from ellipsoid.")
warnings.warn(
"Assuming spherical earth from ellipsoid.",
category=iris.exceptions.IrisDefaultingWarning,
)
radius_of_earth = cs.ellipsoid.semi_major_axis
else:
warnings.warn("Using DEFAULT_SPHERICAL_EARTH_RADIUS.")
warnings.warn(
"Using DEFAULT_SPHERICAL_EARTH_RADIUS.",
category=iris.exceptions.IrisDefaultingWarning,
)
radius_of_earth = DEFAULT_SPHERICAL_EARTH_RADIUS

# Get the lon and lat coords and axes
Expand Down Expand Up @@ -551,7 +560,7 @@ def cosine_latitude_weights(cube):
warnings.warn(
"Out of range latitude values will be "
"clipped to the valid range.",
UserWarning,
category=iris.exceptions.IrisDefaultingWarning,
)
points = lat.points
l_weights = np.cos(points).clip(0.0, 1.0)
Expand Down Expand Up @@ -665,7 +674,8 @@ def project(cube, target_proj, nx=None, ny=None):
# Assume WGS84 latlon if unspecified
warnings.warn(
"Coordinate system of latitude and longitude "
"coordinates is not specified. Assuming WGS84 Geodetic."
"coordinates is not specified. Assuming WGS84 Geodetic.",
category=iris.exceptions.IrisDefaultingWarning,
)
orig_cs = iris.coord_systems.GeogCS(
semi_major_axis=6378137.0, inverse_flattening=298.257223563
Expand Down Expand Up @@ -857,7 +867,8 @@ def project(cube, target_proj, nx=None, ny=None):
lat_coord.name(),
lon_coord.name(),
[coord.name() for coord in discarded_coords],
)
),
category=iris.exceptions.IrisIgnoringWarning,
)

# TODO handle derived coords/aux_factories
Expand Down
8 changes: 4 additions & 4 deletions lib/iris/analysis/geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def _extract_relevant_cube_slice(cube, geometry):
except ValueError:
warnings.warn(
"The geometry exceeds the cube's x dimension at the " "lower end.",
UserWarning,
category=iris.exceptions.IrisGeometryExceedWarning,
)
x_min_ix = 0 if x_ascending else x_coord.points.size - 1

Expand All @@ -84,7 +84,7 @@ def _extract_relevant_cube_slice(cube, geometry):
except ValueError:
warnings.warn(
"The geometry exceeds the cube's x dimension at the " "upper end.",
UserWarning,
category=iris.exceptions.IrisGeometryExceedWarning,
)
x_max_ix = x_coord.points.size - 1 if x_ascending else 0

Expand All @@ -94,7 +94,7 @@ def _extract_relevant_cube_slice(cube, geometry):
except ValueError:
warnings.warn(
"The geometry exceeds the cube's y dimension at the " "lower end.",
UserWarning,
category=iris.exceptions.IrisGeometryExceedWarning,
)
y_min_ix = 0 if y_ascending else y_coord.points.size - 1

Expand All @@ -104,7 +104,7 @@ def _extract_relevant_cube_slice(cube, geometry):
except ValueError:
warnings.warn(
"The geometry exceeds the cube's y dimension at the " "upper end.",
UserWarning,
category=iris.exceptions.IrisGeometryExceedWarning,
)
y_max_ix = y_coord.points.size - 1 if y_ascending else 0

Expand Down
3 changes: 2 additions & 1 deletion lib/iris/analysis/maths.py
Original file line number Diff line number Diff line change
Expand Up @@ -988,7 +988,8 @@ def _broadcast_cube_coord_data(cube, other, operation_name, dim=None):
if other.has_bounds():
warnings.warn(
"Using {!r} with a bounded coordinate is not well "
"defined; ignoring bounds.".format(operation_name)
"defined; ignoring bounds.".format(operation_name),
category=iris.exceptions.IrisIgnoringBoundsWarning,
)

points = other.points
Expand Down
Loading

0 comments on commit 4f126a0

Please sign in to comment.