improver.blending.weights module

Module to create the weights used to blend data.

class ChooseDefaultWeightsLinear(y0val, ynval)[source]

Bases: BasePlugin

Calculate Default Weights using Linear Function.

__init__(y0val, ynval)[source]

Set up for calculating default weights using linear function.

Parameters:
  • y0val (float) – Relative weight of first point. Must be positive.

  • ynval (float) – Relative weight of last point.

_abc_impl = <_abc_data object>
linear_weights(num_of_weights)[source]

Create linear weights

Parameters:

num_of_weights (int) – Number of weights to create.

Return type:

ndarray

Returns:

array of weights, sum of all weights = 1.0

process(cube, coord_name)[source]

Calculated weights for a given cube and coord. Weights scale linearly between self.y0val and self.ynval for the cube provided in ascending order of blend coordinate. self.y0val = self.ynval gives equal weightings across all input fields.

Parameters:
  • cube (Cube) – Cube to blend across the coord.

  • coord_name (str) – Name of coordinate in the cube to be blended.

Return type:

Cube

Returns:

1D cube of normalised (sum = 1.0) weights matching length of input dimension to be blended

Raises:

TypeError – input is not a cube

class ChooseDefaultWeightsNonLinear(cval)[source]

Bases: BasePlugin

Calculate Default Weights using NonLinear Function.

__init__(cval)[source]

Set up for calculating default weights using non-linear function.

Parameters:

cval (float) – Value greater than 0, less than equal 1.0. Weights are calculated for input cubes in order such that the first has weight cval**0, then cval**1, cval**2, etc. The weights are then re-normalised. Thus a value of 1 gives equal weighting across all input fields.

Raises:

ValueError – an inappropriate value of cval is input.

_abc_impl = <_abc_data object>
nonlinear_weights(num_of_weights)[source]

Create nonlinear weights.

Parameters:

num_of_weights (int) – Number of weights to create

Return type:

ndarray

Returns:

Normalised array of weights

process(cube, coord_name, inverse_ordering=False)[source]

Calculate nonlinear weights for a given cube and coord.

Parameters:
  • cube (Cube) – Cube to be blended across the coord.

  • coord_name (str) – Name of coordinate in the cube to be blended.

  • inverse_ordering (bool) – The input cube blend coordinate will be in ascending order, so that calculated blend weights decrease with increasing value. For eg cycle blending by forecast reference time, we wish to weight more recent cubes more highly. This flag gives the option to reverse the blend coordinate order so as to have higher weights for the higher values.

Return type:

Cube

Returns:

1D cube of normalised (sum = 1.0) weights matching input dimension to be blended

Raises:

TypeError – input is not a cube

class ChooseDefaultWeightsTriangular(width, units='no_unit')[source]

Bases: BasePlugin

Calculate Default Weights using a Triangular Function.

__init__(width, units='no_unit')[source]

Set up for calculating default weights using triangular function.

Parameters:
  • width (float) – The width of the triangular function from the centre point.

  • units (Union[Unit, str]) – The cf units of the width and midpoint.

_abc_impl = <_abc_data object>
process(cube, coord_name, midpoint)[source]

Calculate triangular weights for a given cube and coord.

Parameters:
  • cube (Cube) – Cube to blend across the coord.

  • coord_name (str) – Name of coordinate in the cube to be blended.

  • midpoint (float) – The centre point of the triangular function. This is assumed to be provided in the same units as “self.width”, ie “self.parameter_units” as initialised.

Return type:

Cube

Returns:

1D cube of normalised (sum = 1.0) weights matching length of input dimension to be blended.

Raises:

TypeError – input is not a cube

static triangular_weights(coord_vals, midpoint, width)[source]

Calculate triangular weights.

Parameters:
  • coord_vals (ndarray) – An array of coordinate values that we want to calculate weights for.

  • midpoint (float) – The centre point of the triangular function.

  • width (float) – The width from the triangle’s centre point, in units of the plugin’s units argument, which will determine the triangular weighting function used to blend that specified point with its adjacent points. Beyond this width the weighting drops to zero.

Return type:

ndarray

Returns:

An array of weights, the sum of which should equal 1.0.

class ChooseWeightsLinear(weighting_coord_name, config_dict, config_coord_name='model_configuration')[source]

Bases: BasePlugin

Plugin to interpolate weights linearly to the required points, where original weights are provided as a configuration dictionary

__init__(weighting_coord_name, config_dict, config_coord_name='model_configuration')[source]

Set up for calculating linear weights from a dictionary or input cube

Parameters:
  • weighting_coord_name (str) – Standard name of the coordinate along which the weights will be interpolated. For example, if the intention is to provide weights varying with forecast period, then this argument would be “forecast_period”. This coordinate must be included within the configuration dictionary.

  • config_dict (Dict[str, Dict[str, Any]]) – Dictionary containing the configuration information, namely an initial set of weights and information regarding the points along the specified coordinate at which the weights are valid. An example dictionary is shown below.

  • config_coord_name (str) – Name of the coordinate used to select the configuration. For example, if the intention is to create weights that scale differently with the weighting_coord for different models, then MODEL_NAME_COORD would be the config_coord.

Dictionary of format:

{
    "uk_det": {
        "forecast_period": [7, 12],
        "weights": [1, 0],
        "units": "hours"
    }
    "uk_ens": {
        "forecast_period": [7, 12, 48, 54],
        "weights": [0, 1, 1, 0],
        "units": "hours"
    }
}

