Coverage for src/CSET/operators/collapse.py: 100%
15 statements
« prev ^ index » next coverage.py v7.5.4, created at 2024-07-01 08:37 +0000
« prev ^ index » next coverage.py v7.5.4, created at 2024-07-01 08:37 +0000
1# Copyright 2022 Met Office and contributors.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
15"""Operators to perform various kind of collapse on either 1 or 2 dimensions."""
17import warnings
18from typing import Union
20import iris
21import iris.analysis
22import iris.cube
25def collapse(
26 cube: iris.cube.Cube,
27 coordinate: Union[str, list[str]],
28 method: str,
29 additional_percent: float = None,
30 **kwargs,
31) -> iris.cube.Cube:
32 """Collapse coordinate(s) of a cube.
34 Collapses similar (stash) fields in a cube into a cube collapsing around the
35 specified coordinate(s) and method. This could be a (weighted) mean or
36 percentile.
38 Arguments
39 ---------
40 cube: iris.cube.Cube
41 Cube to collapse and iterate over one dimension
42 coordinate: str | list[str]
43 Coordinate(s) to collapse over e.g. 'time', 'longitude', 'latitude',
44 'model_level_number', 'realization'. A list of multiple coordinates can
45 be given.
46 method: str
47 Type of collapse i.e. method: 'MEAN', 'MAX', 'MIN', 'MEDIAN',
48 'PERCENTILE' getattr creates iris.analysis.MEAN, etc For PERCENTILE
49 YAML file requires i.e. method: 'PERCENTILE' additional_percent: 90
51 Returns
52 -------
53 cube: iris.cube.Cube
54 Single variable but several methods of aggregation
56 Raises
57 ------
58 ValueError
59 If additional_percent wasn't supplied while using PERCENTILE method.
60 """
61 if method == "PERCENTILE" and additional_percent is None:
62 raise ValueError("Must specify additional_percent")
63 with warnings.catch_warnings():
64 warnings.filterwarnings(
65 "ignore", "Cannot check if coordinate is contiguous", UserWarning
66 )
67 warnings.filterwarnings(
68 "ignore", "Collapsing spatial coordinate.+without weighting", UserWarning
69 )
70 if method == "PERCENTILE":
71 collapsed_cube = cube.collapsed(
72 coordinate, getattr(iris.analysis, method), percent=additional_percent
73 )
74 else:
75 collapsed_cube = cube.collapsed(coordinate, getattr(iris.analysis, method))
76 return collapsed_cube
79# TODO
80# Collapse function that calculates means, medians etc across members of an
81# ensemble or stratified groups. Need to allow collapse over realisation
82# dimension for fixed time. Hence will require reading in of CubeList