improver.utilities.spatial_morphing module#
Plugin for spatial morphing between forecast sources using Google FILM.
- class SpatialMorphing(forecast_period, cluster_number, model_id_attr='mosg__model_configuration', cycletime=None, selection_attr='spatial_morphing', selection_attr_value='cluster_medoid', transitions=None, model_path=None, scaling='minmax', clipping_bounds=None, clip_in_scaled_space=True, clip_to_physical_bounds=False, model_loader=None, transition_weights_scheme='linear', morphing_method='google_film', apply_suppression=False, suppression_config=None, suppression_stages=None)[source]#
Bases:
BasePluginSpatially morph between forecast sources for a selected realization cluster.
This plugin builds upon RealizationSelection to select realizations from multiple forecast sources according to cluster assignments, then applies spatial morphing using Google FILM to create seamless transitions between different source models.
Unlike hard joins (RealizationSelection alone), this plugin produces spatially smooth blended forecasts where different sources contribute smoothly based on configured transition characteristics.
The input cubes are all expected to represent the same validity time. The forecast period is used only to determine the blending weight within a configured transition window between source_a and source_b; it is not treated as a separate time for temporal interpolation. In other words, this is a model-blending step at one valid time, with the resulting weight passed to the morphing backend for spatial blending between the two source fields.
Workflow: 1. Split input cubes into forecast cubes and cluster cube (from
RealizationClusterAndMatch).
Validate that all forecast cubes have the same validity time and, if requested, update forecast_reference_time using the supplied cycletime.
Parse the cluster mapping attributes to identify the selected source and realization for the requested cluster at the target forecast period.
Check whether the mapped source/realization is available on the provided input cubes; if not, fall back to an alternative valid source for the same cluster.
Diagnose the source and realization pair that should be used for any active transition at this forecast period, including the two source models and their weights for the blended result.
Extract the selected realizations from each contributing source and apply the configured morphing backend (Google FILM by default) to generate a seamless blended output.
Optionally apply one or more local suppression stages to the morphed result: weak_signal damps broad low-intensity excess above a source-weighted reference; convective restores locally concentrated shower-like peaks indicated by the source neighbourhood structure; upper_tail restores high-end intensity where convective signal exists but the morphed upper tail is weaker than source-derived upper-tail expectations.
Finalise the output cube by cleaning metadata, setting the selected cluster as the realization coordinate, and recording expected/actual forecast contributor provenance.
This plugin is designed to work with output from RealizationClusterAndMatch, providing a more direct spatial morphing alternative to the RealizationSelection to ForecastTrajectoryGapFiller pipeline.
- __init__(forecast_period, cluster_number, model_id_attr='mosg__model_configuration', cycletime=None, selection_attr='spatial_morphing', selection_attr_value='cluster_medoid', transitions=None, model_path=None, scaling='minmax', clipping_bounds=None, clip_in_scaled_space=True, clip_to_physical_bounds=False, model_loader=None, transition_weights_scheme='linear', morphing_method='google_film', apply_suppression=False, suppression_config=None, suppression_stages=None)[source]#
Initialise the SpatialMorphing plugin.
- Parameters:
forecast_period (
int) – The forecast period in seconds used to identify the cluster mapping entries that define the source realizations for each source model.cluster_number (
int) – The cluster index to select and output.model_id_attr (
str) – Name of the cube attribute that identifies the source model. Defaults to “mosg__model_configuration”.cycletime (
str|None) – Forecast reference time to apply to the input cubes. If set, the forecast periods are updated while keeping validity times fixed. Expected format is YYYYMMDDTHHMMZ.selection_attr (
str|None) – Optional attribute name to set on the output cube to note that the realization was selected by this plugin.selection_attr_value (
str) – Value assigned toselection_attrwhen it is set.transitions (
dict[str,Any] |None) – Optional explicit transition specification. This can be either a dictionary containing a “transitions” list or a list of transition dictionaries with keys “source_a”, “source_b”, “start_forecast_period_minutes” and “end_forecast_period_minutes”.model_path (
str|None) – Path to the TensorFlow Hub module used by Google FILM.scaling (
str) – Scaling strategy applied by Google FILM. One of “log10” or “minmax”.clipping_bounds (
tuple[float,float] |None) – Optional lower and upper physical bounds used when clipping the morphed field.clip_in_scaled_space (
bool) – If True, clipping is applied before reverse scaling.clip_to_physical_bounds (
bool) – If True, clipping is applied after reverse scaling to the physical domain.transition_weights_scheme (
str) – Weighting scheme used during a transition. Supported values are “linear” and “smoothstep”.morphing_method (
str) – Spatial morphing backend to use for transitions. Supported values are “google_film” (default) and “linear”.apply_suppression (
bool) – If True, apply the local suppression workflow to the morphed result.suppression_config (
dict[str,Any] |None) – Optional dictionary of tuning parameters for the local suppression workflow.suppression_stages (
list[str] |tuple[str,...] |None) – Optional list of suppression stages to apply. Supported values are “weak_signal”, “convective”, and “upper_tail”.
- Returns:
None.
- Raises:
ValueError – If transition_weights_scheme is not recognised.
ValueError – If morphing_method is not recognised.
- _abc_impl = <_abc._abc_data object>#
- _apply_morphing(result_cube, cluster_to_selection, forecast_cubes, cluster_available_source_names, cluster_cube, full_cluster_to_selection, primary_map, secondary_map)[source]#
Apply any active transition morphing and update provenance metadata.
This method resolves the actual source selected for the current cluster, checks whether the forecast period lies within a configured transition, and, if so, applies the active source transition logic (including optional local suppression) before returning the final cube for provenance finalisation.
- Parameters:
result_cube (
Cube) – The cube selected before any transition remapping.cluster_to_selection (
dict[int,tuple[str,int]]) – Selected source and realization for the current cluster after any fallback logic.forecast_cubes (
CubeList) – Available forecast cubes.cluster_available_source_names (
set[str]) – Source names available for the selected cluster, constrained by cluster_sources metadata and the input forecast cubes.cluster_cube (
Cube) – Cube containing the cluster metadata.full_cluster_to_selection (
dict[int,tuple[str,int]]) – Full cluster-to-source/realization lookup.primary_map (
dict[str,int]) – Primary cluster-to-realization mapping e.g. {‘0’: 49, ‘1’: 33, ‘2’: 44, ‘3’: 29} where the key is the cluster number and the value is the realization index.secondary_map (
dict[str,dict[str,list[dict[str,list[int]]]]] |None) – Secondary realization map e.g. {‘source_a’: {‘0’: [{‘realization’: 17, ‘forecast_periods’: [475200, 518400, 561600, 604800, 648000]}]}} where the key is the source name, the value is a dictionary keyed by cluster number.
- Return type:
- Returns:
The cube after the active transition has been applied (if any), or the original result cube when no transition is active.
- _apply_morphing_backend(cube_a, cube_b, weight)[source]#
Apply the configured morphing backend between two source cubes.
- Parameters:
- Return type:
- Returns:
A cube containing the blended result produced by the selected morphing backend.
- Raises:
ValueError – If the requested
morphing_methodis not supported.
- static _as_contributor(source, realization, weight)[source]#
Create a provenance contributor record for one blended source.
A contributor record describes one input field that contributed to the final morphed output for a given transition. It is a lightweight summary of the source model name, the realization index selected from that source, and the weight assigned to that source in the blended result. These records are then attached to the output cube as provenance metadata so the downstream forecast can be traced back to the specific model/realization combination that contributed to each part of the transition.
- Parameters:
- Returns:
{“source”: “model_a”, “realization”: 5, “weight”: 0.75}.
- Return type:
A dictionary representing one contributor entry, for example
- static _calculate_transition_weight(forecast_period, start_forecast_period_seconds, end_forecast_period_seconds)[source]#
Calculate the blending weight for a transition window.
This method does not perform temporal interpolation between different validity times. For a single validity time, it computes the relative position of
forecast_periodwithin the configured transition window, giving the blend fraction between source_a and source_b at that time.- Parameters:
- Return type:
- Returns:
A float in the range [0, 1] representing the relative position of the forecast period within the transition window. Values below the start of the window return 0.0 and values above the end return 1.0.
- _call_google_film_for_morphing(cube_a, cube_b, weight)[source]#
Use Google FILM to spatially morph between two source cubes.
- Parameters:
- Return type:
- Returns:
Morphed cube at the specified weight, with data returned as float32.
- Raises:
ValueError – If weight is outside [0, 1] or if FILM config is missing.
RuntimeError – If FILM returns no results.
- _choose_fallback_cluster_source(cluster_to_selection, forecast_cubes, cluster_cube, primary_map, secondary_map, requested_source, requested_realization, available_source_names, has_valid_requested_realization)[source]#
Select the first valid fallback source and realization for the cluster.
Fallback realization diagnosis is source-aware: it first uses the secondary map for the candidate fallback source, and only if that is unavailable does it fall back to the primary-map realization for the cluster.
- Parameters:
cluster_to_selection (
dict[int,tuple[str,int]]) – Mapping from cluster number to selected source and realization.forecast_cubes (
CubeList) – List of forecast cubes to select from.cluster_cube (
Cube) – Cube containing the cluster mapping metadata.primary_map (
dict[str,int]) – Primary cluster-to-realization mapping e.g. {‘0’: 49, ‘1’: 33, ‘2’: 44, ‘3’: 29} where the key is the cluster number and the value is the realization index.secondary_map (
dict[str,dict[str,list[dict[str,list[int]]]]] |None) – Secondary realization map e.g. {‘source_a’: {‘0’: [{‘realization’: 17, ‘forecast_periods’: [475200, 518400, 561600, 604800, 648000]}]}} where the key is the source name, the value is a dictionary keyed by cluster number.requested_source (
str) – The source that was originally requested for the cluster.requested_realization (
int) – The realization that was originally requested for the cluster.available_source_names (
set[str]) – Set of source names present on the forecast cubes.has_valid_requested_realization (
bool) – Whether the requested source and realization are valid and present on the forecast cubes.
- Return type:
- Returns:
Updated cluster_to_selection mapping with a valid source and realization for the requested cluster number.
- Warns:
If the requested source and realization are unavailable and no valid
fallback source is found, a warning is issued.
If the requested source is unavailable but a valid fallback source is
found, a warning is issued indicating the fallback source and
realization being used.
- _diagnose_expected_morphing_contributions(expected_selected_source, expected_selected_realization, cluster_available_source_names, full_cluster_to_selection, primary_map, secondary_map, cluster_cube)[source]#
Set expected provenance metadata for the selected cluster and forecast.
This method determines whether the selected cluster falls within an active transition and, if so, records the expected source/realization contribution(s) that should appear in the final blended output. The values are stored in
self.expected_forecast_contributorsfor later provenance reporting.- Parameters:
expected_selected_source (
str) – Source model selected by the initial cluster mapping.expected_selected_realization (
int) – Realization selected by the initial cluster mapping.cluster_available_source_names (
set[str]) – Source names available for the selected cluster, constrained by cluster_sources metadata and the input forecast cubes.full_cluster_to_selection (
dict[int,tuple[str,int]]) – Full cluster-to-source/realization lookup.primary_map (
dict[str,int]) – Primary cluster-to-realization mapping e.g. {‘0’: 49, ‘1’: 33, ‘2’: 44, ‘3’: 29} where the key is the cluster number and the value is the realization index.secondary_map (
dict[str,dict[str,list[dict[str,list[int]]]]] |None) – Secondary realization map e.g. {‘source_a’: {‘0’: [{‘realization’: 17, ‘forecast_periods’: [475200, 518400, 561600, 604800, 648000]}]}} where the key is the source name, the value is a dictionary keyed by cluster number.cluster_cube (
Cube) – Cube containing the cluster metadata used to diagnose source/realization selections.
- Return type:
- Returns:
None. This method updates expected contributor metadata on the plugin instance.
- _diagnose_realization_for_source(source_name, cluster_number, target_period, primary_map, secondary_map, cluster_cube, full_cluster_to_selection)[source]#
Diagnose the realization index for a source at or near a target period.
- Parameters:
source_name (
str) – Source label to diagnose for.cluster_number (
int) – Cluster being processed.target_period (
int) – Forecast period in seconds used to find the most relevant source realization.primary_map (
dict[str,int]) – Primary cluster-to-realization mapping e.g. {‘0’: 49, ‘1’: 33, ‘2’: 44, ‘3’: 29} where the key is the cluster number and the value is the realization index.secondary_map (
dict[str,dict[str,list[dict[str,list[int]]]]] |None) – Optional secondary realization map e.g. {‘source_a’: {‘0’: [{‘realization’: 17, ‘forecast_periods’: [475200, 518400, 561600, 604800, 648000]}]}} where the key is the source name, the value is a dictionary keyed by cluster number.cluster_cube (
Cube) – Cube containing the cluster mapping metadata.full_cluster_to_selection (
dict[int,tuple[str,int]]) – Full mapping from cluster number to the selected source/realization pairing.
- Return type:
- Returns:
The matching realization index if one can be diagnosed, otherwise None.
- _finalise_output_cube(result_cube)[source]#
Apply final attribute and coordinate cleanup before returning output.
- _find_active_transition(forecast_period, selected_source_name=None, available_source_names=None)[source]#
Return the active transition for the supplied forecast period and source.
If multiple transitions are active at the same forecast period, the selected source name is used to choose between them. If available source names are supplied, the active transition is further constrained to those whose source pair is actually usable with the input forecast cubes. In particular, if an active transition window exists but neither source in the defining source pair is available in the supplied inputs, this method returns None so the caller can skip morphing and retain the already selected source without raising an exception.
- Parameters:
- Return type:
- Returns:
The active transition dictionary if found, otherwise None.
Examples
No active transition window covers the forecast period: returns None.
A -> Bis active, but neitherAnorBis present inavailable_source_names. In this case the transition is unusable, so the method returns None and the caller keeps the already selected source (for exampleC) instead of trying to morph betweenAandB.A -> Bis active and bothAandBare available: returns that transition so morphing can proceed.If the selected source is
Aand bothA -> BandA -> Care active, but onlyBis available, the method selectsA -> B. In other words, the usable partner is whichever active transition endpoint is present.If the selected source is
Aand bothBandCare available as active partners, the method raises ValueError because the choice is ambiguous.
- Raises:
ValueError – If overlapping active transitions require a selected source name to disambiguate them, or if a selected source is involved in an active transition window but no compatible transition can be resolved after filtering against the available input sources.
- static _format_transition_mismatch_error(forecast_period, selected_source_name, active_transitions, available_source_names)[source]#
Format an explanatory error for a missing transition match.
- Parameters:
forecast_period (
int) – The forecast period (in seconds) that was checked.selected_source_name (
str) – The source name that was used to select a transition.active_transitions (
list[dict[str,Any]]) – List of transitions that were active at the forecast period.available_source_names (
set[str] |None) – Optional set of source names present on the input forecast cubes.
- Return type:
- Returns:
A formatted error message explaining the mismatch.
- _get_cluster_available_source_names(forecast_cubes, cluster_cube, cluster_number)[source]#
Get source names available for the requested cluster.
- Parameters:
- Return type:
- Returns:
Set of source names that are both listed for the cluster and present on the provided forecast cubes.
- Raises:
ValueError – If cluster_sources metadata is missing or does not include the requested cluster.
- static _match_transition_against_sources(active_transitions, selected_source_name, available_source_names)[source]#
Return the first transition that is both active and compatible.
In practice, “active” means the transition definition covers the target forecast period, i.e. the period lies between the transition’s configured start and end bounds. “Compatible” means the transition can be used with the current source set: one side of the transition must match the selected source name, and the other side must be available on the input forecast cubes (when a source list is supplied).
This method therefore filters the list of active transitions to those that are relevant to the chosen source and that do not reference a model source which is absent from the available forecast inputs.
- Parameters:
active_transitions (
list[dict[str,Any]]) – Transition definitions that are active at the target forecast period.selected_source_name (
str) – Source name used to choose the correct transition when multiple definitions overlap.available_source_names (
set[str] |None) – Optional set of source names present on the input forecast cubes; used to restrict matches to sources that are actually available.
- Return type:
- Returns:
The matching transition dictionary, or None if no compatible transition is found.
- Raises:
ValueError – If more than one compatible transition remains after filtering by the selected source and available source set. This indicates the configuration is ambiguous and cannot be resolved without additional information.
- _parse_transitions(transitions)[source]#
Validate and format explicit transition definitions.
- Parameters:
transitions (
dict[str,Any] |None) – Transition specification to parse. This may be a dictionary containing a top-level “transitions” list, a list of transition dictionaries, or None.- Return type:
- Returns:
A formatted list of transition dictionaries with forecast-period bounds converted to seconds. If transitions is None, returns an empty list.
- Raises:
TypeError – If transitions is not a dictionary, list, or None.
TypeError – If an individual transition entry is not a dictionary.
ValueError – If the transition data are malformed or missing required keys.
- _prepare_inputs(*cubes)[source]#
Flatten and validate the input cubes before morphing.
- Parameters:
*cubes (
Any) – Inputs passed to process; may be a single CubeList or multiple Cube objects.- Returns:
validated forecast cubes
the cluster cube.
- Return type:
Tuple of
- _resolve_cluster_selection(cluster_cube)[source]#
Resolve the cluster-to-source mapping for the selected forecast period.
- Parameters:
cluster_cube (
Cube) – Cube containing cluster mapping metadata.- Returns:
full_cluster_to_selection: mapping from cluster number to selected source/realization
- primary_map: Primary cluster-to-realization mapping e.g.
{‘0’: 49, ‘1’: 33, ‘2’: 44, ‘3’: 29} where the key is the cluster number and the value is the realization index.
- secondary_map: Secondary realization map e.g.
{‘source_a’: {‘0’: [{‘realization’: 17, ‘forecast_periods’: [475200, 518400, 561600, 604800, 648000]}]}} where the key is the source name, the value is a dictionary keyed by cluster number.
- Return type:
A tuple of
- Raises:
ValueError – If the requested cluster number is not found in the mapping.
- _resolve_cluster_selection_with_available_sources(cluster_to_selection, forecast_cubes, cluster_cube, primary_map, secondary_map)[source]#
Fall back to an available source if the mapped source is absent or invalid
- Parameters:
cluster_to_selection (
dict[int,tuple[str,int]]) – Mapping from cluster number to selected source and realization.forecast_cubes (
CubeList) – List of forecast cubes to select from.cluster_cube (
Cube) – Cube containing the cluster mapping metadata.primary_map (
dict[str,int]) – Primary cluster-to-realization mapping e.g. {‘0’: 49, ‘1’: 33, ‘2’: 44, ‘3’: 29} where the key is the cluster number and the value is the realization index.secondary_map (
dict[str,dict[str,list[dict[str,list[int]]]]] |None) – Secondary realization map e.g. {‘source_a’: {‘0’: [{‘realization’: 17, ‘forecast_periods’: [475200, 518400, 561600, 604800, 648000]}]}} where the key is the source name, the value is a dictionary keyed by cluster number.
- Return type:
- Returns:
Updated cluster_to_selection mapping with a valid source and realization for the requested cluster number.
- _select_single_source_cube(source_name, realization_index, forecast_cubes)[source]#
Select the single source cube needed for morphing.
This is a convenience wrapper around the more general
RealizationSelection.select_realizations_for_clustershelper. The generic helper is designed to select a list of cubes for a cluster-to- source mapping, whereas the morphing path needs exactly one field for one source and one realization at a time. This method therefore builds a one-entry cluster selection map, extracts the matching cube, and returns the result directly.A
Nonereturn indicates that the requested source/realization pair is not available in the current input cube set. This is handled gracefully in the transition logic as a non-fatal fallback so morphing can skip an unavailable source rather than aborting the whole selection.- Parameters:
- Return type:
- Returns:
The selected source cube for the requested source and realization, or
Noneif the source/realization cannot be extracted from the available inputs.
- _select_transition_source_cubes(active_transition, forecast_cubes, cluster_number, secondary_map, primary_map, cluster_cube, full_cluster_to_selection)[source]#
Select the source cubes and transition weight for the active transition.
- Parameters:
active_transition (
dict[str,Any]) – Active transition definition for the target forecast period.forecast_cubes (
CubeList) – Available forecast cubes.cluster_number (
int) – Requested cluster number.secondary_map (
dict[str,dict[str,list[dict[str,list[int]]]]] |None) – Secondary realization map e.g. {‘source_a’: {‘0’: [{‘realization’: 17, ‘forecast_periods’: [475200, 518400, 561600, 604800, 648000]}]}} where the key is the source name, the value is a dictionary keyed by cluster number.primary_map (
dict[str,int]) – Primary cluster-to-realization mapping e.g. {‘0’: 49, ‘1’: 33, ‘2’: 44, ‘3’: 29} where the key is the cluster number and the value is the realization index.cluster_cube (
Cube) – Cube containing cluster metadata.full_cluster_to_selection (
dict[int,tuple[str,int]]) – Mapping from every cluster number to the selected source and realization for that cluster, e.g. {0: (“uk_ens”, 8), 1: (“uk_ens”, 7), 2: (“uk_ens”, 6)}. This is the comprehensive cluster-to-source selection table used to resolve source/realization choices across all clusters; the current cluster number is then selected from this table when a transition is being evaluated.
- Return type:
tuple[Cube|None,Cube|None,float|None,int|None,int|None]- Returns:
A tuple of
(cube_a, cube_b, weight, source_a_realization, source_b_realization), where weight is the morphing weight for the active transition or None if no transition is being applied.
- process(*cubes)[source]#
Select realizations from forecast sources and apply spatial morphing.
Uses RealizationSelection workflow to identify which realization from which forecast source corresponds to the requested cluster_number, then applies Google FILM spatial morphing if needed to create seamless blends.
- Parameters:
*cubes (
Any) – Input cubes (CubeList or multiple Cube objects) containing forecast cubes from different sources (all at same validity time) and a cluster cube with mapping attributes from RealizationClusterAndMatch.- Return type:
- Returns:
Single Cube containing the selected and (if applicable) spatially morphed realization, relabelled to cluster_number.
- Raises:
RuntimeError – If no realization is selected for the requested cluster.
- class SpatialMorphingSuppression(suppression_config=None, suppression_stages=None)[source]#
Bases:
BasePluginApply local precipitation suppression stages to a morphed transition field.
This plugin encapsulates the suppression workflow used after spatial morphing, including weak-signal damping, convective restoration, and upper-tail restoration. It is designed specifically for precipitation-like fields where wet-threshold and intensity-tail logic is meaningful. The implementation does not enforce a diagnostic-name check because multiple precipitation diagnostics (for example, accumulation or rate) may be valid inputs. Callers are therefore expected to pass precipitation diagnostics only.
- __init__(suppression_config=None, suppression_stages=None)[source]#
Initialise suppression settings for morphed fields.
- _abc_impl = <_abc._abc_data object>#
- _compute_weak_signal_suppression(result_data, source_a_data, source_b_data, weighted_reference, valid_mask, weight, threshold, quantile_for_centre, width_fraction, maximum_suppression, showery_neighbourhood_size, showery_weight_factor, weakness_weight_factor, sigmoid_clip_limit)[source]#
Reduce broad weak wet halos while retaining coherent source-supported rain.
This stage damps the portion of the morphed field that sits above a source- weighted reference. The reference is a weighted average of the two source fields, so the suppression acts only on excess precipitation that falls outside the local source-supported envelope rather than on the whole field.
The motivation is to avoid Google FILM turning sparse showers into a broad area of light precipitation. In other words, the method suppresses the weak, diffuse excess that can appear around the transition without removing the coherent rain that is still supported by the source fields.
The strength of the correction is based on two complementary indicators:
A weak-signal diagnostic that compares the morphed intensity with a source-derived central quantile. This identifies the broad, diffuse areas where the transition is only weakly supported by the source data.
A local showery diagnostic based on wet-occurrence in the neighbouring source pixels. This increases the suppression where the signal looks spatially diffuse or low confidence, rather than strongly tied to the source precipitation structure.
The term “logistic” here refers to a smooth sigmoid-shaped transfer function, not a fitted logistic-regression model. It is used because the suppression should change gradually as the signal moves away from the source-supported centre, rather than switching abruptly at a hard threshold. As the morphed intensity rises above that centre, the function transitions smoothly from weak support toward stronger confidence, which is then converted into a capped suppression amount.
The method does not force the field back below the weighted reference in a hard step. Instead, it reduces only the positive excess by a capped amount, which helps remove weak, widespread FILM artefacts while preserving coherent rain structures that are supported by the source fields.
Example
Suppose
weight=0.5, source A is 100, source B is 200, and the morphed value is 170 at one point. The weighted reference is0.5 * 100 + 0.5 * 200 = 150, so the excess is170 - 150 = 20. If the combined correction fraction at that point is 0.4, the output is170 - 0.4 * 20 = 162. If the correction fraction were 0, the point would remain 170.- Parameters:
result_data (
ndarray) – Morphed output data before suppression.source_a_data (
ndarray) – Source-a data array.source_b_data (
ndarray) – Source-b data array.weighted_reference (
ndarray) – Weighted source reference data already calculated in the parent process method.valid_mask (
ndarray) – Boolean mask for points valid across all inputs.weight (
float) – Morphing weight in the range [0, 1].threshold (
float) – Wet-occurrence threshold for the source fields.quantile_for_centre (
float) – Quantile of the valid source signal used to set the centre of the smooth sigmoid transition.width_fraction (
float) – Fractional width of the sigmoid around that centre.maximum_suppression (
float) – Upper bound on the suppression fraction applied to excess precipitation.showery_neighbourhood_size (
int) – Neighbourhood size for the showery diagnosis.showery_weight_factor (
float) – Weight applied to the showery term in the final correction.weakness_weight_factor (
float) – Weight applied to the weak-signal term in the final correction.sigmoid_clip_limit (
float) – Maximum absolute value used to clip the normalised sigmoid input before exponentiation.
- Returns:
suppression-adjusted output data array
weighted source reference array.
- Return type:
Tuple of
- static _diagnose_convective_weight(result_data, source_a_data, source_b_data, weighted_reference, valid_mask, threshold, convective_neighbourhood_size, convective_gain, concentration_reference, concentration_scale)[source]#
Diagnose where the source fields are locally convective or shower-like.
This stage looks for small, intense precipitation structures that are still present in the source fields but may have been weakened by the earlier broad weak-signal suppression. It compares the local maximum in a neighbourhood to the local mean, which gives a simple measure of how concentrated the rain is.
A larger value means the precipitation is more sharply peaked, which usually indicates a convective or shower-like structure. The diagnosed weight is then used to nudge the output back toward the higher of the current result and the weighted source reference, but only in those locally concentrated areas. If the current FILM result is already stronger than the source-informed target, no additional uplift is applied and the field is left unchanged.
Example
Suppose at one point
result_data=30andweighted_reference=50so the local target is 50. If local concentration givesconvective_weight=0.8andconvective_gain=0.5, the uplift is0.5 * 0.8 * (50 - 30) = 8and the corrected value becomes 38. If insteadresult_data=55, the target is 55 andtarget - result_data = 0, so no convective uplift is applied.- Parameters:
result_data (
ndarray) – Current output data to adjust.source_a_data (
ndarray) – Source-a data array.source_b_data (
ndarray) – Source-b data array.weighted_reference (
ndarray) – Weighted source reference data.valid_mask (
ndarray) – Boolean mask for points valid across all inputs.threshold (
float) – Minimum allowed denominator when comparing local max and mean.convective_neighbourhood_size (
int) – Size of the neighbourhood used for the local statistics.convective_gain (
float) – Strength of the local restoration in convective areas.concentration_reference (
float) – Baseline concentration value for the start of the convective response.concentration_scale (
float) – Spread of the concentration-to-weight conversion.
- Returns:
output data with local convective intensity restored
diagnosed convective weight array.
- Return type:
Tuple of
- static _restore_upper_tail(result_data, source_a_data, source_b_data, valid_mask, convective_weight, weight, threshold, upper_tail_quantile, convective_mask_threshold, maximum_intensity_scale, upper_tail_intensity_quantile, intensity_weight_width_fraction, sigmoid_clip_limit)[source]#
Restore intense precipitation where the convective signal is still weak.
This stage compares a source-derived high-end value with the current morphed field in locally convective, wet areas. The source-derived value is calculated from the wet occurrences in both source fields at a chosen upper-tail quantile, and the current value is calculated from the same quantile in the corresponding Google FILM output.
If the current field is weaker than the expected source signal, the ratio between the two values gives a local scale factor. That scale is then applied only to the strongest wet pixels, with a cap on the maximum allowed increase so the correction stays local and physically realistic.
Example
Suppose
weight=0.5and the source wet upper-tail quantiles are 80 (source A) and 120 (source B). The source-derived target quantile is0.5 * 80 + 0.5 * 120 = 100. If the current morphed upper-tail quantile in convective wet points is 70, the raw uplift scale is100 / 70 = 1.43(before applyingmaximum_intensity_scalecap). Ifmaximum_intensity_scale=1.5, the scale remains 1.43. A point with combined local weight 0.6 then getslocal_scale = 1 + 0.6 * (1.43 - 1) = 1.258and is multiplied by 1.258, while points with near-zero weight are minimally changed.- Parameters:
result_data (
ndarray) – Current output data to adjust.source_a_data (
ndarray) – Source-a data array.source_b_data (
ndarray) – Source-b data array.valid_mask (
ndarray) – Boolean mask for points valid across all inputs.convective_weight (
ndarray) – Diagnosed convective weight array.weight (
float) – Morphing weight in the range [0, 1].threshold (
float) – Wet-value threshold.upper_tail_quantile (
float) – High-end quantile used to compare source and current upper-tail intensity.convective_mask_threshold (
float) – Minimum convective weight needed for local restoration.maximum_intensity_scale (
float) – Largest allowed local scaling factor.upper_tail_intensity_quantile (
float) – Quantile used to decide where the strongest points lie.intensity_weight_width_fraction (
float) – Fraction of the local intensity centre used as the sigmoid width for the upper-tail weight.sigmoid_clip_limit (
float) – Maximum absolute value used to clip the normalised sigmoid input before exponentiation.
- Return type:
- Returns:
Output data array after the upper-tail restoration.
- static _sanitize_valid_data(data, valid_mask)[source]#
Replace invalid values with zeros while leaving valid points unchanged.
- Return type:
- static _validate_suppression_settings(settings)[source]#
Validate merged suppression settings and transition weight.
- Parameters:
settings (
dict[str,Any]) – Fully populated suppression settings dictionary.- Return type:
- Returns:
None.
- Raises:
ValueError – If any validated setting is outside its accepted range.
- process(result_cube, source_a, source_b, weight)[source]#
Suppress weak precipitation excess in a morphed field.
The weighted mean of the two source fields is used as a smoothly varying guide rather than as a replacement field. Weak FILM precipitation is reduced more strongly than moderate or intense precipitation, helping to suppress broad, weak wet halos while preserving stronger, coherent precipitation features that FILM is intended to represent.
- Parameters:
result_cube (
Cube) – Precipitation field produced by morphing.source_a (
Cube) – Precipitation source field at the beginning of the transition.source_b (
Cube) – Precipitation source field at the end of the transition.weight (
float) – Interpolation weight in [0, 1], where 0 corresponds to source A and 1 corresponds to source B.
- Return type:
- Returns:
Cube containing the suppression-adjusted FILM result.
- Raises:
ValueError – If source and result shapes are inconsistent, or if suppression settings fail validation.
Notes
This method is intended for precipitation diagnostics only. No diagnostic-name validation is applied because different precipitation diagnostics may be supported by the same suppression logic.
- classmethod validate_suppression_config(suppression_config)[source]#
Validate suppression tuning values from config data or defaults.
- Parameters:
suppression_config (
dict[str,Any] |None) – Optional dictionary of suppression settings. If None, the class defaults are used.- Return type:
- Returns:
Dictionary containing a complete suppression configuration with all expected keys populated.
- Raises:
TypeError – If suppression_config is not a dictionary or None.
ValueError – If suppression_config contains unsupported keys.
- classmethod validate_suppression_stages(suppression_stages)[source]#
Validate the requested suppression stages and return canonical names.
If no suppression stages are specified, an empty tuple is returned so that no suppression is applied by default.
- Parameters:
suppression_stages (
list[str] |tuple[str,...] |None) – Optional stage names requested by the caller.- Return type:
- Returns:
Tuple of canonical stage names in execution order. An empty tuple means that suppression is disabled.
- Raises:
ValueError – If an unsupported stage name is provided.
- _active_source_names_for_exact_period(periods_to_sources, sorted_periods, exact_index)[source]#
Get active source names when target forecast period is an exact match.
- Parameters:
periods_to_sources (
dict[int,set[str]]) – Mapping from forecast period (seconds) to one or more source names that are active at that period.sorted_periods (
list[int]) – Increasing list of forecast periods available inperiods_to_sources.exact_index (
int) – Index insorted_periodswhere the target forecast period is located.
- Return type:
- Returns:
Ordered list of relevant source names. This includes sources from the immediately preceding period plus the exact-period source(s), or the exact-period source(s) plus the immediate successor when no preceding period exists.
- _active_source_names_for_nearest_periods(periods_to_sources, sorted_periods, insertion_index)[source]#
Get active source names when target period lies between known periods.
- Parameters:
periods_to_sources (
dict[int,set[str]]) – Mapping from forecast period (seconds) to one or more source names that are active at that period.sorted_periods (
list[int]) – Increasing list of forecast periods available inperiods_to_sources.insertion_index (
int) – Index where the target forecast period would be inserted intosorted_periodswhile preserving sorted order.
- Return type:
- Returns:
Ordered list of relevant source names derived from the nearest bounding periods, or from the nearest edge period when the target is outside the known period range.
- get_active_source_names_for_forecast_period(cluster_sources, target_fp)[source]#
Return the source names that are active at a given forecast period.
The cluster metadata associates each source with a list of valid forecast periods. For a target time between two transition bounds, the relevant sources are the two bounding sources. If the target period exactly matches a bound, the matching source and the preceding source are returned; if there is no preceding source, the first source and its immediate successor are used.