To assign a different constant weight to each model, choose any coordinate for “weighting_coord_name” and choose any two points for its value in the dictionary. Set the value of “weights” to be the same for both points in each model’s dictionary. For example, we can assign weights of 0.3 and 0.7 to models uk_det and uk_ens as follows:

{
    "uk_det": {
        "forecast_period": [0, 48],
        "weights": [0.3, 0.3],
        "units": "hours"
    }
    "uk_ens": {
        "forecast_period": [0, 48],
        "weights": [0.7, 0.7],
        "units": "hours"
    }
}
_abc_impl = <_abc_data object>
_calculate_weights(cube)[source]

Method to wrap the calls to other methods to support calculation of the weights by interpolation.

Parameters:

cube (Cube) – Cube containing the coordinate information that will be used for setting up the interpolation and create the new weights cube.

Return type:

Cube

Returns:

Cube containing the output from the interpolation. This has been renamed using the self.weights_key_name but otherwise matches the input cube.

_check_config_dict()[source]

Check whether the items within the configuration dictionary are present and of matching lengths.

Raises:
  • ValueError – If items within the configuration dictionary are not of matching lengths.

  • KeyError – If the required items are not present in the configuration dictionary.

Return type:

None

_create_new_weights_cube(cube, weights)[source]

Create a cube to contain the output of the interpolation. It is currently assumed that the output weights matches the size of the input cube.

Parameters:
  • cube (Cube) – Cube containing the coordinate information that will be used for setting up the new_weights_cube.

  • weights (ndarray) – Weights calculated following interpolation.

Return type:

Cube

Returns:

Cube containing the output from the interpolation. This has the same shape as “cube”, without the x and y dimensions.

_define_slice(cube)[source]

Returns a list of coordinates over which to slice the input cube to create a list of cubes for blending.

Parameters:

cube (Cube) – Cube input to plugin

Return type:

List[Coord]

Returns:

List of coordinates defining the slice to iterate over

_get_interpolation_inputs_from_dict(cube)[source]

Generate inputs required for linear interpolation.

Parameters:

cube (Cube) – Cube containing the coordinate information that will be used for setting up the interpolation inputs.

Return type:

Tuple[ndarray, ndarray, ndarray, Tuple[int, int]]

Returns:

  • Points within the configuration dictionary that will be used as the input to the interpolation.

  • Points within the cube that will be the target points for the interpolation.

  • Weights from the configuration dictionary that will be used as the input to the interpolation.

  • Values that be used if extrapolation is required. The fill values will be used as constants that are extrapolated if the target_points are outside the source_points provided. These are equal to the first and last values provided by the source weights.

static _interpolate_to_find_weights(source_points, target_points, source_weights, fill_value, axis=0)[source]

Use of scipy.interpolate.interp1d to interpolate source_weights (valid at source_points) onto target_points grid. This allows the specification of an axis for the interpolation, so that the source_weights can be a multi-dimensional numpy array.

Parameters:
  • source_points (ndarray) – Points within the configuration dictionary that will be used as the input to the interpolation.

  • target_points (ndarray) – Points within the cube that will be the target points for the interpolation.

  • source_weights (ndarray) – Weights from the configuration dictionary that will be used as the input to the interpolation.

  • fill_value (Tuple[int, int]) – Values to be used if extrapolation is required. The fill values are used for target_points that are outside the source_points grid.

  • axis (int) – Axis along which the interpolation will occur.

Return type:

ndarray

Returns:

Weights corresponding to target_points following interpolation.

_slice_input_cubes(cubes)[source]

From input iris.cube.Cube or iris.cube.CubeList, create a list of cubes with different values of the config coordinate (over which to blend), with irrelevant dimensions sliced out.

Parameters:

cubes (Union[Cube, CubeList]) – Cubes passed into the plugin.

Return type:

CubeList

Returns:

List of cubes (from which to calculate weights) with dimensions (y, x) if weighting_coord is scalar on the input cube, or (weighting_coord, y, x) if weighting_coord is non-scalar

process(cubes)[source]

Calculation of linear weights based on an input dictionary.

Parameters:

cubes (Union[Cube, CubeList]) – Cubes containing the coordinate (source point) information that will be used for setting up the interpolation. Each cube should have “self.config_coord_name” as a scalar dimension; if a merged cube is passed in, the plugin will split this into a list cubes.

Return type:

Cube

Returns:

Cube containing the output from the interpolation. DimCoords (such as model_id) will be in sorted-ascending order.

class WeightsUtilities[source]

Bases: object

Utilities for Weight processing.

static build_weights_cube(cube, weights, blending_coord)[source]

Build a cube containing weights for use in blending.

Parameters:
  • cube (Cube) – The cube that is being blended over blending_coord.

  • weights (ndarray) – Array of weights

  • blending_coord (str) – Name of the coordinate over which the weights will be used to blend data, e.g. across model name when grid blending.

Return type:

Cube

Returns:

A cube containing the array of weights.

Raises:

ValueError – If weights array is not of the same length as the coordinate being blended over on cube.

static normalise_weights(weights, axis=None)[source]

Ensures all weights add up to one.

Parameters:
  • weights (ndarray) – array of weights

  • axis (Optional[int]) – The axis that we want to normalise along for a multiple dimensional array. Defaults to None, meaning the whole array is used for the normalisation.

Return type:

ndarray

Returns:

array of weights where sum = 1.0

Raises:
  • ValueError – any negative weights are found in input.

  • ValueError – sum of weights in the input is 0.