Skip to content

Commit 2405d95

Browse files
Unified ignoring of iris.warnings.IrisVagueMetadataWarning in preprocessors (#2646)
Co-authored-by: Valeriu Predoi <[email protected]>
1 parent 8f85fad commit 2405d95

20 files changed

+215
-121
lines changed

esmvalcore/cmor/_fixes/emac/emac.py

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
"""
1313

1414
import logging
15+
import warnings
1516
from shutil import copyfile
1617

1718
import dask.array as da
@@ -23,6 +24,8 @@
2324
from netCDF4 import Dataset
2425
from scipy import constants
2526

27+
from esmvalcore.iris_helpers import ignore_iris_vague_metadata_warnings
28+
2629
from ..shared import add_aux_coords_from_cubes
2730
from ._base_fixes import EmacFix, NegateData
2831

@@ -230,14 +233,22 @@ def fix_metadata(self, cubes):
230233
)
231234
dt_cube = self.get_cube(cubes, var_name="dt")
232235

233-
cube = (
234-
noxcg_cube.collapsed(
235-
["longitude", "latitude"], iris.analysis.SUM, weights=None
236-
)
237-
+ noxic_cube.collapsed(
238-
["longitude", "latitude"], iris.analysis.SUM, weights=None
236+
with warnings.catch_warnings(), ignore_iris_vague_metadata_warnings():
237+
warnings.filterwarnings(
238+
"ignore",
239+
message="Collapsing spatial coordinate 'latitude' without "
240+
"weighting",
241+
category=UserWarning,
242+
module="iris",
239243
)
240-
) / dt_cube
244+
cube = (
245+
noxcg_cube.collapsed(
246+
["longitude", "latitude"], iris.analysis.SUM, weights=None
247+
)
248+
+ noxic_cube.collapsed(
249+
["longitude", "latitude"], iris.analysis.SUM, weights=None
250+
)
251+
) / dt_cube
241252
cube.units = "kg s-1"
242253
cube.var_name = self.vardef.short_name
243254

@@ -261,7 +272,8 @@ def fix_metadata(self, cubes):
261272
cubes = super().fix_metadata(cubes)
262273
cube = self.get_cube(cubes)
263274
z_coord = cube.coord(axis="Z")
264-
cube = cube.collapsed(z_coord, iris.analysis.SUM)
275+
with ignore_iris_vague_metadata_warnings():
276+
cube = cube.collapsed(z_coord, iris.analysis.SUM)
265277
return CubeList([cube])
266278

267279

esmvalcore/iris_helpers.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
from __future__ import annotations
44

5+
import warnings
6+
from collections.abc import Generator
7+
from contextlib import contextmanager
58
from typing import Dict, Iterable, List, Literal, Sequence
69

710
import dask.array as da
@@ -13,10 +16,28 @@
1316
from iris.coords import Coord
1417
from iris.cube import Cube
1518
from iris.exceptions import CoordinateMultiDimError, CoordinateNotFoundError
19+
from iris.warnings import IrisVagueMetadataWarning
1620

1721
from esmvalcore.typing import NetCDFAttr
1822

1923

24+
@contextmanager
25+
def ignore_iris_vague_metadata_warnings() -> Generator[None]:
26+
"""Ignore specific warnings.
27+
28+
This can be used as a context manager. See also
29+
https://scitools-iris.readthedocs.io/en/stable/generated/api/iris.warnings.html#iris.warnings.IrisVagueMetadataWarning.
30+
31+
"""
32+
with warnings.catch_warnings():
33+
warnings.filterwarnings(
34+
"ignore",
35+
category=IrisVagueMetadataWarning,
36+
module="iris",
37+
)
38+
yield
39+
40+
2041
def add_leading_dim_to_cube(cube, dim_coord):
2142
"""Add new leading dimension to cube.
2243

esmvalcore/preprocessor/_area.py

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
from __future__ import annotations
88

99
import logging
10-
import warnings
1110
from pathlib import Path
1211
from typing import TYPE_CHECKING, Iterable, Literal, Optional
1312

@@ -21,6 +20,7 @@
2120
from iris.cube import Cube, CubeList
2221
from iris.exceptions import CoordinateNotFoundError
2322

23+
from esmvalcore.iris_helpers import ignore_iris_vague_metadata_warnings
2424
from esmvalcore.preprocessor._shared import (
2525
apply_mask,
2626
get_dims_along_axes,
@@ -240,7 +240,8 @@ def zonal_statistics(
240240
"Zonal statistics on irregular grids not yet implemented"
241241
)
242242
(agg, agg_kwargs) = get_iris_aggregator(operator, **operator_kwargs)
243-
result = cube.collapsed("longitude", agg, **agg_kwargs)
243+
with ignore_iris_vague_metadata_warnings():
244+
result = cube.collapsed("longitude", agg, **agg_kwargs)
244245
if normalize is not None:
245246
result = get_normalized_cube(cube, result, normalize)
246247
return result
@@ -289,7 +290,8 @@ def meridional_statistics(
289290
"Meridional statistics on irregular grids not yet implemented"
290291
)
291292
(agg, agg_kwargs) = get_iris_aggregator(operator, **operator_kwargs)
292-
result = cube.collapsed("latitude", agg, **agg_kwargs)
293+
with ignore_iris_vague_metadata_warnings():
294+
result = cube.collapsed("latitude", agg, **agg_kwargs)
293295
if normalize is not None:
294296
result = get_normalized_cube(cube, result, normalize)
295297
return result
@@ -355,15 +357,7 @@ def area_statistics(
355357
agg, agg_kwargs, "cell_area", cube, try_adding_calculated_cell_area
356358
)
357359

358-
with warnings.catch_warnings():
359-
# Silence various warnings about collapsing multi-dimensional and/or
360-
# non contiguous coordinates as this should be fine when the cell areas
361-
# are provided and will fail when they needed but not provided.
362-
warnings.filterwarnings(
363-
"ignore",
364-
category=iris.warnings.IrisVagueMetadataWarning,
365-
module="iris",
366-
)
360+
with ignore_iris_vague_metadata_warnings():
367361
result = cube.collapsed(["latitude", "longitude"], agg, **agg_kwargs)
368362
if normalize is not None:
369363
result = get_normalized_cube(cube, result, normalize)

esmvalcore/preprocessor/_compare_with_refs.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,10 @@
1717
from iris.cube import Cube, CubeList
1818
from scipy.stats import wasserstein_distance
1919

20-
from esmvalcore.iris_helpers import rechunk_cube
20+
from esmvalcore.iris_helpers import (
21+
ignore_iris_vague_metadata_warnings,
22+
rechunk_cube,
23+
)
2124
from esmvalcore.preprocessor._io import concatenate
2225
from esmvalcore.preprocessor._other import histogram
2326
from esmvalcore.preprocessor._shared import (
@@ -431,7 +434,8 @@ def _calculate_metric(
431434

432435
# Get result cube with correct dimensional metadata by using dummy
433436
# operation (max)
434-
res_cube = cube.collapsed(coords, iris.analysis.MAX)
437+
with ignore_iris_vague_metadata_warnings():
438+
res_cube = cube.collapsed(coords, iris.analysis.MAX)
435439
res_cube.data = res_data
436440
res_cube.metadata = res_metadata
437441
res_cube.cell_methods = [*cube.cell_methods, CellMethod(metric, coords)]

esmvalcore/preprocessor/_cycles.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import iris
66
import iris.coord_categorisation
77

8+
from esmvalcore.iris_helpers import ignore_iris_vague_metadata_warnings
9+
810
logger = logging.getLogger(__name__)
911

1012

@@ -69,8 +71,9 @@ def amplitude(cube, coords):
6971
)
7072

7173
# Calculate amplitude
72-
max_cube = cube.aggregated_by(coords, iris.analysis.MAX)
73-
min_cube = cube.aggregated_by(coords, iris.analysis.MIN)
74+
with ignore_iris_vague_metadata_warnings():
75+
max_cube = cube.aggregated_by(coords, iris.analysis.MAX)
76+
min_cube = cube.aggregated_by(coords, iris.analysis.MIN)
7477
amplitude_cube = max_cube - min_cube
7578
amplitude_cube.metadata = cube.metadata
7679

esmvalcore/preprocessor/_derive/_shared.py

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
from iris import NameConstraint
99
from scipy import constants
1010

11+
from esmvalcore.iris_helpers import ignore_iris_vague_metadata_warnings
12+
1113
logger = logging.getLogger(__name__)
1214

1315

@@ -21,12 +23,13 @@ def cloud_area_fraction(cubes, tau_constraint, plev_constraint):
2123
for coord in new_cube.coords()
2224
if len(coord.points) > 1
2325
]
24-
if "atmosphere_optical_thickness_due_to_cloud" in coord_names:
25-
new_cube = new_cube.collapsed(
26-
"atmosphere_optical_thickness_due_to_cloud", iris.analysis.SUM
27-
)
28-
if "air_pressure" in coord_names:
29-
new_cube = new_cube.collapsed("air_pressure", iris.analysis.SUM)
26+
with ignore_iris_vague_metadata_warnings():
27+
if "atmosphere_optical_thickness_due_to_cloud" in coord_names:
28+
new_cube = new_cube.collapsed(
29+
"atmosphere_optical_thickness_due_to_cloud", iris.analysis.SUM
30+
)
31+
if "air_pressure" in coord_names:
32+
new_cube = new_cube.collapsed("air_pressure", iris.analysis.SUM)
3033

3134
return new_cube
3235

@@ -108,11 +111,12 @@ def column_average(cube, hus_cube, zg_cube, ps_cube):
108111
cube.data = cube.core_data() * n_dry.core_data()
109112

110113
# Column-average
111-
cube = cube.collapsed("air_pressure", iris.analysis.SUM)
112-
cube.data = (
113-
cube.core_data()
114-
/ n_dry.collapsed("air_pressure", iris.analysis.SUM).core_data()
115-
)
114+
with ignore_iris_vague_metadata_warnings():
115+
cube = cube.collapsed("air_pressure", iris.analysis.SUM)
116+
cube.data = (
117+
cube.core_data()
118+
/ n_dry.collapsed("air_pressure", iris.analysis.SUM).core_data()
119+
)
116120
return cube
117121

118122

esmvalcore/preprocessor/_derive/amoc.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import iris
44
import numpy as np
55

6+
from esmvalcore.iris_helpers import ignore_iris_vague_metadata_warnings
7+
68
from ._baseclass import DerivedVariableBase
79

810

@@ -86,9 +88,7 @@ def calculate(cubes):
8688
cube = cube.extract(constraint=rapid_constraint)
8789

8890
# 4: find the maximum in the water column along the time axis.
89-
cube = cube.collapsed(
90-
["depth", "region"],
91-
iris.analysis.MAX,
92-
)
91+
with ignore_iris_vague_metadata_warnings():
92+
cube = cube.collapsed(["depth", "region"], iris.analysis.MAX)
9393

9494
return cube

esmvalcore/preprocessor/_derive/toz.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
"""Derivation of variable ``toz``."""
22

3-
import warnings
4-
53
import cf_units
64
import iris
75
from scipy import constants
86

97
from esmvalcore.cmor.table import CMOR_TABLES
8+
from esmvalcore.iris_helpers import ignore_iris_vague_metadata_warnings
109

1110
from .._regrid import extract_levels, regrid
1211
from ._baseclass import DerivedVariableBase
@@ -104,7 +103,8 @@ def calculate(cubes):
104103
# have correct shapes
105104
if not o3_cube.coords("longitude"):
106105
o3_cube = add_longitude_coord(o3_cube)
107-
ps_cube = ps_cube.collapsed("longitude", iris.analysis.MEAN)
106+
with ignore_iris_vague_metadata_warnings():
107+
ps_cube = ps_cube.collapsed("longitude", iris.analysis.MEAN)
108108
ps_cube.remove_coord("longitude")
109109
ps_cube = add_longitude_coord(ps_cube)
110110

@@ -117,12 +117,7 @@ def calculate(cubes):
117117
# widths
118118
p_layer_widths = pressure_level_widths(o3_cube, ps_cube, top_limit=0.0)
119119
toz_cube = o3_cube * p_layer_widths / STANDARD_GRAVITY * MW_O3 / MW_AIR
120-
with warnings.catch_warnings():
121-
warnings.filterwarnings(
122-
"ignore",
123-
category=UserWarning,
124-
message="Collapsing a non-contiguous coordinate",
125-
)
120+
with ignore_iris_vague_metadata_warnings():
126121
toz_cube = toz_cube.collapsed("air_pressure", iris.analysis.SUM)
127122
toz_cube.units = (
128123
o3_cube.units

esmvalcore/preprocessor/_derive/troz.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import dask.array as da
44
import iris
55

6+
from esmvalcore.iris_helpers import ignore_iris_vague_metadata_warnings
7+
68
from ._baseclass import DerivedVariableBase
79
from .soz import STRATOSPHERIC_O3_THRESHOLD
810
from .toz import DerivedVariable as Toz
@@ -45,7 +47,8 @@ def calculate(cubes):
4547
# have correct shapes
4648
if not o3_cube.coords("longitude"):
4749
o3_cube = add_longitude_coord(o3_cube)
48-
ps_cube = ps_cube.collapsed("longitude", iris.analysis.MEAN)
50+
with ignore_iris_vague_metadata_warnings():
51+
ps_cube = ps_cube.collapsed("longitude", iris.analysis.MEAN)
4952
ps_cube.remove_coord("longitude")
5053
ps_cube = add_longitude_coord(ps_cube)
5154

esmvalcore/preprocessor/_derive/uajet.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
import iris
55
import numpy as np
66

7+
from esmvalcore.iris_helpers import ignore_iris_vague_metadata_warnings
8+
79
from ._baseclass import DerivedVariableBase
810

911
# Constants (Southern hemisphere at 850 hPa)
@@ -31,7 +33,8 @@ def calculate(cubes):
3133
ua_cube = ua_cube.extract(
3234
iris.Constraint(latitude=lambda cell: LAT[0] <= cell <= LAT[1])
3335
)
34-
ua_cube = ua_cube.collapsed("longitude", iris.analysis.MEAN)
36+
with ignore_iris_vague_metadata_warnings():
37+
ua_cube = ua_cube.collapsed("longitude", iris.analysis.MEAN)
3538

3639
# Calculate maximum jet position
3740
uajet_vals = []

esmvalcore/preprocessor/_mask.py

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,10 @@
2121
from iris.cube import Cube
2222
from iris.util import rolling_window
2323

24-
from esmvalcore.preprocessor._shared import apply_mask
24+
from esmvalcore.iris_helpers import ignore_iris_vague_metadata_warnings
25+
from esmvalcore.preprocessor._shared import (
26+
apply_mask,
27+
)
2528

2629
from ._supplementary_vars import register_supplementaries
2730

@@ -396,12 +399,13 @@ def count_spells(
396399
# if you want overlapping windows set the step to be m*spell_length
397400
# where m is a float
398401
###############################################################
399-
hit_windows = rolling_window(
400-
data_hits,
401-
window=spell_length,
402-
step=spell_length,
403-
axis=axis,
404-
)
402+
with ignore_iris_vague_metadata_warnings():
403+
hit_windows = rolling_window(
404+
data_hits,
405+
window=spell_length,
406+
step=spell_length,
407+
axis=axis,
408+
)
405409
# Find the windows "full of True-s" (along the added 'window axis').
406410
full_windows = array_module.all(hit_windows, axis=axis + 1)
407411
# Count points fulfilling the condition (along the time axis).
@@ -726,12 +730,13 @@ def _get_fillvalues_mask(
726730
)
727731

728732
# Calculate the statistic.
729-
counts_windowed_cube = cube.collapsed(
730-
"time",
731-
spell_count,
732-
threshold=min_value,
733-
spell_length=time_window,
734-
)
733+
with ignore_iris_vague_metadata_warnings():
734+
counts_windowed_cube = cube.collapsed(
735+
"time",
736+
spell_count,
737+
threshold=min_value,
738+
spell_length=time_window,
739+
)
735740

736741
# Create mask
737742
mask = counts_windowed_cube.core_data() < counts_threshold

0 commit comments

Comments
 (0)