# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown copyright. The Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
This module defines the Accumulation class for calculating precipitation
accumulations from advected radar fields. It is also possible to create longer
accumulations from shorter intervals.
"""
from typing import List, Optional, Tuple, Union
import iris
import numpy as np
from iris.cube import Cube, CubeList
from numpy import ndarray
from improver import BasePlugin
from improver.metadata.check_datatypes import check_mandatory_standards
from improver.utilities.cube_manipulation import expand_bounds
[docs]class Accumulation(BasePlugin):
"""
Class to calculate precipitation accumulations from radar rates fields
provided at discrete time intervals. The plugin will calculate
accumulations between each pair of rates fields provided. These will be
used to construct the accumulation period requested when possible, and
cubes of this desired period are then returned.
"""
[docs] def __init__(
self,
accumulation_units: str = "m",
accumulation_period: Optional[int] = None,
forecast_periods: Optional[List[float]] = None,
) -> None:
"""
Initialise the plugin.
Args:
accumulation_units:
The physical units in which the accumulation should be
returned. The default is metres.
accumulation_period:
The desired accumulation period in seconds. This period
must be evenly divisible by the time intervals of the input
cubes. The default is None, in which case an accumulation is
calculated across the span of time covered by the input rates
cubes.
forecast_periods:
The forecast periods in seconds that define the end of an
accumulation period.
"""
self.accumulation_units = accumulation_units
self.accumulation_period = accumulation_period
self.forecast_periods = forecast_periods
def __repr__(self) -> str:
"""Represent the plugin instance as a string."""
result = (
"<Accumulation: accumulation_units={}, "
"accumulation_period={}s, "
"forecast_periods={}s>"
)
return result.format(
self.accumulation_units, self.accumulation_period, self.forecast_periods
)
[docs] @staticmethod
def sort_cubes_by_time(cubes: CubeList) -> Tuple[CubeList, List[int]]:
"""
Sort cubes in time ascending order (from earliest time to latest time).
Args:
cubes:
A cubelist containing input precipitation rate cubes.
Returns:
- The cubelist in ascending time order.
- A list of the validity times of the precipitation rate
cubes in integer seconds since 1970-01-01 00:00:00.
"""
times = np.array([cube.coord("time").points[0] for cube in cubes])
time_sorted = np.argsort(times)
times = times[time_sorted]
cubes = iris.cube.CubeList(np.array(cubes)[time_sorted])
return cubes, times
[docs] def _get_cube_subsets(
self, cubes: CubeList, forecast_period: Union[int, ndarray]
) -> CubeList:
"""Finding the subset of cubes from the input cubelist that are
within the accumulation period, based on the required forecast period
that defines the upper bound of the accumulation period and the length
of the accumulation period.
Args:
cubes:
Cubelist containing all the rates cubes that are available
to be used to calculate accumulations.
forecast_period:
Forecast period in seconds matching the upper bound of the
accumulation period.
Returns:
Cubelist that defines the cubes used to calculate
the accumulations.
"""
# If the input is a numpy array, get the integer value from the array
# for use in the constraint.
if isinstance(forecast_period, np.ndarray):
(forecast_period,) = forecast_period
start_point = forecast_period - self.accumulation_period
constr = iris.Constraint(
forecast_period=lambda fp: start_point <= fp <= forecast_period
)
return cubes.extract(constr)
[docs] @staticmethod
def _calculate_accumulation(
cube_subset: CubeList, time_interval: float
) -> Optional[ndarray]:
"""Calculate the accumulation for the requested accumulation period
by finding the mean rate between each adjacent pair of cubes within
the cube_subset and multiplying this mean rate by the time_interval,
in order to compute an accumulation. The accumulation between each
pair of cubes is summed, in order to generate a total accumulation
using all of the cubes within the cube_subset.
Args:
cube_subset:
Cubelist containing all the rates cubes that will be used
to calculate the accumulation.
time_interval:
Interval between the timesteps from the input cubelist.
Returns:
If either the forecast period given by the input cube is not
a requested forecast_period at which to calculate the
accumulations, or the number of input cubelist is only
sufficient to partially cover the desired accumulation, then
None is returned.
If an accumulation can be successfully computed, then a
numpy array is returned.
"""
accumulation = 0.0
# Accumulations are calculated using the mean precipitation rate
# calculated from the rates cubes that bookend the desired period.
iterator = zip(cube_subset[0:-1], cube_subset[1:])
for start_cube, end_cube in iterator:
accumulation += (start_cube.data + end_cube.data) * time_interval * 0.5
return accumulation
[docs] def process(self, cubes: CubeList) -> CubeList:
"""
Calculate period precipitation accumulations based upon precipitation
rate fields. All calculations are performed in SI units, so
precipitation rates are converted to "m/s" and times into seconds
before calculations are performed. The output units of accumulation
are set by the plugin keyword argument accumulation_units.
Args:
cubes:
A cubelist containing input precipitation rate cubes.
Returns:
A cubelist containing precipitation accumulation cubes where
the accumulation periods are determined by plugin argument
accumulation_period.
"""
cubes, time_interval = self._check_inputs(cubes)
accumulation_cubes = iris.cube.CubeList()
for forecast_period in self.forecast_periods:
cube_subset = self._get_cube_subsets(cubes, forecast_period)
accumulation = self._calculate_accumulation(cube_subset, time_interval)
accumulation_cube = self._set_metadata(cube_subset)
# Calculate new data and insert into cube.
accumulation_cube.data = accumulation
accumulation_cube.convert_units(self.accumulation_units)
accumulation_cubes.append(accumulation_cube)
return accumulation_cubes