From 5d0509f99adf30e8026c8c16c89a951f58aee674 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Wed, 29 Apr 2026 12:23:27 +0200 Subject: [PATCH 01/43] Erstelle statcorr_control.py --- hydpy/models/statcorr/__init__.py | 0 hydpy/models/statcorr/statcorr_control.py | 6 ++++++ 2 files changed, 6 insertions(+) create mode 100644 hydpy/models/statcorr/__init__.py create mode 100644 hydpy/models/statcorr/statcorr_control.py diff --git a/hydpy/models/statcorr/__init__.py b/hydpy/models/statcorr/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py new file mode 100644 index 0000000000..6cce5073b8 --- /dev/null +++ b/hydpy/models/statcorr/statcorr_control.py @@ -0,0 +1,6 @@ +class AriNQ(parametertools.Parameter): + """Average size of the water surface [km²].""" + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = float + SPAN = (0.0, None) From f84eaef310137adfb21438049df574225fc2deb4 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Tue, 21 Jul 2026 13:08:39 +0200 Subject: [PATCH 02/43] Implementierung des statcorr-Modells --- hydpy/core/optiontools.py | 98 +- hydpy/core/sequencetools.py | 2 + hydpy/core/typingtools.py | 2 + hydpy/interfaces/statcorrinterfaces.py | 59 ++ hydpy/models/statcorr/__init__.py | 17 + hydpy/models/statcorr/statcorr_control.py | 182 +++- hydpy/models/statcorr/statcorr_derived.py | 98 ++ hydpy/models/statcorr/statcorr_fluxes.py | 16 + hydpy/models/statcorr/statcorr_inlets.py | 10 + hydpy/models/statcorr/statcorr_inputs.py | 12 + hydpy/models/statcorr/statcorr_logs.py | 14 + hydpy/models/statcorr/statcorr_model.py | 1127 +++++++++++++++++++++ hydpy/models/statcorr/statcorr_outlets.py | 10 + hydpy/models/statcorr/statcorr_states.py | 74 ++ hydpy/models/statcorr_arima010.py | 163 +++ hydpy/models/statcorr_main.py | 132 +++ 16 files changed, 2012 insertions(+), 4 deletions(-) create mode 100644 hydpy/interfaces/statcorrinterfaces.py create mode 100644 hydpy/models/statcorr/statcorr_derived.py create mode 100644 hydpy/models/statcorr/statcorr_fluxes.py create mode 100644 hydpy/models/statcorr/statcorr_inlets.py create mode 100644 hydpy/models/statcorr/statcorr_inputs.py create mode 100644 hydpy/models/statcorr/statcorr_logs.py create mode 100644 hydpy/models/statcorr/statcorr_model.py create mode 100644 hydpy/models/statcorr/statcorr_outlets.py create mode 100644 hydpy/models/statcorr/statcorr_states.py create mode 100644 hydpy/models/statcorr_arima010.py create mode 100644 hydpy/models/statcorr_main.py diff --git a/hydpy/core/optiontools.py b/hydpy/core/optiontools.py index b9445d23f6..a29dc67435 100644 --- a/hydpy/core/optiontools.py +++ b/hydpy/core/optiontools.py @@ -20,6 +20,7 @@ SeriesFileType, SeriesAggregationType, SeriesConventionType, + SimulationMode, ) TypeOptionContextBase = TypeVar("TypeOptionContextBase", bound="OptionContextBase[Any]") TypeOptionPropertyBase = TypeVar( @@ -707,6 +708,73 @@ class OptionPropertySeriesConvention( _CONTEXT = OptionContextStr[SeriesConventionType] +def _check_simulationmode(value: SimulationMode) -> SimulationMode: + try: + if value == "historical": + return "historical" + if value == "forecast": + return "forecast" + assert_never(value) + except AssertionError: + raise ValueError( + f"The given simulation mode `{value}` is not implemented. Please " + f"choose one of the following simulation modes: historical, forecast." + ) from None + assert False + + +class _OptionPropertySimulationMode( + OptionPropertyBase[SimulationMode, OptionContextStr[SimulationMode]] +): + """Descriptor for defining options of type |SimulationMode|. + + *HydPy* currently supports two simulation modes: historical and forecast. + Options based on |OptionPropertySimulationMode| + automatically check if the given string is a supported simulatio mode + and raise errors if not: + + >>> from hydpy.core.optiontools import _OptionPropertySimulationMode + >>> class T: + ... v = _OptionPropertySimulationMode("historical", "x") + >>> T.v.__doc__ + 'x' + + >>> t = T() + >>> assert t.v == "historical" + >>> t.v = "abc" + Traceback (most recent call last): + ... + ValueError: The given simulation mode `abc` is not implemented. Please choose \ +one of the following simulation modes: historical, forecast. + >>> assert t.v == "historical" + >>> t.v = "forecast" + >>> assert t.v == "forecast" + >>> t.v = "historical" + >>> assert t.v == "historical" + + >>> with t.v("abc"): + ... pass + Traceback (most recent call last): + ... + ValueError: The given simulation mode `abc` is not implemented. Please choose \ +one of the following simulation modes: historical, forecast. + >>> assert t.v == "historical" + >>> with t.v("forecast"): + ... assert t.v == "forecast" + ... with t.v("historical"): + ... assert t.v == "historical" + ... with t.v(): + ... assert t.v == "historical" + ... with t.v(None): + ... assert t.v == "historical" + ... assert t.v == "forecast" + >>> assert t.v == "historical" + """ + + _CONVERTER = (_check_simulationmode,) + _CONTEXT = OptionContextStr[SimulationMode] + + class Options: """Singleton class for the general options available in the global |pub| module. @@ -813,7 +881,7 @@ class Options: """, ) printprogress = OptionPropertyBool( - True, + False, """A bool-like flag for printing information about the progress of some processes to the standard output. @@ -839,6 +907,32 @@ class Options: >>> assert pub.options.reprdigits == -1 """, ) + simulationmode = _OptionPropertySimulationMode( + "historical", + """The current simulation mode. + + The supported values are "historical" (default) and "forecast". In + "historical" mode, the simulation typically relies on observed data, + whereas "forecast" mode might involve different initialization or + meteorological forcing. + + >>> from hydpy import pub + >>> pub.options.simulationmode + 'historical' + + You can switch the mode by assigning one of the valid string identifiers: + + >>> pub.options.simulationmode = "forecast" + >>> pub.options.simulationmode + 'forecast' + + Resetting the option restores the default "historical" mode: + + >>> del pub.options.simulationmode + >>> pub.options.simulationmode + 'historical' + """, + ) simulationstep = _OptionPropertySimulationstep( timetools.Period(), """The actual simulation time step size. @@ -921,7 +1015,7 @@ class Options: """, ) usecython = OptionPropertyBool( - True, + False, """A bool-like flag for applying cythonized models, which are much faster than pure Python models. diff --git a/hydpy/core/sequencetools.py b/hydpy/core/sequencetools.py index f07c8d54a9..c489ceb97f 100644 --- a/hydpy/core/sequencetools.py +++ b/hydpy/core/sequencetools.py @@ -438,6 +438,8 @@ class StandardInputNames(enum.StrEnum): """Capillary rise [mm/T].""" CLEAR_SKY_SOLAR_RADIATION = "clear_sky_solar_radiation" """Clear sky solar radiation [W/m²].""" + DISCHARGE = "Discharge" + """Discharge [m³/s]""" EVAPOTRANSPIRATION = "evapotranspiration" """Actual evapotranspiration [mm/T].""" GLOBAL_RADIATION = "global_radiation" diff --git a/hydpy/core/typingtools.py b/hydpy/core/typingtools.py index 0cc911f083..6e94abafaf 100644 --- a/hydpy/core/typingtools.py +++ b/hydpy/core/typingtools.py @@ -412,6 +412,7 @@ class CySubstepModelProtocol(CyModelProtocol): SeriesFileType = Literal["npy", "asc", "nc"] SeriesAggregationType = Literal["none", "mean"] SeriesConventionType = Literal["model-specific", "HydPy"] +SimulationMode = Literal["historical", "forecast"] l1: Literal[1] = 1 @@ -521,6 +522,7 @@ class CySubstepModelProtocol(CyModelProtocol): "Sequence2", "Sequence3", "SharableConfiguration", + "SimulationMode", "Sized", "StepSize", "T_inv", diff --git a/hydpy/interfaces/statcorrinterfaces.py b/hydpy/interfaces/statcorrinterfaces.py new file mode 100644 index 0000000000..5fbf4d4454 --- /dev/null +++ b/hydpy/interfaces/statcorrinterfaces.py @@ -0,0 +1,59 @@ +"""This module defines submodel interfaces for statistical output correction of +discharge forecasts.""" + +from hydpy.core import modeltools +from hydpy.core.typingtools import * + + +class OutputCorrModel_V1(modeltools.SubmodelInterface): + """Simple interface for statistical output correction of discharge forecasts. + + Each submodel owns and maintains its own persistent log of simulated and + observed discharge. The main model (|statcorr|) merely passes the current + simulated and observed discharge to the submodel once per simulation step; + the submodel is responsible for shifting these values into its internal log + and for using the resulting history when calculating the correction. + + The expected call order within one simulation step is: + + 1. |OutputCorrModel_V1.set_simulateddischarge| + 2. |OutputCorrModel_V1.set_observeddischarge| + 3. |OutputCorrModel_V1.determine_outputcorrection| + 4. |OutputCorrModel_V1.get_correctedoutput| + """ + + typeid: ClassVar[Literal[1]] = 1 + """Type identifier for |OutputCorrModel_V1| submodels.""" + + def prepare_nmblogentries(self, nmblogentries: int) -> None: + """Allocate the internal log to hold `nmblogentries` discharge values.""" + + @modeltools.abstractmodelmethod + def set_simulateddischarge(self, simulateddischarge: float) -> None: + """Pass the current simulated discharge (in m³/s) to the submodel, which + appends it to its internal log of simulated discharge.""" + + @modeltools.abstractmodelmethod + def set_observeddischarge(self, observeddischarge: float) -> None: + """Pass the current observed discharge (in m³/s, or |numpy.nan| when + unavailable) to the submodel, which appends it to its internal log of + observed discharge.""" + + @modeltools.abstractmodelmethod + def determine_outputcorrection(self, isforecastmode: bool) -> None: + """Calculate the corrected output discharge from the internal logs of + simulated and observed discharge. + + The main model passes its current |Options.simulationmode| via + `isforecastmode` (|True| for `forecast`, |False| for `historical`) + instead of leaving the submodel to inspect the global option itself, + because a submodel cannot safely track *changes* of + |Options.simulationmode| between simulation steps on its own (there is + no per-step hook comparable to |OutputCorrModel_V1.set_simulateddischarge| + for it, and refreshing a submodel-owned derived parameter via + |Model.update_parameters| would also needlessly re-run its submodel + attachment/initialisation logic, wiping its logged history).""" + + @modeltools.abstractmodelmethod + def get_correctedoutput(self) -> float: + """Get the previously calculated corrected discharge in m³/s.""" diff --git a/hydpy/models/statcorr/__init__.py b/hydpy/models/statcorr/__init__.py index e69de29bb2..8d59d7e540 100644 --- a/hydpy/models/statcorr/__init__.py +++ b/hydpy/models/statcorr/__init__.py @@ -0,0 +1,17 @@ +""" +The Statcorr model is... +""" + +from hydpy.exe.modelimports import * +from hydpy.models.statcorr import statcorr_control + +ADDITIONAL_CONTROLPARAMETERS = ( + statcorr_control.LoggingWindow, + statcorr_control.NmbOutputCorrModels, + statcorr_control.PropagateCorrection, +) + +from hydpy.models.statcorr.statcorr_model import Model + +tester = Tester() +cythonizer = Cythonizer() diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index 6cce5073b8..bad2b7c7ea 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -1,6 +1,184 @@ -class AriNQ(parametertools.Parameter): - """Average size of the water surface [km²].""" +# pylint: disable=missing-module-docstring + +from hydpy.core import exceptiontools +from hydpy.core import parametertools, timetools +from hydpy.core.typingtools import * + + +class LoggingWindow(parametertools.Parameter): + """The length of the time period to be logged.""" + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = int + + +class NmbOutputCorrModels(parametertools.Parameter): + """The number of output correction submodels [-]. + + Setting |NmbOutputCorrModels| automatically resizes the + |Model.outputcorrmodels| submodel slots accordingly: + + >>> from hydpy.models.statcorr import * + >>> parameterstep() + >>> nmboutputcorrmodels(3) + >>> model.outputcorrmodels.number + 3 + """ + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = int + SPAN = (0, None) + + def __call__(self, *args, **kwargs) -> None: + super().__call__(*args, **kwargs) + self.subpars.pars.model.outputcorrmodels.number = self.value + + +class EvaluationWindow(parametertools.Parameter): + """The length of the time period for evaluation of flow conditions.""" + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = int + + +class MaxResidualLookback(parametertools.Parameter): + """The maximum number of log entries to search back for the most recently + available residual when the current or recent observed discharge values are + missing.""" + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = int + SPAN = (0, None) + + +class CorrNQ(parametertools.Parameter): + """Determines whether output correction is applied to the low flow range (NQ)""" + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = bool + + +class CorrMQ(parametertools.Parameter): + """Determines whether output correction is applied to the mean flow range (MQ)""" + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = bool + + +class CorrHQ(parametertools.Parameter): + """Determines whether output correction is applied to the high flow range (HQ)""" + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = bool + + +class QminQmax(parametertools.Parameter): + """Threshold value [%] for the quotient of the minimum and the maximum measured + flow within the |NqmStationarityWindow| assessment period, below which flow + conditions are considered instationary.""" + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = float + SPAN = (0.0, 100.0) + + +class NqmStationarityWindow(parametertools.Parameter): + """Assessment period (timesteps) for determining stationarity + of low and mean flow conditions""" + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = int + + +class LinearReductionTime(parametertools.Parameter): + """Number of timesteps for linearly reducing the ARIMA correction to zero once + instationary flow conditions are detected, separately for the NQ range (index 0) + and the MQ range (index 1). + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> control.linearreductiontime(12, 6) + >>> control.linearreductiontime + linearreductiontime(12, 6) + """ + + NDIM: Final[Literal[1]] = 1 + TYPE: Final = int + SPAN = (0, None) + + def __call__(self, *args, **kwargs) -> None: + self.shape = 2 + super().__call__(*args, **kwargs) + + +class LimitNQM(parametertools.Parameter): + """ + Discharge threshold for the transition from NQ to MQ range in m³/s. + """ + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = float + + +class LimitMQH(parametertools.Parameter): + """ + Discharge threshold for the transition from MQ to HQ range in m³/s. + """ + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = float + + +class MaxAbsoluteShift(parametertools.Parameter): + """The maximum absolute shift (in m³/s) applied when the current forecast + discharge exceeds the simulated discharge at the point the residual was + determined (see |Determine_OutputCorrection_V1|).""" + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = float + SPAN = (0.0, None) + + +class MaxRelativeShift(parametertools.Parameter): + """The maximum relative shift (in %) applied when the current forecast + discharge is at or below the simulated discharge at the point the residual + was determined (see |Determine_OutputCorrection_V1|).""" NDIM: Final[Literal[0]] = 0 TYPE: Final = float SPAN = (0.0, None) + + +class ResidualAveragingWindow(parametertools.Parameter): + """The length (in log entries) of the averaging period immediately + preceding the current forecast run, used to determine the mean-value-based + ARIMA residual (see |Determine_OutputCorrection_V1|). Set to zero to + disable mean-value-based correction and rely on the single most recent + (pointwise) residual only, as |Determine_OutputCorrection_V1| already did + before |ResidualAveragingWindow| and |ResidualTransitionTime| were + introduced.""" + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = int + SPAN = (0, None) + + +class ResidualTransitionTime(parametertools.Parameter): + """The number of forecast steps over which the applied residual + transitions linearly from the single most recent (pointwise) residual to + the mean-value-based residual determined via |ResidualAveragingWindow|, + avoiding an abrupt jump right at the start of the forecast horizon.""" + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = int + SPAN = (0, None) + + +class PropagateCorrection(parametertools.Parameter): + """Flag determining whether the corrected discharge is passed on to the + downstream network (|True|) or calculated only for local output at the + current gauge, while the uncorrected inflow is passed on instead + (|False|).""" + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = bool diff --git a/hydpy/models/statcorr/statcorr_derived.py b/hydpy/models/statcorr/statcorr_derived.py new file mode 100644 index 0000000000..85c303987f --- /dev/null +++ b/hydpy/models/statcorr/statcorr_derived.py @@ -0,0 +1,98 @@ +# pylint: disable=missing-module-docstring + +import numpy + +import hydpy +from hydpy.core import exceptiontools +from hydpy.core import objecttools +from hydpy.core import parametertools +from hydpy.core.typingtools import * +from hydpy.models.statcorr import statcorr_control + + +class IsForecastMode(parametertools.Parameter): + """Flag telling whether |Options.simulationmode| currently is `forecast` [-].""" + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = bool + + def update(self) -> None: + """Take the current value of |Options.simulationmode| from module |pub|. + + >>> from hydpy.models.statcorr import * + >>> parameterstep() + >>> from hydpy import pub + >>> pub.options.simulationmode = "historical" + >>> derived.isforecastmode.update() + >>> derived.isforecastmode + isforecastmode(False) + + >>> pub.options.simulationmode = "forecast" + >>> derived.isforecastmode.update() + >>> derived.isforecastmode + isforecastmode(True) + + >>> del pub.options.simulationmode + """ + self(hydpy.pub.options.simulationmode == "forecast") + + +class NmbLogEntries(parametertools.Parameter): + """The number of log entries required for memorising the data for the + logging window [-].""" + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = int + SPAN = (1, None) + CONTROLPARAMETERS = (statcorr_control.LoggingWindow,) + + def update(self) -> None: + """Calculate the number of entries and adjust the shape of all relevant log + sequences. + + The number of the required log entries depends on the + parameter |LoggingWindow| and the simulation step size: + + >>> from hydpy.models.statcorr import * + >>> parameterstep() + >>> from hydpy import pub + >>> from hydpy.core.timetools import Period + >>> pub.timegrids = "2000-01-01", "2000-01-02", "1h" + >>> loggingwindow(24) + >>> derived.nmblogentries.update() + >>> derived.nmblogentries + nmblogentries(24) + >>> logs # doctest: +ELLIPSIS + loggedobserveddischarge(nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, + nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, + nan, nan, nan, nan) + loggedsimulateddischarge(nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, + nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, + nan, nan, nan, nan) + + To prevent losing information, updating parameter |NmbLogEntries| resets the + shape of the relevant log sequences only when necessary: + + >>> logs.loggedobserveddischarge = 1.0 + >>> derived.nmblogentries(24) + >>> logs # doctest: +ELLIPSIS + loggedobserveddischarge(1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0) + loggedsimulateddischarge(nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, + nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, + nan, nan, nan, nan) + + .. testsetup:: + + >>> del pub.timegrids + """ + control = self.subpars.pars.control + + nmb = control.loggingwindow.value + self(nmb) + nmb = int(nmb) + for seq in self.subpars.pars.model.sequences.logs: + shape = exceptiontools.getattr_(seq, "shape", (None,)) + if nmb != shape[-1]: + seq.shape = nmb diff --git a/hydpy/models/statcorr/statcorr_fluxes.py b/hydpy/models/statcorr/statcorr_fluxes.py new file mode 100644 index 0000000000..805a277fa6 --- /dev/null +++ b/hydpy/models/statcorr/statcorr_fluxes.py @@ -0,0 +1,16 @@ +# pylint: disable=missing-module-docstring + +from hydpy.core import sequencetools +from hydpy.core.typingtools import * + + +class Inflow(sequencetools.FluxSequence): + """Flow into the first channel segment [m³/s].""" + + NDIM: Final[Literal[0]] = 0 + + +class CorrectedQ(sequencetools.FluxSequence): + """Corrected Discharge [m³/s].""" + + NDIM: Final[Literal[0]] = 0 diff --git a/hydpy/models/statcorr/statcorr_inlets.py b/hydpy/models/statcorr/statcorr_inlets.py new file mode 100644 index 0000000000..c95be13e8d --- /dev/null +++ b/hydpy/models/statcorr/statcorr_inlets.py @@ -0,0 +1,10 @@ +# pylint: disable=missing-module-docstring + +from hydpy.core import sequencetools +from hydpy.core.typingtools import * + + +class Q(sequencetools.InletSequence): + """Abfluss (runoff) [m³/s].""" + + NDIM: Final[Literal[1]] = 1 diff --git a/hydpy/models/statcorr/statcorr_inputs.py b/hydpy/models/statcorr/statcorr_inputs.py new file mode 100644 index 0000000000..9db28e771e --- /dev/null +++ b/hydpy/models/statcorr/statcorr_inputs.py @@ -0,0 +1,12 @@ +# pylint: disable=missing-module-docstring + +from hydpy.core import sequencetools +from hydpy.core.typingtools import * + + +class Discharge(sequencetools.InputSequence): + """Discharge [m³/s].""" + + NDIM: Final[Literal[0]] = 0 + SPAN = (0.0, None) + STANDARD_NAME = sequencetools.StandardInputNames.DISCHARGE diff --git a/hydpy/models/statcorr/statcorr_logs.py b/hydpy/models/statcorr/statcorr_logs.py new file mode 100644 index 0000000000..9433fdd2b1 --- /dev/null +++ b/hydpy/models/statcorr/statcorr_logs.py @@ -0,0 +1,14 @@ +from hydpy.core import sequencetools +from hydpy.core.typingtools import * + + +class LoggedObservedDischarge(sequencetools.LogSequence): + """Logged observed discharge [m³/s]""" + + NDIM: Final[Literal[1]] = 1 + + +class LoggedSimulatedDischarge(sequencetools.LogSequence): + """Logged simulated discharge [m³/s].""" + + NDIM: Final[Literal[1]] = 1 diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py new file mode 100644 index 0000000000..38b279b975 --- /dev/null +++ b/hydpy/models/statcorr/statcorr_model.py @@ -0,0 +1,1127 @@ +# pylint: disable=missing-module-docstring +from hydpy.core import importtools +from hydpy.core import modeltools +from hydpy.core.typingtools import * +from hydpy.cythons import modelutils +from hydpy.interfaces import statcorrinterfaces +from hydpy.models.statcorr import statcorr_control +from hydpy.models.statcorr import statcorr_inputs +from hydpy.models.statcorr import statcorr_inlets +from hydpy.models.statcorr import statcorr_outlets +from hydpy.models.statcorr import statcorr_fluxes +from hydpy.models.statcorr import statcorr_logs +from hydpy.models.statcorr import statcorr_states +from hydpy.models.statcorr import statcorr_derived + + +class Pick_Inflow_V1(modeltools.Method): + r"""Sum up the current inflow from all inlet nodes. + + Basic equation: + :math:`Inflow = \sum Q` + + Example: + + >>> from hydpy.models.statcorr import * + >>> parameterstep() + >>> inlets.q.shape = 2 + >>> inlets.q = 2.0, 4.0 + >>> model.pick_inflow_v1() + >>> fluxes.inflow + inflow(6.0) + """ + + REQUIREDSEQUENCES = (statcorr_inlets.Q,) + RESULTSEQUENCES = (statcorr_fluxes.Inflow,) + + @staticmethod + def __call__(model: modeltools.Model, /) -> None: + inl = model.sequences.inlets.fastaccess + flu = model.sequences.fluxes.fastaccess + + flu.inflow = 0.0 + for idx in range(inl.len_q): + flu.inflow += inl.q[idx] + + +class Calc_OutputCorr_V1(modeltools.Method): + """Apply each |OutputCorrModel_V1| submodel to the current simulated and observed + discharge and combine their results into the corrected discharge. + + This method orchestrates one or more submodels of identical interface type: + + 1. The current simulated discharge (|Inflow|) and observed discharge + (|Discharge|) are passed to each attached |OutputCorrModel_V1| submodel + via |OutputCorrModel_V1.set_simulateddischarge| and + |OutputCorrModel_V1.set_observeddischarge|. While |Options.simulationmode| + equals `forecast`, |Calc_OutputCorr_V1| passes |numpy.nan| instead of the + actual value of |Discharge|, regardless of whether an observation is + available. This relies on the assumption that a previous `historical` + simulation run already logged all relevant past observations and + simulations (read in as conditions). + 2. Each submodel computes its corrected discharge via + |OutputCorrModel_V1.determine_outputcorrection|. + 3. The corrected output of the *last* attached submodel is taken as + |CorrectedQ|. When no submodel is attached, |CorrectedQ| equals + |Inflow|. Since each submodel decides for itself, based on its own + |CorrNQ|, |CorrMQ|, and |CorrHQ| flags, whether the current NQ, MQ, or + HQ flow condition warrants a correction (passing through the current + simulated discharge unchanged otherwise), attaching several submodels + configured for mutually exclusive flow ranges automatically lets only + the one responsible for the current flow condition take effect. + + Examples: + + Without any attached submodel, the corrected discharge equals the inflow: + + >>> from hydpy.models.statcorr import * + >>> parameterstep() + >>> fluxes.inflow = 2.0 + >>> inputs.discharge = 3.0 + >>> model.calc_outputcorr_v1() + >>> fluxes.correctedq + correctedq(2.0) + + With a single attached |statcorr_arima010| submodel, the corrected + discharge is the inflow plus the most recent residual (here: + ``3.0 - 2.0 = 1.0``, applied to the new inflow ``2.5``). We enable + correction for all discharge ranges and set |QminQmax| to zero so that + the LARSIM stationarity check never suppresses the correction: + + >>> def configure(submodel): + ... submodel.parameters.control.corrnq(True) + ... submodel.parameters.control.corrmq(True) + ... submodel.parameters.control.corrhq(True) + ... submodel.parameters.control.limitnqm(0.0) + ... submodel.parameters.control.limitmqh(100.0) + ... submodel.parameters.control.evaluationwindow(2) + ... submodel.parameters.control.maxresiduallookback(3) + ... submodel.parameters.control.maxabsoluteshift(100.0) + ... submodel.parameters.control.maxrelativeshift(1000.0) + ... submodel.parameters.control.residualaveragingwindow(0) + ... submodel.parameters.control.residualtransitiontime(0) + ... submodel.parameters.control.qminqmax(0.0) + ... submodel.parameters.control.nqmstationaritywindow(2) + ... submodel.parameters.control.linearreductiontime(1, 1) + + >>> loggingwindow(2) + >>> nmboutputcorrmodels(1) + >>> with model.add_outputcorrmodel_v1( + ... "statcorr_arima010", position=0 + ... ) as submodel: + ... configure(submodel) + >>> model.calc_outputcorr_v1() + >>> fluxes.correctedq + correctedq(3.0) + >>> from numpy import nan + >>> fluxes.inflow = 2.5 + >>> inputs.discharge = nan + >>> model.calc_outputcorr_v1() + >>> fluxes.correctedq + correctedq(3.5) + + With two attached submodels of the same type, the second one's output + wins: + + >>> nmboutputcorrmodels(2) + >>> with model.add_outputcorrmodel_v1( + ... "statcorr_arima010", position=0 + ... ) as submodel: + ... configure(submodel) + >>> with model.add_outputcorrmodel_v1( + ... "statcorr_arima010", position=1 + ... ) as submodel: + ... configure(submodel) + >>> fluxes.inflow = 2.5 + >>> inputs.discharge = 4.0 + >>> model.calc_outputcorr_v1() + >>> fluxes.correctedq + correctedq(4.0) + + While |Options.simulationmode| equals ``forecast``, |Calc_OutputCorr_V1| + ignores the actual value of |Discharge| and passes |numpy.nan| to the + submodels instead, relying on their logic to + keep applying the most recently logged residual (see |statcorr_arima010| + for the mechanism and the module docstring of |statcorr_main| for the + assumed workflow of a preceding `historical` run). |Calc_OutputCorr_V1| + also forwards the current |Options.simulationmode| to each submodel's + |OutputCorrModel_V1.determine_outputcorrection| call (see + |Determine_OutputCorrection_V1|), so submodels never need to inspect the + global option themselves. |Parameters.update| (usually triggered via + |HydPy.update_parameters|) must be called after changing + |Options.simulationmode| for |IsForecastMode| (and hence + |Calc_OutputCorr_V1|) to take effect; deliberately, this does *not* + require (or recommend) calling |Model.update_parameters|, which would + also needlessly re-run the submodels' attachment/initialisation logic + and wipe their logged history: + + >>> loggingwindow(3) + >>> nmboutputcorrmodels(1) + >>> with model.add_outputcorrmodel_v1( + ... "statcorr_arima010", position=0 + ... ) as submodel: + ... configure(submodel) + >>> model.parameters.update() + + Two `historical` steps establish a residual of ``0.5``: + + >>> fluxes.inflow = 1.0 + >>> inputs.discharge = 1.5 + >>> model.calc_outputcorr_v1() + >>> fluxes.correctedq + correctedq(1.5) + >>> fluxes.inflow = 2.0 + >>> inputs.discharge = 2.5 + >>> model.calc_outputcorr_v1() + >>> fluxes.correctedq + correctedq(2.5) + + Switching to `forecast` mode and feeding an implausible |Discharge| + value (``999.0``, which would dominate the result if it were not + ignored) still reproduces the persisted residual of ``0.5``: + + >>> from hydpy import pub + >>> with pub.options.simulationmode("forecast"): + ... model.parameters.update() + ... fluxes.inflow = 3.0 + ... inputs.discharge = 999.0 + ... model.calc_outputcorr_v1() + >>> fluxes.correctedq + correctedq(3.5) + >>> with pub.options.simulationmode("forecast"): + ... model.parameters.update() + ... fluxes.inflow = 4.0 + ... inputs.discharge = 999.0 + ... model.calc_outputcorr_v1() + >>> fluxes.correctedq + correctedq(4.5) + + Once the last real observation drops out of the three-step logging + window, no correction is applied anymore: + + >>> with pub.options.simulationmode("forecast"): + ... model.parameters.update() + ... fluxes.inflow = 5.0 + ... inputs.discharge = 999.0 + ... model.calc_outputcorr_v1() + >>> fluxes.correctedq + correctedq(5.0) + """ + + SUBMODELINTERFACES = (statcorrinterfaces.OutputCorrModel_V1,) + DERIVEDPARAMETERS = (statcorr_derived.IsForecastMode,) + REQUIREDSEQUENCES = (statcorr_fluxes.Inflow, statcorr_inputs.Discharge) + RESULTSEQUENCES = (statcorr_fluxes.CorrectedQ,) + + @staticmethod + def __call__(model: modeltools.Model, /) -> None: + der = model.parameters.derived.fastaccess + flu = model.sequences.fluxes.fastaccess + inp = model.sequences.inputs.fastaccess + observeddischarge: float = ( + modelutils.nan if der.isforecastmode else inp.discharge + ) + flu.correctedq = flu.inflow + for i in range(model.outputcorrmodels.number): + if model.outputcorrmodels.typeids[i] == 1: + cast( + statcorrinterfaces.OutputCorrModel_V1, + model.outputcorrmodels.submodels[i], + ).set_simulateddischarge(flu.inflow) + cast( + statcorrinterfaces.OutputCorrModel_V1, + model.outputcorrmodels.submodels[i], + ).set_observeddischarge(observeddischarge) + cast( + statcorrinterfaces.OutputCorrModel_V1, + model.outputcorrmodels.submodels[i], + ).determine_outputcorrection(bool(der.isforecastmode)) + flu.correctedq = cast( + statcorrinterfaces.OutputCorrModel_V1, + model.outputcorrmodels.submodels[i], + ).get_correctedoutput() + + +class Pass_Q_V1(modeltools.Method): + """Update the outlet link sequence. + + Basic equation: + :math:`Q_{outlets} = Q_{fluxes} + Q_{inputs}` + + |Pass_Q_V1| is used, for example, by |statcorr_test|, not by |statcorr| itself + (which uses |Pass_CorrectedQ_V1| instead): + + Example: + + >>> from hydpy.models.statcorr_test import * + >>> parameterstep() + >>> fluxes.inflow = 2.0 + >>> inputs.discharge = 1.0 + >>> model.pass_q_v1() + >>> outlets.q + q(3.0) + """ + + REQUIREDSEQUENCES = (statcorr_fluxes.Inflow, statcorr_inputs.Discharge) + RESULTSEQUENCES = (statcorr_outlets.Q,) + + @staticmethod + def __call__(model: modeltools.Model, /) -> None: + flu = model.sequences.fluxes.fastaccess + inp = model.sequences.inputs.fastaccess + out = model.sequences.outlets.fastaccess + out.q = flu.inflow + inp.discharge + + +class Pass_CorrectedQ_V1(modeltools.Method): + """Pass the corrected discharge on to the outlet link sequence, unless + |PropagateCorrection| is |False|, in which case the uncorrected inflow is + passed on instead. Either way, |CorrectedQ| remains available for local + output at the current gauge. + + Basic equation: + :math:`Q_{outlets} = CorrectedQ` (if |PropagateCorrection|) or + :math:`Q_{outlets} = Inflow` (otherwise) + + Examples: + + >>> from hydpy.models.statcorr import * + >>> parameterstep() + >>> fluxes.inflow = 1.0 + >>> fluxes.correctedq = 2.0 + + >>> propagatecorrection(True) + >>> model.pass_correctedq_v1() + >>> outlets.q + q(2.0) + + >>> propagatecorrection(False) + >>> model.pass_correctedq_v1() + >>> outlets.q + q(1.0) + """ + + CONTROLPARAMETERS = (statcorr_control.PropagateCorrection,) + REQUIREDSEQUENCES = (statcorr_fluxes.Inflow, statcorr_fluxes.CorrectedQ) + RESULTSEQUENCES = (statcorr_outlets.Q,) + + @staticmethod + def __call__(model: modeltools.Model, /) -> None: + con = model.parameters.control.fastaccess + flu = model.sequences.fluxes.fastaccess + out = model.sequences.outlets.fastaccess + out.q = flu.correctedq if con.propagatecorrection else flu.inflow + + +class Get_Discharge_V1(modeltools.Method): + """Get the current measured discharge. + + Example: + + >>> from hydpy.models.statcorr import * + >>> parameterstep() + >>> inputs.discharge = 2.0 + >>> from hydpy import round_ + >>> round_(model.get_discharge_v1()) + 2.0 + """ + + REQUIREDSEQUENCES = (statcorr_inputs.Discharge,) + + @staticmethod + def __call__(model: modeltools.Model, /) -> float: + inp = model.sequences.inputs.fastaccess + + return inp.discharge + + +class Model(modeltools.AdHocModel): + """|statcorr.DOCNAME.complete|.""" + + DOCNAME = modeltools.DocName(short="statcorr") + __HYDPY_ROOTMODEL__ = None + + INLET_METHODS = (Pick_Inflow_V1,) + OBSERVER_METHODS = () + RECEIVER_METHODS = () + RUN_METHODS = (Calc_OutputCorr_V1,) + INTERFACE_METHODS = (Get_Discharge_V1,) + ADD_METHODS = () + OUTLET_METHODS = (Pass_CorrectedQ_V1,) + SENDER_METHODS = () + SUBMODELINTERFACES = (statcorrinterfaces.OutputCorrModel_V1,) + SUBMODELS = () + + outputcorrmodels = modeltools.SubmodelsProperty( + statcorrinterfaces.OutputCorrModel_V1 + ) + + @importtools.prepare_submodel( + "outputcorrmodels", + statcorrinterfaces.OutputCorrModel_V1, + statcorrinterfaces.OutputCorrModel_V1.prepare_nmblogentries, + dimensionality=1, + ) + def add_outputcorrmodel_v1( + self, + outputcorrmodel: statcorrinterfaces.OutputCorrModel_V1, + *, + position: int, + refresh: bool, # pylint: disable=unused-argument + ) -> None: + """Initialise the given submodel that follows the |OutputCorrModel_V1| + interface and propagate the main model's |LoggingWindow| to its internal + log allocation. + + >>> from hydpy.models.statcorr import * + >>> parameterstep() + >>> loggingwindow(4) + >>> nmboutputcorrmodels(1) + >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0): + ... pass + >>> model.outputcorrmodels[0].parameters.derived.nmblogentries + nmblogentries(4) + >>> model.outputcorrmodels[0].sequences.logs.loggedsimulateddischarge + loggedsimulateddischarge(nan, nan, nan, nan) + """ + nmb = int(self.parameters.control.loggingwindow.value) + outputcorrmodel.parameters.control.loggingwindow(nmb) + outputcorrmodel.prepare_nmblogentries(nmb) + + +class Set_SimulatedDischarge_V1(modeltools.Method): + """Append the given simulated discharge value to the internal log of simulated + discharge by shifting the previously buffered values one position to the right + and storing the new value at position 0. + + Example: + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> derived.nmblogentries(3) + >>> logs.loggedsimulateddischarge.shape = 3 + >>> logs.loggedsimulateddischarge = 4.0, 3.0, 2.0 + >>> model.set_simulateddischarge_v1(5.0) + >>> logs.loggedsimulateddischarge + loggedsimulateddischarge(5.0, 4.0, 3.0) + """ + + DERIVEDPARAMETERS = (statcorr_derived.NmbLogEntries,) + UPDATEDSEQUENCES = (statcorr_logs.LoggedSimulatedDischarge,) + + @staticmethod + def __call__(model: modeltools.Model, simulateddischarge: float, /) -> None: + der = model.parameters.derived.fastaccess + log = model.sequences.logs.fastaccess + for idx in range(der.nmblogentries - 1, 0, -1): + log.loggedsimulateddischarge[idx] = log.loggedsimulateddischarge[idx - 1] + log.loggedsimulateddischarge[0] = simulateddischarge + + +class Set_ObservedDischarge_V1(modeltools.Method): + """Append the given observed discharge value to the internal log of observed + discharge by shifting the previously buffered values one position to the right + and storing the new value at position 0. + + The given value may be |numpy.nan| when no observation is available. + + Example: + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> derived.nmblogentries(3) + >>> logs.loggedobserveddischarge.shape = 3 + >>> logs.loggedobserveddischarge = 4.0, 3.0, 2.0 + >>> from numpy import nan + >>> model.set_observeddischarge_v1(nan) + >>> logs.loggedobserveddischarge + loggedobserveddischarge(nan, 4.0, 3.0) + """ + + DERIVEDPARAMETERS = (statcorr_derived.NmbLogEntries,) + UPDATEDSEQUENCES = (statcorr_logs.LoggedObservedDischarge,) + + @staticmethod + def __call__(model: modeltools.Model, observeddischarge: float, /) -> None: + der = model.parameters.derived.fastaccess + log = model.sequences.logs.fastaccess + for idx in range(der.nmblogentries - 1, 0, -1): + log.loggedobserveddischarge[idx] = log.loggedobserveddischarge[idx - 1] + log.loggedobserveddischarge[0] = observeddischarge + + +class Calc_AveragedResidual_V1(modeltools.Method): + r"""Determine the mean-value-based ARIMA residual once, at the first + forecast step, and freeze it for the remainder of the current forecast + horizon. + + |Calc_AveragedResidual_V1| averages the |LoggedObservedDischarge| and + |LoggedSimulatedDischarge| entries covering the |ResidualAveragingWindow| + log positions immediately preceding the current forecast run (log + position ``0`` already holds the current forecast step's own values, so + averaging starts at position ``1``) and stores their difference in + |AveragedResidual|. It leaves |AveragedResidual| unchanged whenever + `forecast_step` is not zero (i.e., beyond the first forecast step) or + |ResidualAveragingWindow| is zero (mean-value-based correction disabled). + When the averaging window contains a |numpy.nan| value, it falls back to + the given `fallback` residual instead (usually the pointwise residual + already determined by |Determine_OutputCorrection_V1|). + + Examples: + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> control.residualaveragingwindow(2) + >>> derived.nmblogentries(3) + >>> logs.loggedsimulateddischarge.shape = 3 + >>> logs.loggedobserveddischarge.shape = 3 + >>> logs.loggedsimulateddischarge = 3.0, 2.0, 4.0 + >>> logs.loggedobserveddischarge = nan, 3.0, 5.0 + + On the first forecast step (`forecast_step` is ``0.0``), the average + is taken from log positions ``1`` and ``2`` (mean observed ``4.0``, + mean simulated ``3.0``): + + >>> from numpy import nan + >>> model.calc_averagedresidual_v1(0.0, -9.0) + >>> states.averagedresidual + averagedresidual(1.0) + + On any later forecast step, the previously determined value remains + unchanged, regardless of the current log contents: + + >>> logs.loggedsimulateddischarge = 3.0, 20.0, 40.0 + >>> logs.loggedobserveddischarge = nan, 30.0, 50.0 + >>> model.calc_averagedresidual_v1(1.0, -9.0) + >>> states.averagedresidual + averagedresidual(1.0) + + Setting |ResidualAveragingWindow| to zero disables mean-value-based + correction; |Calc_AveragedResidual_V1| leaves |AveragedResidual| + unchanged even on the first forecast step: + + >>> control.residualaveragingwindow(0) + >>> states.averagedresidual(-9.0) + >>> model.calc_averagedresidual_v1(0.0, -9.0) + >>> states.averagedresidual + averagedresidual(-9.0) + + A |numpy.nan| value within the averaging window makes + |Calc_AveragedResidual_V1| fall back to the given `fallback` value: + + >>> control.residualaveragingwindow(2) + >>> logs.loggedobserveddischarge = nan, nan, 50.0 + >>> model.calc_averagedresidual_v1(0.0, -9.0) + >>> states.averagedresidual + averagedresidual(-9.0) + """ + + CONTROLPARAMETERS = (statcorr_control.ResidualAveragingWindow,) + DERIVEDPARAMETERS = (statcorr_derived.NmbLogEntries,) + REQUIREDSEQUENCES = ( + statcorr_logs.LoggedSimulatedDischarge, + statcorr_logs.LoggedObservedDischarge, + ) + UPDATEDSEQUENCES = (statcorr_states.AveragedResidual,) + + @staticmethod + def __call__( + model: modeltools.Model, forecast_step: float, fallback: float, / + ) -> None: + con = model.parameters.control.fastaccess + der = model.parameters.derived.fastaccess + log = model.sequences.logs.fastaccess + sta = model.sequences.states.fastaccess + + nmb = min(con.residualaveragingwindow, der.nmblogentries - 1) + if forecast_step != 0.0 or nmb <= 0: + return + + sum_obs: float = 0.0 + sum_sim: float = 0.0 + has_nan = False + for idx in range(1, nmb + 1): + obs_value: float = log.loggedobserveddischarge[idx] + sim_value: float = log.loggedsimulateddischarge[idx] + if modelutils.isnan(obs_value) or modelutils.isnan(sim_value): + has_nan = True + break + sum_obs = sum_obs + obs_value + sum_sim = sum_sim + sim_value + sta.averagedresidual = fallback if has_nan else (sum_obs - sum_sim) / nmb + + +class Determine_OutputCorrection_V1(modeltools.Method): + r"""Calculate the corrected discharge using an ARIMA(0,1,0) — random-walk — + error model. + + The correction is derived from the most recently available residual + (observed minus simulated discharge). The "most recent" residual is taken + from the latest log entry where the observed discharge is not |numpy.nan|, + searching back at most |MaxResidualLookback| log entries (or the entire + log, whichever is smaller). When no observation is available within that + range, the corrected discharge equals the current simulated discharge. + + How that residual is applied to the current simulated ("forecast") + discharge depends on how the latter (:math:`sim_0`) compares to the + simulated discharge at the time the residual was determined (:math:`sim_k`, + with :math:`k` denoting the most recent log index for which :math:`obs_k + \neq \mathrm{nan}`, and :math:`f_{red}` denoting |ReductionFactor|): + + * If :math:`sim_0 > sim_k` (and :math:`sim_k > 0`), + |Determine_OutputCorrection_V1| shifts :math:`sim_0` *additively* by the + |ReductionFactor|-damped residual, capped at |MaxAbsoluteShift| (in + m³/s): + + :math:`q_{corr} = sim_0 + \mathrm{clip}\left((obs_k - sim_k) \cdot + f_{red},\ \pm MaxAbsoluteShift\right)` + + * Otherwise (including :math:`sim_k \leq 0`, for which a relative shift + would be undefined), it shifts :math:`sim_0` *multiplicatively* instead, + expressing the damped residual as a percentage of :math:`sim_k` and + capping that percentage at |MaxRelativeShift|: + + :math:`q_{corr} = sim_0 \cdot \left(1 + \mathrm{clip}\left((obs_k - + sim_k) \cdot f_{red} / sim_k,\ \pm MaxRelativeShift / 100\right) + \right)` + + Applying the residual as a percentage rather than a constant offset + keeps the correction from overshooting or turning negative while the + forecasted discharge recedes towards zero. + + The residual (:math:`obs_k - sim_k` above) used in either branch is not + necessarily the pointwise one. Setting |ResidualAveragingWindow| to a + value greater than zero switches to a mean-value-based residual instead — + the difference between the mean observed and the mean simulated discharge + over that many log entries immediately preceding the current forecast run + (determined once, at the first forecast step, via + |Calc_AveragedResidual_V1|, and frozen in |AveragedResidual| for the + remainder of the forecast horizon). Since that mean-value-based residual + generally does not equal the pointwise residual at the forecast's start, + switching to it abruptly would cause a jump in the corrected discharge + right where the forecast begins. To avoid this, |Determine_OutputCorrection_V1| + starts every forecast run with the pointwise residual (so the corrected + discharge picks up smoothly where the last measurement left off) and then + linearly blends it towards the mean-value-based residual over + |ResidualTransitionTime| forecast steps, applying the mean-value-based + residual unabated from then on. Setting |ResidualAveragingWindow| to zero + (the default behaviour before mean-value-based correction was introduced) + disables this mechanism entirely, relying on the pointwise residual alone, + as described above. + + Within the NQ and MQ ranges, |Determine_OutputCorrection_V1| additionally + assesses whether the measured discharge behaves in a stationary way. It + takes the quotient of the minimum and the maximum |LoggedObservedDischarge| + value within the most recent |NqmStationarityWindow| log entries. Whenever + this quotient falls below |QminQmax| (given in %), it considers the flow + conditions instationary and linearly reduces |ReductionFactor| (the factor + :math:`f_{red}` in the equation above) towards zero, taking as many steps as + given by the NQ or MQ entry of |LinearReductionTime| (depending on the + current flow range). As soon as the quotient reaches |QminQmax| again (or a + |numpy.nan| value prevents its calculation), |ReductionFactor| jumps back to + ``1.0``, applying the correction unabated again. |ReductionFactor| also + resets to ``1.0`` whenever the current flow condition falls into the HQ + range, for which this stationarity check is not defined. + + |Determine_OutputCorrection_V1| only *reassesses* stationarity (the + quotient-based check described above) and the NQ/MQ/HQ flow condition + while |Options.simulationmode| equals `historical`, remembering their + outcomes in |Stationary| and |FlowCondition|, respectively. While + |Options.simulationmode| equals `forecast`, it reuses both values from the + most recent `historical` assessment instead of recomputing them — + recomputing would be unreliable anyway, since |LoggedObservedDischarge| + keeps receiving |numpy.nan| values throughout the forecast (see + |Calc_OutputCorr_V1|), which the quotient-based check always interprets as + "stationary", and since the currently simulated discharge could + temporarily cross into the HQ range and mask an instationary NQ/MQ + situation identified right before the forecast started. So, once a + `historical` run has flagged conditions as instationary in the NQ or MQ + range, |ReductionFactor| keeps ramping towards zero (or staying at + ``0.0``) for the entire forecast horizon, regardless of how the actually + simulated discharge subsequently develops, instead of jumping back to + ``1.0`` either as soon as the last real observation drops out of the + logging window or whenever the forecasted discharge happens to pass + through the HQ range. + + Examples: + + Three log entries are available, the most recent observation (at + position 0) is non-|numpy.nan|, so the correction reproduces the current + observation. The measured discharge is perfectly stationary (the + quotient of its minimum and maximum equals |QminQmax|), so + |ReductionFactor| remains at its initial value of ``1.0``: + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> derived.nmblogentries(3) + >>> control.evaluationwindow(3) + >>> control.corrnq(True) + >>> control.corrmq(True) + >>> control.corrhq(True) + >>> control.limitnqm(3.0) + >>> control.limitmqh(5.0) + >>> control.qminqmax(50.0) + >>> control.nqmstationaritywindow(3) + >>> control.linearreductiontime(2, 2) + >>> control.maxresiduallookback(3) + >>> control.maxabsoluteshift(100.0) + >>> control.maxrelativeshift(1000.0) + >>> control.residualaveragingwindow(0) + >>> control.residualtransitiontime(0) + >>> states.reductionfactor(1.0) + >>> states.stationary(1.0) + >>> logs.loggedsimulateddischarge.shape = 3 + >>> logs.loggedobserveddischarge.shape = 3 + >>> logs.loggedsimulateddischarge = 5.0, 3.0, 2.0 + >>> logs.loggedobserveddischarge = 6.0, 4.0, 3.0 + >>> model.determine_outputcorrection_v1(False) + >>> fluxes.correctedq + correctedq(6.0) + >>> states.reductionfactor + reductionfactor(1.0) + + Disabling correction for the MQ range returns the uncorrected simulated value: + + >>> control.corrmq(False) + >>> model.determine_outputcorrection_v1(False) + >>> fluxes.correctedq + correctedq(5.0) + + Simulated discharges averaging 1.5 m³/s place the model in the NQ range. + With NQ correction enabled, the residual (2.0 − 1.0 = 1.0) is applied: + + >>> logs.loggedsimulateddischarge = 1.0, 2.0, 1.5 + >>> logs.loggedobserveddischarge = 2.0, 3.0, 2.5 + >>> model.determine_outputcorrection_v1(False) + >>> fluxes.correctedq + correctedq(2.0) + + The two most recent observations are missing, so the residual is taken + from the third log entry and added to the current simulated discharge. + Missing observations also make it impossible to assess stationarity, so + |Determine_OutputCorrection_V1| assumes stationary conditions and leaves + |ReductionFactor| untouched: + + >>> from numpy import nan + >>> control.corrmq(True) + >>> logs.loggedsimulateddischarge = 5.0, 3.0, 2.0 + >>> logs.loggedobserveddischarge = nan, nan, 3.0 + >>> model.determine_outputcorrection_v1(False) + >>> fluxes.correctedq + correctedq(6.0) + + All observations are missing — no correction is applied: + + >>> logs.loggedobserveddischarge = nan, nan, nan + >>> model.determine_outputcorrection_v1(False) + >>> fluxes.correctedq + correctedq(5.0) + + Sustained instationary conditions in the NQ range (the quotient of the + minimum and the maximum observed discharge, ``0.5 / 5.0 = 10 %``, falls + well below |QminQmax|) linearly reduce |ReductionFactor| to zero within + the two steps given by the NQ entry of |LinearReductionTime|: + + >>> logs.loggedsimulateddischarge = 1.0, 1.0, 1.0 + >>> logs.loggedobserveddischarge = 0.5, 5.0, 5.0 + >>> model.determine_outputcorrection_v1(False) + >>> states.reductionfactor + reductionfactor(0.5) + >>> fluxes.correctedq + correctedq(0.75) + + >>> model.determine_outputcorrection_v1(False) + >>> states.reductionfactor + reductionfactor(0.0) + >>> fluxes.correctedq + correctedq(1.0) + + The stationarity check does not apply to the HQ range, so switching to + high flow conditions resets |ReductionFactor| to ``1.0`` regardless of + the (still instationary) measured discharge: + + >>> logs.loggedsimulateddischarge = 6.0, 6.0, 6.0 + >>> logs.loggedobserveddischarge = 7.0, 5.0, 5.0 + >>> model.determine_outputcorrection_v1(False) + >>> states.reductionfactor + reductionfactor(1.0) + >>> fluxes.correctedq + correctedq(7.0) + + Once the measured discharge becomes stationary again (quotient + ``4.0 / 5.0 = 80 %``, at or above |QminQmax|), |ReductionFactor| jumps + back to ``1.0`` immediately, applying the correction unabated: + + >>> logs.loggedsimulateddischarge = 1.0, 1.0, 1.0 + >>> logs.loggedobserveddischarge = 4.0, 5.0, 5.0 + >>> model.determine_outputcorrection_v1(False) + >>> states.reductionfactor + reductionfactor(1.0) + >>> fluxes.correctedq + correctedq(4.0) + + Setting the NQ entry of |LinearReductionTime| to zero reduces + |ReductionFactor| to zero immediately once instationary conditions occur: + + >>> control.linearreductiontime(0, 2) + >>> logs.loggedobserveddischarge = 0.5, 5.0, 5.0 + >>> model.determine_outputcorrection_v1(False) + >>> states.reductionfactor + reductionfactor(0.0) + >>> fluxes.correctedq + correctedq(1.0) + + Instationary conditions detected during `historical` mode (the second + call argument is |False|) start a ramp towards zero (here, with + |LinearReductionTime| reset to two steps): + + >>> control.linearreductiontime(2, 2) + >>> states.reductionfactor(1.0) + >>> logs.loggedsimulateddischarge = 1.0, 1.0, 1.0 + >>> logs.loggedobserveddischarge = 0.5, 5.0, 5.0 + >>> model.determine_outputcorrection_v1(False) + >>> states.stationary + stationary(0.0) + >>> states.reductionfactor + reductionfactor(0.5) + + Switching to `forecast` mode (the second call argument is now |True|, + as |Calc_OutputCorr_V1| does automatically) and feeding |numpy.nan| + observations does not reassess |Stationary|; the ramp initiated above + simply continues: + + >>> logs.loggedsimulateddischarge = 1.0, 1.0, 1.0 + >>> logs.loggedobserveddischarge = nan, nan, nan + >>> model.determine_outputcorrection_v1(True) + >>> states.stationary + stationary(0.0) + >>> states.reductionfactor + reductionfactor(0.0) + >>> fluxes.correctedq + correctedq(1.0) + + A further forecast step confirms |ReductionFactor| stays at ``0.0`` + instead of jumping back to ``1.0``, as it would if |Stationary| were + reassessed using the now entirely |numpy.nan| logging window: + + >>> model.determine_outputcorrection_v1(True) + >>> states.reductionfactor + reductionfactor(0.0) + >>> fluxes.correctedq + correctedq(1.0) + + Not only |Stationary| but also the flow condition itself (NQ, MQ, or + HQ, persisted in |FlowCondition|) is frozen at its most recent + `historical` assessment (here, NQ) and is not reassessed while + forecasting. So even though the currently simulated discharge would + classify as HQ now (which used to reset |ReductionFactor| to ``1.0`` + immediately, since the stationarity check does not apply to the HQ + range), the frozen NQ classification keeps applying, and the ramp + (already at its floor of ``0.0``) is left untouched: + + >>> logs.loggedsimulateddischarge = 10.0, 10.0, 10.0 + >>> logs.loggedobserveddischarge = nan, nan, nan + >>> model.determine_outputcorrection_v1(True) + >>> states.flowcondition + flowcondition(0.0) + >>> states.reductionfactor + reductionfactor(0.0) + >>> fluxes.correctedq + correctedq(10.0) + + Enlarging the log beyond |EvaluationWindow| does not change the flow + condition classification, which always relies on the *most recently* + logged |LoggedSimulatedDischarge| entries (index ``0`` upwards) and + never on the oldest ones sitting near the end of a larger log (which + can well still be |numpy.nan|, as is the case for the newly added + entries here): + + >>> control.linearreductiontime(2, 2) + >>> states.reductionfactor(1.0) + >>> derived.nmblogentries(5) + >>> logs.loggedsimulateddischarge.shape = 5 + >>> logs.loggedobserveddischarge.shape = 5 + >>> logs.loggedsimulateddischarge = 1.0, 1.0, 1.0, nan, nan + >>> logs.loggedobserveddischarge = 0.5, 5.0, 5.0, nan, nan + >>> model.determine_outputcorrection_v1(False) + >>> states.stationary + stationary(0.0) + >>> states.reductionfactor + reductionfactor(0.5) + + Restricting |MaxResidualLookback| to fewer entries than the full log + makes |Determine_OutputCorrection_V1| stop searching for a valid + residual once that limit is reached, applying no correction even + though an older, still-logged observation would otherwise be usable: + + >>> control.maxresiduallookback(2) + >>> logs.loggedsimulateddischarge = 1.0, 1.0, 1.0, nan, nan + >>> logs.loggedobserveddischarge = nan, nan, 3.0, nan, nan + >>> model.determine_outputcorrection_v1(False) + >>> fluxes.correctedq + correctedq(1.0) + + Enlarging |MaxResidualLookback| to reach that entry again reinstates + the correction: + + >>> control.maxresiduallookback(3) + >>> model.determine_outputcorrection_v1(False) + >>> fluxes.correctedq + correctedq(3.0) + + So far, the current forecast value (log position 0) has always been + at or above the simulated discharge at the time the residual was + determined, so all examples above used the additive (or, at position + 0 itself, an equivalent) shift. Resetting the log to a *receding* + forecast — position 0 has already dropped clearly below the value at + the residual's log position — switches to the relative (percentage) + shift instead: + + >>> logs.loggedsimulateddischarge = 2.0, 10.0, 10.0, nan, nan + >>> logs.loggedobserveddischarge = nan, 12.0, nan, nan, nan + >>> model.determine_outputcorrection_v1(False) + >>> fluxes.correctedq + correctedq(2.4) + + Limiting |MaxRelativeShift| caps that percentage before it is + converted back into an absolute shift: + + >>> control.maxrelativeshift(10.0) + >>> model.determine_outputcorrection_v1(False) + >>> fluxes.correctedq + correctedq(2.2) + + Likewise, |MaxAbsoluteShift| caps the additive shift applied whenever + the forecast value exceeds the anchor value: + + >>> control.maxabsoluteshift(1.0) + >>> logs.loggedsimulateddischarge = 12.0, 10.0, 10.0, nan, nan + >>> model.determine_outputcorrection_v1(False) + >>> fluxes.correctedq + correctedq(13.0) + + When the anchor value is zero or negative, a relative shift would be + undefined (division by zero), so |Determine_OutputCorrection_V1| + falls back to the additive shift in that case as well, even though + the forecast value does not exceed the anchor value: + + >>> control.maxabsoluteshift(100.0) + >>> logs.loggedsimulateddischarge = 0.0, 0.0, 10.0, nan, nan + >>> logs.loggedobserveddischarge = nan, 2.0, nan, nan, nan + >>> model.determine_outputcorrection_v1(False) + >>> fluxes.correctedq + correctedq(2.0) + + Setting |ResidualAveragingWindow| to a value greater than zero + switches to the mean-value-based residual, blended in linearly over + |ResidualTransitionTime| forecast steps. We reset the log to a + short, clean example (four entries) and freeze |FlowCondition| and + |Stationary| directly (instead of deriving them from a preceding + `historical` call) to keep the focus on the transition mechanism: + + >>> control.maxresiduallookback(4) + >>> control.maxabsoluteshift(100.0) + >>> control.maxrelativeshift(1000.0) + >>> control.residualaveragingwindow(2) + >>> control.residualtransitiontime(2) + >>> derived.nmblogentries(4) + >>> logs.loggedsimulateddischarge.shape = 4 + >>> logs.loggedobserveddischarge.shape = 4 + >>> states.flowcondition(0.0) + >>> states.stationary(1.0) + >>> states.reductionfactor(1.0) + >>> states.forecaststep(0.0) + + The most recent (pointwise) residual, taken from log position ``1`` + (``9.0 - 8.0 = 1.0``), differs from the mean-value-based residual + taken from log positions ``1`` and ``2`` (mean observed ``8.5``, mean + simulated ``6.0``, hence ``2.5``). On the first forecast step, + |Determine_OutputCorrection_V1| applies the pointwise residual + unabated: + + >>> logs.loggedsimulateddischarge = 10.0, 8.0, 4.0, nan + >>> logs.loggedobserveddischarge = nan, 9.0, 8.0, nan + >>> model.determine_outputcorrection_v1(True) + >>> states.averagedresidual + averagedresidual(2.5) + >>> fluxes.correctedq + correctedq(11.0) + + Halfway through the two-step transition, the applied residual is the + average of both (``1.75``): + + >>> logs.loggedsimulateddischarge = 11.0, 10.0, 8.0, 4.0 + >>> logs.loggedobserveddischarge = nan, nan, 9.0, 8.0 + >>> model.determine_outputcorrection_v1(True) + >>> fluxes.correctedq + correctedq(12.75) + + Once the transition period has elapsed, the full mean-value-based + residual applies, regardless of the (still aging) pointwise residual: + + >>> logs.loggedsimulateddischarge = 12.0, 11.0, 10.0, 8.0 + >>> logs.loggedobserveddischarge = nan, nan, nan, 9.0 + >>> model.determine_outputcorrection_v1(True) + >>> states.averagedresidual + averagedresidual(2.5) + >>> fluxes.correctedq + correctedq(14.5) + """ + + SUBMETHODS = (Calc_AveragedResidual_V1,) + CONTROLPARAMETERS = ( + statcorr_control.CorrNQ, + statcorr_control.CorrMQ, + statcorr_control.CorrHQ, + statcorr_control.LimitNQM, + statcorr_control.LimitMQH, + statcorr_control.EvaluationWindow, + statcorr_control.MaxResidualLookback, + statcorr_control.MaxAbsoluteShift, + statcorr_control.MaxRelativeShift, + statcorr_control.ResidualAveragingWindow, + statcorr_control.ResidualTransitionTime, + statcorr_control.QminQmax, + statcorr_control.NqmStationarityWindow, + statcorr_control.LinearReductionTime, + ) + DERIVEDPARAMETERS = (statcorr_derived.NmbLogEntries,) + REQUIREDSEQUENCES = ( + statcorr_logs.LoggedSimulatedDischarge, + statcorr_logs.LoggedObservedDischarge, + ) + UPDATEDSEQUENCES = ( + statcorr_states.ReductionFactor, + statcorr_states.Stationary, + statcorr_states.FlowCondition, + statcorr_states.ForecastStep, + statcorr_states.AveragedResidual, + ) + RESULTSEQUENCES = (statcorr_fluxes.CorrectedQ,) + + @staticmethod + def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: + con = model.parameters.control.fastaccess + der = model.parameters.derived.fastaccess + flu = model.sequences.fluxes.fastaccess + log = model.sequences.logs.fastaccess + sta = model.sequences.states.fastaccess + + assert der.nmblogentries >= con.evaluationwindow + + flow_condition: int + if isforecastmode: + flow_condition = int(sta.flowcondition) + else: + mean_simulated: float = 0.0 + for idx in range(con.evaluationwindow): + mean_simulated = mean_simulated + log.loggedsimulateddischarge[idx] + mean_simulated = mean_simulated / con.evaluationwindow + + if mean_simulated < con.limitnqm: + flow_condition = 0 + elif mean_simulated < con.limitmqh: + flow_condition = 1 + else: + flow_condition = 2 + sta.flowcondition = float(flow_condition) + + if ( + (flow_condition == 0 and con.corrnq is False) + or (flow_condition == 1 and con.corrmq is False) + or (flow_condition == 2 and con.corrhq is False) + ): + flu.correctedq = log.loggedsimulateddischarge[0] + return + + residual: float = 0.0 + sim_anchor: float = 0.0 + for idx in range(min(der.nmblogentries, con.maxresiduallookback)): + if not modelutils.isnan(log.loggedobserveddischarge[idx]): + sim_anchor = log.loggedsimulateddischarge[idx] + residual = log.loggedobserveddischarge[idx] - sim_anchor + break + + if flow_condition == 2: + sta.reductionfactor = 1.0 + else: + if not isforecastmode: + nmb = min(der.nmblogentries, con.nqmstationaritywindow) + stationary: bool = True + has_nan = False + qmin: float = modelutils.inf + qmax: float = -modelutils.inf + for idx in range(nmb): + value: float = log.loggedobserveddischarge[idx] + if modelutils.isnan(value): + has_nan = True + break + qmin = min(qmin, value) + qmax = max(qmax, value) + if not has_nan and qmax > 0.0: + stationary = (qmin / qmax) * 100.0 >= con.qminqmax + sta.stationary = 1.0 if stationary else 0.0 + + if sta.stationary: + sta.reductionfactor = 1.0 + else: + idx_regime = 0 if flow_condition == 0 else 1 + reductiontime = con.linearreductiontime[idx_regime] + if reductiontime <= 0: + sta.reductionfactor = 0.0 + else: + sta.reductionfactor = max( + 0.0, sta.reductionfactor - 1.0 / reductiontime + ) + + forecast_step: float = sta.forecaststep if isforecastmode else 0.0 + sta.forecaststep = (forecast_step + 1.0) if isforecastmode else 0.0 + model.calc_averagedresidual_v1(forecast_step, residual) + effective_residual: float = ( + residual + if con.residualaveragingwindow <= 0 + else residual + + ( + 1.0 + if con.residualtransitiontime <= 0 + else min(1.0, forecast_step / con.residualtransitiontime) + ) + * (sta.averagedresidual - residual) + ) + + forecast_value: float = log.loggedsimulateddischarge[0] + damped_residual: float = effective_residual * sta.reductionfactor + max_fraction: float = con.maxrelativeshift / 100.0 + shift: float = ( + forecast_value + * min(max_fraction, max(-max_fraction, damped_residual / sim_anchor)) + if sim_anchor > 0.0 and forecast_value <= sim_anchor + else min(con.maxabsoluteshift, max(-con.maxabsoluteshift, damped_residual)) + ) + flu.correctedq = forecast_value + shift + + +class Get_CorrectedOutput_V1(modeltools.Method): + """Return the most recently calculated corrected discharge in m³/s. + + Example: + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> fluxes.correctedq = 2.5 + >>> from hydpy import round_ + >>> round_(model.get_correctedoutput_v1()) + 2.5 + """ + + REQUIREDSEQUENCES = (statcorr_fluxes.CorrectedQ,) + + @staticmethod + def __call__(model: modeltools.Model, /) -> float: + flu = model.sequences.fluxes.fastaccess + return flu.correctedq + + +class Sub_OutputCorrModel(modeltools.AdHocModel): + """Base class for submodels that comply with the submodel interfaces defined in + module |statcorrinterfaces|.""" diff --git a/hydpy/models/statcorr/statcorr_outlets.py b/hydpy/models/statcorr/statcorr_outlets.py new file mode 100644 index 0000000000..1c5ddd04ac --- /dev/null +++ b/hydpy/models/statcorr/statcorr_outlets.py @@ -0,0 +1,10 @@ +# pylint: disable=missing-module-docstring + +from hydpy.core import sequencetools +from hydpy.core.typingtools import * + + +class Q(sequencetools.OutletSequence): + """Abfluss (runoff) [m³/s].""" + + NDIM: Final[Literal[0]] = 0 diff --git a/hydpy/models/statcorr/statcorr_states.py b/hydpy/models/statcorr/statcorr_states.py new file mode 100644 index 0000000000..aae200de10 --- /dev/null +++ b/hydpy/models/statcorr/statcorr_states.py @@ -0,0 +1,74 @@ +# pylint: disable=missing-module-docstring + +from hydpy.core import sequencetools +from hydpy.core.typingtools import * + + +class ReductionFactor(sequencetools.StateSequence): + """Factor for linearly reducing the ARIMA correction to zero under instationary + flow conditions (1.0: apply the correction unabated; 0.0: apply no correction at + all) [-].""" + + NDIM: Final[Literal[0]] = 0 + SPAN = (0.0, 1.0) + INIT = 1.0 + + +class Stationary(sequencetools.StateSequence): + """Flag (1.0: yes, 0.0: no) telling whether the measured discharge behaved in a + stationary way at the last assessment (1.0: apply |ReductionFactor| unabated; + 0.0: reduce |ReductionFactor| linearly) [-]. + + |statcorr_arima010| only reassesses stationarity while |Options.simulationmode| + equals `historical`. While it equals `forecast`, |Stationary| keeps the value + determined at the most recent `historical` assessment, so |ReductionFactor| + keeps ramping towards zero (or stays at ``1.0``) throughout the whole forecast + horizon instead of jumping back to ``1.0`` once the logged observations run + out.""" + + NDIM: Final[Literal[0]] = 0 + SPAN = (0.0, 1.0) + INIT = 1.0 + + +class FlowCondition(sequencetools.StateSequence): + """The most recently determined flow condition (0.0: NQ, 1.0: MQ, 2.0: HQ) [-]. + + Like |Stationary|, |statcorr_arima010| only reassesses |FlowCondition| while + |Options.simulationmode| equals `historical`. While it equals `forecast`, + |FlowCondition| keeps the value determined at the most recent `historical` + assessment, so |Determine_OutputCorrection_V1| always relies on the flow + condition observed right before the forecast horizon started rather than on + the (still continuously simulated) current discharge, which could otherwise + let |ReductionFactor| jump back to ``1.0`` whenever the forecasted discharge + happens to pass through the HQ range.""" + + NDIM: Final[Literal[0]] = 0 + SPAN = (0.0, 2.0) + INIT = 2.0 + + +class ForecastStep(sequencetools.StateSequence): + """The number of elapsed forecast steps since the start of the current + forecast run (``0.0`` on the first forecast step), reset to ``0.0`` + whenever |Options.simulationmode| equals `historical` [-]. + + |Determine_OutputCorrection_V1| uses |ForecastStep| to linearly blend the + applied residual from the single most recent (pointwise) value towards + the mean-value-based residual determined via |ResidualAveragingWindow| + over |ResidualTransitionTime| forecast steps.""" + + NDIM: Final[Literal[0]] = 0 + SPAN = (0.0, None) + INIT = 0.0 + + +class AveragedResidual(sequencetools.StateSequence): + """The mean-value-based ARIMA residual (mean observed minus mean simulated + discharge over the |ResidualAveragingWindow| log entries immediately + preceding the current forecast run) in m³/s, determined once at the first + forecast step and kept unchanged for the remainder of the forecast + horizon.""" + + NDIM: Final[Literal[0]] = 0 + INIT = 0.0 diff --git a/hydpy/models/statcorr_arima010.py b/hydpy/models/statcorr_arima010.py new file mode 100644 index 0000000000..d48a487d9e --- /dev/null +++ b/hydpy/models/statcorr_arima010.py @@ -0,0 +1,163 @@ +# pylint: disable=unused-wildcard-import +""" +|statcorr_arima010| performs statistical output correction of discharge forecasts +based on an ARIMA(0,1,0) error model. + +The corrected discharge is derived from the most recently available residual +(observed minus simulated discharge). When the current observation is +|numpy.nan| (typical in forecast mode), the correction falls back to the most +recent past residual within the configured logging window — this is the +random-walk persistence of the error. This fallback search looks back at most +|MaxResidualLookback| log entries; when no observation is available within +that range (or the entire log, whichever is smaller), no correction is applied. + +How the residual is applied depends on how the current simulated discharge +compares to the simulated discharge at the point the residual was determined: +if it is higher, the residual is added unchanged (capped at +|MaxAbsoluteShift|); otherwise, it is applied as a percentage of that anchor +value instead (capped at |MaxRelativeShift|), which keeps the correction from +overshooting or turning negative while the discharge recedes. See +|Determine_OutputCorrection_V1| for the exact formulas. + +Setting |ResidualAveragingWindow| to a value greater than zero switches from +that pointwise residual to a mean-value-based one (mean observed minus mean +simulated discharge over the given number of log entries immediately +preceding the current forecast run), blended in linearly over +|ResidualTransitionTime| forecast steps to avoid a jump right where the +forecast begins. See |Determine_OutputCorrection_V1| and +|Calc_AveragedResidual_V1| for details. + +|statcorr_arima010| serves as a submodel for |statcorr| and complies with the +|OutputCorrModel_V1| interface. + +Example workflow +================ + + Allocating the internal log resizes both the simulated and the observed + discharge log to the requested number of entries: + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> control.corrnq(True) + >>> control.corrmq(True) + >>> control.corrhq(True) + >>> control.limitnqm(3.0) + >>> control.limitmqh(5.0) + >>> control.evaluationwindow(3) + >>> control.qminqmax(0.0) + >>> control.nqmstationaritywindow(3) + >>> control.linearreductiontime(1, 1) + >>> control.maxresiduallookback(3) + >>> control.maxabsoluteshift(100.0) + >>> control.maxrelativeshift(1000.0) + >>> control.residualaveragingwindow(0) + >>> control.residualtransitiontime(0) + >>> model.prepare_nmblogentries(3) + >>> derived.nmblogentries + nmblogentries(3) + >>> logs.loggedsimulateddischarge + loggedsimulateddischarge(nan, nan, nan) + >>> logs.loggedobserveddischarge + loggedobserveddischarge(nan, nan, nan) + + Successive calls of |OutputCorrModel_V1.set_simulateddischarge| and + |OutputCorrModel_V1.set_observeddischarge| shift the previously buffered + values one position to the right and store the new value at position 0: + + >>> model.set_simulateddischarge(2.0) + >>> model.set_observeddischarge(3.0) + >>> model.set_simulateddischarge(3.0) + >>> model.set_observeddischarge(4.0) + >>> model.set_simulateddischarge(5.0) + >>> from numpy import nan + >>> model.set_observeddischarge(nan) + >>> logs.loggedsimulateddischarge + loggedsimulateddischarge(5.0, 3.0, 2.0) + >>> logs.loggedobserveddischarge + loggedobserveddischarge(nan, 4.0, 3.0) + + |OutputCorrModel_V1.determine_outputcorrection| computes the corrected + discharge from the random-walk residual (here taken from log position 1, + since position 0 has no observation) and stores it internally; + |OutputCorrModel_V1.get_correctedoutput| returns the buffered value: + + >>> model.determine_outputcorrection(False) + >>> from hydpy import round_ + >>> round_(model.get_correctedoutput()) + 6.0 +""" + +from hydpy.core import modeltools +from hydpy.exe.modelimports import * +from hydpy.interfaces import statcorrinterfaces +from hydpy.models.statcorr import statcorr_derived +from hydpy.models.statcorr import statcorr_model + +ADDITIONAL_DERIVEDPARAMETERS = (statcorr_derived.NmbLogEntries,) + + +class Model(statcorr_model.Sub_OutputCorrModel, statcorrinterfaces.OutputCorrModel_V1): + """|statcorr_arima010.DOCNAME.complete|.""" + + DOCNAME = modeltools.DocName( + short="Statcorr-ARIMA010", + description="ARIMA(0,1,0) — random walk — output correction for discharge", + ) + __HYDPY_ROOTMODEL__ = False + + INLET_METHODS = () + OBSERVER_METHODS = () + RECEIVER_METHODS = () + RUN_METHODS = () + INTERFACE_METHODS = ( + statcorr_model.Set_SimulatedDischarge_V1, + statcorr_model.Set_ObservedDischarge_V1, + statcorr_model.Determine_OutputCorrection_V1, + statcorr_model.Get_CorrectedOutput_V1, + ) + ADD_METHODS = (statcorr_model.Calc_AveragedResidual_V1,) + OUTLET_METHODS = () + SENDER_METHODS = () + SUBMODELINTERFACES = () + SUBMODELS = () + + def prepare_nmblogentries(self, nmblogentries: int) -> None: + """Allocate the internal log to hold `nmblogentries` discharge values and + initialise |ReductionFactor|, |Stationary|, |FlowCondition|, + |ForecastStep|, and |AveragedResidual| to ``1.0``, ``1.0``, ``2.0``, + ``0.0``, and ``0.0`` (no reduction, stationary conditions assumed, HQ + flow condition assumed, no forecast steps elapsed, no mean-value-based + residual determined yet). + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> model.prepare_nmblogentries(4) + >>> derived.nmblogentries + nmblogentries(4) + >>> logs.loggedsimulateddischarge + loggedsimulateddischarge(nan, nan, nan, nan) + >>> logs.loggedobserveddischarge + loggedobserveddischarge(nan, nan, nan, nan) + >>> states.reductionfactor + reductionfactor(1.0) + >>> states.stationary + stationary(1.0) + >>> states.flowcondition + flowcondition(2.0) + >>> states.forecaststep + forecaststep(0.0) + >>> states.averagedresidual + averagedresidual(0.0) + """ + self.parameters.derived.nmblogentries(nmblogentries) + self.sequences.logs.loggedsimulateddischarge.shape = nmblogentries + self.sequences.logs.loggedobserveddischarge.shape = nmblogentries + self.sequences.states.reductionfactor(1.0) + self.sequences.states.stationary(1.0) + self.sequences.states.flowcondition(2.0) + self.sequences.states.forecaststep(0.0) + self.sequences.states.averagedresidual(0.0) + + +tester = Tester() +cythonizer = Cythonizer() diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py new file mode 100644 index 0000000000..05729fd86a --- /dev/null +++ b/hydpy/models/statcorr_main.py @@ -0,0 +1,132 @@ +# pylint: disable=unused-wildcard-import +""" +|statcorr_main| applies statistical output correction to discharge forecasts. It reads +the simulated discharge from its inlet node(s), passes it through one or more +|OutputCorrModel_V1| submodels (e.g. |statcorr_arima010|), and delivers the corrected +discharge to the outlet node. + +Integration test +================ + + .. how_to_understand_integration_tests:: + + We prepare a simulation period of six days: + + >>> from hydpy import pub + >>> pub.timegrids = "2000-01-01", "2000-01-07", "1d" + + >>> from hydpy.models.statcorr_main import * + >>> parameterstep() + + We connect the model to a single inlet and outlet node and set up the test object: + + >>> from hydpy import Element, IntegrationTest + >>> element = Element("element", inlets="inlet", outlets="outlet") + >>> element.model = model + + We configure a logging window of three time steps and attach a single + |statcorr_arima010| submodel. Setting |QminQmax| to zero disables the LARSIM + stationarity check (any quotient of the measured discharge's minimum and + maximum is at least zero), so the ARIMA correction always applies unabated: + + >>> loggingwindow(3) + >>> nmboutputcorrmodels(1) + >>> propagatecorrection(True) + >>> with model.add_outputcorrmodel_v1( + ... "statcorr_arima010", position=0 + ... ) as submodel: + ... submodel.parameters.control.corrnq(True) + ... submodel.parameters.control.corrmq(True) + ... submodel.parameters.control.corrhq(True) + ... submodel.parameters.control.limitnqm(0.0) + ... submodel.parameters.control.limitmqh(100.0) + ... submodel.parameters.control.evaluationwindow(3) + ... submodel.parameters.control.maxresiduallookback(3) + ... submodel.parameters.control.maxabsoluteshift(100.0) + ... submodel.parameters.control.maxrelativeshift(1000.0) + ... submodel.parameters.control.residualaveragingwindow(0) + ... submodel.parameters.control.residualtransitiontime(0) + ... submodel.parameters.control.qminqmax(0.0) + ... submodel.parameters.control.nqmstationaritywindow(3) + ... submodel.parameters.control.linearreductiontime(1, 1) + + >>> test = IntegrationTest(element) + + The inlet provides the simulated discharge; |Discharge| carries the observations. + Observations are available for the first two steps only, simulating a forecast + period starting on day three: + + >>> from numpy import nan + >>> element.inlets.inlet.sequences.sim.series = 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 + >>> with pub.options.checkseries(False): + ... inputs.discharge.series = 1.5, 2.5, nan, nan, nan, nan + + During the first two steps the correction is based on the concurrent residual + (``0.5``). In the forecast period the model falls back to the most recent + available residual, which stays at ``0.5`` until it drops out of the logging + window on day five, after which no correction is applied: + +.. integration-test:: + + >>> test.dateformat = '%d/%m %H:00' + >>> test() + | date | discharge | inflow | correctedq | inlet | outlet | + ------------------------------------------------------------------ + | 01/01 00:00 | 1.5 | 1.0 | 1.5 | 1.0 | 1.5 | + | 02/01 00:00 | 2.5 | 2.0 | 2.5 | 2.0 | 2.5 | + | 03/01 00:00 | nan | 3.0 | 3.5 | 3.0 | 3.5 | + | 04/01 00:00 | nan | 4.0 | 4.5 | 4.0 | 4.5 | + | 05/01 00:00 | nan | 5.0 | 5.0 | 5.0 | 5.0 | + | 06/01 00:00 | nan | 6.0 | 6.0 | 6.0 | 6.0 | +""" + +from hydpy.core import importtools +from hydpy.core import modeltools +from hydpy.exe.modelimports import * +from hydpy.interfaces import statcorrinterfaces +from hydpy.models.statcorr import statcorr_control +from hydpy.models.statcorr import statcorr_model + +ADDITIONAL_CONTROLPARAMETERS = ( + statcorr_control.LoggingWindow, + statcorr_control.NmbOutputCorrModels, + statcorr_control.PropagateCorrection, +) + + +class Model(statcorr_model.Model): + """|statcorr_main.DOCNAME.complete|.""" + + DOCNAME = modeltools.DocName( + short="Statcorr-Main", + description="main statistical output correction model for discharge forecasts", + ) + __HYDPY_ROOTMODEL__ = True + + outputcorrmodels = modeltools.SubmodelsProperty( + statcorrinterfaces.OutputCorrModel_V1 + ) + + @importtools.prepare_submodel( + "outputcorrmodels", + statcorrinterfaces.OutputCorrModel_V1, + statcorrinterfaces.OutputCorrModel_V1.prepare_nmblogentries, + dimensionality=1, + ) + def add_outputcorrmodel_v1( + self, + outputcorrmodel: statcorrinterfaces.OutputCorrModel_V1, + *, + position: int, + refresh: bool, # pylint: disable=unused-argument + ) -> None: + """Initialise the given submodel that follows the |OutputCorrModel_V1| + interface and propagate the main model's |LoggingWindow| to its internal + log allocation.""" + nmb = int(self.parameters.control.loggingwindow.value) + outputcorrmodel.parameters.control.loggingwindow(nmb) + outputcorrmodel.prepare_nmblogentries(nmb) + + +tester = Tester() +cythonizer = Cythonizer() From 26fe5004ed0ea56f171ddce5f7607ca7eb85e902 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Tue, 21 Jul 2026 13:45:17 +0200 Subject: [PATCH 03/43] Behebe Mypy-Problem in statcorr_main.py --- hydpy/models/statcorr_main.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py index 05729fd86a..89caf0e82b 100644 --- a/hydpy/models/statcorr_main.py +++ b/hydpy/models/statcorr_main.py @@ -94,7 +94,7 @@ ) -class Model(statcorr_model.Model): +class Model(modeltools.AdHocModel): """|statcorr_main.DOCNAME.complete|.""" DOCNAME = modeltools.DocName( @@ -103,6 +103,17 @@ class Model(statcorr_model.Model): ) __HYDPY_ROOTMODEL__ = True + INLET_METHODS = (statcorr_model.Pick_Inflow_V1,) + OBSERVER_METHODS = () + RECEIVER_METHODS = () + RUN_METHODS = (statcorr_model.Calc_OutputCorr_V1,) + INTERFACE_METHODS = (statcorr_model.Get_Discharge_V1,) + ADD_METHODS = () + OUTLET_METHODS = (statcorr_model.Pass_CorrectedQ_V1,) + SENDER_METHODS = () + SUBMODELINTERFACES = (statcorrinterfaces.OutputCorrModel_V1,) + SUBMODELS = () + outputcorrmodels = modeltools.SubmodelsProperty( statcorrinterfaces.OutputCorrModel_V1 ) From 7b21f53f1f56632d44a75f37d33ce2284beab4da Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Thu, 23 Jul 2026 12:15:59 +0200 Subject: [PATCH 04/43] =?UTF-8?q?Mache=20versehentliche=20=C3=84nderung=20?= =?UTF-8?q?in=20optiontools.py=20r=C3=BCckg=C3=A4ngig?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hydpy/core/optiontools.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hydpy/core/optiontools.py b/hydpy/core/optiontools.py index a29dc67435..09588dd2ac 100644 --- a/hydpy/core/optiontools.py +++ b/hydpy/core/optiontools.py @@ -881,7 +881,7 @@ class Options: """, ) printprogress = OptionPropertyBool( - False, + True, """A bool-like flag for printing information about the progress of some processes to the standard output. @@ -1015,7 +1015,7 @@ class Options: """, ) usecython = OptionPropertyBool( - False, + True, """A bool-like flag for applying cythonized models, which are much faster than pure Python models. From 8710426ef2c565ea53f382dfa32cd1e704d4d0eb Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Mon, 27 Jul 2026 13:34:37 +0200 Subject: [PATCH 05/43] Remove unused method Pass_Q_V1 --- hydpy/models/statcorr/statcorr_model.py | 31 ------------------------- 1 file changed, 31 deletions(-) diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 38b279b975..f32202f21e 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -242,37 +242,6 @@ def __call__(model: modeltools.Model, /) -> None: ).get_correctedoutput() -class Pass_Q_V1(modeltools.Method): - """Update the outlet link sequence. - - Basic equation: - :math:`Q_{outlets} = Q_{fluxes} + Q_{inputs}` - - |Pass_Q_V1| is used, for example, by |statcorr_test|, not by |statcorr| itself - (which uses |Pass_CorrectedQ_V1| instead): - - Example: - - >>> from hydpy.models.statcorr_test import * - >>> parameterstep() - >>> fluxes.inflow = 2.0 - >>> inputs.discharge = 1.0 - >>> model.pass_q_v1() - >>> outlets.q - q(3.0) - """ - - REQUIREDSEQUENCES = (statcorr_fluxes.Inflow, statcorr_inputs.Discharge) - RESULTSEQUENCES = (statcorr_outlets.Q,) - - @staticmethod - def __call__(model: modeltools.Model, /) -> None: - flu = model.sequences.fluxes.fastaccess - inp = model.sequences.inputs.fastaccess - out = model.sequences.outlets.fastaccess - out.q = flu.inflow + inp.discharge - - class Pass_CorrectedQ_V1(modeltools.Method): """Pass the corrected discharge on to the outlet link sequence, unless |PropagateCorrection| is |False|, in which case the uncorrected inflow is From 8b61bd6dc863e93deabbfa0103ea8f9003b89553 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Mon, 27 Jul 2026 15:29:14 +0200 Subject: [PATCH 06/43] Fix bug in statcorr_derived.py Add pylint ignore statement in statcorr/__init__.py Add simulationmode in doctest in xmltools.py --- hydpy/exe/xmltools.py | 1 + hydpy/models/statcorr/__init__.py | 4 +++- hydpy/models/statcorr/statcorr_derived.py | 26 +++++++++++------------ 3 files changed, 17 insertions(+), 14 deletions(-) diff --git a/hydpy/exe/xmltools.py b/hydpy/exe/xmltools.py index 79ebc98527..3904815484 100644 --- a/hydpy/exe/xmltools.py +++ b/hydpy/exe/xmltools.py @@ -585,6 +585,7 @@ def update_options(self) -> None: parameterstep -> Period("1d") printprogress -> FALSE reprdigits -> 6 + simulationmode -> 'historical' simulationstep -> Period() threads -> 0 timestampleft -> TRUE diff --git a/hydpy/models/statcorr/__init__.py b/hydpy/models/statcorr/__init__.py index 8d59d7e540..56e96bb327 100644 --- a/hydpy/models/statcorr/__init__.py +++ b/hydpy/models/statcorr/__init__.py @@ -11,7 +11,9 @@ statcorr_control.PropagateCorrection, ) -from hydpy.models.statcorr.statcorr_model import Model +from hydpy.models.statcorr.statcorr_model import ( # pylint: disable=wrong-import-position + Model, +) tester = Tester() cythonizer = Cythonizer() diff --git a/hydpy/models/statcorr/statcorr_derived.py b/hydpy/models/statcorr/statcorr_derived.py index 85c303987f..753c8cbe6f 100644 --- a/hydpy/models/statcorr/statcorr_derived.py +++ b/hydpy/models/statcorr/statcorr_derived.py @@ -53,7 +53,7 @@ def update(self) -> None: The number of the required log entries depends on the parameter |LoggingWindow| and the simulation step size: - >>> from hydpy.models.statcorr import * + >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() >>> from hydpy import pub >>> from hydpy.core.timetools import Period @@ -63,12 +63,12 @@ def update(self) -> None: >>> derived.nmblogentries nmblogentries(24) >>> logs # doctest: +ELLIPSIS - loggedobserveddischarge(nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, - nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, - nan, nan, nan, nan) - loggedsimulateddischarge(nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, - nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, - nan, nan, nan, nan) + loggedobserveddischarge(nan, nan, nan, nan, nan, nan, nan, nan, nan, + nan, nan, nan, nan, nan, nan, nan, nan, nan, + nan, nan, nan, nan, nan, nan) + loggedsimulateddischarge(nan, nan, nan, nan, nan, nan, nan, nan, nan, + nan, nan, nan, nan, nan, nan, nan, nan, nan, + nan, nan, nan, nan, nan, nan) To prevent losing information, updating parameter |NmbLogEntries| resets the shape of the relevant log sequences only when necessary: @@ -76,12 +76,12 @@ def update(self) -> None: >>> logs.loggedobserveddischarge = 1.0 >>> derived.nmblogentries(24) >>> logs # doctest: +ELLIPSIS - loggedobserveddischarge(1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0) - loggedsimulateddischarge(nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, - nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, - nan, nan, nan, nan) + loggedobserveddischarge(1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0) + loggedsimulateddischarge(nan, nan, nan, nan, nan, nan, nan, nan, nan, + nan, nan, nan, nan, nan, nan, nan, nan, nan, + nan, nan, nan, nan, nan, nan) .. testsetup:: From c7500bd0e203bcaa6c601aa270d3a0bc87240ad4 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Mon, 27 Jul 2026 23:38:52 +0200 Subject: [PATCH 07/43] Create HydPy-StatCorr.rst Add statcorr references in model_families.rst and submodel_interfaces.rst --- hydpy/docs/rst/model_families.rst | 1 + hydpy/docs/rst/submodel_interfaces.rst | 1 + 2 files changed, 2 insertions(+) diff --git a/hydpy/docs/rst/model_families.rst b/hydpy/docs/rst/model_families.rst index 61e4e392e6..9cfdf8971f 100644 --- a/hydpy/docs/rst/model_families.rst +++ b/hydpy/docs/rst/model_families.rst @@ -74,6 +74,7 @@ the :ref:`model_overview` section, which clarifies this distinction more clearly HydPy-Musk HydPy-Rconc HydPy-Snow + HydPy-StatCorr HydPy-SW1D HydPy-Test HydPy-W diff --git a/hydpy/docs/rst/submodel_interfaces.rst b/hydpy/docs/rst/submodel_interfaces.rst index fc0de0e80d..ee0c8258a8 100644 --- a/hydpy/docs/rst/submodel_interfaces.rst +++ b/hydpy/docs/rst/submodel_interfaces.rst @@ -29,6 +29,7 @@ available in the :ref:`model_overview` section, which covers all user-relevant m rconcinterfaces routinginterfaces soilinterfaces + statcorrinterfaces stateinterfaces tempinterfaces transferinterfaces From de3e3f9cbf52a2aa0d33cd19622306901cf1d838 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Tue, 28 Jul 2026 00:07:03 +0200 Subject: [PATCH 08/43] Add HydPy-StatCorr.rst --- hydpy/docs/rst/HydPy-StatCorr.rst | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 hydpy/docs/rst/HydPy-StatCorr.rst diff --git a/hydpy/docs/rst/HydPy-StatCorr.rst b/hydpy/docs/rst/HydPy-StatCorr.rst new file mode 100644 index 0000000000..fc0fbbeaca --- /dev/null +++ b/hydpy/docs/rst/HydPy-StatCorr.rst @@ -0,0 +1,21 @@ + +.. _HydPy-StatCorr: + +HydPy-StatCorr +============== + +All HydPy-StatCorr models deal with the statistical correction of discharge +forecasts. The base model |statcorr| reads the simulated discharge from its inlet +node(s), passes it through one or more submodels complying with the +|OutputCorrModel_V1| interface, and delivers the corrected discharge to the outlet +node. |statcorr_arima010| is such a submodel; it estimates the correction from an +ARIMA(0,1,0) error model, following the LARSIM approach. + +Available models: + +.. toctree:: + :maxdepth: 1 + + statcorr + statcorr_main + statcorr_arima010 From 57dad37d8449e4104a571965b899f9fd7a1ef965 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Tue, 28 Jul 2026 00:22:13 +0200 Subject: [PATCH 09/43] Add # type: ignore[call-overload] in statcorr_main.py and statcorr_model.py --- hydpy/models/statcorr/statcorr_model.py | 2 +- hydpy/models/statcorr_main.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index f32202f21e..48be9a76f9 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -325,7 +325,7 @@ class Model(modeltools.AdHocModel): statcorrinterfaces.OutputCorrModel_V1 ) - @importtools.prepare_submodel( + @importtools.prepare_submodel( # type: ignore[call-overload] "outputcorrmodels", statcorrinterfaces.OutputCorrModel_V1, statcorrinterfaces.OutputCorrModel_V1.prepare_nmblogentries, diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py index 89caf0e82b..eb0a60e2bf 100644 --- a/hydpy/models/statcorr_main.py +++ b/hydpy/models/statcorr_main.py @@ -118,7 +118,7 @@ class Model(modeltools.AdHocModel): statcorrinterfaces.OutputCorrModel_V1 ) - @importtools.prepare_submodel( + @importtools.prepare_submodel( # type: ignore[call-overload] "outputcorrmodels", statcorrinterfaces.OutputCorrModel_V1, statcorrinterfaces.OutputCorrModel_V1.prepare_nmblogentries, From f3f921445e696ee04f1a882eac8df0ade6eedd7c Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Tue, 28 Jul 2026 00:23:36 +0200 Subject: [PATCH 10/43] Remove unused import from statcorr_control.py --- hydpy/models/statcorr/statcorr_control.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index bad2b7c7ea..3d552ab8cb 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -1,7 +1,7 @@ # pylint: disable=missing-module-docstring from hydpy.core import exceptiontools -from hydpy.core import parametertools, timetools +from hydpy.core import parametertools from hydpy.core.typingtools import * From c7ff0b301e3b9951ea4c5bc71184047dd952afd1 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Wed, 29 Jul 2026 10:41:46 +0200 Subject: [PATCH 11/43] Change DOCNAME for statcorr to CamelCase for sphinx Fix pylint warnings --- hydpy/models/statcorr/statcorr_control.py | 1 - hydpy/models/statcorr/statcorr_derived.py | 3 --- hydpy/models/statcorr/statcorr_logs.py | 2 ++ hydpy/models/statcorr/statcorr_model.py | 11 ++++------- hydpy/models/statcorr_arima010.py | 2 +- hydpy/models/statcorr_main.py | 4 ++-- 6 files changed, 9 insertions(+), 14 deletions(-) diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index 3d552ab8cb..e97af72412 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -1,6 +1,5 @@ # pylint: disable=missing-module-docstring -from hydpy.core import exceptiontools from hydpy.core import parametertools from hydpy.core.typingtools import * diff --git a/hydpy/models/statcorr/statcorr_derived.py b/hydpy/models/statcorr/statcorr_derived.py index 753c8cbe6f..087ebb825f 100644 --- a/hydpy/models/statcorr/statcorr_derived.py +++ b/hydpy/models/statcorr/statcorr_derived.py @@ -1,10 +1,7 @@ # pylint: disable=missing-module-docstring -import numpy - import hydpy from hydpy.core import exceptiontools -from hydpy.core import objecttools from hydpy.core import parametertools from hydpy.core.typingtools import * from hydpy.models.statcorr import statcorr_control diff --git a/hydpy/models/statcorr/statcorr_logs.py b/hydpy/models/statcorr/statcorr_logs.py index 9433fdd2b1..9ef0124aa4 100644 --- a/hydpy/models/statcorr/statcorr_logs.py +++ b/hydpy/models/statcorr/statcorr_logs.py @@ -1,3 +1,5 @@ +# pylint: disable=missing-module-docstring + from hydpy.core import sequencetools from hydpy.core.typingtools import * diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 48be9a76f9..3a7dc9c534 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -307,7 +307,7 @@ def __call__(model: modeltools.Model, /) -> float: class Model(modeltools.AdHocModel): """|statcorr.DOCNAME.complete|.""" - DOCNAME = modeltools.DocName(short="statcorr") + DOCNAME = modeltools.DocName(short="StatCorr") __HYDPY_ROOTMODEL__ = None INLET_METHODS = (Pick_Inflow_V1,) @@ -335,7 +335,7 @@ def add_outputcorrmodel_v1( self, outputcorrmodel: statcorrinterfaces.OutputCorrModel_V1, *, - position: int, + position: int, # pylint: disable=unused-argument refresh: bool, # pylint: disable=unused-argument ) -> None: """Initialise the given submodel that follows the |OutputCorrModel_V1| @@ -995,11 +995,8 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: flow_condition = 2 sta.flowcondition = float(flow_condition) - if ( - (flow_condition == 0 and con.corrnq is False) - or (flow_condition == 1 and con.corrmq is False) - or (flow_condition == 2 and con.corrhq is False) - ): + corr_active = (con.corrnq, con.corrmq, con.corrhq)[flow_condition] + if corr_active is False: flu.correctedq = log.loggedsimulateddischarge[0] return diff --git a/hydpy/models/statcorr_arima010.py b/hydpy/models/statcorr_arima010.py index d48a487d9e..5e9d626868 100644 --- a/hydpy/models/statcorr_arima010.py +++ b/hydpy/models/statcorr_arima010.py @@ -100,7 +100,7 @@ class Model(statcorr_model.Sub_OutputCorrModel, statcorrinterfaces.OutputCorrMod """|statcorr_arima010.DOCNAME.complete|.""" DOCNAME = modeltools.DocName( - short="Statcorr-ARIMA010", + short="StatCorr-ARIMA010", description="ARIMA(0,1,0) — random walk — output correction for discharge", ) __HYDPY_ROOTMODEL__ = False diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py index eb0a60e2bf..15c59f21c8 100644 --- a/hydpy/models/statcorr_main.py +++ b/hydpy/models/statcorr_main.py @@ -98,7 +98,7 @@ class Model(modeltools.AdHocModel): """|statcorr_main.DOCNAME.complete|.""" DOCNAME = modeltools.DocName( - short="Statcorr-Main", + short="StatCorr-Main", description="main statistical output correction model for discharge forecasts", ) __HYDPY_ROOTMODEL__ = True @@ -128,7 +128,7 @@ def add_outputcorrmodel_v1( self, outputcorrmodel: statcorrinterfaces.OutputCorrModel_V1, *, - position: int, + position: int, # pylint: disable=unused-argument refresh: bool, # pylint: disable=unused-argument ) -> None: """Initialise the given submodel that follows the |OutputCorrModel_V1| From fc05310e2e6b0713223a399967fa9730e83ff1cc Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Wed, 29 Jul 2026 13:50:50 +0200 Subject: [PATCH 12/43] Revert change in statcorr_model.py and insert pylint disable statement instead --- hydpy/models/statcorr/statcorr_model.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 3a7dc9c534..cd5048244e 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -995,8 +995,11 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: flow_condition = 2 sta.flowcondition = float(flow_condition) - corr_active = (con.corrnq, con.corrmq, con.corrhq)[flow_condition] - if corr_active is False: + if ( # pylint: disable=too-many-boolean-expressions + (flow_condition == 0 and con.corrnq is False) + or (flow_condition == 1 and con.corrmq is False) + or (flow_condition == 2 and con.corrhq is False) + ): flu.correctedq = log.loggedsimulateddischarge[0] return From d422b7b2767d52220c4e6b090b4e390a889174d6 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Thu, 30 Jul 2026 10:45:47 +0200 Subject: [PATCH 13/43] Fix pylint statement in statcorr_model.py --- hydpy/models/statcorr/statcorr_model.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index cd5048244e..7a638451ef 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -995,13 +995,15 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: flow_condition = 2 sta.flowcondition = float(flow_condition) - if ( # pylint: disable=too-many-boolean-expressions + # pylint: disable=too-many-boolean-expressions + if ( (flow_condition == 0 and con.corrnq is False) or (flow_condition == 1 and con.corrmq is False) or (flow_condition == 2 and con.corrhq is False) ): flu.correctedq = log.loggedsimulateddischarge[0] return + # pylint: enable=too-many-boolean-expressions residual: float = 0.0 sim_anchor: float = 0.0 From 7e4638198561bbe20dd6764ca4b625ccaa5c29e8 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Tue, 1 Sep 2026 21:55:22 +0200 Subject: [PATCH 14/43] Minor corrections of docstrings --- hydpy/models/statcorr/statcorr_control.py | 6 ++---- hydpy/models/statcorr/statcorr_fluxes.py | 2 +- hydpy/models/statcorr/statcorr_inlets.py | 2 +- hydpy/models/statcorr/statcorr_outlets.py | 2 +- 4 files changed, 5 insertions(+), 7 deletions(-) diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index e97af72412..641b2e7230 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -111,8 +111,7 @@ def __call__(self, *args, **kwargs) -> None: class LimitNQM(parametertools.Parameter): - """ - Discharge threshold for the transition from NQ to MQ range in m³/s. + """Discharge threshold for the transition from NQ to MQ range in m³/s. """ NDIM: Final[Literal[0]] = 0 @@ -120,8 +119,7 @@ class LimitNQM(parametertools.Parameter): class LimitMQH(parametertools.Parameter): - """ - Discharge threshold for the transition from MQ to HQ range in m³/s. + """Discharge threshold for the transition from MQ to HQ range in m³/s. """ NDIM: Final[Literal[0]] = 0 diff --git a/hydpy/models/statcorr/statcorr_fluxes.py b/hydpy/models/statcorr/statcorr_fluxes.py index 805a277fa6..da3e36de14 100644 --- a/hydpy/models/statcorr/statcorr_fluxes.py +++ b/hydpy/models/statcorr/statcorr_fluxes.py @@ -5,7 +5,7 @@ class Inflow(sequencetools.FluxSequence): - """Flow into the first channel segment [m³/s].""" + """Inflow [m³/s].""" NDIM: Final[Literal[0]] = 0 diff --git a/hydpy/models/statcorr/statcorr_inlets.py b/hydpy/models/statcorr/statcorr_inlets.py index c95be13e8d..3443e9101c 100644 --- a/hydpy/models/statcorr/statcorr_inlets.py +++ b/hydpy/models/statcorr/statcorr_inlets.py @@ -5,6 +5,6 @@ class Q(sequencetools.InletSequence): - """Abfluss (runoff) [m³/s].""" + """Discharge [m³/s].""" NDIM: Final[Literal[1]] = 1 diff --git a/hydpy/models/statcorr/statcorr_outlets.py b/hydpy/models/statcorr/statcorr_outlets.py index 1c5ddd04ac..005f765793 100644 --- a/hydpy/models/statcorr/statcorr_outlets.py +++ b/hydpy/models/statcorr/statcorr_outlets.py @@ -5,6 +5,6 @@ class Q(sequencetools.OutletSequence): - """Abfluss (runoff) [m³/s].""" + """Discharge [m³/s].""" NDIM: Final[Literal[0]] = 0 From ff15ba71eadc1cb9633873add0159605683e3d9c Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Wed, 2 Sep 2026 00:15:32 +0200 Subject: [PATCH 15/43] Implement states Residual and ResidualAnchor --- hydpy/models/statcorr/statcorr_model.py | 79 ++++++++++++++++++------ hydpy/models/statcorr/statcorr_states.py | 28 +++++++++ hydpy/models/statcorr_arima010.py | 31 +++++++--- 3 files changed, 111 insertions(+), 27 deletions(-) diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 7a638451ef..947bef71b1 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -196,8 +196,10 @@ class Calc_OutputCorr_V1(modeltools.Method): >>> fluxes.correctedq correctedq(4.5) - Once the last real observation drops out of the three-step logging - window, no correction is applied anymore: + Even once the last real observation drops out of the three-step + logging window, the persisted residual keeps applying without limit + -- only |ReductionFactor| (via |QminQmax| and |LinearReductionTime|, + both disabled here) could still fade it out: >>> with pub.options.simulationmode("forecast"): ... model.parameters.update() @@ -205,7 +207,14 @@ class Calc_OutputCorr_V1(modeltools.Method): ... inputs.discharge = 999.0 ... model.calc_outputcorr_v1() >>> fluxes.correctedq - correctedq(5.0) + correctedq(5.5) + >>> with pub.options.simulationmode("forecast"): + ... model.parameters.update() + ... fluxes.inflow = 6.0 + ... inputs.discharge = 999.0 + ... model.calc_outputcorr_v1() + >>> fluxes.correctedq + correctedq(6.5) """ SUBMODELINTERFACES = (statcorrinterfaces.OutputCorrModel_V1,) @@ -525,11 +534,17 @@ class Determine_OutputCorrection_V1(modeltools.Method): error model. The correction is derived from the most recently available residual - (observed minus simulated discharge). The "most recent" residual is taken - from the latest log entry where the observed discharge is not |numpy.nan|, - searching back at most |MaxResidualLookback| log entries (or the entire - log, whichever is smaller). When no observation is available within that - range, the corrected discharge equals the current simulated discharge. + (observed minus simulated discharge). While |Options.simulationmode| + equals `historical`, the "most recent" residual is taken from the latest + log entry where the observed discharge is not |numpy.nan|, searching back + at most |MaxResidualLookback| log entries (or the entire log, whichever is + smaller), and remembered in |Residual| (together with the corresponding + simulated discharge in |ResidualAnchor|). When no observation is + available within that range, both are set to zero, so the corrected + discharge equals the current simulated discharge. While + |Options.simulationmode| equals `forecast`, |Determine_OutputCorrection_V1| + does not repeat this search — see the paragraph on |Residual| and + |ResidualAnchor| below for why. How that residual is applied to the current simulated ("forecast") discharge depends on how the latter (:math:`sim_0`) compares to the @@ -612,6 +627,18 @@ class Determine_OutputCorrection_V1(modeltools.Method): logging window or whenever the forecasted discharge happens to pass through the HQ range. + Likewise, |Determine_OutputCorrection_V1| only reassesses the pointwise + residual itself (the |MaxResidualLookback| search described above) while + |Options.simulationmode| equals `historical`, remembering the outcome in + |Residual| and |ResidualAnchor|. While it equals `forecast`, it reuses + both from the most recent `historical` assessment instead of repeating + the search, so the (|ReductionFactor|-damped) correction persists for the + entire forecast horizon instead of vanishing as soon as the underlying + log entry drops out of the logging window. Together with the preceding + paragraph, this means only |ReductionFactor| (and, if configured, the + blend towards |AveragedResidual|) can still change the correction once a + forecast run is underway. + Examples: Three log entries are available, the most recent observation (at @@ -884,9 +911,10 @@ class Determine_OutputCorrection_V1(modeltools.Method): Setting |ResidualAveragingWindow| to a value greater than zero switches to the mean-value-based residual, blended in linearly over |ResidualTransitionTime| forecast steps. We reset the log to a - short, clean example (four entries) and freeze |FlowCondition| and - |Stationary| directly (instead of deriving them from a preceding - `historical` call) to keep the focus on the transition mechanism: + short, clean example (four entries) and freeze |FlowCondition|, + |Stationary|, |Residual|, and |ResidualAnchor| directly (instead of + deriving them from a preceding `historical` call) to keep the focus + on the transition mechanism: >>> control.maxresiduallookback(4) >>> control.maxabsoluteshift(100.0) @@ -900,6 +928,8 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> states.stationary(1.0) >>> states.reductionfactor(1.0) >>> states.forecaststep(0.0) + >>> states.residual(1.0) + >>> states.residualanchor(8.0) The most recent (pointwise) residual, taken from log position ``1`` (``9.0 - 8.0 = 1.0``), differs from the mean-value-based residual @@ -965,11 +995,16 @@ class Determine_OutputCorrection_V1(modeltools.Method): statcorr_states.FlowCondition, statcorr_states.ForecastStep, statcorr_states.AveragedResidual, + statcorr_states.Residual, + statcorr_states.ResidualAnchor, ) RESULTSEQUENCES = (statcorr_fluxes.CorrectedQ,) @staticmethod def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: + # pylint: disable=too-many-branches + # (I know this method is much too complex but I do not see a good way to + # refactor it) con = model.parameters.control.fastaccess der = model.parameters.derived.fastaccess flu = model.sequences.fluxes.fastaccess @@ -1005,13 +1040,21 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: return # pylint: enable=too-many-boolean-expressions - residual: float = 0.0 - sim_anchor: float = 0.0 - for idx in range(min(der.nmblogentries, con.maxresiduallookback)): - if not modelutils.isnan(log.loggedobserveddischarge[idx]): - sim_anchor = log.loggedsimulateddischarge[idx] - residual = log.loggedobserveddischarge[idx] - sim_anchor - break + residual: float + sim_anchor: float + if isforecastmode: + residual = sta.residual + sim_anchor = sta.residualanchor + else: + residual = 0.0 + sim_anchor = 0.0 + for idx in range(min(der.nmblogentries, con.maxresiduallookback)): + if not modelutils.isnan(log.loggedobserveddischarge[idx]): + sim_anchor = log.loggedsimulateddischarge[idx] + residual = log.loggedobserveddischarge[idx] - sim_anchor + break + sta.residual = residual + sta.residualanchor = sim_anchor if flow_condition == 2: sta.reductionfactor = 1.0 diff --git a/hydpy/models/statcorr/statcorr_states.py b/hydpy/models/statcorr/statcorr_states.py index aae200de10..3846541daa 100644 --- a/hydpy/models/statcorr/statcorr_states.py +++ b/hydpy/models/statcorr/statcorr_states.py @@ -72,3 +72,31 @@ class AveragedResidual(sequencetools.StateSequence): NDIM: Final[Literal[0]] = 0 INIT = 0.0 + + +class Residual(sequencetools.StateSequence): + """The pointwise ARIMA residual (observed minus simulated discharge, taken + from the most recently logged entry with a non-|numpy.nan| observation, + searching back at most |MaxResidualLookback| entries) in m³/s. + + Like |Stationary| and |FlowCondition|, |statcorr_arima010| only + reassesses |Residual| while |Options.simulationmode| equals `historical`. + While it equals `forecast`, |Residual| keeps the value determined at the + most recent `historical` assessment, so the applied correction persists + throughout the whole forecast horizon (subject only to + |ReductionFactor|) instead of vanishing as soon as the underlying log + entry drops out of the logging window.""" + + NDIM: Final[Literal[0]] = 0 + INIT = 0.0 + + +class ResidualAnchor(sequencetools.StateSequence): + """The simulated discharge (in m³/s) at the log position from which + |Residual| was determined. + + Frozen together with |Residual| while |Options.simulationmode| equals + `forecast`; see |Residual| for details.""" + + NDIM: Final[Literal[0]] = 0 + INIT = 0.0 diff --git a/hydpy/models/statcorr_arima010.py b/hydpy/models/statcorr_arima010.py index 5e9d626868..df2f695f5e 100644 --- a/hydpy/models/statcorr_arima010.py +++ b/hydpy/models/statcorr_arima010.py @@ -4,12 +4,18 @@ based on an ARIMA(0,1,0) error model. The corrected discharge is derived from the most recently available residual -(observed minus simulated discharge). When the current observation is -|numpy.nan| (typical in forecast mode), the correction falls back to the most -recent past residual within the configured logging window — this is the -random-walk persistence of the error. This fallback search looks back at most -|MaxResidualLookback| log entries; when no observation is available within -that range (or the entire log, whichever is smaller), no correction is applied. +(observed minus simulated discharge). While |Options.simulationmode| equals +`historical`, this residual is (re)determined every step by searching back at +most |MaxResidualLookback| log entries for the latest non-|numpy.nan| +observation — this is the random-walk persistence of the error whenever the +*current* observation is missing. When no observation is available within +that range (or the entire log, whichever is smaller), no correction is +applied. While |Options.simulationmode| equals `forecast`, this search is +not repeated: the residual (and the simulated discharge it was measured +against) stays frozen at whatever the most recent `historical` assessment +found, so the correction persists throughout the whole forecast horizon +(subject only to |ReductionFactor|) instead of fading once that log entry +ages past |MaxResidualLookback|. How the residual is applied depends on how the current simulated discharge compares to the simulated discharge at the point the residual was determined: @@ -124,9 +130,10 @@ class Model(statcorr_model.Sub_OutputCorrModel, statcorrinterfaces.OutputCorrMod def prepare_nmblogentries(self, nmblogentries: int) -> None: """Allocate the internal log to hold `nmblogentries` discharge values and initialise |ReductionFactor|, |Stationary|, |FlowCondition|, - |ForecastStep|, and |AveragedResidual| to ``1.0``, ``1.0``, ``2.0``, - ``0.0``, and ``0.0`` (no reduction, stationary conditions assumed, HQ - flow condition assumed, no forecast steps elapsed, no mean-value-based + |ForecastStep|, |AveragedResidual|, |Residual|, and |ResidualAnchor| + to ``1.0``, ``1.0``, ``2.0``, ``0.0``, ``0.0``, ``0.0``, and ``0.0`` + (no reduction, stationary conditions assumed, HQ flow condition + assumed, no forecast steps elapsed, no mean-value-based or pointwise residual determined yet). >>> from hydpy.models.statcorr_arima010 import * @@ -148,6 +155,10 @@ def prepare_nmblogentries(self, nmblogentries: int) -> None: forecaststep(0.0) >>> states.averagedresidual averagedresidual(0.0) + >>> states.residual + residual(0.0) + >>> states.residualanchor + residualanchor(0.0) """ self.parameters.derived.nmblogentries(nmblogentries) self.sequences.logs.loggedsimulateddischarge.shape = nmblogentries @@ -157,6 +168,8 @@ def prepare_nmblogentries(self, nmblogentries: int) -> None: self.sequences.states.flowcondition(2.0) self.sequences.states.forecaststep(0.0) self.sequences.states.averagedresidual(0.0) + self.sequences.states.residual(0.0) + self.sequences.states.residualanchor(0.0) tester = Tester() From 746e3f0acaaedb1d5e602e5780c7e3e506c9a764 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Tue, 27 Oct 2026 12:17:54 +0100 Subject: [PATCH 16/43] Rename Parameter NmbOutputCorrModels to NmbSubmodels --- hydpy/models/statcorr/__init__.py | 2 +- hydpy/models/statcorr/statcorr_control.py | 12 +++++------- hydpy/models/statcorr/statcorr_model.py | 10 +++++----- hydpy/models/statcorr_main.py | 4 ++-- 4 files changed, 13 insertions(+), 15 deletions(-) diff --git a/hydpy/models/statcorr/__init__.py b/hydpy/models/statcorr/__init__.py index 56e96bb327..7cc2d83323 100644 --- a/hydpy/models/statcorr/__init__.py +++ b/hydpy/models/statcorr/__init__.py @@ -7,7 +7,7 @@ ADDITIONAL_CONTROLPARAMETERS = ( statcorr_control.LoggingWindow, - statcorr_control.NmbOutputCorrModels, + statcorr_control.NmbSubmodels, statcorr_control.PropagateCorrection, ) diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index 641b2e7230..9572b32c9b 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -11,15 +11,15 @@ class LoggingWindow(parametertools.Parameter): TYPE: Final = int -class NmbOutputCorrModels(parametertools.Parameter): +class NmbSubmodels(parametertools.Parameter): """The number of output correction submodels [-]. - Setting |NmbOutputCorrModels| automatically resizes the + Setting |NmbSubmodels| automatically resizes the |Model.outputcorrmodels| submodel slots accordingly: >>> from hydpy.models.statcorr import * >>> parameterstep() - >>> nmboutputcorrmodels(3) + >>> nmbsubmodels(3) >>> model.outputcorrmodels.number 3 """ @@ -111,16 +111,14 @@ def __call__(self, *args, **kwargs) -> None: class LimitNQM(parametertools.Parameter): - """Discharge threshold for the transition from NQ to MQ range in m³/s. - """ + """Discharge threshold for the transition from NQ to MQ range in m³/s.""" NDIM: Final[Literal[0]] = 0 TYPE: Final = float class LimitMQH(parametertools.Parameter): - """Discharge threshold for the transition from MQ to HQ range in m³/s. - """ + """Discharge threshold for the transition from MQ to HQ range in m³/s.""" NDIM: Final[Literal[0]] = 0 TYPE: Final = float diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 947bef71b1..16cf686f9a 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -105,7 +105,7 @@ class Calc_OutputCorr_V1(modeltools.Method): ... submodel.parameters.control.linearreductiontime(1, 1) >>> loggingwindow(2) - >>> nmboutputcorrmodels(1) + >>> nmbsubmodels(1) >>> with model.add_outputcorrmodel_v1( ... "statcorr_arima010", position=0 ... ) as submodel: @@ -123,7 +123,7 @@ class Calc_OutputCorr_V1(modeltools.Method): With two attached submodels of the same type, the second one's output wins: - >>> nmboutputcorrmodels(2) + >>> nmbsubmodels(2) >>> with model.add_outputcorrmodel_v1( ... "statcorr_arima010", position=0 ... ) as submodel: @@ -156,7 +156,7 @@ class Calc_OutputCorr_V1(modeltools.Method): and wipe their logged history: >>> loggingwindow(3) - >>> nmboutputcorrmodels(1) + >>> nmbsubmodels(1) >>> with model.add_outputcorrmodel_v1( ... "statcorr_arima010", position=0 ... ) as submodel: @@ -354,7 +354,7 @@ def add_outputcorrmodel_v1( >>> from hydpy.models.statcorr import * >>> parameterstep() >>> loggingwindow(4) - >>> nmboutputcorrmodels(1) + >>> nmbsubmodels(1) >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0): ... pass >>> model.outputcorrmodels[0].parameters.derived.nmblogentries @@ -1061,7 +1061,7 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: else: if not isforecastmode: nmb = min(der.nmblogentries, con.nqmstationaritywindow) - stationary: bool = True + stationary = True has_nan = False qmin: float = modelutils.inf qmax: float = -modelutils.inf diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py index 15c59f21c8..e24d2faa40 100644 --- a/hydpy/models/statcorr_main.py +++ b/hydpy/models/statcorr_main.py @@ -30,7 +30,7 @@ maximum is at least zero), so the ARIMA correction always applies unabated: >>> loggingwindow(3) - >>> nmboutputcorrmodels(1) + >>> nmbsubmodels(1) >>> propagatecorrection(True) >>> with model.add_outputcorrmodel_v1( ... "statcorr_arima010", position=0 @@ -89,7 +89,7 @@ ADDITIONAL_CONTROLPARAMETERS = ( statcorr_control.LoggingWindow, - statcorr_control.NmbOutputCorrModels, + statcorr_control.NmbSubmodels, statcorr_control.PropagateCorrection, ) From 951e9a10c0c7c8a23c4d06803e433525f1a9c803 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Tue, 27 Oct 2026 12:24:17 +0100 Subject: [PATCH 17/43] Rename Parameter PropagateCorrection to Propagate --- hydpy/models/statcorr/__init__.py | 2 +- hydpy/models/statcorr/statcorr_control.py | 2 +- hydpy/models/statcorr/statcorr_model.py | 12 ++++++------ hydpy/models/statcorr_main.py | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/hydpy/models/statcorr/__init__.py b/hydpy/models/statcorr/__init__.py index 7cc2d83323..66298935d3 100644 --- a/hydpy/models/statcorr/__init__.py +++ b/hydpy/models/statcorr/__init__.py @@ -8,7 +8,7 @@ ADDITIONAL_CONTROLPARAMETERS = ( statcorr_control.LoggingWindow, statcorr_control.NmbSubmodels, - statcorr_control.PropagateCorrection, + statcorr_control.Propagate, ) from hydpy.models.statcorr.statcorr_model import ( # pylint: disable=wrong-import-position diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index 9572b32c9b..19d2dce281 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -169,7 +169,7 @@ class ResidualTransitionTime(parametertools.Parameter): SPAN = (0, None) -class PropagateCorrection(parametertools.Parameter): +class Propagate(parametertools.Parameter): """Flag determining whether the corrected discharge is passed on to the downstream network (|True|) or calculated only for local output at the current gauge, while the uncorrected inflow is passed on instead diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 16cf686f9a..b490ea0446 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -253,12 +253,12 @@ def __call__(model: modeltools.Model, /) -> None: class Pass_CorrectedQ_V1(modeltools.Method): """Pass the corrected discharge on to the outlet link sequence, unless - |PropagateCorrection| is |False|, in which case the uncorrected inflow is + |Propagate| is |False|, in which case the uncorrected inflow is passed on instead. Either way, |CorrectedQ| remains available for local output at the current gauge. Basic equation: - :math:`Q_{outlets} = CorrectedQ` (if |PropagateCorrection|) or + :math:`Q_{outlets} = CorrectedQ` (if |Propagate|) or :math:`Q_{outlets} = Inflow` (otherwise) Examples: @@ -268,18 +268,18 @@ class Pass_CorrectedQ_V1(modeltools.Method): >>> fluxes.inflow = 1.0 >>> fluxes.correctedq = 2.0 - >>> propagatecorrection(True) + >>> propagate(True) >>> model.pass_correctedq_v1() >>> outlets.q q(2.0) - >>> propagatecorrection(False) + >>> propagate(False) >>> model.pass_correctedq_v1() >>> outlets.q q(1.0) """ - CONTROLPARAMETERS = (statcorr_control.PropagateCorrection,) + CONTROLPARAMETERS = (statcorr_control.Propagate,) REQUIREDSEQUENCES = (statcorr_fluxes.Inflow, statcorr_fluxes.CorrectedQ) RESULTSEQUENCES = (statcorr_outlets.Q,) @@ -288,7 +288,7 @@ def __call__(model: modeltools.Model, /) -> None: con = model.parameters.control.fastaccess flu = model.sequences.fluxes.fastaccess out = model.sequences.outlets.fastaccess - out.q = flu.correctedq if con.propagatecorrection else flu.inflow + out.q = flu.correctedq if con.propagate else flu.inflow class Get_Discharge_V1(modeltools.Method): diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py index e24d2faa40..550c3eeb42 100644 --- a/hydpy/models/statcorr_main.py +++ b/hydpy/models/statcorr_main.py @@ -31,7 +31,7 @@ >>> loggingwindow(3) >>> nmbsubmodels(1) - >>> propagatecorrection(True) + >>> propagate(True) >>> with model.add_outputcorrmodel_v1( ... "statcorr_arima010", position=0 ... ) as submodel: @@ -90,7 +90,7 @@ ADDITIONAL_CONTROLPARAMETERS = ( statcorr_control.LoggingWindow, statcorr_control.NmbSubmodels, - statcorr_control.PropagateCorrection, + statcorr_control.Propagate, ) From 4c5f65c5481e65876dd3e276b61ef34eab344137 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Tue, 27 Oct 2026 13:07:03 +0100 Subject: [PATCH 18/43] Implement LowerLimit and UpperLimit instead of fixed NQ, MQ and HQ flow conditions --- hydpy/interfaces/statcorrinterfaces.py | 9 +- hydpy/models/statcorr/statcorr_control.py | 256 ++++++++++--- hydpy/models/statcorr/statcorr_derived.py | 78 ++++ hydpy/models/statcorr/statcorr_fluxes.py | 8 + hydpy/models/statcorr/statcorr_model.py | 415 +++++++++++++--------- hydpy/models/statcorr/statcorr_states.py | 27 +- hydpy/models/statcorr_arima010.py | 47 ++- hydpy/models/statcorr_main.py | 23 +- 8 files changed, 606 insertions(+), 257 deletions(-) diff --git a/hydpy/interfaces/statcorrinterfaces.py b/hydpy/interfaces/statcorrinterfaces.py index 5fbf4d4454..e44022516b 100644 --- a/hydpy/interfaces/statcorrinterfaces.py +++ b/hydpy/interfaces/statcorrinterfaces.py @@ -19,7 +19,8 @@ class OutputCorrModel_V1(modeltools.SubmodelInterface): 1. |OutputCorrModel_V1.set_simulateddischarge| 2. |OutputCorrModel_V1.set_observeddischarge| 3. |OutputCorrModel_V1.determine_outputcorrection| - 4. |OutputCorrModel_V1.get_correctedoutput| + 4. |OutputCorrModel_V1.is_active| + 5. |OutputCorrModel_V1.get_correctedoutput| """ typeid: ClassVar[Literal[1]] = 1 @@ -54,6 +55,12 @@ def determine_outputcorrection(self, isforecastmode: bool) -> None: |Model.update_parameters| would also needlessly re-run its submodel attachment/initialisation logic, wiping its logged history).""" + @modeltools.abstractmodelmethod + def is_active(self) -> bool: + """Tell whether the submodel was responsible for correcting the discharge + during the most recent call of + |OutputCorrModel_V1.determine_outputcorrection|.""" + @modeltools.abstractmodelmethod def get_correctedoutput(self) -> float: """Get the previously calculated corrected discharge in m³/s.""" diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index 19d2dce281..1088b038fb 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -1,6 +1,8 @@ # pylint: disable=missing-module-docstring +from hydpy.core import objecttools from hydpy.core import parametertools +from hydpy.core import variabletools from hydpy.core.typingtools import * @@ -50,78 +52,238 @@ class MaxResidualLookback(parametertools.Parameter): SPAN = (0, None) -class CorrNQ(parametertools.Parameter): - """Determines whether output correction is applied to the low flow range (NQ)""" +class Active(parametertools.Parameter): + """Flag determining whether the submodel may correct the discharge at all [-]. - NDIM: Final[Literal[0]] = 0 - TYPE: Final = bool - - -class CorrMQ(parametertools.Parameter): - """Determines whether output correction is applied to the mean flow range (MQ)""" + Even when |Active| is |True|, the submodel only corrects the discharge while the + relevant simulated discharge lies within the range defined by |LowerLimit| and + |UpperLimit| (see |Determine_OutputCorrection_V1|).""" NDIM: Final[Literal[0]] = 0 TYPE: Final = bool -class CorrHQ(parametertools.Parameter): - """Determines whether output correction is applied to the high flow range (HQ)""" +class LowerLimit(parametertools.Parameter): + """Lower (inclusive) discharge limit of the submodel's range of responsibility + [m³/s].""" NDIM: Final[Literal[0]] = 0 - TYPE: Final = bool + TYPE: Final = float + SPAN = (0.0, None) + +class UpperLimit(parametertools.Parameter): + """Upper (exclusive) discharge limit of the submodel's range of responsibility + [m³/s]. -class QminQmax(parametertools.Parameter): - """Threshold value [%] for the quotient of the minimum and the maximum measured - flow within the |NqmStationarityWindow| assessment period, below which flow - conditions are considered instationary.""" + Set it to |numpy.inf| to define a range without an upper limit.""" NDIM: Final[Literal[0]] = 0 TYPE: Final = float - SPAN = (0.0, 100.0) - + SPAN = (0.0, None) -class NqmStationarityWindow(parametertools.Parameter): - """Assessment period (timesteps) for determining stationarity - of low and mean flow conditions""" - NDIM: Final[Literal[0]] = 0 - TYPE: Final = int +class StationarityCheck(parametertools.SpecialParameter): + """Configuration of the check of whether the measured discharge behaves in a + stationary way [-]. - -class LinearReductionTime(parametertools.Parameter): - """Number of timesteps for linearly reducing the ARIMA correction to zero once - instationary flow conditions are detected, separately for the NQ range (index 0) - and the MQ range (index 1). + |StationarityCheck| is a special parameter (see |SpecialParameter|). Either + switch the check off by passing |False| or switch it on by passing the length of + the assessment period (`window`, in log entries) and the threshold for the ratio + of the minimum and the maximum measured discharge within this period + (`ratiominmax`), below which |Determine_OutputCorrection_V1| considers the flow + conditions instationary: >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() - >>> control.linearreductiontime(12, 6) - >>> control.linearreductiontime - linearreductiontime(12, 6) + >>> stationaritycheck + stationaritycheck(?) + >>> stationaritycheck.verify() + Traceback (most recent call last): + ... + RuntimeError: For parameter `stationaritycheck` of element `?`, it is still \ +unknown whether the stationarity check is enabled. + + >>> stationaritycheck(False) + >>> stationaritycheck + stationaritycheck(False) + >>> stationaritycheck.verify() + + Passing `window` and `ratiominmax` implicitly enables the check: + + >>> stationaritycheck(window=10, ratiominmax=0.5) + >>> stationaritycheck + stationaritycheck(window=10, ratiominmax=0.5) + >>> stationaritycheck.enabled, stationaritycheck.window + (True, 10) + >>> from hydpy import round_ + >>> round_(stationaritycheck.ratiominmax) + 0.5 + + Passing |True| explicitly is allowed but optional: + + >>> stationaritycheck(True, window=5, ratiominmax=0.8) + >>> stationaritycheck + stationaritycheck(window=5, ratiominmax=0.8) + + An enabled check requires both `window` and `ratiominmax`: + + >>> stationaritycheck(True) + Traceback (most recent call last): + ... + ValueError: For parameter `stationaritycheck` of element `?`, both `window` and \ +`ratiominmax` must be given when enabling the stationarity check. + + >>> stationaritycheck(window=5) + Traceback (most recent call last): + ... + ValueError: For parameter `stationaritycheck` of element `?`, both `window` and \ +`ratiominmax` must be given when enabling the stationarity check. + + A disabled check does not accept `window` or `ratiominmax`: + + >>> stationaritycheck(False, window=5, ratiominmax=0.8) + Traceback (most recent call last): + ... + ValueError: For parameter `stationaritycheck` of element `?`, `window` and \ +`ratiominmax` must not be given when disabling the stationarity check. + + >>> stationaritycheck() + Traceback (most recent call last): + ... + ValueError: For parameter `stationaritycheck` of element `?`, pass either a \ +boolean value or the keyword arguments `window` and `ratiominmax`. + + `window` must be a positive integer, and `ratiominmax` must lie between zero and + one: + + >>> stationaritycheck(window=0, ratiominmax=0.8) + Traceback (most recent call last): + ... + ValueError: For parameter `stationaritycheck` of element `?`, `window` must be a \ +positive integer, but `0` is given. + + >>> stationaritycheck(window=5, ratiominmax=1.5) + Traceback (most recent call last): + ... + ValueError: For parameter `stationaritycheck` of element `?`, `ratiominmax` must \ +lie between zero and one, but `1.5` is given. + + Failed calls leave the previous configuration untouched: + + >>> stationaritycheck + stationaritycheck(window=5, ratiominmax=0.8) """ - NDIM: Final[Literal[1]] = 1 - TYPE: Final = int - SPAN = (0, None) - - def __call__(self, *args, **kwargs) -> None: - self.shape = 2 - super().__call__(*args, **kwargs) - + _config: tuple[bool, int, float] | None + + def __init__(self, subvars: variabletools.SubVariables[Any, Any, Any, Any]) -> None: + super().__init__(subvars) + self._config = None + + def __call__( + self, + value: bool | None = None, + *, + window: int | None = None, + ratiominmax: float | None = None, + ) -> None: + if (value is False) and ((window is not None) or (ratiominmax is not None)): + raise ValueError( + f"For parameter {objecttools.elementphrase(self)}, `window` and " + f"`ratiominmax` must not be given when disabling the stationarity " + f"check." + ) + if value is False: + self._config = (False, 0, 0.0) + return + if (value is None) and (window is None) and (ratiominmax is None): + raise ValueError( + f"For parameter {objecttools.elementphrase(self)}, pass either a " + f"boolean value or the keyword arguments `window` and `ratiominmax`." + ) + if (window is None) or (ratiominmax is None): + raise ValueError( + f"For parameter {objecttools.elementphrase(self)}, both `window` and " + f"`ratiominmax` must be given when enabling the stationarity check." + ) + if (int(window) != window) or (window < 1): + raise ValueError( + f"For parameter {objecttools.elementphrase(self)}, `window` must be a " + f"positive integer, but `{window}` is given." + ) + if not 0.0 <= ratiominmax <= 1.0: + raise ValueError( + f"For parameter {objecttools.elementphrase(self)}, `ratiominmax` must " + f"lie between zero and one, but `{ratiominmax}` is given." + ) + self._config = (True, int(window), float(ratiominmax)) + + def __repr__(self) -> str: + if self._config is None: + return f"{self.name}(?)" + enabled, window, ratiominmax = self._config + if not enabled: + return f"{self.name}(False)" + return ( + f"{self.name}(window={window}, " + f"ratiominmax={objecttools.repr_(ratiominmax)})" + ) + + def verify(self) -> None: + """Raise a |RuntimeError| if the configuration is still unknown.""" + if self._config is None: + raise RuntimeError( + f"For parameter {objecttools.elementphrase(self)}, it is still unknown " + f"whether the stationarity check is enabled." + ) + + @property + def configured(self) -> bool: + """Flag indicating whether the stationarity check has already been + configured. + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> stationaritycheck.configured + False + >>> stationaritycheck(False) + >>> stationaritycheck.configured + True + """ + return self._config is not None + + def _get_config(self) -> tuple[bool, int, float]: + self.verify() + assert self._config is not None + return self._config + + @property + def enabled(self) -> bool: + """Flag indicating whether the stationarity check is enabled.""" + return self._get_config()[0] + + @property + def window(self) -> int: + """The length of the assessment period in log entries (zero if the check is + disabled).""" + return self._get_config()[1] + + @property + def ratiominmax(self) -> float: + """The threshold ratio of the minimum and the maximum measured discharge + (zero if the check is disabled).""" + return self._get_config()[2] -class LimitNQM(parametertools.Parameter): - """Discharge threshold for the transition from NQ to MQ range in m³/s.""" - NDIM: Final[Literal[0]] = 0 - TYPE: Final = float - - -class LimitMQH(parametertools.Parameter): - """Discharge threshold for the transition from MQ to HQ range in m³/s.""" +class LinearReductionTime(parametertools.Parameter): + """Number of timesteps for linearly reducing the ARIMA correction to zero once + the stationarity check (see |StationarityCheck|) detects instationary flow + conditions [-].""" NDIM: Final[Literal[0]] = 0 - TYPE: Final = float + TYPE: Final = int + SPAN = (0, None) class MaxAbsoluteShift(parametertools.Parameter): diff --git a/hydpy/models/statcorr/statcorr_derived.py b/hydpy/models/statcorr/statcorr_derived.py index 087ebb825f..227696e793 100644 --- a/hydpy/models/statcorr/statcorr_derived.py +++ b/hydpy/models/statcorr/statcorr_derived.py @@ -93,3 +93,81 @@ def update(self) -> None: shape = exceptiontools.getattr_(seq, "shape", (None,)) if nmb != shape[-1]: seq.shape = nmb + + +class StationarityWindow(parametertools.Parameter): + """The length of the assessment period of the stationarity check in log entries + (zero if the check is disabled) [-].""" + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = int + SPAN = (0, None) + CONTROLPARAMETERS = (statcorr_control.StationarityCheck,) + + def update(self) -> None: + """Take the assessment period from parameter |StationarityCheck|. + + As long as |StationarityCheck| is not configured, + |StationarityWindow.update| leaves the current value untouched: + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> derived.stationaritywindow.update() + >>> derived.stationaritywindow + stationaritywindow(?) + + >>> stationaritycheck(window=4, ratiominmax=0.5) + >>> derived.stationaritywindow.update() + >>> derived.stationaritywindow + stationaritywindow(4) + + >>> stationaritycheck(False) + >>> derived.stationaritywindow.update() + >>> derived.stationaritywindow + stationaritywindow(0) + """ + stationaritycheck = cast( + statcorr_control.StationarityCheck, + self.subpars.pars.control.stationaritycheck, + ) + if stationaritycheck.configured: + self(stationaritycheck.window) + + +class RatioMinMax(parametertools.Parameter): + """The threshold ratio of the minimum and the maximum measured discharge of the + stationarity check (zero if the check is disabled) [-].""" + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = float + SPAN = (0.0, 1.0) + CONTROLPARAMETERS = (statcorr_control.StationarityCheck,) + + def update(self) -> None: + """Take the threshold ratio from parameter |StationarityCheck|. + + As long as |StationarityCheck| is not configured, |RatioMinMax.update| leaves + the current value untouched: + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> derived.ratiominmax.update() + >>> derived.ratiominmax + ratiominmax(?) + + >>> stationaritycheck(window=4, ratiominmax=0.5) + >>> derived.ratiominmax.update() + >>> derived.ratiominmax + ratiominmax(0.5) + + >>> stationaritycheck(False) + >>> derived.ratiominmax.update() + >>> derived.ratiominmax + ratiominmax(0.0) + """ + stationaritycheck = cast( + statcorr_control.StationarityCheck, + self.subpars.pars.control.stationaritycheck, + ) + if stationaritycheck.configured: + self(stationaritycheck.ratiominmax) diff --git a/hydpy/models/statcorr/statcorr_fluxes.py b/hydpy/models/statcorr/statcorr_fluxes.py index da3e36de14..594e634e62 100644 --- a/hydpy/models/statcorr/statcorr_fluxes.py +++ b/hydpy/models/statcorr/statcorr_fluxes.py @@ -14,3 +14,11 @@ class CorrectedQ(sequencetools.FluxSequence): """Corrected Discharge [m³/s].""" NDIM: Final[Literal[0]] = 0 + + +class IsActive(sequencetools.FluxSequence): + """Flag (1.0: yes, 0.0: no) telling whether the submodel corrected the discharge + in the current simulation step (see |Determine_OutputCorrection_V1|) [-].""" + + NDIM: Final[Literal[0]] = 0 + SPAN = (0.0, 1.0) diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index b490ea0446..138058edd7 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -61,14 +61,14 @@ class Calc_OutputCorr_V1(modeltools.Method): simulations (read in as conditions). 2. Each submodel computes its corrected discharge via |OutputCorrModel_V1.determine_outputcorrection|. - 3. The corrected output of the *last* attached submodel is taken as - |CorrectedQ|. When no submodel is attached, |CorrectedQ| equals - |Inflow|. Since each submodel decides for itself, based on its own - |CorrNQ|, |CorrMQ|, and |CorrHQ| flags, whether the current NQ, MQ, or - HQ flow condition warrants a correction (passing through the current - simulated discharge unchanged otherwise), attaching several submodels - configured for mutually exclusive flow ranges automatically lets only - the one responsible for the current flow condition take effect. + 3. Each submodel decides for itself, based on its own |Active| flag and its + |LowerLimit| and |UpperLimit| parameters, whether it is responsible for + the current discharge (see |OutputCorrModel_V1.is_active|). The + corrected output of the *last* responsible submodel is taken as + |CorrectedQ|. When no submodel is attached or responsible, |CorrectedQ| + equals |Inflow|. Hence, attaching several submodels configured for + mutually exclusive discharge ranges lets only the one responsible for the + current discharge take effect. Examples: @@ -84,25 +84,23 @@ class Calc_OutputCorr_V1(modeltools.Method): With a single attached |statcorr_arima010| submodel, the corrected discharge is the inflow plus the most recent residual (here: - ``3.0 - 2.0 = 1.0``, applied to the new inflow ``2.5``). We enable - correction for all discharge ranges and set |QminQmax| to zero so that - the LARSIM stationarity check never suppresses the correction: - - >>> def configure(submodel): - ... submodel.parameters.control.corrnq(True) - ... submodel.parameters.control.corrmq(True) - ... submodel.parameters.control.corrhq(True) - ... submodel.parameters.control.limitnqm(0.0) - ... submodel.parameters.control.limitmqh(100.0) - ... submodel.parameters.control.evaluationwindow(2) + ``3.0 - 2.0 = 1.0``, applied to the new inflow ``2.5``). By default, we + make the submodel responsible for all discharges and disable the + stationarity check so that it never suppresses the correction: + + >>> from numpy import inf + >>> def configure(submodel, lowerlimit=0.0, upperlimit=inf): + ... submodel.parameters.control.active(True) + ... submodel.parameters.control.lowerlimit(lowerlimit) + ... submodel.parameters.control.upperlimit(upperlimit) + ... submodel.parameters.control.evaluationwindow(1) ... submodel.parameters.control.maxresiduallookback(3) ... submodel.parameters.control.maxabsoluteshift(100.0) ... submodel.parameters.control.maxrelativeshift(1000.0) ... submodel.parameters.control.residualaveragingwindow(0) ... submodel.parameters.control.residualtransitiontime(0) - ... submodel.parameters.control.qminqmax(0.0) - ... submodel.parameters.control.nqmstationaritywindow(2) - ... submodel.parameters.control.linearreductiontime(1, 1) + ... submodel.parameters.control.stationaritycheck(False) + ... submodel.parameters.control.linearreductiontime(1) >>> loggingwindow(2) >>> nmbsubmodels(1) @@ -120,23 +118,52 @@ class Calc_OutputCorr_V1(modeltools.Method): >>> fluxes.correctedq correctedq(3.5) - With two attached submodels of the same type, the second one's output - wins: + We now attach two submodels responsible for different discharge ranges. + The first one covers discharges below 3 m³/s, the second one all + discharges from 3 m³/s upwards: >>> nmbsubmodels(2) >>> with model.add_outputcorrmodel_v1( ... "statcorr_arima010", position=0 ... ) as submodel: - ... configure(submodel) + ... configure(submodel, upperlimit=3.0) >>> with model.add_outputcorrmodel_v1( ... "statcorr_arima010", position=1 ... ) as submodel: - ... configure(submodel) + ... configure(submodel, lowerlimit=3.0) + + For an inflow of 2.5 m³/s, only the first submodel is responsible. + Hence, its corrected output wins, although the second submodel comes + later and returns the uncorrected inflow: + >>> fluxes.inflow = 2.5 >>> inputs.discharge = 4.0 >>> model.calc_outputcorr_v1() >>> fluxes.correctedq correctedq(4.0) + >>> model.outputcorrmodels[0].sequences.fluxes.isactive + isactive(1.0) + >>> model.outputcorrmodels[1].sequences.fluxes.isactive + isactive(0.0) + + For an inflow of 3.5 m³/s, the second submodel takes over: + + >>> fluxes.inflow = 3.5 + >>> inputs.discharge = 3.0 + >>> model.calc_outputcorr_v1() + >>> fluxes.correctedq + correctedq(3.0) + >>> model.outputcorrmodels[0].sequences.fluxes.isactive + isactive(0.0) + >>> model.outputcorrmodels[1].sequences.fluxes.isactive + isactive(1.0) + + If no submodel is responsible, |CorrectedQ| equals |Inflow|: + + >>> model.outputcorrmodels[1].parameters.control.active(False) + >>> model.calc_outputcorr_v1() + >>> fluxes.correctedq + correctedq(3.5) While |Options.simulationmode| equals ``forecast``, |Calc_OutputCorr_V1| ignores the actual value of |Discharge| and passes |numpy.nan| to the @@ -198,8 +225,8 @@ class Calc_OutputCorr_V1(modeltools.Method): Even once the last real observation drops out of the three-step logging window, the persisted residual keeps applying without limit - -- only |ReductionFactor| (via |QminQmax| and |LinearReductionTime|, - both disabled here) could still fade it out: + -- only |ReductionFactor| (via |StationarityCheck| and + |LinearReductionTime|, disabled here) could still fade it out: >>> with pub.options.simulationmode("forecast"): ... model.parameters.update() @@ -245,10 +272,14 @@ def __call__(model: modeltools.Model, /) -> None: statcorrinterfaces.OutputCorrModel_V1, model.outputcorrmodels.submodels[i], ).determine_outputcorrection(bool(der.isforecastmode)) - flu.correctedq = cast( + if cast( statcorrinterfaces.OutputCorrModel_V1, model.outputcorrmodels.submodels[i], - ).get_correctedoutput() + ).is_active(): + flu.correctedq = cast( + statcorrinterfaces.OutputCorrModel_V1, + model.outputcorrmodels.submodels[i], + ).get_correctedoutput() class Pass_CorrectedQ_V1(modeltools.Method): @@ -533,6 +564,27 @@ class Determine_OutputCorrection_V1(modeltools.Method): r"""Calculate the corrected discharge using an ARIMA(0,1,0) — random-walk — error model. + Each submodel is responsible for a specific discharge range only. It corrects + the discharge only while |Active| is |True| and the mean of the + |EvaluationWindow| most recent |LoggedSimulatedDischarge| values + (:math:`\overline{sim}`, stored in |EvaluatedDischarge|) lies within the + range defined by |LowerLimit| and |UpperLimit|: + + :math:`LowerLimit \leq \overline{sim} < UpperLimit` + + |Determine_OutputCorrection_V1| determines :math:`\overline{sim}` only while + |Options.simulationmode| equals `historical`. While it equals `forecast`, it + reuses the value of the most recent `historical` assessment, so the + responsible submodel does not change throughout the forecast horizon. It + checks the condition in each simulation step (so changes of |Active|, + |LowerLimit|, or |UpperLimit| take effect immediately) and stores the outcome + in |IsActive|. Whenever the condition is not met, the corrected discharge + equals the current simulated discharge. However, + |Determine_OutputCorrection_V1| keeps updating all internal states (the + residual, the stationarity assessment, and the |ReductionFactor|) in either + case, so that a submodel taking over responsibility starts with up-to-date + information. + The correction is derived from the most recently available residual (observed minus simulated discharge). While |Options.simulationmode| equals `historical`, the "most recent" residual is taken from the latest @@ -593,39 +645,31 @@ class Determine_OutputCorrection_V1(modeltools.Method): disables this mechanism entirely, relying on the pointwise residual alone, as described above. - Within the NQ and MQ ranges, |Determine_OutputCorrection_V1| additionally - assesses whether the measured discharge behaves in a stationary way. It - takes the quotient of the minimum and the maximum |LoggedObservedDischarge| - value within the most recent |NqmStationarityWindow| log entries. Whenever - this quotient falls below |QminQmax| (given in %), it considers the flow - conditions instationary and linearly reduces |ReductionFactor| (the factor - :math:`f_{red}` in the equation above) towards zero, taking as many steps as - given by the NQ or MQ entry of |LinearReductionTime| (depending on the - current flow range). As soon as the quotient reaches |QminQmax| again (or a - |numpy.nan| value prevents its calculation), |ReductionFactor| jumps back to - ``1.0``, applying the correction unabated again. |ReductionFactor| also - resets to ``1.0`` whenever the current flow condition falls into the HQ - range, for which this stationarity check is not defined. + If enabled via |StationarityCheck|, |Determine_OutputCorrection_V1| + additionally assesses whether the measured discharge behaves in a stationary + way. It takes the ratio of the minimum and the maximum + |LoggedObservedDischarge| value within the most recent |StationarityWindow| + log entries. Whenever this ratio falls below |RatioMinMax|, it considers the + flow conditions instationary and linearly reduces |ReductionFactor| (the + factor :math:`f_{red}` in the equation above) towards zero, taking as many + steps as given by |LinearReductionTime|. As soon as the ratio reaches + |RatioMinMax| again (or a |numpy.nan| value prevents its calculation), + |ReductionFactor| jumps back to ``1.0``, applying the correction unabated + again. With the stationarity check disabled, |ReductionFactor| is always + ``1.0``. |Determine_OutputCorrection_V1| only *reassesses* stationarity (the - quotient-based check described above) and the NQ/MQ/HQ flow condition - while |Options.simulationmode| equals `historical`, remembering their - outcomes in |Stationary| and |FlowCondition|, respectively. While - |Options.simulationmode| equals `forecast`, it reuses both values from the - most recent `historical` assessment instead of recomputing them — + ratio-based check described above) while |Options.simulationmode| equals + `historical`, remembering its outcome in |Stationary|. While + |Options.simulationmode| equals `forecast`, it reuses this value from the + most recent `historical` assessment instead of recomputing it — recomputing would be unreliable anyway, since |LoggedObservedDischarge| keeps receiving |numpy.nan| values throughout the forecast (see - |Calc_OutputCorr_V1|), which the quotient-based check always interprets as - "stationary", and since the currently simulated discharge could - temporarily cross into the HQ range and mask an instationary NQ/MQ - situation identified right before the forecast started. So, once a - `historical` run has flagged conditions as instationary in the NQ or MQ - range, |ReductionFactor| keeps ramping towards zero (or staying at - ``0.0``) for the entire forecast horizon, regardless of how the actually - simulated discharge subsequently develops, instead of jumping back to - ``1.0`` either as soon as the last real observation drops out of the - logging window or whenever the forecasted discharge happens to pass - through the HQ range. + |Calc_OutputCorr_V1|), which the ratio-based check always interprets as + "stationary". So, once a `historical` run has flagged conditions as + instationary, |ReductionFactor| keeps ramping towards zero (or staying at + ``0.0``) for the entire forecast horizon instead of jumping back to ``1.0`` + as soon as the last real observation drops out of the logging window. Likewise, |Determine_OutputCorrection_V1| only reassesses the pointwise residual itself (the |MaxResidualLookback| search described above) while @@ -643,22 +687,23 @@ class Determine_OutputCorrection_V1(modeltools.Method): Three log entries are available, the most recent observation (at position 0) is non-|numpy.nan|, so the correction reproduces the current - observation. The measured discharge is perfectly stationary (the - quotient of its minimum and maximum equals |QminQmax|), so - |ReductionFactor| remains at its initial value of ``1.0``: + observation. The submodel is responsible for all discharges. The + measured discharge is just stationary (the ratio of its minimum and + maximum equals |RatioMinMax|), so |ReductionFactor| remains at its + initial value of ``1.0``: >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() + >>> from numpy import inf, nan >>> derived.nmblogentries(3) >>> control.evaluationwindow(3) - >>> control.corrnq(True) - >>> control.corrmq(True) - >>> control.corrhq(True) - >>> control.limitnqm(3.0) - >>> control.limitmqh(5.0) - >>> control.qminqmax(50.0) - >>> control.nqmstationaritywindow(3) - >>> control.linearreductiontime(2, 2) + >>> control.active(True) + >>> control.lowerlimit(0.0) + >>> control.upperlimit(inf) + >>> control.stationaritycheck(window=3, ratiominmax=0.5) + >>> derived.stationaritywindow.update() + >>> derived.ratiominmax.update() + >>> control.linearreductiontime(2) >>> control.maxresiduallookback(3) >>> control.maxabsoluteshift(100.0) >>> control.maxrelativeshift(1000.0) @@ -671,26 +716,50 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> logs.loggedsimulateddischarge = 5.0, 3.0, 2.0 >>> logs.loggedobserveddischarge = 6.0, 4.0, 3.0 >>> model.determine_outputcorrection_v1(False) + >>> fluxes.isactive + isactive(1.0) >>> fluxes.correctedq correctedq(6.0) >>> states.reductionfactor reductionfactor(1.0) - Disabling correction for the MQ range returns the uncorrected simulated value: + The mean simulated discharge (``10/3`` m³/s) is not below an + |UpperLimit| of 3 m³/s, so the submodel is not responsible and returns + the uncorrected simulated value: - >>> control.corrmq(False) + >>> control.upperlimit(3.0) >>> model.determine_outputcorrection_v1(False) + >>> fluxes.isactive + isactive(0.0) >>> fluxes.correctedq correctedq(5.0) - Simulated discharges averaging 1.5 m³/s place the model in the NQ range. - With NQ correction enabled, the residual (2.0 − 1.0 = 1.0) is applied: + |UpperLimit| is exclusive, while |LowerLimit| is inclusive: - >>> logs.loggedsimulateddischarge = 1.0, 2.0, 1.5 - >>> logs.loggedobserveddischarge = 2.0, 3.0, 2.5 + >>> logs.loggedsimulateddischarge = 3.0, 3.0, 3.0 + >>> logs.loggedobserveddischarge = 4.0, 4.0, 4.0 >>> model.determine_outputcorrection_v1(False) + >>> fluxes.isactive + isactive(0.0) >>> fluxes.correctedq - correctedq(2.0) + correctedq(3.0) + + >>> control.lowerlimit(3.0) + >>> control.upperlimit(inf) + >>> model.determine_outputcorrection_v1(False) + >>> fluxes.isactive + isactive(1.0) + >>> fluxes.correctedq + correctedq(4.0) + + Setting |Active| to |False| disables the correction completely: + + >>> control.active(False) + >>> model.determine_outputcorrection_v1(False) + >>> fluxes.isactive + isactive(0.0) + >>> fluxes.correctedq + correctedq(3.0) The two most recent observations are missing, so the residual is taken from the third log entry and added to the current simulated discharge. @@ -698,8 +767,8 @@ class Determine_OutputCorrection_V1(modeltools.Method): |Determine_OutputCorrection_V1| assumes stationary conditions and leaves |ReductionFactor| untouched: - >>> from numpy import nan - >>> control.corrmq(True) + >>> control.active(True) + >>> control.lowerlimit(0.0) >>> logs.loggedsimulateddischarge = 5.0, 3.0, 2.0 >>> logs.loggedobserveddischarge = nan, nan, 3.0 >>> model.determine_outputcorrection_v1(False) @@ -713,14 +782,16 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> fluxes.correctedq correctedq(5.0) - Sustained instationary conditions in the NQ range (the quotient of the - minimum and the maximum observed discharge, ``0.5 / 5.0 = 10 %``, falls - well below |QminQmax|) linearly reduce |ReductionFactor| to zero within - the two steps given by the NQ entry of |LinearReductionTime|: + Sustained instationary conditions (the ratio of the minimum and the + maximum observed discharge, ``0.5 / 5.0 = 0.1``, falls well below + |RatioMinMax|) linearly reduce |ReductionFactor| to zero within the two + steps given by |LinearReductionTime|: >>> logs.loggedsimulateddischarge = 1.0, 1.0, 1.0 >>> logs.loggedobserveddischarge = 0.5, 5.0, 5.0 >>> model.determine_outputcorrection_v1(False) + >>> states.stationary + stationary(0.0) >>> states.reductionfactor reductionfactor(0.5) >>> fluxes.correctedq @@ -732,23 +803,26 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> fluxes.correctedq correctedq(1.0) - The stationarity check does not apply to the HQ range, so switching to - high flow conditions resets |ReductionFactor| to ``1.0`` regardless of - the (still instationary) measured discharge: + Disabling the stationarity check resets |ReductionFactor| to ``1.0`` + regardless of the (still instationary) measured discharge: - >>> logs.loggedsimulateddischarge = 6.0, 6.0, 6.0 - >>> logs.loggedobserveddischarge = 7.0, 5.0, 5.0 + >>> control.stationaritycheck(False) + >>> derived.stationaritywindow.update() + >>> derived.ratiominmax.update() >>> model.determine_outputcorrection_v1(False) >>> states.reductionfactor reductionfactor(1.0) >>> fluxes.correctedq - correctedq(7.0) + correctedq(0.5) - Once the measured discharge becomes stationary again (quotient - ``4.0 / 5.0 = 80 %``, at or above |QminQmax|), |ReductionFactor| jumps + Once the measured discharge becomes stationary again (ratio + ``4.0 / 5.0 = 0.8``, at or above |RatioMinMax|), |ReductionFactor| jumps back to ``1.0`` immediately, applying the correction unabated: - >>> logs.loggedsimulateddischarge = 1.0, 1.0, 1.0 + >>> control.stationaritycheck(window=3, ratiominmax=0.5) + >>> derived.stationaritywindow.update() + >>> derived.ratiominmax.update() + >>> states.reductionfactor(0.0) >>> logs.loggedobserveddischarge = 4.0, 5.0, 5.0 >>> model.determine_outputcorrection_v1(False) >>> states.reductionfactor @@ -756,10 +830,10 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> fluxes.correctedq correctedq(4.0) - Setting the NQ entry of |LinearReductionTime| to zero reduces - |ReductionFactor| to zero immediately once instationary conditions occur: + Setting |LinearReductionTime| to zero reduces |ReductionFactor| to zero + immediately once instationary conditions occur: - >>> control.linearreductiontime(0, 2) + >>> control.linearreductiontime(0) >>> logs.loggedobserveddischarge = 0.5, 5.0, 5.0 >>> model.determine_outputcorrection_v1(False) >>> states.reductionfactor @@ -771,7 +845,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): call argument is |False|) start a ramp towards zero (here, with |LinearReductionTime| reset to two steps): - >>> control.linearreductiontime(2, 2) + >>> control.linearreductiontime(2) >>> states.reductionfactor(1.0) >>> logs.loggedsimulateddischarge = 1.0, 1.0, 1.0 >>> logs.loggedobserveddischarge = 0.5, 5.0, 5.0 @@ -806,33 +880,39 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> fluxes.correctedq correctedq(1.0) - Not only |Stationary| but also the flow condition itself (NQ, MQ, or - HQ, persisted in |FlowCondition|) is frozen at its most recent - `historical` assessment (here, NQ) and is not reassessed while - forecasting. So even though the currently simulated discharge would - classify as HQ now (which used to reset |ReductionFactor| to ``1.0`` - immediately, since the stationarity check does not apply to the HQ - range), the frozen NQ classification keeps applying, and the ramp - (already at its floor of ``0.0``) is left untouched: + The same holds for the mean simulated discharge deciding on the + submodel's responsibility. It was determined at the last `historical` + call (``1.0`` m³/s) and stays frozen while forecasting. So, even if the + forecasted discharge rises above |UpperLimit|, the submodel remains + responsible: + >>> control.upperlimit(5.0) >>> logs.loggedsimulateddischarge = 10.0, 10.0, 10.0 - >>> logs.loggedobserveddischarge = nan, nan, nan >>> model.determine_outputcorrection_v1(True) - >>> states.flowcondition - flowcondition(0.0) - >>> states.reductionfactor - reductionfactor(0.0) + >>> states.evaluateddischarge + evaluateddischarge(1.0) + >>> fluxes.isactive + isactive(1.0) + + Only a `historical` call updates |EvaluatedDischarge|, which then exceeds + |UpperLimit|, so the submodel stops correcting: + + >>> model.determine_outputcorrection_v1(False) + >>> states.evaluateddischarge + evaluateddischarge(10.0) + >>> fluxes.isactive + isactive(0.0) >>> fluxes.correctedq correctedq(10.0) - Enlarging the log beyond |EvaluationWindow| does not change the flow - condition classification, which always relies on the *most recently* + Enlarging the log beyond |EvaluationWindow| does not change the + responsibility assessment, which always relies on the *most recently* logged |LoggedSimulatedDischarge| entries (index ``0`` upwards) and never on the oldest ones sitting near the end of a larger log (which can well still be |numpy.nan|, as is the case for the newly added entries here): - >>> control.linearreductiontime(2, 2) + >>> control.upperlimit(inf) >>> states.reductionfactor(1.0) >>> derived.nmblogentries(5) >>> logs.loggedsimulateddischarge.shape = 5 @@ -840,6 +920,8 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> logs.loggedsimulateddischarge = 1.0, 1.0, 1.0, nan, nan >>> logs.loggedobserveddischarge = 0.5, 5.0, 5.0, nan, nan >>> model.determine_outputcorrection_v1(False) + >>> fluxes.isactive + isactive(1.0) >>> states.stationary stationary(0.0) >>> states.reductionfactor @@ -911,10 +993,10 @@ class Determine_OutputCorrection_V1(modeltools.Method): Setting |ResidualAveragingWindow| to a value greater than zero switches to the mean-value-based residual, blended in linearly over |ResidualTransitionTime| forecast steps. We reset the log to a - short, clean example (four entries) and freeze |FlowCondition|, + short, clean example (four entries) and freeze |EvaluatedDischarge|, |Stationary|, |Residual|, and |ResidualAnchor| directly (instead of - deriving them from a preceding `historical` call) to keep the focus - on the transition mechanism: + deriving them from a preceding `historical` call) to keep the focus on + the transition mechanism: >>> control.maxresiduallookback(4) >>> control.maxabsoluteshift(100.0) @@ -924,7 +1006,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> derived.nmblogentries(4) >>> logs.loggedsimulateddischarge.shape = 4 >>> logs.loggedobserveddischarge.shape = 4 - >>> states.flowcondition(0.0) + >>> states.evaluateddischarge(8.0) >>> states.stationary(1.0) >>> states.reductionfactor(1.0) >>> states.forecaststep(0.0) @@ -969,42 +1051,39 @@ class Determine_OutputCorrection_V1(modeltools.Method): SUBMETHODS = (Calc_AveragedResidual_V1,) CONTROLPARAMETERS = ( - statcorr_control.CorrNQ, - statcorr_control.CorrMQ, - statcorr_control.CorrHQ, - statcorr_control.LimitNQM, - statcorr_control.LimitMQH, + statcorr_control.Active, + statcorr_control.LowerLimit, + statcorr_control.UpperLimit, statcorr_control.EvaluationWindow, statcorr_control.MaxResidualLookback, statcorr_control.MaxAbsoluteShift, statcorr_control.MaxRelativeShift, statcorr_control.ResidualAveragingWindow, statcorr_control.ResidualTransitionTime, - statcorr_control.QminQmax, - statcorr_control.NqmStationarityWindow, statcorr_control.LinearReductionTime, ) - DERIVEDPARAMETERS = (statcorr_derived.NmbLogEntries,) + DERIVEDPARAMETERS = ( + statcorr_derived.NmbLogEntries, + statcorr_derived.StationarityWindow, + statcorr_derived.RatioMinMax, + ) REQUIREDSEQUENCES = ( statcorr_logs.LoggedSimulatedDischarge, statcorr_logs.LoggedObservedDischarge, ) UPDATEDSEQUENCES = ( + statcorr_states.EvaluatedDischarge, statcorr_states.ReductionFactor, statcorr_states.Stationary, - statcorr_states.FlowCondition, statcorr_states.ForecastStep, statcorr_states.AveragedResidual, statcorr_states.Residual, statcorr_states.ResidualAnchor, ) - RESULTSEQUENCES = (statcorr_fluxes.CorrectedQ,) + RESULTSEQUENCES = (statcorr_fluxes.IsActive, statcorr_fluxes.CorrectedQ) @staticmethod def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: - # pylint: disable=too-many-branches - # (I know this method is much too complex but I do not see a good way to - # refactor it) con = model.parameters.control.fastaccess der = model.parameters.derived.fastaccess flu = model.sequences.fluxes.fastaccess @@ -1013,32 +1092,15 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: assert der.nmblogentries >= con.evaluationwindow - flow_condition: int - if isforecastmode: - flow_condition = int(sta.flowcondition) - else: + if not isforecastmode: mean_simulated: float = 0.0 for idx in range(con.evaluationwindow): mean_simulated = mean_simulated + log.loggedsimulateddischarge[idx] - mean_simulated = mean_simulated / con.evaluationwindow - - if mean_simulated < con.limitnqm: - flow_condition = 0 - elif mean_simulated < con.limitmqh: - flow_condition = 1 - else: - flow_condition = 2 - sta.flowcondition = float(flow_condition) - - # pylint: disable=too-many-boolean-expressions - if ( - (flow_condition == 0 and con.corrnq is False) - or (flow_condition == 1 and con.corrmq is False) - or (flow_condition == 2 and con.corrhq is False) - ): - flu.correctedq = log.loggedsimulateddischarge[0] - return - # pylint: enable=too-many-boolean-expressions + sta.evaluateddischarge = mean_simulated / con.evaluationwindow + if con.active and (con.lowerlimit <= sta.evaluateddischarge < con.upperlimit): + flu.isactive = 1.0 + else: + flu.isactive = 0.0 residual: float sim_anchor: float @@ -1056,11 +1118,11 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: sta.residual = residual sta.residualanchor = sim_anchor - if flow_condition == 2: + if der.stationaritywindow <= 0: sta.reductionfactor = 1.0 else: if not isforecastmode: - nmb = min(der.nmblogentries, con.nqmstationaritywindow) + nmb = min(der.nmblogentries, der.stationaritywindow) stationary = True has_nan = False qmin: float = modelutils.inf @@ -1073,24 +1135,27 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: qmin = min(qmin, value) qmax = max(qmax, value) if not has_nan and qmax > 0.0: - stationary = (qmin / qmax) * 100.0 >= con.qminqmax + stationary = qmin / qmax >= der.ratiominmax sta.stationary = 1.0 if stationary else 0.0 if sta.stationary: sta.reductionfactor = 1.0 + elif con.linearreductiontime <= 0: + sta.reductionfactor = 0.0 else: - idx_regime = 0 if flow_condition == 0 else 1 - reductiontime = con.linearreductiontime[idx_regime] - if reductiontime <= 0: - sta.reductionfactor = 0.0 - else: - sta.reductionfactor = max( - 0.0, sta.reductionfactor - 1.0 / reductiontime - ) + sta.reductionfactor = max( + 0.0, sta.reductionfactor - 1.0 / con.linearreductiontime + ) forecast_step: float = sta.forecaststep if isforecastmode else 0.0 sta.forecaststep = (forecast_step + 1.0) if isforecastmode else 0.0 model.calc_averagedresidual_v1(forecast_step, residual) + + forecast_value: float = log.loggedsimulateddischarge[0] + if flu.isactive == 0.0: + flu.correctedq = forecast_value + return + effective_residual: float = ( residual if con.residualaveragingwindow <= 0 @@ -1102,8 +1167,6 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: ) * (sta.averagedresidual - residual) ) - - forecast_value: float = log.loggedsimulateddischarge[0] damped_residual: float = effective_residual * sta.reductionfactor max_fraction: float = con.maxrelativeshift / 100.0 shift: float = ( @@ -1115,6 +1178,28 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: flu.correctedq = forecast_value + shift +class Is_Active_V1(modeltools.Method): + """Tell whether the submodel corrected the discharge during the most recent call + of |Determine_OutputCorrection_V1|. + + Example: + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> fluxes.isactive = 1.0 + >>> assert model.is_active_v1() + >>> fluxes.isactive = 0.0 + >>> assert not model.is_active_v1() + """ + + REQUIREDSEQUENCES = (statcorr_fluxes.IsActive,) + + @staticmethod + def __call__(model: modeltools.Model, /) -> bool: + flu = model.sequences.fluxes.fastaccess + return flu.isactive == 1.0 + + class Get_CorrectedOutput_V1(modeltools.Method): """Return the most recently calculated corrected discharge in m³/s. diff --git a/hydpy/models/statcorr/statcorr_states.py b/hydpy/models/statcorr/statcorr_states.py index 3846541daa..696e279464 100644 --- a/hydpy/models/statcorr/statcorr_states.py +++ b/hydpy/models/statcorr/statcorr_states.py @@ -31,21 +31,20 @@ class Stationary(sequencetools.StateSequence): INIT = 1.0 -class FlowCondition(sequencetools.StateSequence): - """The most recently determined flow condition (0.0: NQ, 1.0: MQ, 2.0: HQ) [-]. - - Like |Stationary|, |statcorr_arima010| only reassesses |FlowCondition| while - |Options.simulationmode| equals `historical`. While it equals `forecast`, - |FlowCondition| keeps the value determined at the most recent `historical` - assessment, so |Determine_OutputCorrection_V1| always relies on the flow - condition observed right before the forecast horizon started rather than on - the (still continuously simulated) current discharge, which could otherwise - let |ReductionFactor| jump back to ``1.0`` whenever the forecasted discharge - happens to pass through the HQ range.""" +class EvaluatedDischarge(sequencetools.StateSequence): + """The mean simulated discharge over the |EvaluationWindow| most recent log + entries, as determined at the last `historical` assessment [m³/s]. + + |Determine_OutputCorrection_V1| compares |EvaluatedDischarge| with |LowerLimit| + and |UpperLimit| to decide whether the submodel is responsible for correcting + the discharge. Like |Stationary|, |statcorr_arima010| only reassesses + |EvaluatedDischarge| while |Options.simulationmode| equals `historical`. + While it equals `forecast`, |EvaluatedDischarge| keeps the value determined + at the most recent `historical` assessment, so the responsible submodel does + not change throughout the whole forecast horizon, regardless of how the + forecasted discharge develops.""" NDIM: Final[Literal[0]] = 0 - SPAN = (0.0, 2.0) - INIT = 2.0 class ForecastStep(sequencetools.StateSequence): @@ -79,7 +78,7 @@ class Residual(sequencetools.StateSequence): from the most recently logged entry with a non-|numpy.nan| observation, searching back at most |MaxResidualLookback| entries) in m³/s. - Like |Stationary| and |FlowCondition|, |statcorr_arima010| only + Like |Stationary|, |statcorr_arima010| only reassesses |Residual| while |Options.simulationmode| equals `historical`. While it equals `forecast`, |Residual| keeps the value determined at the most recent `historical` assessment, so the applied correction persists diff --git a/hydpy/models/statcorr_arima010.py b/hydpy/models/statcorr_arima010.py index df2f695f5e..1b4967a906 100644 --- a/hydpy/models/statcorr_arima010.py +++ b/hydpy/models/statcorr_arima010.py @@ -33,6 +33,11 @@ forecast begins. See |Determine_OutputCorrection_V1| and |Calc_AveragedResidual_V1| for details. +Each |statcorr_arima010| instance is responsible for a specific discharge range +only, defined by |LowerLimit| and |UpperLimit|, and can be switched off completely +via |Active|. Optionally, |StationarityCheck| lets it fade out the correction under +instationary flow conditions. + |statcorr_arima010| serves as a submodel for |statcorr| and complies with the |OutputCorrModel_V1| interface. @@ -44,15 +49,15 @@ >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() - >>> control.corrnq(True) - >>> control.corrmq(True) - >>> control.corrhq(True) - >>> control.limitnqm(3.0) - >>> control.limitmqh(5.0) + >>> from numpy import inf + >>> control.active(True) + >>> control.lowerlimit(0.0) + >>> control.upperlimit(inf) >>> control.evaluationwindow(3) - >>> control.qminqmax(0.0) - >>> control.nqmstationaritywindow(3) - >>> control.linearreductiontime(1, 1) + >>> control.stationaritycheck(False) + >>> derived.stationaritywindow.update() + >>> derived.ratiominmax.update() + >>> control.linearreductiontime(1) >>> control.maxresiduallookback(3) >>> control.maxabsoluteshift(100.0) >>> control.maxrelativeshift(1000.0) @@ -85,14 +90,19 @@ |OutputCorrModel_V1.determine_outputcorrection| computes the corrected discharge from the random-walk residual (here taken from log position 1, since position 0 has no observation) and stores it internally; - |OutputCorrModel_V1.get_correctedoutput| returns the buffered value: + |OutputCorrModel_V1.is_active| confirms the submodel is responsible for the + current discharge, and |OutputCorrModel_V1.get_correctedoutput| returns the + buffered value: >>> model.determine_outputcorrection(False) + >>> assert model.is_active() >>> from hydpy import round_ >>> round_(model.get_correctedoutput()) 6.0 """ +import numpy + from hydpy.core import modeltools from hydpy.exe.modelimports import * from hydpy.interfaces import statcorrinterfaces @@ -119,6 +129,7 @@ class Model(statcorr_model.Sub_OutputCorrModel, statcorrinterfaces.OutputCorrMod statcorr_model.Set_SimulatedDischarge_V1, statcorr_model.Set_ObservedDischarge_V1, statcorr_model.Determine_OutputCorrection_V1, + statcorr_model.Is_Active_V1, statcorr_model.Get_CorrectedOutput_V1, ) ADD_METHODS = (statcorr_model.Calc_AveragedResidual_V1,) @@ -129,12 +140,12 @@ class Model(statcorr_model.Sub_OutputCorrModel, statcorrinterfaces.OutputCorrMod def prepare_nmblogentries(self, nmblogentries: int) -> None: """Allocate the internal log to hold `nmblogentries` discharge values and - initialise |ReductionFactor|, |Stationary|, |FlowCondition|, - |ForecastStep|, |AveragedResidual|, |Residual|, and |ResidualAnchor| - to ``1.0``, ``1.0``, ``2.0``, ``0.0``, ``0.0``, ``0.0``, and ``0.0`` - (no reduction, stationary conditions assumed, HQ flow condition - assumed, no forecast steps elapsed, no mean-value-based or pointwise - residual determined yet). + initialise |EvaluatedDischarge|, |ReductionFactor|, |Stationary|, + |ForecastStep|, |AveragedResidual|, |Residual|, and |ResidualAnchor| to + |numpy.nan|, ``1.0``, ``1.0``, ``0.0``, ``0.0``, ``0.0``, and ``0.0`` + (no mean simulated discharge determined yet, no reduction, stationary + conditions assumed, no forecast steps elapsed, no mean-value-based or + pointwise residual determined yet). >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() @@ -145,12 +156,12 @@ def prepare_nmblogentries(self, nmblogentries: int) -> None: loggedsimulateddischarge(nan, nan, nan, nan) >>> logs.loggedobserveddischarge loggedobserveddischarge(nan, nan, nan, nan) + >>> states.evaluateddischarge + evaluateddischarge(nan) >>> states.reductionfactor reductionfactor(1.0) >>> states.stationary stationary(1.0) - >>> states.flowcondition - flowcondition(2.0) >>> states.forecaststep forecaststep(0.0) >>> states.averagedresidual @@ -163,9 +174,9 @@ def prepare_nmblogentries(self, nmblogentries: int) -> None: self.parameters.derived.nmblogentries(nmblogentries) self.sequences.logs.loggedsimulateddischarge.shape = nmblogentries self.sequences.logs.loggedobserveddischarge.shape = nmblogentries + self.sequences.states.evaluateddischarge(numpy.nan) self.sequences.states.reductionfactor(1.0) self.sequences.states.stationary(1.0) - self.sequences.states.flowcondition(2.0) self.sequences.states.forecaststep(0.0) self.sequences.states.averagedresidual(0.0) self.sequences.states.residual(0.0) diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py index 550c3eeb42..e5e93d26c0 100644 --- a/hydpy/models/statcorr_main.py +++ b/hydpy/models/statcorr_main.py @@ -25,30 +25,29 @@ >>> element.model = model We configure a logging window of three time steps and attach a single - |statcorr_arima010| submodel. Setting |QminQmax| to zero disables the LARSIM - stationarity check (any quotient of the measured discharge's minimum and - maximum is at least zero), so the ARIMA correction always applies unabated: + |statcorr_arima010| submodel, which is responsible for all discharges (its + |EvaluationWindow| of one step means it assesses its responsibility based on the + current simulated discharge only). We disable the stationarity check via + |StationarityCheck|, so the ARIMA correction always applies unabated: + >>> from numpy import inf >>> loggingwindow(3) >>> nmbsubmodels(1) >>> propagate(True) >>> with model.add_outputcorrmodel_v1( ... "statcorr_arima010", position=0 ... ) as submodel: - ... submodel.parameters.control.corrnq(True) - ... submodel.parameters.control.corrmq(True) - ... submodel.parameters.control.corrhq(True) - ... submodel.parameters.control.limitnqm(0.0) - ... submodel.parameters.control.limitmqh(100.0) - ... submodel.parameters.control.evaluationwindow(3) + ... submodel.parameters.control.active(True) + ... submodel.parameters.control.lowerlimit(0.0) + ... submodel.parameters.control.upperlimit(inf) + ... submodel.parameters.control.evaluationwindow(1) ... submodel.parameters.control.maxresiduallookback(3) ... submodel.parameters.control.maxabsoluteshift(100.0) ... submodel.parameters.control.maxrelativeshift(1000.0) ... submodel.parameters.control.residualaveragingwindow(0) ... submodel.parameters.control.residualtransitiontime(0) - ... submodel.parameters.control.qminqmax(0.0) - ... submodel.parameters.control.nqmstationaritywindow(3) - ... submodel.parameters.control.linearreductiontime(1, 1) + ... submodel.parameters.control.stationaritycheck(False) + ... submodel.parameters.control.linearreductiontime(1) >>> test = IntegrationTest(element) From d0f4c18685bb1b8d1eb98228c8dce891d9cfc3b6 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Tue, 27 Oct 2026 14:56:13 +0100 Subject: [PATCH 19/43] Implement VariabilityCheck (LARSIMs rel. SumDeltaQ Check) --- hydpy/models/statcorr/statcorr_control.py | 202 ++++++++++++++++++++- hydpy/models/statcorr/statcorr_derived.py | 80 +++++++++ hydpy/models/statcorr/statcorr_model.py | 209 ++++++++++++++++++++-- hydpy/models/statcorr/statcorr_states.py | 25 +++ hydpy/models/statcorr_arima010.py | 26 ++- hydpy/models/statcorr_main.py | 6 +- 6 files changed, 522 insertions(+), 26 deletions(-) diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index 1088b038fb..73fb0bafef 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -276,7 +276,207 @@ def ratiominmax(self) -> float: return self._get_config()[2] -class LinearReductionTime(parametertools.Parameter): +class VariabilityCheck(parametertools.SpecialParameter): + """Configuration of the check of whether the simulated discharge varies little + enough to base the correction on a long-term mean residual [-]. + + |VariabilityCheck| is a special parameter (see |SpecialParameter|). Either + switch the check off by passing |False| or switch it on by passing the threshold + for the sum of the absolute changes of the simulated discharge within the + |EvaluationWindow| divided by |EvaluatedDischarge| (`maxrelsumdelta`) and the + length of the averaging period (`averagingwindow`, in log entries) for + determining the mean-value-based residual under stationary conditions (see + |Determine_OutputCorrection_V1|): + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> variabilitycheck + variabilitycheck(?) + >>> variabilitycheck.verify() + Traceback (most recent call last): + ... + RuntimeError: For parameter `variabilitycheck` of element `?`, it is still \ +unknown whether the variability check is enabled. + + >>> variabilitycheck(False) + >>> variabilitycheck + variabilitycheck(False) + >>> variabilitycheck.verify() + + Passing `maxrelsumdelta` and `averagingwindow` implicitly enables the check: + + >>> variabilitycheck(maxrelsumdelta=0.2, averagingwindow=24) + >>> variabilitycheck + variabilitycheck(maxrelsumdelta=0.2, averagingwindow=24) + >>> variabilitycheck.enabled, variabilitycheck.averagingwindow + (True, 24) + >>> from hydpy import round_ + >>> round_(variabilitycheck.maxrelsumdelta) + 0.2 + + Passing |True| explicitly is allowed but optional: + + >>> variabilitycheck(True, maxrelsumdelta=0.1, averagingwindow=12) + >>> variabilitycheck + variabilitycheck(maxrelsumdelta=0.1, averagingwindow=12) + + An enabled check requires both `maxrelsumdelta` and `averagingwindow`: + + >>> variabilitycheck(True) + Traceback (most recent call last): + ... + ValueError: For parameter `variabilitycheck` of element `?`, both \ +`maxrelsumdelta` and `averagingwindow` must be given when enabling the variability \ +check. + + >>> variabilitycheck(maxrelsumdelta=0.1) + Traceback (most recent call last): + ... + ValueError: For parameter `variabilitycheck` of element `?`, both \ +`maxrelsumdelta` and `averagingwindow` must be given when enabling the variability \ +check. + + A disabled check does not accept `maxrelsumdelta` or `averagingwindow`: + + >>> variabilitycheck(False, maxrelsumdelta=0.1, averagingwindow=12) + Traceback (most recent call last): + ... + ValueError: For parameter `variabilitycheck` of element `?`, `maxrelsumdelta` \ +and `averagingwindow` must not be given when disabling the variability check. + + >>> variabilitycheck() + Traceback (most recent call last): + ... + ValueError: For parameter `variabilitycheck` of element `?`, pass either a \ +boolean value or the keyword arguments `maxrelsumdelta` and `averagingwindow`. + + `maxrelsumdelta` must not be negative, and `averagingwindow` must be a positive + integer: + + >>> variabilitycheck(maxrelsumdelta=-0.1, averagingwindow=12) + Traceback (most recent call last): + ... + ValueError: For parameter `variabilitycheck` of element `?`, `maxrelsumdelta` \ +must not be negative, but `-0.1` is given. + + >>> variabilitycheck(maxrelsumdelta=0.1, averagingwindow=0) + Traceback (most recent call last): + ... + ValueError: For parameter `variabilitycheck` of element `?`, `averagingwindow` \ +must be a positive integer, but `0` is given. + + Failed calls leave the previous configuration untouched: + + >>> variabilitycheck + variabilitycheck(maxrelsumdelta=0.1, averagingwindow=12) + """ + + _config: tuple[bool, float, int] | None + + def __init__(self, subvars: variabletools.SubVariables[Any, Any, Any, Any]) -> None: + super().__init__(subvars) + self._config = None + + def __call__( + self, + value: bool | None = None, + *, + maxrelsumdelta: float | None = None, + averagingwindow: int | None = None, + ) -> None: + if (value is False) and ( + (maxrelsumdelta is not None) or (averagingwindow is not None) + ): + raise ValueError( + f"For parameter {objecttools.elementphrase(self)}, `maxrelsumdelta` " + f"and `averagingwindow` must not be given when disabling the " + f"variability check." + ) + if value is False: + self._config = (False, 0.0, 0) + return + if (value is None) and (maxrelsumdelta is None) and (averagingwindow is None): + raise ValueError( + f"For parameter {objecttools.elementphrase(self)}, pass either a " + f"boolean value or the keyword arguments `maxrelsumdelta` and " + f"`averagingwindow`." + ) + if (maxrelsumdelta is None) or (averagingwindow is None): + raise ValueError( + f"For parameter {objecttools.elementphrase(self)}, both " + f"`maxrelsumdelta` and `averagingwindow` must be given when enabling " + f"the variability check." + ) + if maxrelsumdelta < 0.0: + raise ValueError( + f"For parameter {objecttools.elementphrase(self)}, `maxrelsumdelta` " + f"must not be negative, but `{maxrelsumdelta}` is given." + ) + if (int(averagingwindow) != averagingwindow) or (averagingwindow < 1): + raise ValueError( + f"For parameter {objecttools.elementphrase(self)}, `averagingwindow` " + f"must be a positive integer, but `{averagingwindow}` is given." + ) + self._config = (True, float(maxrelsumdelta), int(averagingwindow)) + + def __repr__(self) -> str: + if self._config is None: + return f"{self.name}(?)" + enabled, maxrelsumdelta, averagingwindow = self._config + if not enabled: + return f"{self.name}(False)" + return ( + f"{self.name}(maxrelsumdelta={objecttools.repr_(maxrelsumdelta)}, " + f"averagingwindow={averagingwindow})" + ) + + def verify(self) -> None: + """Raise a |RuntimeError| if the configuration is still unknown.""" + if self._config is None: + raise RuntimeError( + f"For parameter {objecttools.elementphrase(self)}, it is still unknown " + f"whether the variability check is enabled." + ) + + @property + def configured(self) -> bool: + """Flag indicating whether the variability check has already been + configured. + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> variabilitycheck.configured + False + >>> variabilitycheck(False) + >>> variabilitycheck.configured + True + """ + return self._config is not None + + def _get_config(self) -> tuple[bool, float, int]: + self.verify() + assert self._config is not None + return self._config + + @property + def enabled(self) -> bool: + """Flag indicating whether the variability check is enabled.""" + return self._get_config()[0] + + @property + def maxrelsumdelta(self) -> float: + """The threshold for the relative sum of the absolute changes of the + simulated discharge (zero if the check is disabled).""" + return self._get_config()[1] + + @property + def averagingwindow(self) -> int: + """The length of the averaging period under stationary conditions in log + entries (zero if the check is disabled).""" + return self._get_config()[2] + + +class ReductionSteps(parametertools.Parameter): """Number of timesteps for linearly reducing the ARIMA correction to zero once the stationarity check (see |StationarityCheck|) detects instationary flow conditions [-].""" diff --git a/hydpy/models/statcorr/statcorr_derived.py b/hydpy/models/statcorr/statcorr_derived.py index 227696e793..e0835831ea 100644 --- a/hydpy/models/statcorr/statcorr_derived.py +++ b/hydpy/models/statcorr/statcorr_derived.py @@ -171,3 +171,83 @@ def update(self) -> None: ) if stationaritycheck.configured: self(stationaritycheck.ratiominmax) + + +class MaxRelSumDelta(parametertools.Parameter): + """The threshold for the sum of the absolute changes of the simulated discharge + within the |EvaluationWindow| divided by |EvaluatedDischarge| of the variability + check (zero if the check is disabled) [-].""" + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = float + SPAN = (0.0, None) + CONTROLPARAMETERS = (statcorr_control.VariabilityCheck,) + + def update(self) -> None: + """Take the threshold from parameter |VariabilityCheck|. + + As long as |VariabilityCheck| is not configured, |MaxRelSumDelta.update| + leaves the current value untouched: + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> derived.maxrelsumdelta.update() + >>> derived.maxrelsumdelta + maxrelsumdelta(?) + + >>> variabilitycheck(maxrelsumdelta=0.2, averagingwindow=24) + >>> derived.maxrelsumdelta.update() + >>> derived.maxrelsumdelta + maxrelsumdelta(0.2) + + >>> variabilitycheck(False) + >>> derived.maxrelsumdelta.update() + >>> derived.maxrelsumdelta + maxrelsumdelta(0.0) + """ + variabilitycheck = cast( + statcorr_control.VariabilityCheck, + self.subpars.pars.control.variabilitycheck, + ) + if variabilitycheck.configured: + self(variabilitycheck.maxrelsumdelta) + + +class StationaryAveragingWindow(parametertools.Parameter): + """The length of the averaging period for determining the mean-value-based + residual under stationary conditions in log entries (zero if the variability + check is disabled) [-].""" + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = int + SPAN = (0, None) + CONTROLPARAMETERS = (statcorr_control.VariabilityCheck,) + + def update(self) -> None: + """Take the averaging period from parameter |VariabilityCheck|. + + As long as |VariabilityCheck| is not configured, + |StationaryAveragingWindow.update| leaves the current value untouched: + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> derived.stationaryaveragingwindow.update() + >>> derived.stationaryaveragingwindow + stationaryaveragingwindow(?) + + >>> variabilitycheck(maxrelsumdelta=0.2, averagingwindow=24) + >>> derived.stationaryaveragingwindow.update() + >>> derived.stationaryaveragingwindow + stationaryaveragingwindow(24) + + >>> variabilitycheck(False) + >>> derived.stationaryaveragingwindow.update() + >>> derived.stationaryaveragingwindow + stationaryaveragingwindow(0) + """ + variabilitycheck = cast( + statcorr_control.VariabilityCheck, + self.subpars.pars.control.variabilitycheck, + ) + if variabilitycheck.configured: + self(variabilitycheck.averagingwindow) diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 138058edd7..7c5d7a8050 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -100,7 +100,7 @@ class Calc_OutputCorr_V1(modeltools.Method): ... submodel.parameters.control.residualaveragingwindow(0) ... submodel.parameters.control.residualtransitiontime(0) ... submodel.parameters.control.stationaritycheck(False) - ... submodel.parameters.control.linearreductiontime(1) + ... submodel.parameters.control.reductionsteps(1) >>> loggingwindow(2) >>> nmbsubmodels(1) @@ -226,7 +226,7 @@ class Calc_OutputCorr_V1(modeltools.Method): Even once the last real observation drops out of the three-step logging window, the persisted residual keeps applying without limit -- only |ReductionFactor| (via |StationarityCheck| and - |LinearReductionTime|, disabled here) could still fade it out: + |ReductionSteps|, disabled here) could still fade it out: >>> with pub.options.simulationmode("forecast"): ... model.parameters.update() @@ -474,13 +474,18 @@ class Calc_AveragedResidual_V1(modeltools.Method): |ResidualAveragingWindow| is zero (mean-value-based correction disabled). When the averaging window contains a |numpy.nan| value, it falls back to the given `fallback` residual instead (usually the pointwise residual - already determined by |Determine_OutputCorrection_V1|). + already determined by |Determine_OutputCorrection_V1|). While + |LowVariability| is ``1.0`` (stationary conditions according to + |VariabilityCheck|), the |StationaryAveragingWindow| replaces the + |ResidualAveragingWindow|. Examples: >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() >>> control.residualaveragingwindow(2) + >>> derived.stationaryaveragingwindow(1) + >>> states.lowvariability(0.0) >>> derived.nmblogentries(3) >>> logs.loggedsimulateddischarge.shape = 3 >>> logs.loggedobserveddischarge.shape = 3 @@ -523,13 +528,29 @@ class Calc_AveragedResidual_V1(modeltools.Method): >>> model.calc_averagedresidual_v1(0.0, -9.0) >>> states.averagedresidual averagedresidual(-9.0) + + Under stationary conditions according to |VariabilityCheck|, the + averaging period covers the single log position ``1`` given by + |StationaryAveragingWindow| (``30.0 - 20.0``), even if + |ResidualAveragingWindow| is zero: + + >>> control.residualaveragingwindow(0) + >>> states.lowvariability(1.0) + >>> logs.loggedobserveddischarge = nan, 30.0, nan + >>> model.calc_averagedresidual_v1(0.0, -9.0) + >>> states.averagedresidual + averagedresidual(10.0) """ CONTROLPARAMETERS = (statcorr_control.ResidualAveragingWindow,) - DERIVEDPARAMETERS = (statcorr_derived.NmbLogEntries,) + DERIVEDPARAMETERS = ( + statcorr_derived.NmbLogEntries, + statcorr_derived.StationaryAveragingWindow, + ) REQUIREDSEQUENCES = ( statcorr_logs.LoggedSimulatedDischarge, statcorr_logs.LoggedObservedDischarge, + statcorr_states.LowVariability, ) UPDATEDSEQUENCES = (statcorr_states.AveragedResidual,) @@ -542,7 +563,10 @@ def __call__( log = model.sequences.logs.fastaccess sta = model.sequences.states.fastaccess - nmb = min(con.residualaveragingwindow, der.nmblogentries - 1) + if sta.lowvariability == 1.0: + nmb = min(der.stationaryaveragingwindow, der.nmblogentries - 1) + else: + nmb = min(con.residualaveragingwindow, der.nmblogentries - 1) if forecast_step != 0.0 or nmb <= 0: return @@ -652,7 +676,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): log entries. Whenever this ratio falls below |RatioMinMax|, it considers the flow conditions instationary and linearly reduces |ReductionFactor| (the factor :math:`f_{red}` in the equation above) towards zero, taking as many - steps as given by |LinearReductionTime|. As soon as the ratio reaches + steps as given by |ReductionSteps|. As soon as the ratio reaches |RatioMinMax| again (or a |numpy.nan| value prevents its calculation), |ReductionFactor| jumps back to ``1.0``, applying the correction unabated again. With the stationarity check disabled, |ReductionFactor| is always @@ -671,6 +695,26 @@ class Determine_OutputCorrection_V1(modeltools.Method): ``0.0``) for the entire forecast horizon instead of jumping back to ``1.0`` as soon as the last real observation drops out of the logging window. + If enabled via |VariabilityCheck|, |Determine_OutputCorrection_V1| + additionally assesses how much the simulated discharge varies. It sums the + absolute changes between successive |LoggedSimulatedDischarge| values within + the |EvaluationWindow| and divides this sum by |EvaluatedDischarge|, storing + the result in |RelSumDelta|. It considers the flow conditions stationary + (|LowVariability| is ``1.0``) if |RelSumDelta| does not exceed + |MaxRelSumDelta| and the stationarity check described above is either + disabled or also detects stationary conditions. Hence, the variability check + never interferes with the linear reduction of the correction. Under + stationary conditions, the mean-value-based residual (see + |Calc_AveragedResidual_V1|) relies on the |StationaryAveragingWindow| instead + of the |ResidualAveragingWindow| (and so applies even if + |ResidualAveragingWindow| is zero), while the transition over + |ResidualTransitionTime| forecast steps remains unchanged. Otherwise + (including the case of a non-positive |EvaluatedDischarge|, for which + |RelSumDelta| is |numpy.nan|), the correction works as described above. + Like |Stationary|, |Determine_OutputCorrection_V1| reassesses |RelSumDelta| + and |LowVariability| only while |Options.simulationmode| equals + `historical`. + Likewise, |Determine_OutputCorrection_V1| only reassesses the pointwise residual itself (the |MaxResidualLookback| search described above) while |Options.simulationmode| equals `historical`, remembering the outcome in @@ -703,7 +747,10 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> control.stationaritycheck(window=3, ratiominmax=0.5) >>> derived.stationaritywindow.update() >>> derived.ratiominmax.update() - >>> control.linearreductiontime(2) + >>> control.variabilitycheck(False) + >>> derived.maxrelsumdelta.update() + >>> derived.stationaryaveragingwindow.update() + >>> control.reductionsteps(2) >>> control.maxresiduallookback(3) >>> control.maxabsoluteshift(100.0) >>> control.maxrelativeshift(1000.0) @@ -785,7 +832,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): Sustained instationary conditions (the ratio of the minimum and the maximum observed discharge, ``0.5 / 5.0 = 0.1``, falls well below |RatioMinMax|) linearly reduce |ReductionFactor| to zero within the two - steps given by |LinearReductionTime|: + steps given by |ReductionSteps|: >>> logs.loggedsimulateddischarge = 1.0, 1.0, 1.0 >>> logs.loggedobserveddischarge = 0.5, 5.0, 5.0 @@ -830,10 +877,10 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> fluxes.correctedq correctedq(4.0) - Setting |LinearReductionTime| to zero reduces |ReductionFactor| to zero + Setting |ReductionSteps| to zero reduces |ReductionFactor| to zero immediately once instationary conditions occur: - >>> control.linearreductiontime(0) + >>> control.reductionsteps(0) >>> logs.loggedobserveddischarge = 0.5, 5.0, 5.0 >>> model.determine_outputcorrection_v1(False) >>> states.reductionfactor @@ -843,9 +890,9 @@ class Determine_OutputCorrection_V1(modeltools.Method): Instationary conditions detected during `historical` mode (the second call argument is |False|) start a ramp towards zero (here, with - |LinearReductionTime| reset to two steps): + |ReductionSteps| reset to two steps): - >>> control.linearreductiontime(2) + >>> control.reductionsteps(2) >>> states.reductionfactor(1.0) >>> logs.loggedsimulateddischarge = 1.0, 1.0, 1.0 >>> logs.loggedobserveddischarge = 0.5, 5.0, 5.0 @@ -1047,6 +1094,111 @@ class Determine_OutputCorrection_V1(modeltools.Method): averagedresidual(2.5) >>> fluxes.correctedq correctedq(14.5) + + Next, we enable the variability check. In the following `historical` + call, the absolute changes of the simulated discharge within the + |EvaluationWindow| sum up to ``2.0``, which is 20 % of their mean value + (``10.0``). So, |RelSumDelta| does not exceed |MaxRelSumDelta|, and + (as the stationarity check also detects stationary conditions) + |LowVariability| becomes ``1.0``: + + >>> control.variabilitycheck(maxrelsumdelta=0.2, averagingwindow=3) + >>> derived.maxrelsumdelta.update() + >>> derived.stationaryaveragingwindow.update() + >>> logs.loggedsimulateddischarge = 9.0, 10.0, 11.0, 10.0 + >>> logs.loggedobserveddischarge = 10.0, 12.0, 14.0, 12.0 + >>> model.determine_outputcorrection_v1(False) + >>> states.stationary + stationary(1.0) + >>> states.relsumdelta + relsumdelta(0.2) + >>> states.lowvariability + lowvariability(1.0) + >>> fluxes.correctedq + correctedq(10.0) + + In the subsequent forecast run, the mean-value-based residual covers the + three log entries given by |StationaryAveragingWindow| (mean observed + ``12.0``, mean simulated ``10.0``) instead of the two given by + |ResidualAveragingWindow|. The transition from the pointwise residual + (``1.0``) works as before: + + >>> logs.loggedsimulateddischarge = 12.0, 9.0, 10.0, 11.0 + >>> logs.loggedobserveddischarge = nan, 10.0, 12.0, 14.0 + >>> model.determine_outputcorrection_v1(True) + >>> states.averagedresidual + averagedresidual(2.0) + >>> fluxes.correctedq + correctedq(13.0) + + >>> logs.loggedsimulateddischarge = 13.0, 12.0, 9.0, 10.0 + >>> logs.loggedobserveddischarge = nan, nan, 10.0, 12.0 + >>> model.determine_outputcorrection_v1(True) + >>> fluxes.correctedq + correctedq(14.5) + + >>> logs.loggedsimulateddischarge = 14.0, 13.0, 12.0, 9.0 + >>> logs.loggedobserveddischarge = nan, nan, nan, 10.0 + >>> model.determine_outputcorrection_v1(True) + >>> states.lowvariability + lowvariability(1.0) + >>> fluxes.correctedq + correctedq(16.0) + + A larger variability (``4.0 / 10.0 = 0.4``) exceeds |MaxRelSumDelta|, so + the next forecast run falls back to the |ResidualAveragingWindow| (mean + observed ``11.0``, mean simulated ``9.0``) instead of using the + |StationaryAveragingWindow| (which would result in a value of ``3.0``): + + >>> logs.loggedsimulateddischarge = 8.0, 10.0, 12.0, 9.0 + >>> logs.loggedobserveddischarge = 10.0, 12.0, 14.0, 12.0 + >>> model.determine_outputcorrection_v1(False) + >>> states.relsumdelta + relsumdelta(0.4) + >>> states.lowvariability + lowvariability(0.0) + >>> logs.loggedsimulateddischarge = 12.0, 8.0, 10.0, 9.0 + >>> logs.loggedobserveddischarge = nan, 10.0, 12.0, 14.0 + >>> model.determine_outputcorrection_v1(True) + >>> states.averagedresidual + averagedresidual(2.0) + + Instationary conditions according to the stationarity check (ratio + ``5.0 / 14.0``, below |RatioMinMax|) prevent the variability check from + detecting stationary conditions, even if |RelSumDelta| does not exceed + |MaxRelSumDelta|: + + >>> logs.loggedsimulateddischarge = 9.0, 10.0, 11.0, 10.0 + >>> logs.loggedobserveddischarge = 5.0, 12.0, 14.0, 12.0 + >>> model.determine_outputcorrection_v1(False) + >>> states.stationary + stationary(0.0) + >>> states.relsumdelta + relsumdelta(0.2) + >>> states.lowvariability + lowvariability(0.0) + + For a non-positive |EvaluatedDischarge|, |RelSumDelta| is undefined, and + |Determine_OutputCorrection_V1| does not consider the flow conditions + stationary: + + >>> logs.loggedsimulateddischarge = 0.0, 0.0, 0.0, 0.0 + >>> logs.loggedobserveddischarge = 1.0, 1.0, 1.0, 1.0 + >>> model.determine_outputcorrection_v1(False) + >>> states.relsumdelta + relsumdelta(nan) + >>> states.lowvariability + lowvariability(0.0) + + Disabling the variability check resets |LowVariability| to ``0.0``: + + >>> states.lowvariability(1.0) + >>> control.variabilitycheck(False) + >>> derived.maxrelsumdelta.update() + >>> derived.stationaryaveragingwindow.update() + >>> model.determine_outputcorrection_v1(True) + >>> states.lowvariability + lowvariability(0.0) """ SUBMETHODS = (Calc_AveragedResidual_V1,) @@ -1060,12 +1212,14 @@ class Determine_OutputCorrection_V1(modeltools.Method): statcorr_control.MaxRelativeShift, statcorr_control.ResidualAveragingWindow, statcorr_control.ResidualTransitionTime, - statcorr_control.LinearReductionTime, + statcorr_control.ReductionSteps, ) DERIVEDPARAMETERS = ( statcorr_derived.NmbLogEntries, statcorr_derived.StationarityWindow, statcorr_derived.RatioMinMax, + statcorr_derived.MaxRelSumDelta, + statcorr_derived.StationaryAveragingWindow, ) REQUIREDSEQUENCES = ( statcorr_logs.LoggedSimulatedDischarge, @@ -1075,6 +1229,8 @@ class Determine_OutputCorrection_V1(modeltools.Method): statcorr_states.EvaluatedDischarge, statcorr_states.ReductionFactor, statcorr_states.Stationary, + statcorr_states.RelSumDelta, + statcorr_states.LowVariability, statcorr_states.ForecastStep, statcorr_states.AveragedResidual, statcorr_states.Residual, @@ -1084,6 +1240,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): @staticmethod def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: + # pylint: disable=too-many-branches con = model.parameters.control.fastaccess der = model.parameters.derived.fastaccess flu = model.sequences.fluxes.fastaccess @@ -1140,12 +1297,32 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: if sta.stationary: sta.reductionfactor = 1.0 - elif con.linearreductiontime <= 0: + elif con.reductionsteps <= 0: sta.reductionfactor = 0.0 else: sta.reductionfactor = max( - 0.0, sta.reductionfactor - 1.0 / con.linearreductiontime + 0.0, sta.reductionfactor - 1.0 / con.reductionsteps + ) + + if der.stationaryaveragingwindow <= 0: + sta.lowvariability = 0.0 + elif not isforecastmode: + sumdelta: float = 0.0 + for idx in range(con.evaluationwindow - 1): + sumdelta = sumdelta + modelutils.fabs( + log.loggedsimulateddischarge[idx] + - log.loggedsimulateddischarge[idx + 1] ) + if sta.evaluateddischarge > 0.0: + sta.relsumdelta = sumdelta / sta.evaluateddischarge + else: + sta.relsumdelta = modelutils.nan + if (der.stationaritywindow <= 0 or sta.stationary == 1.0) and ( + sta.relsumdelta <= der.maxrelsumdelta + ): + sta.lowvariability = 1.0 + else: + sta.lowvariability = 0.0 forecast_step: float = sta.forecaststep if isforecastmode else 0.0 sta.forecaststep = (forecast_step + 1.0) if isforecastmode else 0.0 @@ -1158,7 +1335,7 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: effective_residual: float = ( residual - if con.residualaveragingwindow <= 0 + if con.residualaveragingwindow <= 0 and sta.lowvariability == 0.0 else residual + ( 1.0 diff --git a/hydpy/models/statcorr/statcorr_states.py b/hydpy/models/statcorr/statcorr_states.py index 696e279464..68b1a67723 100644 --- a/hydpy/models/statcorr/statcorr_states.py +++ b/hydpy/models/statcorr/statcorr_states.py @@ -47,6 +47,31 @@ class EvaluatedDischarge(sequencetools.StateSequence): NDIM: Final[Literal[0]] = 0 +class RelSumDelta(sequencetools.StateSequence): + """The sum of the absolute changes of the simulated discharge within the + |EvaluationWindow| divided by |EvaluatedDischarge|, as determined at the last + `historical` assessment [-]. + + Like |Stationary|, |statcorr_arima010| only reassesses |RelSumDelta| while + |Options.simulationmode| equals `historical`.""" + + NDIM: Final[Literal[0]] = 0 + + +class LowVariability(sequencetools.StateSequence): + """Flag (1.0: yes, 0.0: no) telling whether the variability check (see + |VariabilityCheck|) found stationary conditions at the last assessment, so that + the mean-value-based residual relies on the |StationaryAveragingWindow| instead + of the |ResidualAveragingWindow| [-]. + + Like |Stationary|, |statcorr_arima010| only reassesses |LowVariability| while + |Options.simulationmode| equals `historical`.""" + + NDIM: Final[Literal[0]] = 0 + SPAN = (0.0, 1.0) + INIT = 0.0 + + class ForecastStep(sequencetools.StateSequence): """The number of elapsed forecast steps since the start of the current forecast run (``0.0`` on the first forecast step), reset to ``0.0`` diff --git a/hydpy/models/statcorr_arima010.py b/hydpy/models/statcorr_arima010.py index 1b4967a906..8e1ae45730 100644 --- a/hydpy/models/statcorr_arima010.py +++ b/hydpy/models/statcorr_arima010.py @@ -36,7 +36,9 @@ Each |statcorr_arima010| instance is responsible for a specific discharge range only, defined by |LowerLimit| and |UpperLimit|, and can be switched off completely via |Active|. Optionally, |StationarityCheck| lets it fade out the correction under -instationary flow conditions. +instationary flow conditions, and |VariabilityCheck| lets it base the +mean-value-based residual on a separate averaging period under stationary flow +conditions. |statcorr_arima010| serves as a submodel for |statcorr| and complies with the |OutputCorrModel_V1| interface. @@ -57,7 +59,10 @@ >>> control.stationaritycheck(False) >>> derived.stationaritywindow.update() >>> derived.ratiominmax.update() - >>> control.linearreductiontime(1) + >>> control.variabilitycheck(False) + >>> derived.maxrelsumdelta.update() + >>> derived.stationaryaveragingwindow.update() + >>> control.reductionsteps(1) >>> control.maxresiduallookback(3) >>> control.maxabsoluteshift(100.0) >>> control.maxrelativeshift(1000.0) @@ -141,11 +146,12 @@ class Model(statcorr_model.Sub_OutputCorrModel, statcorrinterfaces.OutputCorrMod def prepare_nmblogentries(self, nmblogentries: int) -> None: """Allocate the internal log to hold `nmblogentries` discharge values and initialise |EvaluatedDischarge|, |ReductionFactor|, |Stationary|, - |ForecastStep|, |AveragedResidual|, |Residual|, and |ResidualAnchor| to - |numpy.nan|, ``1.0``, ``1.0``, ``0.0``, ``0.0``, ``0.0``, and ``0.0`` - (no mean simulated discharge determined yet, no reduction, stationary - conditions assumed, no forecast steps elapsed, no mean-value-based or - pointwise residual determined yet). + |RelSumDelta|, |LowVariability|, |ForecastStep|, |AveragedResidual|, + |Residual|, and |ResidualAnchor| to |numpy.nan|, ``1.0``, ``1.0``, + |numpy.nan|, ``0.0``, ``0.0``, ``0.0``, ``0.0``, and ``0.0`` (no mean + simulated discharge determined yet, no reduction, stationary conditions + assumed, no variability determined yet, no forecast steps elapsed, no + mean-value-based or pointwise residual determined yet). >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() @@ -162,6 +168,10 @@ def prepare_nmblogentries(self, nmblogentries: int) -> None: reductionfactor(1.0) >>> states.stationary stationary(1.0) + >>> states.relsumdelta + relsumdelta(nan) + >>> states.lowvariability + lowvariability(0.0) >>> states.forecaststep forecaststep(0.0) >>> states.averagedresidual @@ -177,6 +187,8 @@ def prepare_nmblogentries(self, nmblogentries: int) -> None: self.sequences.states.evaluateddischarge(numpy.nan) self.sequences.states.reductionfactor(1.0) self.sequences.states.stationary(1.0) + self.sequences.states.relsumdelta(numpy.nan) + self.sequences.states.lowvariability(0.0) self.sequences.states.forecaststep(0.0) self.sequences.states.averagedresidual(0.0) self.sequences.states.residual(0.0) diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py index e5e93d26c0..9febea300a 100644 --- a/hydpy/models/statcorr_main.py +++ b/hydpy/models/statcorr_main.py @@ -28,7 +28,8 @@ |statcorr_arima010| submodel, which is responsible for all discharges (its |EvaluationWindow| of one step means it assesses its responsibility based on the current simulated discharge only). We disable the stationarity check via - |StationarityCheck|, so the ARIMA correction always applies unabated: + |StationarityCheck| and the variability check via |VariabilityCheck|, so the + ARIMA correction always applies unabated: >>> from numpy import inf >>> loggingwindow(3) @@ -47,7 +48,8 @@ ... submodel.parameters.control.residualaveragingwindow(0) ... submodel.parameters.control.residualtransitiontime(0) ... submodel.parameters.control.stationaritycheck(False) - ... submodel.parameters.control.linearreductiontime(1) + ... submodel.parameters.control.variabilitycheck(False) + ... submodel.parameters.control.reductionsteps(1) >>> test = IntegrationTest(element) From 4911b35a409055ef1e843b9499f6ae2f263a3b39 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Tue, 27 Oct 2026 15:01:36 +0100 Subject: [PATCH 20/43] Rename MaxResidualLookback to MaxNaNSkip --- hydpy/models/statcorr/statcorr_control.py | 2 +- hydpy/models/statcorr/statcorr_model.py | 22 +++++++++++----------- hydpy/models/statcorr/statcorr_states.py | 2 +- hydpy/models/statcorr_arima010.py | 6 +++--- hydpy/models/statcorr_main.py | 2 +- 5 files changed, 17 insertions(+), 17 deletions(-) diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index 73fb0bafef..a77866c0d1 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -42,7 +42,7 @@ class EvaluationWindow(parametertools.Parameter): TYPE: Final = int -class MaxResidualLookback(parametertools.Parameter): +class MaxNaNSkip(parametertools.Parameter): """The maximum number of log entries to search back for the most recently available residual when the current or recent observed discharge values are missing.""" diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 7c5d7a8050..1e4ae23111 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -94,7 +94,7 @@ class Calc_OutputCorr_V1(modeltools.Method): ... submodel.parameters.control.lowerlimit(lowerlimit) ... submodel.parameters.control.upperlimit(upperlimit) ... submodel.parameters.control.evaluationwindow(1) - ... submodel.parameters.control.maxresiduallookback(3) + ... submodel.parameters.control.maxnanskip(3) ... submodel.parameters.control.maxabsoluteshift(100.0) ... submodel.parameters.control.maxrelativeshift(1000.0) ... submodel.parameters.control.residualaveragingwindow(0) @@ -613,7 +613,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): (observed minus simulated discharge). While |Options.simulationmode| equals `historical`, the "most recent" residual is taken from the latest log entry where the observed discharge is not |numpy.nan|, searching back - at most |MaxResidualLookback| log entries (or the entire log, whichever is + at most |MaxNaNSkip| log entries (or the entire log, whichever is smaller), and remembered in |Residual| (together with the corresponding simulated discharge in |ResidualAnchor|). When no observation is available within that range, both are set to zero, so the corrected @@ -716,7 +716,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): `historical`. Likewise, |Determine_OutputCorrection_V1| only reassesses the pointwise - residual itself (the |MaxResidualLookback| search described above) while + residual itself (the |MaxNaNSkip| search described above) while |Options.simulationmode| equals `historical`, remembering the outcome in |Residual| and |ResidualAnchor|. While it equals `forecast`, it reuses both from the most recent `historical` assessment instead of repeating @@ -751,7 +751,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> derived.maxrelsumdelta.update() >>> derived.stationaryaveragingwindow.update() >>> control.reductionsteps(2) - >>> control.maxresiduallookback(3) + >>> control.maxnanskip(3) >>> control.maxabsoluteshift(100.0) >>> control.maxrelativeshift(1000.0) >>> control.residualaveragingwindow(0) @@ -974,22 +974,22 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> states.reductionfactor reductionfactor(0.5) - Restricting |MaxResidualLookback| to fewer entries than the full log + Restricting |MaxNaNSkip| to fewer entries than the full log makes |Determine_OutputCorrection_V1| stop searching for a valid residual once that limit is reached, applying no correction even though an older, still-logged observation would otherwise be usable: - >>> control.maxresiduallookback(2) + >>> control.maxnanskip(2) >>> logs.loggedsimulateddischarge = 1.0, 1.0, 1.0, nan, nan >>> logs.loggedobserveddischarge = nan, nan, 3.0, nan, nan >>> model.determine_outputcorrection_v1(False) >>> fluxes.correctedq correctedq(1.0) - Enlarging |MaxResidualLookback| to reach that entry again reinstates + Enlarging |MaxNaNSkip| to reach that entry again reinstates the correction: - >>> control.maxresiduallookback(3) + >>> control.maxnanskip(3) >>> model.determine_outputcorrection_v1(False) >>> fluxes.correctedq correctedq(3.0) @@ -1045,7 +1045,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): deriving them from a preceding `historical` call) to keep the focus on the transition mechanism: - >>> control.maxresiduallookback(4) + >>> control.maxnanskip(4) >>> control.maxabsoluteshift(100.0) >>> control.maxrelativeshift(1000.0) >>> control.residualaveragingwindow(2) @@ -1207,7 +1207,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): statcorr_control.LowerLimit, statcorr_control.UpperLimit, statcorr_control.EvaluationWindow, - statcorr_control.MaxResidualLookback, + statcorr_control.MaxNaNSkip, statcorr_control.MaxAbsoluteShift, statcorr_control.MaxRelativeShift, statcorr_control.ResidualAveragingWindow, @@ -1267,7 +1267,7 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: else: residual = 0.0 sim_anchor = 0.0 - for idx in range(min(der.nmblogentries, con.maxresiduallookback)): + for idx in range(min(der.nmblogentries, con.maxnanskip)): if not modelutils.isnan(log.loggedobserveddischarge[idx]): sim_anchor = log.loggedsimulateddischarge[idx] residual = log.loggedobserveddischarge[idx] - sim_anchor diff --git a/hydpy/models/statcorr/statcorr_states.py b/hydpy/models/statcorr/statcorr_states.py index 68b1a67723..1d2d85e220 100644 --- a/hydpy/models/statcorr/statcorr_states.py +++ b/hydpy/models/statcorr/statcorr_states.py @@ -101,7 +101,7 @@ class AveragedResidual(sequencetools.StateSequence): class Residual(sequencetools.StateSequence): """The pointwise ARIMA residual (observed minus simulated discharge, taken from the most recently logged entry with a non-|numpy.nan| observation, - searching back at most |MaxResidualLookback| entries) in m³/s. + searching back at most |MaxNaNSkip| entries) in m³/s. Like |Stationary|, |statcorr_arima010| only reassesses |Residual| while |Options.simulationmode| equals `historical`. diff --git a/hydpy/models/statcorr_arima010.py b/hydpy/models/statcorr_arima010.py index 8e1ae45730..343a4d248b 100644 --- a/hydpy/models/statcorr_arima010.py +++ b/hydpy/models/statcorr_arima010.py @@ -6,7 +6,7 @@ The corrected discharge is derived from the most recently available residual (observed minus simulated discharge). While |Options.simulationmode| equals `historical`, this residual is (re)determined every step by searching back at -most |MaxResidualLookback| log entries for the latest non-|numpy.nan| +most |MaxNaNSkip| log entries for the latest non-|numpy.nan| observation — this is the random-walk persistence of the error whenever the *current* observation is missing. When no observation is available within that range (or the entire log, whichever is smaller), no correction is @@ -15,7 +15,7 @@ against) stays frozen at whatever the most recent `historical` assessment found, so the correction persists throughout the whole forecast horizon (subject only to |ReductionFactor|) instead of fading once that log entry -ages past |MaxResidualLookback|. +ages past |MaxNaNSkip|. How the residual is applied depends on how the current simulated discharge compares to the simulated discharge at the point the residual was determined: @@ -63,7 +63,7 @@ >>> derived.maxrelsumdelta.update() >>> derived.stationaryaveragingwindow.update() >>> control.reductionsteps(1) - >>> control.maxresiduallookback(3) + >>> control.maxnanskip(3) >>> control.maxabsoluteshift(100.0) >>> control.maxrelativeshift(1000.0) >>> control.residualaveragingwindow(0) diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py index 9febea300a..f11354d281 100644 --- a/hydpy/models/statcorr_main.py +++ b/hydpy/models/statcorr_main.py @@ -42,7 +42,7 @@ ... submodel.parameters.control.lowerlimit(0.0) ... submodel.parameters.control.upperlimit(inf) ... submodel.parameters.control.evaluationwindow(1) - ... submodel.parameters.control.maxresiduallookback(3) + ... submodel.parameters.control.maxnanskip(3) ... submodel.parameters.control.maxabsoluteshift(100.0) ... submodel.parameters.control.maxrelativeshift(1000.0) ... submodel.parameters.control.residualaveragingwindow(0) From 22dbcf2d04b80afa2916b7569a50459439e71796 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Tue, 27 Oct 2026 15:08:44 +0100 Subject: [PATCH 21/43] Rename MaxRelativeshift to MaxRelShift, MaxAbsoluteShift to MaxAbsShift and ResidualTransitionTime to TransitionSteps --- hydpy/models/statcorr/statcorr_control.py | 12 +-- hydpy/models/statcorr/statcorr_model.py | 102 +++++++++++----------- hydpy/models/statcorr/statcorr_states.py | 8 +- hydpy/models/statcorr_arima010.py | 16 ++-- hydpy/models/statcorr_main.py | 8 +- 5 files changed, 73 insertions(+), 73 deletions(-) diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index a77866c0d1..db3b0dfbc7 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -486,7 +486,7 @@ class ReductionSteps(parametertools.Parameter): SPAN = (0, None) -class MaxAbsoluteShift(parametertools.Parameter): +class MaxAbsShift(parametertools.Parameter): """The maximum absolute shift (in m³/s) applied when the current forecast discharge exceeds the simulated discharge at the point the residual was determined (see |Determine_OutputCorrection_V1|).""" @@ -496,7 +496,7 @@ class MaxAbsoluteShift(parametertools.Parameter): SPAN = (0.0, None) -class MaxRelativeShift(parametertools.Parameter): +class MaxRelShift(parametertools.Parameter): """The maximum relative shift (in %) applied when the current forecast discharge is at or below the simulated discharge at the point the residual was determined (see |Determine_OutputCorrection_V1|).""" @@ -506,13 +506,13 @@ class MaxRelativeShift(parametertools.Parameter): SPAN = (0.0, None) -class ResidualAveragingWindow(parametertools.Parameter): +class AveragingWindow(parametertools.Parameter): """The length (in log entries) of the averaging period immediately preceding the current forecast run, used to determine the mean-value-based ARIMA residual (see |Determine_OutputCorrection_V1|). Set to zero to disable mean-value-based correction and rely on the single most recent (pointwise) residual only, as |Determine_OutputCorrection_V1| already did - before |ResidualAveragingWindow| and |ResidualTransitionTime| were + before |AveragingWindow| and |TransitionSteps| were introduced.""" NDIM: Final[Literal[0]] = 0 @@ -520,10 +520,10 @@ class ResidualAveragingWindow(parametertools.Parameter): SPAN = (0, None) -class ResidualTransitionTime(parametertools.Parameter): +class TransitionSteps(parametertools.Parameter): """The number of forecast steps over which the applied residual transitions linearly from the single most recent (pointwise) residual to - the mean-value-based residual determined via |ResidualAveragingWindow|, + the mean-value-based residual determined via |AveragingWindow|, avoiding an abrupt jump right at the start of the forecast horizon.""" NDIM: Final[Literal[0]] = 0 diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 1e4ae23111..2287febd53 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -95,10 +95,10 @@ class Calc_OutputCorr_V1(modeltools.Method): ... submodel.parameters.control.upperlimit(upperlimit) ... submodel.parameters.control.evaluationwindow(1) ... submodel.parameters.control.maxnanskip(3) - ... submodel.parameters.control.maxabsoluteshift(100.0) - ... submodel.parameters.control.maxrelativeshift(1000.0) - ... submodel.parameters.control.residualaveragingwindow(0) - ... submodel.parameters.control.residualtransitiontime(0) + ... submodel.parameters.control.maxabsshift(100.0) + ... submodel.parameters.control.maxrelshift(1000.0) + ... submodel.parameters.control.averagingwindow(0) + ... submodel.parameters.control.transitionsteps(0) ... submodel.parameters.control.stationaritycheck(False) ... submodel.parameters.control.reductionsteps(1) @@ -465,25 +465,25 @@ class Calc_AveragedResidual_V1(modeltools.Method): horizon. |Calc_AveragedResidual_V1| averages the |LoggedObservedDischarge| and - |LoggedSimulatedDischarge| entries covering the |ResidualAveragingWindow| + |LoggedSimulatedDischarge| entries covering the |AveragingWindow| log positions immediately preceding the current forecast run (log position ``0`` already holds the current forecast step's own values, so averaging starts at position ``1``) and stores their difference in |AveragedResidual|. It leaves |AveragedResidual| unchanged whenever `forecast_step` is not zero (i.e., beyond the first forecast step) or - |ResidualAveragingWindow| is zero (mean-value-based correction disabled). + |AveragingWindow| is zero (mean-value-based correction disabled). When the averaging window contains a |numpy.nan| value, it falls back to the given `fallback` residual instead (usually the pointwise residual already determined by |Determine_OutputCorrection_V1|). While |LowVariability| is ``1.0`` (stationary conditions according to |VariabilityCheck|), the |StationaryAveragingWindow| replaces the - |ResidualAveragingWindow|. + |AveragingWindow|. Examples: >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() - >>> control.residualaveragingwindow(2) + >>> control.averagingwindow(2) >>> derived.stationaryaveragingwindow(1) >>> states.lowvariability(0.0) >>> derived.nmblogentries(3) @@ -510,11 +510,11 @@ class Calc_AveragedResidual_V1(modeltools.Method): >>> states.averagedresidual averagedresidual(1.0) - Setting |ResidualAveragingWindow| to zero disables mean-value-based + Setting |AveragingWindow| to zero disables mean-value-based correction; |Calc_AveragedResidual_V1| leaves |AveragedResidual| unchanged even on the first forecast step: - >>> control.residualaveragingwindow(0) + >>> control.averagingwindow(0) >>> states.averagedresidual(-9.0) >>> model.calc_averagedresidual_v1(0.0, -9.0) >>> states.averagedresidual @@ -523,7 +523,7 @@ class Calc_AveragedResidual_V1(modeltools.Method): A |numpy.nan| value within the averaging window makes |Calc_AveragedResidual_V1| fall back to the given `fallback` value: - >>> control.residualaveragingwindow(2) + >>> control.averagingwindow(2) >>> logs.loggedobserveddischarge = nan, nan, 50.0 >>> model.calc_averagedresidual_v1(0.0, -9.0) >>> states.averagedresidual @@ -532,9 +532,9 @@ class Calc_AveragedResidual_V1(modeltools.Method): Under stationary conditions according to |VariabilityCheck|, the averaging period covers the single log position ``1`` given by |StationaryAveragingWindow| (``30.0 - 20.0``), even if - |ResidualAveragingWindow| is zero: + |AveragingWindow| is zero: - >>> control.residualaveragingwindow(0) + >>> control.averagingwindow(0) >>> states.lowvariability(1.0) >>> logs.loggedobserveddischarge = nan, 30.0, nan >>> model.calc_averagedresidual_v1(0.0, -9.0) @@ -542,7 +542,7 @@ class Calc_AveragedResidual_V1(modeltools.Method): averagedresidual(10.0) """ - CONTROLPARAMETERS = (statcorr_control.ResidualAveragingWindow,) + CONTROLPARAMETERS = (statcorr_control.AveragingWindow,) DERIVEDPARAMETERS = ( statcorr_derived.NmbLogEntries, statcorr_derived.StationaryAveragingWindow, @@ -566,7 +566,7 @@ def __call__( if sta.lowvariability == 1.0: nmb = min(der.stationaryaveragingwindow, der.nmblogentries - 1) else: - nmb = min(con.residualaveragingwindow, der.nmblogentries - 1) + nmb = min(con.averagingwindow, der.nmblogentries - 1) if forecast_step != 0.0 or nmb <= 0: return @@ -630,19 +630,19 @@ class Determine_OutputCorrection_V1(modeltools.Method): * If :math:`sim_0 > sim_k` (and :math:`sim_k > 0`), |Determine_OutputCorrection_V1| shifts :math:`sim_0` *additively* by the - |ReductionFactor|-damped residual, capped at |MaxAbsoluteShift| (in + |ReductionFactor|-damped residual, capped at |MaxAbsShift| (in m³/s): :math:`q_{corr} = sim_0 + \mathrm{clip}\left((obs_k - sim_k) \cdot - f_{red},\ \pm MaxAbsoluteShift\right)` + f_{red},\ \pm MaxAbsShift\right)` * Otherwise (including :math:`sim_k \leq 0`, for which a relative shift would be undefined), it shifts :math:`sim_0` *multiplicatively* instead, expressing the damped residual as a percentage of :math:`sim_k` and - capping that percentage at |MaxRelativeShift|: + capping that percentage at |MaxRelShift|: :math:`q_{corr} = sim_0 \cdot \left(1 + \mathrm{clip}\left((obs_k - - sim_k) \cdot f_{red} / sim_k,\ \pm MaxRelativeShift / 100\right) + sim_k) \cdot f_{red} / sim_k,\ \pm MaxRelShift / 100\right) \right)` Applying the residual as a percentage rather than a constant offset @@ -650,7 +650,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): forecasted discharge recedes towards zero. The residual (:math:`obs_k - sim_k` above) used in either branch is not - necessarily the pointwise one. Setting |ResidualAveragingWindow| to a + necessarily the pointwise one. Setting |AveragingWindow| to a value greater than zero switches to a mean-value-based residual instead — the difference between the mean observed and the mean simulated discharge over that many log entries immediately preceding the current forecast run @@ -663,8 +663,8 @@ class Determine_OutputCorrection_V1(modeltools.Method): starts every forecast run with the pointwise residual (so the corrected discharge picks up smoothly where the last measurement left off) and then linearly blends it towards the mean-value-based residual over - |ResidualTransitionTime| forecast steps, applying the mean-value-based - residual unabated from then on. Setting |ResidualAveragingWindow| to zero + |TransitionSteps| forecast steps, applying the mean-value-based + residual unabated from then on. Setting |AveragingWindow| to zero (the default behaviour before mean-value-based correction was introduced) disables this mechanism entirely, relying on the pointwise residual alone, as described above. @@ -706,9 +706,9 @@ class Determine_OutputCorrection_V1(modeltools.Method): never interferes with the linear reduction of the correction. Under stationary conditions, the mean-value-based residual (see |Calc_AveragedResidual_V1|) relies on the |StationaryAveragingWindow| instead - of the |ResidualAveragingWindow| (and so applies even if - |ResidualAveragingWindow| is zero), while the transition over - |ResidualTransitionTime| forecast steps remains unchanged. Otherwise + of the |AveragingWindow| (and so applies even if + |AveragingWindow| is zero), while the transition over + |TransitionSteps| forecast steps remains unchanged. Otherwise (including the case of a non-positive |EvaluatedDischarge|, for which |RelSumDelta| is |numpy.nan|), the correction works as described above. Like |Stationary|, |Determine_OutputCorrection_V1| reassesses |RelSumDelta| @@ -752,10 +752,10 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> derived.stationaryaveragingwindow.update() >>> control.reductionsteps(2) >>> control.maxnanskip(3) - >>> control.maxabsoluteshift(100.0) - >>> control.maxrelativeshift(1000.0) - >>> control.residualaveragingwindow(0) - >>> control.residualtransitiontime(0) + >>> control.maxabsshift(100.0) + >>> control.maxrelshift(1000.0) + >>> control.averagingwindow(0) + >>> control.transitionsteps(0) >>> states.reductionfactor(1.0) >>> states.stationary(1.0) >>> logs.loggedsimulateddischarge.shape = 3 @@ -1008,18 +1008,18 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> fluxes.correctedq correctedq(2.4) - Limiting |MaxRelativeShift| caps that percentage before it is + Limiting |MaxRelShift| caps that percentage before it is converted back into an absolute shift: - >>> control.maxrelativeshift(10.0) + >>> control.maxrelshift(10.0) >>> model.determine_outputcorrection_v1(False) >>> fluxes.correctedq correctedq(2.2) - Likewise, |MaxAbsoluteShift| caps the additive shift applied whenever + Likewise, |MaxAbsShift| caps the additive shift applied whenever the forecast value exceeds the anchor value: - >>> control.maxabsoluteshift(1.0) + >>> control.maxabsshift(1.0) >>> logs.loggedsimulateddischarge = 12.0, 10.0, 10.0, nan, nan >>> model.determine_outputcorrection_v1(False) >>> fluxes.correctedq @@ -1030,26 +1030,26 @@ class Determine_OutputCorrection_V1(modeltools.Method): falls back to the additive shift in that case as well, even though the forecast value does not exceed the anchor value: - >>> control.maxabsoluteshift(100.0) + >>> control.maxabsshift(100.0) >>> logs.loggedsimulateddischarge = 0.0, 0.0, 10.0, nan, nan >>> logs.loggedobserveddischarge = nan, 2.0, nan, nan, nan >>> model.determine_outputcorrection_v1(False) >>> fluxes.correctedq correctedq(2.0) - Setting |ResidualAveragingWindow| to a value greater than zero + Setting |AveragingWindow| to a value greater than zero switches to the mean-value-based residual, blended in linearly over - |ResidualTransitionTime| forecast steps. We reset the log to a + |TransitionSteps| forecast steps. We reset the log to a short, clean example (four entries) and freeze |EvaluatedDischarge|, |Stationary|, |Residual|, and |ResidualAnchor| directly (instead of deriving them from a preceding `historical` call) to keep the focus on the transition mechanism: >>> control.maxnanskip(4) - >>> control.maxabsoluteshift(100.0) - >>> control.maxrelativeshift(1000.0) - >>> control.residualaveragingwindow(2) - >>> control.residualtransitiontime(2) + >>> control.maxabsshift(100.0) + >>> control.maxrelshift(1000.0) + >>> control.averagingwindow(2) + >>> control.transitionsteps(2) >>> derived.nmblogentries(4) >>> logs.loggedsimulateddischarge.shape = 4 >>> logs.loggedobserveddischarge.shape = 4 @@ -1120,7 +1120,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): In the subsequent forecast run, the mean-value-based residual covers the three log entries given by |StationaryAveragingWindow| (mean observed ``12.0``, mean simulated ``10.0``) instead of the two given by - |ResidualAveragingWindow|. The transition from the pointwise residual + |AveragingWindow|. The transition from the pointwise residual (``1.0``) works as before: >>> logs.loggedsimulateddischarge = 12.0, 9.0, 10.0, 11.0 @@ -1146,7 +1146,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): correctedq(16.0) A larger variability (``4.0 / 10.0 = 0.4``) exceeds |MaxRelSumDelta|, so - the next forecast run falls back to the |ResidualAveragingWindow| (mean + the next forecast run falls back to the |AveragingWindow| (mean observed ``11.0``, mean simulated ``9.0``) instead of using the |StationaryAveragingWindow| (which would result in a value of ``3.0``): @@ -1208,10 +1208,10 @@ class Determine_OutputCorrection_V1(modeltools.Method): statcorr_control.UpperLimit, statcorr_control.EvaluationWindow, statcorr_control.MaxNaNSkip, - statcorr_control.MaxAbsoluteShift, - statcorr_control.MaxRelativeShift, - statcorr_control.ResidualAveragingWindow, - statcorr_control.ResidualTransitionTime, + statcorr_control.MaxAbsShift, + statcorr_control.MaxRelShift, + statcorr_control.AveragingWindow, + statcorr_control.TransitionSteps, statcorr_control.ReductionSteps, ) DERIVEDPARAMETERS = ( @@ -1335,22 +1335,22 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: effective_residual: float = ( residual - if con.residualaveragingwindow <= 0 and sta.lowvariability == 0.0 + if con.averagingwindow <= 0 and sta.lowvariability == 0.0 else residual + ( 1.0 - if con.residualtransitiontime <= 0 - else min(1.0, forecast_step / con.residualtransitiontime) + if con.transitionsteps <= 0 + else min(1.0, forecast_step / con.transitionsteps) ) * (sta.averagedresidual - residual) ) damped_residual: float = effective_residual * sta.reductionfactor - max_fraction: float = con.maxrelativeshift / 100.0 + max_fraction: float = con.maxrelshift / 100.0 shift: float = ( forecast_value * min(max_fraction, max(-max_fraction, damped_residual / sim_anchor)) if sim_anchor > 0.0 and forecast_value <= sim_anchor - else min(con.maxabsoluteshift, max(-con.maxabsoluteshift, damped_residual)) + else min(con.maxabsshift, max(-con.maxabsshift, damped_residual)) ) flu.correctedq = forecast_value + shift diff --git a/hydpy/models/statcorr/statcorr_states.py b/hydpy/models/statcorr/statcorr_states.py index 1d2d85e220..f6ee6e61d2 100644 --- a/hydpy/models/statcorr/statcorr_states.py +++ b/hydpy/models/statcorr/statcorr_states.py @@ -62,7 +62,7 @@ class LowVariability(sequencetools.StateSequence): """Flag (1.0: yes, 0.0: no) telling whether the variability check (see |VariabilityCheck|) found stationary conditions at the last assessment, so that the mean-value-based residual relies on the |StationaryAveragingWindow| instead - of the |ResidualAveragingWindow| [-]. + of the |AveragingWindow| [-]. Like |Stationary|, |statcorr_arima010| only reassesses |LowVariability| while |Options.simulationmode| equals `historical`.""" @@ -79,8 +79,8 @@ class ForecastStep(sequencetools.StateSequence): |Determine_OutputCorrection_V1| uses |ForecastStep| to linearly blend the applied residual from the single most recent (pointwise) value towards - the mean-value-based residual determined via |ResidualAveragingWindow| - over |ResidualTransitionTime| forecast steps.""" + the mean-value-based residual determined via |AveragingWindow| + over |TransitionSteps| forecast steps.""" NDIM: Final[Literal[0]] = 0 SPAN = (0.0, None) @@ -89,7 +89,7 @@ class ForecastStep(sequencetools.StateSequence): class AveragedResidual(sequencetools.StateSequence): """The mean-value-based ARIMA residual (mean observed minus mean simulated - discharge over the |ResidualAveragingWindow| log entries immediately + discharge over the |AveragingWindow| log entries immediately preceding the current forecast run) in m³/s, determined once at the first forecast step and kept unchanged for the remainder of the forecast horizon.""" diff --git a/hydpy/models/statcorr_arima010.py b/hydpy/models/statcorr_arima010.py index 343a4d248b..44ce9ad9b8 100644 --- a/hydpy/models/statcorr_arima010.py +++ b/hydpy/models/statcorr_arima010.py @@ -20,16 +20,16 @@ How the residual is applied depends on how the current simulated discharge compares to the simulated discharge at the point the residual was determined: if it is higher, the residual is added unchanged (capped at -|MaxAbsoluteShift|); otherwise, it is applied as a percentage of that anchor -value instead (capped at |MaxRelativeShift|), which keeps the correction from +|MaxAbsShift|); otherwise, it is applied as a percentage of that anchor +value instead (capped at |MaxRelShift|), which keeps the correction from overshooting or turning negative while the discharge recedes. See |Determine_OutputCorrection_V1| for the exact formulas. -Setting |ResidualAveragingWindow| to a value greater than zero switches from +Setting |AveragingWindow| to a value greater than zero switches from that pointwise residual to a mean-value-based one (mean observed minus mean simulated discharge over the given number of log entries immediately preceding the current forecast run), blended in linearly over -|ResidualTransitionTime| forecast steps to avoid a jump right where the +|TransitionSteps| forecast steps to avoid a jump right where the forecast begins. See |Determine_OutputCorrection_V1| and |Calc_AveragedResidual_V1| for details. @@ -64,10 +64,10 @@ >>> derived.stationaryaveragingwindow.update() >>> control.reductionsteps(1) >>> control.maxnanskip(3) - >>> control.maxabsoluteshift(100.0) - >>> control.maxrelativeshift(1000.0) - >>> control.residualaveragingwindow(0) - >>> control.residualtransitiontime(0) + >>> control.maxabsshift(100.0) + >>> control.maxrelshift(1000.0) + >>> control.averagingwindow(0) + >>> control.transitionsteps(0) >>> model.prepare_nmblogentries(3) >>> derived.nmblogentries nmblogentries(3) diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py index f11354d281..aa76d4db31 100644 --- a/hydpy/models/statcorr_main.py +++ b/hydpy/models/statcorr_main.py @@ -43,10 +43,10 @@ ... submodel.parameters.control.upperlimit(inf) ... submodel.parameters.control.evaluationwindow(1) ... submodel.parameters.control.maxnanskip(3) - ... submodel.parameters.control.maxabsoluteshift(100.0) - ... submodel.parameters.control.maxrelativeshift(1000.0) - ... submodel.parameters.control.residualaveragingwindow(0) - ... submodel.parameters.control.residualtransitiontime(0) + ... submodel.parameters.control.maxabsshift(100.0) + ... submodel.parameters.control.maxrelshift(1000.0) + ... submodel.parameters.control.averagingwindow(0) + ... submodel.parameters.control.transitionsteps(0) ... submodel.parameters.control.stationaritycheck(False) ... submodel.parameters.control.variabilitycheck(False) ... submodel.parameters.control.reductionsteps(1) From 10785d95d9b1a42e64d083409ab99016bb42def1 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Tue, 27 Oct 2026 20:07:58 +0100 Subject: [PATCH 22/43] Remove Parameter LoggingWindow Add Parameter correctionmode Update docstrings Add docstring to __init__.py --- hydpy/core/optiontools.py | 33 +++-- hydpy/core/sequencetools.py | 4 +- hydpy/interfaces/statcorrinterfaces.py | 6 +- hydpy/models/statcorr/__init__.py | 4 +- hydpy/models/statcorr/statcorr_control.py | 79 ++++++++++-- hydpy/models/statcorr/statcorr_derived.py | 146 ++++++++++++++++------ hydpy/models/statcorr/statcorr_model.py | 142 ++++++++++++--------- hydpy/models/statcorr/statcorr_states.py | 4 + hydpy/models/statcorr_arima010.py | 61 +-------- hydpy/models/statcorr_main.py | 39 +++--- 10 files changed, 314 insertions(+), 204 deletions(-) diff --git a/hydpy/core/optiontools.py b/hydpy/core/optiontools.py index 09588dd2ac..b99a73f2a7 100644 --- a/hydpy/core/optiontools.py +++ b/hydpy/core/optiontools.py @@ -723,19 +723,18 @@ def _check_simulationmode(value: SimulationMode) -> SimulationMode: assert False -class _OptionPropertySimulationMode( +class OptionPropertySimulationMode( OptionPropertyBase[SimulationMode, OptionContextStr[SimulationMode]] ): """Descriptor for defining options of type |SimulationMode|. - *HydPy* currently supports two simulation modes: historical and forecast. - Options based on |OptionPropertySimulationMode| - automatically check if the given string is a supported simulatio mode - and raise errors if not: + *HydPy* currently supports two simulation modes: `historical` and `forecast`. + Options based on |OptionPropertySimulationMode| automatically check if the given + string is a supported simulation mode and raise errors if not: - >>> from hydpy.core.optiontools import _OptionPropertySimulationMode + >>> from hydpy.core.optiontools import OptionPropertySimulationMode >>> class T: - ... v = _OptionPropertySimulationMode("historical", "x") + ... v = OptionPropertySimulationMode("historical", "x") >>> T.v.__doc__ 'x' @@ -907,27 +906,27 @@ class Options: >>> assert pub.options.reprdigits == -1 """, ) - simulationmode = _OptionPropertySimulationMode( + simulationmode = OptionPropertySimulationMode( "historical", """The current simulation mode. - The supported values are "historical" (default) and "forecast". In - "historical" mode, the simulation typically relies on observed data, - whereas "forecast" mode might involve different initialization or - meteorological forcing. - + The supported values are "historical" (default) and "forecast". In + "historical" mode, the simulation typically relies on observed data, whereas + "forecast" mode might involve different initialisation or meteorological + forcing. + >>> from hydpy import pub >>> pub.options.simulationmode 'historical' - + You can switch the mode by assigning one of the valid string identifiers: - + >>> pub.options.simulationmode = "forecast" >>> pub.options.simulationmode 'forecast' - + Resetting the option restores the default "historical" mode: - + >>> del pub.options.simulationmode >>> pub.options.simulationmode 'historical' diff --git a/hydpy/core/sequencetools.py b/hydpy/core/sequencetools.py index c489ceb97f..b435be9562 100644 --- a/hydpy/core/sequencetools.py +++ b/hydpy/core/sequencetools.py @@ -438,8 +438,8 @@ class StandardInputNames(enum.StrEnum): """Capillary rise [mm/T].""" CLEAR_SKY_SOLAR_RADIATION = "clear_sky_solar_radiation" """Clear sky solar radiation [W/m²].""" - DISCHARGE = "Discharge" - """Discharge [m³/s]""" + DISCHARGE = "discharge" + """Discharge [m³/s].""" EVAPOTRANSPIRATION = "evapotranspiration" """Actual evapotranspiration [mm/T].""" GLOBAL_RADIATION = "global_radiation" diff --git a/hydpy/interfaces/statcorrinterfaces.py b/hydpy/interfaces/statcorrinterfaces.py index e44022516b..482c6f5b24 100644 --- a/hydpy/interfaces/statcorrinterfaces.py +++ b/hydpy/interfaces/statcorrinterfaces.py @@ -12,7 +12,8 @@ class OutputCorrModel_V1(modeltools.SubmodelInterface): observed discharge. The main model (|statcorr|) merely passes the current simulated and observed discharge to the submodel once per simulation step; the submodel is responsible for shifting these values into its internal log - and for using the resulting history when calculating the correction. + and for using the resulting history when calculating the correction. It also + determines the required length of its log from its own parameters. The expected call order within one simulation step is: @@ -26,9 +27,6 @@ class OutputCorrModel_V1(modeltools.SubmodelInterface): typeid: ClassVar[Literal[1]] = 1 """Type identifier for |OutputCorrModel_V1| submodels.""" - def prepare_nmblogentries(self, nmblogentries: int) -> None: - """Allocate the internal log to hold `nmblogentries` discharge values.""" - @modeltools.abstractmodelmethod def set_simulateddischarge(self, simulateddischarge: float) -> None: """Pass the current simulated discharge (in m³/s) to the submodel, which diff --git a/hydpy/models/statcorr/__init__.py b/hydpy/models/statcorr/__init__.py index 66298935d3..70cb7a2013 100644 --- a/hydpy/models/statcorr/__init__.py +++ b/hydpy/models/statcorr/__init__.py @@ -1,12 +1,12 @@ """ -The Statcorr model is... +The |statcorr.DOCNAME.long| base model provides features for the statistical +correction of simulated discharge based on observed discharge values. """ from hydpy.exe.modelimports import * from hydpy.models.statcorr import statcorr_control ADDITIONAL_CONTROLPARAMETERS = ( - statcorr_control.LoggingWindow, statcorr_control.NmbSubmodels, statcorr_control.Propagate, ) diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index db3b0dfbc7..c2676b59d1 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -1,18 +1,12 @@ # pylint: disable=missing-module-docstring +from hydpy.core import exceptiontools from hydpy.core import objecttools from hydpy.core import parametertools from hydpy.core import variabletools from hydpy.core.typingtools import * -class LoggingWindow(parametertools.Parameter): - """The length of the time period to be logged.""" - - NDIM: Final[Literal[0]] = 0 - TYPE: Final = int - - class NmbSubmodels(parametertools.Parameter): """The number of output correction submodels [-]. @@ -63,6 +57,77 @@ class Active(parametertools.Parameter): TYPE: Final = bool +class CorrectionMode(parametertools.Parameter): + """The simulation mode(s) in which the submodel may correct the discharge [-]. + + Pass one of the strings `historical`, `forecast`, or `both`, corresponding to + the possible values of |Options.simulationmode|. Internally, |CorrectionMode| + stores them as the integer values 1, 2, and 3: + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> correctionmode + correctionmode(?) + >>> correctionmode("historical") + >>> correctionmode + correctionmode("historical") + >>> correctionmode.value + 1 + >>> correctionmode("forecast") + >>> correctionmode + correctionmode("forecast") + >>> correctionmode.value + 2 + >>> correctionmode("both") + >>> correctionmode + correctionmode("both") + >>> correctionmode.value + 3 + + Other strings are not allowed: + + >>> correctionmode("always") + Traceback (most recent call last): + ... + ValueError: For parameter `correctionmode` of element `?`, the given mode \ +`always` is not among the supported modes `historical`, `forecast`, and `both`. + + Passing the integer values directly is also possible: + + >>> correctionmode(1) + >>> correctionmode + correctionmode("historical") + + Regardless of |CorrectionMode|, the submodel keeps updating its log and states + in both simulation modes (see |Determine_OutputCorrection_V1|). + """ + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = int + SPAN = (1, 3) + + MODES: Final = {"historical": 1, "forecast": 2, "both": 3} + + def __call__(self, *args, **kwargs) -> None: + if (len(args) == 1) and not kwargs and isinstance(args[0], str): + mode = args[0] + if mode not in self.MODES: + raise ValueError( + f"For parameter {objecttools.elementphrase(self)}, the given " + f"mode `{mode}` is not among the supported modes `historical`, " + f"`forecast`, and `both`." + ) + super().__call__(self.MODES[mode]) + else: + super().__call__(*args, **kwargs) + + def __repr__(self) -> str: + for mode, value in self.MODES.items(): + if exceptiontools.getattr_(self, "value", None) == value: + return f'{self.name}("{mode}")' + return super().__repr__() + + class LowerLimit(parametertools.Parameter): """Lower (inclusive) discharge limit of the submodel's range of responsibility [m³/s].""" diff --git a/hydpy/models/statcorr/statcorr_derived.py b/hydpy/models/statcorr/statcorr_derived.py index e0835831ea..6933e695c0 100644 --- a/hydpy/models/statcorr/statcorr_derived.py +++ b/hydpy/models/statcorr/statcorr_derived.py @@ -35,64 +35,134 @@ def update(self) -> None: class NmbLogEntries(parametertools.Parameter): - """The number of log entries required for memorising the data for the - logging window [-].""" + """The number of log entries required for memorising the simulated and observed + discharge values [-].""" NDIM: Final[Literal[0]] = 0 TYPE: Final = int SPAN = (1, None) - CONTROLPARAMETERS = (statcorr_control.LoggingWindow,) + CONTROLPARAMETERS = ( + statcorr_control.EvaluationWindow, + statcorr_control.StationarityCheck, + statcorr_control.VariabilityCheck, + statcorr_control.MaxNaNSkip, + statcorr_control.AveragingWindow, + ) def update(self) -> None: - """Calculate the number of entries and adjust the shape of all relevant log - sequences. + """Calculate the number of required log entries from the submodel's other + parameters and adjust the shape of all log sequences. - The number of the required log entries depends on the - parameter |LoggingWindow| and the simulation step size: + The log must cover the |EvaluationWindow|, the assessment period of the + stationarity check (see |StationarityCheck|), and the |MaxNaNSkip| most + recent entries. The mean-value-based residual (see + |Calc_AveragedResidual_V1|) relies on the |AveragingWindow| (or the averaging + period of the variability check, see |VariabilityCheck|) entries preceding + the current one, which requires one additional entry. + + As long as not all relevant control parameters are defined, + |NmbLogEntries.update| leaves the current value untouched: >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() - >>> from hydpy import pub - >>> from hydpy.core.timetools import Period - >>> pub.timegrids = "2000-01-01", "2000-01-02", "1h" - >>> loggingwindow(24) + >>> evaluationwindow(3) + >>> stationaritycheck(window=4, ratiominmax=0.5) + >>> variabilitycheck(False) + >>> maxnanskip(2) + >>> derived.nmblogentries.update() + >>> derived.nmblogentries + nmblogentries(?) + + >>> averagingwindow(1) + >>> derived.nmblogentries.update() + >>> derived.nmblogentries + nmblogentries(4) + + >>> stationaritycheck(False) + >>> variabilitycheck(maxrelsumdelta=0.2, averagingwindow=5) + >>> derived.nmblogentries.update() + >>> derived.nmblogentries + nmblogentries(6) + + >>> variabilitycheck(False) + >>> maxnanskip(7) >>> derived.nmblogentries.update() >>> derived.nmblogentries - nmblogentries(24) - >>> logs # doctest: +ELLIPSIS - loggedobserveddischarge(nan, nan, nan, nan, nan, nan, nan, nan, nan, - nan, nan, nan, nan, nan, nan, nan, nan, nan, - nan, nan, nan, nan, nan, nan) - loggedsimulateddischarge(nan, nan, nan, nan, nan, nan, nan, nan, nan, - nan, nan, nan, nan, nan, nan, nan, nan, nan, - nan, nan, nan, nan, nan, nan) - - To prevent losing information, updating parameter |NmbLogEntries| resets the - shape of the relevant log sequences only when necessary: + nmblogentries(7) + + >>> maxnanskip(0) + >>> averagingwindow(3) + >>> derived.nmblogentries.update() + >>> derived.nmblogentries + nmblogentries(4) + + Whenever the number of log entries changes, |NmbLogEntries.update| resizes + all log sequences (filling them with |numpy.nan| values) and resets all + state sequences to their initial values, as the latter depend on the logged + data: + + >>> logs + loggedobserveddischarge(nan, nan, nan, nan) + loggedsimulateddischarge(nan, nan, nan, nan) + >>> states + reductionfactor(1.0) + stationary(1.0) + evaluateddischarge(nan) + relsumdelta(nan) + lowvariability(0.0) + forecaststep(0.0) + averagedresidual(0.0) + residual(0.0) + residualanchor(0.0) + + To prevent losing information, it leaves the log and state sequences + untouched as long as the number of log entries does not change: >>> logs.loggedobserveddischarge = 1.0 - >>> derived.nmblogentries(24) - >>> logs # doctest: +ELLIPSIS - loggedobserveddischarge(1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0) - loggedsimulateddischarge(nan, nan, nan, nan, nan, nan, nan, nan, nan, - nan, nan, nan, nan, nan, nan, nan, nan, nan, - nan, nan, nan, nan, nan, nan) - - .. testsetup:: - - >>> del pub.timegrids + >>> states.residual(2.0) + >>> evaluationwindow(2) + >>> derived.nmblogentries.update() + >>> derived.nmblogentries + nmblogentries(4) + >>> logs.loggedobserveddischarge + loggedobserveddischarge(1.0, 1.0, 1.0, 1.0) + >>> states.residual + residual(2.0) """ control = self.subpars.pars.control - - nmb = control.loggingwindow.value + stationaritycheck = cast( + statcorr_control.StationarityCheck, control.stationaritycheck + ) + variabilitycheck = cast( + statcorr_control.VariabilityCheck, control.variabilitycheck + ) + if not ( + stationaritycheck.configured + and variabilitycheck.configured + and exceptiontools.attrready(control.evaluationwindow, "value") + and exceptiontools.attrready(control.maxnanskip, "value") + and exceptiontools.attrready(control.averagingwindow, "value") + ): + return + nmb = max( + control.evaluationwindow.value, + stationaritycheck.window, + control.maxnanskip.value, + control.averagingwindow.value + 1, + variabilitycheck.averagingwindow + 1, + ) self(nmb) - nmb = int(nmb) - for seq in self.subpars.pars.model.sequences.logs: + nmb = int(self.value) + sequences = self.subpars.pars.model.sequences + resized = False + for seq in sequences.logs: shape = exceptiontools.getattr_(seq, "shape", (None,)) if nmb != shape[-1]: seq.shape = nmb + resized = True + if resized: + for state in sequences.states: + state(state.INIT) class StationarityWindow(parametertools.Parameter): diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 2287febd53..1fcd6ad326 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -61,14 +61,14 @@ class Calc_OutputCorr_V1(modeltools.Method): simulations (read in as conditions). 2. Each submodel computes its corrected discharge via |OutputCorrModel_V1.determine_outputcorrection|. - 3. Each submodel decides for itself, based on its own |Active| flag and its - |LowerLimit| and |UpperLimit| parameters, whether it is responsible for - the current discharge (see |OutputCorrModel_V1.is_active|). The - corrected output of the *last* responsible submodel is taken as - |CorrectedQ|. When no submodel is attached or responsible, |CorrectedQ| - equals |Inflow|. Hence, attaching several submodels configured for - mutually exclusive discharge ranges lets only the one responsible for the - current discharge take effect. + 3. Each submodel decides for itself, based on its own |Active| flag, its + |CorrectionMode|, and its |LowerLimit| and |UpperLimit| parameters, + whether it is responsible for the current discharge (see + |OutputCorrModel_V1.is_active|). The corrected output of the *last* + responsible submodel is taken as |CorrectedQ|. When no submodel is + attached or responsible, |CorrectedQ| equals |Inflow|. Hence, attaching + several submodels configured for mutually exclusive discharge ranges lets + only the one responsible for the current discharge take effect. Examples: @@ -91,6 +91,7 @@ class Calc_OutputCorr_V1(modeltools.Method): >>> from numpy import inf >>> def configure(submodel, lowerlimit=0.0, upperlimit=inf): ... submodel.parameters.control.active(True) + ... submodel.parameters.control.correctionmode("both") ... submodel.parameters.control.lowerlimit(lowerlimit) ... submodel.parameters.control.upperlimit(upperlimit) ... submodel.parameters.control.evaluationwindow(1) @@ -100,9 +101,9 @@ class Calc_OutputCorr_V1(modeltools.Method): ... submodel.parameters.control.averagingwindow(0) ... submodel.parameters.control.transitionsteps(0) ... submodel.parameters.control.stationaritycheck(False) + ... submodel.parameters.control.variabilitycheck(False) ... submodel.parameters.control.reductionsteps(1) - >>> loggingwindow(2) >>> nmbsubmodels(1) >>> with model.add_outputcorrmodel_v1( ... "statcorr_arima010", position=0 @@ -182,7 +183,6 @@ class Calc_OutputCorr_V1(modeltools.Method): also needlessly re-run the submodels' attachment/initialisation logic and wipe their logged history: - >>> loggingwindow(3) >>> nmbsubmodels(1) >>> with model.add_outputcorrmodel_v1( ... "statcorr_arima010", position=0 @@ -223,10 +223,10 @@ class Calc_OutputCorr_V1(modeltools.Method): >>> fluxes.correctedq correctedq(4.5) - Even once the last real observation drops out of the three-step - logging window, the persisted residual keeps applying without limit - -- only |ReductionFactor| (via |StationarityCheck| and - |ReductionSteps|, disabled here) could still fade it out: + Even once the last real observation drops out of the submodel's log + (three entries due to |MaxNaNSkip|), the persisted residual keeps + applying without limit -- only |ReductionFactor| (via |StationarityCheck| + and |ReductionSteps|, disabled here) could still fade it out: >>> with pub.options.simulationmode("forecast"): ... model.parameters.update() @@ -322,28 +322,6 @@ def __call__(model: modeltools.Model, /) -> None: out.q = flu.correctedq if con.propagate else flu.inflow -class Get_Discharge_V1(modeltools.Method): - """Get the current measured discharge. - - Example: - - >>> from hydpy.models.statcorr import * - >>> parameterstep() - >>> inputs.discharge = 2.0 - >>> from hydpy import round_ - >>> round_(model.get_discharge_v1()) - 2.0 - """ - - REQUIREDSEQUENCES = (statcorr_inputs.Discharge,) - - @staticmethod - def __call__(model: modeltools.Model, /) -> float: - inp = model.sequences.inputs.fastaccess - - return inp.discharge - - class Model(modeltools.AdHocModel): """|statcorr.DOCNAME.complete|.""" @@ -354,7 +332,7 @@ class Model(modeltools.AdHocModel): OBSERVER_METHODS = () RECEIVER_METHODS = () RUN_METHODS = (Calc_OutputCorr_V1,) - INTERFACE_METHODS = (Get_Discharge_V1,) + INTERFACE_METHODS = () ADD_METHODS = () OUTLET_METHODS = (Pass_CorrectedQ_V1,) SENDER_METHODS = () @@ -366,36 +344,36 @@ class Model(modeltools.AdHocModel): ) @importtools.prepare_submodel( # type: ignore[call-overload] - "outputcorrmodels", - statcorrinterfaces.OutputCorrModel_V1, - statcorrinterfaces.OutputCorrModel_V1.prepare_nmblogentries, - dimensionality=1, + "outputcorrmodels", statcorrinterfaces.OutputCorrModel_V1, dimensionality=1 ) def add_outputcorrmodel_v1( self, outputcorrmodel: statcorrinterfaces.OutputCorrModel_V1, *, - position: int, # pylint: disable=unused-argument - refresh: bool, # pylint: disable=unused-argument + position: int, + refresh: bool, ) -> None: """Initialise the given submodel that follows the |OutputCorrModel_V1| - interface and propagate the main model's |LoggingWindow| to its internal - log allocation. + interface. + + The main model does not need to pass any information to the submodel. In + particular, the submodel determines the length of its log from its own + parameters (see |NmbLogEntries|): >>> from hydpy.models.statcorr import * >>> parameterstep() - >>> loggingwindow(4) >>> nmbsubmodels(1) >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0): - ... pass + ... evaluationwindow(2) + ... stationaritycheck(window=4, ratiominmax=0.5) + ... variabilitycheck(False) + ... maxnanskip(3) + ... averagingwindow(0) >>> model.outputcorrmodels[0].parameters.derived.nmblogentries nmblogentries(4) >>> model.outputcorrmodels[0].sequences.logs.loggedsimulateddischarge loggedsimulateddischarge(nan, nan, nan, nan) """ - nmb = int(self.parameters.control.loggingwindow.value) - outputcorrmodel.parameters.control.loggingwindow(nmb) - outputcorrmodel.prepare_nmblogentries(nmb) class Set_SimulatedDischarge_V1(modeltools.Method): @@ -589,7 +567,8 @@ class Determine_OutputCorrection_V1(modeltools.Method): error model. Each submodel is responsible for a specific discharge range only. It corrects - the discharge only while |Active| is |True| and the mean of the + the discharge only while |Active| is |True|, |CorrectionMode| allows a + correction in the current simulation mode, and the mean of the |EvaluationWindow| most recent |LoggedSimulatedDischarge| values (:math:`\overline{sim}`, stored in |EvaluatedDischarge|) lies within the range defined by |LowerLimit| and |UpperLimit|: @@ -601,13 +580,15 @@ class Determine_OutputCorrection_V1(modeltools.Method): reuses the value of the most recent `historical` assessment, so the responsible submodel does not change throughout the forecast horizon. It checks the condition in each simulation step (so changes of |Active|, - |LowerLimit|, or |UpperLimit| take effect immediately) and stores the outcome - in |IsActive|. Whenever the condition is not met, the corrected discharge - equals the current simulated discharge. However, + |CorrectionMode|, |LowerLimit|, or |UpperLimit| take effect immediately) and + stores the outcome in |IsActive|. Whenever the condition is not met, the + corrected discharge equals the current simulated discharge. However, |Determine_OutputCorrection_V1| keeps updating all internal states (the residual, the stationarity assessment, and the |ReductionFactor|) in either case, so that a submodel taking over responsibility starts with up-to-date - information. + information. This also holds for a submodel that |CorrectionMode| restricts + to the `forecast` mode, which, therefore, relies on the residual and the flow + conditions determined during the preceding `historical` run. The correction is derived from the most recently available residual (observed minus simulated discharge). While |Options.simulationmode| @@ -742,6 +723,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> derived.nmblogentries(3) >>> control.evaluationwindow(3) >>> control.active(True) + >>> control.correctionmode("both") >>> control.lowerlimit(0.0) >>> control.upperlimit(inf) >>> control.stationaritycheck(window=3, ratiominmax=0.5) @@ -808,6 +790,43 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> fluxes.correctedq correctedq(3.0) + |CorrectionMode| restricts the correction to one simulation mode. With + `forecast`, the submodel does not correct the discharge in the `historical` + mode: + + >>> control.active(True) + >>> control.correctionmode("forecast") + >>> model.determine_outputcorrection_v1(False) + >>> fluxes.isactive + isactive(0.0) + >>> fluxes.correctedq + correctedq(3.0) + + With `historical`, it does: + + >>> control.correctionmode("historical") + >>> model.determine_outputcorrection_v1(False) + >>> fluxes.isactive + isactive(1.0) + >>> fluxes.correctedq + correctedq(4.0) + + In the `forecast` mode, it is the other way round: + + >>> model.determine_outputcorrection_v1(True) + >>> fluxes.isactive + isactive(0.0) + >>> fluxes.correctedq + correctedq(3.0) + + >>> control.correctionmode("forecast") + >>> model.determine_outputcorrection_v1(True) + >>> fluxes.isactive + isactive(1.0) + >>> fluxes.correctedq + correctedq(4.0) + >>> control.correctionmode("both") + The two most recent observations are missing, so the residual is taken from the third log entry and added to the current simulated discharge. Missing observations also make it impossible to assess stationarity, so @@ -1204,6 +1223,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): SUBMETHODS = (Calc_AveragedResidual_V1,) CONTROLPARAMETERS = ( statcorr_control.Active, + statcorr_control.CorrectionMode, statcorr_control.LowerLimit, statcorr_control.UpperLimit, statcorr_control.EvaluationWindow, @@ -1254,7 +1274,17 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: for idx in range(con.evaluationwindow): mean_simulated = mean_simulated + log.loggedsimulateddischarge[idx] sta.evaluateddischarge = mean_simulated / con.evaluationwindow - if con.active and (con.lowerlimit <= sta.evaluateddischarge < con.upperlimit): + if con.correctionmode == 3: + modeallowed = True + elif isforecastmode: + modeallowed = con.correctionmode == 2 + else: + modeallowed = con.correctionmode == 1 + if ( + con.active + and modeallowed + and (con.lowerlimit <= sta.evaluateddischarge < con.upperlimit) + ): flu.isactive = 1.0 else: flu.isactive = 0.0 diff --git a/hydpy/models/statcorr/statcorr_states.py b/hydpy/models/statcorr/statcorr_states.py index f6ee6e61d2..153ef51199 100644 --- a/hydpy/models/statcorr/statcorr_states.py +++ b/hydpy/models/statcorr/statcorr_states.py @@ -1,5 +1,7 @@ # pylint: disable=missing-module-docstring +import numpy + from hydpy.core import sequencetools from hydpy.core.typingtools import * @@ -45,6 +47,7 @@ class EvaluatedDischarge(sequencetools.StateSequence): forecasted discharge develops.""" NDIM: Final[Literal[0]] = 0 + INIT = numpy.nan class RelSumDelta(sequencetools.StateSequence): @@ -56,6 +59,7 @@ class RelSumDelta(sequencetools.StateSequence): |Options.simulationmode| equals `historical`.""" NDIM: Final[Literal[0]] = 0 + INIT = numpy.nan class LowVariability(sequencetools.StateSequence): diff --git a/hydpy/models/statcorr_arima010.py b/hydpy/models/statcorr_arima010.py index 44ce9ad9b8..8f4526625a 100644 --- a/hydpy/models/statcorr_arima010.py +++ b/hydpy/models/statcorr_arima010.py @@ -46,13 +46,15 @@ Example workflow ================ - Allocating the internal log resizes both the simulated and the observed - discharge log to the requested number of entries: + |statcorr_arima010| determines the length of its internal log from its + parameters (see |NmbLogEntries|) and resizes both the simulated and the + observed discharge log accordingly: >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() >>> from numpy import inf >>> control.active(True) + >>> control.correctionmode("both") >>> control.lowerlimit(0.0) >>> control.upperlimit(inf) >>> control.evaluationwindow(3) @@ -68,7 +70,7 @@ >>> control.maxrelshift(1000.0) >>> control.averagingwindow(0) >>> control.transitionsteps(0) - >>> model.prepare_nmblogentries(3) + >>> derived.nmblogentries.update() >>> derived.nmblogentries nmblogentries(3) >>> logs.loggedsimulateddischarge @@ -106,8 +108,6 @@ 6.0 """ -import numpy - from hydpy.core import modeltools from hydpy.exe.modelimports import * from hydpy.interfaces import statcorrinterfaces @@ -143,57 +143,6 @@ class Model(statcorr_model.Sub_OutputCorrModel, statcorrinterfaces.OutputCorrMod SUBMODELINTERFACES = () SUBMODELS = () - def prepare_nmblogentries(self, nmblogentries: int) -> None: - """Allocate the internal log to hold `nmblogentries` discharge values and - initialise |EvaluatedDischarge|, |ReductionFactor|, |Stationary|, - |RelSumDelta|, |LowVariability|, |ForecastStep|, |AveragedResidual|, - |Residual|, and |ResidualAnchor| to |numpy.nan|, ``1.0``, ``1.0``, - |numpy.nan|, ``0.0``, ``0.0``, ``0.0``, ``0.0``, and ``0.0`` (no mean - simulated discharge determined yet, no reduction, stationary conditions - assumed, no variability determined yet, no forecast steps elapsed, no - mean-value-based or pointwise residual determined yet). - - >>> from hydpy.models.statcorr_arima010 import * - >>> parameterstep() - >>> model.prepare_nmblogentries(4) - >>> derived.nmblogentries - nmblogentries(4) - >>> logs.loggedsimulateddischarge - loggedsimulateddischarge(nan, nan, nan, nan) - >>> logs.loggedobserveddischarge - loggedobserveddischarge(nan, nan, nan, nan) - >>> states.evaluateddischarge - evaluateddischarge(nan) - >>> states.reductionfactor - reductionfactor(1.0) - >>> states.stationary - stationary(1.0) - >>> states.relsumdelta - relsumdelta(nan) - >>> states.lowvariability - lowvariability(0.0) - >>> states.forecaststep - forecaststep(0.0) - >>> states.averagedresidual - averagedresidual(0.0) - >>> states.residual - residual(0.0) - >>> states.residualanchor - residualanchor(0.0) - """ - self.parameters.derived.nmblogentries(nmblogentries) - self.sequences.logs.loggedsimulateddischarge.shape = nmblogentries - self.sequences.logs.loggedobserveddischarge.shape = nmblogentries - self.sequences.states.evaluateddischarge(numpy.nan) - self.sequences.states.reductionfactor(1.0) - self.sequences.states.stationary(1.0) - self.sequences.states.relsumdelta(numpy.nan) - self.sequences.states.lowvariability(0.0) - self.sequences.states.forecaststep(0.0) - self.sequences.states.averagedresidual(0.0) - self.sequences.states.residual(0.0) - self.sequences.states.residualanchor(0.0) - tester = Tester() cythonizer = Cythonizer() diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py index aa76d4db31..8addfbfc32 100644 --- a/hydpy/models/statcorr_main.py +++ b/hydpy/models/statcorr_main.py @@ -24,21 +24,20 @@ >>> element = Element("element", inlets="inlet", outlets="outlet") >>> element.model = model - We configure a logging window of three time steps and attach a single - |statcorr_arima010| submodel, which is responsible for all discharges (its - |EvaluationWindow| of one step means it assesses its responsibility based on the - current simulated discharge only). We disable the stationarity check via - |StationarityCheck| and the variability check via |VariabilityCheck|, so the - ARIMA correction always applies unabated: + We attach a single |statcorr_arima010| submodel, which is responsible for all + discharges (its |EvaluationWindow| of one step means it assesses its + responsibility based on the current simulated discharge only). We disable the + stationarity check via |StationarityCheck| and the variability check via + |VariabilityCheck|, so the ARIMA correction always applies unabated: >>> from numpy import inf - >>> loggingwindow(3) >>> nmbsubmodels(1) >>> propagate(True) >>> with model.add_outputcorrmodel_v1( ... "statcorr_arima010", position=0 ... ) as submodel: ... submodel.parameters.control.active(True) + ... submodel.parameters.control.correctionmode("both") ... submodel.parameters.control.lowerlimit(0.0) ... submodel.parameters.control.upperlimit(inf) ... submodel.parameters.control.evaluationwindow(1) @@ -64,8 +63,8 @@ During the first two steps the correction is based on the concurrent residual (``0.5``). In the forecast period the model falls back to the most recent - available residual, which stays at ``0.5`` until it drops out of the logging - window on day five, after which no correction is applied: + available residual, which stays at ``0.5`` until it lies more than + |MaxNaNSkip| entries back on day five, after which no correction is applied: .. integration-test:: @@ -89,7 +88,6 @@ from hydpy.models.statcorr import statcorr_model ADDITIONAL_CONTROLPARAMETERS = ( - statcorr_control.LoggingWindow, statcorr_control.NmbSubmodels, statcorr_control.Propagate, ) @@ -108,7 +106,7 @@ class Model(modeltools.AdHocModel): OBSERVER_METHODS = () RECEIVER_METHODS = () RUN_METHODS = (statcorr_model.Calc_OutputCorr_V1,) - INTERFACE_METHODS = (statcorr_model.Get_Discharge_V1,) + INTERFACE_METHODS = () ADD_METHODS = () OUTLET_METHODS = (statcorr_model.Pass_CorrectedQ_V1,) SENDER_METHODS = () @@ -120,24 +118,21 @@ class Model(modeltools.AdHocModel): ) @importtools.prepare_submodel( # type: ignore[call-overload] - "outputcorrmodels", - statcorrinterfaces.OutputCorrModel_V1, - statcorrinterfaces.OutputCorrModel_V1.prepare_nmblogentries, - dimensionality=1, + "outputcorrmodels", statcorrinterfaces.OutputCorrModel_V1, dimensionality=1 ) def add_outputcorrmodel_v1( self, outputcorrmodel: statcorrinterfaces.OutputCorrModel_V1, *, - position: int, # pylint: disable=unused-argument - refresh: bool, # pylint: disable=unused-argument + position: int, + refresh: bool, ) -> None: """Initialise the given submodel that follows the |OutputCorrModel_V1| - interface and propagate the main model's |LoggingWindow| to its internal - log allocation.""" - nmb = int(self.parameters.control.loggingwindow.value) - outputcorrmodel.parameters.control.loggingwindow(nmb) - outputcorrmodel.prepare_nmblogentries(nmb) + interface. + + The submodel determines the length of its log from its own parameters (see + |NmbLogEntries|), so the main model does not need to pass any information. + """ tester = Tester() From 1ef36a9d2961372c690c988f3e5573cf12a29aa5 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Tue, 27 Oct 2026 20:55:47 +0100 Subject: [PATCH 23/43] Rename parameters that referred to discharge --- hydpy/interfaces/statcorrinterfaces.py | 43 +-- hydpy/models/statcorr/statcorr_control.py | 54 ++-- hydpy/models/statcorr/statcorr_derived.py | 20 +- hydpy/models/statcorr/statcorr_logs.py | 8 +- hydpy/models/statcorr/statcorr_model.py | 337 +++++++++++----------- hydpy/models/statcorr/statcorr_states.py | 35 +-- hydpy/models/statcorr_arima010.py | 70 ++--- 7 files changed, 285 insertions(+), 282 deletions(-) diff --git a/hydpy/interfaces/statcorrinterfaces.py b/hydpy/interfaces/statcorrinterfaces.py index 482c6f5b24..48267066b5 100644 --- a/hydpy/interfaces/statcorrinterfaces.py +++ b/hydpy/interfaces/statcorrinterfaces.py @@ -1,24 +1,28 @@ -"""This module defines submodel interfaces for statistical output correction of -discharge forecasts.""" +"""This module defines submodel interfaces for the statistical output correction of +simulated values (for example, discharge forecasts) based on observed values.""" from hydpy.core import modeltools from hydpy.core.typingtools import * class OutputCorrModel_V1(modeltools.SubmodelInterface): - """Simple interface for statistical output correction of discharge forecasts. + """Simple interface for the statistical output correction of simulated values. + + The interface does not prescribe the corrected variable (|statcorr_main|, for + example, corrects discharge). All values passed to and returned by the + submodel share the unit of this variable. Each submodel owns and maintains its own persistent log of simulated and - observed discharge. The main model (|statcorr|) merely passes the current - simulated and observed discharge to the submodel once per simulation step; + observed values. The main model merely passes the current simulated and + observed value to the submodel once per simulation step; the submodel is responsible for shifting these values into its internal log and for using the resulting history when calculating the correction. It also determines the required length of its log from its own parameters. The expected call order within one simulation step is: - 1. |OutputCorrModel_V1.set_simulateddischarge| - 2. |OutputCorrModel_V1.set_observeddischarge| + 1. |OutputCorrModel_V1.set_simulatedvalue| + 2. |OutputCorrModel_V1.set_observedvalue| 3. |OutputCorrModel_V1.determine_outputcorrection| 4. |OutputCorrModel_V1.is_active| 5. |OutputCorrModel_V1.get_correctedoutput| @@ -28,37 +32,36 @@ class OutputCorrModel_V1(modeltools.SubmodelInterface): """Type identifier for |OutputCorrModel_V1| submodels.""" @modeltools.abstractmodelmethod - def set_simulateddischarge(self, simulateddischarge: float) -> None: - """Pass the current simulated discharge (in m³/s) to the submodel, which - appends it to its internal log of simulated discharge.""" + def set_simulatedvalue(self, simulatedvalue: float) -> None: + """Pass the current simulated value to the submodel, which appends it to + its internal log of simulated values.""" @modeltools.abstractmodelmethod - def set_observeddischarge(self, observeddischarge: float) -> None: - """Pass the current observed discharge (in m³/s, or |numpy.nan| when - unavailable) to the submodel, which appends it to its internal log of - observed discharge.""" + def set_observedvalue(self, observedvalue: float) -> None: + """Pass the current observed value (or |numpy.nan| when unavailable) to the + submodel, which appends it to its internal log of observed values.""" @modeltools.abstractmodelmethod def determine_outputcorrection(self, isforecastmode: bool) -> None: - """Calculate the corrected output discharge from the internal logs of - simulated and observed discharge. + """Calculate the corrected output value from the internal logs of + simulated and observed values. The main model passes its current |Options.simulationmode| via `isforecastmode` (|True| for `forecast`, |False| for `historical`) instead of leaving the submodel to inspect the global option itself, because a submodel cannot safely track *changes* of |Options.simulationmode| between simulation steps on its own (there is - no per-step hook comparable to |OutputCorrModel_V1.set_simulateddischarge| + no per-step hook comparable to |OutputCorrModel_V1.set_simulatedvalue| for it, and refreshing a submodel-owned derived parameter via |Model.update_parameters| would also needlessly re-run its submodel attachment/initialisation logic, wiping its logged history).""" @modeltools.abstractmodelmethod def is_active(self) -> bool: - """Tell whether the submodel was responsible for correcting the discharge - during the most recent call of + """Tell whether the submodel was responsible for correcting the simulated + value during the most recent call of |OutputCorrModel_V1.determine_outputcorrection|.""" @modeltools.abstractmodelmethod def get_correctedoutput(self) -> float: - """Get the previously calculated corrected discharge in m³/s.""" + """Get the previously calculated corrected value.""" diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index c2676b59d1..488bb879a9 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -30,7 +30,7 @@ def __call__(self, *args, **kwargs) -> None: class EvaluationWindow(parametertools.Parameter): - """The length of the time period for evaluation of flow conditions.""" + """The length of the time period for evaluating the current conditions.""" NDIM: Final[Literal[0]] = 0 TYPE: Final = int @@ -38,7 +38,7 @@ class EvaluationWindow(parametertools.Parameter): class MaxNaNSkip(parametertools.Parameter): """The maximum number of log entries to search back for the most recently - available residual when the current or recent observed discharge values are + available residual when the current or recent observed values are missing.""" NDIM: Final[Literal[0]] = 0 @@ -47,18 +47,20 @@ class MaxNaNSkip(parametertools.Parameter): class Active(parametertools.Parameter): - """Flag determining whether the submodel may correct the discharge at all [-]. + """Flag determining whether the submodel may correct the simulated values at + all [-]. - Even when |Active| is |True|, the submodel only corrects the discharge while the - relevant simulated discharge lies within the range defined by |LowerLimit| and - |UpperLimit| (see |Determine_OutputCorrection_V1|).""" + Even when |Active| is |True|, the submodel only corrects the simulated values + while the relevant mean simulated value lies within the range defined by + |LowerLimit| and |UpperLimit| (see |Determine_OutputCorrection_V1|).""" NDIM: Final[Literal[0]] = 0 TYPE: Final = bool class CorrectionMode(parametertools.Parameter): - """The simulation mode(s) in which the submodel may correct the discharge [-]. + """The simulation mode(s) in which the submodel may correct the simulated + values [-]. Pass one of the strings `historical`, `forecast`, or `both`, corresponding to the possible values of |Options.simulationmode|. Internally, |CorrectionMode| @@ -129,8 +131,8 @@ def __repr__(self) -> str: class LowerLimit(parametertools.Parameter): - """Lower (inclusive) discharge limit of the submodel's range of responsibility - [m³/s].""" + """Lower (inclusive) limit of the submodel's range of responsibility + [unit of the corrected variable].""" NDIM: Final[Literal[0]] = 0 TYPE: Final = float @@ -138,8 +140,8 @@ class LowerLimit(parametertools.Parameter): class UpperLimit(parametertools.Parameter): - """Upper (exclusive) discharge limit of the submodel's range of responsibility - [m³/s]. + """Upper (exclusive) limit of the submodel's range of responsibility + [unit of the corrected variable]. Set it to |numpy.inf| to define a range without an upper limit.""" @@ -149,14 +151,14 @@ class UpperLimit(parametertools.Parameter): class StationarityCheck(parametertools.SpecialParameter): - """Configuration of the check of whether the measured discharge behaves in a + """Configuration of the check of whether the observed values behave in a stationary way [-]. |StationarityCheck| is a special parameter (see |SpecialParameter|). Either switch the check off by passing |False| or switch it on by passing the length of the assessment period (`window`, in log entries) and the threshold for the ratio - of the minimum and the maximum measured discharge within this period - (`ratiominmax`), below which |Determine_OutputCorrection_V1| considers the flow + of the minimum and the maximum observed values within this period + (`ratiominmax`), below which |Determine_OutputCorrection_V1| considers the conditions instationary: >>> from hydpy.models.statcorr_arima010 import * @@ -336,19 +338,19 @@ def window(self) -> int: @property def ratiominmax(self) -> float: - """The threshold ratio of the minimum and the maximum measured discharge + """The threshold ratio of the minimum and the maximum observed values (zero if the check is disabled).""" return self._get_config()[2] class VariabilityCheck(parametertools.SpecialParameter): - """Configuration of the check of whether the simulated discharge varies little + """Configuration of the check of whether the simulated values vary little enough to base the correction on a long-term mean residual [-]. |VariabilityCheck| is a special parameter (see |SpecialParameter|). Either switch the check off by passing |False| or switch it on by passing the threshold - for the sum of the absolute changes of the simulated discharge within the - |EvaluationWindow| divided by |EvaluatedDischarge| (`maxrelsumdelta`) and the + for the sum of the absolute changes of the simulated values within the + |EvaluationWindow| divided by |EvaluatedValue| (`maxrelsumdelta`) and the length of the averaging period (`averagingwindow`, in log entries) for determining the mean-value-based residual under stationary conditions (see |Determine_OutputCorrection_V1|): @@ -531,7 +533,7 @@ def enabled(self) -> bool: @property def maxrelsumdelta(self) -> float: """The threshold for the relative sum of the absolute changes of the - simulated discharge (zero if the check is disabled).""" + simulated values (zero if the check is disabled).""" return self._get_config()[1] @property @@ -543,7 +545,7 @@ def averagingwindow(self) -> int: class ReductionSteps(parametertools.Parameter): """Number of timesteps for linearly reducing the ARIMA correction to zero once - the stationarity check (see |StationarityCheck|) detects instationary flow + the stationarity check (see |StationarityCheck|) detects instationary conditions [-].""" NDIM: Final[Literal[0]] = 0 @@ -552,9 +554,9 @@ class ReductionSteps(parametertools.Parameter): class MaxAbsShift(parametertools.Parameter): - """The maximum absolute shift (in m³/s) applied when the current forecast - discharge exceeds the simulated discharge at the point the residual was - determined (see |Determine_OutputCorrection_V1|).""" + """The maximum absolute shift applied when the current forecast value + exceeds the simulated value at the point the residual was determined (see + |Determine_OutputCorrection_V1|) [unit of the corrected variable].""" NDIM: Final[Literal[0]] = 0 TYPE: Final = float @@ -562,9 +564,9 @@ class MaxAbsShift(parametertools.Parameter): class MaxRelShift(parametertools.Parameter): - """The maximum relative shift (in %) applied when the current forecast - discharge is at or below the simulated discharge at the point the residual - was determined (see |Determine_OutputCorrection_V1|).""" + """The maximum relative shift (in %) applied when the current forecast value + is at or below the simulated value at the point the residual was + determined (see |Determine_OutputCorrection_V1|).""" NDIM: Final[Literal[0]] = 0 TYPE: Final = float diff --git a/hydpy/models/statcorr/statcorr_derived.py b/hydpy/models/statcorr/statcorr_derived.py index 6933e695c0..15e2efcf73 100644 --- a/hydpy/models/statcorr/statcorr_derived.py +++ b/hydpy/models/statcorr/statcorr_derived.py @@ -36,7 +36,7 @@ def update(self) -> None: class NmbLogEntries(parametertools.Parameter): """The number of log entries required for memorising the simulated and observed - discharge values [-].""" + values [-].""" NDIM: Final[Literal[0]] = 0 TYPE: Final = int @@ -102,12 +102,12 @@ def update(self) -> None: data: >>> logs - loggedobserveddischarge(nan, nan, nan, nan) - loggedsimulateddischarge(nan, nan, nan, nan) + loggedobservedvalue(nan, nan, nan, nan) + loggedsimulatedvalue(nan, nan, nan, nan) >>> states reductionfactor(1.0) stationary(1.0) - evaluateddischarge(nan) + evaluatedvalue(nan) relsumdelta(nan) lowvariability(0.0) forecaststep(0.0) @@ -118,14 +118,14 @@ def update(self) -> None: To prevent losing information, it leaves the log and state sequences untouched as long as the number of log entries does not change: - >>> logs.loggedobserveddischarge = 1.0 + >>> logs.loggedobservedvalue = 1.0 >>> states.residual(2.0) >>> evaluationwindow(2) >>> derived.nmblogentries.update() >>> derived.nmblogentries nmblogentries(4) - >>> logs.loggedobserveddischarge - loggedobserveddischarge(1.0, 1.0, 1.0, 1.0) + >>> logs.loggedobservedvalue + loggedobservedvalue(1.0, 1.0, 1.0, 1.0) >>> states.residual residual(2.0) """ @@ -205,7 +205,7 @@ def update(self) -> None: class RatioMinMax(parametertools.Parameter): - """The threshold ratio of the minimum and the maximum measured discharge of the + """The threshold ratio of the minimum and the maximum observed values of the stationarity check (zero if the check is disabled) [-].""" NDIM: Final[Literal[0]] = 0 @@ -244,8 +244,8 @@ def update(self) -> None: class MaxRelSumDelta(parametertools.Parameter): - """The threshold for the sum of the absolute changes of the simulated discharge - within the |EvaluationWindow| divided by |EvaluatedDischarge| of the variability + """The threshold for the sum of the absolute changes of the simulated values + within the |EvaluationWindow| divided by |EvaluatedValue| of the variability check (zero if the check is disabled) [-].""" NDIM: Final[Literal[0]] = 0 diff --git a/hydpy/models/statcorr/statcorr_logs.py b/hydpy/models/statcorr/statcorr_logs.py index 9ef0124aa4..41885c64e5 100644 --- a/hydpy/models/statcorr/statcorr_logs.py +++ b/hydpy/models/statcorr/statcorr_logs.py @@ -4,13 +4,13 @@ from hydpy.core.typingtools import * -class LoggedObservedDischarge(sequencetools.LogSequence): - """Logged observed discharge [m³/s]""" +class LoggedObservedValue(sequencetools.LogSequence): + """Logged observed values [unit of the corrected variable]""" NDIM: Final[Literal[1]] = 1 -class LoggedSimulatedDischarge(sequencetools.LogSequence): - """Logged simulated discharge [m³/s].""" +class LoggedSimulatedValue(sequencetools.LogSequence): + """Logged simulated values [unit of the corrected variable].""" NDIM: Final[Literal[1]] = 1 diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 1fcd6ad326..5d7f192749 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -52,8 +52,8 @@ class Calc_OutputCorr_V1(modeltools.Method): 1. The current simulated discharge (|Inflow|) and observed discharge (|Discharge|) are passed to each attached |OutputCorrModel_V1| submodel - via |OutputCorrModel_V1.set_simulateddischarge| and - |OutputCorrModel_V1.set_observeddischarge|. While |Options.simulationmode| + via |OutputCorrModel_V1.set_simulatedvalue| and + |OutputCorrModel_V1.set_observedvalue|. While |Options.simulationmode| equals `forecast`, |Calc_OutputCorr_V1| passes |numpy.nan| instead of the actual value of |Discharge|, regardless of whether an observation is available. This relies on the assumption that a previous `historical` @@ -254,20 +254,18 @@ def __call__(model: modeltools.Model, /) -> None: der = model.parameters.derived.fastaccess flu = model.sequences.fluxes.fastaccess inp = model.sequences.inputs.fastaccess - observeddischarge: float = ( - modelutils.nan if der.isforecastmode else inp.discharge - ) + observedvalue: float = modelutils.nan if der.isforecastmode else inp.discharge flu.correctedq = flu.inflow for i in range(model.outputcorrmodels.number): if model.outputcorrmodels.typeids[i] == 1: cast( statcorrinterfaces.OutputCorrModel_V1, model.outputcorrmodels.submodels[i], - ).set_simulateddischarge(flu.inflow) + ).set_simulatedvalue(flu.inflow) cast( statcorrinterfaces.OutputCorrModel_V1, model.outputcorrmodels.submodels[i], - ).set_observeddischarge(observeddischarge) + ).set_observedvalue(observedvalue) cast( statcorrinterfaces.OutputCorrModel_V1, model.outputcorrmodels.submodels[i], @@ -371,14 +369,14 @@ def add_outputcorrmodel_v1( ... averagingwindow(0) >>> model.outputcorrmodels[0].parameters.derived.nmblogentries nmblogentries(4) - >>> model.outputcorrmodels[0].sequences.logs.loggedsimulateddischarge - loggedsimulateddischarge(nan, nan, nan, nan) + >>> model.outputcorrmodels[0].sequences.logs.loggedsimulatedvalue + loggedsimulatedvalue(nan, nan, nan, nan) """ -class Set_SimulatedDischarge_V1(modeltools.Method): - """Append the given simulated discharge value to the internal log of simulated - discharge by shifting the previously buffered values one position to the right +class Set_SimulatedValue_V1(modeltools.Method): + """Append the given simulated value to the internal log of simulated values + by shifting the previously buffered values one position to the right and storing the new value at position 0. Example: @@ -386,28 +384,28 @@ class Set_SimulatedDischarge_V1(modeltools.Method): >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() >>> derived.nmblogentries(3) - >>> logs.loggedsimulateddischarge.shape = 3 - >>> logs.loggedsimulateddischarge = 4.0, 3.0, 2.0 - >>> model.set_simulateddischarge_v1(5.0) - >>> logs.loggedsimulateddischarge - loggedsimulateddischarge(5.0, 4.0, 3.0) + >>> logs.loggedsimulatedvalue.shape = 3 + >>> logs.loggedsimulatedvalue = 4.0, 3.0, 2.0 + >>> model.set_simulatedvalue_v1(5.0) + >>> logs.loggedsimulatedvalue + loggedsimulatedvalue(5.0, 4.0, 3.0) """ DERIVEDPARAMETERS = (statcorr_derived.NmbLogEntries,) - UPDATEDSEQUENCES = (statcorr_logs.LoggedSimulatedDischarge,) + UPDATEDSEQUENCES = (statcorr_logs.LoggedSimulatedValue,) @staticmethod - def __call__(model: modeltools.Model, simulateddischarge: float, /) -> None: + def __call__(model: modeltools.Model, simulatedvalue: float, /) -> None: der = model.parameters.derived.fastaccess log = model.sequences.logs.fastaccess for idx in range(der.nmblogentries - 1, 0, -1): - log.loggedsimulateddischarge[idx] = log.loggedsimulateddischarge[idx - 1] - log.loggedsimulateddischarge[0] = simulateddischarge + log.loggedsimulatedvalue[idx] = log.loggedsimulatedvalue[idx - 1] + log.loggedsimulatedvalue[0] = simulatedvalue -class Set_ObservedDischarge_V1(modeltools.Method): - """Append the given observed discharge value to the internal log of observed - discharge by shifting the previously buffered values one position to the right +class Set_ObservedValue_V1(modeltools.Method): + """Append the given observed value to the internal log of observed values + by shifting the previously buffered values one position to the right and storing the new value at position 0. The given value may be |numpy.nan| when no observation is available. @@ -417,24 +415,24 @@ class Set_ObservedDischarge_V1(modeltools.Method): >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() >>> derived.nmblogentries(3) - >>> logs.loggedobserveddischarge.shape = 3 - >>> logs.loggedobserveddischarge = 4.0, 3.0, 2.0 + >>> logs.loggedobservedvalue.shape = 3 + >>> logs.loggedobservedvalue = 4.0, 3.0, 2.0 >>> from numpy import nan - >>> model.set_observeddischarge_v1(nan) - >>> logs.loggedobserveddischarge - loggedobserveddischarge(nan, 4.0, 3.0) + >>> model.set_observedvalue_v1(nan) + >>> logs.loggedobservedvalue + loggedobservedvalue(nan, 4.0, 3.0) """ DERIVEDPARAMETERS = (statcorr_derived.NmbLogEntries,) - UPDATEDSEQUENCES = (statcorr_logs.LoggedObservedDischarge,) + UPDATEDSEQUENCES = (statcorr_logs.LoggedObservedValue,) @staticmethod - def __call__(model: modeltools.Model, observeddischarge: float, /) -> None: + def __call__(model: modeltools.Model, observedvalue: float, /) -> None: der = model.parameters.derived.fastaccess log = model.sequences.logs.fastaccess for idx in range(der.nmblogentries - 1, 0, -1): - log.loggedobserveddischarge[idx] = log.loggedobserveddischarge[idx - 1] - log.loggedobserveddischarge[0] = observeddischarge + log.loggedobservedvalue[idx] = log.loggedobservedvalue[idx - 1] + log.loggedobservedvalue[0] = observedvalue class Calc_AveragedResidual_V1(modeltools.Method): @@ -442,8 +440,8 @@ class Calc_AveragedResidual_V1(modeltools.Method): forecast step, and freeze it for the remainder of the current forecast horizon. - |Calc_AveragedResidual_V1| averages the |LoggedObservedDischarge| and - |LoggedSimulatedDischarge| entries covering the |AveragingWindow| + |Calc_AveragedResidual_V1| averages the |LoggedObservedValue| and + |LoggedSimulatedValue| entries covering the |AveragingWindow| log positions immediately preceding the current forecast run (log position ``0`` already holds the current forecast step's own values, so averaging starts at position ``1``) and stores their difference in @@ -465,10 +463,10 @@ class Calc_AveragedResidual_V1(modeltools.Method): >>> derived.stationaryaveragingwindow(1) >>> states.lowvariability(0.0) >>> derived.nmblogentries(3) - >>> logs.loggedsimulateddischarge.shape = 3 - >>> logs.loggedobserveddischarge.shape = 3 - >>> logs.loggedsimulateddischarge = 3.0, 2.0, 4.0 - >>> logs.loggedobserveddischarge = nan, 3.0, 5.0 + >>> logs.loggedsimulatedvalue.shape = 3 + >>> logs.loggedobservedvalue.shape = 3 + >>> logs.loggedsimulatedvalue = 3.0, 2.0, 4.0 + >>> logs.loggedobservedvalue = nan, 3.0, 5.0 On the first forecast step (`forecast_step` is ``0.0``), the average is taken from log positions ``1`` and ``2`` (mean observed ``4.0``, @@ -482,8 +480,8 @@ class Calc_AveragedResidual_V1(modeltools.Method): On any later forecast step, the previously determined value remains unchanged, regardless of the current log contents: - >>> logs.loggedsimulateddischarge = 3.0, 20.0, 40.0 - >>> logs.loggedobserveddischarge = nan, 30.0, 50.0 + >>> logs.loggedsimulatedvalue = 3.0, 20.0, 40.0 + >>> logs.loggedobservedvalue = nan, 30.0, 50.0 >>> model.calc_averagedresidual_v1(1.0, -9.0) >>> states.averagedresidual averagedresidual(1.0) @@ -502,7 +500,7 @@ class Calc_AveragedResidual_V1(modeltools.Method): |Calc_AveragedResidual_V1| fall back to the given `fallback` value: >>> control.averagingwindow(2) - >>> logs.loggedobserveddischarge = nan, nan, 50.0 + >>> logs.loggedobservedvalue = nan, nan, 50.0 >>> model.calc_averagedresidual_v1(0.0, -9.0) >>> states.averagedresidual averagedresidual(-9.0) @@ -514,7 +512,7 @@ class Calc_AveragedResidual_V1(modeltools.Method): >>> control.averagingwindow(0) >>> states.lowvariability(1.0) - >>> logs.loggedobserveddischarge = nan, 30.0, nan + >>> logs.loggedobservedvalue = nan, 30.0, nan >>> model.calc_averagedresidual_v1(0.0, -9.0) >>> states.averagedresidual averagedresidual(10.0) @@ -526,8 +524,8 @@ class Calc_AveragedResidual_V1(modeltools.Method): statcorr_derived.StationaryAveragingWindow, ) REQUIREDSEQUENCES = ( - statcorr_logs.LoggedSimulatedDischarge, - statcorr_logs.LoggedObservedDischarge, + statcorr_logs.LoggedSimulatedValue, + statcorr_logs.LoggedObservedValue, statcorr_states.LowVariability, ) UPDATEDSEQUENCES = (statcorr_states.AveragedResidual,) @@ -552,8 +550,8 @@ def __call__( sum_sim: float = 0.0 has_nan = False for idx in range(1, nmb + 1): - obs_value: float = log.loggedobserveddischarge[idx] - sim_value: float = log.loggedsimulateddischarge[idx] + obs_value: float = log.loggedobservedvalue[idx] + sim_value: float = log.loggedsimulatedvalue[idx] if modelutils.isnan(obs_value) or modelutils.isnan(sim_value): has_nan = True break @@ -563,14 +561,14 @@ def __call__( class Determine_OutputCorrection_V1(modeltools.Method): - r"""Calculate the corrected discharge using an ARIMA(0,1,0) — random-walk — + r"""Calculate the corrected value using an ARIMA(0,1,0) — random-walk — error model. - Each submodel is responsible for a specific discharge range only. It corrects - the discharge only while |Active| is |True|, |CorrectionMode| allows a + Each submodel is responsible for a specific value range only. It corrects + the simulated values only while |Active| is |True|, |CorrectionMode| allows a correction in the current simulation mode, and the mean of the - |EvaluationWindow| most recent |LoggedSimulatedDischarge| values - (:math:`\overline{sim}`, stored in |EvaluatedDischarge|) lies within the + |EvaluationWindow| most recent |LoggedSimulatedValue| values + (:math:`\overline{sim}`, stored in |EvaluatedValue|) lies within the range defined by |LowerLimit| and |UpperLimit|: :math:`LowerLimit \leq \overline{sim} < UpperLimit` @@ -582,37 +580,36 @@ class Determine_OutputCorrection_V1(modeltools.Method): checks the condition in each simulation step (so changes of |Active|, |CorrectionMode|, |LowerLimit|, or |UpperLimit| take effect immediately) and stores the outcome in |IsActive|. Whenever the condition is not met, the - corrected discharge equals the current simulated discharge. However, + corrected value equals the current simulated value. However, |Determine_OutputCorrection_V1| keeps updating all internal states (the residual, the stationarity assessment, and the |ReductionFactor|) in either case, so that a submodel taking over responsibility starts with up-to-date information. This also holds for a submodel that |CorrectionMode| restricts - to the `forecast` mode, which, therefore, relies on the residual and the flow + to the `forecast` mode, which, therefore, relies on the residual and the conditions determined during the preceding `historical` run. The correction is derived from the most recently available residual - (observed minus simulated discharge). While |Options.simulationmode| + (observed minus simulated values). While |Options.simulationmode| equals `historical`, the "most recent" residual is taken from the latest - log entry where the observed discharge is not |numpy.nan|, searching back + log entry where the observed value is not |numpy.nan|, searching back at most |MaxNaNSkip| log entries (or the entire log, whichever is smaller), and remembered in |Residual| (together with the corresponding - simulated discharge in |ResidualAnchor|). When no observation is + simulated value in |ResidualAnchor|). When no observation is available within that range, both are set to zero, so the corrected - discharge equals the current simulated discharge. While + value equals the current simulated value. While |Options.simulationmode| equals `forecast`, |Determine_OutputCorrection_V1| does not repeat this search — see the paragraph on |Residual| and |ResidualAnchor| below for why. How that residual is applied to the current simulated ("forecast") - discharge depends on how the latter (:math:`sim_0`) compares to the - simulated discharge at the time the residual was determined (:math:`sim_k`, + value depends on how the latter (:math:`sim_0`) compares to the + simulated value at the time the residual was determined (:math:`sim_k`, with :math:`k` denoting the most recent log index for which :math:`obs_k \neq \mathrm{nan}`, and :math:`f_{red}` denoting |ReductionFactor|): * If :math:`sim_0 > sim_k` (and :math:`sim_k > 0`), |Determine_OutputCorrection_V1| shifts :math:`sim_0` *additively* by the - |ReductionFactor|-damped residual, capped at |MaxAbsShift| (in - m³/s): + |ReductionFactor|-damped residual, capped at |MaxAbsShift|: :math:`q_{corr} = sim_0 + \mathrm{clip}\left((obs_k - sim_k) \cdot f_{red},\ \pm MaxAbsShift\right)` @@ -628,21 +625,21 @@ class Determine_OutputCorrection_V1(modeltools.Method): Applying the residual as a percentage rather than a constant offset keeps the correction from overshooting or turning negative while the - forecasted discharge recedes towards zero. + forecasted values recede towards zero. The residual (:math:`obs_k - sim_k` above) used in either branch is not necessarily the pointwise one. Setting |AveragingWindow| to a value greater than zero switches to a mean-value-based residual instead — - the difference between the mean observed and the mean simulated discharge + the difference between the mean observed and the mean simulated values over that many log entries immediately preceding the current forecast run (determined once, at the first forecast step, via |Calc_AveragedResidual_V1|, and frozen in |AveragedResidual| for the remainder of the forecast horizon). Since that mean-value-based residual generally does not equal the pointwise residual at the forecast's start, - switching to it abruptly would cause a jump in the corrected discharge + switching to it abruptly would cause a jump in the corrected value right where the forecast begins. To avoid this, |Determine_OutputCorrection_V1| starts every forecast run with the pointwise residual (so the corrected - discharge picks up smoothly where the last measurement left off) and then + value picks up smoothly where the last measurement left off) and then linearly blends it towards the mean-value-based residual over |TransitionSteps| forecast steps, applying the mean-value-based residual unabated from then on. Setting |AveragingWindow| to zero @@ -651,11 +648,11 @@ class Determine_OutputCorrection_V1(modeltools.Method): as described above. If enabled via |StationarityCheck|, |Determine_OutputCorrection_V1| - additionally assesses whether the measured discharge behaves in a stationary + additionally assesses whether the observed values behave in a stationary way. It takes the ratio of the minimum and the maximum - |LoggedObservedDischarge| value within the most recent |StationarityWindow| + |LoggedObservedValue| value within the most recent |StationarityWindow| log entries. Whenever this ratio falls below |RatioMinMax|, it considers the - flow conditions instationary and linearly reduces |ReductionFactor| (the + conditions instationary and linearly reduces |ReductionFactor| (the factor :math:`f_{red}` in the equation above) towards zero, taking as many steps as given by |ReductionSteps|. As soon as the ratio reaches |RatioMinMax| again (or a |numpy.nan| value prevents its calculation), @@ -668,7 +665,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): `historical`, remembering its outcome in |Stationary|. While |Options.simulationmode| equals `forecast`, it reuses this value from the most recent `historical` assessment instead of recomputing it — - recomputing would be unreliable anyway, since |LoggedObservedDischarge| + recomputing would be unreliable anyway, since |LoggedObservedValue| keeps receiving |numpy.nan| values throughout the forecast (see |Calc_OutputCorr_V1|), which the ratio-based check always interprets as "stationary". So, once a `historical` run has flagged conditions as @@ -677,10 +674,10 @@ class Determine_OutputCorrection_V1(modeltools.Method): as soon as the last real observation drops out of the logging window. If enabled via |VariabilityCheck|, |Determine_OutputCorrection_V1| - additionally assesses how much the simulated discharge varies. It sums the - absolute changes between successive |LoggedSimulatedDischarge| values within - the |EvaluationWindow| and divides this sum by |EvaluatedDischarge|, storing - the result in |RelSumDelta|. It considers the flow conditions stationary + additionally assesses how much the simulated values vary. It sums the + absolute changes between successive |LoggedSimulatedValue| values within + the |EvaluationWindow| and divides this sum by |EvaluatedValue|, storing + the result in |RelSumDelta|. It considers the conditions stationary (|LowVariability| is ``1.0``) if |RelSumDelta| does not exceed |MaxRelSumDelta| and the stationarity check described above is either disabled or also detects stationary conditions. Hence, the variability check @@ -690,7 +687,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): of the |AveragingWindow| (and so applies even if |AveragingWindow| is zero), while the transition over |TransitionSteps| forecast steps remains unchanged. Otherwise - (including the case of a non-positive |EvaluatedDischarge|, for which + (including the case of a non-positive |EvaluatedValue|, for which |RelSumDelta| is |numpy.nan|), the correction works as described above. Like |Stationary|, |Determine_OutputCorrection_V1| reassesses |RelSumDelta| and |LowVariability| only while |Options.simulationmode| equals @@ -712,8 +709,8 @@ class Determine_OutputCorrection_V1(modeltools.Method): Three log entries are available, the most recent observation (at position 0) is non-|numpy.nan|, so the correction reproduces the current - observation. The submodel is responsible for all discharges. The - measured discharge is just stationary (the ratio of its minimum and + observation. The submodel is responsible for all values. The + observed values are just stationary (the ratio of their minimum and maximum equals |RatioMinMax|), so |ReductionFactor| remains at its initial value of ``1.0``: @@ -740,10 +737,10 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> control.transitionsteps(0) >>> states.reductionfactor(1.0) >>> states.stationary(1.0) - >>> logs.loggedsimulateddischarge.shape = 3 - >>> logs.loggedobserveddischarge.shape = 3 - >>> logs.loggedsimulateddischarge = 5.0, 3.0, 2.0 - >>> logs.loggedobserveddischarge = 6.0, 4.0, 3.0 + >>> logs.loggedsimulatedvalue.shape = 3 + >>> logs.loggedobservedvalue.shape = 3 + >>> logs.loggedsimulatedvalue = 5.0, 3.0, 2.0 + >>> logs.loggedobservedvalue = 6.0, 4.0, 3.0 >>> model.determine_outputcorrection_v1(False) >>> fluxes.isactive isactive(1.0) @@ -752,8 +749,8 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> states.reductionfactor reductionfactor(1.0) - The mean simulated discharge (``10/3`` m³/s) is not below an - |UpperLimit| of 3 m³/s, so the submodel is not responsible and returns + The mean simulated value (``10/3``) is not below an + |UpperLimit| of 3, so the submodel is not responsible and returns the uncorrected simulated value: >>> control.upperlimit(3.0) @@ -765,8 +762,8 @@ class Determine_OutputCorrection_V1(modeltools.Method): |UpperLimit| is exclusive, while |LowerLimit| is inclusive: - >>> logs.loggedsimulateddischarge = 3.0, 3.0, 3.0 - >>> logs.loggedobserveddischarge = 4.0, 4.0, 4.0 + >>> logs.loggedsimulatedvalue = 3.0, 3.0, 3.0 + >>> logs.loggedobservedvalue = 4.0, 4.0, 4.0 >>> model.determine_outputcorrection_v1(False) >>> fluxes.isactive isactive(0.0) @@ -791,7 +788,8 @@ class Determine_OutputCorrection_V1(modeltools.Method): correctedq(3.0) |CorrectionMode| restricts the correction to one simulation mode. With - `forecast`, the submodel does not correct the discharge in the `historical` + `forecast`, the submodel does not correct the simulated values in the + `historical` mode: >>> control.active(True) @@ -828,33 +826,33 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> control.correctionmode("both") The two most recent observations are missing, so the residual is taken - from the third log entry and added to the current simulated discharge. + from the third log entry and added to the current simulated value. Missing observations also make it impossible to assess stationarity, so |Determine_OutputCorrection_V1| assumes stationary conditions and leaves |ReductionFactor| untouched: >>> control.active(True) >>> control.lowerlimit(0.0) - >>> logs.loggedsimulateddischarge = 5.0, 3.0, 2.0 - >>> logs.loggedobserveddischarge = nan, nan, 3.0 + >>> logs.loggedsimulatedvalue = 5.0, 3.0, 2.0 + >>> logs.loggedobservedvalue = nan, nan, 3.0 >>> model.determine_outputcorrection_v1(False) >>> fluxes.correctedq correctedq(6.0) All observations are missing — no correction is applied: - >>> logs.loggedobserveddischarge = nan, nan, nan + >>> logs.loggedobservedvalue = nan, nan, nan >>> model.determine_outputcorrection_v1(False) >>> fluxes.correctedq correctedq(5.0) Sustained instationary conditions (the ratio of the minimum and the - maximum observed discharge, ``0.5 / 5.0 = 0.1``, falls well below + maximum observed values, ``0.5 / 5.0 = 0.1``, falls well below |RatioMinMax|) linearly reduce |ReductionFactor| to zero within the two steps given by |ReductionSteps|: - >>> logs.loggedsimulateddischarge = 1.0, 1.0, 1.0 - >>> logs.loggedobserveddischarge = 0.5, 5.0, 5.0 + >>> logs.loggedsimulatedvalue = 1.0, 1.0, 1.0 + >>> logs.loggedobservedvalue = 0.5, 5.0, 5.0 >>> model.determine_outputcorrection_v1(False) >>> states.stationary stationary(0.0) @@ -870,7 +868,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): correctedq(1.0) Disabling the stationarity check resets |ReductionFactor| to ``1.0`` - regardless of the (still instationary) measured discharge: + regardless of the (still instationary) observed values: >>> control.stationaritycheck(False) >>> derived.stationaritywindow.update() @@ -881,7 +879,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> fluxes.correctedq correctedq(0.5) - Once the measured discharge becomes stationary again (ratio + Once the observed values become stationary again (ratio ``4.0 / 5.0 = 0.8``, at or above |RatioMinMax|), |ReductionFactor| jumps back to ``1.0`` immediately, applying the correction unabated: @@ -889,7 +887,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> derived.stationaritywindow.update() >>> derived.ratiominmax.update() >>> states.reductionfactor(0.0) - >>> logs.loggedobserveddischarge = 4.0, 5.0, 5.0 + >>> logs.loggedobservedvalue = 4.0, 5.0, 5.0 >>> model.determine_outputcorrection_v1(False) >>> states.reductionfactor reductionfactor(1.0) @@ -900,7 +898,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): immediately once instationary conditions occur: >>> control.reductionsteps(0) - >>> logs.loggedobserveddischarge = 0.5, 5.0, 5.0 + >>> logs.loggedobservedvalue = 0.5, 5.0, 5.0 >>> model.determine_outputcorrection_v1(False) >>> states.reductionfactor reductionfactor(0.0) @@ -913,8 +911,8 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> control.reductionsteps(2) >>> states.reductionfactor(1.0) - >>> logs.loggedsimulateddischarge = 1.0, 1.0, 1.0 - >>> logs.loggedobserveddischarge = 0.5, 5.0, 5.0 + >>> logs.loggedsimulatedvalue = 1.0, 1.0, 1.0 + >>> logs.loggedobservedvalue = 0.5, 5.0, 5.0 >>> model.determine_outputcorrection_v1(False) >>> states.stationary stationary(0.0) @@ -926,8 +924,8 @@ class Determine_OutputCorrection_V1(modeltools.Method): observations does not reassess |Stationary|; the ramp initiated above simply continues: - >>> logs.loggedsimulateddischarge = 1.0, 1.0, 1.0 - >>> logs.loggedobserveddischarge = nan, nan, nan + >>> logs.loggedsimulatedvalue = 1.0, 1.0, 1.0 + >>> logs.loggedobservedvalue = nan, nan, nan >>> model.determine_outputcorrection_v1(True) >>> states.stationary stationary(0.0) @@ -946,26 +944,26 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> fluxes.correctedq correctedq(1.0) - The same holds for the mean simulated discharge deciding on the + The same holds for the mean simulated value deciding on the submodel's responsibility. It was determined at the last `historical` - call (``1.0`` m³/s) and stays frozen while forecasting. So, even if the - forecasted discharge rises above |UpperLimit|, the submodel remains + call (``1.0``) and stays frozen while forecasting. So, even if the + forecasted values rise above |UpperLimit|, the submodel remains responsible: >>> control.upperlimit(5.0) - >>> logs.loggedsimulateddischarge = 10.0, 10.0, 10.0 + >>> logs.loggedsimulatedvalue = 10.0, 10.0, 10.0 >>> model.determine_outputcorrection_v1(True) - >>> states.evaluateddischarge - evaluateddischarge(1.0) + >>> states.evaluatedvalue + evaluatedvalue(1.0) >>> fluxes.isactive isactive(1.0) - Only a `historical` call updates |EvaluatedDischarge|, which then exceeds + Only a `historical` call updates |EvaluatedValue|, which then exceeds |UpperLimit|, so the submodel stops correcting: >>> model.determine_outputcorrection_v1(False) - >>> states.evaluateddischarge - evaluateddischarge(10.0) + >>> states.evaluatedvalue + evaluatedvalue(10.0) >>> fluxes.isactive isactive(0.0) >>> fluxes.correctedq @@ -973,7 +971,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): Enlarging the log beyond |EvaluationWindow| does not change the responsibility assessment, which always relies on the *most recently* - logged |LoggedSimulatedDischarge| entries (index ``0`` upwards) and + logged |LoggedSimulatedValue| entries (index ``0`` upwards) and never on the oldest ones sitting near the end of a larger log (which can well still be |numpy.nan|, as is the case for the newly added entries here): @@ -981,10 +979,10 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> control.upperlimit(inf) >>> states.reductionfactor(1.0) >>> derived.nmblogentries(5) - >>> logs.loggedsimulateddischarge.shape = 5 - >>> logs.loggedobserveddischarge.shape = 5 - >>> logs.loggedsimulateddischarge = 1.0, 1.0, 1.0, nan, nan - >>> logs.loggedobserveddischarge = 0.5, 5.0, 5.0, nan, nan + >>> logs.loggedsimulatedvalue.shape = 5 + >>> logs.loggedobservedvalue.shape = 5 + >>> logs.loggedsimulatedvalue = 1.0, 1.0, 1.0, nan, nan + >>> logs.loggedobservedvalue = 0.5, 5.0, 5.0, nan, nan >>> model.determine_outputcorrection_v1(False) >>> fluxes.isactive isactive(1.0) @@ -999,8 +997,8 @@ class Determine_OutputCorrection_V1(modeltools.Method): though an older, still-logged observation would otherwise be usable: >>> control.maxnanskip(2) - >>> logs.loggedsimulateddischarge = 1.0, 1.0, 1.0, nan, nan - >>> logs.loggedobserveddischarge = nan, nan, 3.0, nan, nan + >>> logs.loggedsimulatedvalue = 1.0, 1.0, 1.0, nan, nan + >>> logs.loggedobservedvalue = nan, nan, 3.0, nan, nan >>> model.determine_outputcorrection_v1(False) >>> fluxes.correctedq correctedq(1.0) @@ -1014,15 +1012,15 @@ class Determine_OutputCorrection_V1(modeltools.Method): correctedq(3.0) So far, the current forecast value (log position 0) has always been - at or above the simulated discharge at the time the residual was + at or above the simulated value at the time the residual was determined, so all examples above used the additive (or, at position 0 itself, an equivalent) shift. Resetting the log to a *receding* forecast — position 0 has already dropped clearly below the value at the residual's log position — switches to the relative (percentage) shift instead: - >>> logs.loggedsimulateddischarge = 2.0, 10.0, 10.0, nan, nan - >>> logs.loggedobserveddischarge = nan, 12.0, nan, nan, nan + >>> logs.loggedsimulatedvalue = 2.0, 10.0, 10.0, nan, nan + >>> logs.loggedobservedvalue = nan, 12.0, nan, nan, nan >>> model.determine_outputcorrection_v1(False) >>> fluxes.correctedq correctedq(2.4) @@ -1039,7 +1037,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): the forecast value exceeds the anchor value: >>> control.maxabsshift(1.0) - >>> logs.loggedsimulateddischarge = 12.0, 10.0, 10.0, nan, nan + >>> logs.loggedsimulatedvalue = 12.0, 10.0, 10.0, nan, nan >>> model.determine_outputcorrection_v1(False) >>> fluxes.correctedq correctedq(13.0) @@ -1050,8 +1048,8 @@ class Determine_OutputCorrection_V1(modeltools.Method): the forecast value does not exceed the anchor value: >>> control.maxabsshift(100.0) - >>> logs.loggedsimulateddischarge = 0.0, 0.0, 10.0, nan, nan - >>> logs.loggedobserveddischarge = nan, 2.0, nan, nan, nan + >>> logs.loggedsimulatedvalue = 0.0, 0.0, 10.0, nan, nan + >>> logs.loggedobservedvalue = nan, 2.0, nan, nan, nan >>> model.determine_outputcorrection_v1(False) >>> fluxes.correctedq correctedq(2.0) @@ -1059,7 +1057,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): Setting |AveragingWindow| to a value greater than zero switches to the mean-value-based residual, blended in linearly over |TransitionSteps| forecast steps. We reset the log to a - short, clean example (four entries) and freeze |EvaluatedDischarge|, + short, clean example (four entries) and freeze |EvaluatedValue|, |Stationary|, |Residual|, and |ResidualAnchor| directly (instead of deriving them from a preceding `historical` call) to keep the focus on the transition mechanism: @@ -1070,9 +1068,9 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> control.averagingwindow(2) >>> control.transitionsteps(2) >>> derived.nmblogentries(4) - >>> logs.loggedsimulateddischarge.shape = 4 - >>> logs.loggedobserveddischarge.shape = 4 - >>> states.evaluateddischarge(8.0) + >>> logs.loggedsimulatedvalue.shape = 4 + >>> logs.loggedobservedvalue.shape = 4 + >>> states.evaluatedvalue(8.0) >>> states.stationary(1.0) >>> states.reductionfactor(1.0) >>> states.forecaststep(0.0) @@ -1086,8 +1084,8 @@ class Determine_OutputCorrection_V1(modeltools.Method): |Determine_OutputCorrection_V1| applies the pointwise residual unabated: - >>> logs.loggedsimulateddischarge = 10.0, 8.0, 4.0, nan - >>> logs.loggedobserveddischarge = nan, 9.0, 8.0, nan + >>> logs.loggedsimulatedvalue = 10.0, 8.0, 4.0, nan + >>> logs.loggedobservedvalue = nan, 9.0, 8.0, nan >>> model.determine_outputcorrection_v1(True) >>> states.averagedresidual averagedresidual(2.5) @@ -1097,8 +1095,8 @@ class Determine_OutputCorrection_V1(modeltools.Method): Halfway through the two-step transition, the applied residual is the average of both (``1.75``): - >>> logs.loggedsimulateddischarge = 11.0, 10.0, 8.0, 4.0 - >>> logs.loggedobserveddischarge = nan, nan, 9.0, 8.0 + >>> logs.loggedsimulatedvalue = 11.0, 10.0, 8.0, 4.0 + >>> logs.loggedobservedvalue = nan, nan, 9.0, 8.0 >>> model.determine_outputcorrection_v1(True) >>> fluxes.correctedq correctedq(12.75) @@ -1106,8 +1104,8 @@ class Determine_OutputCorrection_V1(modeltools.Method): Once the transition period has elapsed, the full mean-value-based residual applies, regardless of the (still aging) pointwise residual: - >>> logs.loggedsimulateddischarge = 12.0, 11.0, 10.0, 8.0 - >>> logs.loggedobserveddischarge = nan, nan, nan, 9.0 + >>> logs.loggedsimulatedvalue = 12.0, 11.0, 10.0, 8.0 + >>> logs.loggedobservedvalue = nan, nan, nan, 9.0 >>> model.determine_outputcorrection_v1(True) >>> states.averagedresidual averagedresidual(2.5) @@ -1115,7 +1113,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): correctedq(14.5) Next, we enable the variability check. In the following `historical` - call, the absolute changes of the simulated discharge within the + call, the absolute changes of the simulated values within the |EvaluationWindow| sum up to ``2.0``, which is 20 % of their mean value (``10.0``). So, |RelSumDelta| does not exceed |MaxRelSumDelta|, and (as the stationarity check also detects stationary conditions) @@ -1124,8 +1122,8 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> control.variabilitycheck(maxrelsumdelta=0.2, averagingwindow=3) >>> derived.maxrelsumdelta.update() >>> derived.stationaryaveragingwindow.update() - >>> logs.loggedsimulateddischarge = 9.0, 10.0, 11.0, 10.0 - >>> logs.loggedobserveddischarge = 10.0, 12.0, 14.0, 12.0 + >>> logs.loggedsimulatedvalue = 9.0, 10.0, 11.0, 10.0 + >>> logs.loggedobservedvalue = 10.0, 12.0, 14.0, 12.0 >>> model.determine_outputcorrection_v1(False) >>> states.stationary stationary(1.0) @@ -1142,22 +1140,22 @@ class Determine_OutputCorrection_V1(modeltools.Method): |AveragingWindow|. The transition from the pointwise residual (``1.0``) works as before: - >>> logs.loggedsimulateddischarge = 12.0, 9.0, 10.0, 11.0 - >>> logs.loggedobserveddischarge = nan, 10.0, 12.0, 14.0 + >>> logs.loggedsimulatedvalue = 12.0, 9.0, 10.0, 11.0 + >>> logs.loggedobservedvalue = nan, 10.0, 12.0, 14.0 >>> model.determine_outputcorrection_v1(True) >>> states.averagedresidual averagedresidual(2.0) >>> fluxes.correctedq correctedq(13.0) - >>> logs.loggedsimulateddischarge = 13.0, 12.0, 9.0, 10.0 - >>> logs.loggedobserveddischarge = nan, nan, 10.0, 12.0 + >>> logs.loggedsimulatedvalue = 13.0, 12.0, 9.0, 10.0 + >>> logs.loggedobservedvalue = nan, nan, 10.0, 12.0 >>> model.determine_outputcorrection_v1(True) >>> fluxes.correctedq correctedq(14.5) - >>> logs.loggedsimulateddischarge = 14.0, 13.0, 12.0, 9.0 - >>> logs.loggedobserveddischarge = nan, nan, nan, 10.0 + >>> logs.loggedsimulatedvalue = 14.0, 13.0, 12.0, 9.0 + >>> logs.loggedobservedvalue = nan, nan, nan, 10.0 >>> model.determine_outputcorrection_v1(True) >>> states.lowvariability lowvariability(1.0) @@ -1169,15 +1167,15 @@ class Determine_OutputCorrection_V1(modeltools.Method): observed ``11.0``, mean simulated ``9.0``) instead of using the |StationaryAveragingWindow| (which would result in a value of ``3.0``): - >>> logs.loggedsimulateddischarge = 8.0, 10.0, 12.0, 9.0 - >>> logs.loggedobserveddischarge = 10.0, 12.0, 14.0, 12.0 + >>> logs.loggedsimulatedvalue = 8.0, 10.0, 12.0, 9.0 + >>> logs.loggedobservedvalue = 10.0, 12.0, 14.0, 12.0 >>> model.determine_outputcorrection_v1(False) >>> states.relsumdelta relsumdelta(0.4) >>> states.lowvariability lowvariability(0.0) - >>> logs.loggedsimulateddischarge = 12.0, 8.0, 10.0, 9.0 - >>> logs.loggedobserveddischarge = nan, 10.0, 12.0, 14.0 + >>> logs.loggedsimulatedvalue = 12.0, 8.0, 10.0, 9.0 + >>> logs.loggedobservedvalue = nan, 10.0, 12.0, 14.0 >>> model.determine_outputcorrection_v1(True) >>> states.averagedresidual averagedresidual(2.0) @@ -1187,8 +1185,8 @@ class Determine_OutputCorrection_V1(modeltools.Method): detecting stationary conditions, even if |RelSumDelta| does not exceed |MaxRelSumDelta|: - >>> logs.loggedsimulateddischarge = 9.0, 10.0, 11.0, 10.0 - >>> logs.loggedobserveddischarge = 5.0, 12.0, 14.0, 12.0 + >>> logs.loggedsimulatedvalue = 9.0, 10.0, 11.0, 10.0 + >>> logs.loggedobservedvalue = 5.0, 12.0, 14.0, 12.0 >>> model.determine_outputcorrection_v1(False) >>> states.stationary stationary(0.0) @@ -1197,12 +1195,12 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> states.lowvariability lowvariability(0.0) - For a non-positive |EvaluatedDischarge|, |RelSumDelta| is undefined, and - |Determine_OutputCorrection_V1| does not consider the flow conditions + For a non-positive |EvaluatedValue|, |RelSumDelta| is undefined, and + |Determine_OutputCorrection_V1| does not consider the conditions stationary: - >>> logs.loggedsimulateddischarge = 0.0, 0.0, 0.0, 0.0 - >>> logs.loggedobserveddischarge = 1.0, 1.0, 1.0, 1.0 + >>> logs.loggedsimulatedvalue = 0.0, 0.0, 0.0, 0.0 + >>> logs.loggedobservedvalue = 1.0, 1.0, 1.0, 1.0 >>> model.determine_outputcorrection_v1(False) >>> states.relsumdelta relsumdelta(nan) @@ -1242,11 +1240,11 @@ class Determine_OutputCorrection_V1(modeltools.Method): statcorr_derived.StationaryAveragingWindow, ) REQUIREDSEQUENCES = ( - statcorr_logs.LoggedSimulatedDischarge, - statcorr_logs.LoggedObservedDischarge, + statcorr_logs.LoggedSimulatedValue, + statcorr_logs.LoggedObservedValue, ) UPDATEDSEQUENCES = ( - statcorr_states.EvaluatedDischarge, + statcorr_states.EvaluatedValue, statcorr_states.ReductionFactor, statcorr_states.Stationary, statcorr_states.RelSumDelta, @@ -1272,8 +1270,8 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: if not isforecastmode: mean_simulated: float = 0.0 for idx in range(con.evaluationwindow): - mean_simulated = mean_simulated + log.loggedsimulateddischarge[idx] - sta.evaluateddischarge = mean_simulated / con.evaluationwindow + mean_simulated = mean_simulated + log.loggedsimulatedvalue[idx] + sta.evaluatedvalue = mean_simulated / con.evaluationwindow if con.correctionmode == 3: modeallowed = True elif isforecastmode: @@ -1283,7 +1281,7 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: if ( con.active and modeallowed - and (con.lowerlimit <= sta.evaluateddischarge < con.upperlimit) + and (con.lowerlimit <= sta.evaluatedvalue < con.upperlimit) ): flu.isactive = 1.0 else: @@ -1298,9 +1296,9 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: residual = 0.0 sim_anchor = 0.0 for idx in range(min(der.nmblogentries, con.maxnanskip)): - if not modelutils.isnan(log.loggedobserveddischarge[idx]): - sim_anchor = log.loggedsimulateddischarge[idx] - residual = log.loggedobserveddischarge[idx] - sim_anchor + if not modelutils.isnan(log.loggedobservedvalue[idx]): + sim_anchor = log.loggedsimulatedvalue[idx] + residual = log.loggedobservedvalue[idx] - sim_anchor break sta.residual = residual sta.residualanchor = sim_anchor @@ -1315,7 +1313,7 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: qmin: float = modelutils.inf qmax: float = -modelutils.inf for idx in range(nmb): - value: float = log.loggedobserveddischarge[idx] + value: float = log.loggedobservedvalue[idx] if modelutils.isnan(value): has_nan = True break @@ -1340,11 +1338,10 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: sumdelta: float = 0.0 for idx in range(con.evaluationwindow - 1): sumdelta = sumdelta + modelutils.fabs( - log.loggedsimulateddischarge[idx] - - log.loggedsimulateddischarge[idx + 1] + log.loggedsimulatedvalue[idx] - log.loggedsimulatedvalue[idx + 1] ) - if sta.evaluateddischarge > 0.0: - sta.relsumdelta = sumdelta / sta.evaluateddischarge + if sta.evaluatedvalue > 0.0: + sta.relsumdelta = sumdelta / sta.evaluatedvalue else: sta.relsumdelta = modelutils.nan if (der.stationaritywindow <= 0 or sta.stationary == 1.0) and ( @@ -1358,7 +1355,7 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: sta.forecaststep = (forecast_step + 1.0) if isforecastmode else 0.0 model.calc_averagedresidual_v1(forecast_step, residual) - forecast_value: float = log.loggedsimulateddischarge[0] + forecast_value: float = log.loggedsimulatedvalue[0] if flu.isactive == 0.0: flu.correctedq = forecast_value return @@ -1386,8 +1383,8 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: class Is_Active_V1(modeltools.Method): - """Tell whether the submodel corrected the discharge during the most recent call - of |Determine_OutputCorrection_V1|. + """Tell whether the submodel corrected the simulated value during the most + recent call of |Determine_OutputCorrection_V1|. Example: @@ -1408,7 +1405,7 @@ def __call__(model: modeltools.Model, /) -> bool: class Get_CorrectedOutput_V1(modeltools.Method): - """Return the most recently calculated corrected discharge in m³/s. + """Return the most recently calculated corrected value. Example: diff --git a/hydpy/models/statcorr/statcorr_states.py b/hydpy/models/statcorr/statcorr_states.py index 153ef51199..46c4db34a5 100644 --- a/hydpy/models/statcorr/statcorr_states.py +++ b/hydpy/models/statcorr/statcorr_states.py @@ -8,7 +8,7 @@ class ReductionFactor(sequencetools.StateSequence): """Factor for linearly reducing the ARIMA correction to zero under instationary - flow conditions (1.0: apply the correction unabated; 0.0: apply no correction at + conditions (1.0: apply the correction unabated; 0.0: apply no correction at all) [-].""" NDIM: Final[Literal[0]] = 0 @@ -17,7 +17,7 @@ class ReductionFactor(sequencetools.StateSequence): class Stationary(sequencetools.StateSequence): - """Flag (1.0: yes, 0.0: no) telling whether the measured discharge behaved in a + """Flag (1.0: yes, 0.0: no) telling whether the observed values behaved in a stationary way at the last assessment (1.0: apply |ReductionFactor| unabated; 0.0: reduce |ReductionFactor| linearly) [-]. @@ -33,26 +33,27 @@ class Stationary(sequencetools.StateSequence): INIT = 1.0 -class EvaluatedDischarge(sequencetools.StateSequence): - """The mean simulated discharge over the |EvaluationWindow| most recent log - entries, as determined at the last `historical` assessment [m³/s]. +class EvaluatedValue(sequencetools.StateSequence): + """The mean of the simulated values over the |EvaluationWindow| most recent log + entries, as determined at the last `historical` assessment [unit of the + corrected variable]. - |Determine_OutputCorrection_V1| compares |EvaluatedDischarge| with |LowerLimit| + |Determine_OutputCorrection_V1| compares |EvaluatedValue| with |LowerLimit| and |UpperLimit| to decide whether the submodel is responsible for correcting - the discharge. Like |Stationary|, |statcorr_arima010| only reassesses - |EvaluatedDischarge| while |Options.simulationmode| equals `historical`. - While it equals `forecast`, |EvaluatedDischarge| keeps the value determined + the simulated values. Like |Stationary|, |statcorr_arima010| only reassesses + |EvaluatedValue| while |Options.simulationmode| equals `historical`. + While it equals `forecast`, |EvaluatedValue| keeps the value determined at the most recent `historical` assessment, so the responsible submodel does not change throughout the whole forecast horizon, regardless of how the - forecasted discharge develops.""" + forecasted values develop.""" NDIM: Final[Literal[0]] = 0 INIT = numpy.nan class RelSumDelta(sequencetools.StateSequence): - """The sum of the absolute changes of the simulated discharge within the - |EvaluationWindow| divided by |EvaluatedDischarge|, as determined at the last + """The sum of the absolute changes of the simulated values within the + |EvaluationWindow| divided by |EvaluatedValue|, as determined at the last `historical` assessment [-]. Like |Stationary|, |statcorr_arima010| only reassesses |RelSumDelta| while @@ -93,8 +94,8 @@ class ForecastStep(sequencetools.StateSequence): class AveragedResidual(sequencetools.StateSequence): """The mean-value-based ARIMA residual (mean observed minus mean simulated - discharge over the |AveragingWindow| log entries immediately - preceding the current forecast run) in m³/s, determined once at the first + values over the |AveragingWindow| log entries immediately + preceding the current forecast run), determined once at the first forecast step and kept unchanged for the remainder of the forecast horizon.""" @@ -103,9 +104,9 @@ class AveragedResidual(sequencetools.StateSequence): class Residual(sequencetools.StateSequence): - """The pointwise ARIMA residual (observed minus simulated discharge, taken + """The pointwise ARIMA residual (observed minus simulated values, taken from the most recently logged entry with a non-|numpy.nan| observation, - searching back at most |MaxNaNSkip| entries) in m³/s. + searching back at most |MaxNaNSkip| entries). Like |Stationary|, |statcorr_arima010| only reassesses |Residual| while |Options.simulationmode| equals `historical`. @@ -120,7 +121,7 @@ class Residual(sequencetools.StateSequence): class ResidualAnchor(sequencetools.StateSequence): - """The simulated discharge (in m³/s) at the log position from which + """The simulated value at the log position from which |Residual| was determined. Frozen together with |Residual| while |Options.simulationmode| equals diff --git a/hydpy/models/statcorr_arima010.py b/hydpy/models/statcorr_arima010.py index 8f4526625a..4d6467d547 100644 --- a/hydpy/models/statcorr_arima010.py +++ b/hydpy/models/statcorr_arima010.py @@ -1,44 +1,44 @@ # pylint: disable=unused-wildcard-import """ -|statcorr_arima010| performs statistical output correction of discharge forecasts +|statcorr_arima010| performs statistical output correction of simulated values based on an ARIMA(0,1,0) error model. -The corrected discharge is derived from the most recently available residual -(observed minus simulated discharge). While |Options.simulationmode| equals +The corrected value is derived from the most recently available residual +(observed minus simulated values). While |Options.simulationmode| equals `historical`, this residual is (re)determined every step by searching back at most |MaxNaNSkip| log entries for the latest non-|numpy.nan| observation — this is the random-walk persistence of the error whenever the *current* observation is missing. When no observation is available within that range (or the entire log, whichever is smaller), no correction is applied. While |Options.simulationmode| equals `forecast`, this search is -not repeated: the residual (and the simulated discharge it was measured +not repeated: the residual (and the simulated value it was measured against) stays frozen at whatever the most recent `historical` assessment found, so the correction persists throughout the whole forecast horizon (subject only to |ReductionFactor|) instead of fading once that log entry ages past |MaxNaNSkip|. -How the residual is applied depends on how the current simulated discharge -compares to the simulated discharge at the point the residual was determined: +How the residual is applied depends on how the current simulated value +compares to the simulated value at the point the residual was determined: if it is higher, the residual is added unchanged (capped at |MaxAbsShift|); otherwise, it is applied as a percentage of that anchor value instead (capped at |MaxRelShift|), which keeps the correction from -overshooting or turning negative while the discharge recedes. See +overshooting or turning negative while the simulated values recede. See |Determine_OutputCorrection_V1| for the exact formulas. Setting |AveragingWindow| to a value greater than zero switches from that pointwise residual to a mean-value-based one (mean observed minus mean -simulated discharge over the given number of log entries immediately +simulated values over the given number of log entries immediately preceding the current forecast run), blended in linearly over |TransitionSteps| forecast steps to avoid a jump right where the forecast begins. See |Determine_OutputCorrection_V1| and |Calc_AveragedResidual_V1| for details. -Each |statcorr_arima010| instance is responsible for a specific discharge range +Each |statcorr_arima010| instance is responsible for a specific value range only, defined by |LowerLimit| and |UpperLimit|, and can be switched off completely -via |Active|. Optionally, |StationarityCheck| lets it fade out the correction under -instationary flow conditions, and |VariabilityCheck| lets it base the -mean-value-based residual on a separate averaging period under stationary flow -conditions. +via |Active| or restricted to one simulation mode via |CorrectionMode|. +Optionally, |StationarityCheck| lets it fade out the correction under instationary +conditions, and |VariabilityCheck| lets it base the mean-value-based residual on a +separate averaging period under stationary conditions. |statcorr_arima010| serves as a submodel for |statcorr| and complies with the |OutputCorrModel_V1| interface. @@ -48,7 +48,7 @@ |statcorr_arima010| determines the length of its internal log from its parameters (see |NmbLogEntries|) and resizes both the simulated and the - observed discharge log accordingly: + observed values log accordingly: >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() @@ -73,32 +73,32 @@ >>> derived.nmblogentries.update() >>> derived.nmblogentries nmblogentries(3) - >>> logs.loggedsimulateddischarge - loggedsimulateddischarge(nan, nan, nan) - >>> logs.loggedobserveddischarge - loggedobserveddischarge(nan, nan, nan) + >>> logs.loggedsimulatedvalue + loggedsimulatedvalue(nan, nan, nan) + >>> logs.loggedobservedvalue + loggedobservedvalue(nan, nan, nan) - Successive calls of |OutputCorrModel_V1.set_simulateddischarge| and - |OutputCorrModel_V1.set_observeddischarge| shift the previously buffered + Successive calls of |OutputCorrModel_V1.set_simulatedvalue| and + |OutputCorrModel_V1.set_observedvalue| shift the previously buffered values one position to the right and store the new value at position 0: - >>> model.set_simulateddischarge(2.0) - >>> model.set_observeddischarge(3.0) - >>> model.set_simulateddischarge(3.0) - >>> model.set_observeddischarge(4.0) - >>> model.set_simulateddischarge(5.0) + >>> model.set_simulatedvalue(2.0) + >>> model.set_observedvalue(3.0) + >>> model.set_simulatedvalue(3.0) + >>> model.set_observedvalue(4.0) + >>> model.set_simulatedvalue(5.0) >>> from numpy import nan - >>> model.set_observeddischarge(nan) - >>> logs.loggedsimulateddischarge - loggedsimulateddischarge(5.0, 3.0, 2.0) - >>> logs.loggedobserveddischarge - loggedobserveddischarge(nan, 4.0, 3.0) + >>> model.set_observedvalue(nan) + >>> logs.loggedsimulatedvalue + loggedsimulatedvalue(5.0, 3.0, 2.0) + >>> logs.loggedobservedvalue + loggedobservedvalue(nan, 4.0, 3.0) |OutputCorrModel_V1.determine_outputcorrection| computes the corrected - discharge from the random-walk residual (here taken from log position 1, + value from the random-walk residual (here taken from log position 1, since position 0 has no observation) and stores it internally; |OutputCorrModel_V1.is_active| confirms the submodel is responsible for the - current discharge, and |OutputCorrModel_V1.get_correctedoutput| returns the + current value, and |OutputCorrModel_V1.get_correctedoutput| returns the buffered value: >>> model.determine_outputcorrection(False) @@ -122,7 +122,7 @@ class Model(statcorr_model.Sub_OutputCorrModel, statcorrinterfaces.OutputCorrMod DOCNAME = modeltools.DocName( short="StatCorr-ARIMA010", - description="ARIMA(0,1,0) — random walk — output correction for discharge", + description="ARIMA(0,1,0) — random walk — output correction ", ) __HYDPY_ROOTMODEL__ = False @@ -131,8 +131,8 @@ class Model(statcorr_model.Sub_OutputCorrModel, statcorrinterfaces.OutputCorrMod RECEIVER_METHODS = () RUN_METHODS = () INTERFACE_METHODS = ( - statcorr_model.Set_SimulatedDischarge_V1, - statcorr_model.Set_ObservedDischarge_V1, + statcorr_model.Set_SimulatedValue_V1, + statcorr_model.Set_ObservedValue_V1, statcorr_model.Determine_OutputCorrection_V1, statcorr_model.Is_Active_V1, statcorr_model.Get_CorrectedOutput_V1, From 399e74768401d8ccca42618949a2d2af458af264 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Tue, 3 Nov 2026 13:11:12 +0100 Subject: [PATCH 24/43] Change unit of MaxRelShift from percent to fraction --- hydpy/models/statcorr/statcorr_control.py | 9 +++++--- hydpy/models/statcorr/statcorr_model.py | 27 +++++++++++------------ hydpy/models/statcorr_arima010.py | 4 ++-- hydpy/models/statcorr_main.py | 2 +- 4 files changed, 22 insertions(+), 20 deletions(-) diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index 488bb879a9..6b0b15ddbd 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -564,9 +564,12 @@ class MaxAbsShift(parametertools.Parameter): class MaxRelShift(parametertools.Parameter): - """The maximum relative shift (in %) applied when the current forecast value - is at or below the simulated value at the point the residual was - determined (see |Determine_OutputCorrection_V1|).""" + """The maximum relative shift applied when the current forecast value is at or + below the simulated value at the point the residual was determined (see + |Determine_OutputCorrection_V1|) [-]. + + |MaxRelShift| is a fraction, not a percentage. For example, a value of + ``0.1`` restricts the multiplicative correction to ±10 %.""" NDIM: Final[Literal[0]] = 0 TYPE: Final = float diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 5d7f192749..961171e418 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -97,7 +97,7 @@ class Calc_OutputCorr_V1(modeltools.Method): ... submodel.parameters.control.evaluationwindow(1) ... submodel.parameters.control.maxnanskip(3) ... submodel.parameters.control.maxabsshift(100.0) - ... submodel.parameters.control.maxrelshift(1000.0) + ... submodel.parameters.control.maxrelshift(10.0) ... submodel.parameters.control.averagingwindow(0) ... submodel.parameters.control.transitionsteps(0) ... submodel.parameters.control.stationaritycheck(False) @@ -616,14 +616,14 @@ class Determine_OutputCorrection_V1(modeltools.Method): * Otherwise (including :math:`sim_k \leq 0`, for which a relative shift would be undefined), it shifts :math:`sim_0` *multiplicatively* instead, - expressing the damped residual as a percentage of :math:`sim_k` and - capping that percentage at |MaxRelShift|: + expressing the damped residual as a fraction of :math:`sim_k` and + capping that fraction at |MaxRelShift|: :math:`q_{corr} = sim_0 \cdot \left(1 + \mathrm{clip}\left((obs_k - - sim_k) \cdot f_{red} / sim_k,\ \pm MaxRelShift / 100\right) + sim_k) \cdot f_{red} / sim_k,\ \pm MaxRelShift\right) \right)` - Applying the residual as a percentage rather than a constant offset + Applying the residual as a fraction rather than a constant offset keeps the correction from overshooting or turning negative while the forecasted values recede towards zero. @@ -732,7 +732,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> control.reductionsteps(2) >>> control.maxnanskip(3) >>> control.maxabsshift(100.0) - >>> control.maxrelshift(1000.0) + >>> control.maxrelshift(10.0) >>> control.averagingwindow(0) >>> control.transitionsteps(0) >>> states.reductionfactor(1.0) @@ -1016,8 +1016,8 @@ class Determine_OutputCorrection_V1(modeltools.Method): determined, so all examples above used the additive (or, at position 0 itself, an equivalent) shift. Resetting the log to a *receding* forecast — position 0 has already dropped clearly below the value at - the residual's log position — switches to the relative (percentage) - shift instead: + the residual's log position — switches to the relative + (multiplicative) shift instead: >>> logs.loggedsimulatedvalue = 2.0, 10.0, 10.0, nan, nan >>> logs.loggedobservedvalue = nan, 12.0, nan, nan, nan @@ -1025,10 +1025,10 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> fluxes.correctedq correctedq(2.4) - Limiting |MaxRelShift| caps that percentage before it is - converted back into an absolute shift: + Limiting |MaxRelShift| to ``0.1`` caps that fraction at 10 % before it + is converted back into an absolute shift: - >>> control.maxrelshift(10.0) + >>> control.maxrelshift(0.1) >>> model.determine_outputcorrection_v1(False) >>> fluxes.correctedq correctedq(2.2) @@ -1064,7 +1064,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> control.maxnanskip(4) >>> control.maxabsshift(100.0) - >>> control.maxrelshift(1000.0) + >>> control.maxrelshift(10.0) >>> control.averagingwindow(2) >>> control.transitionsteps(2) >>> derived.nmblogentries(4) @@ -1372,10 +1372,9 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: * (sta.averagedresidual - residual) ) damped_residual: float = effective_residual * sta.reductionfactor - max_fraction: float = con.maxrelshift / 100.0 shift: float = ( forecast_value - * min(max_fraction, max(-max_fraction, damped_residual / sim_anchor)) + * min(con.maxrelshift, max(-con.maxrelshift, damped_residual / sim_anchor)) if sim_anchor > 0.0 and forecast_value <= sim_anchor else min(con.maxabsshift, max(-con.maxabsshift, damped_residual)) ) diff --git a/hydpy/models/statcorr_arima010.py b/hydpy/models/statcorr_arima010.py index 4d6467d547..6277a1e408 100644 --- a/hydpy/models/statcorr_arima010.py +++ b/hydpy/models/statcorr_arima010.py @@ -20,7 +20,7 @@ How the residual is applied depends on how the current simulated value compares to the simulated value at the point the residual was determined: if it is higher, the residual is added unchanged (capped at -|MaxAbsShift|); otherwise, it is applied as a percentage of that anchor +|MaxAbsShift|); otherwise, it is applied relative to that anchor value instead (capped at |MaxRelShift|), which keeps the correction from overshooting or turning negative while the simulated values recede. See |Determine_OutputCorrection_V1| for the exact formulas. @@ -67,7 +67,7 @@ >>> control.reductionsteps(1) >>> control.maxnanskip(3) >>> control.maxabsshift(100.0) - >>> control.maxrelshift(1000.0) + >>> control.maxrelshift(10.0) >>> control.averagingwindow(0) >>> control.transitionsteps(0) >>> derived.nmblogentries.update() diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py index 8addfbfc32..508dd161ca 100644 --- a/hydpy/models/statcorr_main.py +++ b/hydpy/models/statcorr_main.py @@ -43,7 +43,7 @@ ... submodel.parameters.control.evaluationwindow(1) ... submodel.parameters.control.maxnanskip(3) ... submodel.parameters.control.maxabsshift(100.0) - ... submodel.parameters.control.maxrelshift(1000.0) + ... submodel.parameters.control.maxrelshift(10.0) ... submodel.parameters.control.averagingwindow(0) ... submodel.parameters.control.transitionsteps(0) ... submodel.parameters.control.stationaritycheck(False) From 513287e03b4e2d316a5b1acd643df89f021ad5e2 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Thu, 5 Nov 2026 06:26:55 +0100 Subject: [PATCH 25/43] Implement requested changes from review --- hydpy/conf/HydPyConfigBase.xsdt | 9 + hydpy/data/HydPy-H-Lahn/single_run.xml | 1 + hydpy/exe/xmltools.py | 1 + hydpy/models/statcorr/statcorr_control.py | 128 ++++---- hydpy/models/statcorr/statcorr_derived.py | 48 +-- hydpy/models/statcorr/statcorr_logs.py | 11 +- hydpy/models/statcorr/statcorr_model.py | 148 +++++---- hydpy/models/statcorr/statcorr_states.py | 11 +- hydpy/models/statcorr/statcorr_variables.py | 38 +++ hydpy/models/statcorr_arima010.py | 18 +- hydpy/models/statcorr_main.py | 313 +++++++++++++++++--- 11 files changed, 535 insertions(+), 191 deletions(-) create mode 100644 hydpy/models/statcorr/statcorr_variables.py diff --git a/hydpy/conf/HydPyConfigBase.xsdt b/hydpy/conf/HydPyConfigBase.xsdt index 979f27d388..0bc70d9c9c 100644 --- a/hydpy/conf/HydPyConfigBase.xsdt +++ b/hydpy/conf/HydPyConfigBase.xsdt @@ -44,6 +44,15 @@ + + + + + + + + diff --git a/hydpy/data/HydPy-H-Lahn/single_run.xml b/hydpy/data/HydPy-H-Lahn/single_run.xml index aa6a719c89..c850f04712 100644 --- a/hydpy/data/HydPy-H-Lahn/single_run.xml +++ b/hydpy/data/HydPy-H-Lahn/single_run.xml @@ -7,6 +7,7 @@ true 1d 6 + historical true false 60 diff --git a/hydpy/exe/xmltools.py b/hydpy/exe/xmltools.py index 3904815484..d2232d94dd 100644 --- a/hydpy/exe/xmltools.py +++ b/hydpy/exe/xmltools.py @@ -572,6 +572,7 @@ def update_options(self) -> None: >>> pub.options.parameterstep = "1h" >>> pub.options.printprogress = True >>> pub.options.reprdigits = -1 + >>> pub.options.simulationmode = "forecast" >>> pub.options.utcoffset = -60 >>> pub.options.threads = 4 >>> pub.options.timestampleft = False diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index 6b0b15ddbd..a7d5a41798 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -7,7 +7,7 @@ from hydpy.core.typingtools import * -class NmbSubmodels(parametertools.Parameter): +class NmbSubmodels(parametertools.NmbParameter): """The number of output correction submodels [-]. Setting |NmbSubmodels| automatically resizes the @@ -20,8 +20,6 @@ class NmbSubmodels(parametertools.Parameter): 3 """ - NDIM: Final[Literal[0]] = 0 - TYPE: Final = int SPAN = (0, None) def __call__(self, *args, **kwargs) -> None: @@ -30,16 +28,20 @@ def __call__(self, *args, **kwargs) -> None: class EvaluationWindow(parametertools.Parameter): - """The length of the time period for evaluating the current conditions.""" + """The length (in log entries) of the time period for evaluating the current + conditions [-].""" NDIM: Final[Literal[0]] = 0 TYPE: Final = int + SPAN = (1, None) class MaxNaNSkip(parametertools.Parameter): - """The maximum number of log entries to search back for the most recently - available residual when the current or recent observed values are - missing.""" + """The maximum number of log entries with missing observed values to skip + when searching back for the most recently available residual [-]. + + The search covers the current log entry and the |MaxNaNSkip| preceding ones. + A value of zero restricts the search to the current log entry.""" NDIM: Final[Literal[0]] = 0 TYPE: Final = int @@ -62,43 +64,34 @@ class CorrectionMode(parametertools.Parameter): """The simulation mode(s) in which the submodel may correct the simulated values [-]. - Pass one of the strings `historical`, `forecast`, or `both`, corresponding to - the possible values of |Options.simulationmode|. Internally, |CorrectionMode| - stores them as the integer values 1, 2, and 3: + Pass one of the options `historical`, `forecast`, or `both` (corresponding to + the possible values of |Options.simulationmode|) via the keyword argument + `option`. Internally, |CorrectionMode| stores them as the integer values 1, 2, + and 3: >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() >>> correctionmode correctionmode(?) - >>> correctionmode("historical") + >>> correctionmode(option="historical") >>> correctionmode - correctionmode("historical") + correctionmode(option="historical") >>> correctionmode.value 1 - >>> correctionmode("forecast") - >>> correctionmode - correctionmode("forecast") + >>> correctionmode(option="forecast") >>> correctionmode.value 2 - >>> correctionmode("both") - >>> correctionmode - correctionmode("both") + >>> correctionmode(option="both") >>> correctionmode.value 3 - Other strings are not allowed: + Other options are not allowed: - >>> correctionmode("always") + >>> correctionmode(option="always") Traceback (most recent call last): ... - ValueError: For parameter `correctionmode` of element `?`, the given mode \ -`always` is not among the supported modes `historical`, `forecast`, and `both`. - - Passing the integer values directly is also possible: - - >>> correctionmode(1) - >>> correctionmode - correctionmode("historical") + ValueError: Parameter `correctionmode` of element `?` supports the options \ +`historical`, `forecast`, and `both`, but `always` is given. Regardless of |CorrectionMode|, the submodel keeps updating its log and states in both simulation modes (see |Determine_OutputCorrection_V1|). @@ -108,26 +101,25 @@ class CorrectionMode(parametertools.Parameter): TYPE: Final = int SPAN = (1, 3) - MODES: Final = {"historical": 1, "forecast": 2, "both": 3} - - def __call__(self, *args, **kwargs) -> None: - if (len(args) == 1) and not kwargs and isinstance(args[0], str): - mode = args[0] - if mode not in self.MODES: - raise ValueError( - f"For parameter {objecttools.elementphrase(self)}, the given " - f"mode `{mode}` is not among the supported modes `historical`, " - f"`forecast`, and `both`." - ) - super().__call__(self.MODES[mode]) + def _set_option(self, *, option: str) -> dict[str, str]: + if option == "historical": + self.values = 1 + elif option == "forecast": + self.values = 2 + elif option == "both": + self.values = 3 else: - super().__call__(*args, **kwargs) + raise ValueError( + f"Parameter {objecttools.elementphrase(self)} supports the options " + f"`historical`, `forecast`, and `both`, but `{option}` is given." + ) + return {"option": option} - def __repr__(self) -> str: - for mode, value in self.MODES.items(): - if exceptiontools.getattr_(self, "value", None) == value: - return f'{self.name}("{mode}")' - return super().__repr__() + KEYWORDS = parametertools.KeywordGroups( + parametertools.KeywordGroup( + parametertools.Keyword("option", type_=str), setter=_set_option + ) + ) class LowerLimit(parametertools.Parameter): @@ -138,6 +130,23 @@ class LowerLimit(parametertools.Parameter): TYPE: Final = float SPAN = (0.0, None) + def trim(self, lower: TrimHook = None, upper: TrimHook = None) -> bool: + r"""Trim upper values in accordance with :math:`LowerLimit \leq UpperLimit`. + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> upperlimit.value = 2.0 + >>> lowerlimit(1.0) + >>> lowerlimit + lowerlimit(1.0) + >>> lowerlimit(3.0) + >>> lowerlimit + lowerlimit(2.0) + """ + if upper is None: + upper = exceptiontools.getattr_(self.subpars.upperlimit, "value", None) + return super().trim(lower, upper) + class UpperLimit(parametertools.Parameter): """Upper (exclusive) limit of the submodel's range of responsibility @@ -149,6 +158,23 @@ class UpperLimit(parametertools.Parameter): TYPE: Final = float SPAN = (0.0, None) + def trim(self, lower: TrimHook = None, upper: TrimHook = None) -> bool: + r"""Trim lower values in accordance with :math:`LowerLimit \leq UpperLimit`. + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> lowerlimit.value = 2.0 + >>> upperlimit(3.0) + >>> upperlimit + upperlimit(3.0) + >>> upperlimit(1.0) + >>> upperlimit + upperlimit(2.0) + """ + if lower is None: + lower = exceptiontools.getattr_(self.subpars.lowerlimit, "value", None) + return super().trim(lower, upper) + class StationarityCheck(parametertools.SpecialParameter): """Configuration of the check of whether the observed values behave in a @@ -579,11 +605,9 @@ class MaxRelShift(parametertools.Parameter): class AveragingWindow(parametertools.Parameter): """The length (in log entries) of the averaging period immediately preceding the current forecast run, used to determine the mean-value-based - ARIMA residual (see |Determine_OutputCorrection_V1|). Set to zero to + ARIMA residual (see |Determine_OutputCorrection_V1|) [-]. Set to zero to disable mean-value-based correction and rely on the single most recent - (pointwise) residual only, as |Determine_OutputCorrection_V1| already did - before |AveragingWindow| and |TransitionSteps| were - introduced.""" + (pointwise) residual only.""" NDIM: Final[Literal[0]] = 0 TYPE: Final = int @@ -594,7 +618,7 @@ class TransitionSteps(parametertools.Parameter): """The number of forecast steps over which the applied residual transitions linearly from the single most recent (pointwise) residual to the mean-value-based residual determined via |AveragingWindow|, - avoiding an abrupt jump right at the start of the forecast horizon.""" + avoiding an abrupt jump right at the start of the forecast horizon [-].""" NDIM: Final[Literal[0]] = 0 TYPE: Final = int @@ -605,7 +629,7 @@ class Propagate(parametertools.Parameter): """Flag determining whether the corrected discharge is passed on to the downstream network (|True|) or calculated only for local output at the current gauge, while the uncorrected inflow is passed on instead - (|False|).""" + (|False|) [-].""" NDIM: Final[Literal[0]] = 0 TYPE: Final = bool diff --git a/hydpy/models/statcorr/statcorr_derived.py b/hydpy/models/statcorr/statcorr_derived.py index 15e2efcf73..1aa7de4267 100644 --- a/hydpy/models/statcorr/statcorr_derived.py +++ b/hydpy/models/statcorr/statcorr_derived.py @@ -34,12 +34,26 @@ def update(self) -> None: self(hydpy.pub.options.simulationmode == "forecast") -class NmbLogEntries(parametertools.Parameter): +class NmbLogEntries(parametertools.NmbParameter): """The number of log entries required for memorising the simulated and observed - values [-].""" + values [-]. + + Besides setting the shape of all log sequences (see |MixinLogEntries|), + |NmbLogEntries| resets all state sequences to their initial values whenever its + value changes, as the latter depend on the logged data: + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> derived.nmblogentries(2) + >>> states.residual(2.0) + >>> derived.nmblogentries(2) + >>> states.residual + residual(2.0) + >>> derived.nmblogentries(3) + >>> states.residual + residual(0.0) + """ - NDIM: Final[Literal[0]] = 0 - TYPE: Final = int SPAN = (1, None) CONTROLPARAMETERS = ( statcorr_control.EvaluationWindow, @@ -54,8 +68,8 @@ def update(self) -> None: parameters and adjust the shape of all log sequences. The log must cover the |EvaluationWindow|, the assessment period of the - stationarity check (see |StationarityCheck|), and the |MaxNaNSkip| most - recent entries. The mean-value-based residual (see + stationarity check (see |StationarityCheck|), and the current entry plus the + |MaxNaNSkip| preceding ones. The mean-value-based residual (see |Calc_AveragedResidual_V1|) relies on the |AveragingWindow| (or the averaging period of the variability check, see |VariabilityCheck|) entries preceding the current one, which requires one additional entry. @@ -68,7 +82,7 @@ def update(self) -> None: >>> evaluationwindow(3) >>> stationaritycheck(window=4, ratiominmax=0.5) >>> variabilitycheck(False) - >>> maxnanskip(2) + >>> maxnanskip(1) >>> derived.nmblogentries.update() >>> derived.nmblogentries nmblogentries(?) @@ -85,7 +99,7 @@ def update(self) -> None: nmblogentries(6) >>> variabilitycheck(False) - >>> maxnanskip(7) + >>> maxnanskip(6) >>> derived.nmblogentries.update() >>> derived.nmblogentries nmblogentries(7) @@ -147,21 +161,17 @@ def update(self) -> None: nmb = max( control.evaluationwindow.value, stationaritycheck.window, - control.maxnanskip.value, + control.maxnanskip.value + 1, control.averagingwindow.value + 1, variabilitycheck.averagingwindow + 1, ) self(nmb) - nmb = int(self.value) - sequences = self.subpars.pars.model.sequences - resized = False - for seq in sequences.logs: - shape = exceptiontools.getattr_(seq, "shape", (None,)) - if nmb != shape[-1]: - seq.shape = nmb - resized = True - if resized: - for state in sequences.states: + + def __call__(self, *args, **kwargs) -> None: + old = exceptiontools.getattr_(self, "value", None) + super().__call__(*args, **kwargs) + if self.value != old: + for state in self.subpars.pars.model.sequences.states: state(state.INIT) diff --git a/hydpy/models/statcorr/statcorr_logs.py b/hydpy/models/statcorr/statcorr_logs.py index 41885c64e5..3b7b813a34 100644 --- a/hydpy/models/statcorr/statcorr_logs.py +++ b/hydpy/models/statcorr/statcorr_logs.py @@ -2,15 +2,20 @@ from hydpy.core import sequencetools from hydpy.core.typingtools import * +from hydpy.models.statcorr import statcorr_variables -class LoggedObservedValue(sequencetools.LogSequence): - """Logged observed values [unit of the corrected variable]""" +class LoggedObservedValue( + statcorr_variables.MixinLogEntries, sequencetools.LogSequence +): + """Logged observed values [unit of the corrected variable].""" NDIM: Final[Literal[1]] = 1 -class LoggedSimulatedValue(sequencetools.LogSequence): +class LoggedSimulatedValue( + statcorr_variables.MixinLogEntries, sequencetools.LogSequence +): """Logged simulated values [unit of the corrected variable].""" NDIM: Final[Literal[1]] = 1 diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 961171e418..e5de76c90a 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -91,11 +91,11 @@ class Calc_OutputCorr_V1(modeltools.Method): >>> from numpy import inf >>> def configure(submodel, lowerlimit=0.0, upperlimit=inf): ... submodel.parameters.control.active(True) - ... submodel.parameters.control.correctionmode("both") + ... submodel.parameters.control.correctionmode(option="both") ... submodel.parameters.control.lowerlimit(lowerlimit) ... submodel.parameters.control.upperlimit(upperlimit) ... submodel.parameters.control.evaluationwindow(1) - ... submodel.parameters.control.maxnanskip(3) + ... submodel.parameters.control.maxnanskip(2) ... submodel.parameters.control.maxabsshift(100.0) ... submodel.parameters.control.maxrelshift(10.0) ... submodel.parameters.control.averagingwindow(0) @@ -224,9 +224,10 @@ class Calc_OutputCorr_V1(modeltools.Method): correctedq(4.5) Even once the last real observation drops out of the submodel's log - (three entries due to |MaxNaNSkip|), the persisted residual keeps - applying without limit -- only |ReductionFactor| (via |StationarityCheck| - and |ReductionSteps|, disabled here) could still fade it out: + (the current entry plus the two preceding ones due to |MaxNaNSkip|), the + persisted residual keeps applying without limit -- only |ReductionFactor| + (via |StationarityCheck| and |ReductionSteps|, disabled here) could still + fade it out: >>> with pub.options.simulationmode("forecast"): ... model.parameters.update() @@ -365,7 +366,7 @@ def add_outputcorrmodel_v1( ... evaluationwindow(2) ... stationaritycheck(window=4, ratiominmax=0.5) ... variabilitycheck(False) - ... maxnanskip(3) + ... maxnanskip(2) ... averagingwindow(0) >>> model.outputcorrmodels[0].parameters.derived.nmblogentries nmblogentries(4) @@ -384,7 +385,6 @@ class Set_SimulatedValue_V1(modeltools.Method): >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() >>> derived.nmblogentries(3) - >>> logs.loggedsimulatedvalue.shape = 3 >>> logs.loggedsimulatedvalue = 4.0, 3.0, 2.0 >>> model.set_simulatedvalue_v1(5.0) >>> logs.loggedsimulatedvalue @@ -415,7 +415,6 @@ class Set_ObservedValue_V1(modeltools.Method): >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() >>> derived.nmblogentries(3) - >>> logs.loggedobservedvalue.shape = 3 >>> logs.loggedobservedvalue = 4.0, 3.0, 2.0 >>> from numpy import nan >>> model.set_observedvalue_v1(nan) @@ -463,8 +462,6 @@ class Calc_AveragedResidual_V1(modeltools.Method): >>> derived.stationaryaveragingwindow(1) >>> states.lowvariability(0.0) >>> derived.nmblogentries(3) - >>> logs.loggedsimulatedvalue.shape = 3 - >>> logs.loggedobservedvalue.shape = 3 >>> logs.loggedsimulatedvalue = 3.0, 2.0, 4.0 >>> logs.loggedobservedvalue = nan, 3.0, 5.0 @@ -591,10 +588,11 @@ class Determine_OutputCorrection_V1(modeltools.Method): The correction is derived from the most recently available residual (observed minus simulated values). While |Options.simulationmode| equals `historical`, the "most recent" residual is taken from the latest - log entry where the observed value is not |numpy.nan|, searching back - at most |MaxNaNSkip| log entries (or the entire log, whichever is - smaller), and remembered in |Residual| (together with the corresponding - simulated value in |ResidualAnchor|). When no observation is + log entry where the observed value is not |numpy.nan|, skipping at + most |MaxNaNSkip| preceding log entries with missing observations (or + searching the entire log, whichever is smaller), and remembered in + |Residual| (together with the corresponding simulated value in + |ResidualAnchor|). When no observation is available within that range, both are set to zero, so the corrected value equals the current simulated value. While |Options.simulationmode| equals `forecast`, |Determine_OutputCorrection_V1| @@ -607,17 +605,17 @@ class Determine_OutputCorrection_V1(modeltools.Method): with :math:`k` denoting the most recent log index for which :math:`obs_k \neq \mathrm{nan}`, and :math:`f_{red}` denoting |ReductionFactor|): - * If :math:`sim_0 > sim_k` (and :math:`sim_k > 0`), - |Determine_OutputCorrection_V1| shifts :math:`sim_0` *additively* by the - |ReductionFactor|-damped residual, capped at |MaxAbsShift|: + * If :math:`sim_0 > sim_k` or :math:`sim_k \leq 0` (for which a relative + shift would be undefined), |Determine_OutputCorrection_V1| shifts + :math:`sim_0` *additively* by the |ReductionFactor|-damped residual, capped + at |MaxAbsShift|: :math:`q_{corr} = sim_0 + \mathrm{clip}\left((obs_k - sim_k) \cdot f_{red},\ \pm MaxAbsShift\right)` - * Otherwise (including :math:`sim_k \leq 0`, for which a relative shift - would be undefined), it shifts :math:`sim_0` *multiplicatively* instead, - expressing the damped residual as a fraction of :math:`sim_k` and - capping that fraction at |MaxRelShift|: + * Otherwise (:math:`0 < sim_0 \leq sim_k`), it shifts :math:`sim_0` + *multiplicatively* instead, expressing the damped residual as a fraction + of :math:`sim_k` and capping that fraction at |MaxRelShift|: :math:`q_{corr} = sim_0 \cdot \left(1 + \mathrm{clip}\left((obs_k - sim_k) \cdot f_{red} / sim_k,\ \pm MaxRelShift\right) @@ -629,7 +627,8 @@ class Determine_OutputCorrection_V1(modeltools.Method): The residual (:math:`obs_k - sim_k` above) used in either branch is not necessarily the pointwise one. Setting |AveragingWindow| to a - value greater than zero switches to a mean-value-based residual instead — + value greater than zero switches to a mean-value-based residual during + forecast runs (`historical` runs always rely on the pointwise residual) — the difference between the mean observed and the mean simulated values over that many log entries immediately preceding the current forecast run (determined once, at the first forecast step, via @@ -643,7 +642,6 @@ class Determine_OutputCorrection_V1(modeltools.Method): linearly blends it towards the mean-value-based residual over |TransitionSteps| forecast steps, applying the mean-value-based residual unabated from then on. Setting |AveragingWindow| to zero - (the default behaviour before mean-value-based correction was introduced) disables this mechanism entirely, relying on the pointwise residual alone, as described above. @@ -655,10 +653,12 @@ class Determine_OutputCorrection_V1(modeltools.Method): conditions instationary and linearly reduces |ReductionFactor| (the factor :math:`f_{red}` in the equation above) towards zero, taking as many steps as given by |ReductionSteps|. As soon as the ratio reaches - |RatioMinMax| again (or a |numpy.nan| value prevents its calculation), - |ReductionFactor| jumps back to ``1.0``, applying the correction unabated - again. With the stationarity check disabled, |ReductionFactor| is always - ``1.0``. + |RatioMinMax| again, |ReductionFactor| jumps back to ``1.0``, applying the + correction unabated again. If a |numpy.nan| value within the + |StationarityWindow| prevents calculating the ratio, it keeps the outcome of + the previous assessment (|Stationary|), so that a single missing observation + neither interrupts an ongoing reduction nor triggers a new one. With the + stationarity check disabled, |ReductionFactor| is always ``1.0``. |Determine_OutputCorrection_V1| only *reassesses* stationarity (the ratio-based check described above) while |Options.simulationmode| equals @@ -667,11 +667,12 @@ class Determine_OutputCorrection_V1(modeltools.Method): most recent `historical` assessment instead of recomputing it — recomputing would be unreliable anyway, since |LoggedObservedValue| keeps receiving |numpy.nan| values throughout the forecast (see - |Calc_OutputCorr_V1|), which the ratio-based check always interprets as - "stationary". So, once a `historical` run has flagged conditions as - instationary, |ReductionFactor| keeps ramping towards zero (or staying at - ``0.0``) for the entire forecast horizon instead of jumping back to ``1.0`` - as soon as the last real observation drops out of the logging window. + |Calc_OutputCorr_V1|), which would prevent any new assessment as soon as + the first of them enters the |StationarityWindow|. So, once a `historical` + run has flagged conditions as instationary, |ReductionFactor| keeps ramping + towards zero (or staying at ``0.0``) for the entire forecast horizon instead + of jumping back to ``1.0`` as soon as the last real observation drops out of + the logging window. If enabled via |VariabilityCheck|, |Determine_OutputCorrection_V1| additionally assesses how much the simulated values vary. It sums the @@ -720,7 +721,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> derived.nmblogentries(3) >>> control.evaluationwindow(3) >>> control.active(True) - >>> control.correctionmode("both") + >>> control.correctionmode(option="both") >>> control.lowerlimit(0.0) >>> control.upperlimit(inf) >>> control.stationaritycheck(window=3, ratiominmax=0.5) @@ -730,15 +731,13 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> derived.maxrelsumdelta.update() >>> derived.stationaryaveragingwindow.update() >>> control.reductionsteps(2) - >>> control.maxnanskip(3) + >>> control.maxnanskip(2) >>> control.maxabsshift(100.0) >>> control.maxrelshift(10.0) >>> control.averagingwindow(0) >>> control.transitionsteps(0) >>> states.reductionfactor(1.0) >>> states.stationary(1.0) - >>> logs.loggedsimulatedvalue.shape = 3 - >>> logs.loggedobservedvalue.shape = 3 >>> logs.loggedsimulatedvalue = 5.0, 3.0, 2.0 >>> logs.loggedobservedvalue = 6.0, 4.0, 3.0 >>> model.determine_outputcorrection_v1(False) @@ -793,7 +792,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): mode: >>> control.active(True) - >>> control.correctionmode("forecast") + >>> control.correctionmode(option="forecast") >>> model.determine_outputcorrection_v1(False) >>> fluxes.isactive isactive(0.0) @@ -802,7 +801,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): With `historical`, it does: - >>> control.correctionmode("historical") + >>> control.correctionmode(option="historical") >>> model.determine_outputcorrection_v1(False) >>> fluxes.isactive isactive(1.0) @@ -817,19 +816,19 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> fluxes.correctedq correctedq(3.0) - >>> control.correctionmode("forecast") + >>> control.correctionmode(option="forecast") >>> model.determine_outputcorrection_v1(True) >>> fluxes.isactive isactive(1.0) >>> fluxes.correctedq correctedq(4.0) - >>> control.correctionmode("both") + >>> control.correctionmode(option="both") The two most recent observations are missing, so the residual is taken from the third log entry and added to the current simulated value. Missing observations also make it impossible to assess stationarity, so - |Determine_OutputCorrection_V1| assumes stationary conditions and leaves - |ReductionFactor| untouched: + |Determine_OutputCorrection_V1| keeps the previous assessment (here, the + initial stationary conditions) and leaves |ReductionFactor| untouched: >>> control.active(True) >>> control.lowerlimit(0.0) @@ -867,6 +866,20 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> fluxes.correctedq correctedq(1.0) + A single missing observation within the |StationarityWindow| does not + reset |ReductionFactor|. Instead, |Determine_OutputCorrection_V1| keeps + the previous assessment, so the conditions remain instationary: + + >>> logs.loggedobservedvalue = 0.5, nan, 5.0 + >>> model.determine_outputcorrection_v1(False) + >>> states.stationary + stationary(0.0) + >>> states.reductionfactor + reductionfactor(0.0) + >>> fluxes.correctedq + correctedq(1.0) + >>> logs.loggedobservedvalue = 0.5, 5.0, 5.0 + Disabling the stationarity check resets |ReductionFactor| to ``1.0`` regardless of the (still instationary) observed values: @@ -979,8 +992,6 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> control.upperlimit(inf) >>> states.reductionfactor(1.0) >>> derived.nmblogentries(5) - >>> logs.loggedsimulatedvalue.shape = 5 - >>> logs.loggedobservedvalue.shape = 5 >>> logs.loggedsimulatedvalue = 1.0, 1.0, 1.0, nan, nan >>> logs.loggedobservedvalue = 0.5, 5.0, 5.0, nan, nan >>> model.determine_outputcorrection_v1(False) @@ -991,12 +1002,16 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> states.reductionfactor reductionfactor(0.5) - Restricting |MaxNaNSkip| to fewer entries than the full log + Restricting |MaxNaNSkip| so that the search does not cover the full log makes |Determine_OutputCorrection_V1| stop searching for a valid residual once that limit is reached, applying no correction even - though an older, still-logged observation would otherwise be usable: + though an older, still-logged observation would otherwise be usable. + The following examples contain missing observations, which prevent a + new stationarity assessment. To focus on the residual search, we reset + |Stationary| to ``1.0`` so that |ReductionFactor| returns to ``1.0``: - >>> control.maxnanskip(2) + >>> states.stationary(1.0) + >>> control.maxnanskip(1) >>> logs.loggedsimulatedvalue = 1.0, 1.0, 1.0, nan, nan >>> logs.loggedobservedvalue = nan, nan, 3.0, nan, nan >>> model.determine_outputcorrection_v1(False) @@ -1006,7 +1021,7 @@ class Determine_OutputCorrection_V1(modeltools.Method): Enlarging |MaxNaNSkip| to reach that entry again reinstates the correction: - >>> control.maxnanskip(3) + >>> control.maxnanskip(2) >>> model.determine_outputcorrection_v1(False) >>> fluxes.correctedq correctedq(3.0) @@ -1062,14 +1077,12 @@ class Determine_OutputCorrection_V1(modeltools.Method): deriving them from a preceding `historical` call) to keep the focus on the transition mechanism: - >>> control.maxnanskip(4) + >>> control.maxnanskip(3) >>> control.maxabsshift(100.0) >>> control.maxrelshift(10.0) >>> control.averagingwindow(2) >>> control.transitionsteps(2) >>> derived.nmblogentries(4) - >>> logs.loggedsimulatedvalue.shape = 4 - >>> logs.loggedobservedvalue.shape = 4 >>> states.evaluatedvalue(8.0) >>> states.stationary(1.0) >>> states.reductionfactor(1.0) @@ -1112,6 +1125,22 @@ class Determine_OutputCorrection_V1(modeltools.Method): >>> fluxes.correctedq correctedq(14.5) + The mean-value-based residual only applies to forecast runs. During + `historical` runs, |Determine_OutputCorrection_V1| always relies on the + pointwise residual, so that the corrected value reproduces the current + observation even if |TransitionSteps| is zero (which would otherwise + apply the mean-value-based residual unabated): + + >>> control.transitionsteps(0) + >>> logs.loggedsimulatedvalue = 1.0, 2.0, 4.0, 6.0 + >>> logs.loggedobservedvalue = 5.0, 3.0, 4.0, 6.0 + >>> model.determine_outputcorrection_v1(False) + >>> states.averagedresidual + averagedresidual(2.5) + >>> fluxes.correctedq + correctedq(5.0) + >>> control.transitionsteps(2) + Next, we enable the variability check. In the following `historical` call, the absolute changes of the simulated values within the |EvaluationWindow| sum up to ``2.0``, which is 20 % of their mean value @@ -1295,7 +1324,7 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: else: residual = 0.0 sim_anchor = 0.0 - for idx in range(min(der.nmblogentries, con.maxnanskip)): + for idx in range(min(der.nmblogentries, con.maxnanskip + 1)): if not modelutils.isnan(log.loggedobservedvalue[idx]): sim_anchor = log.loggedsimulatedvalue[idx] residual = log.loggedobservedvalue[idx] - sim_anchor @@ -1308,7 +1337,6 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: else: if not isforecastmode: nmb = min(der.nmblogentries, der.stationaritywindow) - stationary = True has_nan = False qmin: float = modelutils.inf qmax: float = -modelutils.inf @@ -1319,9 +1347,11 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: break qmin = min(qmin, value) qmax = max(qmax, value) - if not has_nan and qmax > 0.0: - stationary = qmin / qmax >= der.ratiominmax - sta.stationary = 1.0 if stationary else 0.0 + if not has_nan: + if qmax > 0.0 and qmin / qmax < der.ratiominmax: + sta.stationary = 0.0 + else: + sta.stationary = 1.0 if sta.stationary: sta.reductionfactor = 1.0 @@ -1353,7 +1383,8 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: forecast_step: float = sta.forecaststep if isforecastmode else 0.0 sta.forecaststep = (forecast_step + 1.0) if isforecastmode else 0.0 - model.calc_averagedresidual_v1(forecast_step, residual) + if isforecastmode: + model.calc_averagedresidual_v1(forecast_step, residual) forecast_value: float = log.loggedsimulatedvalue[0] if flu.isactive == 0.0: @@ -1362,7 +1393,8 @@ def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: effective_residual: float = ( residual - if con.averagingwindow <= 0 and sta.lowvariability == 0.0 + if not isforecastmode + or (con.averagingwindow <= 0 and sta.lowvariability == 0.0) else residual + ( 1.0 diff --git a/hydpy/models/statcorr/statcorr_states.py b/hydpy/models/statcorr/statcorr_states.py index 46c4db34a5..71aa7fc9f7 100644 --- a/hydpy/models/statcorr/statcorr_states.py +++ b/hydpy/models/statcorr/statcorr_states.py @@ -26,7 +26,9 @@ class Stationary(sequencetools.StateSequence): determined at the most recent `historical` assessment, so |ReductionFactor| keeps ramping towards zero (or stays at ``1.0``) throughout the whole forecast horizon instead of jumping back to ``1.0`` once the logged observations run - out.""" + out. Also in `historical` mode, a |numpy.nan| value within the + |StationarityWindow| prevents a new assessment, so |Stationary| keeps its + previous value.""" NDIM: Final[Literal[0]] = 0 SPAN = (0.0, 1.0) @@ -97,7 +99,7 @@ class AveragedResidual(sequencetools.StateSequence): values over the |AveragingWindow| log entries immediately preceding the current forecast run), determined once at the first forecast step and kept unchanged for the remainder of the forecast - horizon.""" + horizon [unit of the corrected variable].""" NDIM: Final[Literal[0]] = 0 INIT = 0.0 @@ -106,7 +108,8 @@ class AveragedResidual(sequencetools.StateSequence): class Residual(sequencetools.StateSequence): """The pointwise ARIMA residual (observed minus simulated values, taken from the most recently logged entry with a non-|numpy.nan| observation, - searching back at most |MaxNaNSkip| entries). + skipping at most |MaxNaNSkip| entries with missing observations) + [unit of the corrected variable]. Like |Stationary|, |statcorr_arima010| only reassesses |Residual| while |Options.simulationmode| equals `historical`. @@ -122,7 +125,7 @@ class Residual(sequencetools.StateSequence): class ResidualAnchor(sequencetools.StateSequence): """The simulated value at the log position from which - |Residual| was determined. + |Residual| was determined [unit of the corrected variable]. Frozen together with |Residual| while |Options.simulationmode| equals `forecast`; see |Residual| for details.""" diff --git a/hydpy/models/statcorr/statcorr_variables.py b/hydpy/models/statcorr/statcorr_variables.py new file mode 100644 index 0000000000..a6c23cfb43 --- /dev/null +++ b/hydpy/models/statcorr/statcorr_variables.py @@ -0,0 +1,38 @@ +# pylint: disable=missing-module-docstring + +import abc + +from hydpy.core import parametertools +from hydpy.core import variabletools + + +class MixinLogEntries(variabletools.Variable, abc.ABC): + """Mixin class for 1-dimensional log sequences whose shape depends on the value of + parameter |NmbLogEntries|. + + We take the log sequence |LoggedObservedValue| as an example: + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> derived.nmblogentries(3) + >>> logs.loggedobservedvalue + loggedobservedvalue(nan, nan, nan) + + To prevent losing information, updating parameter |NmbLogEntries| resets the + shape only when necessary: + + >>> logs.loggedobservedvalue = 1.0 + >>> derived.nmblogentries(3) + >>> logs.loggedobservedvalue + loggedobservedvalue(1.0, 1.0, 1.0) + >>> derived.nmblogentries(2) + >>> logs.loggedobservedvalue + loggedobservedvalue(nan, nan) + """ + + def __hydpy__let_par_set_shape__(self, p: parametertools.NmbParameter, /) -> None: + # pylint: disable=import-outside-toplevel + from hydpy.models.statcorr import statcorr_derived + + if isinstance(p, statcorr_derived.NmbLogEntries): + self.__hydpy__change_shape_if_necessary__((p.value,)) diff --git a/hydpy/models/statcorr_arima010.py b/hydpy/models/statcorr_arima010.py index 6277a1e408..827b955801 100644 --- a/hydpy/models/statcorr_arima010.py +++ b/hydpy/models/statcorr_arima010.py @@ -5,22 +5,22 @@ The corrected value is derived from the most recently available residual (observed minus simulated values). While |Options.simulationmode| equals -`historical`, this residual is (re)determined every step by searching back at -most |MaxNaNSkip| log entries for the latest non-|numpy.nan| -observation — this is the random-walk persistence of the error whenever the -*current* observation is missing. When no observation is available within +`historical`, this residual is (re)determined every step by skipping at most +|MaxNaNSkip| log entries with missing observations to find the latest +non-|numpy.nan| observation — this is the random-walk persistence of the error +whenever the *current* observation is missing. When no observation is available within that range (or the entire log, whichever is smaller), no correction is applied. While |Options.simulationmode| equals `forecast`, this search is not repeated: the residual (and the simulated value it was measured against) stays frozen at whatever the most recent `historical` assessment found, so the correction persists throughout the whole forecast horizon (subject only to |ReductionFactor|) instead of fading once that log entry -ages past |MaxNaNSkip|. +lies more than |MaxNaNSkip| entries back. How the residual is applied depends on how the current simulated value compares to the simulated value at the point the residual was determined: -if it is higher, the residual is added unchanged (capped at -|MaxAbsShift|); otherwise, it is applied relative to that anchor +if it is higher (or the anchor value is not positive), the residual is added +unchanged (capped at |MaxAbsShift|); otherwise, it is applied relative to that anchor value instead (capped at |MaxRelShift|), which keeps the correction from overshooting or turning negative while the simulated values recede. See |Determine_OutputCorrection_V1| for the exact formulas. @@ -54,7 +54,7 @@ >>> parameterstep() >>> from numpy import inf >>> control.active(True) - >>> control.correctionmode("both") + >>> control.correctionmode(option="both") >>> control.lowerlimit(0.0) >>> control.upperlimit(inf) >>> control.evaluationwindow(3) @@ -65,7 +65,7 @@ >>> derived.maxrelsumdelta.update() >>> derived.stationaryaveragingwindow.update() >>> control.reductionsteps(1) - >>> control.maxnanskip(3) + >>> control.maxnanskip(2) >>> control.maxabsshift(100.0) >>> control.maxrelshift(10.0) >>> control.averagingwindow(0) diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py index 508dd161ca..89e01d8bde 100644 --- a/hydpy/models/statcorr_main.py +++ b/hydpy/models/statcorr_main.py @@ -5,15 +5,15 @@ |OutputCorrModel_V1| submodels (e.g. |statcorr_arima010|), and delivers the corrected discharge to the outlet node. -Integration test -================ +Integration tests +================= .. how_to_understand_integration_tests:: - We prepare a simulation period of six days: + We prepare a simulation period of ten days: >>> from hydpy import pub - >>> pub.timegrids = "2000-01-01", "2000-01-07", "1d" + >>> pub.timegrids = "2000-01-01", "2000-01-11", "1d" >>> from hydpy.models.statcorr_main import * >>> parameterstep() @@ -23,61 +23,282 @@ >>> from hydpy import Element, IntegrationTest >>> element = Element("element", inlets="inlet", outlets="outlet") >>> element.model = model + >>> propagate(True) + >>> test = IntegrationTest(element) + >>> test.dateformat = "%d/%m" - We attach a single |statcorr_arima010| submodel, which is responsible for all + The following function configures a |statcorr_arima010| submodel with the + settings shared by all examples. It makes the submodel responsible for all discharges (its |EvaluationWindow| of one step means it assesses its - responsibility based on the current simulated discharge only). We disable the - stationarity check via |StationarityCheck| and the variability check via - |VariabilityCheck|, so the ARIMA correction always applies unabated: + responsibility based on the current simulated discharge only) and disables the + stationarity check via |StationarityCheck|, the variability check via + |VariabilityCheck|, and the mean-value-based residual via |AveragingWindow|, so + the ARIMA correction always applies unabated. The individual examples + override some of these settings: - >>> from numpy import inf - >>> nmbsubmodels(1) - >>> propagate(True) - >>> with model.add_outputcorrmodel_v1( - ... "statcorr_arima010", position=0 - ... ) as submodel: - ... submodel.parameters.control.active(True) - ... submodel.parameters.control.correctionmode("both") - ... submodel.parameters.control.lowerlimit(0.0) - ... submodel.parameters.control.upperlimit(inf) - ... submodel.parameters.control.evaluationwindow(1) - ... submodel.parameters.control.maxnanskip(3) - ... submodel.parameters.control.maxabsshift(100.0) - ... submodel.parameters.control.maxrelshift(10.0) - ... submodel.parameters.control.averagingwindow(0) - ... submodel.parameters.control.transitionsteps(0) - ... submodel.parameters.control.stationaritycheck(False) - ... submodel.parameters.control.variabilitycheck(False) - ... submodel.parameters.control.reductionsteps(1) + >>> from numpy import inf, nan + >>> def configure(submodel): + ... control = submodel.parameters.control + ... control.active(True) + ... control.correctionmode(option="both") + ... control.lowerlimit(0.0) + ... control.upperlimit(inf) + ... control.evaluationwindow(1) + ... control.maxnanskip(2) + ... control.maxabsshift(100.0) + ... control.maxrelshift(10.0) + ... control.averagingwindow(0) + ... control.transitionsteps(0) + ... control.stationaritycheck(False) + ... control.variabilitycheck(False) + ... control.reductionsteps(1) - >>> test = IntegrationTest(element) + The inlet provides the simulated discharge; |Discharge| carries the + observations. + +Historical simulation +_____________________ - The inlet provides the simulated discharge; |Discharge| carries the observations. - Observations are available for the first two steps only, simulating a forecast - period starting on day three: + We attach a single submodel: - >>> from numpy import nan - >>> element.inlets.inlet.sequences.sim.series = 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 + >>> nmbsubmodels(1) + >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0) as sub: + ... configure(sub) + + In the first example, the complete simulation period runs in `historical` + mode. Observations are available for the first two days only: + + >>> element.inlets.inlet.sequences.sim.series = range(1, 11) >>> with pub.options.checkseries(False): - ... inputs.discharge.series = 1.5, 2.5, nan, nan, nan, nan + ... inputs.discharge.series = 1.5, 2.5, nan, nan, nan, nan, nan, nan, nan, nan During the first two steps the correction is based on the concurrent residual - (``0.5``). In the forecast period the model falls back to the most recent - available residual, which stays at ``0.5`` until it lies more than - |MaxNaNSkip| entries back on day five, after which no correction is applied: + (``0.5``). Afterwards, the model falls back to the most recent available + residual, which stays at ``0.5`` until it lies more than |MaxNaNSkip| entries + back on day five, after which no correction is applied: .. integration-test:: - >>> test.dateformat = '%d/%m %H:00' >>> test() - | date | discharge | inflow | correctedq | inlet | outlet | - ------------------------------------------------------------------ - | 01/01 00:00 | 1.5 | 1.0 | 1.5 | 1.0 | 1.5 | - | 02/01 00:00 | 2.5 | 2.0 | 2.5 | 2.0 | 2.5 | - | 03/01 00:00 | nan | 3.0 | 3.5 | 3.0 | 3.5 | - | 04/01 00:00 | nan | 4.0 | 4.5 | 4.0 | 4.5 | - | 05/01 00:00 | nan | 5.0 | 5.0 | 5.0 | 5.0 | - | 06/01 00:00 | nan | 6.0 | 6.0 | 6.0 | 6.0 | + | date | discharge | inflow | correctedq | inlet | outlet | + ------------------------------------------------------------ + | 01/01 | 1.5 | 1.0 | 1.5 | 1.0 | 1.5 | + | 02/01 | 2.5 | 2.0 | 2.5 | 2.0 | 2.5 | + | 03/01 | nan | 3.0 | 3.5 | 3.0 | 3.5 | + | 04/01 | nan | 4.0 | 4.5 | 4.0 | 4.5 | + | 05/01 | nan | 5.0 | 5.0 | 5.0 | 5.0 | + | 06/01 | nan | 6.0 | 6.0 | 6.0 | 6.0 | + | 07/01 | nan | 7.0 | 7.0 | 7.0 | 7.0 | + | 08/01 | nan | 8.0 | 8.0 | 8.0 | 8.0 | + | 09/01 | nan | 9.0 | 9.0 | 9.0 | 9.0 | + | 10/01 | nan | 10.0 | 10.0 | 10.0 | 10.0 | + +Forecast simulation +___________________ + + In operational use, a forecast consists of two separate simulation runs. First, + a `historical` run covers the period with observations and ends with saving the + current conditions (the states and logs of all submodels). Second, a + `forecast` run starts from these conditions and covers the forecast horizon. + The following function emulates this workflow by splitting the simulation + period at the given date, switching |Options.simulationmode| in between, and + printing the results of both runs in a single table: + + >>> def forecast_test(split): + ... test.prepare_model(update_parameters=True, use_conditions=None) + ... first, last = pub.timegrids.sim.firstdate, pub.timegrids.sim.lastdate + ... pub.timegrids.sim.lastdate = split + ... with pub.options.simulationmode("historical"): + ... model.update_parameters() + ... test.hydpy.simulate() + ... conditions = model.conditions + ... pub.timegrids.sim.dates = split, last + ... with pub.options.simulationmode("forecast"): + ... model.update_parameters() + ... model.conditions = conditions + ... test.hydpy.simulate() + ... pub.timegrids.sim.dates = first, last + ... test.print_table() + + We replace the submodel of the previous example with a fresh one and let the + forecast start on day six. In contrast to the previous example, observations + are available for all days. However, |Calc_OutputCorr_V1| ignores them during + the `forecast` run. Instead, the submodel keeps applying the residual + determined at the end of the `historical` run (``6.0 - 5.0 = 1.0``) throughout + the whole forecast horizon, even after it lies more than |MaxNaNSkip| entries + back: + + >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0) as sub: + ... configure(sub) + >>> with pub.options.checkseries(False): + ... inputs.discharge.series = 1.5, 2.5, 3.5, 4.5, 6.0, 9.0, 9.0, 9.0, 9.0, 9.0 + +.. integration-test:: + + >>> forecast_test("2000-01-06") + | date | discharge | inflow | correctedq | inlet | outlet | + ------------------------------------------------------------ + | 01/01 | 1.5 | 1.0 | 1.5 | 1.0 | 1.5 | + | 02/01 | 2.5 | 2.0 | 2.5 | 2.0 | 2.5 | + | 03/01 | 3.5 | 3.0 | 3.5 | 3.0 | 3.5 | + | 04/01 | 4.5 | 4.0 | 4.5 | 4.0 | 4.5 | + | 05/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | + | 06/01 | 9.0 | 6.0 | 7.0 | 6.0 | 7.0 | + | 07/01 | 9.0 | 7.0 | 8.0 | 7.0 | 8.0 | + | 08/01 | 9.0 | 8.0 | 9.0 | 8.0 | 9.0 | + | 09/01 | 9.0 | 9.0 | 10.0 | 9.0 | 10.0 | + | 10/01 | 9.0 | 10.0 | 11.0 | 10.0 | 11.0 | + +Mean-value-based residual +_________________________ + + Setting |AveragingWindow| to two makes the submodel determine a mean-value-based + residual from the two days preceding the forecast (days four and five, mean + observed ``5.0``, mean simulated ``4.5``, hence ``0.5``). Setting + |TransitionSteps| to two makes the applied residual change linearly from the + pointwise residual (``1.0``) to the mean-value-based residual over the first two + forecast steps: + + >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0) as sub: + ... configure(sub) + ... averagingwindow(2) + ... transitionsteps(2) + >>> with pub.options.checkseries(False): + ... inputs.discharge.series = 1.5, 2.5, 3.5, 4.0, 6.0, nan, nan, nan, nan, nan + +.. integration-test:: + + >>> forecast_test("2000-01-06") + | date | discharge | inflow | correctedq | inlet | outlet | + ------------------------------------------------------------ + | 01/01 | 1.5 | 1.0 | 1.5 | 1.0 | 1.5 | + | 02/01 | 2.5 | 2.0 | 2.5 | 2.0 | 2.5 | + | 03/01 | 3.5 | 3.0 | 3.5 | 3.0 | 3.5 | + | 04/01 | 4.0 | 4.0 | 4.0 | 4.0 | 4.0 | + | 05/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | + | 06/01 | nan | 6.0 | 7.0 | 6.0 | 7.0 | + | 07/01 | nan | 7.0 | 7.75 | 7.0 | 7.75 | + | 08/01 | nan | 8.0 | 8.5 | 8.0 | 8.5 | + | 09/01 | nan | 9.0 | 9.5 | 9.0 | 9.5 | + | 10/01 | nan | 10.0 | 10.5 | 10.0 | 10.5 | + +Stationarity check +__________________ + + Next, we enable the stationarity check with a window of three days and a + |RatioMinMax| of ``0.5``, and set |ReductionSteps| to four. The simulated + discharge is constant. On day five, the observations of days three to five + (``5.5``, ``8.0``, and ``3.0``) become instationary (``3.0 / 8.0 < 0.5``), so + |ReductionFactor| starts to decrease linearly. It continues to do so during the + `forecast` run, which reuses the assessment of the `historical` run, until the + correction vanishes completely: + + >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0) as sub: + ... configure(sub) + ... stationaritycheck(window=3, ratiominmax=0.5) + ... reductionsteps(4) + >>> element.inlets.inlet.sequences.sim.series = 5.0 + >>> with pub.options.checkseries(False): + ... inputs.discharge.series = 5.5, 5.5, 5.5, 8.0, 3.0, nan, nan, nan, nan, nan + +.. integration-test:: + + >>> forecast_test("2000-01-06") + | date | discharge | inflow | correctedq | inlet | outlet | + ------------------------------------------------------------ + | 01/01 | 5.5 | 5.0 | 5.5 | 5.0 | 5.5 | + | 02/01 | 5.5 | 5.0 | 5.5 | 5.0 | 5.5 | + | 03/01 | 5.5 | 5.0 | 5.5 | 5.0 | 5.5 | + | 04/01 | 8.0 | 5.0 | 8.0 | 5.0 | 8.0 | + | 05/01 | 3.0 | 5.0 | 3.5 | 5.0 | 3.5 | + | 06/01 | nan | 5.0 | 4.0 | 5.0 | 4.0 | + | 07/01 | nan | 5.0 | 4.5 | 5.0 | 4.5 | + | 08/01 | nan | 5.0 | 5.0 | 5.0 | 5.0 | + | 09/01 | nan | 5.0 | 5.0 | 5.0 | 5.0 | + | 10/01 | nan | 5.0 | 5.0 | 5.0 | 5.0 | + +Variability check +_________________ + + Now, we enable the variability check instead, with a |MaxRelSumDelta| of + ``0.1`` and an averaging period of four days, and set |EvaluationWindow| to + three and |AveragingWindow| to one. During the first two days, the + |EvaluationWindow| still contains missing values, so the submodel does not + consider itself responsible. As the simulated discharge is constant, the + variability check detects stationary conditions, so the mean-value-based + residual relies on the four days preceding the forecast (mean observed + ``6.25``, mean simulated ``5.0``) instead of on the single day given by + |AveragingWindow| (which would result in ``1.0``): + + >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0) as sub: + ... configure(sub) + ... evaluationwindow(3) + ... averagingwindow(1) + ... variabilitycheck(maxrelsumdelta=0.1, averagingwindow=4) + >>> with pub.options.checkseries(False): + ... inputs.discharge.series = 6.0, 6.0, 6.0, 7.0, 6.0, nan, nan, nan, nan, nan + +.. integration-test:: + + >>> forecast_test("2000-01-06") + | date | discharge | inflow | correctedq | inlet | outlet | + ------------------------------------------------------------ + | 01/01 | 6.0 | 5.0 | 5.0 | 5.0 | 5.0 | + | 02/01 | 6.0 | 5.0 | 5.0 | 5.0 | 5.0 | + | 03/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | + | 04/01 | 7.0 | 5.0 | 7.0 | 5.0 | 7.0 | + | 05/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | + | 06/01 | nan | 5.0 | 6.25 | 5.0 | 6.25 | + | 07/01 | nan | 5.0 | 6.25 | 5.0 | 6.25 | + | 08/01 | nan | 5.0 | 6.25 | 5.0 | 6.25 | + | 09/01 | nan | 5.0 | 6.25 | 5.0 | 6.25 | + | 10/01 | nan | 5.0 | 6.25 | 5.0 | 6.25 | + +Multiple submodels +__________________ + + Finally, we attach two submodels responsible for different discharge ranges. + The first one handles simulated discharges below ``5.0`` and the second one all + others. The second one restricts the relative shift to 5 % and the absolute + shift to ``0.25``: + + >>> nmbsubmodels(2) + >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0) as sub: + ... configure(sub) + ... upperlimit(5.0) + >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=1) as sub: + ... configure(sub) + ... lowerlimit(5.0) + ... maxrelshift(0.05) + ... maxabsshift(0.25) + >>> element.inlets.inlet.sequences.sim.series = ( + ... 1.0, 2.0, 6.0, 7.0, 3.0, 4.0, 6.0, 8.0, 4.0, 3.0 + ... ) + >>> with pub.options.checkseries(False): + ... inputs.discharge.series = 1.5, 2.5, 8.0, 9.0, 3.5, nan, nan, nan, nan, nan + + During the `historical` run, the second submodel takes over on days three and + four, where its restricted relative shift prevents reproducing the + observations. During the `forecast` run, the responsible submodel does not + change (see |EvaluatedValue|). Hence, the first submodel, which was + responsible at the end of the `historical` run, keeps applying the residual of + ``0.5`` unrestricted, even when the forecasted discharge exceeds ``5.0``: + +.. integration-test:: + + >>> forecast_test("2000-01-06") + | date | discharge | inflow | correctedq | inlet | outlet | + ------------------------------------------------------------ + | 01/01 | 1.5 | 1.0 | 1.5 | 1.0 | 1.5 | + | 02/01 | 2.5 | 2.0 | 2.5 | 2.0 | 2.5 | + | 03/01 | 8.0 | 6.0 | 6.3 | 6.0 | 6.3 | + | 04/01 | 9.0 | 7.0 | 7.35 | 7.0 | 7.35 | + | 05/01 | 3.5 | 3.0 | 3.5 | 3.0 | 3.5 | + | 06/01 | nan | 4.0 | 4.5 | 4.0 | 4.5 | + | 07/01 | nan | 6.0 | 6.5 | 6.0 | 6.5 | + | 08/01 | nan | 8.0 | 8.5 | 8.0 | 8.5 | + | 09/01 | nan | 4.0 | 4.5 | 4.0 | 4.5 | + | 10/01 | nan | 3.0 | 3.5 | 3.0 | 3.5 | """ from hydpy.core import importtools From 620d49a4e9a4d32f80189aeac7df437353c7905d Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Thu, 5 Nov 2026 13:05:26 +0100 Subject: [PATCH 26/43] Implement requested changes from review --- hydpy/models/statcorr/statcorr_control.py | 189 ++- hydpy/models/statcorr/statcorr_derived.py | 26 +- hydpy/models/statcorr/statcorr_fluxes.py | 11 +- hydpy/models/statcorr/statcorr_model.py | 1830 ++++++++++++--------- hydpy/models/statcorr/statcorr_states.py | 4 +- hydpy/models/statcorr_arima010.py | 41 +- hydpy/models/statcorr_main.py | 21 +- 7 files changed, 1181 insertions(+), 941 deletions(-) diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index a7d5a41798..6638ae8fc5 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -54,7 +54,7 @@ class Active(parametertools.Parameter): Even when |Active| is |True|, the submodel only corrects the simulated values while the relevant mean simulated value lies within the range defined by - |LowerLimit| and |UpperLimit| (see |Determine_OutputCorrection_V1|).""" + |LowerLimit| and |UpperLimit| (see |Calc_IsActive_V1|).""" NDIM: Final[Literal[0]] = 0 TYPE: Final = bool @@ -181,11 +181,11 @@ class StationarityCheck(parametertools.SpecialParameter): stationary way [-]. |StationarityCheck| is a special parameter (see |SpecialParameter|). Either - switch the check off by passing |False| or switch it on by passing the length of - the assessment period (`window`, in log entries) and the threshold for the ratio - of the minimum and the maximum observed values within this period - (`ratiominmax`), below which |Determine_OutputCorrection_V1| considers the - conditions instationary: + switch the check off by passing `active=False` or switch it on by passing + `active=True` together with the length of the assessment period (`window`, in log + entries) and the threshold for the ratio of the minimum and the maximum observed + values within this period (`ratiominmax`), below which |Calc_Stationary_V1| + considers the conditions instationary: >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() @@ -197,37 +197,31 @@ class StationarityCheck(parametertools.SpecialParameter): RuntimeError: For parameter `stationaritycheck` of element `?`, it is still \ unknown whether the stationarity check is enabled. - >>> stationaritycheck(False) + >>> stationaritycheck(active=False) >>> stationaritycheck - stationaritycheck(False) + stationaritycheck(active=False) >>> stationaritycheck.verify() - Passing `window` and `ratiominmax` implicitly enables the check: - - >>> stationaritycheck(window=10, ratiominmax=0.5) + >>> stationaritycheck(active=True, window=10, ratiominmax=0.5) >>> stationaritycheck - stationaritycheck(window=10, ratiominmax=0.5) + stationaritycheck(active=True, window=10, ratiominmax=0.5) >>> stationaritycheck.enabled, stationaritycheck.window (True, 10) >>> from hydpy import round_ >>> round_(stationaritycheck.ratiominmax) 0.5 - Passing |True| explicitly is allowed but optional: - - >>> stationaritycheck(True, window=5, ratiominmax=0.8) - >>> stationaritycheck - stationaritycheck(window=5, ratiominmax=0.8) - - An enabled check requires both `window` and `ratiominmax`: + `active` is always required: - >>> stationaritycheck(True) + >>> stationaritycheck(window=5, ratiominmax=0.8) Traceback (most recent call last): ... - ValueError: For parameter `stationaritycheck` of element `?`, both `window` and \ -`ratiominmax` must be given when enabling the stationarity check. + ValueError: For parameter `stationaritycheck` of element `?`, the keyword \ +argument `active` must be given. - >>> stationaritycheck(window=5) + An enabled check requires both `window` and `ratiominmax`: + + >>> stationaritycheck(active=True, window=5) Traceback (most recent call last): ... ValueError: For parameter `stationaritycheck` of element `?`, both `window` and \ @@ -235,28 +229,22 @@ class StationarityCheck(parametertools.SpecialParameter): A disabled check does not accept `window` or `ratiominmax`: - >>> stationaritycheck(False, window=5, ratiominmax=0.8) + >>> stationaritycheck(active=False, window=5, ratiominmax=0.8) Traceback (most recent call last): ... ValueError: For parameter `stationaritycheck` of element `?`, `window` and \ `ratiominmax` must not be given when disabling the stationarity check. - >>> stationaritycheck() - Traceback (most recent call last): - ... - ValueError: For parameter `stationaritycheck` of element `?`, pass either a \ -boolean value or the keyword arguments `window` and `ratiominmax`. - `window` must be a positive integer, and `ratiominmax` must lie between zero and one: - >>> stationaritycheck(window=0, ratiominmax=0.8) + >>> stationaritycheck(active=True, window=0, ratiominmax=0.8) Traceback (most recent call last): ... ValueError: For parameter `stationaritycheck` of element `?`, `window` must be a \ positive integer, but `0` is given. - >>> stationaritycheck(window=5, ratiominmax=1.5) + >>> stationaritycheck(active=True, window=5, ratiominmax=1.5) Traceback (most recent call last): ... ValueError: For parameter `stationaritycheck` of element `?`, `ratiominmax` must \ @@ -265,7 +253,7 @@ class StationarityCheck(parametertools.SpecialParameter): Failed calls leave the previous configuration untouched: >>> stationaritycheck - stationaritycheck(window=5, ratiominmax=0.8) + stationaritycheck(active=True, window=10, ratiominmax=0.5) """ _config: tuple[bool, int, float] | None @@ -274,27 +262,35 @@ def __init__(self, subvars: variabletools.SubVariables[Any, Any, Any, Any]) -> N super().__init__(subvars) self._config = None + @overload + def __call__(self, *, active: Literal[False]) -> None: ... + + @overload + def __call__( + self, *, active: Literal[True], window: int, ratiominmax: float + ) -> None: ... + def __call__( self, - value: bool | None = None, *, + active: bool | None = None, window: int | None = None, ratiominmax: float | None = None, ) -> None: - if (value is False) and ((window is not None) or (ratiominmax is not None)): + if active is None: + raise ValueError( + f"For parameter {objecttools.elementphrase(self)}, the keyword " + f"argument `active` must be given." + ) + if (not active) and ((window is not None) or (ratiominmax is not None)): raise ValueError( f"For parameter {objecttools.elementphrase(self)}, `window` and " f"`ratiominmax` must not be given when disabling the stationarity " f"check." ) - if value is False: + if not active: self._config = (False, 0, 0.0) return - if (value is None) and (window is None) and (ratiominmax is None): - raise ValueError( - f"For parameter {objecttools.elementphrase(self)}, pass either a " - f"boolean value or the keyword arguments `window` and `ratiominmax`." - ) if (window is None) or (ratiominmax is None): raise ValueError( f"For parameter {objecttools.elementphrase(self)}, both `window` and " @@ -317,9 +313,9 @@ def __repr__(self) -> str: return f"{self.name}(?)" enabled, window, ratiominmax = self._config if not enabled: - return f"{self.name}(False)" + return f"{self.name}(active=False)" return ( - f"{self.name}(window={window}, " + f"{self.name}(active=True, window={window}, " f"ratiominmax={objecttools.repr_(ratiominmax)})" ) @@ -340,7 +336,7 @@ def configured(self) -> bool: >>> parameterstep() >>> stationaritycheck.configured False - >>> stationaritycheck(False) + >>> stationaritycheck(active=False) >>> stationaritycheck.configured True """ @@ -374,12 +370,12 @@ class VariabilityCheck(parametertools.SpecialParameter): enough to base the correction on a long-term mean residual [-]. |VariabilityCheck| is a special parameter (see |SpecialParameter|). Either - switch the check off by passing |False| or switch it on by passing the threshold - for the sum of the absolute changes of the simulated values within the - |EvaluationWindow| divided by |EvaluatedValue| (`maxrelsumdelta`) and the - length of the averaging period (`averagingwindow`, in log entries) for - determining the mean-value-based residual under stationary conditions (see - |Determine_OutputCorrection_V1|): + switch the check off by passing `active=False` or switch it on by passing + `active=True` together with the threshold for the sum of the absolute changes of + the simulated values within the |EvaluationWindow| divided by |EvaluatedValue| + (`maxrelsumdelta`, see |Calc_LowVariability_V1|) and the length of the averaging + period (`averagingwindow`, in log entries) for determining the mean-value-based + residual under stationary conditions (see |Calc_AveragedResidual_V1|): >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() @@ -391,38 +387,31 @@ class VariabilityCheck(parametertools.SpecialParameter): RuntimeError: For parameter `variabilitycheck` of element `?`, it is still \ unknown whether the variability check is enabled. - >>> variabilitycheck(False) + >>> variabilitycheck(active=False) >>> variabilitycheck - variabilitycheck(False) + variabilitycheck(active=False) >>> variabilitycheck.verify() - Passing `maxrelsumdelta` and `averagingwindow` implicitly enables the check: - - >>> variabilitycheck(maxrelsumdelta=0.2, averagingwindow=24) + >>> variabilitycheck(active=True, maxrelsumdelta=0.2, averagingwindow=24) >>> variabilitycheck - variabilitycheck(maxrelsumdelta=0.2, averagingwindow=24) + variabilitycheck(active=True, maxrelsumdelta=0.2, averagingwindow=24) >>> variabilitycheck.enabled, variabilitycheck.averagingwindow (True, 24) >>> from hydpy import round_ >>> round_(variabilitycheck.maxrelsumdelta) 0.2 - Passing |True| explicitly is allowed but optional: + `active` is always required: - >>> variabilitycheck(True, maxrelsumdelta=0.1, averagingwindow=12) - >>> variabilitycheck - variabilitycheck(maxrelsumdelta=0.1, averagingwindow=12) - - An enabled check requires both `maxrelsumdelta` and `averagingwindow`: - - >>> variabilitycheck(True) + >>> variabilitycheck(maxrelsumdelta=0.1, averagingwindow=12) Traceback (most recent call last): ... - ValueError: For parameter `variabilitycheck` of element `?`, both \ -`maxrelsumdelta` and `averagingwindow` must be given when enabling the variability \ -check. + ValueError: For parameter `variabilitycheck` of element `?`, the keyword \ +argument `active` must be given. - >>> variabilitycheck(maxrelsumdelta=0.1) + An enabled check requires both `maxrelsumdelta` and `averagingwindow`: + + >>> variabilitycheck(active=True, maxrelsumdelta=0.1) Traceback (most recent call last): ... ValueError: For parameter `variabilitycheck` of element `?`, both \ @@ -431,28 +420,22 @@ class VariabilityCheck(parametertools.SpecialParameter): A disabled check does not accept `maxrelsumdelta` or `averagingwindow`: - >>> variabilitycheck(False, maxrelsumdelta=0.1, averagingwindow=12) + >>> variabilitycheck(active=False, maxrelsumdelta=0.1, averagingwindow=12) Traceback (most recent call last): ... ValueError: For parameter `variabilitycheck` of element `?`, `maxrelsumdelta` \ and `averagingwindow` must not be given when disabling the variability check. - >>> variabilitycheck() - Traceback (most recent call last): - ... - ValueError: For parameter `variabilitycheck` of element `?`, pass either a \ -boolean value or the keyword arguments `maxrelsumdelta` and `averagingwindow`. - `maxrelsumdelta` must not be negative, and `averagingwindow` must be a positive integer: - >>> variabilitycheck(maxrelsumdelta=-0.1, averagingwindow=12) + >>> variabilitycheck(active=True, maxrelsumdelta=-0.1, averagingwindow=12) Traceback (most recent call last): ... ValueError: For parameter `variabilitycheck` of element `?`, `maxrelsumdelta` \ must not be negative, but `-0.1` is given. - >>> variabilitycheck(maxrelsumdelta=0.1, averagingwindow=0) + >>> variabilitycheck(active=True, maxrelsumdelta=0.1, averagingwindow=0) Traceback (most recent call last): ... ValueError: For parameter `variabilitycheck` of element `?`, `averagingwindow` \ @@ -461,7 +444,7 @@ class VariabilityCheck(parametertools.SpecialParameter): Failed calls leave the previous configuration untouched: >>> variabilitycheck - variabilitycheck(maxrelsumdelta=0.1, averagingwindow=12) + variabilitycheck(active=True, maxrelsumdelta=0.2, averagingwindow=24) """ _config: tuple[bool, float, int] | None @@ -470,14 +453,27 @@ def __init__(self, subvars: variabletools.SubVariables[Any, Any, Any, Any]) -> N super().__init__(subvars) self._config = None + @overload + def __call__(self, *, active: Literal[False]) -> None: ... + + @overload + def __call__( + self, *, active: Literal[True], maxrelsumdelta: float, averagingwindow: int + ) -> None: ... + def __call__( self, - value: bool | None = None, *, + active: bool | None = None, maxrelsumdelta: float | None = None, averagingwindow: int | None = None, ) -> None: - if (value is False) and ( + if active is None: + raise ValueError( + f"For parameter {objecttools.elementphrase(self)}, the keyword " + f"argument `active` must be given." + ) + if (not active) and ( (maxrelsumdelta is not None) or (averagingwindow is not None) ): raise ValueError( @@ -485,15 +481,9 @@ def __call__( f"and `averagingwindow` must not be given when disabling the " f"variability check." ) - if value is False: + if not active: self._config = (False, 0.0, 0) return - if (value is None) and (maxrelsumdelta is None) and (averagingwindow is None): - raise ValueError( - f"For parameter {objecttools.elementphrase(self)}, pass either a " - f"boolean value or the keyword arguments `maxrelsumdelta` and " - f"`averagingwindow`." - ) if (maxrelsumdelta is None) or (averagingwindow is None): raise ValueError( f"For parameter {objecttools.elementphrase(self)}, both " @@ -517,9 +507,10 @@ def __repr__(self) -> str: return f"{self.name}(?)" enabled, maxrelsumdelta, averagingwindow = self._config if not enabled: - return f"{self.name}(False)" + return f"{self.name}(active=False)" return ( - f"{self.name}(maxrelsumdelta={objecttools.repr_(maxrelsumdelta)}, " + f"{self.name}(active=True, " + f"maxrelsumdelta={objecttools.repr_(maxrelsumdelta)}, " f"averagingwindow={averagingwindow})" ) @@ -540,7 +531,7 @@ def configured(self) -> bool: >>> parameterstep() >>> variabilitycheck.configured False - >>> variabilitycheck(False) + >>> variabilitycheck(active=False) >>> variabilitycheck.configured True """ @@ -580,9 +571,13 @@ class ReductionSteps(parametertools.Parameter): class MaxAbsShift(parametertools.Parameter): - """The maximum absolute shift applied when the current forecast value - exceeds the simulated value at the point the residual was determined (see - |Determine_OutputCorrection_V1|) [unit of the corrected variable].""" + """The maximum absolute shift applied when the current simulated value is not + positive or not below |ResidualAnchor| (the simulated value at the time the + residual was determined, see |Calc_CorrectedQ_V1|) [unit of the corrected + variable]. + + This includes the `historical` mode whenever the current observation is + available, as |ResidualAnchor| then equals the current simulated value.""" NDIM: Final[Literal[0]] = 0 TYPE: Final = float @@ -590,9 +585,9 @@ class MaxAbsShift(parametertools.Parameter): class MaxRelShift(parametertools.Parameter): - """The maximum relative shift applied when the current forecast value is at or - below the simulated value at the point the residual was determined (see - |Determine_OutputCorrection_V1|) [-]. + """The maximum relative shift applied when the current simulated value is + positive and below |ResidualAnchor| (the simulated value at the time the residual + was determined, see |Calc_CorrectedQ_V1|) [-]. |MaxRelShift| is a fraction, not a percentage. For example, a value of ``0.1`` restricts the multiplicative correction to ±10 %.""" @@ -605,7 +600,7 @@ class MaxRelShift(parametertools.Parameter): class AveragingWindow(parametertools.Parameter): """The length (in log entries) of the averaging period immediately preceding the current forecast run, used to determine the mean-value-based - ARIMA residual (see |Determine_OutputCorrection_V1|) [-]. Set to zero to + ARIMA residual (see |Calc_AveragedResidual_V1|) [-]. Set to zero to disable mean-value-based correction and rely on the single most recent (pointwise) residual only.""" diff --git a/hydpy/models/statcorr/statcorr_derived.py b/hydpy/models/statcorr/statcorr_derived.py index 1aa7de4267..1507102225 100644 --- a/hydpy/models/statcorr/statcorr_derived.py +++ b/hydpy/models/statcorr/statcorr_derived.py @@ -80,8 +80,8 @@ def update(self) -> None: >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() >>> evaluationwindow(3) - >>> stationaritycheck(window=4, ratiominmax=0.5) - >>> variabilitycheck(False) + >>> stationaritycheck(active=True, window=4, ratiominmax=0.5) + >>> variabilitycheck(active=False) >>> maxnanskip(1) >>> derived.nmblogentries.update() >>> derived.nmblogentries @@ -92,13 +92,13 @@ def update(self) -> None: >>> derived.nmblogentries nmblogentries(4) - >>> stationaritycheck(False) - >>> variabilitycheck(maxrelsumdelta=0.2, averagingwindow=5) + >>> stationaritycheck(active=False) + >>> variabilitycheck(active=True, maxrelsumdelta=0.2, averagingwindow=5) >>> derived.nmblogentries.update() >>> derived.nmblogentries nmblogentries(6) - >>> variabilitycheck(False) + >>> variabilitycheck(active=False) >>> maxnanskip(6) >>> derived.nmblogentries.update() >>> derived.nmblogentries @@ -196,12 +196,12 @@ def update(self) -> None: >>> derived.stationaritywindow stationaritywindow(?) - >>> stationaritycheck(window=4, ratiominmax=0.5) + >>> stationaritycheck(active=True, window=4, ratiominmax=0.5) >>> derived.stationaritywindow.update() >>> derived.stationaritywindow stationaritywindow(4) - >>> stationaritycheck(False) + >>> stationaritycheck(active=False) >>> derived.stationaritywindow.update() >>> derived.stationaritywindow stationaritywindow(0) @@ -235,12 +235,12 @@ def update(self) -> None: >>> derived.ratiominmax ratiominmax(?) - >>> stationaritycheck(window=4, ratiominmax=0.5) + >>> stationaritycheck(active=True, window=4, ratiominmax=0.5) >>> derived.ratiominmax.update() >>> derived.ratiominmax ratiominmax(0.5) - >>> stationaritycheck(False) + >>> stationaritycheck(active=False) >>> derived.ratiominmax.update() >>> derived.ratiominmax ratiominmax(0.0) @@ -275,12 +275,12 @@ def update(self) -> None: >>> derived.maxrelsumdelta maxrelsumdelta(?) - >>> variabilitycheck(maxrelsumdelta=0.2, averagingwindow=24) + >>> variabilitycheck(active=True, maxrelsumdelta=0.2, averagingwindow=24) >>> derived.maxrelsumdelta.update() >>> derived.maxrelsumdelta maxrelsumdelta(0.2) - >>> variabilitycheck(False) + >>> variabilitycheck(active=False) >>> derived.maxrelsumdelta.update() >>> derived.maxrelsumdelta maxrelsumdelta(0.0) @@ -315,12 +315,12 @@ def update(self) -> None: >>> derived.stationaryaveragingwindow stationaryaveragingwindow(?) - >>> variabilitycheck(maxrelsumdelta=0.2, averagingwindow=24) + >>> variabilitycheck(active=True, maxrelsumdelta=0.2, averagingwindow=24) >>> derived.stationaryaveragingwindow.update() >>> derived.stationaryaveragingwindow stationaryaveragingwindow(24) - >>> variabilitycheck(False) + >>> variabilitycheck(active=False) >>> derived.stationaryaveragingwindow.update() >>> derived.stationaryaveragingwindow stationaryaveragingwindow(0) diff --git a/hydpy/models/statcorr/statcorr_fluxes.py b/hydpy/models/statcorr/statcorr_fluxes.py index 594e634e62..a5cf96ebb3 100644 --- a/hydpy/models/statcorr/statcorr_fluxes.py +++ b/hydpy/models/statcorr/statcorr_fluxes.py @@ -16,9 +16,18 @@ class CorrectedQ(sequencetools.FluxSequence): NDIM: Final[Literal[0]] = 0 +class ForecastMode(sequencetools.FluxSequence): + """Flag (1.0: `forecast`, 0.0: `historical`) telling the simulation mode the main + model passed to |Determine_OutputCorrection_V1| in the current simulation step + [-].""" + + NDIM: Final[Literal[0]] = 0 + SPAN = (0.0, 1.0) + + class IsActive(sequencetools.FluxSequence): """Flag (1.0: yes, 0.0: no) telling whether the submodel corrected the discharge - in the current simulation step (see |Determine_OutputCorrection_V1|) [-].""" + in the current simulation step (see |Calc_IsActive_V1|) [-].""" NDIM: Final[Literal[0]] = 0 SPAN = (0.0, 1.0) diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index e5de76c90a..4065f630ce 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -44,6 +44,33 @@ def __call__(model: modeltools.Model, /) -> None: flu.inflow += inl.q[idx] +class Calc_OutputCorr_OutputCorrModel_V1(modeltools.Method): + """Let a submodel that complies with the |OutputCorrModel_V1| interface correct + the current simulated discharge and take over its result if it is active. + + See |Calc_OutputCorr_V1| for examples. + """ + + SUBMODELINTERFACES = (statcorrinterfaces.OutputCorrModel_V1,) + DERIVEDPARAMETERS = (statcorr_derived.IsForecastMode,) + REQUIREDSEQUENCES = (statcorr_fluxes.Inflow, statcorr_inputs.Discharge) + RESULTSEQUENCES = (statcorr_fluxes.CorrectedQ,) + + @staticmethod + def __call__( + model: modeltools.Model, submodel: statcorrinterfaces.OutputCorrModel_V1, / + ) -> None: + der = model.parameters.derived.fastaccess + flu = model.sequences.fluxes.fastaccess + inp = model.sequences.inputs.fastaccess + observedvalue: float = modelutils.nan if der.isforecastmode else inp.discharge + submodel.set_simulatedvalue(flu.inflow) + submodel.set_observedvalue(observedvalue) + submodel.determine_outputcorrection(bool(der.isforecastmode)) + if submodel.is_active(): + flu.correctedq = submodel.get_correctedoutput() + + class Calc_OutputCorr_V1(modeltools.Method): """Apply each |OutputCorrModel_V1| submodel to the current simulated and observed discharge and combine their results into the corrected discharge. @@ -100,8 +127,8 @@ class Calc_OutputCorr_V1(modeltools.Method): ... submodel.parameters.control.maxrelshift(10.0) ... submodel.parameters.control.averagingwindow(0) ... submodel.parameters.control.transitionsteps(0) - ... submodel.parameters.control.stationaritycheck(False) - ... submodel.parameters.control.variabilitycheck(False) + ... submodel.parameters.control.stationaritycheck(active=False) + ... submodel.parameters.control.variabilitycheck(active=False) ... submodel.parameters.control.reductionsteps(1) >>> nmbsubmodels(1) @@ -246,39 +273,23 @@ class Calc_OutputCorr_V1(modeltools.Method): """ SUBMODELINTERFACES = (statcorrinterfaces.OutputCorrModel_V1,) + SUBMETHODS = (Calc_OutputCorr_OutputCorrModel_V1,) DERIVEDPARAMETERS = (statcorr_derived.IsForecastMode,) REQUIREDSEQUENCES = (statcorr_fluxes.Inflow, statcorr_inputs.Discharge) RESULTSEQUENCES = (statcorr_fluxes.CorrectedQ,) @staticmethod def __call__(model: modeltools.Model, /) -> None: - der = model.parameters.derived.fastaccess flu = model.sequences.fluxes.fastaccess - inp = model.sequences.inputs.fastaccess - observedvalue: float = modelutils.nan if der.isforecastmode else inp.discharge flu.correctedq = flu.inflow for i in range(model.outputcorrmodels.number): if model.outputcorrmodels.typeids[i] == 1: - cast( - statcorrinterfaces.OutputCorrModel_V1, - model.outputcorrmodels.submodels[i], - ).set_simulatedvalue(flu.inflow) - cast( - statcorrinterfaces.OutputCorrModel_V1, - model.outputcorrmodels.submodels[i], - ).set_observedvalue(observedvalue) - cast( - statcorrinterfaces.OutputCorrModel_V1, - model.outputcorrmodels.submodels[i], - ).determine_outputcorrection(bool(der.isforecastmode)) - if cast( - statcorrinterfaces.OutputCorrModel_V1, - model.outputcorrmodels.submodels[i], - ).is_active(): - flu.correctedq = cast( + model.calc_outputcorr_outputcorrmodel_v1( + cast( statcorrinterfaces.OutputCorrModel_V1, model.outputcorrmodels.submodels[i], - ).get_correctedoutput() + ) + ) class Pass_CorrectedQ_V1(modeltools.Method): @@ -332,7 +343,7 @@ class Model(modeltools.AdHocModel): RECEIVER_METHODS = () RUN_METHODS = (Calc_OutputCorr_V1,) INTERFACE_METHODS = () - ADD_METHODS = () + ADD_METHODS = (Calc_OutputCorr_OutputCorrModel_V1,) OUTLET_METHODS = (Pass_CorrectedQ_V1,) SENDER_METHODS = () SUBMODELINTERFACES = (statcorrinterfaces.OutputCorrModel_V1,) @@ -364,8 +375,8 @@ def add_outputcorrmodel_v1( >>> nmbsubmodels(1) >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0): ... evaluationwindow(2) - ... stationaritycheck(window=4, ratiominmax=0.5) - ... variabilitycheck(False) + ... stationaritycheck(active=True, window=4, ratiominmax=0.5) + ... variabilitycheck(active=False) ... maxnanskip(2) ... averagingwindow(0) >>> model.outputcorrmodels[0].parameters.derived.nmblogentries @@ -434,820 +445,1156 @@ def __call__(model: modeltools.Model, observedvalue: float, /) -> None: log.loggedobservedvalue[0] = observedvalue -class Calc_AveragedResidual_V1(modeltools.Method): - r"""Determine the mean-value-based ARIMA residual once, at the first - forecast step, and freeze it for the remainder of the current forecast - horizon. - - |Calc_AveragedResidual_V1| averages the |LoggedObservedValue| and - |LoggedSimulatedValue| entries covering the |AveragingWindow| - log positions immediately preceding the current forecast run (log - position ``0`` already holds the current forecast step's own values, so - averaging starts at position ``1``) and stores their difference in - |AveragedResidual|. It leaves |AveragedResidual| unchanged whenever - `forecast_step` is not zero (i.e., beyond the first forecast step) or - |AveragingWindow| is zero (mean-value-based correction disabled). - When the averaging window contains a |numpy.nan| value, it falls back to - the given `fallback` residual instead (usually the pointwise residual - already determined by |Determine_OutputCorrection_V1|). While - |LowVariability| is ``1.0`` (stationary conditions according to - |VariabilityCheck|), the |StationaryAveragingWindow| replaces the - |AveragingWindow|. +class Set_ForecastMode_V1(modeltools.Method): + """Remember whether the main model currently runs in `forecast` or `historical` + mode. Examples: >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() - >>> control.averagingwindow(2) - >>> derived.stationaryaveragingwindow(1) - >>> states.lowvariability(0.0) - >>> derived.nmblogentries(3) - >>> logs.loggedsimulatedvalue = 3.0, 2.0, 4.0 - >>> logs.loggedobservedvalue = nan, 3.0, 5.0 + >>> model.set_forecastmode_v1(True) + >>> fluxes.forecastmode + forecastmode(1.0) + >>> model.set_forecastmode_v1(False) + >>> fluxes.forecastmode + forecastmode(0.0) + """ - On the first forecast step (`forecast_step` is ``0.0``), the average - is taken from log positions ``1`` and ``2`` (mean observed ``4.0``, - mean simulated ``3.0``): + RESULTSEQUENCES = (statcorr_fluxes.ForecastMode,) - >>> from numpy import nan - >>> model.calc_averagedresidual_v1(0.0, -9.0) - >>> states.averagedresidual - averagedresidual(1.0) + @staticmethod + def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: + flu = model.sequences.fluxes.fastaccess + flu.forecastmode = 1.0 if isforecastmode else 0.0 - On any later forecast step, the previously determined value remains - unchanged, regardless of the current log contents: - >>> logs.loggedsimulatedvalue = 3.0, 20.0, 40.0 - >>> logs.loggedobservedvalue = nan, 30.0, 50.0 - >>> model.calc_averagedresidual_v1(1.0, -9.0) - >>> states.averagedresidual - averagedresidual(1.0) +class Calc_EvaluatedValue_V1(modeltools.Method): + r"""Calculate the mean of the |EvaluationWindow| most recent + |LoggedSimulatedValue| values while |ForecastMode| is ``0.0`` (`historical`). - Setting |AveragingWindow| to zero disables mean-value-based - correction; |Calc_AveragedResidual_V1| leaves |AveragedResidual| - unchanged even on the first forecast step: + Basic equation: + :math:`EvaluatedValue = \frac{1}{EvaluationWindow} + \sum_{i=0}^{EvaluationWindow-1} LoggedSimulatedValue_i` - >>> control.averagingwindow(0) - >>> states.averagedresidual(-9.0) - >>> model.calc_averagedresidual_v1(0.0, -9.0) - >>> states.averagedresidual - averagedresidual(-9.0) + While |ForecastMode| is ``1.0`` (`forecast`), |Calc_EvaluatedValue_V1| keeps the + value of the most recent `historical` assessment, so the responsible submodel + (see |Calc_IsActive_V1|) does not change throughout the forecast horizon. - A |numpy.nan| value within the averaging window makes - |Calc_AveragedResidual_V1| fall back to the given `fallback` value: + Examples: - >>> control.averagingwindow(2) - >>> logs.loggedobservedvalue = nan, nan, 50.0 - >>> model.calc_averagedresidual_v1(0.0, -9.0) - >>> states.averagedresidual - averagedresidual(-9.0) + |Calc_EvaluatedValue_V1| always relies on the *most recently* logged values + (index ``0`` upwards) and never on the oldest ones sitting near the end of a + larger log (which can well still be |numpy.nan|): - Under stationary conditions according to |VariabilityCheck|, the - averaging period covers the single log position ``1`` given by - |StationaryAveragingWindow| (``30.0 - 20.0``), even if - |AveragingWindow| is zero: + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> from numpy import nan + >>> control.evaluationwindow(3) + >>> derived.nmblogentries(5) + >>> logs.loggedsimulatedvalue = 1.0, 2.0, 6.0, nan, nan + >>> fluxes.forecastmode = 0.0 + >>> model.calc_evaluatedvalue_v1() + >>> states.evaluatedvalue + evaluatedvalue(3.0) - >>> control.averagingwindow(0) - >>> states.lowvariability(1.0) - >>> logs.loggedobservedvalue = nan, 30.0, nan - >>> model.calc_averagedresidual_v1(0.0, -9.0) - >>> states.averagedresidual - averagedresidual(10.0) + In `forecast` mode, |EvaluatedValue| stays frozen: + + >>> fluxes.forecastmode = 1.0 + >>> logs.loggedsimulatedvalue = 10.0, 10.0, 10.0, nan, nan + >>> model.calc_evaluatedvalue_v1() + >>> states.evaluatedvalue + evaluatedvalue(3.0) """ - CONTROLPARAMETERS = (statcorr_control.AveragingWindow,) - DERIVEDPARAMETERS = ( - statcorr_derived.NmbLogEntries, - statcorr_derived.StationaryAveragingWindow, - ) + CONTROLPARAMETERS = (statcorr_control.EvaluationWindow,) REQUIREDSEQUENCES = ( + statcorr_fluxes.ForecastMode, statcorr_logs.LoggedSimulatedValue, - statcorr_logs.LoggedObservedValue, - statcorr_states.LowVariability, ) - UPDATEDSEQUENCES = (statcorr_states.AveragedResidual,) + UPDATEDSEQUENCES = (statcorr_states.EvaluatedValue,) @staticmethod - def __call__( - model: modeltools.Model, forecast_step: float, fallback: float, / - ) -> None: + def __call__(model: modeltools.Model, /) -> None: con = model.parameters.control.fastaccess - der = model.parameters.derived.fastaccess + flu = model.sequences.fluxes.fastaccess log = model.sequences.logs.fastaccess sta = model.sequences.states.fastaccess + if flu.forecastmode == 0.0: + sum_simulated: float = 0.0 + for idx in range(con.evaluationwindow): + sum_simulated = sum_simulated + log.loggedsimulatedvalue[idx] + sta.evaluatedvalue = sum_simulated / con.evaluationwindow - if sta.lowvariability == 1.0: - nmb = min(der.stationaryaveragingwindow, der.nmblogentries - 1) - else: - nmb = min(con.averagingwindow, der.nmblogentries - 1) - if forecast_step != 0.0 or nmb <= 0: - return - - sum_obs: float = 0.0 - sum_sim: float = 0.0 - has_nan = False - for idx in range(1, nmb + 1): - obs_value: float = log.loggedobservedvalue[idx] - sim_value: float = log.loggedsimulatedvalue[idx] - if modelutils.isnan(obs_value) or modelutils.isnan(sim_value): - has_nan = True - break - sum_obs = sum_obs + obs_value - sum_sim = sum_sim + sim_value - sta.averagedresidual = fallback if has_nan else (sum_obs - sum_sim) / nmb - - -class Determine_OutputCorrection_V1(modeltools.Method): - r"""Calculate the corrected value using an ARIMA(0,1,0) — random-walk — - error model. - - Each submodel is responsible for a specific value range only. It corrects - the simulated values only while |Active| is |True|, |CorrectionMode| allows a - correction in the current simulation mode, and the mean of the - |EvaluationWindow| most recent |LoggedSimulatedValue| values - (:math:`\overline{sim}`, stored in |EvaluatedValue|) lies within the - range defined by |LowerLimit| and |UpperLimit|: + +class Calc_IsActive_V1(modeltools.Method): + r"""Decide whether the submodel is responsible for correcting the current + simulated value. + + Each submodel is responsible for a specific value range only. It corrects the + simulated values only while |Active| is |True|, |CorrectionMode| allows a + correction in the current simulation mode (see |ForecastMode|), and + |EvaluatedValue| (:math:`\overline{sim}`) lies within the range defined by + |LowerLimit| and |UpperLimit|: :math:`LowerLimit \leq \overline{sim} < UpperLimit` - |Determine_OutputCorrection_V1| determines :math:`\overline{sim}` only while - |Options.simulationmode| equals `historical`. While it equals `forecast`, it - reuses the value of the most recent `historical` assessment, so the - responsible submodel does not change throughout the forecast horizon. It - checks the condition in each simulation step (so changes of |Active|, - |CorrectionMode|, |LowerLimit|, or |UpperLimit| take effect immediately) and - stores the outcome in |IsActive|. Whenever the condition is not met, the - corrected value equals the current simulated value. However, - |Determine_OutputCorrection_V1| keeps updating all internal states (the - residual, the stationarity assessment, and the |ReductionFactor|) in either - case, so that a submodel taking over responsibility starts with up-to-date - information. This also holds for a submodel that |CorrectionMode| restricts - to the `forecast` mode, which, therefore, relies on the residual and the - conditions determined during the preceding `historical` run. - - The correction is derived from the most recently available residual - (observed minus simulated values). While |Options.simulationmode| - equals `historical`, the "most recent" residual is taken from the latest - log entry where the observed value is not |numpy.nan|, skipping at - most |MaxNaNSkip| preceding log entries with missing observations (or - searching the entire log, whichever is smaller), and remembered in - |Residual| (together with the corresponding simulated value in - |ResidualAnchor|). When no observation is - available within that range, both are set to zero, so the corrected - value equals the current simulated value. While - |Options.simulationmode| equals `forecast`, |Determine_OutputCorrection_V1| - does not repeat this search — see the paragraph on |Residual| and - |ResidualAnchor| below for why. - - How that residual is applied to the current simulated ("forecast") - value depends on how the latter (:math:`sim_0`) compares to the - simulated value at the time the residual was determined (:math:`sim_k`, - with :math:`k` denoting the most recent log index for which :math:`obs_k - \neq \mathrm{nan}`, and :math:`f_{red}` denoting |ReductionFactor|): - - * If :math:`sim_0 > sim_k` or :math:`sim_k \leq 0` (for which a relative - shift would be undefined), |Determine_OutputCorrection_V1| shifts - :math:`sim_0` *additively* by the |ReductionFactor|-damped residual, capped - at |MaxAbsShift|: - - :math:`q_{corr} = sim_0 + \mathrm{clip}\left((obs_k - sim_k) \cdot - f_{red},\ \pm MaxAbsShift\right)` - - * Otherwise (:math:`0 < sim_0 \leq sim_k`), it shifts :math:`sim_0` - *multiplicatively* instead, expressing the damped residual as a fraction - of :math:`sim_k` and capping that fraction at |MaxRelShift|: - - :math:`q_{corr} = sim_0 \cdot \left(1 + \mathrm{clip}\left((obs_k - - sim_k) \cdot f_{red} / sim_k,\ \pm MaxRelShift\right) - \right)` - - Applying the residual as a fraction rather than a constant offset - keeps the correction from overshooting or turning negative while the - forecasted values recede towards zero. - - The residual (:math:`obs_k - sim_k` above) used in either branch is not - necessarily the pointwise one. Setting |AveragingWindow| to a - value greater than zero switches to a mean-value-based residual during - forecast runs (`historical` runs always rely on the pointwise residual) — - the difference between the mean observed and the mean simulated values - over that many log entries immediately preceding the current forecast run - (determined once, at the first forecast step, via - |Calc_AveragedResidual_V1|, and frozen in |AveragedResidual| for the - remainder of the forecast horizon). Since that mean-value-based residual - generally does not equal the pointwise residual at the forecast's start, - switching to it abruptly would cause a jump in the corrected value - right where the forecast begins. To avoid this, |Determine_OutputCorrection_V1| - starts every forecast run with the pointwise residual (so the corrected - value picks up smoothly where the last measurement left off) and then - linearly blends it towards the mean-value-based residual over - |TransitionSteps| forecast steps, applying the mean-value-based - residual unabated from then on. Setting |AveragingWindow| to zero - disables this mechanism entirely, relying on the pointwise residual alone, - as described above. - - If enabled via |StationarityCheck|, |Determine_OutputCorrection_V1| - additionally assesses whether the observed values behave in a stationary - way. It takes the ratio of the minimum and the maximum - |LoggedObservedValue| value within the most recent |StationarityWindow| - log entries. Whenever this ratio falls below |RatioMinMax|, it considers the - conditions instationary and linearly reduces |ReductionFactor| (the - factor :math:`f_{red}` in the equation above) towards zero, taking as many - steps as given by |ReductionSteps|. As soon as the ratio reaches - |RatioMinMax| again, |ReductionFactor| jumps back to ``1.0``, applying the - correction unabated again. If a |numpy.nan| value within the - |StationarityWindow| prevents calculating the ratio, it keeps the outcome of - the previous assessment (|Stationary|), so that a single missing observation - neither interrupts an ongoing reduction nor triggers a new one. With the - stationarity check disabled, |ReductionFactor| is always ``1.0``. - - |Determine_OutputCorrection_V1| only *reassesses* stationarity (the - ratio-based check described above) while |Options.simulationmode| equals - `historical`, remembering its outcome in |Stationary|. While - |Options.simulationmode| equals `forecast`, it reuses this value from the - most recent `historical` assessment instead of recomputing it — - recomputing would be unreliable anyway, since |LoggedObservedValue| - keeps receiving |numpy.nan| values throughout the forecast (see - |Calc_OutputCorr_V1|), which would prevent any new assessment as soon as - the first of them enters the |StationarityWindow|. So, once a `historical` - run has flagged conditions as instationary, |ReductionFactor| keeps ramping - towards zero (or staying at ``0.0``) for the entire forecast horizon instead - of jumping back to ``1.0`` as soon as the last real observation drops out of - the logging window. - - If enabled via |VariabilityCheck|, |Determine_OutputCorrection_V1| - additionally assesses how much the simulated values vary. It sums the - absolute changes between successive |LoggedSimulatedValue| values within - the |EvaluationWindow| and divides this sum by |EvaluatedValue|, storing - the result in |RelSumDelta|. It considers the conditions stationary - (|LowVariability| is ``1.0``) if |RelSumDelta| does not exceed - |MaxRelSumDelta| and the stationarity check described above is either - disabled or also detects stationary conditions. Hence, the variability check - never interferes with the linear reduction of the correction. Under - stationary conditions, the mean-value-based residual (see - |Calc_AveragedResidual_V1|) relies on the |StationaryAveragingWindow| instead - of the |AveragingWindow| (and so applies even if - |AveragingWindow| is zero), while the transition over - |TransitionSteps| forecast steps remains unchanged. Otherwise - (including the case of a non-positive |EvaluatedValue|, for which - |RelSumDelta| is |numpy.nan|), the correction works as described above. - Like |Stationary|, |Determine_OutputCorrection_V1| reassesses |RelSumDelta| - and |LowVariability| only while |Options.simulationmode| equals - `historical`. - - Likewise, |Determine_OutputCorrection_V1| only reassesses the pointwise - residual itself (the |MaxNaNSkip| search described above) while - |Options.simulationmode| equals `historical`, remembering the outcome in - |Residual| and |ResidualAnchor|. While it equals `forecast`, it reuses - both from the most recent `historical` assessment instead of repeating - the search, so the (|ReductionFactor|-damped) correction persists for the - entire forecast horizon instead of vanishing as soon as the underlying - log entry drops out of the logging window. Together with the preceding - paragraph, this means only |ReductionFactor| (and, if configured, the - blend towards |AveragedResidual|) can still change the correction once a - forecast run is underway. + |Calc_IsActive_V1| checks this condition in each simulation step, so changes of + |Active|, |CorrectionMode|, |LowerLimit|, or |UpperLimit| take effect + immediately. Examples: - Three log entries are available, the most recent observation (at - position 0) is non-|numpy.nan|, so the correction reproduces the current - observation. The submodel is responsible for all values. The - observed values are just stationary (the ratio of their minimum and - maximum equals |RatioMinMax|), so |ReductionFactor| remains at its - initial value of ``1.0``: - >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() - >>> from numpy import inf, nan - >>> derived.nmblogentries(3) - >>> control.evaluationwindow(3) + >>> from numpy import inf >>> control.active(True) >>> control.correctionmode(option="both") >>> control.lowerlimit(0.0) >>> control.upperlimit(inf) - >>> control.stationaritycheck(window=3, ratiominmax=0.5) - >>> derived.stationaritywindow.update() - >>> derived.ratiominmax.update() - >>> control.variabilitycheck(False) - >>> derived.maxrelsumdelta.update() - >>> derived.stationaryaveragingwindow.update() - >>> control.reductionsteps(2) - >>> control.maxnanskip(2) - >>> control.maxabsshift(100.0) - >>> control.maxrelshift(10.0) - >>> control.averagingwindow(0) - >>> control.transitionsteps(0) - >>> states.reductionfactor(1.0) - >>> states.stationary(1.0) - >>> logs.loggedsimulatedvalue = 5.0, 3.0, 2.0 - >>> logs.loggedobservedvalue = 6.0, 4.0, 3.0 - >>> model.determine_outputcorrection_v1(False) + >>> states.evaluatedvalue(3.0) + >>> fluxes.forecastmode = 0.0 + >>> model.calc_isactive_v1() >>> fluxes.isactive isactive(1.0) - >>> fluxes.correctedq - correctedq(6.0) - >>> states.reductionfactor - reductionfactor(1.0) - - The mean simulated value (``10/3``) is not below an - |UpperLimit| of 3, so the submodel is not responsible and returns - the uncorrected simulated value: - - >>> control.upperlimit(3.0) - >>> model.determine_outputcorrection_v1(False) - >>> fluxes.isactive - isactive(0.0) - >>> fluxes.correctedq - correctedq(5.0) |UpperLimit| is exclusive, while |LowerLimit| is inclusive: - >>> logs.loggedsimulatedvalue = 3.0, 3.0, 3.0 - >>> logs.loggedobservedvalue = 4.0, 4.0, 4.0 - >>> model.determine_outputcorrection_v1(False) + >>> control.upperlimit(3.0) + >>> model.calc_isactive_v1() >>> fluxes.isactive isactive(0.0) - >>> fluxes.correctedq - correctedq(3.0) >>> control.lowerlimit(3.0) >>> control.upperlimit(inf) - >>> model.determine_outputcorrection_v1(False) + >>> model.calc_isactive_v1() >>> fluxes.isactive isactive(1.0) - >>> fluxes.correctedq - correctedq(4.0) Setting |Active| to |False| disables the correction completely: >>> control.active(False) - >>> model.determine_outputcorrection_v1(False) + >>> model.calc_isactive_v1() >>> fluxes.isactive isactive(0.0) - >>> fluxes.correctedq - correctedq(3.0) |CorrectionMode| restricts the correction to one simulation mode. With `forecast`, the submodel does not correct the simulated values in the - `historical` - mode: + `historical` mode: >>> control.active(True) >>> control.correctionmode(option="forecast") - >>> model.determine_outputcorrection_v1(False) + >>> model.calc_isactive_v1() >>> fluxes.isactive isactive(0.0) - >>> fluxes.correctedq - correctedq(3.0) - - With `historical`, it does: - >>> control.correctionmode(option="historical") - >>> model.determine_outputcorrection_v1(False) + >>> fluxes.forecastmode = 1.0 + >>> model.calc_isactive_v1() >>> fluxes.isactive isactive(1.0) - >>> fluxes.correctedq - correctedq(4.0) - In the `forecast` mode, it is the other way round: + With `historical`, it is the other way round: - >>> model.determine_outputcorrection_v1(True) + >>> control.correctionmode(option="historical") + >>> model.calc_isactive_v1() >>> fluxes.isactive isactive(0.0) - >>> fluxes.correctedq - correctedq(3.0) - >>> control.correctionmode(option="forecast") - >>> model.determine_outputcorrection_v1(True) + >>> fluxes.forecastmode = 0.0 + >>> model.calc_isactive_v1() >>> fluxes.isactive isactive(1.0) - >>> fluxes.correctedq - correctedq(4.0) - >>> control.correctionmode(option="both") + """ - The two most recent observations are missing, so the residual is taken - from the third log entry and added to the current simulated value. - Missing observations also make it impossible to assess stationarity, so - |Determine_OutputCorrection_V1| keeps the previous assessment (here, the - initial stationary conditions) and leaves |ReductionFactor| untouched: + CONTROLPARAMETERS = ( + statcorr_control.Active, + statcorr_control.CorrectionMode, + statcorr_control.LowerLimit, + statcorr_control.UpperLimit, + ) + REQUIREDSEQUENCES = (statcorr_fluxes.ForecastMode, statcorr_states.EvaluatedValue) + RESULTSEQUENCES = (statcorr_fluxes.IsActive,) - >>> control.active(True) - >>> control.lowerlimit(0.0) - >>> logs.loggedsimulatedvalue = 5.0, 3.0, 2.0 - >>> logs.loggedobservedvalue = nan, nan, 3.0 - >>> model.determine_outputcorrection_v1(False) - >>> fluxes.correctedq - correctedq(6.0) + @staticmethod + def __call__(model: modeltools.Model, /) -> None: + con = model.parameters.control.fastaccess + flu = model.sequences.fluxes.fastaccess + sta = model.sequences.states.fastaccess + if con.correctionmode == 3: + modeallowed = True + elif flu.forecastmode == 1.0: + modeallowed = con.correctionmode == 2 + else: + modeallowed = con.correctionmode == 1 + if ( + con.active + and modeallowed + and (con.lowerlimit <= sta.evaluatedvalue < con.upperlimit) + ): + flu.isactive = 1.0 + else: + flu.isactive = 0.0 - All observations are missing — no correction is applied: - >>> logs.loggedobservedvalue = nan, nan, nan - >>> model.determine_outputcorrection_v1(False) - >>> fluxes.correctedq - correctedq(5.0) +class Calc_Residual_ResidualAnchor_V1(modeltools.Method): + r"""Determine the most recent pointwise residual (observed minus simulated + value) and the corresponding simulated value while |ForecastMode| is ``0.0`` + (`historical`). - Sustained instationary conditions (the ratio of the minimum and the - maximum observed values, ``0.5 / 5.0 = 0.1``, falls well below - |RatioMinMax|) linearly reduce |ReductionFactor| to zero within the two - steps given by |ReductionSteps|: + Basic equations: + :math:`Residual = LoggedObservedValue_k - LoggedSimulatedValue_k` - >>> logs.loggedsimulatedvalue = 1.0, 1.0, 1.0 - >>> logs.loggedobservedvalue = 0.5, 5.0, 5.0 - >>> model.determine_outputcorrection_v1(False) - >>> states.stationary - stationary(0.0) - >>> states.reductionfactor - reductionfactor(0.5) - >>> fluxes.correctedq - correctedq(0.75) + :math:`ResidualAnchor = LoggedSimulatedValue_k` - >>> model.determine_outputcorrection_v1(False) - >>> states.reductionfactor - reductionfactor(0.0) - >>> fluxes.correctedq - correctedq(1.0) + :math:`k` denotes the most recent log index for which the observed value is not + |numpy.nan|. The search skips at most |MaxNaNSkip| preceding log entries with + missing observations (or searches the entire log, whichever is smaller). When + no observation is available within that range, |Residual| and |ResidualAnchor| + are set to zero, so no correction applies. - A single missing observation within the |StationarityWindow| does not - reset |ReductionFactor|. Instead, |Determine_OutputCorrection_V1| keeps - the previous assessment, so the conditions remain instationary: + While |ForecastMode| is ``1.0`` (`forecast`), |Calc_Residual_ResidualAnchor_V1| + does not repeat the search and keeps both values of the most recent `historical` + assessment. Hence, the correction persists for the entire forecast horizon + instead of vanishing as soon as the underlying log entry drops out of the + logging window. - >>> logs.loggedobservedvalue = 0.5, nan, 5.0 - >>> model.determine_outputcorrection_v1(False) - >>> states.stationary - stationary(0.0) - >>> states.reductionfactor - reductionfactor(0.0) - >>> fluxes.correctedq - correctedq(1.0) - >>> logs.loggedobservedvalue = 0.5, 5.0, 5.0 + Examples: - Disabling the stationarity check resets |ReductionFactor| to ``1.0`` - regardless of the (still instationary) observed values: + If the most recent observation is available, it determines the residual: - >>> control.stationaritycheck(False) - >>> derived.stationaritywindow.update() - >>> derived.ratiominmax.update() - >>> model.determine_outputcorrection_v1(False) - >>> states.reductionfactor - reductionfactor(1.0) - >>> fluxes.correctedq - correctedq(0.5) + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> from numpy import nan + >>> control.maxnanskip(2) + >>> derived.nmblogentries(3) + >>> fluxes.forecastmode = 0.0 + >>> logs.loggedsimulatedvalue = 5.0, 3.0, 2.0 + >>> logs.loggedobservedvalue = 6.0, 4.0, 3.0 + >>> model.calc_residual_residualanchor_v1() + >>> states.residual, states.residualanchor + (residual(1.0), residualanchor(5.0)) - Once the observed values become stationary again (ratio - ``4.0 / 5.0 = 0.8``, at or above |RatioMinMax|), |ReductionFactor| jumps - back to ``1.0`` immediately, applying the correction unabated: + If the two most recent observations are missing, the residual stems from + the third log entry: - >>> control.stationaritycheck(window=3, ratiominmax=0.5) - >>> derived.stationaritywindow.update() - >>> derived.ratiominmax.update() - >>> states.reductionfactor(0.0) - >>> logs.loggedobservedvalue = 4.0, 5.0, 5.0 - >>> model.determine_outputcorrection_v1(False) - >>> states.reductionfactor - reductionfactor(1.0) - >>> fluxes.correctedq - correctedq(4.0) + >>> logs.loggedobservedvalue = nan, nan, 3.0 + >>> model.calc_residual_residualanchor_v1() + >>> states.residual, states.residualanchor + (residual(1.0), residualanchor(2.0)) - Setting |ReductionSteps| to zero reduces |ReductionFactor| to zero - immediately once instationary conditions occur: + Restricting |MaxNaNSkip| so that the search does not reach this entry results + in zero values: - >>> control.reductionsteps(0) - >>> logs.loggedobservedvalue = 0.5, 5.0, 5.0 - >>> model.determine_outputcorrection_v1(False) - >>> states.reductionfactor - reductionfactor(0.0) - >>> fluxes.correctedq - correctedq(1.0) + >>> control.maxnanskip(1) + >>> model.calc_residual_residualanchor_v1() + >>> states.residual, states.residualanchor + (residual(0.0), residualanchor(0.0)) - Instationary conditions detected during `historical` mode (the second - call argument is |False|) start a ramp towards zero (here, with - |ReductionSteps| reset to two steps): + A |MaxNaNSkip| value exceeding the log length is no problem: - >>> control.reductionsteps(2) - >>> states.reductionfactor(1.0) - >>> logs.loggedsimulatedvalue = 1.0, 1.0, 1.0 - >>> logs.loggedobservedvalue = 0.5, 5.0, 5.0 - >>> model.determine_outputcorrection_v1(False) - >>> states.stationary - stationary(0.0) - >>> states.reductionfactor - reductionfactor(0.5) + >>> control.maxnanskip(5) + >>> model.calc_residual_residualanchor_v1() + >>> states.residual, states.residualanchor + (residual(1.0), residualanchor(2.0)) - Switching to `forecast` mode (the second call argument is now |True|, - as |Calc_OutputCorr_V1| does automatically) and feeding |numpy.nan| - observations does not reassess |Stationary|; the ramp initiated above - simply continues: + In `forecast` mode, both values stay frozen: - >>> logs.loggedsimulatedvalue = 1.0, 1.0, 1.0 + >>> fluxes.forecastmode = 1.0 >>> logs.loggedobservedvalue = nan, nan, nan - >>> model.determine_outputcorrection_v1(True) - >>> states.stationary - stationary(0.0) - >>> states.reductionfactor - reductionfactor(0.0) - >>> fluxes.correctedq - correctedq(1.0) - - A further forecast step confirms |ReductionFactor| stays at ``0.0`` - instead of jumping back to ``1.0``, as it would if |Stationary| were - reassessed using the now entirely |numpy.nan| logging window: - - >>> model.determine_outputcorrection_v1(True) - >>> states.reductionfactor - reductionfactor(0.0) - >>> fluxes.correctedq - correctedq(1.0) + >>> model.calc_residual_residualanchor_v1() + >>> states.residual, states.residualanchor + (residual(1.0), residualanchor(2.0)) + """ - The same holds for the mean simulated value deciding on the - submodel's responsibility. It was determined at the last `historical` - call (``1.0``) and stays frozen while forecasting. So, even if the - forecasted values rise above |UpperLimit|, the submodel remains - responsible: + CONTROLPARAMETERS = (statcorr_control.MaxNaNSkip,) + DERIVEDPARAMETERS = (statcorr_derived.NmbLogEntries,) + REQUIREDSEQUENCES = ( + statcorr_fluxes.ForecastMode, + statcorr_logs.LoggedSimulatedValue, + statcorr_logs.LoggedObservedValue, + ) + UPDATEDSEQUENCES = (statcorr_states.Residual, statcorr_states.ResidualAnchor) - >>> control.upperlimit(5.0) - >>> logs.loggedsimulatedvalue = 10.0, 10.0, 10.0 - >>> model.determine_outputcorrection_v1(True) - >>> states.evaluatedvalue - evaluatedvalue(1.0) - >>> fluxes.isactive - isactive(1.0) + @staticmethod + def __call__(model: modeltools.Model, /) -> None: + con = model.parameters.control.fastaccess + der = model.parameters.derived.fastaccess + flu = model.sequences.fluxes.fastaccess + log = model.sequences.logs.fastaccess + sta = model.sequences.states.fastaccess + if flu.forecastmode == 0.0: + sta.residual = 0.0 + sta.residualanchor = 0.0 + for idx in range(min(der.nmblogentries, con.maxnanskip + 1)): + if not modelutils.isnan(log.loggedobservedvalue[idx]): + sta.residualanchor = log.loggedsimulatedvalue[idx] + sta.residual = log.loggedobservedvalue[idx] - sta.residualanchor + break + + +class Calc_Stationary_V1(modeltools.Method): + r"""Assess whether the observed values behave in a stationary way while the + stationarity check is enabled (see |StationarityCheck|) and |ForecastMode| is + ``0.0`` (`historical`). + + |Calc_Stationary_V1| takes the ratio of the minimum and the maximum + |LoggedObservedValue| value within the most recent |StationarityWindow| log + entries. Whenever this ratio falls below |RatioMinMax|, it considers the + conditions instationary (|Stationary| is ``0.0``), otherwise stationary + (|Stationary| is ``1.0``). If a |numpy.nan| value within the + |StationarityWindow| prevents calculating the ratio, |Stationary| keeps the + outcome of the previous assessment, so that a single missing observation neither + interrupts an ongoing reduction of |ReductionFactor| (see + |Calc_ReductionFactor_V1|) nor triggers a new one. + + While |ForecastMode| is ``1.0`` (`forecast`), |Calc_Stationary_V1| keeps the + outcome of the most recent `historical` assessment. Recomputing it would be + unreliable, as |LoggedObservedValue| keeps receiving |numpy.nan| values + throughout the forecast (see |Calc_OutputCorr_V1|), which would prevent any new + assessment as soon as the first of them enters the |StationarityWindow|. + + Examples: + + The ratio ``4.0 / 5.0 = 0.8`` is not below |RatioMinMax|: + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> from numpy import nan + >>> control.stationaritycheck(active=True, window=3, ratiominmax=0.5) + >>> derived.stationaritywindow.update() + >>> derived.ratiominmax.update() + >>> derived.nmblogentries(3) + >>> fluxes.forecastmode = 0.0 + >>> logs.loggedobservedvalue = 4.0, 5.0, 5.0 + >>> model.calc_stationary_v1() + >>> states.stationary + stationary(1.0) + + The ratio ``0.5 / 5.0 = 0.1`` is: + + >>> logs.loggedobservedvalue = 0.5, 5.0, 5.0 + >>> model.calc_stationary_v1() + >>> states.stationary + stationary(0.0) + + A single missing observation within the |StationarityWindow| prevents a new + assessment: + + >>> logs.loggedobservedvalue = 4.0, nan, 5.0 + >>> model.calc_stationary_v1() + >>> states.stationary + stationary(0.0) + + In `forecast` mode, |Stationary| stays frozen: + + >>> fluxes.forecastmode = 1.0 + >>> logs.loggedobservedvalue = 4.0, 5.0, 5.0 + >>> model.calc_stationary_v1() + >>> states.stationary + stationary(0.0) + + The same holds when the stationarity check is disabled: + + >>> control.stationaritycheck(active=False) + >>> derived.stationaritywindow.update() + >>> fluxes.forecastmode = 0.0 + >>> model.calc_stationary_v1() + >>> states.stationary + stationary(0.0) + """ + + DERIVEDPARAMETERS = ( + statcorr_derived.NmbLogEntries, + statcorr_derived.StationarityWindow, + statcorr_derived.RatioMinMax, + ) + REQUIREDSEQUENCES = ( + statcorr_fluxes.ForecastMode, + statcorr_logs.LoggedObservedValue, + ) + UPDATEDSEQUENCES = (statcorr_states.Stationary,) + + @staticmethod + def __call__(model: modeltools.Model, /) -> None: + der = model.parameters.derived.fastaccess + flu = model.sequences.fluxes.fastaccess + log = model.sequences.logs.fastaccess + sta = model.sequences.states.fastaccess + if (der.stationaritywindow > 0) and (flu.forecastmode == 0.0): + has_nan = False + qmin: float = modelutils.inf + qmax: float = -modelutils.inf + for idx in range(min(der.nmblogentries, der.stationaritywindow)): + value: float = log.loggedobservedvalue[idx] + if modelutils.isnan(value): + has_nan = True + break + qmin = min(qmin, value) + qmax = max(qmax, value) + if not has_nan: + if qmax > 0.0 and qmin / qmax < der.ratiominmax: + sta.stationary = 0.0 + else: + sta.stationary = 1.0 + + +class Calc_ReductionFactor_V1(modeltools.Method): + r"""Update the factor for damping the correction based on the outcome of the + stationarity check. + + Under instationary conditions (|Stationary| is ``0.0``), + |Calc_ReductionFactor_V1| linearly reduces |ReductionFactor| towards zero, + taking as many steps as given by |ReductionSteps|. As soon as the conditions + are stationary again, |ReductionFactor| jumps back to ``1.0``, applying the + correction unabated again. With the stationarity check disabled (see + |StationarityCheck|), |ReductionFactor| is always ``1.0``. + + As |Stationary| does not change in `forecast` mode (see |Calc_Stationary_V1|), + |ReductionFactor| keeps ramping towards zero (or staying at ``0.0``) for the + entire forecast horizon once a `historical` run has flagged conditions as + instationary. + + Examples: + + Sustained instationary conditions reduce |ReductionFactor| to zero within + the two steps given by |ReductionSteps|: + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> control.reductionsteps(2) + >>> derived.stationaritywindow(3) + >>> states.stationary(0.0) + >>> states.reductionfactor(1.0) + >>> model.calc_reductionfactor_v1() + >>> states.reductionfactor + reductionfactor(0.5) + >>> model.calc_reductionfactor_v1() + >>> states.reductionfactor + reductionfactor(0.0) + >>> model.calc_reductionfactor_v1() + >>> states.reductionfactor + reductionfactor(0.0) + + Stationary conditions reset |ReductionFactor| to ``1.0`` immediately: + + >>> states.stationary(1.0) + >>> model.calc_reductionfactor_v1() + >>> states.reductionfactor + reductionfactor(1.0) + + Setting |ReductionSteps| to zero reduces |ReductionFactor| to zero + immediately once instationary conditions occur: + + >>> control.reductionsteps(0) + >>> states.stationary(0.0) + >>> model.calc_reductionfactor_v1() + >>> states.reductionfactor + reductionfactor(0.0) + + Disabling the stationarity check resets |ReductionFactor| to ``1.0`` + regardless of |Stationary|: + + >>> derived.stationaritywindow(0) + >>> model.calc_reductionfactor_v1() + >>> states.reductionfactor + reductionfactor(1.0) + """ + + CONTROLPARAMETERS = (statcorr_control.ReductionSteps,) + DERIVEDPARAMETERS = (statcorr_derived.StationarityWindow,) + REQUIREDSEQUENCES = (statcorr_states.Stationary,) + UPDATEDSEQUENCES = (statcorr_states.ReductionFactor,) + + @staticmethod + def __call__(model: modeltools.Model, /) -> None: + con = model.parameters.control.fastaccess + der = model.parameters.derived.fastaccess + sta = model.sequences.states.fastaccess + if (der.stationaritywindow <= 0) or (sta.stationary == 1.0): + sta.reductionfactor = 1.0 + elif con.reductionsteps <= 0: + sta.reductionfactor = 0.0 + else: + sta.reductionfactor = max( + 0.0, sta.reductionfactor - 1.0 / con.reductionsteps + ) + + +class Calc_RelSumDelta_V1(modeltools.Method): + r"""Calculate the relative sum of the absolute changes between successive + simulated values while the variability check is enabled (see + |VariabilityCheck|) and |ForecastMode| is ``0.0`` (`historical`). + + Basic equation: + :math:`RelSumDelta = \frac{1}{EvaluatedValue} + \sum_{i=0}^{EvaluationWindow-2} + |LoggedSimulatedValue_i - LoggedSimulatedValue_{i+1}|` + + For a non-positive |EvaluatedValue|, |RelSumDelta| is |numpy.nan|. While + |ForecastMode| is ``1.0`` (`forecast`), |Calc_RelSumDelta_V1| keeps the value of + the most recent `historical` assessment. + + Examples: + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> control.evaluationwindow(3) + >>> derived.stationaryaveragingwindow(3) + >>> derived.nmblogentries(3) + >>> fluxes.forecastmode = 0.0 + >>> logs.loggedsimulatedvalue = 9.0, 10.0, 11.0 + >>> states.evaluatedvalue(10.0) + >>> model.calc_relsumdelta_v1() + >>> states.relsumdelta + relsumdelta(0.2) + + >>> states.evaluatedvalue(0.0) + >>> model.calc_relsumdelta_v1() + >>> states.relsumdelta + relsumdelta(nan) + + In `forecast` mode or with the variability check disabled, |RelSumDelta| + stays unchanged: + + >>> states.evaluatedvalue(10.0) + >>> fluxes.forecastmode = 1.0 + >>> model.calc_relsumdelta_v1() + >>> states.relsumdelta + relsumdelta(nan) + + >>> fluxes.forecastmode = 0.0 + >>> derived.stationaryaveragingwindow(0) + >>> model.calc_relsumdelta_v1() + >>> states.relsumdelta + relsumdelta(nan) + """ + + CONTROLPARAMETERS = (statcorr_control.EvaluationWindow,) + DERIVEDPARAMETERS = (statcorr_derived.StationaryAveragingWindow,) + REQUIREDSEQUENCES = ( + statcorr_fluxes.ForecastMode, + statcorr_logs.LoggedSimulatedValue, + statcorr_states.EvaluatedValue, + ) + UPDATEDSEQUENCES = (statcorr_states.RelSumDelta,) + + @staticmethod + def __call__(model: modeltools.Model, /) -> None: + con = model.parameters.control.fastaccess + der = model.parameters.derived.fastaccess + flu = model.sequences.fluxes.fastaccess + log = model.sequences.logs.fastaccess + sta = model.sequences.states.fastaccess + if (der.stationaryaveragingwindow > 0) and (flu.forecastmode == 0.0): + sumdelta: float = 0.0 + for idx in range(con.evaluationwindow - 1): + sumdelta = sumdelta + modelutils.fabs( + log.loggedsimulatedvalue[idx] - log.loggedsimulatedvalue[idx + 1] + ) + if sta.evaluatedvalue > 0.0: + sta.relsumdelta = sumdelta / sta.evaluatedvalue + else: + sta.relsumdelta = modelutils.nan + + +class Calc_LowVariability_V1(modeltools.Method): + r"""Decide whether the simulated values vary little enough to use the + |StationaryAveragingWindow| instead of the |AveragingWindow| (see + |Calc_AveragedResidual_V1|). + + If the variability check is enabled (see |VariabilityCheck|), + |Calc_LowVariability_V1| considers the conditions stationary (|LowVariability| + is ``1.0``) if |RelSumDelta| does not exceed |MaxRelSumDelta| and the + stationarity check (see |Calc_Stationary_V1|) is either disabled or also detects + stationary conditions. Hence, the variability check never interferes with the + linear reduction of the correction (see |Calc_ReductionFactor_V1|). A + |numpy.nan| value of |RelSumDelta| results in |LowVariability| being ``0.0``. + Like |Calc_RelSumDelta_V1|, |Calc_LowVariability_V1| reassesses + |LowVariability| only while |ForecastMode| is ``0.0`` (`historical`). With the + variability check disabled, |LowVariability| is always ``0.0``. + + Examples: + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> from numpy import nan + >>> derived.stationaryaveragingwindow(3) + >>> derived.maxrelsumdelta(0.2) + >>> derived.stationaritywindow(3) + >>> fluxes.forecastmode = 0.0 + >>> states.stationary(1.0) + >>> states.relsumdelta(0.2) + >>> model.calc_lowvariability_v1() + >>> states.lowvariability + lowvariability(1.0) + + >>> states.relsumdelta(0.4) + >>> model.calc_lowvariability_v1() + >>> states.lowvariability + lowvariability(0.0) + + >>> states.relsumdelta(nan) + >>> model.calc_lowvariability_v1() + >>> states.lowvariability + lowvariability(0.0) + + Instationary conditions according to the stationarity check prevent the + variability check from detecting stationary conditions, unless the + stationarity check is disabled: + + >>> states.relsumdelta(0.2) + >>> states.stationary(0.0) + >>> model.calc_lowvariability_v1() + >>> states.lowvariability + lowvariability(0.0) + + >>> derived.stationaritywindow(0) + >>> model.calc_lowvariability_v1() + >>> states.lowvariability + lowvariability(1.0) + + In `forecast` mode, |LowVariability| stays frozen: + + >>> fluxes.forecastmode = 1.0 + >>> states.relsumdelta(0.4) + >>> model.calc_lowvariability_v1() + >>> states.lowvariability + lowvariability(1.0) + + Disabling the variability check resets |LowVariability| to ``0.0``, even in + `forecast` mode: + + >>> derived.stationaryaveragingwindow(0) + >>> model.calc_lowvariability_v1() + >>> states.lowvariability + lowvariability(0.0) + """ + + DERIVEDPARAMETERS = ( + statcorr_derived.StationarityWindow, + statcorr_derived.MaxRelSumDelta, + statcorr_derived.StationaryAveragingWindow, + ) + REQUIREDSEQUENCES = ( + statcorr_fluxes.ForecastMode, + statcorr_states.Stationary, + statcorr_states.RelSumDelta, + ) + UPDATEDSEQUENCES = (statcorr_states.LowVariability,) + + @staticmethod + def __call__(model: modeltools.Model, /) -> None: + der = model.parameters.derived.fastaccess + flu = model.sequences.fluxes.fastaccess + sta = model.sequences.states.fastaccess + if der.stationaryaveragingwindow <= 0: + sta.lowvariability = 0.0 + elif flu.forecastmode == 0.0: + if ((der.stationaritywindow <= 0) or (sta.stationary == 1.0)) and ( + sta.relsumdelta <= der.maxrelsumdelta + ): + sta.lowvariability = 1.0 + else: + sta.lowvariability = 0.0 + + +class Calc_AveragedResidual_V1(modeltools.Method): + r"""Determine the mean-value-based residual once, at the first forecast step, + and freeze it for the remainder of the current forecast horizon. + + |Calc_AveragedResidual_V1| averages the |LoggedObservedValue| and + |LoggedSimulatedValue| entries covering the |AveragingWindow| log positions + immediately preceding the current forecast run (log position ``0`` already holds + the current forecast step's own values, so averaging starts at position ``1``) + and stores their difference in |AveragedResidual|. It leaves |AveragedResidual| + unchanged whenever |ForecastMode| is ``0.0`` (`historical`), |ForecastStep| is + not zero (i.e., beyond the first forecast step), or |AveragingWindow| is zero + (mean-value-based correction disabled). When the averaging window contains a + |numpy.nan| value, it falls back to the pointwise |Residual| (see + |Calc_Residual_ResidualAnchor_V1|). While |LowVariability| is ``1.0`` + (stationary conditions according to |VariabilityCheck|), the + |StationaryAveragingWindow| replaces the |AveragingWindow|. + + Examples: + + On the first forecast step, the average is taken from log positions ``1`` + and ``2`` (mean observed ``4.0``, mean simulated ``3.0``): + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> from numpy import nan + >>> control.averagingwindow(2) + >>> derived.stationaryaveragingwindow(1) + >>> derived.nmblogentries(3) + >>> fluxes.forecastmode = 1.0 + >>> states.forecaststep(0.0) + >>> states.lowvariability(0.0) + >>> states.residual(-9.0) + >>> logs.loggedsimulatedvalue = 3.0, 2.0, 4.0 + >>> logs.loggedobservedvalue = nan, 3.0, 5.0 + >>> model.calc_averagedresidual_v1() + >>> states.averagedresidual + averagedresidual(1.0) + + On any later forecast step and in `historical` mode, the previously + determined value remains unchanged, regardless of the current log contents: + + >>> logs.loggedsimulatedvalue = 3.0, 20.0, 40.0 + >>> logs.loggedobservedvalue = nan, 30.0, 50.0 + >>> states.forecaststep(1.0) + >>> model.calc_averagedresidual_v1() + >>> states.averagedresidual + averagedresidual(1.0) + + >>> states.forecaststep(0.0) + >>> fluxes.forecastmode = 0.0 + >>> model.calc_averagedresidual_v1() + >>> states.averagedresidual + averagedresidual(1.0) + + Setting |AveragingWindow| to zero disables mean-value-based correction: + + >>> fluxes.forecastmode = 1.0 + >>> control.averagingwindow(0) + >>> model.calc_averagedresidual_v1() + >>> states.averagedresidual + averagedresidual(1.0) + + A |numpy.nan| value within the averaging window makes + |Calc_AveragedResidual_V1| fall back to |Residual|: + + >>> control.averagingwindow(2) + >>> logs.loggedobservedvalue = nan, nan, 50.0 + >>> model.calc_averagedresidual_v1() + >>> states.averagedresidual + averagedresidual(-9.0) + + Under stationary conditions according to |VariabilityCheck|, the averaging + period covers the single log position ``1`` given by + |StationaryAveragingWindow| (``30.0 - 20.0``), even if |AveragingWindow| is + zero: + + >>> control.averagingwindow(0) + >>> states.lowvariability(1.0) + >>> logs.loggedobservedvalue = nan, 30.0, nan + >>> model.calc_averagedresidual_v1() + >>> states.averagedresidual + averagedresidual(10.0) + """ + + CONTROLPARAMETERS = (statcorr_control.AveragingWindow,) + DERIVEDPARAMETERS = ( + statcorr_derived.NmbLogEntries, + statcorr_derived.StationaryAveragingWindow, + ) + REQUIREDSEQUENCES = ( + statcorr_fluxes.ForecastMode, + statcorr_logs.LoggedSimulatedValue, + statcorr_logs.LoggedObservedValue, + statcorr_states.LowVariability, + statcorr_states.ForecastStep, + statcorr_states.Residual, + ) + UPDATEDSEQUENCES = (statcorr_states.AveragedResidual,) + + @staticmethod + def __call__(model: modeltools.Model, /) -> None: + con = model.parameters.control.fastaccess + der = model.parameters.derived.fastaccess + flu = model.sequences.fluxes.fastaccess + log = model.sequences.logs.fastaccess + sta = model.sequences.states.fastaccess + if sta.lowvariability == 1.0: + nmb = min(der.stationaryaveragingwindow, der.nmblogentries - 1) + else: + nmb = min(con.averagingwindow, der.nmblogentries - 1) + if (flu.forecastmode == 1.0) and (sta.forecaststep == 0.0) and (nmb > 0): + sum_obs: float = 0.0 + sum_sim: float = 0.0 + has_nan = False + for idx in range(1, nmb + 1): + obs_value: float = log.loggedobservedvalue[idx] + sim_value: float = log.loggedsimulatedvalue[idx] + if modelutils.isnan(obs_value) or modelutils.isnan(sim_value): + has_nan = True + break + sum_obs = sum_obs + obs_value + sum_sim = sum_sim + sim_value + if has_nan: + sta.averagedresidual = sta.residual + else: + sta.averagedresidual = (sum_obs - sum_sim) / nmb - Only a `historical` call updates |EvaluatedValue|, which then exceeds - |UpperLimit|, so the submodel stops correcting: - >>> model.determine_outputcorrection_v1(False) - >>> states.evaluatedvalue - evaluatedvalue(10.0) - >>> fluxes.isactive - isactive(0.0) - >>> fluxes.correctedq - correctedq(10.0) +class Calc_CorrectedQ_V1(modeltools.Method): + r"""Calculate the corrected value by shifting the current simulated value based + on the (damped) residual. - Enlarging the log beyond |EvaluationWindow| does not change the - responsibility assessment, which always relies on the *most recently* - logged |LoggedSimulatedValue| entries (index ``0`` upwards) and - never on the oldest ones sitting near the end of a larger log (which - can well still be |numpy.nan|, as is the case for the newly added - entries here): + If the submodel is not responsible (|IsActive| is ``0.0``), the corrected value + equals the current simulated value (:math:`sim_0`). Otherwise, how the residual + (:math:`r`) applies depends on how :math:`sim_0` compares to |ResidualAnchor| + (:math:`sim_k`, the simulated value at the time the residual was determined), + with :math:`f_{red}` denoting |ReductionFactor|: - >>> control.upperlimit(inf) + * If :math:`0 < sim_0 < sim_k`, |Calc_CorrectedQ_V1| shifts :math:`sim_0` + *multiplicatively*, expressing the damped residual as a fraction of + :math:`sim_k` and capping that fraction at |MaxRelShift|: + + :math:`CorrectedQ = sim_0 \cdot \left(1 + \mathrm{clip}\left(r \cdot f_{red} + / sim_k,\ \pm MaxRelShift\right) \right)` + + Applying the residual as a fraction rather than a constant offset keeps the + correction from overshooting or turning negative while the simulated values + recede towards zero. + + * Otherwise (:math:`sim_0 \geq sim_k` or :math:`sim_0 \leq 0`), it shifts + :math:`sim_0` *additively*, capping the damped residual at |MaxAbsShift|: + + :math:`CorrectedQ = sim_0 + \mathrm{clip}\left(r \cdot f_{red},\ + \pm MaxAbsShift\right)` + + This includes the `historical` mode whenever the current observation is + available, as :math:`sim_k` then equals :math:`sim_0`. + + In `historical` mode (|ForecastMode| is ``0.0``), :math:`r` is the pointwise + |Residual|. In `forecast` mode, setting |AveragingWindow| to a value greater + than zero (or |LowVariability| being ``1.0``) switches to the mean-value-based + |AveragedResidual| (see |Calc_AveragedResidual_V1|). Since it generally does + not equal the pointwise residual at the forecast's start, switching to it + abruptly would cause a jump in the corrected value right where the forecast + begins. To avoid this, |Calc_CorrectedQ_V1| starts every forecast run with the + pointwise residual (so the corrected value picks up smoothly where the last + measurement left off) and then linearly blends it towards the mean-value-based + residual over |TransitionSteps| forecast steps (counted by |ForecastStep|), + applying the mean-value-based residual unabated from then on: + + :math:`r = Residual + \min\left(1, \frac{ForecastStep}{TransitionSteps} + \right) \cdot (AveragedResidual - Residual)` + + Examples: + + If the submodel is not responsible, no correction applies: + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> control.maxabsshift(100.0) + >>> control.maxrelshift(10.0) + >>> control.averagingwindow(0) + >>> control.transitionsteps(0) + >>> derived.nmblogentries(1) + >>> fluxes.forecastmode = 0.0 + >>> fluxes.isactive = 0.0 >>> states.reductionfactor(1.0) - >>> derived.nmblogentries(5) - >>> logs.loggedsimulatedvalue = 1.0, 1.0, 1.0, nan, nan - >>> logs.loggedobservedvalue = 0.5, 5.0, 5.0, nan, nan - >>> model.determine_outputcorrection_v1(False) - >>> fluxes.isactive - isactive(1.0) - >>> states.stationary - stationary(0.0) - >>> states.reductionfactor - reductionfactor(0.5) + >>> states.lowvariability(0.0) + >>> states.forecaststep(0.0) + >>> states.averagedresidual(0.0) + >>> states.residual(1.0) + >>> states.residualanchor(5.0) + >>> logs.loggedsimulatedvalue = 6.0 + >>> model.calc_correctedq_v1() + >>> fluxes.correctedq + correctedq(6.0) - Restricting |MaxNaNSkip| so that the search does not cover the full log - makes |Determine_OutputCorrection_V1| stop searching for a valid - residual once that limit is reached, applying no correction even - though an older, still-logged observation would otherwise be usable. - The following examples contain missing observations, which prevent a - new stationarity assessment. To focus on the residual search, we reset - |Stationary| to ``1.0`` so that |ReductionFactor| returns to ``1.0``: + The current simulated value exceeds |ResidualAnchor|, so the residual + applies additively: - >>> states.stationary(1.0) - >>> control.maxnanskip(1) - >>> logs.loggedsimulatedvalue = 1.0, 1.0, 1.0, nan, nan - >>> logs.loggedobservedvalue = nan, nan, 3.0, nan, nan - >>> model.determine_outputcorrection_v1(False) + >>> fluxes.isactive = 1.0 + >>> model.calc_correctedq_v1() >>> fluxes.correctedq - correctedq(1.0) + correctedq(7.0) - Enlarging |MaxNaNSkip| to reach that entry again reinstates - the correction: + |ReductionFactor| dampens the residual: - >>> control.maxnanskip(2) - >>> model.determine_outputcorrection_v1(False) + >>> states.reductionfactor(0.5) + >>> model.calc_correctedq_v1() >>> fluxes.correctedq - correctedq(3.0) + correctedq(6.5) - So far, the current forecast value (log position 0) has always been - at or above the simulated value at the time the residual was - determined, so all examples above used the additive (or, at position - 0 itself, an equivalent) shift. Resetting the log to a *receding* - forecast — position 0 has already dropped clearly below the value at - the residual's log position — switches to the relative - (multiplicative) shift instead: + |MaxAbsShift| caps the additive shift: - >>> logs.loggedsimulatedvalue = 2.0, 10.0, 10.0, nan, nan - >>> logs.loggedobservedvalue = nan, 12.0, nan, nan, nan - >>> model.determine_outputcorrection_v1(False) + >>> states.reductionfactor(1.0) + >>> control.maxabsshift(0.2) + >>> model.calc_correctedq_v1() + >>> fluxes.correctedq + correctedq(6.2) + + For a *receding* simulation (the current simulated value is below + |ResidualAnchor|), the residual applies multiplicatively: + + >>> control.maxabsshift(100.0) + >>> states.residual(2.0) + >>> states.residualanchor(10.0) + >>> logs.loggedsimulatedvalue = 2.0 + >>> model.calc_correctedq_v1() >>> fluxes.correctedq correctedq(2.4) - Limiting |MaxRelShift| to ``0.1`` caps that fraction at 10 % before it - is converted back into an absolute shift: + Limiting |MaxRelShift| to ``0.1`` caps that fraction at 10 % before it is + converted back into an absolute shift: >>> control.maxrelshift(0.1) - >>> model.determine_outputcorrection_v1(False) + >>> model.calc_correctedq_v1() >>> fluxes.correctedq correctedq(2.2) - Likewise, |MaxAbsShift| caps the additive shift applied whenever - the forecast value exceeds the anchor value: + If the current simulated value equals |ResidualAnchor| (as in `historical` + mode whenever the current observation is available), the residual applies + additively, so |MaxRelShift| has no effect: - >>> control.maxabsshift(1.0) - >>> logs.loggedsimulatedvalue = 12.0, 10.0, 10.0, nan, nan - >>> model.determine_outputcorrection_v1(False) + >>> control.maxrelshift(0.0) + >>> logs.loggedsimulatedvalue = 10.0 + >>> model.calc_correctedq_v1() >>> fluxes.correctedq - correctedq(13.0) + correctedq(12.0) - When the anchor value is zero or negative, a relative shift would be - undefined (division by zero), so |Determine_OutputCorrection_V1| - falls back to the additive shift in that case as well, even though - the forecast value does not exceed the anchor value: + The same holds for a non-positive current simulated value: - >>> control.maxabsshift(100.0) - >>> logs.loggedsimulatedvalue = 0.0, 0.0, 10.0, nan, nan - >>> logs.loggedobservedvalue = nan, 2.0, nan, nan, nan - >>> model.determine_outputcorrection_v1(False) + >>> logs.loggedsimulatedvalue = 0.0 + >>> model.calc_correctedq_v1() >>> fluxes.correctedq correctedq(2.0) + >>> control.maxrelshift(10.0) - Setting |AveragingWindow| to a value greater than zero - switches to the mean-value-based residual, blended in linearly over - |TransitionSteps| forecast steps. We reset the log to a - short, clean example (four entries) and freeze |EvaluatedValue|, - |Stationary|, |Residual|, and |ResidualAnchor| directly (instead of - deriving them from a preceding `historical` call) to keep the focus on - the transition mechanism: + Now, we demonstrate the transition from the pointwise residual (``1.0``) + to the mean-value-based residual (``2.5``) over two forecast steps. On the + first forecast step, |Calc_CorrectedQ_V1| applies the pointwise residual + unabated: - >>> control.maxnanskip(3) - >>> control.maxabsshift(100.0) - >>> control.maxrelshift(10.0) >>> control.averagingwindow(2) >>> control.transitionsteps(2) - >>> derived.nmblogentries(4) - >>> states.evaluatedvalue(8.0) - >>> states.stationary(1.0) - >>> states.reductionfactor(1.0) - >>> states.forecaststep(0.0) + >>> fluxes.forecastmode = 1.0 >>> states.residual(1.0) >>> states.residualanchor(8.0) - - The most recent (pointwise) residual, taken from log position ``1`` - (``9.0 - 8.0 = 1.0``), differs from the mean-value-based residual - taken from log positions ``1`` and ``2`` (mean observed ``8.5``, mean - simulated ``6.0``, hence ``2.5``). On the first forecast step, - |Determine_OutputCorrection_V1| applies the pointwise residual - unabated: - - >>> logs.loggedsimulatedvalue = 10.0, 8.0, 4.0, nan - >>> logs.loggedobservedvalue = nan, 9.0, 8.0, nan - >>> model.determine_outputcorrection_v1(True) - >>> states.averagedresidual - averagedresidual(2.5) + >>> states.averagedresidual(2.5) + >>> logs.loggedsimulatedvalue = 10.0 + >>> model.calc_correctedq_v1() >>> fluxes.correctedq correctedq(11.0) - Halfway through the two-step transition, the applied residual is the - average of both (``1.75``): + Halfway through the transition, the applied residual is the average of both + (``1.75``): - >>> logs.loggedsimulatedvalue = 11.0, 10.0, 8.0, 4.0 - >>> logs.loggedobservedvalue = nan, nan, 9.0, 8.0 - >>> model.determine_outputcorrection_v1(True) + >>> states.forecaststep(1.0) + >>> logs.loggedsimulatedvalue = 11.0 + >>> model.calc_correctedq_v1() >>> fluxes.correctedq correctedq(12.75) - Once the transition period has elapsed, the full mean-value-based - residual applies, regardless of the (still aging) pointwise residual: + Once the transition period has elapsed, the full mean-value-based residual + applies: - >>> logs.loggedsimulatedvalue = 12.0, 11.0, 10.0, 8.0 - >>> logs.loggedobservedvalue = nan, nan, nan, 9.0 - >>> model.determine_outputcorrection_v1(True) - >>> states.averagedresidual - averagedresidual(2.5) + >>> states.forecaststep(2.0) + >>> logs.loggedsimulatedvalue = 12.0 + >>> model.calc_correctedq_v1() >>> fluxes.correctedq correctedq(14.5) - The mean-value-based residual only applies to forecast runs. During - `historical` runs, |Determine_OutputCorrection_V1| always relies on the - pointwise residual, so that the corrected value reproduces the current - observation even if |TransitionSteps| is zero (which would otherwise - apply the mean-value-based residual unabated): + Setting |TransitionSteps| to zero applies the mean-value-based residual + immediately: >>> control.transitionsteps(0) - >>> logs.loggedsimulatedvalue = 1.0, 2.0, 4.0, 6.0 - >>> logs.loggedobservedvalue = 5.0, 3.0, 4.0, 6.0 - >>> model.determine_outputcorrection_v1(False) - >>> states.averagedresidual - averagedresidual(2.5) + >>> states.forecaststep(0.0) + >>> model.calc_correctedq_v1() >>> fluxes.correctedq - correctedq(5.0) - >>> control.transitionsteps(2) + correctedq(14.5) - Next, we enable the variability check. In the following `historical` - call, the absolute changes of the simulated values within the - |EvaluationWindow| sum up to ``2.0``, which is 20 % of their mean value - (``10.0``). So, |RelSumDelta| does not exceed |MaxRelSumDelta|, and - (as the stationarity check also detects stationary conditions) - |LowVariability| becomes ``1.0``: + Under stationary conditions according to |VariabilityCheck| (see + |Calc_LowVariability_V1|), the mean-value-based residual applies even if + |AveragingWindow| is zero: - >>> control.variabilitycheck(maxrelsumdelta=0.2, averagingwindow=3) - >>> derived.maxrelsumdelta.update() - >>> derived.stationaryaveragingwindow.update() - >>> logs.loggedsimulatedvalue = 9.0, 10.0, 11.0, 10.0 - >>> logs.loggedobservedvalue = 10.0, 12.0, 14.0, 12.0 - >>> model.determine_outputcorrection_v1(False) - >>> states.stationary - stationary(1.0) - >>> states.relsumdelta - relsumdelta(0.2) - >>> states.lowvariability - lowvariability(1.0) + >>> control.averagingwindow(0) + >>> states.lowvariability(1.0) + >>> model.calc_correctedq_v1() >>> fluxes.correctedq - correctedq(10.0) + correctedq(14.5) - In the subsequent forecast run, the mean-value-based residual covers the - three log entries given by |StationaryAveragingWindow| (mean observed - ``12.0``, mean simulated ``10.0``) instead of the two given by - |AveragingWindow|. The transition from the pointwise residual - (``1.0``) works as before: + In `historical` mode, |Calc_CorrectedQ_V1| always relies on the pointwise + residual, so that the corrected value reproduces the current observation: - >>> logs.loggedsimulatedvalue = 12.0, 9.0, 10.0, 11.0 - >>> logs.loggedobservedvalue = nan, 10.0, 12.0, 14.0 - >>> model.determine_outputcorrection_v1(True) - >>> states.averagedresidual - averagedresidual(2.0) + >>> fluxes.forecastmode = 0.0 + >>> model.calc_correctedq_v1() >>> fluxes.correctedq correctedq(13.0) + """ - >>> logs.loggedsimulatedvalue = 13.0, 12.0, 9.0, 10.0 - >>> logs.loggedobservedvalue = nan, nan, 10.0, 12.0 - >>> model.determine_outputcorrection_v1(True) - >>> fluxes.correctedq - correctedq(14.5) + CONTROLPARAMETERS = ( + statcorr_control.MaxAbsShift, + statcorr_control.MaxRelShift, + statcorr_control.AveragingWindow, + statcorr_control.TransitionSteps, + ) + REQUIREDSEQUENCES = ( + statcorr_fluxes.ForecastMode, + statcorr_fluxes.IsActive, + statcorr_logs.LoggedSimulatedValue, + statcorr_states.ReductionFactor, + statcorr_states.LowVariability, + statcorr_states.ForecastStep, + statcorr_states.AveragedResidual, + statcorr_states.Residual, + statcorr_states.ResidualAnchor, + ) + RESULTSEQUENCES = (statcorr_fluxes.CorrectedQ,) - >>> logs.loggedsimulatedvalue = 14.0, 13.0, 12.0, 9.0 - >>> logs.loggedobservedvalue = nan, nan, nan, 10.0 - >>> model.determine_outputcorrection_v1(True) - >>> states.lowvariability - lowvariability(1.0) - >>> fluxes.correctedq - correctedq(16.0) + @staticmethod + def __call__(model: modeltools.Model, /) -> None: + con = model.parameters.control.fastaccess + flu = model.sequences.fluxes.fastaccess + log = model.sequences.logs.fastaccess + sta = model.sequences.states.fastaccess + sim: float = log.loggedsimulatedvalue[0] + if flu.isactive == 0.0: + flu.correctedq = sim + else: + residual: float = sta.residual + if (flu.forecastmode == 1.0) and ( + (con.averagingwindow > 0) or (sta.lowvariability == 1.0) + ): + weight: float = 1.0 + if con.transitionsteps > 0: + weight = min(1.0, sta.forecaststep / con.transitionsteps) + residual = residual + weight * (sta.averagedresidual - residual) + residual = residual * sta.reductionfactor + if 0.0 < sim < sta.residualanchor: + flu.correctedq = sim + sim * min( + con.maxrelshift, + max(-con.maxrelshift, residual / sta.residualanchor), + ) + else: + flu.correctedq = sim + min( + con.maxabsshift, max(-con.maxabsshift, residual) + ) - A larger variability (``4.0 / 10.0 = 0.4``) exceeds |MaxRelSumDelta|, so - the next forecast run falls back to the |AveragingWindow| (mean - observed ``11.0``, mean simulated ``9.0``) instead of using the - |StationaryAveragingWindow| (which would result in a value of ``3.0``): - >>> logs.loggedsimulatedvalue = 8.0, 10.0, 12.0, 9.0 - >>> logs.loggedobservedvalue = 10.0, 12.0, 14.0, 12.0 - >>> model.determine_outputcorrection_v1(False) - >>> states.relsumdelta - relsumdelta(0.4) - >>> states.lowvariability - lowvariability(0.0) - >>> logs.loggedsimulatedvalue = 12.0, 8.0, 10.0, 9.0 - >>> logs.loggedobservedvalue = nan, 10.0, 12.0, 14.0 - >>> model.determine_outputcorrection_v1(True) - >>> states.averagedresidual - averagedresidual(2.0) +class Update_ForecastStep_V1(modeltools.Method): + r"""Count the forecast steps since the last `historical` simulation step. - Instationary conditions according to the stationarity check (ratio - ``5.0 / 14.0``, below |RatioMinMax|) prevent the variability check from - detecting stationary conditions, even if |RelSumDelta| does not exceed - |MaxRelSumDelta|: + Basic equation: + :math:`ForecastStep_{new} = \begin{cases} + ForecastStep_{old} + 1 &|\ ForecastMode = 1 \\ + 0 &|\ ForecastMode = 0 + \end{cases}` - >>> logs.loggedsimulatedvalue = 9.0, 10.0, 11.0, 10.0 - >>> logs.loggedobservedvalue = 5.0, 12.0, 14.0, 12.0 - >>> model.determine_outputcorrection_v1(False) - >>> states.stationary - stationary(0.0) - >>> states.relsumdelta - relsumdelta(0.2) - >>> states.lowvariability - lowvariability(0.0) + Examples: - For a non-positive |EvaluatedValue|, |RelSumDelta| is undefined, and - |Determine_OutputCorrection_V1| does not consider the conditions - stationary: + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> states.forecaststep(0.0) + >>> fluxes.forecastmode = 1.0 + >>> model.update_forecaststep_v1() + >>> model.update_forecaststep_v1() + >>> states.forecaststep + forecaststep(2.0) + + >>> fluxes.forecastmode = 0.0 + >>> model.update_forecaststep_v1() + >>> states.forecaststep + forecaststep(0.0) + """ - >>> logs.loggedsimulatedvalue = 0.0, 0.0, 0.0, 0.0 - >>> logs.loggedobservedvalue = 1.0, 1.0, 1.0, 1.0 - >>> model.determine_outputcorrection_v1(False) - >>> states.relsumdelta - relsumdelta(nan) - >>> states.lowvariability - lowvariability(0.0) + REQUIREDSEQUENCES = (statcorr_fluxes.ForecastMode,) + UPDATEDSEQUENCES = (statcorr_states.ForecastStep,) - Disabling the variability check resets |LowVariability| to ``0.0``: + @staticmethod + def __call__(model: modeltools.Model, /) -> None: + flu = model.sequences.fluxes.fastaccess + sta = model.sequences.states.fastaccess + if flu.forecastmode == 1.0: + sta.forecaststep = sta.forecaststep + 1.0 + else: + sta.forecaststep = 0.0 + + +class Determine_OutputCorrection_V1(modeltools.SetAutoMethod): + r"""Interface method that calculates the corrected value using an + ARIMA(0,1,0) error model. + + |Determine_OutputCorrection_V1| stores the given simulation mode in + |ForecastMode| and then executes the following submethods: + + * |Calc_EvaluatedValue_V1| and |Calc_IsActive_V1| decide whether the submodel + is responsible for the current simulated value. + * |Calc_Residual_ResidualAnchor_V1| determines the most recent pointwise + residual. + * |Calc_Stationary_V1| and |Calc_ReductionFactor_V1| dampen the correction under + instationary conditions. + * |Calc_RelSumDelta_V1|, |Calc_LowVariability_V1|, and + |Calc_AveragedResidual_V1| determine the mean-value-based residual for + forecast runs. + * |Calc_CorrectedQ_V1| applies the resulting residual to the current simulated + value. + * |Update_ForecastStep_V1| counts the forecast steps. + + All submethods update the internal states even when the submodel is not + responsible, so that a submodel taking over responsibility starts with + up-to-date information. While |ForecastMode| is ``1.0`` (`forecast`), they keep + the outcomes of the most recent `historical` assessment (the responsibility, the + pointwise residual, and the stationarity and variability assessments), so that + only |ReductionFactor| and, if configured, the blend towards |AveragedResidual| + can still change the correction once a forecast run is underway. - >>> states.lowvariability(1.0) - >>> control.variabilitycheck(False) + Example: + + In `historical` mode, the correction reproduces the most recent + observation: + + >>> from hydpy.models.statcorr_arima010 import * + >>> parameterstep() + >>> from numpy import inf, nan + >>> derived.nmblogentries(3) + >>> control.evaluationwindow(3) + >>> control.active(True) + >>> control.correctionmode(option="both") + >>> control.lowerlimit(0.0) + >>> control.upperlimit(inf) + >>> control.stationaritycheck(active=False) + >>> derived.stationaritywindow.update() + >>> derived.ratiominmax.update() + >>> control.variabilitycheck(active=False) >>> derived.maxrelsumdelta.update() >>> derived.stationaryaveragingwindow.update() + >>> control.reductionsteps(2) + >>> control.maxnanskip(2) + >>> control.maxabsshift(100.0) + >>> control.maxrelshift(10.0) + >>> control.averagingwindow(0) + >>> control.transitionsteps(0) + >>> logs.loggedsimulatedvalue = 5.0, 3.0, 2.0 + >>> logs.loggedobservedvalue = 6.0, 4.0, 3.0 + >>> model.determine_outputcorrection_v1(False) + >>> fluxes.forecastmode + forecastmode(0.0) + >>> fluxes.isactive + isactive(1.0) + >>> fluxes.correctedq + correctedq(6.0) + + In `forecast` mode, the residual of the last `historical` step persists: + + >>> logs.loggedsimulatedvalue = 7.0, 5.0, 3.0 + >>> logs.loggedobservedvalue = nan, 6.0, 4.0 >>> model.determine_outputcorrection_v1(True) - >>> states.lowvariability - lowvariability(0.0) + >>> fluxes.forecastmode + forecastmode(1.0) + >>> fluxes.correctedq + correctedq(8.0) + >>> states.forecaststep + forecaststep(1.0) """ - SUBMETHODS = (Calc_AveragedResidual_V1,) + SUBMETHODS = ( + Set_ForecastMode_V1, + Calc_EvaluatedValue_V1, + Calc_IsActive_V1, + Calc_Residual_ResidualAnchor_V1, + Calc_Stationary_V1, + Calc_ReductionFactor_V1, + Calc_RelSumDelta_V1, + Calc_LowVariability_V1, + Calc_AveragedResidual_V1, + Calc_CorrectedQ_V1, + Update_ForecastStep_V1, + ) CONTROLPARAMETERS = ( statcorr_control.Active, statcorr_control.CorrectionMode, @@ -1283,134 +1630,11 @@ class Determine_OutputCorrection_V1(modeltools.Method): statcorr_states.Residual, statcorr_states.ResidualAnchor, ) - RESULTSEQUENCES = (statcorr_fluxes.IsActive, statcorr_fluxes.CorrectedQ) - - @staticmethod - def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: - # pylint: disable=too-many-branches - con = model.parameters.control.fastaccess - der = model.parameters.derived.fastaccess - flu = model.sequences.fluxes.fastaccess - log = model.sequences.logs.fastaccess - sta = model.sequences.states.fastaccess - - assert der.nmblogentries >= con.evaluationwindow - - if not isforecastmode: - mean_simulated: float = 0.0 - for idx in range(con.evaluationwindow): - mean_simulated = mean_simulated + log.loggedsimulatedvalue[idx] - sta.evaluatedvalue = mean_simulated / con.evaluationwindow - if con.correctionmode == 3: - modeallowed = True - elif isforecastmode: - modeallowed = con.correctionmode == 2 - else: - modeallowed = con.correctionmode == 1 - if ( - con.active - and modeallowed - and (con.lowerlimit <= sta.evaluatedvalue < con.upperlimit) - ): - flu.isactive = 1.0 - else: - flu.isactive = 0.0 - - residual: float - sim_anchor: float - if isforecastmode: - residual = sta.residual - sim_anchor = sta.residualanchor - else: - residual = 0.0 - sim_anchor = 0.0 - for idx in range(min(der.nmblogentries, con.maxnanskip + 1)): - if not modelutils.isnan(log.loggedobservedvalue[idx]): - sim_anchor = log.loggedsimulatedvalue[idx] - residual = log.loggedobservedvalue[idx] - sim_anchor - break - sta.residual = residual - sta.residualanchor = sim_anchor - - if der.stationaritywindow <= 0: - sta.reductionfactor = 1.0 - else: - if not isforecastmode: - nmb = min(der.nmblogentries, der.stationaritywindow) - has_nan = False - qmin: float = modelutils.inf - qmax: float = -modelutils.inf - for idx in range(nmb): - value: float = log.loggedobservedvalue[idx] - if modelutils.isnan(value): - has_nan = True - break - qmin = min(qmin, value) - qmax = max(qmax, value) - if not has_nan: - if qmax > 0.0 and qmin / qmax < der.ratiominmax: - sta.stationary = 0.0 - else: - sta.stationary = 1.0 - - if sta.stationary: - sta.reductionfactor = 1.0 - elif con.reductionsteps <= 0: - sta.reductionfactor = 0.0 - else: - sta.reductionfactor = max( - 0.0, sta.reductionfactor - 1.0 / con.reductionsteps - ) - - if der.stationaryaveragingwindow <= 0: - sta.lowvariability = 0.0 - elif not isforecastmode: - sumdelta: float = 0.0 - for idx in range(con.evaluationwindow - 1): - sumdelta = sumdelta + modelutils.fabs( - log.loggedsimulatedvalue[idx] - log.loggedsimulatedvalue[idx + 1] - ) - if sta.evaluatedvalue > 0.0: - sta.relsumdelta = sumdelta / sta.evaluatedvalue - else: - sta.relsumdelta = modelutils.nan - if (der.stationaritywindow <= 0 or sta.stationary == 1.0) and ( - sta.relsumdelta <= der.maxrelsumdelta - ): - sta.lowvariability = 1.0 - else: - sta.lowvariability = 0.0 - - forecast_step: float = sta.forecaststep if isforecastmode else 0.0 - sta.forecaststep = (forecast_step + 1.0) if isforecastmode else 0.0 - if isforecastmode: - model.calc_averagedresidual_v1(forecast_step, residual) - - forecast_value: float = log.loggedsimulatedvalue[0] - if flu.isactive == 0.0: - flu.correctedq = forecast_value - return - - effective_residual: float = ( - residual - if not isforecastmode - or (con.averagingwindow <= 0 and sta.lowvariability == 0.0) - else residual - + ( - 1.0 - if con.transitionsteps <= 0 - else min(1.0, forecast_step / con.transitionsteps) - ) - * (sta.averagedresidual - residual) - ) - damped_residual: float = effective_residual * sta.reductionfactor - shift: float = ( - forecast_value - * min(con.maxrelshift, max(-con.maxrelshift, damped_residual / sim_anchor)) - if sim_anchor > 0.0 and forecast_value <= sim_anchor - else min(con.maxabsshift, max(-con.maxabsshift, damped_residual)) - ) - flu.correctedq = forecast_value + shift + RESULTSEQUENCES = ( + statcorr_fluxes.ForecastMode, + statcorr_fluxes.IsActive, + statcorr_fluxes.CorrectedQ, + ) class Is_Active_V1(modeltools.Method): diff --git a/hydpy/models/statcorr/statcorr_states.py b/hydpy/models/statcorr/statcorr_states.py index 71aa7fc9f7..4340b69ecc 100644 --- a/hydpy/models/statcorr/statcorr_states.py +++ b/hydpy/models/statcorr/statcorr_states.py @@ -40,7 +40,7 @@ class EvaluatedValue(sequencetools.StateSequence): entries, as determined at the last `historical` assessment [unit of the corrected variable]. - |Determine_OutputCorrection_V1| compares |EvaluatedValue| with |LowerLimit| + |Calc_IsActive_V1| compares |EvaluatedValue| with |LowerLimit| and |UpperLimit| to decide whether the submodel is responsible for correcting the simulated values. Like |Stationary|, |statcorr_arima010| only reassesses |EvaluatedValue| while |Options.simulationmode| equals `historical`. @@ -84,7 +84,7 @@ class ForecastStep(sequencetools.StateSequence): forecast run (``0.0`` on the first forecast step), reset to ``0.0`` whenever |Options.simulationmode| equals `historical` [-]. - |Determine_OutputCorrection_V1| uses |ForecastStep| to linearly blend the + |Calc_CorrectedQ_V1| uses |ForecastStep| to linearly blend the applied residual from the single most recent (pointwise) value towards the mean-value-based residual determined via |AveragingWindow| over |TransitionSteps| forecast steps.""" diff --git a/hydpy/models/statcorr_arima010.py b/hydpy/models/statcorr_arima010.py index 827b955801..4fa1060fa2 100644 --- a/hydpy/models/statcorr_arima010.py +++ b/hydpy/models/statcorr_arima010.py @@ -7,8 +7,8 @@ (observed minus simulated values). While |Options.simulationmode| equals `historical`, this residual is (re)determined every step by skipping at most |MaxNaNSkip| log entries with missing observations to find the latest -non-|numpy.nan| observation — this is the random-walk persistence of the error -whenever the *current* observation is missing. When no observation is available within +non-|numpy.nan| observation, so that the error persists whenever the *current* +observation is missing. When no observation is available within that range (or the entire log, whichever is smaller), no correction is applied. While |Options.simulationmode| equals `forecast`, this search is not repeated: the residual (and the simulated value it was measured @@ -19,19 +19,19 @@ How the residual is applied depends on how the current simulated value compares to the simulated value at the point the residual was determined: -if it is higher (or the anchor value is not positive), the residual is added -unchanged (capped at |MaxAbsShift|); otherwise, it is applied relative to that anchor -value instead (capped at |MaxRelShift|), which keeps the correction from -overshooting or turning negative while the simulated values recede. See -|Determine_OutputCorrection_V1| for the exact formulas. +if it is positive and lower than this anchor value, the residual is applied +relative to the anchor value (capped at |MaxRelShift|), which keeps the correction +from overshooting or turning negative while the simulated values recede; +otherwise, the residual is added unchanged (capped at |MaxAbsShift|). See +|Calc_CorrectedQ_V1| for the exact formulas. Setting |AveragingWindow| to a value greater than zero switches from that pointwise residual to a mean-value-based one (mean observed minus mean simulated values over the given number of log entries immediately preceding the current forecast run), blended in linearly over |TransitionSteps| forecast steps to avoid a jump right where the -forecast begins. See |Determine_OutputCorrection_V1| and -|Calc_AveragedResidual_V1| for details. +forecast begins. See |Calc_AveragedResidual_V1| and |Calc_CorrectedQ_V1| for +details. Each |statcorr_arima010| instance is responsible for a specific value range only, defined by |LowerLimit| and |UpperLimit|, and can be switched off completely @@ -58,10 +58,10 @@ >>> control.lowerlimit(0.0) >>> control.upperlimit(inf) >>> control.evaluationwindow(3) - >>> control.stationaritycheck(False) + >>> control.stationaritycheck(active=False) >>> derived.stationaritywindow.update() >>> derived.ratiominmax.update() - >>> control.variabilitycheck(False) + >>> control.variabilitycheck(active=False) >>> derived.maxrelsumdelta.update() >>> derived.stationaryaveragingwindow.update() >>> control.reductionsteps(1) @@ -95,7 +95,7 @@ loggedobservedvalue(nan, 4.0, 3.0) |OutputCorrModel_V1.determine_outputcorrection| computes the corrected - value from the random-walk residual (here taken from log position 1, + value from the most recent residual (here taken from log position 1, since position 0 has no observation) and stores it internally; |OutputCorrModel_V1.is_active| confirms the submodel is responsible for the current value, and |OutputCorrModel_V1.get_correctedoutput| returns the @@ -121,8 +121,7 @@ class Model(statcorr_model.Sub_OutputCorrModel, statcorrinterfaces.OutputCorrMod """|statcorr_arima010.DOCNAME.complete|.""" DOCNAME = modeltools.DocName( - short="StatCorr-ARIMA010", - description="ARIMA(0,1,0) — random walk — output correction ", + short="StatCorr-ARIMA010", description="ARIMA(0,1,0) output correction " ) __HYDPY_ROOTMODEL__ = False @@ -137,7 +136,19 @@ class Model(statcorr_model.Sub_OutputCorrModel, statcorrinterfaces.OutputCorrMod statcorr_model.Is_Active_V1, statcorr_model.Get_CorrectedOutput_V1, ) - ADD_METHODS = (statcorr_model.Calc_AveragedResidual_V1,) + ADD_METHODS = ( + statcorr_model.Set_ForecastMode_V1, + statcorr_model.Calc_EvaluatedValue_V1, + statcorr_model.Calc_IsActive_V1, + statcorr_model.Calc_Residual_ResidualAnchor_V1, + statcorr_model.Calc_Stationary_V1, + statcorr_model.Calc_ReductionFactor_V1, + statcorr_model.Calc_RelSumDelta_V1, + statcorr_model.Calc_LowVariability_V1, + statcorr_model.Calc_AveragedResidual_V1, + statcorr_model.Calc_CorrectedQ_V1, + statcorr_model.Update_ForecastStep_V1, + ) OUTLET_METHODS = () SENDER_METHODS = () SUBMODELINTERFACES = () diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py index 89e01d8bde..04c576089e 100644 --- a/hydpy/models/statcorr_main.py +++ b/hydpy/models/statcorr_main.py @@ -49,8 +49,8 @@ ... control.maxrelshift(10.0) ... control.averagingwindow(0) ... control.transitionsteps(0) - ... control.stationaritycheck(False) - ... control.variabilitycheck(False) + ... control.stationaritycheck(active=False) + ... control.variabilitycheck(active=False) ... control.reductionsteps(1) The inlet provides the simulated discharge; |Discharge| carries the @@ -195,7 +195,7 @@ >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0) as sub: ... configure(sub) - ... stationaritycheck(window=3, ratiominmax=0.5) + ... stationaritycheck(active=True, window=3, ratiominmax=0.5) ... reductionsteps(4) >>> element.inlets.inlet.sequences.sim.series = 5.0 >>> with pub.options.checkseries(False): @@ -234,7 +234,7 @@ ... configure(sub) ... evaluationwindow(3) ... averagingwindow(1) - ... variabilitycheck(maxrelsumdelta=0.1, averagingwindow=4) + ... variabilitycheck(active=True, maxrelsumdelta=0.1, averagingwindow=4) >>> with pub.options.checkseries(False): ... inputs.discharge.series = 6.0, 6.0, 6.0, 7.0, 6.0, nan, nan, nan, nan, nan @@ -278,9 +278,10 @@ ... inputs.discharge.series = 1.5, 2.5, 8.0, 9.0, 3.5, nan, nan, nan, nan, nan During the `historical` run, the second submodel takes over on days three and - four, where its restricted relative shift prevents reproducing the - observations. During the `forecast` run, the responsible submodel does not - change (see |EvaluatedValue|). Hence, the first submodel, which was + four, where its restricted absolute shift prevents reproducing the observations + (the relative shift does not apply, as the current observation is available, + see |Calc_CorrectedQ_V1|). During the `forecast` run, the responsible submodel + does not change (see |EvaluatedValue|). Hence, the first submodel, which was responsible at the end of the `historical` run, keeps applying the residual of ``0.5`` unrestricted, even when the forecasted discharge exceeds ``5.0``: @@ -291,8 +292,8 @@ ------------------------------------------------------------ | 01/01 | 1.5 | 1.0 | 1.5 | 1.0 | 1.5 | | 02/01 | 2.5 | 2.0 | 2.5 | 2.0 | 2.5 | - | 03/01 | 8.0 | 6.0 | 6.3 | 6.0 | 6.3 | - | 04/01 | 9.0 | 7.0 | 7.35 | 7.0 | 7.35 | + | 03/01 | 8.0 | 6.0 | 6.25 | 6.0 | 6.25 | + | 04/01 | 9.0 | 7.0 | 7.25 | 7.0 | 7.25 | | 05/01 | 3.5 | 3.0 | 3.5 | 3.0 | 3.5 | | 06/01 | nan | 4.0 | 4.5 | 4.0 | 4.5 | | 07/01 | nan | 6.0 | 6.5 | 6.0 | 6.5 | @@ -328,7 +329,7 @@ class Model(modeltools.AdHocModel): RECEIVER_METHODS = () RUN_METHODS = (statcorr_model.Calc_OutputCorr_V1,) INTERFACE_METHODS = () - ADD_METHODS = () + ADD_METHODS = (statcorr_model.Calc_OutputCorr_OutputCorrModel_V1,) OUTLET_METHODS = (statcorr_model.Pass_CorrectedQ_V1,) SENDER_METHODS = () SUBMODELINTERFACES = (statcorrinterfaces.OutputCorrModel_V1,) From 6f5582058172455ca7795e3927514824787b3f1a Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Thu, 5 Nov 2026 13:26:44 +0100 Subject: [PATCH 27/43] Fix typing problems after update of mypy plugin --- hydpy/interfaces/statcorrinterfaces.py | 11 +++----- hydpy/models/statcorr/statcorr_control.py | 2 +- hydpy/models/statcorr/statcorr_derived.py | 34 +++++++---------------- hydpy/models/statcorr/statcorr_model.py | 16 +++++------ hydpy/models/statcorr_main.py | 3 +- 5 files changed, 25 insertions(+), 41 deletions(-) diff --git a/hydpy/interfaces/statcorrinterfaces.py b/hydpy/interfaces/statcorrinterfaces.py index 48267066b5..ca629b80fa 100644 --- a/hydpy/interfaces/statcorrinterfaces.py +++ b/hydpy/interfaces/statcorrinterfaces.py @@ -48,13 +48,10 @@ def determine_outputcorrection(self, isforecastmode: bool) -> None: The main model passes its current |Options.simulationmode| via `isforecastmode` (|True| for `forecast`, |False| for `historical`) - instead of leaving the submodel to inspect the global option itself, - because a submodel cannot safely track *changes* of - |Options.simulationmode| between simulation steps on its own (there is - no per-step hook comparable to |OutputCorrModel_V1.set_simulatedvalue| - for it, and refreshing a submodel-owned derived parameter via - |Model.update_parameters| would also needlessly re-run its submodel - attachment/initialisation logic, wiping its logged history).""" + instead of leaving the submodel to inspect the global option itself. + Hence, the main model is the only place that evaluates + |Options.simulationmode|, and submodels do not need their own derived + parameter that must be kept in sync with it.""" @modeltools.abstractmodelmethod def is_active(self) -> bool: diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index 6638ae8fc5..607a3b800e 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -22,7 +22,7 @@ class NmbSubmodels(parametertools.NmbParameter): SPAN = (0, None) - def __call__(self, *args, **kwargs) -> None: + def __call__(self, *args: CallHook, **kwargs: Any) -> None: super().__call__(*args, **kwargs) self.subpars.pars.model.outputcorrmodels.number = self.value diff --git a/hydpy/models/statcorr/statcorr_derived.py b/hydpy/models/statcorr/statcorr_derived.py index 1507102225..95766bdab3 100644 --- a/hydpy/models/statcorr/statcorr_derived.py +++ b/hydpy/models/statcorr/statcorr_derived.py @@ -144,12 +144,8 @@ def update(self) -> None: residual(2.0) """ control = self.subpars.pars.control - stationaritycheck = cast( - statcorr_control.StationarityCheck, control.stationaritycheck - ) - variabilitycheck = cast( - statcorr_control.VariabilityCheck, control.variabilitycheck - ) + stationaritycheck = control.stationaritycheck + variabilitycheck = control.variabilitycheck if not ( stationaritycheck.configured and variabilitycheck.configured @@ -167,12 +163,14 @@ def update(self) -> None: ) self(nmb) - def __call__(self, *args, **kwargs) -> None: + def __call__(self, *args: CallHook, **kwargs: Any) -> None: old = exceptiontools.getattr_(self, "value", None) super().__call__(*args, **kwargs) if self.value != old: for state in self.subpars.pars.model.sequences.states: - state(state.INIT) + init = state.INIT + if init is not None: + state(init) class StationarityWindow(parametertools.Parameter): @@ -206,10 +204,7 @@ def update(self) -> None: >>> derived.stationaritywindow stationaritywindow(0) """ - stationaritycheck = cast( - statcorr_control.StationarityCheck, - self.subpars.pars.control.stationaritycheck, - ) + stationaritycheck = self.subpars.pars.control.stationaritycheck if stationaritycheck.configured: self(stationaritycheck.window) @@ -245,10 +240,7 @@ def update(self) -> None: >>> derived.ratiominmax ratiominmax(0.0) """ - stationaritycheck = cast( - statcorr_control.StationarityCheck, - self.subpars.pars.control.stationaritycheck, - ) + stationaritycheck = self.subpars.pars.control.stationaritycheck if stationaritycheck.configured: self(stationaritycheck.ratiominmax) @@ -285,10 +277,7 @@ def update(self) -> None: >>> derived.maxrelsumdelta maxrelsumdelta(0.0) """ - variabilitycheck = cast( - statcorr_control.VariabilityCheck, - self.subpars.pars.control.variabilitycheck, - ) + variabilitycheck = self.subpars.pars.control.variabilitycheck if variabilitycheck.configured: self(variabilitycheck.maxrelsumdelta) @@ -325,9 +314,6 @@ def update(self) -> None: >>> derived.stationaryaveragingwindow stationaryaveragingwindow(0) """ - variabilitycheck = cast( - statcorr_control.VariabilityCheck, - self.subpars.pars.control.variabilitycheck, - ) + variabilitycheck = self.subpars.pars.control.variabilitycheck if variabilitycheck.configured: self(variabilitycheck.averagingwindow) diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 4065f630ce..8110863310 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -202,13 +202,12 @@ class Calc_OutputCorr_V1(modeltools.Method): also forwards the current |Options.simulationmode| to each submodel's |OutputCorrModel_V1.determine_outputcorrection| call (see |Determine_OutputCorrection_V1|), so submodels never need to inspect the - global option themselves. |Parameters.update| (usually triggered via - |HydPy.update_parameters|) must be called after changing - |Options.simulationmode| for |IsForecastMode| (and hence - |Calc_OutputCorr_V1|) to take effect; deliberately, this does *not* - require (or recommend) calling |Model.update_parameters|, which would - also needlessly re-run the submodels' attachment/initialisation logic - and wipe their logged history: + global option themselves. After changing |Options.simulationmode|, one + must call |Parameters.update| (or |Model.update_parameters| or + |HydPy.update_parameters|) for |IsForecastMode| (and hence + |Calc_OutputCorr_V1|) to take effect. This leaves the submodels' logs and + states untouched as long as their number of log entries (see + |NmbLogEntries|) does not change: >>> nmbsubmodels(1) >>> with model.add_outputcorrmodel_v1( @@ -353,12 +352,13 @@ class Model(modeltools.AdHocModel): statcorrinterfaces.OutputCorrModel_V1 ) - @importtools.prepare_submodel( # type: ignore[call-overload] + @importtools.prepare_submodel( # type: ignore[call-overload, untyped-decorator] "outputcorrmodels", statcorrinterfaces.OutputCorrModel_V1, dimensionality=1 ) def add_outputcorrmodel_v1( self, outputcorrmodel: statcorrinterfaces.OutputCorrModel_V1, + /, *, position: int, refresh: bool, diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py index 04c576089e..ec54317f93 100644 --- a/hydpy/models/statcorr_main.py +++ b/hydpy/models/statcorr_main.py @@ -339,12 +339,13 @@ class Model(modeltools.AdHocModel): statcorrinterfaces.OutputCorrModel_V1 ) - @importtools.prepare_submodel( # type: ignore[call-overload] + @importtools.prepare_submodel( # type: ignore[call-overload, untyped-decorator] "outputcorrmodels", statcorrinterfaces.OutputCorrModel_V1, dimensionality=1 ) def add_outputcorrmodel_v1( self, outputcorrmodel: statcorrinterfaces.OutputCorrModel_V1, + /, *, position: int, refresh: bool, From 189d2860191fd2c3eee0fc427f028dec89573eb3 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Thu, 5 Nov 2026 19:42:14 +0100 Subject: [PATCH 28/43] Implement further requested changes from Review --- hydpy/docs/rst/HydPy-StatCorr.rst | 12 ++- hydpy/models/statcorr/statcorr_control.py | 4 +- hydpy/models/statcorr/statcorr_fluxes.py | 10 +- hydpy/models/statcorr/statcorr_model.py | 126 +++++++++++----------- hydpy/models/statcorr/statcorr_states.py | 2 +- hydpy/models/statcorr_arima010.py | 6 +- hydpy/models/statcorr_main.py | 2 +- 7 files changed, 85 insertions(+), 77 deletions(-) diff --git a/hydpy/docs/rst/HydPy-StatCorr.rst b/hydpy/docs/rst/HydPy-StatCorr.rst index fc0fbbeaca..a55650d7c8 100644 --- a/hydpy/docs/rst/HydPy-StatCorr.rst +++ b/hydpy/docs/rst/HydPy-StatCorr.rst @@ -1,13 +1,15 @@ - .. _HydPy-StatCorr: HydPy-StatCorr ============== -All HydPy-StatCorr models deal with the statistical correction of discharge -forecasts. The base model |statcorr| reads the simulated discharge from its inlet -node(s), passes it through one or more submodels complying with the -|OutputCorrModel_V1| interface, and delivers the corrected discharge to the outlet +All HydPy-StatCorr models deal with the statistical correction of simulated values +based on observed values, for example, to improve forecasts. The models are +designed for different kinds of variables, and the submodels complying with the +|OutputCorrModel_V1| interface are not restricted to a specific variable. However, +the currently available application model |statcorr_main| focuses on discharge: it +reads the simulated discharge from its inlet node(s), passes it through one or more +|OutputCorrModel_V1| submodels, and delivers the corrected discharge to its outlet node. |statcorr_arima010| is such a submodel; it estimates the correction from an ARIMA(0,1,0) error model, following the LARSIM approach. diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index 607a3b800e..74d6b27a26 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -573,7 +573,7 @@ class ReductionSteps(parametertools.Parameter): class MaxAbsShift(parametertools.Parameter): """The maximum absolute shift applied when the current simulated value is not positive or not below |ResidualAnchor| (the simulated value at the time the - residual was determined, see |Calc_CorrectedQ_V1|) [unit of the corrected + residual was determined, see |Calc_CorrectedValue_V1|) [unit of the corrected variable]. This includes the `historical` mode whenever the current observation is @@ -587,7 +587,7 @@ class MaxAbsShift(parametertools.Parameter): class MaxRelShift(parametertools.Parameter): """The maximum relative shift applied when the current simulated value is positive and below |ResidualAnchor| (the simulated value at the time the residual - was determined, see |Calc_CorrectedQ_V1|) [-]. + was determined, see |Calc_CorrectedValue_V1|) [-]. |MaxRelShift| is a fraction, not a percentage. For example, a value of ``0.1`` restricts the multiplicative correction to ±10 %.""" diff --git a/hydpy/models/statcorr/statcorr_fluxes.py b/hydpy/models/statcorr/statcorr_fluxes.py index a5cf96ebb3..896c9f0e5b 100644 --- a/hydpy/models/statcorr/statcorr_fluxes.py +++ b/hydpy/models/statcorr/statcorr_fluxes.py @@ -16,6 +16,12 @@ class CorrectedQ(sequencetools.FluxSequence): NDIM: Final[Literal[0]] = 0 +class CorrectedValue(sequencetools.FluxSequence): + """Corrected value [unit of the corrected variable].""" + + NDIM: Final[Literal[0]] = 0 + + class ForecastMode(sequencetools.FluxSequence): """Flag (1.0: `forecast`, 0.0: `historical`) telling the simulation mode the main model passed to |Determine_OutputCorrection_V1| in the current simulation step @@ -26,8 +32,8 @@ class ForecastMode(sequencetools.FluxSequence): class IsActive(sequencetools.FluxSequence): - """Flag (1.0: yes, 0.0: no) telling whether the submodel corrected the discharge - in the current simulation step (see |Calc_IsActive_V1|) [-].""" + """Flag (1.0: yes, 0.0: no) telling whether the submodel corrected the simulated + value in the current simulation step (see |Calc_IsActive_V1|) [-].""" NDIM: Final[Literal[0]] = 0 SPAN = (0.0, 1.0) diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 8110863310..1a9562991c 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -1226,7 +1226,7 @@ def __call__(model: modeltools.Model, /) -> None: sta.averagedresidual = (sum_obs - sum_sim) / nmb -class Calc_CorrectedQ_V1(modeltools.Method): +class Calc_CorrectedValue_V1(modeltools.Method): r"""Calculate the corrected value by shifting the current simulated value based on the (damped) residual. @@ -1236,11 +1236,11 @@ class Calc_CorrectedQ_V1(modeltools.Method): (:math:`sim_k`, the simulated value at the time the residual was determined), with :math:`f_{red}` denoting |ReductionFactor|: - * If :math:`0 < sim_0 < sim_k`, |Calc_CorrectedQ_V1| shifts :math:`sim_0` + * If :math:`0 < sim_0 < sim_k`, |Calc_CorrectedValue_V1| shifts :math:`sim_0` *multiplicatively*, expressing the damped residual as a fraction of :math:`sim_k` and capping that fraction at |MaxRelShift|: - :math:`CorrectedQ = sim_0 \cdot \left(1 + \mathrm{clip}\left(r \cdot f_{red} + :math:`CorrectedValue = sim_0 \cdot \left(1 + \mathrm{clip}\left(r \cdot f_{red} / sim_k,\ \pm MaxRelShift\right) \right)` Applying the residual as a fraction rather than a constant offset keeps the @@ -1250,7 +1250,7 @@ class Calc_CorrectedQ_V1(modeltools.Method): * Otherwise (:math:`sim_0 \geq sim_k` or :math:`sim_0 \leq 0`), it shifts :math:`sim_0` *additively*, capping the damped residual at |MaxAbsShift|: - :math:`CorrectedQ = sim_0 + \mathrm{clip}\left(r \cdot f_{red},\ + :math:`CorrectedValue = sim_0 + \mathrm{clip}\left(r \cdot f_{red},\ \pm MaxAbsShift\right)` This includes the `historical` mode whenever the current observation is @@ -1262,7 +1262,7 @@ class Calc_CorrectedQ_V1(modeltools.Method): |AveragedResidual| (see |Calc_AveragedResidual_V1|). Since it generally does not equal the pointwise residual at the forecast's start, switching to it abruptly would cause a jump in the corrected value right where the forecast - begins. To avoid this, |Calc_CorrectedQ_V1| starts every forecast run with the + begins. To avoid this, |Calc_CorrectedValue_V1| starts every forecast run with the pointwise residual (so the corrected value picks up smoothly where the last measurement left off) and then linearly blends it towards the mean-value-based residual over |TransitionSteps| forecast steps (counted by |ForecastStep|), @@ -1291,32 +1291,32 @@ class Calc_CorrectedQ_V1(modeltools.Method): >>> states.residual(1.0) >>> states.residualanchor(5.0) >>> logs.loggedsimulatedvalue = 6.0 - >>> model.calc_correctedq_v1() - >>> fluxes.correctedq - correctedq(6.0) + >>> model.calc_correctedvalue_v1() + >>> fluxes.correctedvalue + correctedvalue(6.0) The current simulated value exceeds |ResidualAnchor|, so the residual applies additively: >>> fluxes.isactive = 1.0 - >>> model.calc_correctedq_v1() - >>> fluxes.correctedq - correctedq(7.0) + >>> model.calc_correctedvalue_v1() + >>> fluxes.correctedvalue + correctedvalue(7.0) |ReductionFactor| dampens the residual: >>> states.reductionfactor(0.5) - >>> model.calc_correctedq_v1() - >>> fluxes.correctedq - correctedq(6.5) + >>> model.calc_correctedvalue_v1() + >>> fluxes.correctedvalue + correctedvalue(6.5) |MaxAbsShift| caps the additive shift: >>> states.reductionfactor(1.0) >>> control.maxabsshift(0.2) - >>> model.calc_correctedq_v1() - >>> fluxes.correctedq - correctedq(6.2) + >>> model.calc_correctedvalue_v1() + >>> fluxes.correctedvalue + correctedvalue(6.2) For a *receding* simulation (the current simulated value is below |ResidualAnchor|), the residual applies multiplicatively: @@ -1325,17 +1325,17 @@ class Calc_CorrectedQ_V1(modeltools.Method): >>> states.residual(2.0) >>> states.residualanchor(10.0) >>> logs.loggedsimulatedvalue = 2.0 - >>> model.calc_correctedq_v1() - >>> fluxes.correctedq - correctedq(2.4) + >>> model.calc_correctedvalue_v1() + >>> fluxes.correctedvalue + correctedvalue(2.4) Limiting |MaxRelShift| to ``0.1`` caps that fraction at 10 % before it is converted back into an absolute shift: >>> control.maxrelshift(0.1) - >>> model.calc_correctedq_v1() - >>> fluxes.correctedq - correctedq(2.2) + >>> model.calc_correctedvalue_v1() + >>> fluxes.correctedvalue + correctedvalue(2.2) If the current simulated value equals |ResidualAnchor| (as in `historical` mode whenever the current observation is available), the residual applies @@ -1343,21 +1343,21 @@ class Calc_CorrectedQ_V1(modeltools.Method): >>> control.maxrelshift(0.0) >>> logs.loggedsimulatedvalue = 10.0 - >>> model.calc_correctedq_v1() - >>> fluxes.correctedq - correctedq(12.0) + >>> model.calc_correctedvalue_v1() + >>> fluxes.correctedvalue + correctedvalue(12.0) The same holds for a non-positive current simulated value: >>> logs.loggedsimulatedvalue = 0.0 - >>> model.calc_correctedq_v1() - >>> fluxes.correctedq - correctedq(2.0) + >>> model.calc_correctedvalue_v1() + >>> fluxes.correctedvalue + correctedvalue(2.0) >>> control.maxrelshift(10.0) Now, we demonstrate the transition from the pointwise residual (``1.0``) to the mean-value-based residual (``2.5``) over two forecast steps. On the - first forecast step, |Calc_CorrectedQ_V1| applies the pointwise residual + first forecast step, |Calc_CorrectedValue_V1| applies the pointwise residual unabated: >>> control.averagingwindow(2) @@ -1367,36 +1367,36 @@ class Calc_CorrectedQ_V1(modeltools.Method): >>> states.residualanchor(8.0) >>> states.averagedresidual(2.5) >>> logs.loggedsimulatedvalue = 10.0 - >>> model.calc_correctedq_v1() - >>> fluxes.correctedq - correctedq(11.0) + >>> model.calc_correctedvalue_v1() + >>> fluxes.correctedvalue + correctedvalue(11.0) Halfway through the transition, the applied residual is the average of both (``1.75``): >>> states.forecaststep(1.0) >>> logs.loggedsimulatedvalue = 11.0 - >>> model.calc_correctedq_v1() - >>> fluxes.correctedq - correctedq(12.75) + >>> model.calc_correctedvalue_v1() + >>> fluxes.correctedvalue + correctedvalue(12.75) Once the transition period has elapsed, the full mean-value-based residual applies: >>> states.forecaststep(2.0) >>> logs.loggedsimulatedvalue = 12.0 - >>> model.calc_correctedq_v1() - >>> fluxes.correctedq - correctedq(14.5) + >>> model.calc_correctedvalue_v1() + >>> fluxes.correctedvalue + correctedvalue(14.5) Setting |TransitionSteps| to zero applies the mean-value-based residual immediately: >>> control.transitionsteps(0) >>> states.forecaststep(0.0) - >>> model.calc_correctedq_v1() - >>> fluxes.correctedq - correctedq(14.5) + >>> model.calc_correctedvalue_v1() + >>> fluxes.correctedvalue + correctedvalue(14.5) Under stationary conditions according to |VariabilityCheck| (see |Calc_LowVariability_V1|), the mean-value-based residual applies even if @@ -1404,17 +1404,17 @@ class Calc_CorrectedQ_V1(modeltools.Method): >>> control.averagingwindow(0) >>> states.lowvariability(1.0) - >>> model.calc_correctedq_v1() - >>> fluxes.correctedq - correctedq(14.5) + >>> model.calc_correctedvalue_v1() + >>> fluxes.correctedvalue + correctedvalue(14.5) - In `historical` mode, |Calc_CorrectedQ_V1| always relies on the pointwise + In `historical` mode, |Calc_CorrectedValue_V1| always relies on the pointwise residual, so that the corrected value reproduces the current observation: >>> fluxes.forecastmode = 0.0 - >>> model.calc_correctedq_v1() - >>> fluxes.correctedq - correctedq(13.0) + >>> model.calc_correctedvalue_v1() + >>> fluxes.correctedvalue + correctedvalue(13.0) """ CONTROLPARAMETERS = ( @@ -1434,7 +1434,7 @@ class Calc_CorrectedQ_V1(modeltools.Method): statcorr_states.Residual, statcorr_states.ResidualAnchor, ) - RESULTSEQUENCES = (statcorr_fluxes.CorrectedQ,) + RESULTSEQUENCES = (statcorr_fluxes.CorrectedValue,) @staticmethod def __call__(model: modeltools.Model, /) -> None: @@ -1444,7 +1444,7 @@ def __call__(model: modeltools.Model, /) -> None: sta = model.sequences.states.fastaccess sim: float = log.loggedsimulatedvalue[0] if flu.isactive == 0.0: - flu.correctedq = sim + flu.correctedvalue = sim else: residual: float = sta.residual if (flu.forecastmode == 1.0) and ( @@ -1456,12 +1456,12 @@ def __call__(model: modeltools.Model, /) -> None: residual = residual + weight * (sta.averagedresidual - residual) residual = residual * sta.reductionfactor if 0.0 < sim < sta.residualanchor: - flu.correctedq = sim + sim * min( + flu.correctedvalue = sim + sim * min( con.maxrelshift, max(-con.maxrelshift, residual / sta.residualanchor), ) else: - flu.correctedq = sim + min( + flu.correctedvalue = sim + min( con.maxabsshift, max(-con.maxabsshift, residual) ) @@ -1521,7 +1521,7 @@ class Determine_OutputCorrection_V1(modeltools.SetAutoMethod): * |Calc_RelSumDelta_V1|, |Calc_LowVariability_V1|, and |Calc_AveragedResidual_V1| determine the mean-value-based residual for forecast runs. - * |Calc_CorrectedQ_V1| applies the resulting residual to the current simulated + * |Calc_CorrectedValue_V1| applies the resulting residual to the current simulated value. * |Update_ForecastStep_V1| counts the forecast steps. @@ -1566,8 +1566,8 @@ class Determine_OutputCorrection_V1(modeltools.SetAutoMethod): forecastmode(0.0) >>> fluxes.isactive isactive(1.0) - >>> fluxes.correctedq - correctedq(6.0) + >>> fluxes.correctedvalue + correctedvalue(6.0) In `forecast` mode, the residual of the last `historical` step persists: @@ -1576,8 +1576,8 @@ class Determine_OutputCorrection_V1(modeltools.SetAutoMethod): >>> model.determine_outputcorrection_v1(True) >>> fluxes.forecastmode forecastmode(1.0) - >>> fluxes.correctedq - correctedq(8.0) + >>> fluxes.correctedvalue + correctedvalue(8.0) >>> states.forecaststep forecaststep(1.0) """ @@ -1592,7 +1592,7 @@ class Determine_OutputCorrection_V1(modeltools.SetAutoMethod): Calc_RelSumDelta_V1, Calc_LowVariability_V1, Calc_AveragedResidual_V1, - Calc_CorrectedQ_V1, + Calc_CorrectedValue_V1, Update_ForecastStep_V1, ) CONTROLPARAMETERS = ( @@ -1633,7 +1633,7 @@ class Determine_OutputCorrection_V1(modeltools.SetAutoMethod): RESULTSEQUENCES = ( statcorr_fluxes.ForecastMode, statcorr_fluxes.IsActive, - statcorr_fluxes.CorrectedQ, + statcorr_fluxes.CorrectedValue, ) @@ -1666,18 +1666,18 @@ class Get_CorrectedOutput_V1(modeltools.Method): >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() - >>> fluxes.correctedq = 2.5 + >>> fluxes.correctedvalue = 2.5 >>> from hydpy import round_ >>> round_(model.get_correctedoutput_v1()) 2.5 """ - REQUIREDSEQUENCES = (statcorr_fluxes.CorrectedQ,) + REQUIREDSEQUENCES = (statcorr_fluxes.CorrectedValue,) @staticmethod def __call__(model: modeltools.Model, /) -> float: flu = model.sequences.fluxes.fastaccess - return flu.correctedq + return flu.correctedvalue class Sub_OutputCorrModel(modeltools.AdHocModel): diff --git a/hydpy/models/statcorr/statcorr_states.py b/hydpy/models/statcorr/statcorr_states.py index 4340b69ecc..226640e186 100644 --- a/hydpy/models/statcorr/statcorr_states.py +++ b/hydpy/models/statcorr/statcorr_states.py @@ -84,7 +84,7 @@ class ForecastStep(sequencetools.StateSequence): forecast run (``0.0`` on the first forecast step), reset to ``0.0`` whenever |Options.simulationmode| equals `historical` [-]. - |Calc_CorrectedQ_V1| uses |ForecastStep| to linearly blend the + |Calc_CorrectedValue_V1| uses |ForecastStep| to linearly blend the applied residual from the single most recent (pointwise) value towards the mean-value-based residual determined via |AveragingWindow| over |TransitionSteps| forecast steps.""" diff --git a/hydpy/models/statcorr_arima010.py b/hydpy/models/statcorr_arima010.py index 4fa1060fa2..db8cc7484c 100644 --- a/hydpy/models/statcorr_arima010.py +++ b/hydpy/models/statcorr_arima010.py @@ -23,14 +23,14 @@ relative to the anchor value (capped at |MaxRelShift|), which keeps the correction from overshooting or turning negative while the simulated values recede; otherwise, the residual is added unchanged (capped at |MaxAbsShift|). See -|Calc_CorrectedQ_V1| for the exact formulas. +|Calc_CorrectedValue_V1| for the exact formulas. Setting |AveragingWindow| to a value greater than zero switches from that pointwise residual to a mean-value-based one (mean observed minus mean simulated values over the given number of log entries immediately preceding the current forecast run), blended in linearly over |TransitionSteps| forecast steps to avoid a jump right where the -forecast begins. See |Calc_AveragedResidual_V1| and |Calc_CorrectedQ_V1| for +forecast begins. See |Calc_AveragedResidual_V1| and |Calc_CorrectedValue_V1| for details. Each |statcorr_arima010| instance is responsible for a specific value range @@ -146,7 +146,7 @@ class Model(statcorr_model.Sub_OutputCorrModel, statcorrinterfaces.OutputCorrMod statcorr_model.Calc_RelSumDelta_V1, statcorr_model.Calc_LowVariability_V1, statcorr_model.Calc_AveragedResidual_V1, - statcorr_model.Calc_CorrectedQ_V1, + statcorr_model.Calc_CorrectedValue_V1, statcorr_model.Update_ForecastStep_V1, ) OUTLET_METHODS = () diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py index ec54317f93..6ea8d0ed59 100644 --- a/hydpy/models/statcorr_main.py +++ b/hydpy/models/statcorr_main.py @@ -280,7 +280,7 @@ During the `historical` run, the second submodel takes over on days three and four, where its restricted absolute shift prevents reproducing the observations (the relative shift does not apply, as the current observation is available, - see |Calc_CorrectedQ_V1|). During the `forecast` run, the responsible submodel + see |Calc_CorrectedValue_V1|). During the `forecast` run, the responsible submodel does not change (see |EvaluatedValue|). Hence, the first submodel, which was responsible at the end of the `historical` run, keeps applying the residual of ``0.5`` unrestricted, even when the forecasted discharge exceeds ``5.0``: From 1d14730ddf8aef56cc932b0de6ac7ae1f7ddd4ad Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Mon, 9 Nov 2026 10:11:59 +0100 Subject: [PATCH 29/43] Implement further requested changes from Review --- hydpy/interfaces/statcorrinterfaces.py | 11 +- hydpy/models/statcorr/statcorr_derived.py | 28 --- hydpy/models/statcorr/statcorr_fluxes.py | 9 - hydpy/models/statcorr/statcorr_model.py | 228 +++++++++------------- hydpy/models/statcorr_arima010.py | 3 +- hydpy/models/statcorr_main.py | 2 - 6 files changed, 99 insertions(+), 182 deletions(-) diff --git a/hydpy/interfaces/statcorrinterfaces.py b/hydpy/interfaces/statcorrinterfaces.py index ca629b80fa..08110d3a72 100644 --- a/hydpy/interfaces/statcorrinterfaces.py +++ b/hydpy/interfaces/statcorrinterfaces.py @@ -42,16 +42,13 @@ def set_observedvalue(self, observedvalue: float) -> None: submodel, which appends it to its internal log of observed values.""" @modeltools.abstractmodelmethod - def determine_outputcorrection(self, isforecastmode: bool) -> None: + def determine_outputcorrection(self) -> None: """Calculate the corrected output value from the internal logs of simulated and observed values. - The main model passes its current |Options.simulationmode| via - `isforecastmode` (|True| for `forecast`, |False| for `historical`) - instead of leaving the submodel to inspect the global option itself. - Hence, the main model is the only place that evaluates - |Options.simulationmode|, and submodels do not need their own derived - parameter that must be kept in sync with it.""" + Submodels that behave differently in `historical` and `forecast` mode + read the current |Options.simulationmode| at runtime via + |Model.runsettings|.""" @modeltools.abstractmodelmethod def is_active(self) -> bool: diff --git a/hydpy/models/statcorr/statcorr_derived.py b/hydpy/models/statcorr/statcorr_derived.py index 95766bdab3..16034f9682 100644 --- a/hydpy/models/statcorr/statcorr_derived.py +++ b/hydpy/models/statcorr/statcorr_derived.py @@ -1,39 +1,11 @@ # pylint: disable=missing-module-docstring -import hydpy from hydpy.core import exceptiontools from hydpy.core import parametertools from hydpy.core.typingtools import * from hydpy.models.statcorr import statcorr_control -class IsForecastMode(parametertools.Parameter): - """Flag telling whether |Options.simulationmode| currently is `forecast` [-].""" - - NDIM: Final[Literal[0]] = 0 - TYPE: Final = bool - - def update(self) -> None: - """Take the current value of |Options.simulationmode| from module |pub|. - - >>> from hydpy.models.statcorr import * - >>> parameterstep() - >>> from hydpy import pub - >>> pub.options.simulationmode = "historical" - >>> derived.isforecastmode.update() - >>> derived.isforecastmode - isforecastmode(False) - - >>> pub.options.simulationmode = "forecast" - >>> derived.isforecastmode.update() - >>> derived.isforecastmode - isforecastmode(True) - - >>> del pub.options.simulationmode - """ - self(hydpy.pub.options.simulationmode == "forecast") - - class NmbLogEntries(parametertools.NmbParameter): """The number of log entries required for memorising the simulated and observed values [-]. diff --git a/hydpy/models/statcorr/statcorr_fluxes.py b/hydpy/models/statcorr/statcorr_fluxes.py index 896c9f0e5b..6d1b19024e 100644 --- a/hydpy/models/statcorr/statcorr_fluxes.py +++ b/hydpy/models/statcorr/statcorr_fluxes.py @@ -22,15 +22,6 @@ class CorrectedValue(sequencetools.FluxSequence): NDIM: Final[Literal[0]] = 0 -class ForecastMode(sequencetools.FluxSequence): - """Flag (1.0: `forecast`, 0.0: `historical`) telling the simulation mode the main - model passed to |Determine_OutputCorrection_V1| in the current simulation step - [-].""" - - NDIM: Final[Literal[0]] = 0 - SPAN = (0.0, 1.0) - - class IsActive(sequencetools.FluxSequence): """Flag (1.0: yes, 0.0: no) telling whether the submodel corrected the simulated value in the current simulation step (see |Calc_IsActive_V1|) [-].""" diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 1a9562991c..b4a2c42912 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -52,7 +52,6 @@ class Calc_OutputCorr_OutputCorrModel_V1(modeltools.Method): """ SUBMODELINTERFACES = (statcorrinterfaces.OutputCorrModel_V1,) - DERIVEDPARAMETERS = (statcorr_derived.IsForecastMode,) REQUIREDSEQUENCES = (statcorr_fluxes.Inflow, statcorr_inputs.Discharge) RESULTSEQUENCES = (statcorr_fluxes.CorrectedQ,) @@ -60,13 +59,14 @@ class Calc_OutputCorr_OutputCorrModel_V1(modeltools.Method): def __call__( model: modeltools.Model, submodel: statcorrinterfaces.OutputCorrModel_V1, / ) -> None: - der = model.parameters.derived.fastaccess flu = model.sequences.fluxes.fastaccess inp = model.sequences.inputs.fastaccess - observedvalue: float = modelutils.nan if der.isforecastmode else inp.discharge submodel.set_simulatedvalue(flu.inflow) - submodel.set_observedvalue(observedvalue) - submodel.determine_outputcorrection(bool(der.isforecastmode)) + if model.runsettings.simulationmode == modelutils.FORECAST: + submodel.set_observedvalue(modelutils.nan) + else: + submodel.set_observedvalue(inp.discharge) + submodel.determine_outputcorrection() if submodel.is_active(): flu.correctedq = submodel.get_correctedoutput() @@ -198,16 +198,10 @@ class Calc_OutputCorr_V1(modeltools.Method): submodels instead, relying on their logic to keep applying the most recently logged residual (see |statcorr_arima010| for the mechanism and the module docstring of |statcorr_main| for the - assumed workflow of a preceding `historical` run). |Calc_OutputCorr_V1| - also forwards the current |Options.simulationmode| to each submodel's - |OutputCorrModel_V1.determine_outputcorrection| call (see - |Determine_OutputCorrection_V1|), so submodels never need to inspect the - global option themselves. After changing |Options.simulationmode|, one - must call |Parameters.update| (or |Model.update_parameters| or - |HydPy.update_parameters|) for |IsForecastMode| (and hence - |Calc_OutputCorr_V1|) to take effect. This leaves the submodels' logs and - states untouched as long as their number of log entries (see - |NmbLogEntries|) does not change: + assumed workflow of a preceding `historical` run). The main model and + its submodels read the current simulation mode at runtime via + |Model.runsettings|, so changing |Options.simulationmode| takes effect + immediately without updating any parameters: >>> nmbsubmodels(1) >>> with model.add_outputcorrmodel_v1( @@ -235,14 +229,12 @@ class Calc_OutputCorr_V1(modeltools.Method): >>> from hydpy import pub >>> with pub.options.simulationmode("forecast"): - ... model.parameters.update() ... fluxes.inflow = 3.0 ... inputs.discharge = 999.0 ... model.calc_outputcorr_v1() >>> fluxes.correctedq correctedq(3.5) >>> with pub.options.simulationmode("forecast"): - ... model.parameters.update() ... fluxes.inflow = 4.0 ... inputs.discharge = 999.0 ... model.calc_outputcorr_v1() @@ -256,14 +248,12 @@ class Calc_OutputCorr_V1(modeltools.Method): fade it out: >>> with pub.options.simulationmode("forecast"): - ... model.parameters.update() ... fluxes.inflow = 5.0 ... inputs.discharge = 999.0 ... model.calc_outputcorr_v1() >>> fluxes.correctedq correctedq(5.5) >>> with pub.options.simulationmode("forecast"): - ... model.parameters.update() ... fluxes.inflow = 6.0 ... inputs.discharge = 999.0 ... model.calc_outputcorr_v1() @@ -273,7 +263,6 @@ class Calc_OutputCorr_V1(modeltools.Method): SUBMODELINTERFACES = (statcorrinterfaces.OutputCorrModel_V1,) SUBMETHODS = (Calc_OutputCorr_OutputCorrModel_V1,) - DERIVEDPARAMETERS = (statcorr_derived.IsForecastMode,) REQUIREDSEQUENCES = (statcorr_fluxes.Inflow, statcorr_inputs.Discharge) RESULTSEQUENCES = (statcorr_fluxes.CorrectedQ,) @@ -445,39 +434,15 @@ def __call__(model: modeltools.Model, observedvalue: float, /) -> None: log.loggedobservedvalue[0] = observedvalue -class Set_ForecastMode_V1(modeltools.Method): - """Remember whether the main model currently runs in `forecast` or `historical` - mode. - - Examples: - - >>> from hydpy.models.statcorr_arima010 import * - >>> parameterstep() - >>> model.set_forecastmode_v1(True) - >>> fluxes.forecastmode - forecastmode(1.0) - >>> model.set_forecastmode_v1(False) - >>> fluxes.forecastmode - forecastmode(0.0) - """ - - RESULTSEQUENCES = (statcorr_fluxes.ForecastMode,) - - @staticmethod - def __call__(model: modeltools.Model, isforecastmode: bool, /) -> None: - flu = model.sequences.fluxes.fastaccess - flu.forecastmode = 1.0 if isforecastmode else 0.0 - - class Calc_EvaluatedValue_V1(modeltools.Method): r"""Calculate the mean of the |EvaluationWindow| most recent - |LoggedSimulatedValue| values while |ForecastMode| is ``0.0`` (`historical`). + |LoggedSimulatedValue| values while |Options.simulationmode| is `historical`. Basic equation: :math:`EvaluatedValue = \frac{1}{EvaluationWindow} \sum_{i=0}^{EvaluationWindow-1} LoggedSimulatedValue_i` - While |ForecastMode| is ``1.0`` (`forecast`), |Calc_EvaluatedValue_V1| keeps the + While |Options.simulationmode| is `forecast`, |Calc_EvaluatedValue_V1| keeps the value of the most recent `historical` assessment, so the responsible submodel (see |Calc_IsActive_V1|) does not change throughout the forecast horizon. @@ -493,34 +458,32 @@ class Calc_EvaluatedValue_V1(modeltools.Method): >>> control.evaluationwindow(3) >>> derived.nmblogentries(5) >>> logs.loggedsimulatedvalue = 1.0, 2.0, 6.0, nan, nan - >>> fluxes.forecastmode = 0.0 + >>> from hydpy import pub + >>> pub.options.simulationmode = "historical" >>> model.calc_evaluatedvalue_v1() >>> states.evaluatedvalue evaluatedvalue(3.0) In `forecast` mode, |EvaluatedValue| stays frozen: - >>> fluxes.forecastmode = 1.0 + >>> pub.options.simulationmode = "forecast" >>> logs.loggedsimulatedvalue = 10.0, 10.0, 10.0, nan, nan >>> model.calc_evaluatedvalue_v1() >>> states.evaluatedvalue evaluatedvalue(3.0) + >>> del pub.options.simulationmode """ CONTROLPARAMETERS = (statcorr_control.EvaluationWindow,) - REQUIREDSEQUENCES = ( - statcorr_fluxes.ForecastMode, - statcorr_logs.LoggedSimulatedValue, - ) + REQUIREDSEQUENCES = (statcorr_logs.LoggedSimulatedValue,) UPDATEDSEQUENCES = (statcorr_states.EvaluatedValue,) @staticmethod def __call__(model: modeltools.Model, /) -> None: con = model.parameters.control.fastaccess - flu = model.sequences.fluxes.fastaccess log = model.sequences.logs.fastaccess sta = model.sequences.states.fastaccess - if flu.forecastmode == 0.0: + if model.runsettings.simulationmode == modelutils.HISTORICAL: sum_simulated: float = 0.0 for idx in range(con.evaluationwindow): sum_simulated = sum_simulated + log.loggedsimulatedvalue[idx] @@ -533,7 +496,7 @@ class Calc_IsActive_V1(modeltools.Method): Each submodel is responsible for a specific value range only. It corrects the simulated values only while |Active| is |True|, |CorrectionMode| allows a - correction in the current simulation mode (see |ForecastMode|), and + correction in the current simulation mode (see |Options.simulationmode|), and |EvaluatedValue| (:math:`\overline{sim}`) lies within the range defined by |LowerLimit| and |UpperLimit|: @@ -553,7 +516,8 @@ class Calc_IsActive_V1(modeltools.Method): >>> control.lowerlimit(0.0) >>> control.upperlimit(inf) >>> states.evaluatedvalue(3.0) - >>> fluxes.forecastmode = 0.0 + >>> from hydpy import pub + >>> pub.options.simulationmode = "historical" >>> model.calc_isactive_v1() >>> fluxes.isactive isactive(1.0) @@ -588,7 +552,7 @@ class Calc_IsActive_V1(modeltools.Method): >>> fluxes.isactive isactive(0.0) - >>> fluxes.forecastmode = 1.0 + >>> pub.options.simulationmode = "forecast" >>> model.calc_isactive_v1() >>> fluxes.isactive isactive(1.0) @@ -600,7 +564,7 @@ class Calc_IsActive_V1(modeltools.Method): >>> fluxes.isactive isactive(0.0) - >>> fluxes.forecastmode = 0.0 + >>> pub.options.simulationmode = "historical" >>> model.calc_isactive_v1() >>> fluxes.isactive isactive(1.0) @@ -612,7 +576,7 @@ class Calc_IsActive_V1(modeltools.Method): statcorr_control.LowerLimit, statcorr_control.UpperLimit, ) - REQUIREDSEQUENCES = (statcorr_fluxes.ForecastMode, statcorr_states.EvaluatedValue) + REQUIREDSEQUENCES = (statcorr_states.EvaluatedValue,) RESULTSEQUENCES = (statcorr_fluxes.IsActive,) @staticmethod @@ -622,7 +586,7 @@ def __call__(model: modeltools.Model, /) -> None: sta = model.sequences.states.fastaccess if con.correctionmode == 3: modeallowed = True - elif flu.forecastmode == 1.0: + elif model.runsettings.simulationmode == modelutils.FORECAST: modeallowed = con.correctionmode == 2 else: modeallowed = con.correctionmode == 1 @@ -638,8 +602,8 @@ def __call__(model: modeltools.Model, /) -> None: class Calc_Residual_ResidualAnchor_V1(modeltools.Method): r"""Determine the most recent pointwise residual (observed minus simulated - value) and the corresponding simulated value while |ForecastMode| is ``0.0`` - (`historical`). + value) and the corresponding simulated value while |Options.simulationmode| is + `historical`. Basic equations: :math:`Residual = LoggedObservedValue_k - LoggedSimulatedValue_k` @@ -652,7 +616,7 @@ class Calc_Residual_ResidualAnchor_V1(modeltools.Method): no observation is available within that range, |Residual| and |ResidualAnchor| are set to zero, so no correction applies. - While |ForecastMode| is ``1.0`` (`forecast`), |Calc_Residual_ResidualAnchor_V1| + While |Options.simulationmode| is `forecast`, |Calc_Residual_ResidualAnchor_V1| does not repeat the search and keeps both values of the most recent `historical` assessment. Hence, the correction persists for the entire forecast horizon instead of vanishing as soon as the underlying log entry drops out of the @@ -667,7 +631,8 @@ class Calc_Residual_ResidualAnchor_V1(modeltools.Method): >>> from numpy import nan >>> control.maxnanskip(2) >>> derived.nmblogentries(3) - >>> fluxes.forecastmode = 0.0 + >>> from hydpy import pub + >>> pub.options.simulationmode = "historical" >>> logs.loggedsimulatedvalue = 5.0, 3.0, 2.0 >>> logs.loggedobservedvalue = 6.0, 4.0, 3.0 >>> model.calc_residual_residualanchor_v1() @@ -699,17 +664,17 @@ class Calc_Residual_ResidualAnchor_V1(modeltools.Method): In `forecast` mode, both values stay frozen: - >>> fluxes.forecastmode = 1.0 + >>> pub.options.simulationmode = "forecast" >>> logs.loggedobservedvalue = nan, nan, nan >>> model.calc_residual_residualanchor_v1() >>> states.residual, states.residualanchor (residual(1.0), residualanchor(2.0)) + >>> del pub.options.simulationmode """ CONTROLPARAMETERS = (statcorr_control.MaxNaNSkip,) DERIVEDPARAMETERS = (statcorr_derived.NmbLogEntries,) REQUIREDSEQUENCES = ( - statcorr_fluxes.ForecastMode, statcorr_logs.LoggedSimulatedValue, statcorr_logs.LoggedObservedValue, ) @@ -719,10 +684,9 @@ class Calc_Residual_ResidualAnchor_V1(modeltools.Method): def __call__(model: modeltools.Model, /) -> None: con = model.parameters.control.fastaccess der = model.parameters.derived.fastaccess - flu = model.sequences.fluxes.fastaccess log = model.sequences.logs.fastaccess sta = model.sequences.states.fastaccess - if flu.forecastmode == 0.0: + if model.runsettings.simulationmode == modelutils.HISTORICAL: sta.residual = 0.0 sta.residualanchor = 0.0 for idx in range(min(der.nmblogentries, con.maxnanskip + 1)): @@ -734,8 +698,8 @@ def __call__(model: modeltools.Model, /) -> None: class Calc_Stationary_V1(modeltools.Method): r"""Assess whether the observed values behave in a stationary way while the - stationarity check is enabled (see |StationarityCheck|) and |ForecastMode| is - ``0.0`` (`historical`). + stationarity check is enabled (see |StationarityCheck|) and + |Options.simulationmode| is `historical`. |Calc_Stationary_V1| takes the ratio of the minimum and the maximum |LoggedObservedValue| value within the most recent |StationarityWindow| log @@ -747,7 +711,7 @@ class Calc_Stationary_V1(modeltools.Method): interrupts an ongoing reduction of |ReductionFactor| (see |Calc_ReductionFactor_V1|) nor triggers a new one. - While |ForecastMode| is ``1.0`` (`forecast`), |Calc_Stationary_V1| keeps the + While |Options.simulationmode| is `forecast`, |Calc_Stationary_V1| keeps the outcome of the most recent `historical` assessment. Recomputing it would be unreliable, as |LoggedObservedValue| keeps receiving |numpy.nan| values throughout the forecast (see |Calc_OutputCorr_V1|), which would prevent any new @@ -764,7 +728,8 @@ class Calc_Stationary_V1(modeltools.Method): >>> derived.stationaritywindow.update() >>> derived.ratiominmax.update() >>> derived.nmblogentries(3) - >>> fluxes.forecastmode = 0.0 + >>> from hydpy import pub + >>> pub.options.simulationmode = "historical" >>> logs.loggedobservedvalue = 4.0, 5.0, 5.0 >>> model.calc_stationary_v1() >>> states.stationary @@ -787,7 +752,7 @@ class Calc_Stationary_V1(modeltools.Method): In `forecast` mode, |Stationary| stays frozen: - >>> fluxes.forecastmode = 1.0 + >>> pub.options.simulationmode = "forecast" >>> logs.loggedobservedvalue = 4.0, 5.0, 5.0 >>> model.calc_stationary_v1() >>> states.stationary @@ -797,7 +762,7 @@ class Calc_Stationary_V1(modeltools.Method): >>> control.stationaritycheck(active=False) >>> derived.stationaritywindow.update() - >>> fluxes.forecastmode = 0.0 + >>> pub.options.simulationmode = "historical" >>> model.calc_stationary_v1() >>> states.stationary stationary(0.0) @@ -808,19 +773,17 @@ class Calc_Stationary_V1(modeltools.Method): statcorr_derived.StationarityWindow, statcorr_derived.RatioMinMax, ) - REQUIREDSEQUENCES = ( - statcorr_fluxes.ForecastMode, - statcorr_logs.LoggedObservedValue, - ) + REQUIREDSEQUENCES = (statcorr_logs.LoggedObservedValue,) UPDATEDSEQUENCES = (statcorr_states.Stationary,) @staticmethod def __call__(model: modeltools.Model, /) -> None: der = model.parameters.derived.fastaccess - flu = model.sequences.fluxes.fastaccess log = model.sequences.logs.fastaccess sta = model.sequences.states.fastaccess - if (der.stationaritywindow > 0) and (flu.forecastmode == 0.0): + if (der.stationaritywindow > 0) and ( + model.runsettings.simulationmode == modelutils.HISTORICAL + ): has_nan = False qmin: float = modelutils.inf qmax: float = -modelutils.inf @@ -923,7 +886,7 @@ def __call__(model: modeltools.Model, /) -> None: class Calc_RelSumDelta_V1(modeltools.Method): r"""Calculate the relative sum of the absolute changes between successive simulated values while the variability check is enabled (see - |VariabilityCheck|) and |ForecastMode| is ``0.0`` (`historical`). + |VariabilityCheck|) and |Options.simulationmode| is `historical`. Basic equation: :math:`RelSumDelta = \frac{1}{EvaluatedValue} @@ -931,7 +894,7 @@ class Calc_RelSumDelta_V1(modeltools.Method): |LoggedSimulatedValue_i - LoggedSimulatedValue_{i+1}|` For a non-positive |EvaluatedValue|, |RelSumDelta| is |numpy.nan|. While - |ForecastMode| is ``1.0`` (`forecast`), |Calc_RelSumDelta_V1| keeps the value of + |Options.simulationmode| is `forecast`, |Calc_RelSumDelta_V1| keeps the value of the most recent `historical` assessment. Examples: @@ -941,7 +904,8 @@ class Calc_RelSumDelta_V1(modeltools.Method): >>> control.evaluationwindow(3) >>> derived.stationaryaveragingwindow(3) >>> derived.nmblogentries(3) - >>> fluxes.forecastmode = 0.0 + >>> from hydpy import pub + >>> pub.options.simulationmode = "historical" >>> logs.loggedsimulatedvalue = 9.0, 10.0, 11.0 >>> states.evaluatedvalue(10.0) >>> model.calc_relsumdelta_v1() @@ -957,12 +921,12 @@ class Calc_RelSumDelta_V1(modeltools.Method): stays unchanged: >>> states.evaluatedvalue(10.0) - >>> fluxes.forecastmode = 1.0 + >>> pub.options.simulationmode = "forecast" >>> model.calc_relsumdelta_v1() >>> states.relsumdelta relsumdelta(nan) - >>> fluxes.forecastmode = 0.0 + >>> pub.options.simulationmode = "historical" >>> derived.stationaryaveragingwindow(0) >>> model.calc_relsumdelta_v1() >>> states.relsumdelta @@ -972,7 +936,6 @@ class Calc_RelSumDelta_V1(modeltools.Method): CONTROLPARAMETERS = (statcorr_control.EvaluationWindow,) DERIVEDPARAMETERS = (statcorr_derived.StationaryAveragingWindow,) REQUIREDSEQUENCES = ( - statcorr_fluxes.ForecastMode, statcorr_logs.LoggedSimulatedValue, statcorr_states.EvaluatedValue, ) @@ -982,10 +945,11 @@ class Calc_RelSumDelta_V1(modeltools.Method): def __call__(model: modeltools.Model, /) -> None: con = model.parameters.control.fastaccess der = model.parameters.derived.fastaccess - flu = model.sequences.fluxes.fastaccess log = model.sequences.logs.fastaccess sta = model.sequences.states.fastaccess - if (der.stationaryaveragingwindow > 0) and (flu.forecastmode == 0.0): + if (der.stationaryaveragingwindow > 0) and ( + model.runsettings.simulationmode == modelutils.HISTORICAL + ): sumdelta: float = 0.0 for idx in range(con.evaluationwindow - 1): sumdelta = sumdelta + modelutils.fabs( @@ -1010,7 +974,7 @@ class Calc_LowVariability_V1(modeltools.Method): linear reduction of the correction (see |Calc_ReductionFactor_V1|). A |numpy.nan| value of |RelSumDelta| results in |LowVariability| being ``0.0``. Like |Calc_RelSumDelta_V1|, |Calc_LowVariability_V1| reassesses - |LowVariability| only while |ForecastMode| is ``0.0`` (`historical`). With the + |LowVariability| only while |Options.simulationmode| is `historical`. With the variability check disabled, |LowVariability| is always ``0.0``. Examples: @@ -1021,7 +985,8 @@ class Calc_LowVariability_V1(modeltools.Method): >>> derived.stationaryaveragingwindow(3) >>> derived.maxrelsumdelta(0.2) >>> derived.stationaritywindow(3) - >>> fluxes.forecastmode = 0.0 + >>> from hydpy import pub + >>> pub.options.simulationmode = "historical" >>> states.stationary(1.0) >>> states.relsumdelta(0.2) >>> model.calc_lowvariability_v1() @@ -1055,7 +1020,7 @@ class Calc_LowVariability_V1(modeltools.Method): In `forecast` mode, |LowVariability| stays frozen: - >>> fluxes.forecastmode = 1.0 + >>> pub.options.simulationmode = "forecast" >>> states.relsumdelta(0.4) >>> model.calc_lowvariability_v1() >>> states.lowvariability @@ -1068,6 +1033,7 @@ class Calc_LowVariability_V1(modeltools.Method): >>> model.calc_lowvariability_v1() >>> states.lowvariability lowvariability(0.0) + >>> del pub.options.simulationmode """ DERIVEDPARAMETERS = ( @@ -1075,21 +1041,16 @@ class Calc_LowVariability_V1(modeltools.Method): statcorr_derived.MaxRelSumDelta, statcorr_derived.StationaryAveragingWindow, ) - REQUIREDSEQUENCES = ( - statcorr_fluxes.ForecastMode, - statcorr_states.Stationary, - statcorr_states.RelSumDelta, - ) + REQUIREDSEQUENCES = (statcorr_states.Stationary, statcorr_states.RelSumDelta) UPDATEDSEQUENCES = (statcorr_states.LowVariability,) @staticmethod def __call__(model: modeltools.Model, /) -> None: der = model.parameters.derived.fastaccess - flu = model.sequences.fluxes.fastaccess sta = model.sequences.states.fastaccess if der.stationaryaveragingwindow <= 0: sta.lowvariability = 0.0 - elif flu.forecastmode == 0.0: + elif model.runsettings.simulationmode == modelutils.HISTORICAL: if ((der.stationaritywindow <= 0) or (sta.stationary == 1.0)) and ( sta.relsumdelta <= der.maxrelsumdelta ): @@ -1107,7 +1068,7 @@ class Calc_AveragedResidual_V1(modeltools.Method): immediately preceding the current forecast run (log position ``0`` already holds the current forecast step's own values, so averaging starts at position ``1``) and stores their difference in |AveragedResidual|. It leaves |AveragedResidual| - unchanged whenever |ForecastMode| is ``0.0`` (`historical`), |ForecastStep| is + unchanged whenever |Options.simulationmode| is `historical`, |ForecastStep| is not zero (i.e., beyond the first forecast step), or |AveragingWindow| is zero (mean-value-based correction disabled). When the averaging window contains a |numpy.nan| value, it falls back to the pointwise |Residual| (see @@ -1126,7 +1087,8 @@ class Calc_AveragedResidual_V1(modeltools.Method): >>> control.averagingwindow(2) >>> derived.stationaryaveragingwindow(1) >>> derived.nmblogentries(3) - >>> fluxes.forecastmode = 1.0 + >>> from hydpy import pub + >>> pub.options.simulationmode = "forecast" >>> states.forecaststep(0.0) >>> states.lowvariability(0.0) >>> states.residual(-9.0) @@ -1147,14 +1109,14 @@ class Calc_AveragedResidual_V1(modeltools.Method): averagedresidual(1.0) >>> states.forecaststep(0.0) - >>> fluxes.forecastmode = 0.0 + >>> pub.options.simulationmode = "historical" >>> model.calc_averagedresidual_v1() >>> states.averagedresidual averagedresidual(1.0) Setting |AveragingWindow| to zero disables mean-value-based correction: - >>> fluxes.forecastmode = 1.0 + >>> pub.options.simulationmode = "forecast" >>> control.averagingwindow(0) >>> model.calc_averagedresidual_v1() >>> states.averagedresidual @@ -1180,6 +1142,7 @@ class Calc_AveragedResidual_V1(modeltools.Method): >>> model.calc_averagedresidual_v1() >>> states.averagedresidual averagedresidual(10.0) + >>> del pub.options.simulationmode """ CONTROLPARAMETERS = (statcorr_control.AveragingWindow,) @@ -1188,7 +1151,6 @@ class Calc_AveragedResidual_V1(modeltools.Method): statcorr_derived.StationaryAveragingWindow, ) REQUIREDSEQUENCES = ( - statcorr_fluxes.ForecastMode, statcorr_logs.LoggedSimulatedValue, statcorr_logs.LoggedObservedValue, statcorr_states.LowVariability, @@ -1201,14 +1163,17 @@ class Calc_AveragedResidual_V1(modeltools.Method): def __call__(model: modeltools.Model, /) -> None: con = model.parameters.control.fastaccess der = model.parameters.derived.fastaccess - flu = model.sequences.fluxes.fastaccess log = model.sequences.logs.fastaccess sta = model.sequences.states.fastaccess if sta.lowvariability == 1.0: nmb = min(der.stationaryaveragingwindow, der.nmblogentries - 1) else: nmb = min(con.averagingwindow, der.nmblogentries - 1) - if (flu.forecastmode == 1.0) and (sta.forecaststep == 0.0) and (nmb > 0): + if ( + (model.runsettings.simulationmode == modelutils.FORECAST) + and (sta.forecaststep == 0.0) + and (nmb > 0) + ): sum_obs: float = 0.0 sum_sim: float = 0.0 has_nan = False @@ -1256,7 +1221,7 @@ class Calc_CorrectedValue_V1(modeltools.Method): This includes the `historical` mode whenever the current observation is available, as :math:`sim_k` then equals :math:`sim_0`. - In `historical` mode (|ForecastMode| is ``0.0``), :math:`r` is the pointwise + In `historical` mode (see |Options.simulationmode|), :math:`r` is the pointwise |Residual|. In `forecast` mode, setting |AveragingWindow| to a value greater than zero (or |LowVariability| being ``1.0``) switches to the mean-value-based |AveragedResidual| (see |Calc_AveragedResidual_V1|). Since it generally does @@ -1282,7 +1247,8 @@ class Calc_CorrectedValue_V1(modeltools.Method): >>> control.averagingwindow(0) >>> control.transitionsteps(0) >>> derived.nmblogentries(1) - >>> fluxes.forecastmode = 0.0 + >>> from hydpy import pub + >>> pub.options.simulationmode = "historical" >>> fluxes.isactive = 0.0 >>> states.reductionfactor(1.0) >>> states.lowvariability(0.0) @@ -1362,7 +1328,7 @@ class Calc_CorrectedValue_V1(modeltools.Method): >>> control.averagingwindow(2) >>> control.transitionsteps(2) - >>> fluxes.forecastmode = 1.0 + >>> pub.options.simulationmode = "forecast" >>> states.residual(1.0) >>> states.residualanchor(8.0) >>> states.averagedresidual(2.5) @@ -1411,7 +1377,7 @@ class Calc_CorrectedValue_V1(modeltools.Method): In `historical` mode, |Calc_CorrectedValue_V1| always relies on the pointwise residual, so that the corrected value reproduces the current observation: - >>> fluxes.forecastmode = 0.0 + >>> pub.options.simulationmode = "historical" >>> model.calc_correctedvalue_v1() >>> fluxes.correctedvalue correctedvalue(13.0) @@ -1424,7 +1390,6 @@ class Calc_CorrectedValue_V1(modeltools.Method): statcorr_control.TransitionSteps, ) REQUIREDSEQUENCES = ( - statcorr_fluxes.ForecastMode, statcorr_fluxes.IsActive, statcorr_logs.LoggedSimulatedValue, statcorr_states.ReductionFactor, @@ -1447,7 +1412,7 @@ def __call__(model: modeltools.Model, /) -> None: flu.correctedvalue = sim else: residual: float = sta.residual - if (flu.forecastmode == 1.0) and ( + if (model.runsettings.simulationmode == modelutils.FORECAST) and ( (con.averagingwindow > 0) or (sta.lowvariability == 1.0) ): weight: float = 1.0 @@ -1471,46 +1436,48 @@ class Update_ForecastStep_V1(modeltools.Method): Basic equation: :math:`ForecastStep_{new} = \begin{cases} - ForecastStep_{old} + 1 &|\ ForecastMode = 1 \\ - 0 &|\ ForecastMode = 0 + ForecastStep_{old} + 1 &|\ \text{forecast} \\ + 0 &|\ \text{historical} \end{cases}` + The case distinction refers to the current |Options.simulationmode|. + Examples: >>> from hydpy.models.statcorr_arima010 import * >>> parameterstep() >>> states.forecaststep(0.0) - >>> fluxes.forecastmode = 1.0 + >>> from hydpy import pub + >>> pub.options.simulationmode = "forecast" >>> model.update_forecaststep_v1() >>> model.update_forecaststep_v1() >>> states.forecaststep forecaststep(2.0) - >>> fluxes.forecastmode = 0.0 + >>> pub.options.simulationmode = "historical" >>> model.update_forecaststep_v1() >>> states.forecaststep forecaststep(0.0) """ - REQUIREDSEQUENCES = (statcorr_fluxes.ForecastMode,) UPDATEDSEQUENCES = (statcorr_states.ForecastStep,) @staticmethod def __call__(model: modeltools.Model, /) -> None: - flu = model.sequences.fluxes.fastaccess sta = model.sequences.states.fastaccess - if flu.forecastmode == 1.0: + if model.runsettings.simulationmode == modelutils.FORECAST: sta.forecaststep = sta.forecaststep + 1.0 else: sta.forecaststep = 0.0 -class Determine_OutputCorrection_V1(modeltools.SetAutoMethod): +class Determine_OutputCorrection_V1(modeltools.AutoMethod): r"""Interface method that calculates the corrected value using an ARIMA(0,1,0) error model. - |Determine_OutputCorrection_V1| stores the given simulation mode in - |ForecastMode| and then executes the following submethods: + |Determine_OutputCorrection_V1| executes the following submethods, which take + the current simulation mode directly from |Options.simulationmode| (via + |Model.runsettings|): * |Calc_EvaluatedValue_V1| and |Calc_IsActive_V1| decide whether the submodel is responsible for the current simulated value. @@ -1527,7 +1494,7 @@ class Determine_OutputCorrection_V1(modeltools.SetAutoMethod): All submethods update the internal states even when the submodel is not responsible, so that a submodel taking over responsibility starts with - up-to-date information. While |ForecastMode| is ``1.0`` (`forecast`), they keep + up-to-date information. While |Options.simulationmode| is `forecast`, they keep the outcomes of the most recent `historical` assessment (the responsibility, the pointwise residual, and the stationarity and variability assessments), so that only |ReductionFactor| and, if configured, the blend towards |AveragedResidual| @@ -1561,9 +1528,7 @@ class Determine_OutputCorrection_V1(modeltools.SetAutoMethod): >>> control.transitionsteps(0) >>> logs.loggedsimulatedvalue = 5.0, 3.0, 2.0 >>> logs.loggedobservedvalue = 6.0, 4.0, 3.0 - >>> model.determine_outputcorrection_v1(False) - >>> fluxes.forecastmode - forecastmode(0.0) + >>> model.determine_outputcorrection_v1() >>> fluxes.isactive isactive(1.0) >>> fluxes.correctedvalue @@ -1573,9 +1538,9 @@ class Determine_OutputCorrection_V1(modeltools.SetAutoMethod): >>> logs.loggedsimulatedvalue = 7.0, 5.0, 3.0 >>> logs.loggedobservedvalue = nan, 6.0, 4.0 - >>> model.determine_outputcorrection_v1(True) - >>> fluxes.forecastmode - forecastmode(1.0) + >>> from hydpy import pub + >>> with pub.options.simulationmode("forecast"): + ... model.determine_outputcorrection_v1() >>> fluxes.correctedvalue correctedvalue(8.0) >>> states.forecaststep @@ -1583,7 +1548,6 @@ class Determine_OutputCorrection_V1(modeltools.SetAutoMethod): """ SUBMETHODS = ( - Set_ForecastMode_V1, Calc_EvaluatedValue_V1, Calc_IsActive_V1, Calc_Residual_ResidualAnchor_V1, @@ -1630,11 +1594,7 @@ class Determine_OutputCorrection_V1(modeltools.SetAutoMethod): statcorr_states.Residual, statcorr_states.ResidualAnchor, ) - RESULTSEQUENCES = ( - statcorr_fluxes.ForecastMode, - statcorr_fluxes.IsActive, - statcorr_fluxes.CorrectedValue, - ) + RESULTSEQUENCES = (statcorr_fluxes.IsActive, statcorr_fluxes.CorrectedValue) class Is_Active_V1(modeltools.Method): diff --git a/hydpy/models/statcorr_arima010.py b/hydpy/models/statcorr_arima010.py index db8cc7484c..39de19a905 100644 --- a/hydpy/models/statcorr_arima010.py +++ b/hydpy/models/statcorr_arima010.py @@ -101,7 +101,7 @@ current value, and |OutputCorrModel_V1.get_correctedoutput| returns the buffered value: - >>> model.determine_outputcorrection(False) + >>> model.determine_outputcorrection() >>> assert model.is_active() >>> from hydpy import round_ >>> round_(model.get_correctedoutput()) @@ -137,7 +137,6 @@ class Model(statcorr_model.Sub_OutputCorrModel, statcorrinterfaces.OutputCorrMod statcorr_model.Get_CorrectedOutput_V1, ) ADD_METHODS = ( - statcorr_model.Set_ForecastMode_V1, statcorr_model.Calc_EvaluatedValue_V1, statcorr_model.Calc_IsActive_V1, statcorr_model.Calc_Residual_ResidualAnchor_V1, diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py index 6ea8d0ed59..abd7c327e7 100644 --- a/hydpy/models/statcorr_main.py +++ b/hydpy/models/statcorr_main.py @@ -109,12 +109,10 @@ ... first, last = pub.timegrids.sim.firstdate, pub.timegrids.sim.lastdate ... pub.timegrids.sim.lastdate = split ... with pub.options.simulationmode("historical"): - ... model.update_parameters() ... test.hydpy.simulate() ... conditions = model.conditions ... pub.timegrids.sim.dates = split, last ... with pub.options.simulationmode("forecast"): - ... model.update_parameters() ... model.conditions = conditions ... test.hydpy.simulate() ... pub.timegrids.sim.dates = first, last From 1254a68f1a5d5fcebae1e8dfe01830f38371d916 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Mon, 9 Nov 2026 15:51:34 +0100 Subject: [PATCH 30/43] Restructure the statcorr base model so that it knows all methods and parameters --- hydpy/models/statcorr/__init__.py | 8 +- hydpy/models/statcorr/statcorr_control.py | 14 +- hydpy/models/statcorr/statcorr_derived.py | 12 +- hydpy/models/statcorr/statcorr_model.py | 167 +++++++++++--------- hydpy/models/statcorr/statcorr_variables.py | 2 +- hydpy/models/statcorr_arima010.py | 3 - hydpy/models/statcorr_main.py | 26 +-- 7 files changed, 115 insertions(+), 117 deletions(-) diff --git a/hydpy/models/statcorr/__init__.py b/hydpy/models/statcorr/__init__.py index 70cb7a2013..8f532cc689 100644 --- a/hydpy/models/statcorr/__init__.py +++ b/hydpy/models/statcorr/__init__.py @@ -4,12 +4,10 @@ """ from hydpy.exe.modelimports import * -from hydpy.models.statcorr import statcorr_control +from hydpy.models.statcorr.statcorr_control import NmbSubmodels as _NmbSubmodels -ADDITIONAL_CONTROLPARAMETERS = ( - statcorr_control.NmbSubmodels, - statcorr_control.Propagate, -) +ADDITIONAL_CONTROLPARAMETERS = (_NmbSubmodels,) +del _NmbSubmodels from hydpy.models.statcorr.statcorr_model import ( # pylint: disable=wrong-import-position Model, diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index 74d6b27a26..9836b4252d 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -69,7 +69,7 @@ class CorrectionMode(parametertools.Parameter): `option`. Internally, |CorrectionMode| stores them as the integer values 1, 2, and 3: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> correctionmode correctionmode(?) @@ -133,7 +133,7 @@ class LowerLimit(parametertools.Parameter): def trim(self, lower: TrimHook = None, upper: TrimHook = None) -> bool: r"""Trim upper values in accordance with :math:`LowerLimit \leq UpperLimit`. - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> upperlimit.value = 2.0 >>> lowerlimit(1.0) @@ -161,7 +161,7 @@ class UpperLimit(parametertools.Parameter): def trim(self, lower: TrimHook = None, upper: TrimHook = None) -> bool: r"""Trim lower values in accordance with :math:`LowerLimit \leq UpperLimit`. - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> lowerlimit.value = 2.0 >>> upperlimit(3.0) @@ -187,7 +187,7 @@ class StationarityCheck(parametertools.SpecialParameter): values within this period (`ratiominmax`), below which |Calc_Stationary_V1| considers the conditions instationary: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> stationaritycheck stationaritycheck(?) @@ -332,7 +332,7 @@ def configured(self) -> bool: """Flag indicating whether the stationarity check has already been configured. - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> stationaritycheck.configured False @@ -377,7 +377,7 @@ class VariabilityCheck(parametertools.SpecialParameter): period (`averagingwindow`, in log entries) for determining the mean-value-based residual under stationary conditions (see |Calc_AveragedResidual_V1|): - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> variabilitycheck variabilitycheck(?) @@ -527,7 +527,7 @@ def configured(self) -> bool: """Flag indicating whether the variability check has already been configured. - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> variabilitycheck.configured False diff --git a/hydpy/models/statcorr/statcorr_derived.py b/hydpy/models/statcorr/statcorr_derived.py index 16034f9682..7e67e913ce 100644 --- a/hydpy/models/statcorr/statcorr_derived.py +++ b/hydpy/models/statcorr/statcorr_derived.py @@ -14,7 +14,7 @@ class NmbLogEntries(parametertools.NmbParameter): |NmbLogEntries| resets all state sequences to their initial values whenever its value changes, as the latter depend on the logged data: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> derived.nmblogentries(2) >>> states.residual(2.0) @@ -49,7 +49,7 @@ def update(self) -> None: As long as not all relevant control parameters are defined, |NmbLogEntries.update| leaves the current value untouched: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> evaluationwindow(3) >>> stationaritycheck(active=True, window=4, ratiominmax=0.5) @@ -160,7 +160,7 @@ def update(self) -> None: As long as |StationarityCheck| is not configured, |StationarityWindow.update| leaves the current value untouched: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> derived.stationaritywindow.update() >>> derived.stationaritywindow @@ -196,7 +196,7 @@ def update(self) -> None: As long as |StationarityCheck| is not configured, |RatioMinMax.update| leaves the current value untouched: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> derived.ratiominmax.update() >>> derived.ratiominmax @@ -233,7 +233,7 @@ def update(self) -> None: As long as |VariabilityCheck| is not configured, |MaxRelSumDelta.update| leaves the current value untouched: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> derived.maxrelsumdelta.update() >>> derived.maxrelsumdelta @@ -270,7 +270,7 @@ def update(self) -> None: As long as |VariabilityCheck| is not configured, |StationaryAveragingWindow.update| leaves the current value untouched: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> derived.stationaryaveragingwindow.update() >>> derived.stationaryaveragingwindow diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index b4a2c42912..f1edb66608 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -101,7 +101,7 @@ class Calc_OutputCorr_V1(modeltools.Method): Without any attached submodel, the corrected discharge equals the inflow: - >>> from hydpy.models.statcorr import * + >>> from hydpy.models.statcorr_main import * >>> parameterstep() >>> fluxes.inflow = 2.0 >>> inputs.discharge = 3.0 @@ -320,61 +320,6 @@ def __call__(model: modeltools.Model, /) -> None: out.q = flu.correctedq if con.propagate else flu.inflow -class Model(modeltools.AdHocModel): - """|statcorr.DOCNAME.complete|.""" - - DOCNAME = modeltools.DocName(short="StatCorr") - __HYDPY_ROOTMODEL__ = None - - INLET_METHODS = (Pick_Inflow_V1,) - OBSERVER_METHODS = () - RECEIVER_METHODS = () - RUN_METHODS = (Calc_OutputCorr_V1,) - INTERFACE_METHODS = () - ADD_METHODS = (Calc_OutputCorr_OutputCorrModel_V1,) - OUTLET_METHODS = (Pass_CorrectedQ_V1,) - SENDER_METHODS = () - SUBMODELINTERFACES = (statcorrinterfaces.OutputCorrModel_V1,) - SUBMODELS = () - - outputcorrmodels = modeltools.SubmodelsProperty( - statcorrinterfaces.OutputCorrModel_V1 - ) - - @importtools.prepare_submodel( # type: ignore[call-overload, untyped-decorator] - "outputcorrmodels", statcorrinterfaces.OutputCorrModel_V1, dimensionality=1 - ) - def add_outputcorrmodel_v1( - self, - outputcorrmodel: statcorrinterfaces.OutputCorrModel_V1, - /, - *, - position: int, - refresh: bool, - ) -> None: - """Initialise the given submodel that follows the |OutputCorrModel_V1| - interface. - - The main model does not need to pass any information to the submodel. In - particular, the submodel determines the length of its log from its own - parameters (see |NmbLogEntries|): - - >>> from hydpy.models.statcorr import * - >>> parameterstep() - >>> nmbsubmodels(1) - >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0): - ... evaluationwindow(2) - ... stationaritycheck(active=True, window=4, ratiominmax=0.5) - ... variabilitycheck(active=False) - ... maxnanskip(2) - ... averagingwindow(0) - >>> model.outputcorrmodels[0].parameters.derived.nmblogentries - nmblogentries(4) - >>> model.outputcorrmodels[0].sequences.logs.loggedsimulatedvalue - loggedsimulatedvalue(nan, nan, nan, nan) - """ - - class Set_SimulatedValue_V1(modeltools.Method): """Append the given simulated value to the internal log of simulated values by shifting the previously buffered values one position to the right @@ -382,7 +327,7 @@ class Set_SimulatedValue_V1(modeltools.Method): Example: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> derived.nmblogentries(3) >>> logs.loggedsimulatedvalue = 4.0, 3.0, 2.0 @@ -412,7 +357,7 @@ class Set_ObservedValue_V1(modeltools.Method): Example: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> derived.nmblogentries(3) >>> logs.loggedobservedvalue = 4.0, 3.0, 2.0 @@ -452,7 +397,7 @@ class Calc_EvaluatedValue_V1(modeltools.Method): (index ``0`` upwards) and never on the oldest ones sitting near the end of a larger log (which can well still be |numpy.nan|): - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> from numpy import nan >>> control.evaluationwindow(3) @@ -508,7 +453,7 @@ class Calc_IsActive_V1(modeltools.Method): Examples: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> from numpy import inf >>> control.active(True) @@ -626,7 +571,7 @@ class Calc_Residual_ResidualAnchor_V1(modeltools.Method): If the most recent observation is available, it determines the residual: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> from numpy import nan >>> control.maxnanskip(2) @@ -721,7 +666,7 @@ class Calc_Stationary_V1(modeltools.Method): The ratio ``4.0 / 5.0 = 0.8`` is not below |RatioMinMax|: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> from numpy import nan >>> control.stationaritycheck(active=True, window=3, ratiominmax=0.5) @@ -822,7 +767,7 @@ class Calc_ReductionFactor_V1(modeltools.Method): Sustained instationary conditions reduce |ReductionFactor| to zero within the two steps given by |ReductionSteps|: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> control.reductionsteps(2) >>> derived.stationaritywindow(3) @@ -899,7 +844,7 @@ class Calc_RelSumDelta_V1(modeltools.Method): Examples: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> control.evaluationwindow(3) >>> derived.stationaryaveragingwindow(3) @@ -979,7 +924,7 @@ class Calc_LowVariability_V1(modeltools.Method): Examples: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> from numpy import nan >>> derived.stationaryaveragingwindow(3) @@ -1081,7 +1026,7 @@ class Calc_AveragedResidual_V1(modeltools.Method): On the first forecast step, the average is taken from log positions ``1`` and ``2`` (mean observed ``4.0``, mean simulated ``3.0``): - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> from numpy import nan >>> control.averagingwindow(2) @@ -1240,7 +1185,7 @@ class Calc_CorrectedValue_V1(modeltools.Method): If the submodel is not responsible, no correction applies: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> control.maxabsshift(100.0) >>> control.maxrelshift(10.0) @@ -1444,7 +1389,7 @@ class Update_ForecastStep_V1(modeltools.Method): Examples: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> states.forecaststep(0.0) >>> from hydpy import pub @@ -1505,7 +1450,7 @@ class Determine_OutputCorrection_V1(modeltools.AutoMethod): In `historical` mode, the correction reproduces the most recent observation: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> from numpy import inf, nan >>> derived.nmblogentries(3) @@ -1603,7 +1548,7 @@ class Is_Active_V1(modeltools.Method): Example: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> fluxes.isactive = 1.0 >>> assert model.is_active_v1() @@ -1624,7 +1569,7 @@ class Get_CorrectedOutput_V1(modeltools.Method): Example: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> fluxes.correctedvalue = 2.5 >>> from hydpy import round_ @@ -1640,6 +1585,86 @@ def __call__(model: modeltools.Model, /) -> float: return flu.correctedvalue +class Model(modeltools.AdHocModel): + """|statcorr.DOCNAME.complete|.""" + + DOCNAME = modeltools.DocName(short="StatCorr") + __HYDPY_ROOTMODEL__ = None + + INLET_METHODS = (Pick_Inflow_V1,) + OBSERVER_METHODS = () + RECEIVER_METHODS = () + RUN_METHODS = (Calc_OutputCorr_V1,) + INTERFACE_METHODS = ( + Set_SimulatedValue_V1, + Set_ObservedValue_V1, + Determine_OutputCorrection_V1, + Is_Active_V1, + Get_CorrectedOutput_V1, + ) + ADD_METHODS = ( + Calc_OutputCorr_OutputCorrModel_V1, + Calc_EvaluatedValue_V1, + Calc_IsActive_V1, + Calc_Residual_ResidualAnchor_V1, + Calc_Stationary_V1, + Calc_ReductionFactor_V1, + Calc_RelSumDelta_V1, + Calc_LowVariability_V1, + Calc_AveragedResidual_V1, + Calc_CorrectedValue_V1, + Update_ForecastStep_V1, + ) + OUTLET_METHODS = (Pass_CorrectedQ_V1,) + SENDER_METHODS = () + SUBMODELINTERFACES = (statcorrinterfaces.OutputCorrModel_V1,) + SUBMODELS = () + + outputcorrmodels = modeltools.SubmodelsProperty( + statcorrinterfaces.OutputCorrModel_V1 + ) + + +class Main_OutputCorrModel_V1(modeltools.AdHocModel): + """Base class for |statcorr.DOCNAME.long| models that use submodels that comply + with the |OutputCorrModel_V1| interface.""" + + outputcorrmodels: modeltools.SubmodelsProperty + + @importtools.prepare_submodel( # type: ignore[call-overload, untyped-decorator] + "outputcorrmodels", statcorrinterfaces.OutputCorrModel_V1, dimensionality=1 + ) + def add_outputcorrmodel_v1( + self, + outputcorrmodel: statcorrinterfaces.OutputCorrModel_V1, + /, + *, + position: int, + refresh: bool, + ) -> None: + """Initialise the given submodel that follows the |OutputCorrModel_V1| + interface. + + The main model does not need to pass any information to the submodel. In + particular, the submodel determines the length of its log from its own + parameters (see |NmbLogEntries|): + + >>> from hydpy.models.statcorr_main import * + >>> parameterstep() + >>> nmbsubmodels(1) + >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0): + ... evaluationwindow(2) + ... stationaritycheck(active=True, window=4, ratiominmax=0.5) + ... variabilitycheck(active=False) + ... maxnanskip(2) + ... averagingwindow(0) + >>> model.outputcorrmodels[0].parameters.derived.nmblogentries + nmblogentries(4) + >>> model.outputcorrmodels[0].sequences.logs.loggedsimulatedvalue + loggedsimulatedvalue(nan, nan, nan, nan) + """ + + class Sub_OutputCorrModel(modeltools.AdHocModel): """Base class for submodels that comply with the submodel interfaces defined in module |statcorrinterfaces|.""" diff --git a/hydpy/models/statcorr/statcorr_variables.py b/hydpy/models/statcorr/statcorr_variables.py index a6c23cfb43..f92db4ce88 100644 --- a/hydpy/models/statcorr/statcorr_variables.py +++ b/hydpy/models/statcorr/statcorr_variables.py @@ -12,7 +12,7 @@ class MixinLogEntries(variabletools.Variable, abc.ABC): We take the log sequence |LoggedObservedValue| as an example: - >>> from hydpy.models.statcorr_arima010 import * + >>> from hydpy.models.statcorr import * >>> parameterstep() >>> derived.nmblogentries(3) >>> logs.loggedobservedvalue diff --git a/hydpy/models/statcorr_arima010.py b/hydpy/models/statcorr_arima010.py index 39de19a905..8a759260e9 100644 --- a/hydpy/models/statcorr_arima010.py +++ b/hydpy/models/statcorr_arima010.py @@ -111,11 +111,8 @@ from hydpy.core import modeltools from hydpy.exe.modelimports import * from hydpy.interfaces import statcorrinterfaces -from hydpy.models.statcorr import statcorr_derived from hydpy.models.statcorr import statcorr_model -ADDITIONAL_DERIVEDPARAMETERS = (statcorr_derived.NmbLogEntries,) - class Model(statcorr_model.Sub_OutputCorrModel, statcorrinterfaces.OutputCorrModel_V1): """|statcorr_arima010.DOCNAME.complete|.""" diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py index abd7c327e7..61f926d307 100644 --- a/hydpy/models/statcorr_main.py +++ b/hydpy/models/statcorr_main.py @@ -300,20 +300,16 @@ | 10/01 | nan | 3.0 | 3.5 | 3.0 | 3.5 | """ -from hydpy.core import importtools from hydpy.core import modeltools from hydpy.exe.modelimports import * from hydpy.interfaces import statcorrinterfaces from hydpy.models.statcorr import statcorr_control from hydpy.models.statcorr import statcorr_model -ADDITIONAL_CONTROLPARAMETERS = ( - statcorr_control.NmbSubmodels, - statcorr_control.Propagate, -) +ADDITIONAL_CONTROLPARAMETERS = (statcorr_control.NmbSubmodels,) -class Model(modeltools.AdHocModel): +class Model(statcorr_model.Main_OutputCorrModel_V1): """|statcorr_main.DOCNAME.complete|.""" DOCNAME = modeltools.DocName( @@ -337,24 +333,6 @@ class Model(modeltools.AdHocModel): statcorrinterfaces.OutputCorrModel_V1 ) - @importtools.prepare_submodel( # type: ignore[call-overload, untyped-decorator] - "outputcorrmodels", statcorrinterfaces.OutputCorrModel_V1, dimensionality=1 - ) - def add_outputcorrmodel_v1( - self, - outputcorrmodel: statcorrinterfaces.OutputCorrModel_V1, - /, - *, - position: int, - refresh: bool, - ) -> None: - """Initialise the given submodel that follows the |OutputCorrModel_V1| - interface. - - The submodel determines the length of its log from its own parameters (see - |NmbLogEntries|), so the main model does not need to pass any information. - """ - tester = Tester() cythonizer = Cythonizer() From d4dbcca3deb3b2b90b29af6471c584d1d761e9da Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Tue, 10 Nov 2026 17:19:05 +0100 Subject: [PATCH 31/43] Add reference to LARSIM Website to hydpy-statcorr.rst --- hydpy/docs/rst/HydPy-StatCorr.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hydpy/docs/rst/HydPy-StatCorr.rst b/hydpy/docs/rst/HydPy-StatCorr.rst index a55650d7c8..38dd4a2742 100644 --- a/hydpy/docs/rst/HydPy-StatCorr.rst +++ b/hydpy/docs/rst/HydPy-StatCorr.rst @@ -10,8 +10,8 @@ designed for different kinds of variables, and the submodels complying with the the currently available application model |statcorr_main| focuses on discharge: it reads the simulated discharge from its inlet node(s), passes it through one or more |OutputCorrModel_V1| submodels, and delivers the corrected discharge to its outlet -node. |statcorr_arima010| is such a submodel; it estimates the correction from an -ARIMA(0,1,0) error model, following the LARSIM approach. +node. |statcorr_arima010| is such a submodel; it estimates the correction with an +ARIMA(0,1,0) error model, following the LARSIM approach (see https://larsim.info). Available models: From 1c25fdeb5898d2890c0c3e5bba4030f8d8261879 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Tue, 10 Nov 2026 17:19:56 +0100 Subject: [PATCH 32/43] Simplify docstring of statcorr interface --- hydpy/interfaces/statcorrinterfaces.py | 33 ++++---------------------- 1 file changed, 4 insertions(+), 29 deletions(-) diff --git a/hydpy/interfaces/statcorrinterfaces.py b/hydpy/interfaces/statcorrinterfaces.py index 08110d3a72..d729b710ef 100644 --- a/hydpy/interfaces/statcorrinterfaces.py +++ b/hydpy/interfaces/statcorrinterfaces.py @@ -6,49 +6,24 @@ class OutputCorrModel_V1(modeltools.SubmodelInterface): - """Simple interface for the statistical output correction of simulated values. - - The interface does not prescribe the corrected variable (|statcorr_main|, for - example, corrects discharge). All values passed to and returned by the - submodel share the unit of this variable. - - Each submodel owns and maintains its own persistent log of simulated and - observed values. The main model merely passes the current simulated and - observed value to the submodel once per simulation step; - the submodel is responsible for shifting these values into its internal log - and for using the resulting history when calculating the correction. It also - determines the required length of its log from its own parameters. - - The expected call order within one simulation step is: - - 1. |OutputCorrModel_V1.set_simulatedvalue| - 2. |OutputCorrModel_V1.set_observedvalue| - 3. |OutputCorrModel_V1.determine_outputcorrection| - 4. |OutputCorrModel_V1.is_active| - 5. |OutputCorrModel_V1.get_correctedoutput| - """ + """Simple interface for the statistical output correction of simulated values.""" typeid: ClassVar[Literal[1]] = 1 """Type identifier for |OutputCorrModel_V1| submodels.""" @modeltools.abstractmodelmethod def set_simulatedvalue(self, simulatedvalue: float) -> None: - """Pass the current simulated value to the submodel, which appends it to - its internal log of simulated values.""" + """Pass the current simulated value to the submodel.""" @modeltools.abstractmodelmethod def set_observedvalue(self, observedvalue: float) -> None: """Pass the current observed value (or |numpy.nan| when unavailable) to the - submodel, which appends it to its internal log of observed values.""" + submodel.""" @modeltools.abstractmodelmethod def determine_outputcorrection(self) -> None: """Calculate the corrected output value from the internal logs of - simulated and observed values. - - Submodels that behave differently in `historical` and `forecast` mode - read the current |Options.simulationmode| at runtime via - |Model.runsettings|.""" + simulated and observed values.""" @modeltools.abstractmodelmethod def is_active(self) -> bool: From b45593980e18f784842f4f7cf0aada9708f16bad Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Wed, 11 Nov 2026 00:21:49 +0100 Subject: [PATCH 33/43] Implement requested changes from review --- hydpy/interfaces/statcorrinterfaces.py | 18 +- hydpy/models/statcorr/__init__.py | 11 +- hydpy/models/statcorr/statcorr_control.py | 120 ++++---- hydpy/models/statcorr/statcorr_derived.py | 92 +++--- hydpy/models/statcorr/statcorr_fluxes.py | 6 +- hydpy/models/statcorr/statcorr_logs.py | 8 +- hydpy/models/statcorr/statcorr_model.py | 320 ++++++++++---------- hydpy/models/statcorr/statcorr_states.py | 70 +---- hydpy/models/statcorr/statcorr_variables.py | 18 +- hydpy/models/statcorr_arima010.py | 16 +- hydpy/models/statcorr_main.py | 149 +++++---- 11 files changed, 374 insertions(+), 454 deletions(-) diff --git a/hydpy/interfaces/statcorrinterfaces.py b/hydpy/interfaces/statcorrinterfaces.py index d729b710ef..fc0eba12e4 100644 --- a/hydpy/interfaces/statcorrinterfaces.py +++ b/hydpy/interfaces/statcorrinterfaces.py @@ -13,24 +13,24 @@ class OutputCorrModel_V1(modeltools.SubmodelInterface): @modeltools.abstractmodelmethod def set_simulatedvalue(self, simulatedvalue: float) -> None: - """Pass the current simulated value to the submodel.""" + """Set the simulated value.""" @modeltools.abstractmodelmethod def set_observedvalue(self, observedvalue: float) -> None: - """Pass the current observed value (or |numpy.nan| when unavailable) to the - submodel.""" + """Set the observed value.""" @modeltools.abstractmodelmethod def determine_outputcorrection(self) -> None: - """Calculate the corrected output value from the internal logs of - simulated and observed values.""" + """Calculate the corrected output value.""" @modeltools.abstractmodelmethod def is_active(self) -> bool: - """Tell whether the submodel was responsible for correcting the simulated - value during the most recent call of - |OutputCorrModel_V1.determine_outputcorrection|.""" + """Tell whether |OutputCorrModel_V1.determine_outputcorrection| + succeeded. + """ @modeltools.abstractmodelmethod def get_correctedoutput(self) -> float: - """Get the previously calculated corrected value.""" + """Get the previously calculated corrected value (which can be + the originally simulated value, if the output correction is not active). + """ diff --git a/hydpy/models/statcorr/__init__.py b/hydpy/models/statcorr/__init__.py index 8f532cc689..efa22d8623 100644 --- a/hydpy/models/statcorr/__init__.py +++ b/hydpy/models/statcorr/__init__.py @@ -1,17 +1,10 @@ """ The |statcorr.DOCNAME.long| base model provides features for the statistical -correction of simulated discharge based on observed discharge values. +correction of simulated variables based on observed values. """ from hydpy.exe.modelimports import * -from hydpy.models.statcorr.statcorr_control import NmbSubmodels as _NmbSubmodels - -ADDITIONAL_CONTROLPARAMETERS = (_NmbSubmodels,) -del _NmbSubmodels - -from hydpy.models.statcorr.statcorr_model import ( # pylint: disable=wrong-import-position - Model, -) +from hydpy.models.statcorr.statcorr_model import Model tester = Tester() cythonizer = Cythonizer() diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index 9836b4252d..f24b614392 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -10,8 +10,8 @@ class NmbSubmodels(parametertools.NmbParameter): """The number of output correction submodels [-]. - Setting |NmbSubmodels| automatically resizes the - |Model.outputcorrmodels| submodel slots accordingly: + Setting |NmbSubmodels| automatically resizes the |Model.outputcorrmodels| submodel + slots accordingly: >>> from hydpy.models.statcorr import * >>> parameterstep() @@ -22,14 +22,20 @@ class NmbSubmodels(parametertools.NmbParameter): SPAN = (0, None) + @overload + def __call__(self, *values: CallHook) -> None: ... + + @overload + def __call__(self, *, auxfile: str) -> None: ... + def __call__(self, *args: CallHook, **kwargs: Any) -> None: super().__call__(*args, **kwargs) self.subpars.pars.model.outputcorrmodels.number = self.value class EvaluationWindow(parametertools.Parameter): - """The length (in log entries) of the time period for evaluating the current - conditions [-].""" + """The number of the most recent log entries used to determine the mean simulated + value and its variability [-].""" NDIM: Final[Literal[0]] = 0 TYPE: Final = int @@ -41,7 +47,8 @@ class MaxNaNSkip(parametertools.Parameter): when searching back for the most recently available residual [-]. The search covers the current log entry and the |MaxNaNSkip| preceding ones. - A value of zero restricts the search to the current log entry.""" + A value of zero restricts the search to the current log entry. + """ NDIM: Final[Literal[0]] = 0 TYPE: Final = int @@ -50,11 +57,7 @@ class MaxNaNSkip(parametertools.Parameter): class Active(parametertools.Parameter): """Flag determining whether the submodel may correct the simulated values at - all [-]. - - Even when |Active| is |True|, the submodel only corrects the simulated values - while the relevant mean simulated value lies within the range defined by - |LowerLimit| and |UpperLimit| (see |Calc_IsActive_V1|).""" + all [-].""" NDIM: Final[Literal[0]] = 0 TYPE: Final = bool @@ -92,9 +95,6 @@ class CorrectionMode(parametertools.Parameter): ... ValueError: Parameter `correctionmode` of element `?` supports the options \ `historical`, `forecast`, and `both`, but `always` is given. - - Regardless of |CorrectionMode|, the submodel keeps updating its log and states - in both simulation modes (see |Determine_OutputCorrection_V1|). """ NDIM: Final[Literal[0]] = 0 @@ -128,13 +128,16 @@ class LowerLimit(parametertools.Parameter): NDIM: Final[Literal[0]] = 0 TYPE: Final = float - SPAN = (0.0, None) + SPAN = (None, None) def trim(self, lower: TrimHook = None, upper: TrimHook = None) -> bool: r"""Trim upper values in accordance with :math:`LowerLimit \leq UpperLimit`. >>> from hydpy.models.statcorr import * >>> parameterstep() + >>> lowerlimit(3.0) + >>> lowerlimit + lowerlimit(3.0) >>> upperlimit.value = 2.0 >>> lowerlimit(1.0) >>> lowerlimit @@ -156,15 +159,18 @@ class UpperLimit(parametertools.Parameter): NDIM: Final[Literal[0]] = 0 TYPE: Final = float - SPAN = (0.0, None) + SPAN = (None, None) def trim(self, lower: TrimHook = None, upper: TrimHook = None) -> bool: r"""Trim lower values in accordance with :math:`LowerLimit \leq UpperLimit`. >>> from hydpy.models.statcorr import * >>> parameterstep() - >>> lowerlimit.value = 2.0 + >>> upperlimit(1.0) + >>> upperlimit + upperlimit(1.0) >>> upperlimit(3.0) + >>> lowerlimit.value = 2.0 >>> upperlimit upperlimit(3.0) >>> upperlimit(1.0) @@ -194,14 +200,14 @@ class StationarityCheck(parametertools.SpecialParameter): >>> stationaritycheck.verify() Traceback (most recent call last): ... - RuntimeError: For parameter `stationaritycheck` of element `?`, it is still \ -unknown whether the stationarity check is enabled. + RuntimeError: For parameter `stationaritycheck` of element `?`, no configuration \ +has been defined so far. Please pass either `active=False` or `active=True` \ +together with the required keyword arguments. >>> stationaritycheck(active=False) >>> stationaritycheck stationaritycheck(active=False) >>> stationaritycheck.verify() - >>> stationaritycheck(active=True, window=10, ratiominmax=0.5) >>> stationaritycheck stationaritycheck(active=True, window=10, ratiominmax=0.5) @@ -320,11 +326,12 @@ def __repr__(self) -> str: ) def verify(self) -> None: - """Raise a |RuntimeError| if the configuration is still unknown.""" + """Raise a |RuntimeError| if no configuration has been defined so far.""" if self._config is None: raise RuntimeError( - f"For parameter {objecttools.elementphrase(self)}, it is still unknown " - f"whether the stationarity check is enabled." + f"For parameter {objecttools.elementphrase(self)}, no configuration " + f"has been defined so far. Please pass either `active=False` or " + f"`active=True` together with the required keyword arguments." ) @property @@ -369,13 +376,10 @@ class VariabilityCheck(parametertools.SpecialParameter): """Configuration of the check of whether the simulated values vary little enough to base the correction on a long-term mean residual [-]. - |VariabilityCheck| is a special parameter (see |SpecialParameter|). Either - switch the check off by passing `active=False` or switch it on by passing + Either switch the check off by passing `active=False` or switch it on by passing `active=True` together with the threshold for the sum of the absolute changes of - the simulated values within the |EvaluationWindow| divided by |EvaluatedValue| - (`maxrelsumdelta`, see |Calc_LowVariability_V1|) and the length of the averaging - period (`averagingwindow`, in log entries) for determining the mean-value-based - residual under stationary conditions (see |Calc_AveragedResidual_V1|): + the simulated values (`maxrelsumdelta`) and the length of the averaging + period (`averagingwindow`): >>> from hydpy.models.statcorr import * >>> parameterstep() @@ -384,8 +388,9 @@ class VariabilityCheck(parametertools.SpecialParameter): >>> variabilitycheck.verify() Traceback (most recent call last): ... - RuntimeError: For parameter `variabilitycheck` of element `?`, it is still \ -unknown whether the variability check is enabled. + RuntimeError: For parameter `variabilitycheck` of element `?`, no configuration \ +has been defined so far. Please pass either `active=False` or `active=True` \ +together with the required keyword arguments. >>> variabilitycheck(active=False) >>> variabilitycheck @@ -515,11 +520,12 @@ def __repr__(self) -> str: ) def verify(self) -> None: - """Raise a |RuntimeError| if the configuration is still unknown.""" + """Raise a |RuntimeError| if no configuration has been defined so far.""" if self._config is None: raise RuntimeError( - f"For parameter {objecttools.elementphrase(self)}, it is still unknown " - f"whether the variability check is enabled." + f"For parameter {objecttools.elementphrase(self)}, no configuration " + f"has been defined so far. Please pass either `active=False` or " + f"`active=True` together with the required keyword arguments." ) @property @@ -549,21 +555,21 @@ def enabled(self) -> bool: @property def maxrelsumdelta(self) -> float: - """The threshold for the relative sum of the absolute changes of the - simulated values (zero if the check is disabled).""" + """The threshold for the sum of the absolute changes of the simulated values + per time step divided by their mean within the |EvaluationWindow|, which + decides whether the forecast is shifted to the observed value at the time of + forecast or to the mean of the averaging window.""" return self._get_config()[1] @property def averagingwindow(self) -> int: - """The length of the averaging period under stationary conditions in log - entries (zero if the check is disabled).""" + """The length of the averaging period (number of log entries) for + determining the mean-value-based residual under low variability conditions.""" return self._get_config()[2] class ReductionSteps(parametertools.Parameter): - """Number of timesteps for linearly reducing the ARIMA correction to zero once - the stationarity check (see |StationarityCheck|) detects instationary - conditions [-].""" + """Number of timesteps for linearly reducing the ARIMA correction to zero.""" NDIM: Final[Literal[0]] = 0 TYPE: Final = int @@ -571,13 +577,7 @@ class ReductionSteps(parametertools.Parameter): class MaxAbsShift(parametertools.Parameter): - """The maximum absolute shift applied when the current simulated value is not - positive or not below |ResidualAnchor| (the simulated value at the time the - residual was determined, see |Calc_CorrectedValue_V1|) [unit of the corrected - variable]. - - This includes the `historical` mode whenever the current observation is - available, as |ResidualAnchor| then equals the current simulated value.""" + """The maximum absolute shift applied.""" NDIM: Final[Literal[0]] = 0 TYPE: Final = float @@ -585,12 +585,11 @@ class MaxAbsShift(parametertools.Parameter): class MaxRelShift(parametertools.Parameter): - """The maximum relative shift applied when the current simulated value is - positive and below |ResidualAnchor| (the simulated value at the time the residual - was determined, see |Calc_CorrectedValue_V1|) [-]. + """The maximum relative shift applied. - |MaxRelShift| is a fraction, not a percentage. For example, a value of - ``0.1`` restricts the multiplicative correction to ±10 %.""" + |MaxRelShift| is a fraction, not a percentage as in LARSIM (compare + https://larsim.info/larsimhilfe/html/LARSIM-Einzelparameter/LARSIM_Einzelparameter_065_MAX-ARIMA-NQ_[proz].htm) + """ NDIM: Final[Literal[0]] = 0 TYPE: Final = float @@ -600,9 +599,12 @@ class MaxRelShift(parametertools.Parameter): class AveragingWindow(parametertools.Parameter): """The length (in log entries) of the averaging period immediately preceding the current forecast run, used to determine the mean-value-based - ARIMA residual (see |Calc_AveragedResidual_V1|) [-]. Set to zero to + ARIMA residual [-]. + + Set to zero to disable mean-value-based correction and rely on the single most recent - (pointwise) residual only.""" + (pointwise) residual only. + """ NDIM: Final[Literal[0]] = 0 TYPE: Final = int @@ -610,10 +612,10 @@ class AveragingWindow(parametertools.Parameter): class TransitionSteps(parametertools.Parameter): - """The number of forecast steps over which the applied residual - transitions linearly from the single most recent (pointwise) residual to - the mean-value-based residual determined via |AveragingWindow|, - avoiding an abrupt jump right at the start of the forecast horizon [-].""" + """The number of forecast steps over which the applied residual transitions + linearly from the single most recent (pointwise) residual to the mean-value-based + residual determined via |AveragingWindow|, avoiding an abrupt jump right at the + start of the forecast horizon [-].""" NDIM: Final[Literal[0]] = 0 TYPE: Final = int @@ -623,7 +625,7 @@ class TransitionSteps(parametertools.Parameter): class Propagate(parametertools.Parameter): """Flag determining whether the corrected discharge is passed on to the downstream network (|True|) or calculated only for local output at the - current gauge, while the uncorrected inflow is passed on instead + current gauge, while the original discharge is passed on instead (|False|) [-].""" NDIM: Final[Literal[0]] = 0 diff --git a/hydpy/models/statcorr/statcorr_derived.py b/hydpy/models/statcorr/statcorr_derived.py index 7e67e913ce..fa8568c3d9 100644 --- a/hydpy/models/statcorr/statcorr_derived.py +++ b/hydpy/models/statcorr/statcorr_derived.py @@ -36,18 +36,13 @@ class NmbLogEntries(parametertools.NmbParameter): ) def update(self) -> None: - """Calculate the number of required log entries from the submodel's other - parameters and adjust the shape of all log sequences. + """Calculate the number of required log entries and adjust the shape of + all log sequences. - The log must cover the |EvaluationWindow|, the assessment period of the - stationarity check (see |StationarityCheck|), and the current entry plus the - |MaxNaNSkip| preceding ones. The mean-value-based residual (see - |Calc_AveragedResidual_V1|) relies on the |AveragingWindow| (or the averaging - period of the variability check, see |VariabilityCheck|) entries preceding - the current one, which requires one additional entry. + The log must be as long as the largest value that uses it. - As long as not all relevant control parameters are defined, - |NmbLogEntries.update| leaves the current value untouched: + |NmbLogEntries.update| raises an error if any relevant control parameter is + still undefined: >>> from hydpy.models.statcorr import * >>> parameterstep() @@ -56,27 +51,46 @@ def update(self) -> None: >>> variabilitycheck(active=False) >>> maxnanskip(1) >>> derived.nmblogentries.update() - >>> derived.nmblogentries - nmblogentries(?) + Traceback (most recent call last): + ... + hydpy.core.exceptiontools.AttributeNotReady: For variable `averagingwindow`, \ +no value has been defined so far. + + Here, the window of the stationarity check is the largest value: >>> averagingwindow(1) >>> derived.nmblogentries.update() >>> derived.nmblogentries nmblogentries(4) + Here, the averaging window of the variability check (plus one) is the + largest value: + >>> stationaritycheck(active=False) >>> variabilitycheck(active=True, maxrelsumdelta=0.2, averagingwindow=5) >>> derived.nmblogentries.update() >>> derived.nmblogentries nmblogentries(6) + Here, |MaxNaNSkip| (plus one) is the largest value: + >>> variabilitycheck(active=False) >>> maxnanskip(6) >>> derived.nmblogentries.update() >>> derived.nmblogentries nmblogentries(7) + Here, |EvaluationWindow| is the largest value: + >>> maxnanskip(0) + >>> evaluationwindow(5) + >>> derived.nmblogentries.update() + >>> derived.nmblogentries + nmblogentries(5) + + Here, |AveragingWindow| (plus one) is the largest value: + + >>> evaluationwindow(3) >>> averagingwindow(3) >>> derived.nmblogentries.update() >>> derived.nmblogentries @@ -88,8 +102,8 @@ def update(self) -> None: data: >>> logs - loggedobservedvalue(nan, nan, nan, nan) - loggedsimulatedvalue(nan, nan, nan, nan) + loggedobservation(nan, nan, nan, nan) + loggedsimulation(nan, nan, nan, nan) >>> states reductionfactor(1.0) stationary(1.0) @@ -104,28 +118,20 @@ def update(self) -> None: To prevent losing information, it leaves the log and state sequences untouched as long as the number of log entries does not change: - >>> logs.loggedobservedvalue = 1.0 + >>> logs.loggedobservation = 1.0 >>> states.residual(2.0) >>> evaluationwindow(2) >>> derived.nmblogentries.update() >>> derived.nmblogentries nmblogentries(4) - >>> logs.loggedobservedvalue - loggedobservedvalue(1.0, 1.0, 1.0, 1.0) + >>> logs.loggedobservation + loggedobservation(1.0, 1.0, 1.0, 1.0) >>> states.residual residual(2.0) """ control = self.subpars.pars.control stationaritycheck = control.stationaritycheck variabilitycheck = control.variabilitycheck - if not ( - stationaritycheck.configured - and variabilitycheck.configured - and exceptiontools.attrready(control.evaluationwindow, "value") - and exceptiontools.attrready(control.maxnanskip, "value") - and exceptiontools.attrready(control.averagingwindow, "value") - ): - return nmb = max( control.evaluationwindow.value, stationaritycheck.window, @@ -157,14 +163,8 @@ class StationarityWindow(parametertools.Parameter): def update(self) -> None: """Take the assessment period from parameter |StationarityCheck|. - As long as |StationarityCheck| is not configured, - |StationarityWindow.update| leaves the current value untouched: - >>> from hydpy.models.statcorr import * >>> parameterstep() - >>> derived.stationaritywindow.update() - >>> derived.stationaritywindow - stationaritywindow(?) >>> stationaritycheck(active=True, window=4, ratiominmax=0.5) >>> derived.stationaritywindow.update() @@ -177,8 +177,7 @@ def update(self) -> None: stationaritywindow(0) """ stationaritycheck = self.subpars.pars.control.stationaritycheck - if stationaritycheck.configured: - self(stationaritycheck.window) + self(stationaritycheck.window) class RatioMinMax(parametertools.Parameter): @@ -193,14 +192,8 @@ class RatioMinMax(parametertools.Parameter): def update(self) -> None: """Take the threshold ratio from parameter |StationarityCheck|. - As long as |StationarityCheck| is not configured, |RatioMinMax.update| leaves - the current value untouched: - >>> from hydpy.models.statcorr import * >>> parameterstep() - >>> derived.ratiominmax.update() - >>> derived.ratiominmax - ratiominmax(?) >>> stationaritycheck(active=True, window=4, ratiominmax=0.5) >>> derived.ratiominmax.update() @@ -213,8 +206,7 @@ def update(self) -> None: ratiominmax(0.0) """ stationaritycheck = self.subpars.pars.control.stationaritycheck - if stationaritycheck.configured: - self(stationaritycheck.ratiominmax) + self(stationaritycheck.ratiominmax) class MaxRelSumDelta(parametertools.Parameter): @@ -230,14 +222,8 @@ class MaxRelSumDelta(parametertools.Parameter): def update(self) -> None: """Take the threshold from parameter |VariabilityCheck|. - As long as |VariabilityCheck| is not configured, |MaxRelSumDelta.update| - leaves the current value untouched: - >>> from hydpy.models.statcorr import * >>> parameterstep() - >>> derived.maxrelsumdelta.update() - >>> derived.maxrelsumdelta - maxrelsumdelta(?) >>> variabilitycheck(active=True, maxrelsumdelta=0.2, averagingwindow=24) >>> derived.maxrelsumdelta.update() @@ -250,8 +236,7 @@ def update(self) -> None: maxrelsumdelta(0.0) """ variabilitycheck = self.subpars.pars.control.variabilitycheck - if variabilitycheck.configured: - self(variabilitycheck.maxrelsumdelta) + self(variabilitycheck.maxrelsumdelta) class StationaryAveragingWindow(parametertools.Parameter): @@ -267,14 +252,8 @@ class StationaryAveragingWindow(parametertools.Parameter): def update(self) -> None: """Take the averaging period from parameter |VariabilityCheck|. - As long as |VariabilityCheck| is not configured, - |StationaryAveragingWindow.update| leaves the current value untouched: - >>> from hydpy.models.statcorr import * >>> parameterstep() - >>> derived.stationaryaveragingwindow.update() - >>> derived.stationaryaveragingwindow - stationaryaveragingwindow(?) >>> variabilitycheck(active=True, maxrelsumdelta=0.2, averagingwindow=24) >>> derived.stationaryaveragingwindow.update() @@ -287,5 +266,4 @@ def update(self) -> None: stationaryaveragingwindow(0) """ variabilitycheck = self.subpars.pars.control.variabilitycheck - if variabilitycheck.configured: - self(variabilitycheck.averagingwindow) + self(variabilitycheck.averagingwindow) diff --git a/hydpy/models/statcorr/statcorr_fluxes.py b/hydpy/models/statcorr/statcorr_fluxes.py index 6d1b19024e..fb49983ef3 100644 --- a/hydpy/models/statcorr/statcorr_fluxes.py +++ b/hydpy/models/statcorr/statcorr_fluxes.py @@ -4,8 +4,8 @@ from hydpy.core.typingtools import * -class Inflow(sequencetools.FluxSequence): - """Inflow [m³/s].""" +class OriginalQ(sequencetools.FluxSequence): + """Original (uncorrected) discharge [m³/s].""" NDIM: Final[Literal[0]] = 0 @@ -24,7 +24,7 @@ class CorrectedValue(sequencetools.FluxSequence): class IsActive(sequencetools.FluxSequence): """Flag (1.0: yes, 0.0: no) telling whether the submodel corrected the simulated - value in the current simulation step (see |Calc_IsActive_V1|) [-].""" + value in the current simulation step [-].""" NDIM: Final[Literal[0]] = 0 SPAN = (0.0, 1.0) diff --git a/hydpy/models/statcorr/statcorr_logs.py b/hydpy/models/statcorr/statcorr_logs.py index 3b7b813a34..8921337c8b 100644 --- a/hydpy/models/statcorr/statcorr_logs.py +++ b/hydpy/models/statcorr/statcorr_logs.py @@ -5,17 +5,13 @@ from hydpy.models.statcorr import statcorr_variables -class LoggedObservedValue( - statcorr_variables.MixinLogEntries, sequencetools.LogSequence -): +class LoggedObservation(statcorr_variables.MixinLogEntries, sequencetools.LogSequence): """Logged observed values [unit of the corrected variable].""" NDIM: Final[Literal[1]] = 1 -class LoggedSimulatedValue( - statcorr_variables.MixinLogEntries, sequencetools.LogSequence -): +class LoggedSimulation(statcorr_variables.MixinLogEntries, sequencetools.LogSequence): """Logged simulated values [unit of the corrected variable].""" NDIM: Final[Literal[1]] = 1 diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index f1edb66608..5093a55e9f 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -14,11 +14,11 @@ from hydpy.models.statcorr import statcorr_derived -class Pick_Inflow_V1(modeltools.Method): - r"""Sum up the current inflow from all inlet nodes. +class Pick_OriginalQ_V1(modeltools.Method): + r"""Sum up the original discharge from all inlet nodes. Basic equation: - :math:`Inflow = \sum Q` + :math:`OriginalQ = \sum Q` Example: @@ -26,22 +26,22 @@ class Pick_Inflow_V1(modeltools.Method): >>> parameterstep() >>> inlets.q.shape = 2 >>> inlets.q = 2.0, 4.0 - >>> model.pick_inflow_v1() - >>> fluxes.inflow - inflow(6.0) + >>> model.pick_originalq_v1() + >>> fluxes.originalq + originalq(6.0) """ REQUIREDSEQUENCES = (statcorr_inlets.Q,) - RESULTSEQUENCES = (statcorr_fluxes.Inflow,) + RESULTSEQUENCES = (statcorr_fluxes.OriginalQ,) @staticmethod def __call__(model: modeltools.Model, /) -> None: inl = model.sequences.inlets.fastaccess flu = model.sequences.fluxes.fastaccess - flu.inflow = 0.0 + flu.originalq = 0.0 for idx in range(inl.len_q): - flu.inflow += inl.q[idx] + flu.originalq += inl.q[idx] class Calc_OutputCorr_OutputCorrModel_V1(modeltools.Method): @@ -52,7 +52,7 @@ class Calc_OutputCorr_OutputCorrModel_V1(modeltools.Method): """ SUBMODELINTERFACES = (statcorrinterfaces.OutputCorrModel_V1,) - REQUIREDSEQUENCES = (statcorr_fluxes.Inflow, statcorr_inputs.Discharge) + REQUIREDSEQUENCES = (statcorr_fluxes.OriginalQ, statcorr_inputs.Discharge) RESULTSEQUENCES = (statcorr_fluxes.CorrectedQ,) @staticmethod @@ -61,7 +61,7 @@ def __call__( ) -> None: flu = model.sequences.fluxes.fastaccess inp = model.sequences.inputs.fastaccess - submodel.set_simulatedvalue(flu.inflow) + submodel.set_simulatedvalue(flu.originalq) if model.runsettings.simulationmode == modelutils.FORECAST: submodel.set_observedvalue(modelutils.nan) else: @@ -77,43 +77,44 @@ class Calc_OutputCorr_V1(modeltools.Method): This method orchestrates one or more submodels of identical interface type: - 1. The current simulated discharge (|Inflow|) and observed discharge - (|Discharge|) are passed to each attached |OutputCorrModel_V1| submodel - via |OutputCorrModel_V1.set_simulatedvalue| and - |OutputCorrModel_V1.set_observedvalue|. While |Options.simulationmode| - equals `forecast`, |Calc_OutputCorr_V1| passes |numpy.nan| instead of the - actual value of |Discharge|, regardless of whether an observation is - available. This relies on the assumption that a previous `historical` - simulation run already logged all relevant past observations and - simulations (read in as conditions). - 2. Each submodel computes its corrected discharge via - |OutputCorrModel_V1.determine_outputcorrection|. - 3. Each submodel decides for itself, based on its own |Active| flag, its - |CorrectionMode|, and its |LowerLimit| and |UpperLimit| parameters, - whether it is responsible for the current discharge (see - |OutputCorrModel_V1.is_active|). The corrected output of the *last* - responsible submodel is taken as |CorrectedQ|. When no submodel is - attached or responsible, |CorrectedQ| equals |Inflow|. Hence, attaching - several submodels configured for mutually exclusive discharge ranges lets - only the one responsible for the current discharge take effect. + 1. The current simulated discharge (|OriginalQ|) and observed discharge + (|Discharge|) are passed to each attached |OutputCorrModel_V1| submodel + via |OutputCorrModel_V1.set_simulatedvalue| and + |OutputCorrModel_V1.set_observedvalue|. While |Options.simulationmode| + equals `forecast`, |Calc_OutputCorr_V1| passes |numpy.nan| instead of the + actual value of |Discharge|, regardless of whether an observation is + available. This relies on the assumption that a previous `historical` + simulation run already logged all relevant past observations and + simulations (read in as conditions). + 2. Each submodel computes its corrected discharge via + |OutputCorrModel_V1.determine_outputcorrection|. + 3. Each submodel decides for itself, based on its own |Active| flag, its + |CorrectionMode|, and its |LowerLimit| and |UpperLimit| parameters, + whether it is responsible for the current discharge (see + |OutputCorrModel_V1.is_active|). The corrected output of the *last* + responsible submodel is taken as |CorrectedQ|. When no submodel is + attached or responsible, |CorrectedQ| equals |OriginalQ|. Hence, attaching + several submodels configured for mutually exclusive discharge ranges lets + only the one responsible for the current discharge take effect. Examples: - Without any attached submodel, the corrected discharge equals the inflow: + Without any attached submodel, the corrected discharge equals the original + discharge: >>> from hydpy.models.statcorr_main import * >>> parameterstep() - >>> fluxes.inflow = 2.0 + >>> fluxes.originalq = 2.0 >>> inputs.discharge = 3.0 >>> model.calc_outputcorr_v1() >>> fluxes.correctedq correctedq(2.0) With a single attached |statcorr_arima010| submodel, the corrected - discharge is the inflow plus the most recent residual (here: - ``3.0 - 2.0 = 1.0``, applied to the new inflow ``2.5``). By default, we - make the submodel responsible for all discharges and disable the - stationarity check so that it never suppresses the correction: + discharge is the original discharge plus the most recent residual (here: + ``3.0 - 2.0 = 1.0``, applied to the new original discharge ``2.5``). By + default, we make the submodel responsible for all discharges and disable + the stationarity check so that it never suppresses the correction: >>> from numpy import inf >>> def configure(submodel, lowerlimit=0.0, upperlimit=inf): @@ -140,7 +141,7 @@ class Calc_OutputCorr_V1(modeltools.Method): >>> fluxes.correctedq correctedq(3.0) >>> from numpy import nan - >>> fluxes.inflow = 2.5 + >>> fluxes.originalq = 2.5 >>> inputs.discharge = nan >>> model.calc_outputcorr_v1() >>> fluxes.correctedq @@ -160,11 +161,11 @@ class Calc_OutputCorr_V1(modeltools.Method): ... ) as submodel: ... configure(submodel, lowerlimit=3.0) - For an inflow of 2.5 m³/s, only the first submodel is responsible. + For an original discharge of 2.5 m³/s, only the first submodel is responsible. Hence, its corrected output wins, although the second submodel comes - later and returns the uncorrected inflow: + later and returns the original discharge: - >>> fluxes.inflow = 2.5 + >>> fluxes.originalq = 2.5 >>> inputs.discharge = 4.0 >>> model.calc_outputcorr_v1() >>> fluxes.correctedq @@ -174,9 +175,9 @@ class Calc_OutputCorr_V1(modeltools.Method): >>> model.outputcorrmodels[1].sequences.fluxes.isactive isactive(0.0) - For an inflow of 3.5 m³/s, the second submodel takes over: + For an original discharge of 3.5 m³/s, the second submodel takes over: - >>> fluxes.inflow = 3.5 + >>> fluxes.originalq = 3.5 >>> inputs.discharge = 3.0 >>> model.calc_outputcorr_v1() >>> fluxes.correctedq @@ -186,7 +187,7 @@ class Calc_OutputCorr_V1(modeltools.Method): >>> model.outputcorrmodels[1].sequences.fluxes.isactive isactive(1.0) - If no submodel is responsible, |CorrectedQ| equals |Inflow|: + If no submodel is responsible, |CorrectedQ| equals |OriginalQ|: >>> model.outputcorrmodels[1].parameters.control.active(False) >>> model.calc_outputcorr_v1() @@ -212,12 +213,12 @@ class Calc_OutputCorr_V1(modeltools.Method): Two `historical` steps establish a residual of ``0.5``: - >>> fluxes.inflow = 1.0 + >>> fluxes.originalq = 1.0 >>> inputs.discharge = 1.5 >>> model.calc_outputcorr_v1() >>> fluxes.correctedq correctedq(1.5) - >>> fluxes.inflow = 2.0 + >>> fluxes.originalq = 2.0 >>> inputs.discharge = 2.5 >>> model.calc_outputcorr_v1() >>> fluxes.correctedq @@ -229,13 +230,13 @@ class Calc_OutputCorr_V1(modeltools.Method): >>> from hydpy import pub >>> with pub.options.simulationmode("forecast"): - ... fluxes.inflow = 3.0 + ... fluxes.originalq = 3.0 ... inputs.discharge = 999.0 ... model.calc_outputcorr_v1() >>> fluxes.correctedq correctedq(3.5) >>> with pub.options.simulationmode("forecast"): - ... fluxes.inflow = 4.0 + ... fluxes.originalq = 4.0 ... inputs.discharge = 999.0 ... model.calc_outputcorr_v1() >>> fluxes.correctedq @@ -248,13 +249,13 @@ class Calc_OutputCorr_V1(modeltools.Method): fade it out: >>> with pub.options.simulationmode("forecast"): - ... fluxes.inflow = 5.0 + ... fluxes.originalq = 5.0 ... inputs.discharge = 999.0 ... model.calc_outputcorr_v1() >>> fluxes.correctedq correctedq(5.5) >>> with pub.options.simulationmode("forecast"): - ... fluxes.inflow = 6.0 + ... fluxes.originalq = 6.0 ... inputs.discharge = 999.0 ... model.calc_outputcorr_v1() >>> fluxes.correctedq @@ -263,14 +264,16 @@ class Calc_OutputCorr_V1(modeltools.Method): SUBMODELINTERFACES = (statcorrinterfaces.OutputCorrModel_V1,) SUBMETHODS = (Calc_OutputCorr_OutputCorrModel_V1,) - REQUIREDSEQUENCES = (statcorr_fluxes.Inflow, statcorr_inputs.Discharge) + CONTROLPARAMETERS = (statcorr_control.NmbSubmodels,) + REQUIREDSEQUENCES = (statcorr_fluxes.OriginalQ, statcorr_inputs.Discharge) RESULTSEQUENCES = (statcorr_fluxes.CorrectedQ,) @staticmethod def __call__(model: modeltools.Model, /) -> None: flu = model.sequences.fluxes.fastaccess - flu.correctedq = flu.inflow - for i in range(model.outputcorrmodels.number): + con = model.parameters.control.fastaccess + flu.correctedq = flu.originalq + for i in range(con.nmbsubmodels): if model.outputcorrmodels.typeids[i] == 1: model.calc_outputcorr_outputcorrmodel_v1( cast( @@ -282,19 +285,19 @@ def __call__(model: modeltools.Model, /) -> None: class Pass_CorrectedQ_V1(modeltools.Method): """Pass the corrected discharge on to the outlet link sequence, unless - |Propagate| is |False|, in which case the uncorrected inflow is + |Propagate| is |False|, in which case the original discharge is passed on instead. Either way, |CorrectedQ| remains available for local output at the current gauge. Basic equation: :math:`Q_{outlets} = CorrectedQ` (if |Propagate|) or - :math:`Q_{outlets} = Inflow` (otherwise) + :math:`Q_{outlets} = OriginalQ` (otherwise) Examples: >>> from hydpy.models.statcorr import * >>> parameterstep() - >>> fluxes.inflow = 1.0 + >>> fluxes.originalq = 1.0 >>> fluxes.correctedq = 2.0 >>> propagate(True) @@ -309,7 +312,7 @@ class Pass_CorrectedQ_V1(modeltools.Method): """ CONTROLPARAMETERS = (statcorr_control.Propagate,) - REQUIREDSEQUENCES = (statcorr_fluxes.Inflow, statcorr_fluxes.CorrectedQ) + REQUIREDSEQUENCES = (statcorr_fluxes.OriginalQ, statcorr_fluxes.CorrectedQ) RESULTSEQUENCES = (statcorr_outlets.Q,) @staticmethod @@ -317,7 +320,7 @@ def __call__(model: modeltools.Model, /) -> None: con = model.parameters.control.fastaccess flu = model.sequences.fluxes.fastaccess out = model.sequences.outlets.fastaccess - out.q = flu.correctedq if con.propagate else flu.inflow + out.q = flu.correctedq if con.propagate else flu.originalq class Set_SimulatedValue_V1(modeltools.Method): @@ -330,22 +333,22 @@ class Set_SimulatedValue_V1(modeltools.Method): >>> from hydpy.models.statcorr import * >>> parameterstep() >>> derived.nmblogentries(3) - >>> logs.loggedsimulatedvalue = 4.0, 3.0, 2.0 + >>> logs.loggedsimulation = 4.0, 3.0, 2.0 >>> model.set_simulatedvalue_v1(5.0) - >>> logs.loggedsimulatedvalue - loggedsimulatedvalue(5.0, 4.0, 3.0) + >>> logs.loggedsimulation + loggedsimulation(5.0, 4.0, 3.0) """ DERIVEDPARAMETERS = (statcorr_derived.NmbLogEntries,) - UPDATEDSEQUENCES = (statcorr_logs.LoggedSimulatedValue,) + UPDATEDSEQUENCES = (statcorr_logs.LoggedSimulation,) @staticmethod def __call__(model: modeltools.Model, simulatedvalue: float, /) -> None: der = model.parameters.derived.fastaccess log = model.sequences.logs.fastaccess for idx in range(der.nmblogentries - 1, 0, -1): - log.loggedsimulatedvalue[idx] = log.loggedsimulatedvalue[idx - 1] - log.loggedsimulatedvalue[0] = simulatedvalue + log.loggedsimulation[idx] = log.loggedsimulation[idx - 1] + log.loggedsimulation[0] = simulatedvalue class Set_ObservedValue_V1(modeltools.Method): @@ -360,32 +363,32 @@ class Set_ObservedValue_V1(modeltools.Method): >>> from hydpy.models.statcorr import * >>> parameterstep() >>> derived.nmblogentries(3) - >>> logs.loggedobservedvalue = 4.0, 3.0, 2.0 + >>> logs.loggedobservation = 4.0, 3.0, 2.0 >>> from numpy import nan >>> model.set_observedvalue_v1(nan) - >>> logs.loggedobservedvalue - loggedobservedvalue(nan, 4.0, 3.0) + >>> logs.loggedobservation + loggedobservation(nan, 4.0, 3.0) """ DERIVEDPARAMETERS = (statcorr_derived.NmbLogEntries,) - UPDATEDSEQUENCES = (statcorr_logs.LoggedObservedValue,) + UPDATEDSEQUENCES = (statcorr_logs.LoggedObservation,) @staticmethod def __call__(model: modeltools.Model, observedvalue: float, /) -> None: der = model.parameters.derived.fastaccess log = model.sequences.logs.fastaccess for idx in range(der.nmblogentries - 1, 0, -1): - log.loggedobservedvalue[idx] = log.loggedobservedvalue[idx - 1] - log.loggedobservedvalue[0] = observedvalue + log.loggedobservation[idx] = log.loggedobservation[idx - 1] + log.loggedobservation[0] = observedvalue class Calc_EvaluatedValue_V1(modeltools.Method): r"""Calculate the mean of the |EvaluationWindow| most recent - |LoggedSimulatedValue| values while |Options.simulationmode| is `historical`. + |LoggedSimulation| values while |Options.simulationmode| is `historical`. Basic equation: :math:`EvaluatedValue = \frac{1}{EvaluationWindow} - \sum_{i=0}^{EvaluationWindow-1} LoggedSimulatedValue_i` + \sum_{i=0}^{EvaluationWindow-1} LoggedSimulation_i` While |Options.simulationmode| is `forecast`, |Calc_EvaluatedValue_V1| keeps the value of the most recent `historical` assessment, so the responsible submodel @@ -402,7 +405,7 @@ class Calc_EvaluatedValue_V1(modeltools.Method): >>> from numpy import nan >>> control.evaluationwindow(3) >>> derived.nmblogentries(5) - >>> logs.loggedsimulatedvalue = 1.0, 2.0, 6.0, nan, nan + >>> logs.loggedsimulation = 1.0, 2.0, 6.0, nan, nan >>> from hydpy import pub >>> pub.options.simulationmode = "historical" >>> model.calc_evaluatedvalue_v1() @@ -412,7 +415,7 @@ class Calc_EvaluatedValue_V1(modeltools.Method): In `forecast` mode, |EvaluatedValue| stays frozen: >>> pub.options.simulationmode = "forecast" - >>> logs.loggedsimulatedvalue = 10.0, 10.0, 10.0, nan, nan + >>> logs.loggedsimulation = 10.0, 10.0, 10.0, nan, nan >>> model.calc_evaluatedvalue_v1() >>> states.evaluatedvalue evaluatedvalue(3.0) @@ -420,7 +423,7 @@ class Calc_EvaluatedValue_V1(modeltools.Method): """ CONTROLPARAMETERS = (statcorr_control.EvaluationWindow,) - REQUIREDSEQUENCES = (statcorr_logs.LoggedSimulatedValue,) + REQUIREDSEQUENCES = (statcorr_logs.LoggedSimulation,) UPDATEDSEQUENCES = (statcorr_states.EvaluatedValue,) @staticmethod @@ -431,7 +434,7 @@ def __call__(model: modeltools.Model, /) -> None: if model.runsettings.simulationmode == modelutils.HISTORICAL: sum_simulated: float = 0.0 for idx in range(con.evaluationwindow): - sum_simulated = sum_simulated + log.loggedsimulatedvalue[idx] + sum_simulated = sum_simulated + log.loggedsimulation[idx] sta.evaluatedvalue = sum_simulated / con.evaluationwindow @@ -551,9 +554,9 @@ class Calc_Residual_ResidualAnchor_V1(modeltools.Method): `historical`. Basic equations: - :math:`Residual = LoggedObservedValue_k - LoggedSimulatedValue_k` + :math:`Residual = LoggedObservation_k - LoggedSimulation_k` - :math:`ResidualAnchor = LoggedSimulatedValue_k` + :math:`ResidualAnchor = LoggedSimulation_k` :math:`k` denotes the most recent log index for which the observed value is not |numpy.nan|. The search skips at most |MaxNaNSkip| preceding log entries with @@ -578,8 +581,8 @@ class Calc_Residual_ResidualAnchor_V1(modeltools.Method): >>> derived.nmblogentries(3) >>> from hydpy import pub >>> pub.options.simulationmode = "historical" - >>> logs.loggedsimulatedvalue = 5.0, 3.0, 2.0 - >>> logs.loggedobservedvalue = 6.0, 4.0, 3.0 + >>> logs.loggedsimulation = 5.0, 3.0, 2.0 + >>> logs.loggedobservation = 6.0, 4.0, 3.0 >>> model.calc_residual_residualanchor_v1() >>> states.residual, states.residualanchor (residual(1.0), residualanchor(5.0)) @@ -587,7 +590,7 @@ class Calc_Residual_ResidualAnchor_V1(modeltools.Method): If the two most recent observations are missing, the residual stems from the third log entry: - >>> logs.loggedobservedvalue = nan, nan, 3.0 + >>> logs.loggedobservation = nan, nan, 3.0 >>> model.calc_residual_residualanchor_v1() >>> states.residual, states.residualanchor (residual(1.0), residualanchor(2.0)) @@ -610,7 +613,7 @@ class Calc_Residual_ResidualAnchor_V1(modeltools.Method): In `forecast` mode, both values stay frozen: >>> pub.options.simulationmode = "forecast" - >>> logs.loggedobservedvalue = nan, nan, nan + >>> logs.loggedobservation = nan, nan, nan >>> model.calc_residual_residualanchor_v1() >>> states.residual, states.residualanchor (residual(1.0), residualanchor(2.0)) @@ -620,8 +623,8 @@ class Calc_Residual_ResidualAnchor_V1(modeltools.Method): CONTROLPARAMETERS = (statcorr_control.MaxNaNSkip,) DERIVEDPARAMETERS = (statcorr_derived.NmbLogEntries,) REQUIREDSEQUENCES = ( - statcorr_logs.LoggedSimulatedValue, - statcorr_logs.LoggedObservedValue, + statcorr_logs.LoggedSimulation, + statcorr_logs.LoggedObservation, ) UPDATEDSEQUENCES = (statcorr_states.Residual, statcorr_states.ResidualAnchor) @@ -635,9 +638,9 @@ def __call__(model: modeltools.Model, /) -> None: sta.residual = 0.0 sta.residualanchor = 0.0 for idx in range(min(der.nmblogentries, con.maxnanskip + 1)): - if not modelutils.isnan(log.loggedobservedvalue[idx]): - sta.residualanchor = log.loggedsimulatedvalue[idx] - sta.residual = log.loggedobservedvalue[idx] - sta.residualanchor + if not modelutils.isnan(log.loggedobservation[idx]): + sta.residualanchor = log.loggedsimulation[idx] + sta.residual = log.loggedobservation[idx] - sta.residualanchor break @@ -647,7 +650,7 @@ class Calc_Stationary_V1(modeltools.Method): |Options.simulationmode| is `historical`. |Calc_Stationary_V1| takes the ratio of the minimum and the maximum - |LoggedObservedValue| value within the most recent |StationarityWindow| log + |LoggedObservation| value within the most recent |StationarityWindow| log entries. Whenever this ratio falls below |RatioMinMax|, it considers the conditions instationary (|Stationary| is ``0.0``), otherwise stationary (|Stationary| is ``1.0``). If a |numpy.nan| value within the @@ -658,7 +661,7 @@ class Calc_Stationary_V1(modeltools.Method): While |Options.simulationmode| is `forecast`, |Calc_Stationary_V1| keeps the outcome of the most recent `historical` assessment. Recomputing it would be - unreliable, as |LoggedObservedValue| keeps receiving |numpy.nan| values + unreliable, as |LoggedObservation| keeps receiving |numpy.nan| values throughout the forecast (see |Calc_OutputCorr_V1|), which would prevent any new assessment as soon as the first of them enters the |StationarityWindow|. @@ -675,14 +678,14 @@ class Calc_Stationary_V1(modeltools.Method): >>> derived.nmblogentries(3) >>> from hydpy import pub >>> pub.options.simulationmode = "historical" - >>> logs.loggedobservedvalue = 4.0, 5.0, 5.0 + >>> logs.loggedobservation = 4.0, 5.0, 5.0 >>> model.calc_stationary_v1() >>> states.stationary stationary(1.0) The ratio ``0.5 / 5.0 = 0.1`` is: - >>> logs.loggedobservedvalue = 0.5, 5.0, 5.0 + >>> logs.loggedobservation = 0.5, 5.0, 5.0 >>> model.calc_stationary_v1() >>> states.stationary stationary(0.0) @@ -690,7 +693,7 @@ class Calc_Stationary_V1(modeltools.Method): A single missing observation within the |StationarityWindow| prevents a new assessment: - >>> logs.loggedobservedvalue = 4.0, nan, 5.0 + >>> logs.loggedobservation = 4.0, nan, 5.0 >>> model.calc_stationary_v1() >>> states.stationary stationary(0.0) @@ -698,7 +701,7 @@ class Calc_Stationary_V1(modeltools.Method): In `forecast` mode, |Stationary| stays frozen: >>> pub.options.simulationmode = "forecast" - >>> logs.loggedobservedvalue = 4.0, 5.0, 5.0 + >>> logs.loggedobservation = 4.0, 5.0, 5.0 >>> model.calc_stationary_v1() >>> states.stationary stationary(0.0) @@ -718,7 +721,7 @@ class Calc_Stationary_V1(modeltools.Method): statcorr_derived.StationarityWindow, statcorr_derived.RatioMinMax, ) - REQUIREDSEQUENCES = (statcorr_logs.LoggedObservedValue,) + REQUIREDSEQUENCES = (statcorr_logs.LoggedObservation,) UPDATEDSEQUENCES = (statcorr_states.Stationary,) @staticmethod @@ -733,7 +736,7 @@ def __call__(model: modeltools.Model, /) -> None: qmin: float = modelutils.inf qmax: float = -modelutils.inf for idx in range(min(der.nmblogentries, der.stationaritywindow)): - value: float = log.loggedobservedvalue[idx] + value: float = log.loggedobservation[idx] if modelutils.isnan(value): has_nan = True break @@ -758,7 +761,7 @@ class Calc_ReductionFactor_V1(modeltools.Method): |StationarityCheck|), |ReductionFactor| is always ``1.0``. As |Stationary| does not change in `forecast` mode (see |Calc_Stationary_V1|), - |ReductionFactor| keeps ramping towards zero (or staying at ``0.0``) for the + |ReductionFactor| keeps decreasing towards zero (or stays at ``0.0``) for the entire forecast horizon once a `historical` run has flagged conditions as instationary. @@ -836,7 +839,7 @@ class Calc_RelSumDelta_V1(modeltools.Method): Basic equation: :math:`RelSumDelta = \frac{1}{EvaluatedValue} \sum_{i=0}^{EvaluationWindow-2} - |LoggedSimulatedValue_i - LoggedSimulatedValue_{i+1}|` + |LoggedSimulation_i - LoggedSimulation_{i+1}|` For a non-positive |EvaluatedValue|, |RelSumDelta| is |numpy.nan|. While |Options.simulationmode| is `forecast`, |Calc_RelSumDelta_V1| keeps the value of @@ -851,7 +854,7 @@ class Calc_RelSumDelta_V1(modeltools.Method): >>> derived.nmblogentries(3) >>> from hydpy import pub >>> pub.options.simulationmode = "historical" - >>> logs.loggedsimulatedvalue = 9.0, 10.0, 11.0 + >>> logs.loggedsimulation = 9.0, 10.0, 11.0 >>> states.evaluatedvalue(10.0) >>> model.calc_relsumdelta_v1() >>> states.relsumdelta @@ -880,10 +883,7 @@ class Calc_RelSumDelta_V1(modeltools.Method): CONTROLPARAMETERS = (statcorr_control.EvaluationWindow,) DERIVEDPARAMETERS = (statcorr_derived.StationaryAveragingWindow,) - REQUIREDSEQUENCES = ( - statcorr_logs.LoggedSimulatedValue, - statcorr_states.EvaluatedValue, - ) + REQUIREDSEQUENCES = (statcorr_logs.LoggedSimulation, statcorr_states.EvaluatedValue) UPDATEDSEQUENCES = (statcorr_states.RelSumDelta,) @staticmethod @@ -898,7 +898,7 @@ def __call__(model: modeltools.Model, /) -> None: sumdelta: float = 0.0 for idx in range(con.evaluationwindow - 1): sumdelta = sumdelta + modelutils.fabs( - log.loggedsimulatedvalue[idx] - log.loggedsimulatedvalue[idx + 1] + log.loggedsimulation[idx] - log.loggedsimulation[idx + 1] ) if sta.evaluatedvalue > 0.0: sta.relsumdelta = sumdelta / sta.evaluatedvalue @@ -1008,8 +1008,8 @@ class Calc_AveragedResidual_V1(modeltools.Method): r"""Determine the mean-value-based residual once, at the first forecast step, and freeze it for the remainder of the current forecast horizon. - |Calc_AveragedResidual_V1| averages the |LoggedObservedValue| and - |LoggedSimulatedValue| entries covering the |AveragingWindow| log positions + |Calc_AveragedResidual_V1| averages the |LoggedObservation| and + |LoggedSimulation| entries covering the |AveragingWindow| log positions immediately preceding the current forecast run (log position ``0`` already holds the current forecast step's own values, so averaging starts at position ``1``) and stores their difference in |AveragedResidual|. It leaves |AveragedResidual| @@ -1037,8 +1037,8 @@ class Calc_AveragedResidual_V1(modeltools.Method): >>> states.forecaststep(0.0) >>> states.lowvariability(0.0) >>> states.residual(-9.0) - >>> logs.loggedsimulatedvalue = 3.0, 2.0, 4.0 - >>> logs.loggedobservedvalue = nan, 3.0, 5.0 + >>> logs.loggedsimulation = 3.0, 2.0, 4.0 + >>> logs.loggedobservation = nan, 3.0, 5.0 >>> model.calc_averagedresidual_v1() >>> states.averagedresidual averagedresidual(1.0) @@ -1046,8 +1046,8 @@ class Calc_AveragedResidual_V1(modeltools.Method): On any later forecast step and in `historical` mode, the previously determined value remains unchanged, regardless of the current log contents: - >>> logs.loggedsimulatedvalue = 3.0, 20.0, 40.0 - >>> logs.loggedobservedvalue = nan, 30.0, 50.0 + >>> logs.loggedsimulation = 3.0, 20.0, 40.0 + >>> logs.loggedobservation = nan, 30.0, 50.0 >>> states.forecaststep(1.0) >>> model.calc_averagedresidual_v1() >>> states.averagedresidual @@ -1071,7 +1071,7 @@ class Calc_AveragedResidual_V1(modeltools.Method): |Calc_AveragedResidual_V1| fall back to |Residual|: >>> control.averagingwindow(2) - >>> logs.loggedobservedvalue = nan, nan, 50.0 + >>> logs.loggedobservation = nan, nan, 50.0 >>> model.calc_averagedresidual_v1() >>> states.averagedresidual averagedresidual(-9.0) @@ -1083,7 +1083,7 @@ class Calc_AveragedResidual_V1(modeltools.Method): >>> control.averagingwindow(0) >>> states.lowvariability(1.0) - >>> logs.loggedobservedvalue = nan, 30.0, nan + >>> logs.loggedobservation = nan, 30.0, nan >>> model.calc_averagedresidual_v1() >>> states.averagedresidual averagedresidual(10.0) @@ -1096,8 +1096,8 @@ class Calc_AveragedResidual_V1(modeltools.Method): statcorr_derived.StationaryAveragingWindow, ) REQUIREDSEQUENCES = ( - statcorr_logs.LoggedSimulatedValue, - statcorr_logs.LoggedObservedValue, + statcorr_logs.LoggedSimulation, + statcorr_logs.LoggedObservation, statcorr_states.LowVariability, statcorr_states.ForecastStep, statcorr_states.Residual, @@ -1123,8 +1123,8 @@ def __call__(model: modeltools.Model, /) -> None: sum_sim: float = 0.0 has_nan = False for idx in range(1, nmb + 1): - obs_value: float = log.loggedobservedvalue[idx] - sim_value: float = log.loggedsimulatedvalue[idx] + obs_value: float = log.loggedobservation[idx] + sim_value: float = log.loggedsimulation[idx] if modelutils.isnan(obs_value) or modelutils.isnan(sim_value): has_nan = True break @@ -1146,25 +1146,25 @@ class Calc_CorrectedValue_V1(modeltools.Method): (:math:`sim_k`, the simulated value at the time the residual was determined), with :math:`f_{red}` denoting |ReductionFactor|: - * If :math:`0 < sim_0 < sim_k`, |Calc_CorrectedValue_V1| shifts :math:`sim_0` - *multiplicatively*, expressing the damped residual as a fraction of - :math:`sim_k` and capping that fraction at |MaxRelShift|: + * If :math:`0 < sim_0 < sim_k`, |Calc_CorrectedValue_V1| shifts :math:`sim_0` + *multiplicatively*, expressing the damped residual as a fraction of + :math:`sim_k` and capping that fraction at |MaxRelShift|: - :math:`CorrectedValue = sim_0 \cdot \left(1 + \mathrm{clip}\left(r \cdot f_{red} - / sim_k,\ \pm MaxRelShift\right) \right)` + :math:`CorrectedValue = sim_0 \cdot \left(1 + \mathrm{clip}\left(r \cdot + f_{red} / sim_k,\ \pm MaxRelShift\right) \right)` - Applying the residual as a fraction rather than a constant offset keeps the - correction from overshooting or turning negative while the simulated values - recede towards zero. + Applying the residual as a fraction rather than a constant offset keeps the + correction from overshooting or turning negative while the simulated values + recede towards zero. - * Otherwise (:math:`sim_0 \geq sim_k` or :math:`sim_0 \leq 0`), it shifts - :math:`sim_0` *additively*, capping the damped residual at |MaxAbsShift|: + * Otherwise (:math:`sim_0 \geq sim_k` or :math:`sim_0 \leq 0`), it shifts + :math:`sim_0` *additively*, capping the damped residual at |MaxAbsShift|: - :math:`CorrectedValue = sim_0 + \mathrm{clip}\left(r \cdot f_{red},\ - \pm MaxAbsShift\right)` + :math:`CorrectedValue = sim_0 + \mathrm{clip}\left(r \cdot f_{red},\ + \pm MaxAbsShift\right)` - This includes the `historical` mode whenever the current observation is - available, as :math:`sim_k` then equals :math:`sim_0`. + This includes the `historical` mode whenever the current observation is + available, as :math:`sim_k` then equals :math:`sim_0`. In `historical` mode (see |Options.simulationmode|), :math:`r` is the pointwise |Residual|. In `forecast` mode, setting |AveragingWindow| to a value greater @@ -1201,7 +1201,7 @@ class Calc_CorrectedValue_V1(modeltools.Method): >>> states.averagedresidual(0.0) >>> states.residual(1.0) >>> states.residualanchor(5.0) - >>> logs.loggedsimulatedvalue = 6.0 + >>> logs.loggedsimulation = 6.0 >>> model.calc_correctedvalue_v1() >>> fluxes.correctedvalue correctedvalue(6.0) @@ -1235,7 +1235,7 @@ class Calc_CorrectedValue_V1(modeltools.Method): >>> control.maxabsshift(100.0) >>> states.residual(2.0) >>> states.residualanchor(10.0) - >>> logs.loggedsimulatedvalue = 2.0 + >>> logs.loggedsimulation = 2.0 >>> model.calc_correctedvalue_v1() >>> fluxes.correctedvalue correctedvalue(2.4) @@ -1253,14 +1253,14 @@ class Calc_CorrectedValue_V1(modeltools.Method): additively, so |MaxRelShift| has no effect: >>> control.maxrelshift(0.0) - >>> logs.loggedsimulatedvalue = 10.0 + >>> logs.loggedsimulation = 10.0 >>> model.calc_correctedvalue_v1() >>> fluxes.correctedvalue correctedvalue(12.0) The same holds for a non-positive current simulated value: - >>> logs.loggedsimulatedvalue = 0.0 + >>> logs.loggedsimulation = 0.0 >>> model.calc_correctedvalue_v1() >>> fluxes.correctedvalue correctedvalue(2.0) @@ -1277,7 +1277,7 @@ class Calc_CorrectedValue_V1(modeltools.Method): >>> states.residual(1.0) >>> states.residualanchor(8.0) >>> states.averagedresidual(2.5) - >>> logs.loggedsimulatedvalue = 10.0 + >>> logs.loggedsimulation = 10.0 >>> model.calc_correctedvalue_v1() >>> fluxes.correctedvalue correctedvalue(11.0) @@ -1286,7 +1286,7 @@ class Calc_CorrectedValue_V1(modeltools.Method): (``1.75``): >>> states.forecaststep(1.0) - >>> logs.loggedsimulatedvalue = 11.0 + >>> logs.loggedsimulation = 11.0 >>> model.calc_correctedvalue_v1() >>> fluxes.correctedvalue correctedvalue(12.75) @@ -1295,7 +1295,7 @@ class Calc_CorrectedValue_V1(modeltools.Method): applies: >>> states.forecaststep(2.0) - >>> logs.loggedsimulatedvalue = 12.0 + >>> logs.loggedsimulation = 12.0 >>> model.calc_correctedvalue_v1() >>> fluxes.correctedvalue correctedvalue(14.5) @@ -1336,7 +1336,7 @@ class Calc_CorrectedValue_V1(modeltools.Method): ) REQUIREDSEQUENCES = ( statcorr_fluxes.IsActive, - statcorr_logs.LoggedSimulatedValue, + statcorr_logs.LoggedSimulation, statcorr_states.ReductionFactor, statcorr_states.LowVariability, statcorr_states.ForecastStep, @@ -1352,7 +1352,7 @@ def __call__(model: modeltools.Model, /) -> None: flu = model.sequences.fluxes.fastaccess log = model.sequences.logs.fastaccess sta = model.sequences.states.fastaccess - sim: float = log.loggedsimulatedvalue[0] + sim: float = log.loggedsimulation[0] if flu.isactive == 0.0: flu.correctedvalue = sim else: @@ -1424,18 +1424,18 @@ class Determine_OutputCorrection_V1(modeltools.AutoMethod): the current simulation mode directly from |Options.simulationmode| (via |Model.runsettings|): - * |Calc_EvaluatedValue_V1| and |Calc_IsActive_V1| decide whether the submodel - is responsible for the current simulated value. - * |Calc_Residual_ResidualAnchor_V1| determines the most recent pointwise - residual. - * |Calc_Stationary_V1| and |Calc_ReductionFactor_V1| dampen the correction under - instationary conditions. - * |Calc_RelSumDelta_V1|, |Calc_LowVariability_V1|, and - |Calc_AveragedResidual_V1| determine the mean-value-based residual for - forecast runs. - * |Calc_CorrectedValue_V1| applies the resulting residual to the current simulated - value. - * |Update_ForecastStep_V1| counts the forecast steps. + * |Calc_EvaluatedValue_V1| and |Calc_IsActive_V1| decide whether the submodel + is responsible for the current simulated value. + * |Calc_Residual_ResidualAnchor_V1| determines the most recent pointwise + residual. + * |Calc_Stationary_V1| and |Calc_ReductionFactor_V1| dampen the correction under + instationary conditions. + * |Calc_RelSumDelta_V1|, |Calc_LowVariability_V1|, and + |Calc_AveragedResidual_V1| determine the mean-value-based residual for + forecast runs. + * |Calc_CorrectedValue_V1| applies the resulting residual to the current simulated + value. + * |Update_ForecastStep_V1| counts the forecast steps. All submethods update the internal states even when the submodel is not responsible, so that a submodel taking over responsibility starts with @@ -1471,8 +1471,8 @@ class Determine_OutputCorrection_V1(modeltools.AutoMethod): >>> control.maxrelshift(10.0) >>> control.averagingwindow(0) >>> control.transitionsteps(0) - >>> logs.loggedsimulatedvalue = 5.0, 3.0, 2.0 - >>> logs.loggedobservedvalue = 6.0, 4.0, 3.0 + >>> logs.loggedsimulation = 5.0, 3.0, 2.0 + >>> logs.loggedobservation = 6.0, 4.0, 3.0 >>> model.determine_outputcorrection_v1() >>> fluxes.isactive isactive(1.0) @@ -1481,8 +1481,8 @@ class Determine_OutputCorrection_V1(modeltools.AutoMethod): In `forecast` mode, the residual of the last `historical` step persists: - >>> logs.loggedsimulatedvalue = 7.0, 5.0, 3.0 - >>> logs.loggedobservedvalue = nan, 6.0, 4.0 + >>> logs.loggedsimulation = 7.0, 5.0, 3.0 + >>> logs.loggedobservation = nan, 6.0, 4.0 >>> from hydpy import pub >>> with pub.options.simulationmode("forecast"): ... model.determine_outputcorrection_v1() @@ -1525,8 +1525,8 @@ class Determine_OutputCorrection_V1(modeltools.AutoMethod): statcorr_derived.StationaryAveragingWindow, ) REQUIREDSEQUENCES = ( - statcorr_logs.LoggedSimulatedValue, - statcorr_logs.LoggedObservedValue, + statcorr_logs.LoggedSimulation, + statcorr_logs.LoggedObservation, ) UPDATEDSEQUENCES = ( statcorr_states.EvaluatedValue, @@ -1591,7 +1591,7 @@ class Model(modeltools.AdHocModel): DOCNAME = modeltools.DocName(short="StatCorr") __HYDPY_ROOTMODEL__ = None - INLET_METHODS = (Pick_Inflow_V1,) + INLET_METHODS = (Pick_OriginalQ_V1,) OBSERVER_METHODS = () RECEIVER_METHODS = () RUN_METHODS = (Calc_OutputCorr_V1,) @@ -1629,7 +1629,9 @@ class Main_OutputCorrModel_V1(modeltools.AdHocModel): """Base class for |statcorr.DOCNAME.long| models that use submodels that comply with the |OutputCorrModel_V1| interface.""" - outputcorrmodels: modeltools.SubmodelsProperty + outputcorrmodels: modeltools.SubmodelsProperty[ + statcorrinterfaces.OutputCorrModel_V1 + ] @importtools.prepare_submodel( # type: ignore[call-overload, untyped-decorator] "outputcorrmodels", statcorrinterfaces.OutputCorrModel_V1, dimensionality=1 @@ -1660,8 +1662,8 @@ def add_outputcorrmodel_v1( ... averagingwindow(0) >>> model.outputcorrmodels[0].parameters.derived.nmblogentries nmblogentries(4) - >>> model.outputcorrmodels[0].sequences.logs.loggedsimulatedvalue - loggedsimulatedvalue(nan, nan, nan, nan) + >>> model.outputcorrmodels[0].sequences.logs.loggedsimulation + loggedsimulation(nan, nan, nan, nan) """ diff --git a/hydpy/models/statcorr/statcorr_states.py b/hydpy/models/statcorr/statcorr_states.py index 226640e186..8d475653d6 100644 --- a/hydpy/models/statcorr/statcorr_states.py +++ b/hydpy/models/statcorr/statcorr_states.py @@ -19,16 +19,7 @@ class ReductionFactor(sequencetools.StateSequence): class Stationary(sequencetools.StateSequence): """Flag (1.0: yes, 0.0: no) telling whether the observed values behaved in a stationary way at the last assessment (1.0: apply |ReductionFactor| unabated; - 0.0: reduce |ReductionFactor| linearly) [-]. - - |statcorr_arima010| only reassesses stationarity while |Options.simulationmode| - equals `historical`. While it equals `forecast`, |Stationary| keeps the value - determined at the most recent `historical` assessment, so |ReductionFactor| - keeps ramping towards zero (or stays at ``1.0``) throughout the whole forecast - horizon instead of jumping back to ``1.0`` once the logged observations run - out. Also in `historical` mode, a |numpy.nan| value within the - |StationarityWindow| prevents a new assessment, so |Stationary| keeps its - previous value.""" + 0.0: reduce |ReductionFactor| linearly) [-].""" NDIM: Final[Literal[0]] = 0 SPAN = (0.0, 1.0) @@ -38,16 +29,7 @@ class Stationary(sequencetools.StateSequence): class EvaluatedValue(sequencetools.StateSequence): """The mean of the simulated values over the |EvaluationWindow| most recent log entries, as determined at the last `historical` assessment [unit of the - corrected variable]. - - |Calc_IsActive_V1| compares |EvaluatedValue| with |LowerLimit| - and |UpperLimit| to decide whether the submodel is responsible for correcting - the simulated values. Like |Stationary|, |statcorr_arima010| only reassesses - |EvaluatedValue| while |Options.simulationmode| equals `historical`. - While it equals `forecast`, |EvaluatedValue| keeps the value determined - at the most recent `historical` assessment, so the responsible submodel does - not change throughout the whole forecast horizon, regardless of how the - forecasted values develop.""" + corrected variable].""" NDIM: Final[Literal[0]] = 0 INIT = numpy.nan @@ -56,23 +38,15 @@ class EvaluatedValue(sequencetools.StateSequence): class RelSumDelta(sequencetools.StateSequence): """The sum of the absolute changes of the simulated values within the |EvaluationWindow| divided by |EvaluatedValue|, as determined at the last - `historical` assessment [-]. - - Like |Stationary|, |statcorr_arima010| only reassesses |RelSumDelta| while - |Options.simulationmode| equals `historical`.""" + `historical` assessment [-].""" NDIM: Final[Literal[0]] = 0 INIT = numpy.nan class LowVariability(sequencetools.StateSequence): - """Flag (1.0: yes, 0.0: no) telling whether the variability check (see - |VariabilityCheck|) found stationary conditions at the last assessment, so that - the mean-value-based residual relies on the |StationaryAveragingWindow| instead - of the |AveragingWindow| [-]. - - Like |Stationary|, |statcorr_arima010| only reassesses |LowVariability| while - |Options.simulationmode| equals `historical`.""" + """Flag (1.0: yes, 0.0: no) telling whether the variability check found + low variability conditions at the last assessment [-].""" NDIM: Final[Literal[0]] = 0 SPAN = (0.0, 1.0) @@ -81,13 +55,7 @@ class LowVariability(sequencetools.StateSequence): class ForecastStep(sequencetools.StateSequence): """The number of elapsed forecast steps since the start of the current - forecast run (``0.0`` on the first forecast step), reset to ``0.0`` - whenever |Options.simulationmode| equals `historical` [-]. - - |Calc_CorrectedValue_V1| uses |ForecastStep| to linearly blend the - applied residual from the single most recent (pointwise) value towards - the mean-value-based residual determined via |AveragingWindow| - over |TransitionSteps| forecast steps.""" + forecast run [-].""" NDIM: Final[Literal[0]] = 0 SPAN = (0.0, None) @@ -95,29 +63,16 @@ class ForecastStep(sequencetools.StateSequence): class AveragedResidual(sequencetools.StateSequence): - """The mean-value-based ARIMA residual (mean observed minus mean simulated - values over the |AveragingWindow| log entries immediately - preceding the current forecast run), determined once at the first - forecast step and kept unchanged for the remainder of the forecast - horizon [unit of the corrected variable].""" + """The mean-value-based residual (mean observed minus mean simulated value) + [unit of the corrected variable].""" NDIM: Final[Literal[0]] = 0 INIT = 0.0 class Residual(sequencetools.StateSequence): - """The pointwise ARIMA residual (observed minus simulated values, taken - from the most recently logged entry with a non-|numpy.nan| observation, - skipping at most |MaxNaNSkip| entries with missing observations) - [unit of the corrected variable]. - - Like |Stationary|, |statcorr_arima010| only - reassesses |Residual| while |Options.simulationmode| equals `historical`. - While it equals `forecast`, |Residual| keeps the value determined at the - most recent `historical` assessment, so the applied correction persists - throughout the whole forecast horizon (subject only to - |ReductionFactor|) instead of vanishing as soon as the underlying log - entry drops out of the logging window.""" + """The pointwise residual (observed minus simulated value) [unit of the + corrected variable].""" NDIM: Final[Literal[0]] = 0 INIT = 0.0 @@ -125,10 +80,7 @@ class Residual(sequencetools.StateSequence): class ResidualAnchor(sequencetools.StateSequence): """The simulated value at the log position from which - |Residual| was determined [unit of the corrected variable]. - - Frozen together with |Residual| while |Options.simulationmode| equals - `forecast`; see |Residual| for details.""" + |Residual| was determined [unit of the corrected variable].""" NDIM: Final[Literal[0]] = 0 INIT = 0.0 diff --git a/hydpy/models/statcorr/statcorr_variables.py b/hydpy/models/statcorr/statcorr_variables.py index f92db4ce88..0d24258ff6 100644 --- a/hydpy/models/statcorr/statcorr_variables.py +++ b/hydpy/models/statcorr/statcorr_variables.py @@ -4,30 +4,30 @@ from hydpy.core import parametertools from hydpy.core import variabletools - +# from hydpy.models.statcorr import statcorr_derived actual import below class MixinLogEntries(variabletools.Variable, abc.ABC): """Mixin class for 1-dimensional log sequences whose shape depends on the value of parameter |NmbLogEntries|. - We take the log sequence |LoggedObservedValue| as an example: + We take the log sequence |LoggedObservation| as an example: >>> from hydpy.models.statcorr import * >>> parameterstep() >>> derived.nmblogentries(3) - >>> logs.loggedobservedvalue - loggedobservedvalue(nan, nan, nan) + >>> logs.loggedobservation + loggedobservation(nan, nan, nan) To prevent losing information, updating parameter |NmbLogEntries| resets the shape only when necessary: - >>> logs.loggedobservedvalue = 1.0 + >>> logs.loggedobservation = 1.0 >>> derived.nmblogentries(3) - >>> logs.loggedobservedvalue - loggedobservedvalue(1.0, 1.0, 1.0) + >>> logs.loggedobservation + loggedobservation(1.0, 1.0, 1.0) >>> derived.nmblogentries(2) - >>> logs.loggedobservedvalue - loggedobservedvalue(nan, nan) + >>> logs.loggedobservation + loggedobservation(nan, nan) """ def __hydpy__let_par_set_shape__(self, p: parametertools.NmbParameter, /) -> None: diff --git a/hydpy/models/statcorr_arima010.py b/hydpy/models/statcorr_arima010.py index 8a759260e9..7bdc081d00 100644 --- a/hydpy/models/statcorr_arima010.py +++ b/hydpy/models/statcorr_arima010.py @@ -73,10 +73,10 @@ >>> derived.nmblogentries.update() >>> derived.nmblogentries nmblogentries(3) - >>> logs.loggedsimulatedvalue - loggedsimulatedvalue(nan, nan, nan) - >>> logs.loggedobservedvalue - loggedobservedvalue(nan, nan, nan) + >>> logs.loggedsimulation + loggedsimulation(nan, nan, nan) + >>> logs.loggedobservation + loggedobservation(nan, nan, nan) Successive calls of |OutputCorrModel_V1.set_simulatedvalue| and |OutputCorrModel_V1.set_observedvalue| shift the previously buffered @@ -89,10 +89,10 @@ >>> model.set_simulatedvalue(5.0) >>> from numpy import nan >>> model.set_observedvalue(nan) - >>> logs.loggedsimulatedvalue - loggedsimulatedvalue(5.0, 3.0, 2.0) - >>> logs.loggedobservedvalue - loggedobservedvalue(nan, 4.0, 3.0) + >>> logs.loggedsimulation + loggedsimulation(5.0, 3.0, 2.0) + >>> logs.loggedobservation + loggedobservation(nan, 4.0, 3.0) |OutputCorrModel_V1.determine_outputcorrection| computes the corrected value from the most recent residual (here taken from log position 1, diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py index 61f926d307..59ef4db7b9 100644 --- a/hydpy/models/statcorr_main.py +++ b/hydpy/models/statcorr_main.py @@ -80,18 +80,18 @@ .. integration-test:: >>> test() - | date | discharge | inflow | correctedq | inlet | outlet | - ------------------------------------------------------------ - | 01/01 | 1.5 | 1.0 | 1.5 | 1.0 | 1.5 | - | 02/01 | 2.5 | 2.0 | 2.5 | 2.0 | 2.5 | - | 03/01 | nan | 3.0 | 3.5 | 3.0 | 3.5 | - | 04/01 | nan | 4.0 | 4.5 | 4.0 | 4.5 | - | 05/01 | nan | 5.0 | 5.0 | 5.0 | 5.0 | - | 06/01 | nan | 6.0 | 6.0 | 6.0 | 6.0 | - | 07/01 | nan | 7.0 | 7.0 | 7.0 | 7.0 | - | 08/01 | nan | 8.0 | 8.0 | 8.0 | 8.0 | - | 09/01 | nan | 9.0 | 9.0 | 9.0 | 9.0 | - | 10/01 | nan | 10.0 | 10.0 | 10.0 | 10.0 | + | date | discharge | originalq | correctedq | inlet | outlet | + --------------------------------------------------------------- + | 01/01 | 1.5 | 1.0 | 1.5 | 1.0 | 1.5 | + | 02/01 | 2.5 | 2.0 | 2.5 | 2.0 | 2.5 | + | 03/01 | nan | 3.0 | 3.5 | 3.0 | 3.5 | + | 04/01 | nan | 4.0 | 4.5 | 4.0 | 4.5 | + | 05/01 | nan | 5.0 | 5.0 | 5.0 | 5.0 | + | 06/01 | nan | 6.0 | 6.0 | 6.0 | 6.0 | + | 07/01 | nan | 7.0 | 7.0 | 7.0 | 7.0 | + | 08/01 | nan | 8.0 | 8.0 | 8.0 | 8.0 | + | 09/01 | nan | 9.0 | 9.0 | 9.0 | 9.0 | + | 10/01 | nan | 10.0 | 10.0 | 10.0 | 10.0 | Forecast simulation ___________________ @@ -134,18 +134,18 @@ .. integration-test:: >>> forecast_test("2000-01-06") - | date | discharge | inflow | correctedq | inlet | outlet | - ------------------------------------------------------------ - | 01/01 | 1.5 | 1.0 | 1.5 | 1.0 | 1.5 | - | 02/01 | 2.5 | 2.0 | 2.5 | 2.0 | 2.5 | - | 03/01 | 3.5 | 3.0 | 3.5 | 3.0 | 3.5 | - | 04/01 | 4.5 | 4.0 | 4.5 | 4.0 | 4.5 | - | 05/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | - | 06/01 | 9.0 | 6.0 | 7.0 | 6.0 | 7.0 | - | 07/01 | 9.0 | 7.0 | 8.0 | 7.0 | 8.0 | - | 08/01 | 9.0 | 8.0 | 9.0 | 8.0 | 9.0 | - | 09/01 | 9.0 | 9.0 | 10.0 | 9.0 | 10.0 | - | 10/01 | 9.0 | 10.0 | 11.0 | 10.0 | 11.0 | + | date | discharge | originalq | correctedq | inlet | outlet | + --------------------------------------------------------------- + | 01/01 | 1.5 | 1.0 | 1.5 | 1.0 | 1.5 | + | 02/01 | 2.5 | 2.0 | 2.5 | 2.0 | 2.5 | + | 03/01 | 3.5 | 3.0 | 3.5 | 3.0 | 3.5 | + | 04/01 | 4.5 | 4.0 | 4.5 | 4.0 | 4.5 | + | 05/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | + | 06/01 | 9.0 | 6.0 | 7.0 | 6.0 | 7.0 | + | 07/01 | 9.0 | 7.0 | 8.0 | 7.0 | 8.0 | + | 08/01 | 9.0 | 8.0 | 9.0 | 8.0 | 9.0 | + | 09/01 | 9.0 | 9.0 | 10.0 | 9.0 | 10.0 | + | 10/01 | 9.0 | 10.0 | 11.0 | 10.0 | 11.0 | Mean-value-based residual _________________________ @@ -167,18 +167,18 @@ .. integration-test:: >>> forecast_test("2000-01-06") - | date | discharge | inflow | correctedq | inlet | outlet | - ------------------------------------------------------------ - | 01/01 | 1.5 | 1.0 | 1.5 | 1.0 | 1.5 | - | 02/01 | 2.5 | 2.0 | 2.5 | 2.0 | 2.5 | - | 03/01 | 3.5 | 3.0 | 3.5 | 3.0 | 3.5 | - | 04/01 | 4.0 | 4.0 | 4.0 | 4.0 | 4.0 | - | 05/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | - | 06/01 | nan | 6.0 | 7.0 | 6.0 | 7.0 | - | 07/01 | nan | 7.0 | 7.75 | 7.0 | 7.75 | - | 08/01 | nan | 8.0 | 8.5 | 8.0 | 8.5 | - | 09/01 | nan | 9.0 | 9.5 | 9.0 | 9.5 | - | 10/01 | nan | 10.0 | 10.5 | 10.0 | 10.5 | + | date | discharge | originalq | correctedq | inlet | outlet | + --------------------------------------------------------------- + | 01/01 | 1.5 | 1.0 | 1.5 | 1.0 | 1.5 | + | 02/01 | 2.5 | 2.0 | 2.5 | 2.0 | 2.5 | + | 03/01 | 3.5 | 3.0 | 3.5 | 3.0 | 3.5 | + | 04/01 | 4.0 | 4.0 | 4.0 | 4.0 | 4.0 | + | 05/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | + | 06/01 | nan | 6.0 | 7.0 | 6.0 | 7.0 | + | 07/01 | nan | 7.0 | 7.75 | 7.0 | 7.75 | + | 08/01 | nan | 8.0 | 8.5 | 8.0 | 8.5 | + | 09/01 | nan | 9.0 | 9.5 | 9.0 | 9.5 | + | 10/01 | nan | 10.0 | 10.5 | 10.0 | 10.5 | Stationarity check __________________ @@ -202,18 +202,18 @@ .. integration-test:: >>> forecast_test("2000-01-06") - | date | discharge | inflow | correctedq | inlet | outlet | - ------------------------------------------------------------ - | 01/01 | 5.5 | 5.0 | 5.5 | 5.0 | 5.5 | - | 02/01 | 5.5 | 5.0 | 5.5 | 5.0 | 5.5 | - | 03/01 | 5.5 | 5.0 | 5.5 | 5.0 | 5.5 | - | 04/01 | 8.0 | 5.0 | 8.0 | 5.0 | 8.0 | - | 05/01 | 3.0 | 5.0 | 3.5 | 5.0 | 3.5 | - | 06/01 | nan | 5.0 | 4.0 | 5.0 | 4.0 | - | 07/01 | nan | 5.0 | 4.5 | 5.0 | 4.5 | - | 08/01 | nan | 5.0 | 5.0 | 5.0 | 5.0 | - | 09/01 | nan | 5.0 | 5.0 | 5.0 | 5.0 | - | 10/01 | nan | 5.0 | 5.0 | 5.0 | 5.0 | + | date | discharge | originalq | correctedq | inlet | outlet | + --------------------------------------------------------------- + | 01/01 | 5.5 | 5.0 | 5.5 | 5.0 | 5.5 | + | 02/01 | 5.5 | 5.0 | 5.5 | 5.0 | 5.5 | + | 03/01 | 5.5 | 5.0 | 5.5 | 5.0 | 5.5 | + | 04/01 | 8.0 | 5.0 | 8.0 | 5.0 | 8.0 | + | 05/01 | 3.0 | 5.0 | 3.5 | 5.0 | 3.5 | + | 06/01 | nan | 5.0 | 4.0 | 5.0 | 4.0 | + | 07/01 | nan | 5.0 | 4.5 | 5.0 | 4.5 | + | 08/01 | nan | 5.0 | 5.0 | 5.0 | 5.0 | + | 09/01 | nan | 5.0 | 5.0 | 5.0 | 5.0 | + | 10/01 | nan | 5.0 | 5.0 | 5.0 | 5.0 | Variability check _________________ @@ -239,18 +239,18 @@ .. integration-test:: >>> forecast_test("2000-01-06") - | date | discharge | inflow | correctedq | inlet | outlet | - ------------------------------------------------------------ - | 01/01 | 6.0 | 5.0 | 5.0 | 5.0 | 5.0 | - | 02/01 | 6.0 | 5.0 | 5.0 | 5.0 | 5.0 | - | 03/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | - | 04/01 | 7.0 | 5.0 | 7.0 | 5.0 | 7.0 | - | 05/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | - | 06/01 | nan | 5.0 | 6.25 | 5.0 | 6.25 | - | 07/01 | nan | 5.0 | 6.25 | 5.0 | 6.25 | - | 08/01 | nan | 5.0 | 6.25 | 5.0 | 6.25 | - | 09/01 | nan | 5.0 | 6.25 | 5.0 | 6.25 | - | 10/01 | nan | 5.0 | 6.25 | 5.0 | 6.25 | + | date | discharge | originalq | correctedq | inlet | outlet | + --------------------------------------------------------------- + | 01/01 | 6.0 | 5.0 | 5.0 | 5.0 | 5.0 | + | 02/01 | 6.0 | 5.0 | 5.0 | 5.0 | 5.0 | + | 03/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | + | 04/01 | 7.0 | 5.0 | 7.0 | 5.0 | 7.0 | + | 05/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | + | 06/01 | nan | 5.0 | 6.25 | 5.0 | 6.25 | + | 07/01 | nan | 5.0 | 6.25 | 5.0 | 6.25 | + | 08/01 | nan | 5.0 | 6.25 | 5.0 | 6.25 | + | 09/01 | nan | 5.0 | 6.25 | 5.0 | 6.25 | + | 10/01 | nan | 5.0 | 6.25 | 5.0 | 6.25 | Multiple submodels __________________ @@ -286,28 +286,25 @@ .. integration-test:: >>> forecast_test("2000-01-06") - | date | discharge | inflow | correctedq | inlet | outlet | - ------------------------------------------------------------ - | 01/01 | 1.5 | 1.0 | 1.5 | 1.0 | 1.5 | - | 02/01 | 2.5 | 2.0 | 2.5 | 2.0 | 2.5 | - | 03/01 | 8.0 | 6.0 | 6.25 | 6.0 | 6.25 | - | 04/01 | 9.0 | 7.0 | 7.25 | 7.0 | 7.25 | - | 05/01 | 3.5 | 3.0 | 3.5 | 3.0 | 3.5 | - | 06/01 | nan | 4.0 | 4.5 | 4.0 | 4.5 | - | 07/01 | nan | 6.0 | 6.5 | 6.0 | 6.5 | - | 08/01 | nan | 8.0 | 8.5 | 8.0 | 8.5 | - | 09/01 | nan | 4.0 | 4.5 | 4.0 | 4.5 | - | 10/01 | nan | 3.0 | 3.5 | 3.0 | 3.5 | + | date | discharge | originalq | correctedq | inlet | outlet | + --------------------------------------------------------------- + | 01/01 | 1.5 | 1.0 | 1.5 | 1.0 | 1.5 | + | 02/01 | 2.5 | 2.0 | 2.5 | 2.0 | 2.5 | + | 03/01 | 8.0 | 6.0 | 6.25 | 6.0 | 6.25 | + | 04/01 | 9.0 | 7.0 | 7.25 | 7.0 | 7.25 | + | 05/01 | 3.5 | 3.0 | 3.5 | 3.0 | 3.5 | + | 06/01 | nan | 4.0 | 4.5 | 4.0 | 4.5 | + | 07/01 | nan | 6.0 | 6.5 | 6.0 | 6.5 | + | 08/01 | nan | 8.0 | 8.5 | 8.0 | 8.5 | + | 09/01 | nan | 4.0 | 4.5 | 4.0 | 4.5 | + | 10/01 | nan | 3.0 | 3.5 | 3.0 | 3.5 | """ from hydpy.core import modeltools from hydpy.exe.modelimports import * from hydpy.interfaces import statcorrinterfaces -from hydpy.models.statcorr import statcorr_control from hydpy.models.statcorr import statcorr_model -ADDITIONAL_CONTROLPARAMETERS = (statcorr_control.NmbSubmodels,) - class Model(statcorr_model.Main_OutputCorrModel_V1): """|statcorr_main.DOCNAME.complete|.""" @@ -318,7 +315,7 @@ class Model(statcorr_model.Main_OutputCorrModel_V1): ) __HYDPY_ROOTMODEL__ = True - INLET_METHODS = (statcorr_model.Pick_Inflow_V1,) + INLET_METHODS = (statcorr_model.Pick_OriginalQ_V1,) OBSERVER_METHODS = () RECEIVER_METHODS = () RUN_METHODS = (statcorr_model.Calc_OutputCorr_V1,) From 0070df6516112fe93b86b05d4720175d90f0bcab Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Wed, 11 Nov 2026 21:08:58 +0100 Subject: [PATCH 34/43] combine stationaritycheck and variabilitycheck to one parameter --- hydpy/models/statcorr/statcorr_control.py | 348 +++++++++------------- hydpy/models/statcorr/statcorr_derived.py | 52 ++-- hydpy/models/statcorr/statcorr_model.py | 277 ++++++++++------- hydpy/models/statcorr/statcorr_states.py | 16 +- hydpy/models/statcorr_main.py | 56 ++-- 5 files changed, 372 insertions(+), 377 deletions(-) diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index f24b614392..c13f5639f6 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -34,8 +34,9 @@ def __call__(self, *args: CallHook, **kwargs: Any) -> None: class EvaluationWindow(parametertools.Parameter): - """The number of the most recent log entries used to determine the mean simulated - value and its variability [-].""" + """The number of the most recent log entries used to determine the mean observed + value (see |EvaluatedValue|) and the relative variability of the simulated values + (see |RelSumDelta|) [-].""" NDIM: Final[Literal[0]] = 0 TYPE: Final = int @@ -184,7 +185,9 @@ def trim(self, lower: TrimHook = None, upper: TrimHook = None) -> bool: class StationarityCheck(parametertools.SpecialParameter): """Configuration of the check of whether the observed values behave in a - stationary way [-]. + stationary way, optionally combined with the check of whether the simulated + values vary little enough to base the correction on a long-term mean residual + [-]. |StationarityCheck| is a special parameter (see |SpecialParameter|). Either switch the check off by passing `active=False` or switch it on by passing @@ -217,6 +220,27 @@ class StationarityCheck(parametertools.SpecialParameter): >>> round_(stationaritycheck.ratiominmax) 0.5 + The variability check is only meaningful under stationary conditions. Hence, it + is part of the stationarity check. Enable it by additionally passing the + threshold for the relative sum of the absolute changes of the simulated values + (`maxrelsumdelta`) and the length of the averaging period (`averagingwindow`, in + log entries) used under low variability conditions (see + |Calc_LowVariability_V1|): + + >>> stationaritycheck.variabilitycheck + False + >>> stationaritycheck( + ... active=True, window=10, ratiominmax=0.5, maxrelsumdelta=0.2, + ... averagingwindow=24 + ... ) + >>> stationaritycheck + stationaritycheck(active=True, window=10, ratiominmax=0.5, maxrelsumdelta=0.2, \ +averagingwindow=24) + >>> stationaritycheck.variabilitycheck, stationaritycheck.averagingwindow + (True, 24) + >>> round_(stationaritycheck.maxrelsumdelta) + 0.2 + `active` is always required: >>> stationaritycheck(window=5, ratiominmax=0.8) @@ -233,16 +257,30 @@ class StationarityCheck(parametertools.SpecialParameter): ValueError: For parameter `stationaritycheck` of element `?`, both `window` and \ `ratiominmax` must be given when enabling the stationarity check. - A disabled check does not accept `window` or `ratiominmax`: + The variability check requires both `maxrelsumdelta` and `averagingwindow`: + + >>> stationaritycheck(active=True, window=5, ratiominmax=0.8, maxrelsumdelta=0.1) + Traceback (most recent call last): + ... + ValueError: For parameter `stationaritycheck` of element `?`, either both or \ +none of `maxrelsumdelta` and `averagingwindow` must be given. + + A disabled check does not accept any further keyword arguments: >>> stationaritycheck(active=False, window=5, ratiominmax=0.8) Traceback (most recent call last): ... - ValueError: For parameter `stationaritycheck` of element `?`, `window` and \ -`ratiominmax` must not be given when disabling the stationarity check. + ValueError: For parameter `stationaritycheck` of element `?`, no further \ +keyword arguments must be given when disabling the stationarity check. + + >>> stationaritycheck(active=False, maxrelsumdelta=0.1, averagingwindow=12) + Traceback (most recent call last): + ... + ValueError: For parameter `stationaritycheck` of element `?`, no further \ +keyword arguments must be given when disabling the stationarity check. - `window` must be a positive integer, and `ratiominmax` must lie between zero and - one: + `window` and `averagingwindow` must be positive integers, `ratiominmax` must lie + between zero and one, and `maxrelsumdelta` must not be negative: >>> stationaritycheck(active=True, window=0, ratiominmax=0.8) Traceback (most recent call last): @@ -256,13 +294,32 @@ class StationarityCheck(parametertools.SpecialParameter): ValueError: For parameter `stationaritycheck` of element `?`, `ratiominmax` must \ lie between zero and one, but `1.5` is given. + >>> stationaritycheck( + ... active=True, window=5, ratiominmax=0.8, maxrelsumdelta=-0.1, + ... averagingwindow=12 + ... ) + Traceback (most recent call last): + ... + ValueError: For parameter `stationaritycheck` of element `?`, `maxrelsumdelta` \ +must not be negative, but `-0.1` is given. + + >>> stationaritycheck( + ... active=True, window=5, ratiominmax=0.8, maxrelsumdelta=0.1, + ... averagingwindow=0 + ... ) + Traceback (most recent call last): + ... + ValueError: For parameter `stationaritycheck` of element `?`, `averagingwindow` \ +must be a positive integer, but `0` is given. + Failed calls leave the previous configuration untouched: >>> stationaritycheck - stationaritycheck(active=True, window=10, ratiominmax=0.5) + stationaritycheck(active=True, window=10, ratiominmax=0.5, maxrelsumdelta=0.2, \ +averagingwindow=24) """ - _config: tuple[bool, int, float] | None + _config: tuple[bool, int, float, float, int] | None def __init__(self, subvars: variabletools.SubVariables[Any, Any, Any, Any]) -> None: super().__init__(subvars) @@ -276,32 +333,51 @@ def __call__( self, *, active: Literal[True], window: int, ratiominmax: float ) -> None: ... + @overload + def __call__( + self, + *, + active: Literal[True], + window: int, + ratiominmax: float, + maxrelsumdelta: float, + averagingwindow: int, + ) -> None: ... + def __call__( self, *, active: bool | None = None, window: int | None = None, ratiominmax: float | None = None, + maxrelsumdelta: float | None = None, + averagingwindow: int | None = None, ) -> None: if active is None: raise ValueError( f"For parameter {objecttools.elementphrase(self)}, the keyword " f"argument `active` must be given." ) - if (not active) and ((window is not None) or (ratiominmax is not None)): - raise ValueError( - f"For parameter {objecttools.elementphrase(self)}, `window` and " - f"`ratiominmax` must not be given when disabling the stationarity " - f"check." - ) + others = (window, ratiominmax, maxrelsumdelta, averagingwindow) if not active: - self._config = (False, 0, 0.0) + if any(other is not None for other in others): + raise ValueError( + f"For parameter {objecttools.elementphrase(self)}, no further " + f"keyword arguments must be given when disabling the " + f"stationarity check." + ) + self._config = (False, 0, 0.0, 0.0, 0) return if (window is None) or (ratiominmax is None): raise ValueError( f"For parameter {objecttools.elementphrase(self)}, both `window` and " f"`ratiominmax` must be given when enabling the stationarity check." ) + if (maxrelsumdelta is None) != (averagingwindow is None): + raise ValueError( + f"For parameter {objecttools.elementphrase(self)}, either both or " + f"none of `maxrelsumdelta` and `averagingwindow` must be given." + ) if (int(window) != window) or (window < 1): raise ValueError( f"For parameter {objecttools.elementphrase(self)}, `window` must be a " @@ -312,18 +388,43 @@ def __call__( f"For parameter {objecttools.elementphrase(self)}, `ratiominmax` must " f"lie between zero and one, but `{ratiominmax}` is given." ) - self._config = (True, int(window), float(ratiominmax)) + if (maxrelsumdelta is None) or (averagingwindow is None): + self._config = (True, int(window), float(ratiominmax), 0.0, 0) + return + if maxrelsumdelta < 0.0: + raise ValueError( + f"For parameter {objecttools.elementphrase(self)}, `maxrelsumdelta` " + f"must not be negative, but `{maxrelsumdelta}` is given." + ) + if (int(averagingwindow) != averagingwindow) or (averagingwindow < 1): + raise ValueError( + f"For parameter {objecttools.elementphrase(self)}, `averagingwindow` " + f"must be a positive integer, but `{averagingwindow}` is given." + ) + self._config = ( + True, + int(window), + float(ratiominmax), + float(maxrelsumdelta), + int(averagingwindow), + ) def __repr__(self) -> str: if self._config is None: return f"{self.name}(?)" - enabled, window, ratiominmax = self._config + enabled, window, ratiominmax, maxrelsumdelta, averagingwindow = self._config if not enabled: return f"{self.name}(active=False)" - return ( + string = ( f"{self.name}(active=True, window={window}, " - f"ratiominmax={objecttools.repr_(ratiominmax)})" + f"ratiominmax={objecttools.repr_(ratiominmax)}" ) + if averagingwindow > 0: + string = ( + f"{string}, maxrelsumdelta={objecttools.repr_(maxrelsumdelta)}, " + f"averagingwindow={averagingwindow}" + ) + return f"{string})" def verify(self) -> None: """Raise a |RuntimeError| if no configuration has been defined so far.""" @@ -349,7 +450,7 @@ def configured(self) -> bool: """ return self._config is not None - def _get_config(self) -> tuple[bool, int, float]: + def _get_config(self) -> tuple[bool, int, float, float, int]: self.verify() assert self._config is not None return self._config @@ -371,205 +472,31 @@ def ratiominmax(self) -> float: (zero if the check is disabled).""" return self._get_config()[2] - -class VariabilityCheck(parametertools.SpecialParameter): - """Configuration of the check of whether the simulated values vary little - enough to base the correction on a long-term mean residual [-]. - - Either switch the check off by passing `active=False` or switch it on by passing - `active=True` together with the threshold for the sum of the absolute changes of - the simulated values (`maxrelsumdelta`) and the length of the averaging - period (`averagingwindow`): - - >>> from hydpy.models.statcorr import * - >>> parameterstep() - >>> variabilitycheck - variabilitycheck(?) - >>> variabilitycheck.verify() - Traceback (most recent call last): - ... - RuntimeError: For parameter `variabilitycheck` of element `?`, no configuration \ -has been defined so far. Please pass either `active=False` or `active=True` \ -together with the required keyword arguments. - - >>> variabilitycheck(active=False) - >>> variabilitycheck - variabilitycheck(active=False) - >>> variabilitycheck.verify() - - >>> variabilitycheck(active=True, maxrelsumdelta=0.2, averagingwindow=24) - >>> variabilitycheck - variabilitycheck(active=True, maxrelsumdelta=0.2, averagingwindow=24) - >>> variabilitycheck.enabled, variabilitycheck.averagingwindow - (True, 24) - >>> from hydpy import round_ - >>> round_(variabilitycheck.maxrelsumdelta) - 0.2 - - `active` is always required: - - >>> variabilitycheck(maxrelsumdelta=0.1, averagingwindow=12) - Traceback (most recent call last): - ... - ValueError: For parameter `variabilitycheck` of element `?`, the keyword \ -argument `active` must be given. - - An enabled check requires both `maxrelsumdelta` and `averagingwindow`: - - >>> variabilitycheck(active=True, maxrelsumdelta=0.1) - Traceback (most recent call last): - ... - ValueError: For parameter `variabilitycheck` of element `?`, both \ -`maxrelsumdelta` and `averagingwindow` must be given when enabling the variability \ -check. - - A disabled check does not accept `maxrelsumdelta` or `averagingwindow`: - - >>> variabilitycheck(active=False, maxrelsumdelta=0.1, averagingwindow=12) - Traceback (most recent call last): - ... - ValueError: For parameter `variabilitycheck` of element `?`, `maxrelsumdelta` \ -and `averagingwindow` must not be given when disabling the variability check. - - `maxrelsumdelta` must not be negative, and `averagingwindow` must be a positive - integer: - - >>> variabilitycheck(active=True, maxrelsumdelta=-0.1, averagingwindow=12) - Traceback (most recent call last): - ... - ValueError: For parameter `variabilitycheck` of element `?`, `maxrelsumdelta` \ -must not be negative, but `-0.1` is given. - - >>> variabilitycheck(active=True, maxrelsumdelta=0.1, averagingwindow=0) - Traceback (most recent call last): - ... - ValueError: For parameter `variabilitycheck` of element `?`, `averagingwindow` \ -must be a positive integer, but `0` is given. - - Failed calls leave the previous configuration untouched: - - >>> variabilitycheck - variabilitycheck(active=True, maxrelsumdelta=0.2, averagingwindow=24) - """ - - _config: tuple[bool, float, int] | None - - def __init__(self, subvars: variabletools.SubVariables[Any, Any, Any, Any]) -> None: - super().__init__(subvars) - self._config = None - - @overload - def __call__(self, *, active: Literal[False]) -> None: ... - - @overload - def __call__( - self, *, active: Literal[True], maxrelsumdelta: float, averagingwindow: int - ) -> None: ... - - def __call__( - self, - *, - active: bool | None = None, - maxrelsumdelta: float | None = None, - averagingwindow: int | None = None, - ) -> None: - if active is None: - raise ValueError( - f"For parameter {objecttools.elementphrase(self)}, the keyword " - f"argument `active` must be given." - ) - if (not active) and ( - (maxrelsumdelta is not None) or (averagingwindow is not None) - ): - raise ValueError( - f"For parameter {objecttools.elementphrase(self)}, `maxrelsumdelta` " - f"and `averagingwindow` must not be given when disabling the " - f"variability check." - ) - if not active: - self._config = (False, 0.0, 0) - return - if (maxrelsumdelta is None) or (averagingwindow is None): - raise ValueError( - f"For parameter {objecttools.elementphrase(self)}, both " - f"`maxrelsumdelta` and `averagingwindow` must be given when enabling " - f"the variability check." - ) - if maxrelsumdelta < 0.0: - raise ValueError( - f"For parameter {objecttools.elementphrase(self)}, `maxrelsumdelta` " - f"must not be negative, but `{maxrelsumdelta}` is given." - ) - if (int(averagingwindow) != averagingwindow) or (averagingwindow < 1): - raise ValueError( - f"For parameter {objecttools.elementphrase(self)}, `averagingwindow` " - f"must be a positive integer, but `{averagingwindow}` is given." - ) - self._config = (True, float(maxrelsumdelta), int(averagingwindow)) - - def __repr__(self) -> str: - if self._config is None: - return f"{self.name}(?)" - enabled, maxrelsumdelta, averagingwindow = self._config - if not enabled: - return f"{self.name}(active=False)" - return ( - f"{self.name}(active=True, " - f"maxrelsumdelta={objecttools.repr_(maxrelsumdelta)}, " - f"averagingwindow={averagingwindow})" - ) - - def verify(self) -> None: - """Raise a |RuntimeError| if no configuration has been defined so far.""" - if self._config is None: - raise RuntimeError( - f"For parameter {objecttools.elementphrase(self)}, no configuration " - f"has been defined so far. Please pass either `active=False` or " - f"`active=True` together with the required keyword arguments." - ) - - @property - def configured(self) -> bool: - """Flag indicating whether the variability check has already been - configured. - - >>> from hydpy.models.statcorr import * - >>> parameterstep() - >>> variabilitycheck.configured - False - >>> variabilitycheck(active=False) - >>> variabilitycheck.configured - True - """ - return self._config is not None - - def _get_config(self) -> tuple[bool, float, int]: - self.verify() - assert self._config is not None - return self._config - @property - def enabled(self) -> bool: + def variabilitycheck(self) -> bool: """Flag indicating whether the variability check is enabled.""" - return self._get_config()[0] + return self._get_config()[4] > 0 @property def maxrelsumdelta(self) -> float: """The threshold for the sum of the absolute changes of the simulated values - per time step divided by their mean within the |EvaluationWindow|, which - decides whether the forecast is shifted to the observed value at the time of - forecast or to the mean of the averaging window.""" - return self._get_config()[1] + per time step divided by their mean within the |EvaluationWindow| (see + |RelSumDelta|), which decides whether the forecast is shifted to the observed + value at the time of forecast or to the mean of the averaging window (zero if + the variability check is disabled).""" + return self._get_config()[3] @property def averagingwindow(self) -> int: """The length of the averaging period (number of log entries) for - determining the mean-value-based residual under low variability conditions.""" - return self._get_config()[2] + determining the mean-value-based residual under low variability conditions + (zero if the variability check is disabled).""" + return self._get_config()[4] class ReductionSteps(parametertools.Parameter): - """Number of timesteps for linearly reducing the ARIMA correction to zero.""" + """Number of forecast steps for linearly reducing the ARIMA correction to zero + under instationary conditions [-].""" NDIM: Final[Literal[0]] = 0 TYPE: Final = int @@ -601,9 +528,8 @@ class AveragingWindow(parametertools.Parameter): preceding the current forecast run, used to determine the mean-value-based ARIMA residual [-]. - Set to zero to - disable mean-value-based correction and rely on the single most recent - (pointwise) residual only. + Set to zero to disable mean-value-based correction and rely on the single most + recent (pointwise) residual only. """ NDIM: Final[Literal[0]] = 0 diff --git a/hydpy/models/statcorr/statcorr_derived.py b/hydpy/models/statcorr/statcorr_derived.py index fa8568c3d9..0c754f3a6c 100644 --- a/hydpy/models/statcorr/statcorr_derived.py +++ b/hydpy/models/statcorr/statcorr_derived.py @@ -30,7 +30,6 @@ class NmbLogEntries(parametertools.NmbParameter): CONTROLPARAMETERS = ( statcorr_control.EvaluationWindow, statcorr_control.StationarityCheck, - statcorr_control.VariabilityCheck, statcorr_control.MaxNaNSkip, statcorr_control.AveragingWindow, ) @@ -48,7 +47,6 @@ def update(self) -> None: >>> parameterstep() >>> evaluationwindow(3) >>> stationaritycheck(active=True, window=4, ratiominmax=0.5) - >>> variabilitycheck(active=False) >>> maxnanskip(1) >>> derived.nmblogentries.update() Traceback (most recent call last): @@ -66,15 +64,17 @@ def update(self) -> None: Here, the averaging window of the variability check (plus one) is the largest value: - >>> stationaritycheck(active=False) - >>> variabilitycheck(active=True, maxrelsumdelta=0.2, averagingwindow=5) + >>> stationaritycheck( + ... active=True, window=4, ratiominmax=0.5, maxrelsumdelta=0.2, + ... averagingwindow=5 + ... ) >>> derived.nmblogentries.update() >>> derived.nmblogentries nmblogentries(6) Here, |MaxNaNSkip| (plus one) is the largest value: - >>> variabilitycheck(active=False) + >>> stationaritycheck(active=False) >>> maxnanskip(6) >>> derived.nmblogentries.update() >>> derived.nmblogentries @@ -131,13 +131,12 @@ def update(self) -> None: """ control = self.subpars.pars.control stationaritycheck = control.stationaritycheck - variabilitycheck = control.variabilitycheck nmb = max( control.evaluationwindow.value, stationaritycheck.window, control.maxnanskip.value + 1, control.averagingwindow.value + 1, - variabilitycheck.averagingwindow + 1, + stationaritycheck.averagingwindow + 1, ) self(nmb) @@ -211,59 +210,66 @@ def update(self) -> None: class MaxRelSumDelta(parametertools.Parameter): """The threshold for the sum of the absolute changes of the simulated values - within the |EvaluationWindow| divided by |EvaluatedValue| of the variability - check (zero if the check is disabled) [-].""" + within the |EvaluationWindow| divided by their mean (see |RelSumDelta|) of the + variability check (zero if the variability check is disabled, see + |StationarityCheck|) [-].""" NDIM: Final[Literal[0]] = 0 TYPE: Final = float SPAN = (0.0, None) - CONTROLPARAMETERS = (statcorr_control.VariabilityCheck,) + CONTROLPARAMETERS = (statcorr_control.StationarityCheck,) def update(self) -> None: - """Take the threshold from parameter |VariabilityCheck|. + """Take the threshold from parameter |StationarityCheck|. >>> from hydpy.models.statcorr import * >>> parameterstep() - >>> variabilitycheck(active=True, maxrelsumdelta=0.2, averagingwindow=24) + >>> stationaritycheck( + ... active=True, window=4, ratiominmax=0.5, maxrelsumdelta=0.2, + ... averagingwindow=24 + ... ) >>> derived.maxrelsumdelta.update() >>> derived.maxrelsumdelta maxrelsumdelta(0.2) - >>> variabilitycheck(active=False) + >>> stationaritycheck(active=True, window=4, ratiominmax=0.5) >>> derived.maxrelsumdelta.update() >>> derived.maxrelsumdelta maxrelsumdelta(0.0) """ - variabilitycheck = self.subpars.pars.control.variabilitycheck - self(variabilitycheck.maxrelsumdelta) + stationaritycheck = self.subpars.pars.control.stationaritycheck + self(stationaritycheck.maxrelsumdelta) class StationaryAveragingWindow(parametertools.Parameter): """The length of the averaging period for determining the mean-value-based - residual under stationary conditions in log entries (zero if the variability - check is disabled) [-].""" + residual under low variability conditions in log entries (zero if the + variability check is disabled, see |StationarityCheck|) [-].""" NDIM: Final[Literal[0]] = 0 TYPE: Final = int SPAN = (0, None) - CONTROLPARAMETERS = (statcorr_control.VariabilityCheck,) + CONTROLPARAMETERS = (statcorr_control.StationarityCheck,) def update(self) -> None: - """Take the averaging period from parameter |VariabilityCheck|. + """Take the averaging period from parameter |StationarityCheck|. >>> from hydpy.models.statcorr import * >>> parameterstep() - >>> variabilitycheck(active=True, maxrelsumdelta=0.2, averagingwindow=24) + >>> stationaritycheck( + ... active=True, window=4, ratiominmax=0.5, maxrelsumdelta=0.2, + ... averagingwindow=24 + ... ) >>> derived.stationaryaveragingwindow.update() >>> derived.stationaryaveragingwindow stationaryaveragingwindow(24) - >>> variabilitycheck(active=False) + >>> stationaritycheck(active=True, window=4, ratiominmax=0.5) >>> derived.stationaryaveragingwindow.update() >>> derived.stationaryaveragingwindow stationaryaveragingwindow(0) """ - variabilitycheck = self.subpars.pars.control.variabilitycheck - self(variabilitycheck.averagingwindow) + stationaritycheck = self.subpars.pars.control.stationaritycheck + self(stationaritycheck.averagingwindow) diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 5093a55e9f..42a5c4c4b2 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -90,12 +90,13 @@ class Calc_OutputCorr_V1(modeltools.Method): |OutputCorrModel_V1.determine_outputcorrection|. 3. Each submodel decides for itself, based on its own |Active| flag, its |CorrectionMode|, and its |LowerLimit| and |UpperLimit| parameters, - whether it is responsible for the current discharge (see - |OutputCorrModel_V1.is_active|). The corrected output of the *last* - responsible submodel is taken as |CorrectedQ|. When no submodel is - attached or responsible, |CorrectedQ| equals |OriginalQ|. Hence, attaching - several submodels configured for mutually exclusive discharge ranges lets - only the one responsible for the current discharge take effect. + whether it is responsible for the current observed discharge (see + |EvaluatedValue| and |OutputCorrModel_V1.is_active|). The corrected + output of the *last* responsible submodel is taken as |CorrectedQ|. When + no submodel is attached or responsible, |CorrectedQ| equals |OriginalQ|. + Hence, attaching several submodels configured for mutually exclusive + discharge ranges lets only the one responsible for the current observed + discharge take effect. Examples: @@ -129,7 +130,6 @@ class Calc_OutputCorr_V1(modeltools.Method): ... submodel.parameters.control.averagingwindow(0) ... submodel.parameters.control.transitionsteps(0) ... submodel.parameters.control.stationaritycheck(active=False) - ... submodel.parameters.control.variabilitycheck(active=False) ... submodel.parameters.control.reductionsteps(1) >>> nmbsubmodels(1) @@ -161,27 +161,29 @@ class Calc_OutputCorr_V1(modeltools.Method): ... ) as submodel: ... configure(submodel, lowerlimit=3.0) - For an original discharge of 2.5 m³/s, only the first submodel is responsible. - Hence, its corrected output wins, although the second submodel comes - later and returns the original discharge: + The submodels decide based on the observed discharge. For an observed + discharge of 2.5 m³/s, only the first submodel is responsible, although the + original discharge of 3.5 m³/s lies within the range of the second one. + Hence, the corrected output of the first submodel wins, although the second + submodel comes later and returns the original discharge: - >>> fluxes.originalq = 2.5 - >>> inputs.discharge = 4.0 + >>> fluxes.originalq = 3.5 + >>> inputs.discharge = 2.5 >>> model.calc_outputcorr_v1() >>> fluxes.correctedq - correctedq(4.0) + correctedq(2.5) >>> model.outputcorrmodels[0].sequences.fluxes.isactive isactive(1.0) >>> model.outputcorrmodels[1].sequences.fluxes.isactive isactive(0.0) - For an original discharge of 3.5 m³/s, the second submodel takes over: + For an observed discharge of 4.0 m³/s, the second submodel takes over: - >>> fluxes.originalq = 3.5 - >>> inputs.discharge = 3.0 + >>> fluxes.originalq = 2.5 + >>> inputs.discharge = 4.0 >>> model.calc_outputcorr_v1() >>> fluxes.correctedq - correctedq(3.0) + correctedq(4.0) >>> model.outputcorrmodels[0].sequences.fluxes.isactive isactive(0.0) >>> model.outputcorrmodels[1].sequences.fluxes.isactive @@ -192,7 +194,7 @@ class Calc_OutputCorr_V1(modeltools.Method): >>> model.outputcorrmodels[1].parameters.control.active(False) >>> model.calc_outputcorr_v1() >>> fluxes.correctedq - correctedq(3.5) + correctedq(2.5) While |Options.simulationmode| equals ``forecast``, |Calc_OutputCorr_V1| ignores the actual value of |Discharge| and passes |numpy.nan| to the @@ -383,39 +385,59 @@ def __call__(model: modeltools.Model, observedvalue: float, /) -> None: class Calc_EvaluatedValue_V1(modeltools.Method): - r"""Calculate the mean of the |EvaluationWindow| most recent - |LoggedSimulation| values while |Options.simulationmode| is `historical`. + r"""Calculate the mean of the available (non-|numpy.nan|) values among the + |EvaluationWindow| most recent |LoggedObservation| values while + |Options.simulationmode| is `historical`. Basic equation: - :math:`EvaluatedValue = \frac{1}{EvaluationWindow} - \sum_{i=0}^{EvaluationWindow-1} LoggedSimulation_i` + :math:`EvaluatedValue = \frac{1}{n} + \sum_{i=0}^{EvaluationWindow-1} LoggedObservation_i` + + The sum covers only the available values, and :math:`n` is their number. If all + values are |numpy.nan|, |EvaluatedValue| keeps its previous value, so the + responsible submodel (see |Calc_IsActive_V1|) does not change during gaps in the + observations. While |Options.simulationmode| is `forecast`, |Calc_EvaluatedValue_V1| keeps the value of the most recent `historical` assessment, so the responsible submodel - (see |Calc_IsActive_V1|) does not change throughout the forecast horizon. + does not change throughout the forecast horizon. Examples: |Calc_EvaluatedValue_V1| always relies on the *most recently* logged values (index ``0`` upwards) and never on the oldest ones sitting near the end of a - larger log (which can well still be |numpy.nan|): + larger log: >>> from hydpy.models.statcorr import * >>> parameterstep() >>> from numpy import nan >>> control.evaluationwindow(3) >>> derived.nmblogentries(5) - >>> logs.loggedsimulation = 1.0, 2.0, 6.0, nan, nan + >>> logs.loggedobservation = 1.0, 2.0, 6.0, 8.0, 9.0 >>> from hydpy import pub >>> pub.options.simulationmode = "historical" >>> model.calc_evaluatedvalue_v1() >>> states.evaluatedvalue evaluatedvalue(3.0) + Missing observations are left out: + + >>> logs.loggedobservation = 1.0, nan, 5.0, 8.0, 9.0 + >>> model.calc_evaluatedvalue_v1() + >>> states.evaluatedvalue + evaluatedvalue(3.0) + + If no observation is available, |EvaluatedValue| keeps its previous value: + + >>> logs.loggedobservation = nan, nan, nan, 8.0, 9.0 + >>> model.calc_evaluatedvalue_v1() + >>> states.evaluatedvalue + evaluatedvalue(3.0) + In `forecast` mode, |EvaluatedValue| stays frozen: >>> pub.options.simulationmode = "forecast" - >>> logs.loggedsimulation = 10.0, 10.0, 10.0, nan, nan + >>> logs.loggedobservation = 10.0, 10.0, 10.0, nan, nan >>> model.calc_evaluatedvalue_v1() >>> states.evaluatedvalue evaluatedvalue(3.0) @@ -423,7 +445,7 @@ class Calc_EvaluatedValue_V1(modeltools.Method): """ CONTROLPARAMETERS = (statcorr_control.EvaluationWindow,) - REQUIREDSEQUENCES = (statcorr_logs.LoggedSimulation,) + REQUIREDSEQUENCES = (statcorr_logs.LoggedObservation,) UPDATEDSEQUENCES = (statcorr_states.EvaluatedValue,) @staticmethod @@ -432,10 +454,14 @@ def __call__(model: modeltools.Model, /) -> None: log = model.sequences.logs.fastaccess sta = model.sequences.states.fastaccess if model.runsettings.simulationmode == modelutils.HISTORICAL: - sum_simulated: float = 0.0 + sum_observed: float = 0.0 + nmb_observed = 0 for idx in range(con.evaluationwindow): - sum_simulated = sum_simulated + log.loggedsimulation[idx] - sta.evaluatedvalue = sum_simulated / con.evaluationwindow + if not modelutils.isnan(log.loggedobservation[idx]): + sum_observed = sum_observed + log.loggedobservation[idx] + nmb_observed = nmb_observed + 1 + if nmb_observed > 0: + sta.evaluatedvalue = sum_observed / nmb_observed class Calc_IsActive_V1(modeltools.Method): @@ -445,10 +471,13 @@ class Calc_IsActive_V1(modeltools.Method): Each submodel is responsible for a specific value range only. It corrects the simulated values only while |Active| is |True|, |CorrectionMode| allows a correction in the current simulation mode (see |Options.simulationmode|), and - |EvaluatedValue| (:math:`\overline{sim}`) lies within the range defined by + |EvaluatedValue| (:math:`\overline{obs}`) lies within the range defined by |LowerLimit| and |UpperLimit|: - :math:`LowerLimit \leq \overline{sim} < UpperLimit` + :math:`LowerLimit \leq \overline{obs} < UpperLimit` + + As long as |EvaluatedValue| is |numpy.nan| (before the first observation is + available), the submodel is not active. |Calc_IsActive_V1| checks this condition in each simulation step, so changes of |Active|, |CorrectionMode|, |LowerLimit|, or |UpperLimit| take effect @@ -655,9 +684,10 @@ class Calc_Stationary_V1(modeltools.Method): conditions instationary (|Stationary| is ``0.0``), otherwise stationary (|Stationary| is ``1.0``). If a |numpy.nan| value within the |StationarityWindow| prevents calculating the ratio, |Stationary| keeps the - outcome of the previous assessment, so that a single missing observation neither - interrupts an ongoing reduction of |ReductionFactor| (see - |Calc_ReductionFactor_V1|) nor triggers a new one. + outcome of the previous assessment, so that a single missing observation does + not change the outcome of the stationarity check (which decides on the + reduction of the correction during forecast runs, see + |Calc_ReductionFactor_V1|). While |Options.simulationmode| is `forecast`, |Calc_Stationary_V1| keeps the outcome of the most recent `historical` assessment. Recomputing it would be @@ -750,70 +780,82 @@ def __call__(model: modeltools.Model, /) -> None: class Calc_ReductionFactor_V1(modeltools.Method): - r"""Update the factor for damping the correction based on the outcome of the - stationarity check. - - Under instationary conditions (|Stationary| is ``0.0``), - |Calc_ReductionFactor_V1| linearly reduces |ReductionFactor| towards zero, - taking as many steps as given by |ReductionSteps|. As soon as the conditions - are stationary again, |ReductionFactor| jumps back to ``1.0``, applying the - correction unabated again. With the stationarity check disabled (see - |StationarityCheck|), |ReductionFactor| is always ``1.0``. - - As |Stationary| does not change in `forecast` mode (see |Calc_Stationary_V1|), - |ReductionFactor| keeps decreasing towards zero (or stays at ``0.0``) for the - entire forecast horizon once a `historical` run has flagged conditions as - instationary. + r"""Calculate the factor for damping the correction during forecast runs based + on the outcome of the stationarity check. + + Basic equation (under instationary conditions in `forecast` mode): + :math:`ReductionFactor = \max \left( 0, 1 - + \frac{ForecastStep}{ReductionSteps} \right)` + + |ReductionFactor| is ``1.0`` while |Options.simulationmode| is `historical`, so + the stationarity check never dampens the correction of `historical` runs. In + `forecast` mode, instationary conditions (|Stationary| is ``0.0``, as determined + at the last `historical` step, see |Calc_Stationary_V1|) let |ReductionFactor| + decrease linearly from ``1.0`` in the first forecast step to zero after + |ReductionSteps| forecast steps (counted by |ForecastStep|). Hence, the forecast + starts with the unabated correction, avoiding a jump right at the start of the + forecast horizon. With stationary conditions or the stationarity check + disabled (see |StationarityCheck|), |ReductionFactor| is always ``1.0``. Examples: - Sustained instationary conditions reduce |ReductionFactor| to zero within - the two steps given by |ReductionSteps|: + In `historical` mode, |ReductionFactor| is ``1.0``, even under instationary + conditions: >>> from hydpy.models.statcorr import * >>> parameterstep() >>> control.reductionsteps(2) >>> derived.stationaritywindow(3) >>> states.stationary(0.0) - >>> states.reductionfactor(1.0) - >>> model.calc_reductionfactor_v1() - >>> states.reductionfactor - reductionfactor(0.5) + >>> states.forecaststep(0.0) + >>> from hydpy import pub + >>> pub.options.simulationmode = "historical" >>> model.calc_reductionfactor_v1() >>> states.reductionfactor - reductionfactor(0.0) + reductionfactor(1.0) + + In `forecast` mode, |ReductionFactor| decreases to zero within the two + steps given by |ReductionSteps|: + + >>> pub.options.simulationmode = "forecast" + >>> for forecaststep in range(4): + ... states.forecaststep(forecaststep) + ... model.calc_reductionfactor_v1() + ... print(forecaststep, states.reductionfactor.value) + 0 1.0 + 1 0.5 + 2 0.0 + 3 0.0 + + Setting |ReductionSteps| to zero reduces |ReductionFactor| to zero + immediately: + + >>> control.reductionsteps(0) + >>> states.forecaststep(0.0) >>> model.calc_reductionfactor_v1() >>> states.reductionfactor reductionfactor(0.0) - Stationary conditions reset |ReductionFactor| to ``1.0`` immediately: + Stationary conditions result in a |ReductionFactor| of ``1.0``: >>> states.stationary(1.0) >>> model.calc_reductionfactor_v1() >>> states.reductionfactor reductionfactor(1.0) - Setting |ReductionSteps| to zero reduces |ReductionFactor| to zero - immediately once instationary conditions occur: + The same holds when the stationarity check is disabled: - >>> control.reductionsteps(0) >>> states.stationary(0.0) - >>> model.calc_reductionfactor_v1() - >>> states.reductionfactor - reductionfactor(0.0) - - Disabling the stationarity check resets |ReductionFactor| to ``1.0`` - regardless of |Stationary|: - >>> derived.stationaritywindow(0) >>> model.calc_reductionfactor_v1() >>> states.reductionfactor reductionfactor(1.0) + >>> del pub.options.simulationmode """ CONTROLPARAMETERS = (statcorr_control.ReductionSteps,) DERIVEDPARAMETERS = (statcorr_derived.StationarityWindow,) - REQUIREDSEQUENCES = (statcorr_states.Stationary,) + REQUIREDSEQUENCES = (statcorr_states.Stationary, statcorr_states.ForecastStep) UPDATEDSEQUENCES = (statcorr_states.ReductionFactor,) @staticmethod @@ -821,29 +863,37 @@ def __call__(model: modeltools.Model, /) -> None: con = model.parameters.control.fastaccess der = model.parameters.derived.fastaccess sta = model.sequences.states.fastaccess - if (der.stationaritywindow <= 0) or (sta.stationary == 1.0): + if ( + (model.runsettings.simulationmode == modelutils.HISTORICAL) + or (der.stationaritywindow <= 0) + or (sta.stationary == 1.0) + ): sta.reductionfactor = 1.0 elif con.reductionsteps <= 0: sta.reductionfactor = 0.0 else: - sta.reductionfactor = max( - 0.0, sta.reductionfactor - 1.0 / con.reductionsteps - ) + sta.reductionfactor = max(0.0, 1.0 - sta.forecaststep / con.reductionsteps) class Calc_RelSumDelta_V1(modeltools.Method): r"""Calculate the relative sum of the absolute changes between successive simulated values while the variability check is enabled (see - |VariabilityCheck|) and |Options.simulationmode| is `historical`. + |StationarityCheck|) and |Options.simulationmode| is `historical`. Basic equation: - :math:`RelSumDelta = \frac{1}{EvaluatedValue} + :math:`RelSumDelta = \frac{1}{\overline{sim}} \sum_{i=0}^{EvaluationWindow-2} |LoggedSimulation_i - LoggedSimulation_{i+1}|` - For a non-positive |EvaluatedValue|, |RelSumDelta| is |numpy.nan|. While - |Options.simulationmode| is `forecast`, |Calc_RelSumDelta_V1| keeps the value of - the most recent `historical` assessment. + :math:`\overline{sim} = \frac{1}{EvaluationWindow} + \sum_{i=0}^{EvaluationWindow-1} LoggedSimulation_i` + + The variability check assesses the simulated values only, so it relates their + changes to their own mean (:math:`\overline{sim}`) within the |EvaluationWindow|. + For a non-positive or missing :math:`\overline{sim}`, |RelSumDelta| is + |numpy.nan|. While |Options.simulationmode| is `forecast`, + |Calc_RelSumDelta_V1| keeps the value of the most recent `historical` + assessment. Examples: @@ -855,12 +905,11 @@ class Calc_RelSumDelta_V1(modeltools.Method): >>> from hydpy import pub >>> pub.options.simulationmode = "historical" >>> logs.loggedsimulation = 9.0, 10.0, 11.0 - >>> states.evaluatedvalue(10.0) >>> model.calc_relsumdelta_v1() >>> states.relsumdelta relsumdelta(0.2) - >>> states.evaluatedvalue(0.0) + >>> logs.loggedsimulation = 0.0, 0.0, 0.0 >>> model.calc_relsumdelta_v1() >>> states.relsumdelta relsumdelta(nan) @@ -868,7 +917,7 @@ class Calc_RelSumDelta_V1(modeltools.Method): In `forecast` mode or with the variability check disabled, |RelSumDelta| stays unchanged: - >>> states.evaluatedvalue(10.0) + >>> logs.loggedsimulation = 9.0, 10.0, 11.0 >>> pub.options.simulationmode = "forecast" >>> model.calc_relsumdelta_v1() >>> states.relsumdelta @@ -883,7 +932,7 @@ class Calc_RelSumDelta_V1(modeltools.Method): CONTROLPARAMETERS = (statcorr_control.EvaluationWindow,) DERIVEDPARAMETERS = (statcorr_derived.StationaryAveragingWindow,) - REQUIREDSEQUENCES = (statcorr_logs.LoggedSimulation, statcorr_states.EvaluatedValue) + REQUIREDSEQUENCES = (statcorr_logs.LoggedSimulation,) UPDATEDSEQUENCES = (statcorr_states.RelSumDelta,) @staticmethod @@ -900,8 +949,12 @@ def __call__(model: modeltools.Model, /) -> None: sumdelta = sumdelta + modelutils.fabs( log.loggedsimulation[idx] - log.loggedsimulation[idx + 1] ) - if sta.evaluatedvalue > 0.0: - sta.relsumdelta = sumdelta / sta.evaluatedvalue + sumsim: float = 0.0 + for idx in range(con.evaluationwindow): + sumsim = sumsim + log.loggedsimulation[idx] + meansim: float = sumsim / con.evaluationwindow + if meansim > 0.0: + sta.relsumdelta = sumdelta / meansim else: sta.relsumdelta = modelutils.nan @@ -911,15 +964,16 @@ class Calc_LowVariability_V1(modeltools.Method): |StationaryAveragingWindow| instead of the |AveragingWindow| (see |Calc_AveragedResidual_V1|). - If the variability check is enabled (see |VariabilityCheck|), - |Calc_LowVariability_V1| considers the conditions stationary (|LowVariability| - is ``1.0``) if |RelSumDelta| does not exceed |MaxRelSumDelta| and the - stationarity check (see |Calc_Stationary_V1|) is either disabled or also detects - stationary conditions. Hence, the variability check never interferes with the - linear reduction of the correction (see |Calc_ReductionFactor_V1|). A - |numpy.nan| value of |RelSumDelta| results in |LowVariability| being ``0.0``. - Like |Calc_RelSumDelta_V1|, |Calc_LowVariability_V1| reassesses - |LowVariability| only while |Options.simulationmode| is `historical`. With the + The variability check is only meaningful under stationary conditions. Hence, + it is part of the stationarity check (see |StationarityCheck|). If enabled, + |Calc_LowVariability_V1| considers the variability low (|LowVariability| is + ``1.0``) if the stationarity check (see |Calc_Stationary_V1|) detects stationary + conditions and |RelSumDelta| does not exceed |MaxRelSumDelta|. Hence, the + variability check never interferes with the linear reduction of the correction + (see |Calc_ReductionFactor_V1|). A |numpy.nan| value of |RelSumDelta| results + in |LowVariability| being ``0.0``. Like |Calc_RelSumDelta_V1|, + |Calc_LowVariability_V1| reassesses |LowVariability| only while + |Options.simulationmode| is `historical`. With the stationarity check or the variability check disabled, |LowVariability| is always ``0.0``. Examples: @@ -949,8 +1003,7 @@ class Calc_LowVariability_V1(modeltools.Method): lowvariability(0.0) Instationary conditions according to the stationarity check prevent the - variability check from detecting stationary conditions, unless the - stationarity check is disabled: + variability check from detecting low variability: >>> states.relsumdelta(0.2) >>> states.stationary(0.0) @@ -958,26 +1011,32 @@ class Calc_LowVariability_V1(modeltools.Method): >>> states.lowvariability lowvariability(0.0) - >>> derived.stationaritywindow(0) + In `forecast` mode, |LowVariability| stays frozen: + + >>> states.stationary(1.0) >>> model.calc_lowvariability_v1() >>> states.lowvariability lowvariability(1.0) - - In `forecast` mode, |LowVariability| stays frozen: - >>> pub.options.simulationmode = "forecast" >>> states.relsumdelta(0.4) >>> model.calc_lowvariability_v1() >>> states.lowvariability lowvariability(1.0) - Disabling the variability check resets |LowVariability| to ``0.0``, even in - `forecast` mode: + Disabling the variability check or the stationarity check resets + |LowVariability| to ``0.0``, even in `forecast` mode: >>> derived.stationaryaveragingwindow(0) >>> model.calc_lowvariability_v1() >>> states.lowvariability lowvariability(0.0) + + >>> derived.stationaryaveragingwindow(3) + >>> states.lowvariability(1.0) + >>> derived.stationaritywindow(0) + >>> model.calc_lowvariability_v1() + >>> states.lowvariability + lowvariability(0.0) >>> del pub.options.simulationmode """ @@ -993,12 +1052,10 @@ class Calc_LowVariability_V1(modeltools.Method): def __call__(model: modeltools.Model, /) -> None: der = model.parameters.derived.fastaccess sta = model.sequences.states.fastaccess - if der.stationaryaveragingwindow <= 0: + if (der.stationaritywindow <= 0) or (der.stationaryaveragingwindow <= 0): sta.lowvariability = 0.0 elif model.runsettings.simulationmode == modelutils.HISTORICAL: - if ((der.stationaritywindow <= 0) or (sta.stationary == 1.0)) and ( - sta.relsumdelta <= der.maxrelsumdelta - ): + if (sta.stationary == 1.0) and (sta.relsumdelta <= der.maxrelsumdelta): sta.lowvariability = 1.0 else: sta.lowvariability = 0.0 @@ -1017,8 +1074,8 @@ class Calc_AveragedResidual_V1(modeltools.Method): not zero (i.e., beyond the first forecast step), or |AveragingWindow| is zero (mean-value-based correction disabled). When the averaging window contains a |numpy.nan| value, it falls back to the pointwise |Residual| (see - |Calc_Residual_ResidualAnchor_V1|). While |LowVariability| is ``1.0`` - (stationary conditions according to |VariabilityCheck|), the + |Calc_Residual_ResidualAnchor_V1|). While |LowVariability| is ``1.0`` (low + variability according to the variability check, see |StationarityCheck|), the |StationaryAveragingWindow| replaces the |AveragingWindow|. Examples: @@ -1076,7 +1133,7 @@ class Calc_AveragedResidual_V1(modeltools.Method): >>> states.averagedresidual averagedresidual(-9.0) - Under stationary conditions according to |VariabilityCheck|, the averaging + Under low variability conditions (see |Calc_LowVariability_V1|), the averaging period covers the single log position ``1`` given by |StationaryAveragingWindow| (``30.0 - 20.0``), even if |AveragingWindow| is zero: @@ -1309,8 +1366,8 @@ class Calc_CorrectedValue_V1(modeltools.Method): >>> fluxes.correctedvalue correctedvalue(14.5) - Under stationary conditions according to |VariabilityCheck| (see - |Calc_LowVariability_V1|), the mean-value-based residual applies even if + Under low variability conditions, the + mean-value-based residual applies even if |AveragingWindow| is zero: >>> control.averagingwindow(0) @@ -1462,7 +1519,6 @@ class Determine_OutputCorrection_V1(modeltools.AutoMethod): >>> control.stationaritycheck(active=False) >>> derived.stationaritywindow.update() >>> derived.ratiominmax.update() - >>> control.variabilitycheck(active=False) >>> derived.maxrelsumdelta.update() >>> derived.stationaryaveragingwindow.update() >>> control.reductionsteps(2) @@ -1657,7 +1713,6 @@ def add_outputcorrmodel_v1( >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0): ... evaluationwindow(2) ... stationaritycheck(active=True, window=4, ratiominmax=0.5) - ... variabilitycheck(active=False) ... maxnanskip(2) ... averagingwindow(0) >>> model.outputcorrmodels[0].parameters.derived.nmblogentries diff --git a/hydpy/models/statcorr/statcorr_states.py b/hydpy/models/statcorr/statcorr_states.py index 8d475653d6..2ceca5410a 100644 --- a/hydpy/models/statcorr/statcorr_states.py +++ b/hydpy/models/statcorr/statcorr_states.py @@ -7,9 +7,9 @@ class ReductionFactor(sequencetools.StateSequence): - """Factor for linearly reducing the ARIMA correction to zero under instationary - conditions (1.0: apply the correction unabated; 0.0: apply no correction at - all) [-].""" + """Factor for linearly reducing the ARIMA correction to zero during forecast runs + under instationary conditions (1.0: apply the correction unabated; 0.0: apply no + correction at all) [-].""" NDIM: Final[Literal[0]] = 0 SPAN = (0.0, 1.0) @@ -27,9 +27,9 @@ class Stationary(sequencetools.StateSequence): class EvaluatedValue(sequencetools.StateSequence): - """The mean of the simulated values over the |EvaluationWindow| most recent log - entries, as determined at the last `historical` assessment [unit of the - corrected variable].""" + """The mean of the available observed values over the |EvaluationWindow| most + recent log entries, as determined at the last `historical` assessment [unit of + the corrected variable].""" NDIM: Final[Literal[0]] = 0 INIT = numpy.nan @@ -37,8 +37,8 @@ class EvaluatedValue(sequencetools.StateSequence): class RelSumDelta(sequencetools.StateSequence): """The sum of the absolute changes of the simulated values within the - |EvaluationWindow| divided by |EvaluatedValue|, as determined at the last - `historical` assessment [-].""" + |EvaluationWindow| divided by their mean, as determined at the last `historical` + assessment [-].""" NDIM: Final[Literal[0]] = 0 INIT = numpy.nan diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py index 59ef4db7b9..cad156009f 100644 --- a/hydpy/models/statcorr_main.py +++ b/hydpy/models/statcorr_main.py @@ -25,14 +25,14 @@ >>> element.model = model >>> propagate(True) >>> test = IntegrationTest(element) - >>> test.dateformat = "%d/%m" + >>> test.dateformat = "%Y-%d-%m" The following function configures a |statcorr_arima010| submodel with the settings shared by all examples. It makes the submodel responsible for all discharges (its |EvaluationWindow| of one step means it assesses its - responsibility based on the current simulated discharge only) and disables the - stationarity check via |StationarityCheck|, the variability check via - |VariabilityCheck|, and the mean-value-based residual via |AveragingWindow|, so + responsibility based on the current observed discharge only) and disables the + stationarity check (including the variability check) via |StationarityCheck| + and the mean-value-based residual via |AveragingWindow|, so the ARIMA correction always applies unabated. The individual examples override some of these settings: @@ -50,7 +50,6 @@ ... control.averagingwindow(0) ... control.transitionsteps(0) ... control.stationaritycheck(active=False) - ... control.variabilitycheck(active=False) ... control.reductionsteps(1) The inlet provides the simulated discharge; |Discharge| carries the @@ -186,10 +185,11 @@ Next, we enable the stationarity check with a window of three days and a |RatioMinMax| of ``0.5``, and set |ReductionSteps| to four. The simulated discharge is constant. On day five, the observations of days three to five - (``5.5``, ``8.0``, and ``3.0``) become instationary (``3.0 / 8.0 < 0.5``), so - |ReductionFactor| starts to decrease linearly. It continues to do so during the - `forecast` run, which reuses the assessment of the `historical` run, until the - correction vanishes completely: + (``5.5``, ``8.0``, and ``3.0``) become instationary (``3.0 / 8.0 < 0.5``). This + does not affect the `historical` run. The `forecast` run reuses the assessment + of the last `historical` step, so |ReductionFactor| decreases linearly from + ``1.0`` in the first forecast step until the correction vanishes completely + after four steps: >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0) as sub: ... configure(sub) @@ -208,22 +208,27 @@ | 02/01 | 5.5 | 5.0 | 5.5 | 5.0 | 5.5 | | 03/01 | 5.5 | 5.0 | 5.5 | 5.0 | 5.5 | | 04/01 | 8.0 | 5.0 | 8.0 | 5.0 | 8.0 | - | 05/01 | 3.0 | 5.0 | 3.5 | 5.0 | 3.5 | - | 06/01 | nan | 5.0 | 4.0 | 5.0 | 4.0 | - | 07/01 | nan | 5.0 | 4.5 | 5.0 | 4.5 | - | 08/01 | nan | 5.0 | 5.0 | 5.0 | 5.0 | - | 09/01 | nan | 5.0 | 5.0 | 5.0 | 5.0 | + | 05/01 | 3.0 | 5.0 | 3.0 | 5.0 | 3.0 | + | 06/01 | nan | 5.0 | 3.0 | 5.0 | 3.0 | + | 07/01 | nan | 5.0 | 3.5 | 5.0 | 3.5 | + | 08/01 | nan | 5.0 | 4.0 | 5.0 | 4.0 | + | 09/01 | nan | 5.0 | 4.5 | 5.0 | 4.5 | | 10/01 | nan | 5.0 | 5.0 | 5.0 | 5.0 | Variability check _________________ - Now, we enable the variability check instead, with a |MaxRelSumDelta| of - ``0.1`` and an averaging period of four days, and set |EvaluationWindow| to - three and |AveragingWindow| to one. During the first two days, the - |EvaluationWindow| still contains missing values, so the submodel does not - consider itself responsible. As the simulated discharge is constant, the - variability check detects stationary conditions, so the mean-value-based + Now, we enable the variability check, which is only meaningful under stationary + conditions and thus part of the stationarity check. We use the same + stationarity settings as above, a |MaxRelSumDelta| of ``0.1``, and an averaging + period of four days, and set |EvaluationWindow| to three and |AveragingWindow| + to one. The observations of the last three `historical` days (``6.0``, + ``7.0``, and ``6.0``) are stationary (``6.0 / 7.0 >= 0.5``), so there is no + reduction of the correction. During the first two days, the + |EvaluationWindow| still contains missing values, but the submodel considers + itself responsible, as it relies on the available observations only (see + |EvaluatedValue|). As the simulated discharge is constant, the + variability check detects low variability, so the mean-value-based residual relies on the four days preceding the forecast (mean observed ``6.25``, mean simulated ``5.0``) instead of on the single day given by |AveragingWindow| (which would result in ``1.0``): @@ -232,7 +237,10 @@ ... configure(sub) ... evaluationwindow(3) ... averagingwindow(1) - ... variabilitycheck(active=True, maxrelsumdelta=0.1, averagingwindow=4) + ... stationaritycheck( + ... active=True, window=3, ratiominmax=0.5, maxrelsumdelta=0.1, + ... averagingwindow=4 + ... ) >>> with pub.options.checkseries(False): ... inputs.discharge.series = 6.0, 6.0, 6.0, 7.0, 6.0, nan, nan, nan, nan, nan @@ -241,8 +249,8 @@ >>> forecast_test("2000-01-06") | date | discharge | originalq | correctedq | inlet | outlet | --------------------------------------------------------------- - | 01/01 | 6.0 | 5.0 | 5.0 | 5.0 | 5.0 | - | 02/01 | 6.0 | 5.0 | 5.0 | 5.0 | 5.0 | + | 01/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | + | 02/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | | 03/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | | 04/01 | 7.0 | 5.0 | 7.0 | 5.0 | 7.0 | | 05/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | @@ -256,7 +264,7 @@ __________________ Finally, we attach two submodels responsible for different discharge ranges. - The first one handles simulated discharges below ``5.0`` and the second one all + The first one handles observed discharges below ``5.0`` and the second one all others. The second one restricts the relative shift to 5 % and the absolute shift to ``0.25``: From 896e7a59d17d0534257c8273648a40426840a386 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Wed, 11 Nov 2026 21:09:23 +0100 Subject: [PATCH 35/43] Rewrite docstrings and integration tests in statcorr_arima010.py --- hydpy/models/statcorr_arima010.py | 564 ++++++++++++++++++++++++------ 1 file changed, 458 insertions(+), 106 deletions(-) diff --git a/hydpy/models/statcorr_arima010.py b/hydpy/models/statcorr_arima010.py index 7bdc081d00..102f390ffd 100644 --- a/hydpy/models/statcorr_arima010.py +++ b/hydpy/models/statcorr_arima010.py @@ -1,111 +1,463 @@ # pylint: disable=unused-wildcard-import """ -|statcorr_arima010| performs statistical output correction of simulated values -based on an ARIMA(0,1,0) error model. - -The corrected value is derived from the most recently available residual -(observed minus simulated values). While |Options.simulationmode| equals -`historical`, this residual is (re)determined every step by skipping at most -|MaxNaNSkip| log entries with missing observations to find the latest -non-|numpy.nan| observation, so that the error persists whenever the *current* -observation is missing. When no observation is available within -that range (or the entire log, whichever is smaller), no correction is -applied. While |Options.simulationmode| equals `forecast`, this search is -not repeated: the residual (and the simulated value it was measured -against) stays frozen at whatever the most recent `historical` assessment -found, so the correction persists throughout the whole forecast horizon -(subject only to |ReductionFactor|) instead of fading once that log entry -lies more than |MaxNaNSkip| entries back. - -How the residual is applied depends on how the current simulated value -compares to the simulated value at the point the residual was determined: -if it is positive and lower than this anchor value, the residual is applied -relative to the anchor value (capped at |MaxRelShift|), which keeps the correction -from overshooting or turning negative while the simulated values recede; -otherwise, the residual is added unchanged (capped at |MaxAbsShift|). See -|Calc_CorrectedValue_V1| for the exact formulas. - -Setting |AveragingWindow| to a value greater than zero switches from -that pointwise residual to a mean-value-based one (mean observed minus mean -simulated values over the given number of log entries immediately -preceding the current forecast run), blended in linearly over -|TransitionSteps| forecast steps to avoid a jump right where the -forecast begins. See |Calc_AveragedResidual_V1| and |Calc_CorrectedValue_V1| for -details. - -Each |statcorr_arima010| instance is responsible for a specific value range -only, defined by |LowerLimit| and |UpperLimit|, and can be switched off completely -via |Active| or restricted to one simulation mode via |CorrectionMode|. -Optionally, |StationarityCheck| lets it fade out the correction under instationary -conditions, and |VariabilityCheck| lets it base the mean-value-based residual on a -separate averaging period under stationary conditions. - -|statcorr_arima010| serves as a submodel for |statcorr| and complies with the -|OutputCorrModel_V1| interface. - -Example workflow -================ - - |statcorr_arima010| determines the length of its internal log from its - parameters (see |NmbLogEntries|) and resizes both the simulated and the - observed values log accordingly: - - >>> from hydpy.models.statcorr_arima010 import * - >>> parameterstep() - >>> from numpy import inf - >>> control.active(True) - >>> control.correctionmode(option="both") - >>> control.lowerlimit(0.0) - >>> control.upperlimit(inf) - >>> control.evaluationwindow(3) - >>> control.stationaritycheck(active=False) - >>> derived.stationaritywindow.update() - >>> derived.ratiominmax.update() - >>> control.variabilitycheck(active=False) - >>> derived.maxrelsumdelta.update() - >>> derived.stationaryaveragingwindow.update() - >>> control.reductionsteps(1) - >>> control.maxnanskip(2) - >>> control.maxabsshift(100.0) - >>> control.maxrelshift(10.0) - >>> control.averagingwindow(0) - >>> control.transitionsteps(0) - >>> derived.nmblogentries.update() - >>> derived.nmblogentries - nmblogentries(3) - >>> logs.loggedsimulation - loggedsimulation(nan, nan, nan) - >>> logs.loggedobservation - loggedobservation(nan, nan, nan) - - Successive calls of |OutputCorrModel_V1.set_simulatedvalue| and - |OutputCorrModel_V1.set_observedvalue| shift the previously buffered - values one position to the right and store the new value at position 0: - - >>> model.set_simulatedvalue(2.0) - >>> model.set_observedvalue(3.0) - >>> model.set_simulatedvalue(3.0) - >>> model.set_observedvalue(4.0) - >>> model.set_simulatedvalue(5.0) - >>> from numpy import nan - >>> model.set_observedvalue(nan) - >>> logs.loggedsimulation - loggedsimulation(5.0, 3.0, 2.0) - >>> logs.loggedobservation - loggedobservation(nan, 4.0, 3.0) - - |OutputCorrModel_V1.determine_outputcorrection| computes the corrected - value from the most recent residual (here taken from log position 1, - since position 0 has no observation) and stores it internally; - |OutputCorrModel_V1.is_active| confirms the submodel is responsible for the - current value, and |OutputCorrModel_V1.get_correctedoutput| returns the - buffered value: - - >>> model.determine_outputcorrection() - >>> assert model.is_active() - >>> from hydpy import round_ - >>> round_(model.get_correctedoutput()) - 6.0 +The |statcorr.DOCNAME.long| model family member |statcorr_arima010| is an output +correction submodel that follows the LARSIM approach for forecast correction based +on the difference between observed and simulated values. + +Integration tests +================= + + .. how_to_understand_integration_tests:: + + |statcorr_arima010| receives all its input from a main model. Hence, we use it + as a submodel of |statcorr_main| for the following tests. |statcorr_main| is + meant to correct discharge, so in this integration test, we use discharge as + the corrected variable. |statcorr_arima010| can be used to correct all variables + with a true zero point, though. + + We prepare a simulation period of ten days and connect the main model to an inlet + and an outlet node. + + >>> from hydpy import Element, IntegrationTest, prepare_model, pub + >>> pub.timegrids = "2000-01-01", "2000-01-11", "1d" + >>> model = prepare_model("statcorr_main") + >>> element = Element("element", inlets="inlet", outlets="outlet") + >>> element.model = model + >>> model.parameters.control.propagate(True) + >>> model.parameters.control.nmbsubmodels(1) + + We attach a |statcorr_arima010| submodel. We differentiate between two + operating modes: `historical` and `forecast`. `correctionmode(option="both"` means + that the correction will take place in historical and in forecast more. The effect + of the correction candiffer between the two modes. + + The correction will only take place if the mean of the observation in the + evaluation window lies between `lowerlimit` and `upperlimit`. + + We set `evaluationwindow(1)` so only the last observation value will be evaluated + for the decision if the submodel will do the correction. The submodel is only + active if the mean discharge in the evaluation period is between `lowerlimit` + and `upperlimit`. With `lowerlimit(0.0)` and upperlimit(inf), the correction will + take place for any value of the observation. + + We set `averagingwindow(0)`, so the single most recent observation will be used + to calculate the residual which is the base for the correction. This corresponds to + the behaviour of the LARSIM option `WHM-ARIMA-VORHERSAGE`. + + If the last observation is NaN, we search for an available observed value up to + two time steps earlier (`maxnanskip(2)`). + + We set the maximum absolute shift to `100.0` and the maximum relative shift + to `10.0`. The other parameters are set to zero or False so they are inactive for + now, we explain their effect later. + + >>> from numpy import inf, nan + >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0): + ... active(True) + ... correctionmode(option="both") + ... lowerlimit(0.0) + ... upperlimit(inf) + ... evaluationwindow(1) + ... maxnanskip(2) + ... maxabsshift(100.0) + ... maxrelshift(1.0) + ... averagingwindow(0) + ... transitionsteps(0) + ... stationaritycheck(active=False) + ... reductionsteps(1) + >>> test = IntegrationTest(element) + >>> test.dateformat = "%Y-%d-%m" + + The following function first runs a `historical` simulation until the given + date. Then, it runs a `forecast` simulation for the remaining days, starting + from the conditions of the `historical` run: + + >>> def forecast_test(split): + ... test.prepare_model(update_parameters=True, use_conditions=None) + ... first, last = pub.timegrids.sim.firstdate, pub.timegrids.sim.lastdate + ... pub.timegrids.sim.lastdate = split + ... with pub.options.simulationmode("historical"): + ... test.hydpy.simulate() + ... conditions = model.conditions + ... pub.timegrids.sim.dates = split, last + ... with pub.options.simulationmode("forecast"): + ... model.conditions = conditions + ... test.hydpy.simulate() + ... pub.timegrids.sim.dates = first, last + ... test.print_table() + + The observed discharge for the fifth day is `10.0`, and the simulated discharge + is `12.0`, so the last residual is `2.0` (remember, we set `evaluationwindow(1)`: + + >>> element.inlets.inlet.sequences.sim.series = ( + ... 8.0, 9.0, 10.0, 10.0, 10.0, 11.0, 12.0, 9.0, 6.0, 3.0 + ... ) + >>> with pub.options.checkseries(False): + ... model.sequences.inputs.discharge.series = ( + ... [9.6, 10.8, 12.6, 12.0, 12.0] + 5 * [nan] + ... ) + +Additive and relative shift +___________________________ + + If the simulated discharge is greater than the observed discharge at the + forecast start (the mean over the evaluation period), the correction uses an + absolute shift (limited to `maxabsshift`), otherwise a relative shift (limited + to `maxrelshift`). + + In the historical mode, the corrected value is the observed value of this time + step. + + We see that as long as the simulated discharge is not below `10.0` (the simulated + value when the residual was determined), the submodel adds the residual. When the + simulated discharge falls below `10.0`, the submodel applies the residual as + a relative shift (`2.0 / 10.0 = 20 %`). So, the correction becomes smaller + when the discharge decreases: + +.. integration-test:: + + >>> forecast_test("2000-01-06") + | date | discharge | originalq | correctedq | inlet | outlet | + -------------------------------------------------------------------- + | 2000-01-01 | 9.6 | 8.0 | 9.6 | 8.0 | 9.6 | + | 2000-02-01 | 10.8 | 9.0 | 10.8 | 9.0 | 10.8 | + | 2000-03-01 | 12.6 | 10.0 | 12.6 | 10.0 | 12.6 | + | 2000-04-01 | 12.0 | 10.0 | 12.0 | 10.0 | 12.0 | + | 2000-05-01 | 12.0 | 10.0 | 12.0 | 10.0 | 12.0 | + | 2000-06-01 | nan | 11.0 | 13.0 | 11.0 | 13.0 | + | 2000-07-01 | nan | 12.0 | 14.0 | 12.0 | 14.0 | + | 2000-08-01 | nan | 9.0 | 10.8 | 9.0 | 10.8 | + | 2000-09-01 | nan | 6.0 | 7.2 | 6.0 | 7.2 | + | 2000-10-01 | nan | 3.0 | 3.6 | 3.0 | 3.6 | + +Limited relative shift +______________________ + + Now, we limit the relative shift to 10 % with |MaxRelShift|. The first two + forecast days do not change, because the submodel adds the residual there. On + the last three days, the correction is limited to 10 %: + + >>> model.outputcorrmodels[0].parameters.control.maxrelshift(0.1) + +.. integration-test:: + + >>> forecast_test("2000-01-06") + | date | discharge | originalq | correctedq | inlet | outlet | + -------------------------------------------------------------------- + | 2000-01-01 | 9.6 | 8.0 | 9.6 | 8.0 | 9.6 | + | 2000-02-01 | 10.8 | 9.0 | 10.8 | 9.0 | 10.8 | + | 2000-03-01 | 12.6 | 10.0 | 12.6 | 10.0 | 12.6 | + | 2000-04-01 | 12.0 | 10.0 | 12.0 | 10.0 | 12.0 | + | 2000-05-01 | 12.0 | 10.0 | 12.0 | 10.0 | 12.0 | + | 2000-06-01 | nan | 11.0 | 13.0 | 11.0 | 13.0 | + | 2000-07-01 | nan | 12.0 | 14.0 | 12.0 | 14.0 | + | 2000-08-01 | nan | 9.0 | 9.9 | 9.0 | 9.9 | + | 2000-09-01 | nan | 6.0 | 6.6 | 6.0 | 6.6 | + | 2000-10-01 | nan | 3.0 | 3.3 | 3.0 | 3.3 | + +Limited absolute shift +______________________ + + The absolute shift can be limited as well: now, we set |MaxAbsShift| + to `1.0 m³/s`: + + >>> model.outputcorrmodels[0].parameters.control.maxabsshift(1.0) + +.. integration-test:: + + >>> forecast_test("2000-01-06") + | date | discharge | originalq | correctedq | inlet | outlet | + -------------------------------------------------------------------- + | 2000-01-01 | 9.6 | 8.0 | 9.0 | 8.0 | 9.0 | + | 2000-02-01 | 10.8 | 9.0 | 10.0 | 9.0 | 10.0 | + | 2000-03-01 | 12.6 | 10.0 | 11.0 | 10.0 | 11.0 | + | 2000-04-01 | 12.0 | 10.0 | 11.0 | 10.0 | 11.0 | + | 2000-05-01 | 12.0 | 10.0 | 11.0 | 10.0 | 11.0 | + | 2000-06-01 | nan | 11.0 | 12.0 | 11.0 | 12.0 | + | 2000-07-01 | nan | 12.0 | 13.0 | 12.0 | 13.0 | + | 2000-08-01 | nan | 9.0 | 9.9 | 9.0 | 9.9 | + | 2000-09-01 | nan | 6.0 | 6.6 | 6.0 | 6.6 | + | 2000-10-01 | nan | 3.0 | 3.3 | 3.0 | 3.3 | + +Deactivate the submodel +________________________ + + If we deactivate the submodel, the simulated discharge does not get corrected + at all: + + >>> model.outputcorrmodels[0].parameters.control.active(False) + +.. integration-test:: + + >>> forecast_test("2000-01-06") + | date | discharge | originalq | correctedq | inlet | outlet | + -------------------------------------------------------------------- + | 2000-01-01 | 9.6 | 8.0 | 8.0 | 8.0 | 8.0 | + | 2000-02-01 | 10.8 | 9.0 | 9.0 | 9.0 | 9.0 | + | 2000-03-01 | 12.6 | 10.0 | 10.0 | 10.0 | 10.0 | + | 2000-04-01 | 12.0 | 10.0 | 10.0 | 10.0 | 10.0 | + | 2000-05-01 | 12.0 | 10.0 | 10.0 | 10.0 | 10.0 | + | 2000-06-01 | nan | 11.0 | 11.0 | 11.0 | 11.0 | + | 2000-07-01 | nan | 12.0 | 12.0 | 12.0 | 12.0 | + | 2000-08-01 | nan | 9.0 | 9.0 | 9.0 | 9.0 | + | 2000-09-01 | nan | 6.0 | 6.0 | 6.0 | 6.0 | + | 2000-10-01 | nan | 3.0 | 3.0 | 3.0 | 3.0 | + +Use a longer evaluation window +______________________________ + + We activate the submodel and increase the maximum shifts again: + + >>> model.outputcorrmodels[0].parameters.control.active(True) + >>> model.outputcorrmodels[0].parameters.control.maxabsshift(100.0) + >>> model.outputcorrmodels[0].parameters.control.maxrelshift(1.0) + + We set the evaluation window to three time steps and set `lowerlimit(12.0)`. + Now the correction is only active if the mean of the last three observations + is equal or greater than 12.0. For the first four time steps, this is not the + case, so the simulated discharge does not get corrected. + + >>> model.outputcorrmodels[0].parameters.control.evaluationwindow(3.0) + >>> model.outputcorrmodels[0].parameters.control.lowerlimit(12.0) + +.. integration-test:: + + >>> forecast_test("2000-01-06") + | date | discharge | originalq | correctedq | inlet | outlet | + -------------------------------------------------------------------- + | 2000-01-01 | 9.6 | 8.0 | 8.0 | 8.0 | 8.0 | + | 2000-02-01 | 10.8 | 9.0 | 9.0 | 9.0 | 9.0 | + | 2000-03-01 | 12.6 | 10.0 | 10.0 | 10.0 | 10.0 | + | 2000-04-01 | 12.0 | 10.0 | 10.0 | 10.0 | 10.0 | + | 2000-05-01 | 12.0 | 10.0 | 12.0 | 10.0 | 12.0 | + | 2000-06-01 | nan | 11.0 | 13.0 | 11.0 | 13.0 | + | 2000-07-01 | nan | 12.0 | 14.0 | 12.0 | 14.0 | + | 2000-08-01 | nan | 9.0 | 10.8 | 9.0 | 10.8 | + | 2000-09-01 | nan | 6.0 | 7.2 | 6.0 | 7.2 | + | 2000-10-01 | nan | 3.0 | 3.6 | 3.0 | 3.6 | + + If we set `correctionmode(option="forecast")`, the correction will only + start after the fifth timestep: + + >>> model.outputcorrmodels[0].parameters.control.correctionmode(option="forecast") + +.. integration-test:: + + >>> forecast_test("2000-01-06") + | date | discharge | originalq | correctedq | inlet | outlet | + -------------------------------------------------------------------- + | 2000-01-01 | 9.6 | 8.0 | 8.0 | 8.0 | 8.0 | + | 2000-02-01 | 10.8 | 9.0 | 9.0 | 9.0 | 9.0 | + | 2000-03-01 | 12.6 | 10.0 | 10.0 | 10.0 | 10.0 | + | 2000-04-01 | 12.0 | 10.0 | 10.0 | 10.0 | 10.0 | + | 2000-05-01 | 12.0 | 10.0 | 10.0 | 10.0 | 10.0 | + | 2000-06-01 | nan | 11.0 | 13.0 | 11.0 | 13.0 | + | 2000-07-01 | nan | 12.0 | 14.0 | 12.0 | 14.0 | + | 2000-08-01 | nan | 9.0 | 10.8 | 9.0 | 10.8 | + | 2000-09-01 | nan | 6.0 | 7.2 | 6.0 | 7.2 | + | 2000-10-01 | nan | 3.0 | 3.6 | 3.0 | 3.6 | + +Skipping NaN-Values +___________________ + + When calculating the residual, NaN values can be skipped (up to |MaxNanSkip| + time steps). We demonstrate this by setting the last three observations in + the historical period to `nan` and using `maxnanskip(3)`. We see that the last + residual (`1.8`) is used because three steps without observations are skipped. + + >>> model.outputcorrmodels[0].parameters.control.evaluationwindow(1) + >>> model.outputcorrmodels[0].parameters.control.lowerlimit(0.0) + >>> model.outputcorrmodels[0].parameters.control.correctionmode(option="both") + >>> with pub.options.checkseries(False): + ... model.sequences.inputs.discharge.series = [9.6, 10.8] + 8 * [nan] + >>> model.outputcorrmodels[0].parameters.control.maxnanskip(3) + +.. integration-test:: + + >>> forecast_test("2000-01-06") + | date | discharge | originalq | correctedq | inlet | outlet | + -------------------------------------------------------------------- + | 2000-01-01 | 9.6 | 8.0 | 9.6 | 8.0 | 9.6 | + | 2000-02-01 | 10.8 | 9.0 | 10.8 | 9.0 | 10.8 | + | 2000-03-01 | nan | 10.0 | 11.8 | 10.0 | 11.8 | + | 2000-04-01 | nan | 10.0 | 11.8 | 10.0 | 11.8 | + | 2000-05-01 | nan | 10.0 | 11.8 | 10.0 | 11.8 | + | 2000-06-01 | nan | 11.0 | 12.8 | 11.0 | 12.8 | + | 2000-07-01 | nan | 12.0 | 13.8 | 12.0 | 13.8 | + | 2000-08-01 | nan | 9.0 | 10.8 | 9.0 | 10.8 | + | 2000-09-01 | nan | 6.0 | 7.2 | 6.0 | 7.2 | + | 2000-10-01 | nan | 3.0 | 3.6 | 3.0 | 3.6 | + + If we set `maxnanskip(2)`, after the fourth time step no residual can be + calculated and the discharge will not be corrected: + + >>> model.outputcorrmodels[0].parameters.control.maxnanskip(2) + +.. integration-test:: + + >>> forecast_test("2000-01-06") + | date | discharge | originalq | correctedq | inlet | outlet | + -------------------------------------------------------------------- + | 2000-01-01 | 9.6 | 8.0 | 9.6 | 8.0 | 9.6 | + | 2000-02-01 | 10.8 | 9.0 | 10.8 | 9.0 | 10.8 | + | 2000-03-01 | nan | 10.0 | 11.8 | 10.0 | 11.8 | + | 2000-04-01 | nan | 10.0 | 11.8 | 10.0 | 11.8 | + | 2000-05-01 | nan | 10.0 | 10.0 | 10.0 | 10.0 | + | 2000-06-01 | nan | 11.0 | 11.0 | 11.0 | 11.0 | + | 2000-07-01 | nan | 12.0 | 12.0 | 12.0 | 12.0 | + | 2000-08-01 | nan | 9.0 | 9.0 | 9.0 | 9.0 | + | 2000-09-01 | nan | 6.0 | 6.0 | 6.0 | 6.0 | + | 2000-10-01 | nan | 3.0 | 3.0 | 3.0 | 3.0 | + + +Use a mean value for the residual +_________________________________ + + >>> with pub.options.checkseries(False): + ... model.sequences.inputs.discharge.series = ( + ... [9.6, 10.8, 12.6, 12.0, 12.0] + 5 * [nan] + ... ) + + Instead of using the last pointwise residual, it is possible to calculate a + mean residual over the number of time steps set in `averagingwindow`. This only + works in the forecast mode + + >>> model.outputcorrmodels[0].parameters.control.averagingwindow(3) + +.. integration-test:: + + >>> forecast_test("2000-01-06") + | date | discharge | originalq | correctedq | inlet | outlet | + -------------------------------------------------------------------- + | 2000-01-01 | 9.6 | 8.0 | 9.6 | 8.0 | 9.6 | + | 2000-02-01 | 10.8 | 9.0 | 10.8 | 9.0 | 10.8 | + | 2000-03-01 | 12.6 | 10.0 | 12.6 | 10.0 | 12.6 | + | 2000-04-01 | 12.0 | 10.0 | 12.0 | 10.0 | 12.0 | + | 2000-05-01 | 12.0 | 10.0 | 12.0 | 10.0 | 12.0 | + | 2000-06-01 | nan | 11.0 | 13.2 | 11.0 | 13.2 | + | 2000-07-01 | nan | 12.0 | 14.2 | 12.0 | 14.2 | + | 2000-08-01 | nan | 9.0 | 10.98 | 9.0 | 10.98 | + | 2000-09-01 | nan | 6.0 | 7.32 | 6.0 | 7.32 | + | 2000-10-01 | nan | 3.0 | 3.66 | 3.0 | 3.66 | + + When using a mean value for the residual, it is possible to set the + parameter `transition steps`. The correction will then change linearly from + the last pointwise residual to the mean residual. This helps to avoid abrupt + jumps between the last observation and the first forecast value: + + >>> model.outputcorrmodels[0].parameters.control.transitionsteps(4) + +.. integration-test:: + + >>> forecast_test("2000-01-06") + | date | discharge | originalq | correctedq | inlet | outlet | + -------------------------------------------------------------------- + | 2000-01-01 | 9.6 | 8.0 | 9.6 | 8.0 | 9.6 | + | 2000-02-01 | 10.8 | 9.0 | 10.8 | 9.0 | 10.8 | + | 2000-03-01 | 12.6 | 10.0 | 12.6 | 10.0 | 12.6 | + | 2000-04-01 | 12.0 | 10.0 | 12.0 | 10.0 | 12.0 | + | 2000-05-01 | 12.0 | 10.0 | 12.0 | 10.0 | 12.0 | + | 2000-06-01 | nan | 11.0 | 13.0 | 11.0 | 13.0 | + | 2000-07-01 | nan | 12.0 | 14.05 | 12.0 | 14.05 | + | 2000-08-01 | nan | 9.0 | 10.89 | 9.0 | 10.89 | + | 2000-09-01 | nan | 6.0 | 7.29 | 6.0 | 7.29 | + | 2000-10-01 | nan | 3.0 | 3.66 | 3.0 | 3.66 | + +Stationarity check +__________________ + + So far, we had `stationaritycheck(False)`. With + `stationaritycheck(window=4, ratiominmax=0.8)` we turn on a check for stationarity. + That means, that if the ratio between minimum discharge and maximum discharge within + the given period is lower than the given `ratiominmax`, it is assumed that + the conditions are instationary. Then the correction in forecast mode is reduced + linearly over the number of time steps set in `reductionsteps`. + In our example, this ratio is `0.86`, so we set `ratiominmax(0.9)` to demonstrate + the effect. + + >>> model.outputcorrmodels[0].parameters.control.transitionsteps(0) + >>> model.outputcorrmodels[0].parameters.control.stationaritycheck( + ... active=True, window=4, ratiominmax=0.9 + ... ) + >>> model.outputcorrmodels[0].parameters.control.reductionsteps(4) + +.. integration-test:: + + >>> forecast_test("2000-01-06") + | date | discharge | originalq | correctedq | inlet | outlet | + -------------------------------------------------------------------- + | 2000-01-01 | 9.6 | 8.0 | 9.6 | 8.0 | 9.6 | + | 2000-02-01 | 10.8 | 9.0 | 10.8 | 9.0 | 10.8 | + | 2000-03-01 | 12.6 | 10.0 | 12.6 | 10.0 | 12.6 | + | 2000-04-01 | 12.0 | 10.0 | 12.0 | 10.0 | 12.0 | + | 2000-05-01 | 12.0 | 10.0 | 12.0 | 10.0 | 12.0 | + | 2000-06-01 | nan | 11.0 | 13.2 | 11.0 | 13.2 | + | 2000-07-01 | nan | 12.0 | 13.65 | 12.0 | 13.65 | + | 2000-08-01 | nan | 9.0 | 9.99 | 9.0 | 9.99 | + | 2000-09-01 | nan | 6.0 | 6.33 | 6.0 | 6.33 | + | 2000-10-01 | nan | 3.0 | 3.0 | 3.0 | 3.0 | + +Variability check +_________________ + + The optional variability check compares the sum of relative discharge changes + with the keyword parameter `maxrelsumdelta`. If it is less, then the correction + is based on the mean discharge over the timesteps set by the keyword parameter + `averagingwindow`. In accordance with LARSIM, thicheck depends on stationary + conditions, that's why it can be switched on by using two optional keyword + parameters for the stationarity check. In the example, the sum of relative + changes of the simulated discharge over the length of the `evaluationwindow` + is `0.213`. Setting the keyword parameter `maxrelsumdelta` to `0.25` means that + the variability check finds low variability, in this case the output correction + will be based on the mean discharge over the averaging window set as a keyword + parameter in `stationaritycheck` instead of the general averaging window. + + >>> control = model.outputcorrmodels[0].parameters.control + >>> control.evaluationwindow(5) + >>> control.stationaritycheck( + ... active=True, window=4, ratiominmax=0.8, maxrelsumdelta=0.25, + ... averagingwindow=4 + ... ) + +.. integration-test:: + + >>> forecast_test("2000-01-06") + | date | discharge | originalq | correctedq | inlet | outlet | + -------------------------------------------------------------------- + | 2000-01-01 | 9.6 | 8.0 | 9.6 | 8.0 | 9.6 | + | 2000-02-01 | 10.8 | 9.0 | 10.8 | 9.0 | 10.8 | + | 2000-03-01 | 12.6 | 10.0 | 12.6 | 10.0 | 12.6 | + | 2000-04-01 | 12.0 | 10.0 | 12.0 | 10.0 | 12.0 | + | 2000-05-01 | 12.0 | 10.0 | 12.0 | 10.0 | 12.0 | + | 2000-06-01 | nan | 11.0 | 13.1 | 11.0 | 13.1 | + | 2000-07-01 | nan | 12.0 | 14.1 | 12.0 | 14.1 | + | 2000-08-01 | nan | 9.0 | 10.89 | 9.0 | 10.89 | + | 2000-09-01 | nan | 6.0 | 7.26 | 6.0 | 7.26 | + | 2000-10-01 | nan | 3.0 | 3.63 | 3.0 | 3.63 | + + If we change `maxrelsumdelta` to 0.2, the correction is based on the mean discharge + over the general parameter `averagingwindow`: + + >>> control.stationaritycheck( + ... active=True, window=4, ratiominmax=0.8, maxrelsumdelta=0.2, + ... averagingwindow=4 + ... ) + +.. integration-test:: + + >>> forecast_test("2000-01-06") + | date | discharge | originalq | correctedq | inlet | outlet | + -------------------------------------------------------------------- + | 2000-01-01 | 9.6 | 8.0 | 9.6 | 8.0 | 9.6 | + | 2000-02-01 | 10.8 | 9.0 | 10.8 | 9.0 | 10.8 | + | 2000-03-01 | 12.6 | 10.0 | 12.6 | 10.0 | 12.6 | + | 2000-04-01 | 12.0 | 10.0 | 12.0 | 10.0 | 12.0 | + | 2000-05-01 | 12.0 | 10.0 | 12.0 | 10.0 | 12.0 | + | 2000-06-01 | nan | 11.0 | 13.2 | 11.0 | 13.2 | + | 2000-07-01 | nan | 12.0 | 14.2 | 12.0 | 14.2 | + | 2000-08-01 | nan | 9.0 | 10.98 | 9.0 | 10.98 | + | 2000-09-01 | nan | 6.0 | 7.32 | 6.0 | 7.32 | + | 2000-10-01 | nan | 3.0 | 3.66 | 3.0 | 3.66 | """ from hydpy.core import modeltools From 175b3fe9f6e646000562701166e8fb47e347d9e4 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Wed, 11 Nov 2026 21:29:44 +0100 Subject: [PATCH 36/43] Clean docstrings in statcorr_control.py --- hydpy/models/statcorr/statcorr_control.py | 51 ++++++++--------------- 1 file changed, 17 insertions(+), 34 deletions(-) diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index c13f5639f6..db6a467f0a 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -10,9 +10,6 @@ class NmbSubmodels(parametertools.NmbParameter): """The number of output correction submodels [-]. - Setting |NmbSubmodels| automatically resizes the |Model.outputcorrmodels| submodel - slots accordingly: - >>> from hydpy.models.statcorr import * >>> parameterstep() >>> nmbsubmodels(3) @@ -34,9 +31,8 @@ def __call__(self, *args: CallHook, **kwargs: Any) -> None: class EvaluationWindow(parametertools.Parameter): - """The number of the most recent log entries used to determine the mean observed - value (see |EvaluatedValue|) and the relative variability of the simulated values - (see |RelSumDelta|) [-].""" + """The number of time steps the submodels use for evaluating parameters + based on logged values [-].""" NDIM: Final[Literal[0]] = 0 TYPE: Final = int @@ -44,12 +40,8 @@ class EvaluationWindow(parametertools.Parameter): class MaxNaNSkip(parametertools.Parameter): - """The maximum number of log entries with missing observed values to skip - when searching back for the most recently available residual [-]. - - The search covers the current log entry and the |MaxNaNSkip| preceding ones. - A value of zero restricts the search to the current log entry. - """ + """The maximum number of log entries with NaN values to skip + when evaluating logged parameters [-].""" NDIM: Final[Literal[0]] = 0 TYPE: Final = int @@ -189,12 +181,10 @@ class StationarityCheck(parametertools.SpecialParameter): values vary little enough to base the correction on a long-term mean residual [-]. - |StationarityCheck| is a special parameter (see |SpecialParameter|). Either - switch the check off by passing `active=False` or switch it on by passing + Either switch the check off by passing `active=False` or switch it on by passing `active=True` together with the length of the assessment period (`window`, in log entries) and the threshold for the ratio of the minimum and the maximum observed - values within this period (`ratiominmax`), below which |Calc_Stationary_V1| - considers the conditions instationary: + values within this period (`ratiominmax`): >>> from hydpy.models.statcorr import * >>> parameterstep() @@ -220,12 +210,10 @@ class StationarityCheck(parametertools.SpecialParameter): >>> round_(stationaritycheck.ratiominmax) 0.5 - The variability check is only meaningful under stationary conditions. Hence, it - is part of the stationarity check. Enable it by additionally passing the + Optionally, a variability check may switched on by additionally passing the threshold for the relative sum of the absolute changes of the simulated values (`maxrelsumdelta`) and the length of the averaging period (`averagingwindow`, in - log entries) used under low variability conditions (see - |Calc_LowVariability_V1|): + log entries): >>> stationaritycheck.variabilitycheck False @@ -480,10 +468,7 @@ def variabilitycheck(self) -> bool: @property def maxrelsumdelta(self) -> float: """The threshold for the sum of the absolute changes of the simulated values - per time step divided by their mean within the |EvaluationWindow| (see - |RelSumDelta|), which decides whether the forecast is shifted to the observed - value at the time of forecast or to the mean of the averaging window (zero if - the variability check is disabled).""" + per time step divided by their mean.""" return self._get_config()[3] @property @@ -495,8 +480,7 @@ def averagingwindow(self) -> int: class ReductionSteps(parametertools.Parameter): - """Number of forecast steps for linearly reducing the ARIMA correction to zero - under instationary conditions [-].""" + """Number of forecast steps for linearly reducing the correction to zero [-].""" NDIM: Final[Literal[0]] = 0 TYPE: Final = int @@ -504,7 +488,7 @@ class ReductionSteps(parametertools.Parameter): class MaxAbsShift(parametertools.Parameter): - """The maximum absolute shift applied.""" + """The maximum absolute shift applied [unit of the corrected variable].""" NDIM: Final[Literal[0]] = 0 TYPE: Final = float @@ -512,7 +496,7 @@ class MaxAbsShift(parametertools.Parameter): class MaxRelShift(parametertools.Parameter): - """The maximum relative shift applied. + """The maximum relative shift applied [-]. |MaxRelShift| is a fraction, not a percentage as in LARSIM (compare https://larsim.info/larsimhilfe/html/LARSIM-Einzelparameter/LARSIM_Einzelparameter_065_MAX-ARIMA-NQ_[proz].htm) @@ -525,8 +509,8 @@ class MaxRelShift(parametertools.Parameter): class AveragingWindow(parametertools.Parameter): """The length (in log entries) of the averaging period immediately - preceding the current forecast run, used to determine the mean-value-based - ARIMA residual [-]. + preceding the current time step, used to determine the mean-value-based + residual [-]. Set to zero to disable mean-value-based correction and rely on the single most recent (pointwise) residual only. @@ -540,8 +524,7 @@ class AveragingWindow(parametertools.Parameter): class TransitionSteps(parametertools.Parameter): """The number of forecast steps over which the applied residual transitions linearly from the single most recent (pointwise) residual to the mean-value-based - residual determined via |AveragingWindow|, avoiding an abrupt jump right at the - start of the forecast horizon [-].""" + residual [-].""" NDIM: Final[Literal[0]] = 0 TYPE: Final = int @@ -549,9 +532,9 @@ class TransitionSteps(parametertools.Parameter): class Propagate(parametertools.Parameter): - """Flag determining whether the corrected discharge is passed on to the + """Flag determining whether the corrected value is passed on to the downstream network (|True|) or calculated only for local output at the - current gauge, while the original discharge is passed on instead + current gauge, while the original value is passed on instead (|False|) [-].""" NDIM: Final[Literal[0]] = 0 From 4c49a79d3053e9c46532c4dd66995294ac69fcb9 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Wed, 11 Nov 2026 21:32:35 +0100 Subject: [PATCH 37/43] Clean docstrings in statcorr_derived.py --- hydpy/models/statcorr/statcorr_derived.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/hydpy/models/statcorr/statcorr_derived.py b/hydpy/models/statcorr/statcorr_derived.py index 0c754f3a6c..c576aab684 100644 --- a/hydpy/models/statcorr/statcorr_derived.py +++ b/hydpy/models/statcorr/statcorr_derived.py @@ -210,9 +210,7 @@ def update(self) -> None: class MaxRelSumDelta(parametertools.Parameter): """The threshold for the sum of the absolute changes of the simulated values - within the |EvaluationWindow| divided by their mean (see |RelSumDelta|) of the - variability check (zero if the variability check is disabled, see - |StationarityCheck|) [-].""" + within the |EvaluationWindow| divided by their mean [-].""" NDIM: Final[Literal[0]] = 0 TYPE: Final = float @@ -245,7 +243,7 @@ def update(self) -> None: class StationaryAveragingWindow(parametertools.Parameter): """The length of the averaging period for determining the mean-value-based residual under low variability conditions in log entries (zero if the - variability check is disabled, see |StationarityCheck|) [-].""" + variability check is disabled [-].""" NDIM: Final[Literal[0]] = 0 TYPE: Final = int From 7511e76ee705b561ff46ea23db9f5636c079dad1 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Thu, 12 Nov 2026 09:11:32 +0100 Subject: [PATCH 38/43] Rewrite integration tests in statcorr_main.py --- hydpy/models/statcorr_main.py | 315 ++++++++++------------------------ 1 file changed, 87 insertions(+), 228 deletions(-) diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py index cad156009f..dd791f67aa 100644 --- a/hydpy/models/statcorr_main.py +++ b/hydpy/models/statcorr_main.py @@ -10,6 +10,11 @@ .. how_to_understand_integration_tests:: + he exact functionality of the submodels is illustrated in their integration tests. + The main model, `statcorr_main`, serves as a container for the submodels. This + section demonstrates how submodels with different parameterizations can be combined + using the main model. + We prepare a simulation period of ten days: >>> from hydpy import pub @@ -25,22 +30,20 @@ >>> element.model = model >>> propagate(True) >>> test = IntegrationTest(element) - >>> test.dateformat = "%Y-%d-%m" + >>> test.dateformat = "%Y-%m-%d" - The following function configures a |statcorr_arima010| submodel with the - settings shared by all examples. It makes the submodel responsible for all - discharges (its |EvaluationWindow| of one step means it assesses its - responsibility based on the current observed discharge only) and disables the - stationarity check (including the variability check) via |StationarityCheck| - and the mean-value-based residual via |AveragingWindow|, so - the ARIMA correction always applies unabated. The individual examples - override some of these settings: + We attach a two submodels to the main model. For both submodels, `lowerlimit` is + `0.0` and `upperlimit` is `inf`, so the correction should take place for any + observed discharge. Both submodels should correct the discharge only in forecast + mode. For the second submodel, we limit th ecorrection by setting |MaxAbsShift| to + `0.5` and |MaxRelShift| to `0.05`. >>> from numpy import inf, nan - >>> def configure(submodel): - ... control = submodel.parameters.control + >>> nmbsubmodels(2) + >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0) as sub: + ... control = sub.parameters.control ... control.active(True) - ... control.correctionmode(option="both") + ... control.correctionmode(option="forecast") ... control.lowerlimit(0.0) ... control.upperlimit(inf) ... control.evaluationwindow(1) @@ -51,51 +54,33 @@ ... control.transitionsteps(0) ... control.stationaritycheck(active=False) ... control.reductionsteps(1) + >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=1) as sub: + ... control = sub.parameters.control + ... control.active(True) + ... control.correctionmode(option="forecast") + ... control.lowerlimit(0.0) + ... control.upperlimit(inf) + ... control.evaluationwindow(1) + ... control.maxnanskip(2) + ... control.maxabsshift(0.5) + ... control.maxrelshift(0.05) + ... control.averagingwindow(0) + ... control.transitionsteps(0) + ... control.stationaritycheck(active=False) + ... control.reductionsteps(1) - The inlet provides the simulated discharge; |Discharge| carries the - observations. - -Historical simulation -_____________________ - - We attach a single submodel: - - >>> nmbsubmodels(1) - >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0) as sub: - ... configure(sub) - - In the first example, the complete simulation period runs in `historical` - mode. Observations are available for the first two days only: + We specify a time series with simulated values for the entire period and a + time series with observations for the first five time steps. - >>> element.inlets.inlet.sequences.sim.series = range(1, 11) + >>> element.inlets.inlet.sequences.sim.series = ( + ... 8.0, 9.0, 10.0, 10.0, 10.0, 11.0, 12.0, 9.0, 6.0, 3.0 + ... ) >>> with pub.options.checkseries(False): - ... inputs.discharge.series = 1.5, 2.5, nan, nan, nan, nan, nan, nan, nan, nan - - During the first two steps the correction is based on the concurrent residual - (``0.5``). Afterwards, the model falls back to the most recent available - residual, which stays at ``0.5`` until it lies more than |MaxNaNSkip| entries - back on day five, after which no correction is applied: - -.. integration-test:: + ... model.sequences.inputs.discharge.series = ( + ... [9.6, 10.8, 12.6, 12.0, 12.0] + 5 * [nan] + ... ) - >>> test() - | date | discharge | originalq | correctedq | inlet | outlet | - --------------------------------------------------------------- - | 01/01 | 1.5 | 1.0 | 1.5 | 1.0 | 1.5 | - | 02/01 | 2.5 | 2.0 | 2.5 | 2.0 | 2.5 | - | 03/01 | nan | 3.0 | 3.5 | 3.0 | 3.5 | - | 04/01 | nan | 4.0 | 4.5 | 4.0 | 4.5 | - | 05/01 | nan | 5.0 | 5.0 | 5.0 | 5.0 | - | 06/01 | nan | 6.0 | 6.0 | 6.0 | 6.0 | - | 07/01 | nan | 7.0 | 7.0 | 7.0 | 7.0 | - | 08/01 | nan | 8.0 | 8.0 | 8.0 | 8.0 | - | 09/01 | nan | 9.0 | 9.0 | 9.0 | 9.0 | - | 10/01 | nan | 10.0 | 10.0 | 10.0 | 10.0 | - -Forecast simulation -___________________ - - In operational use, a forecast consists of two separate simulation runs. First, + In operational use, a forecast consists of two separate simulation runs. First, a `historical` run covers the period with observations and ends with saving the current conditions (the states and logs of all submodels). Second, a `forecast` run starts from these conditions and covers the forecast horizon. @@ -117,195 +102,69 @@ ... pub.timegrids.sim.dates = first, last ... test.print_table() - We replace the submodel of the previous example with a fresh one and let the - forecast start on day six. In contrast to the previous example, observations - are available for all days. However, |Calc_OutputCorr_V1| ignores them during - the `forecast` run. Instead, the submodel keeps applying the residual - determined at the end of the `historical` run (``6.0 - 5.0 = 1.0``) throughout - the whole forecast horizon, even after it lies more than |MaxNaNSkip| entries - back: - - >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0) as sub: - ... configure(sub) - >>> with pub.options.checkseries(False): - ... inputs.discharge.series = 1.5, 2.5, 3.5, 4.5, 6.0, 9.0, 9.0, 9.0, 9.0, 9.0 + Since the last submodel, which would perform a correction, is given priority, the + correction is limited according to the parameters of the second submodel: .. integration-test:: >>> forecast_test("2000-01-06") - | date | discharge | originalq | correctedq | inlet | outlet | - --------------------------------------------------------------- - | 01/01 | 1.5 | 1.0 | 1.5 | 1.0 | 1.5 | - | 02/01 | 2.5 | 2.0 | 2.5 | 2.0 | 2.5 | - | 03/01 | 3.5 | 3.0 | 3.5 | 3.0 | 3.5 | - | 04/01 | 4.5 | 4.0 | 4.5 | 4.0 | 4.5 | - | 05/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | - | 06/01 | 9.0 | 6.0 | 7.0 | 6.0 | 7.0 | - | 07/01 | 9.0 | 7.0 | 8.0 | 7.0 | 8.0 | - | 08/01 | 9.0 | 8.0 | 9.0 | 8.0 | 9.0 | - | 09/01 | 9.0 | 9.0 | 10.0 | 9.0 | 10.0 | - | 10/01 | 9.0 | 10.0 | 11.0 | 10.0 | 11.0 | - -Mean-value-based residual -_________________________ - - Setting |AveragingWindow| to two makes the submodel determine a mean-value-based - residual from the two days preceding the forecast (days four and five, mean - observed ``5.0``, mean simulated ``4.5``, hence ``0.5``). Setting - |TransitionSteps| to two makes the applied residual change linearly from the - pointwise residual (``1.0``) to the mean-value-based residual over the first two - forecast steps: - - >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0) as sub: - ... configure(sub) - ... averagingwindow(2) - ... transitionsteps(2) - >>> with pub.options.checkseries(False): - ... inputs.discharge.series = 1.5, 2.5, 3.5, 4.0, 6.0, nan, nan, nan, nan, nan + | date | discharge | originalq | correctedq | inlet | outlet | + -------------------------------------------------------------------- + | 2000-01-01 | 9.6 | 8.0 | 8.0 | 8.0 | 8.0 | + | 2000-01-02 | 10.8 | 9.0 | 9.0 | 9.0 | 9.0 | + | 2000-01-03 | 12.6 | 10.0 | 10.0 | 10.0 | 10.0 | + | 2000-01-04 | 12.0 | 10.0 | 10.0 | 10.0 | 10.0 | + | 2000-01-05 | 12.0 | 10.0 | 10.0 | 10.0 | 10.0 | + | 2000-01-06 | nan | 11.0 | 11.5 | 11.0 | 11.5 | + | 2000-01-07 | nan | 12.0 | 12.5 | 12.0 | 12.5 | + | 2000-01-08 | nan | 9.0 | 9.45 | 9.0 | 9.45 | + | 2000-01-09 | nan | 6.0 | 6.3 | 6.0 | 6.3 | + | 2000-01-10 | nan | 3.0 | 3.15 | 3.0 | 3.15 | + + Now we change the correction mode for the first submodel to "both". We see + that in historical mode, the first submodel now does the correction, while in + forecast mode, the second submodel still has priority: + + >>> model.outputcorrmodels[0].parameters.control.correctionmode(option="both") .. integration-test:: >>> forecast_test("2000-01-06") - | date | discharge | originalq | correctedq | inlet | outlet | - --------------------------------------------------------------- - | 01/01 | 1.5 | 1.0 | 1.5 | 1.0 | 1.5 | - | 02/01 | 2.5 | 2.0 | 2.5 | 2.0 | 2.5 | - | 03/01 | 3.5 | 3.0 | 3.5 | 3.0 | 3.5 | - | 04/01 | 4.0 | 4.0 | 4.0 | 4.0 | 4.0 | - | 05/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | - | 06/01 | nan | 6.0 | 7.0 | 6.0 | 7.0 | - | 07/01 | nan | 7.0 | 7.75 | 7.0 | 7.75 | - | 08/01 | nan | 8.0 | 8.5 | 8.0 | 8.5 | - | 09/01 | nan | 9.0 | 9.5 | 9.0 | 9.5 | - | 10/01 | nan | 10.0 | 10.5 | 10.0 | 10.5 | - -Stationarity check -__________________ - - Next, we enable the stationarity check with a window of three days and a - |RatioMinMax| of ``0.5``, and set |ReductionSteps| to four. The simulated - discharge is constant. On day five, the observations of days three to five - (``5.5``, ``8.0``, and ``3.0``) become instationary (``3.0 / 8.0 < 0.5``). This - does not affect the `historical` run. The `forecast` run reuses the assessment - of the last `historical` step, so |ReductionFactor| decreases linearly from - ``1.0`` in the first forecast step until the correction vanishes completely - after four steps: - - >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0) as sub: - ... configure(sub) - ... stationaritycheck(active=True, window=3, ratiominmax=0.5) - ... reductionsteps(4) - >>> element.inlets.inlet.sequences.sim.series = 5.0 - >>> with pub.options.checkseries(False): - ... inputs.discharge.series = 5.5, 5.5, 5.5, 8.0, 3.0, nan, nan, nan, nan, nan + | date | discharge | originalq | correctedq | inlet | outlet | + -------------------------------------------------------------------- + | 2000-01-01 | 9.6 | 8.0 | 9.6 | 8.0 | 9.6 | + | 2000-01-02 | 10.8 | 9.0 | 10.8 | 9.0 | 10.8 | + | 2000-01-03 | 12.6 | 10.0 | 12.6 | 10.0 | 12.6 | + | 2000-01-04 | 12.0 | 10.0 | 12.0 | 10.0 | 12.0 | + | 2000-01-05 | 12.0 | 10.0 | 12.0 | 10.0 | 12.0 | + | 2000-01-06 | nan | 11.0 | 11.5 | 11.0 | 11.5 | + | 2000-01-07 | nan | 12.0 | 12.5 | 12.0 | 12.5 | + | 2000-01-08 | nan | 9.0 | 9.45 | 9.0 | 9.45 | + | 2000-01-09 | nan | 6.0 | 6.3 | 6.0 | 6.3 | + | 2000-01-10 | nan | 3.0 | 3.15 | 3.0 | 3.15 | + + Increasing the |LowerLimit| of the second submodel to `15.0` means that + the correction is now performed by the first submodel even in prediction mode. + + >>> model.outputcorrmodels[0].parameters.control.lowerlimit(15.0) .. integration-test:: >>> forecast_test("2000-01-06") - | date | discharge | originalq | correctedq | inlet | outlet | - --------------------------------------------------------------- - | 01/01 | 5.5 | 5.0 | 5.5 | 5.0 | 5.5 | - | 02/01 | 5.5 | 5.0 | 5.5 | 5.0 | 5.5 | - | 03/01 | 5.5 | 5.0 | 5.5 | 5.0 | 5.5 | - | 04/01 | 8.0 | 5.0 | 8.0 | 5.0 | 8.0 | - | 05/01 | 3.0 | 5.0 | 3.0 | 5.0 | 3.0 | - | 06/01 | nan | 5.0 | 3.0 | 5.0 | 3.0 | - | 07/01 | nan | 5.0 | 3.5 | 5.0 | 3.5 | - | 08/01 | nan | 5.0 | 4.0 | 5.0 | 4.0 | - | 09/01 | nan | 5.0 | 4.5 | 5.0 | 4.5 | - | 10/01 | nan | 5.0 | 5.0 | 5.0 | 5.0 | - -Variability check -_________________ - - Now, we enable the variability check, which is only meaningful under stationary - conditions and thus part of the stationarity check. We use the same - stationarity settings as above, a |MaxRelSumDelta| of ``0.1``, and an averaging - period of four days, and set |EvaluationWindow| to three and |AveragingWindow| - to one. The observations of the last three `historical` days (``6.0``, - ``7.0``, and ``6.0``) are stationary (``6.0 / 7.0 >= 0.5``), so there is no - reduction of the correction. During the first two days, the - |EvaluationWindow| still contains missing values, but the submodel considers - itself responsible, as it relies on the available observations only (see - |EvaluatedValue|). As the simulated discharge is constant, the - variability check detects low variability, so the mean-value-based - residual relies on the four days preceding the forecast (mean observed - ``6.25``, mean simulated ``5.0``) instead of on the single day given by - |AveragingWindow| (which would result in ``1.0``): + | date | discharge | originalq | correctedq | inlet | outlet | + -------------------------------------------------------------------- + | 2000-01-01 | 9.6 | 8.0 | 8.0 | 8.0 | 8.0 | + | 2000-01-02 | 10.8 | 9.0 | 9.0 | 9.0 | 9.0 | + | 2000-01-03 | 12.6 | 10.0 | 10.0 | 10.0 | 10.0 | + | 2000-01-04 | 12.0 | 10.0 | 10.0 | 10.0 | 10.0 | + | 2000-01-05 | 12.0 | 10.0 | 10.0 | 10.0 | 10.0 | + | 2000-01-06 | nan | 11.0 | 11.5 | 11.0 | 11.5 | + | 2000-01-07 | nan | 12.0 | 12.5 | 12.0 | 12.5 | + | 2000-01-08 | nan | 9.0 | 9.45 | 9.0 | 9.45 | + | 2000-01-09 | nan | 6.0 | 6.3 | 6.0 | 6.3 | + | 2000-01-10 | nan | 3.0 | 3.15 | 3.0 | 3.15 | - >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0) as sub: - ... configure(sub) - ... evaluationwindow(3) - ... averagingwindow(1) - ... stationaritycheck( - ... active=True, window=3, ratiominmax=0.5, maxrelsumdelta=0.1, - ... averagingwindow=4 - ... ) - >>> with pub.options.checkseries(False): - ... inputs.discharge.series = 6.0, 6.0, 6.0, 7.0, 6.0, nan, nan, nan, nan, nan -.. integration-test:: - - >>> forecast_test("2000-01-06") - | date | discharge | originalq | correctedq | inlet | outlet | - --------------------------------------------------------------- - | 01/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | - | 02/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | - | 03/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | - | 04/01 | 7.0 | 5.0 | 7.0 | 5.0 | 7.0 | - | 05/01 | 6.0 | 5.0 | 6.0 | 5.0 | 6.0 | - | 06/01 | nan | 5.0 | 6.25 | 5.0 | 6.25 | - | 07/01 | nan | 5.0 | 6.25 | 5.0 | 6.25 | - | 08/01 | nan | 5.0 | 6.25 | 5.0 | 6.25 | - | 09/01 | nan | 5.0 | 6.25 | 5.0 | 6.25 | - | 10/01 | nan | 5.0 | 6.25 | 5.0 | 6.25 | - -Multiple submodels -__________________ - - Finally, we attach two submodels responsible for different discharge ranges. - The first one handles observed discharges below ``5.0`` and the second one all - others. The second one restricts the relative shift to 5 % and the absolute - shift to ``0.25``: - - >>> nmbsubmodels(2) - >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=0) as sub: - ... configure(sub) - ... upperlimit(5.0) - >>> with model.add_outputcorrmodel_v1("statcorr_arima010", position=1) as sub: - ... configure(sub) - ... lowerlimit(5.0) - ... maxrelshift(0.05) - ... maxabsshift(0.25) - >>> element.inlets.inlet.sequences.sim.series = ( - ... 1.0, 2.0, 6.0, 7.0, 3.0, 4.0, 6.0, 8.0, 4.0, 3.0 - ... ) - >>> with pub.options.checkseries(False): - ... inputs.discharge.series = 1.5, 2.5, 8.0, 9.0, 3.5, nan, nan, nan, nan, nan - - During the `historical` run, the second submodel takes over on days three and - four, where its restricted absolute shift prevents reproducing the observations - (the relative shift does not apply, as the current observation is available, - see |Calc_CorrectedValue_V1|). During the `forecast` run, the responsible submodel - does not change (see |EvaluatedValue|). Hence, the first submodel, which was - responsible at the end of the `historical` run, keeps applying the residual of - ``0.5`` unrestricted, even when the forecasted discharge exceeds ``5.0``: - -.. integration-test:: - - >>> forecast_test("2000-01-06") - | date | discharge | originalq | correctedq | inlet | outlet | - --------------------------------------------------------------- - | 01/01 | 1.5 | 1.0 | 1.5 | 1.0 | 1.5 | - | 02/01 | 2.5 | 2.0 | 2.5 | 2.0 | 2.5 | - | 03/01 | 8.0 | 6.0 | 6.25 | 6.0 | 6.25 | - | 04/01 | 9.0 | 7.0 | 7.25 | 7.0 | 7.25 | - | 05/01 | 3.5 | 3.0 | 3.5 | 3.0 | 3.5 | - | 06/01 | nan | 4.0 | 4.5 | 4.0 | 4.5 | - | 07/01 | nan | 6.0 | 6.5 | 6.0 | 6.5 | - | 08/01 | nan | 8.0 | 8.5 | 8.0 | 8.5 | - | 09/01 | nan | 4.0 | 4.5 | 4.0 | 4.5 | - | 10/01 | nan | 3.0 | 3.5 | 3.0 | 3.5 | """ from hydpy.core import modeltools From 5dd5618bf220e4a7f833b32df254f69b64e4e604 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Thu, 12 Nov 2026 10:02:10 +0100 Subject: [PATCH 39/43] Clean docstrings in statcorr_model.py --- hydpy/models/statcorr/statcorr_model.py | 409 ++++++------------------ 1 file changed, 100 insertions(+), 309 deletions(-) diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 42a5c4c4b2..7b5cca373b 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -72,110 +72,53 @@ def __call__( class Calc_OutputCorr_V1(modeltools.Method): - """Apply each |OutputCorrModel_V1| submodel to the current simulated and observed - discharge and combine their results into the corrected discharge. - - This method orchestrates one or more submodels of identical interface type: - - 1. The current simulated discharge (|OriginalQ|) and observed discharge - (|Discharge|) are passed to each attached |OutputCorrModel_V1| submodel - via |OutputCorrModel_V1.set_simulatedvalue| and - |OutputCorrModel_V1.set_observedvalue|. While |Options.simulationmode| - equals `forecast`, |Calc_OutputCorr_V1| passes |numpy.nan| instead of the - actual value of |Discharge|, regardless of whether an observation is - available. This relies on the assumption that a previous `historical` - simulation run already logged all relevant past observations and - simulations (read in as conditions). - 2. Each submodel computes its corrected discharge via - |OutputCorrModel_V1.determine_outputcorrection|. - 3. Each submodel decides for itself, based on its own |Active| flag, its - |CorrectionMode|, and its |LowerLimit| and |UpperLimit| parameters, - whether it is responsible for the current observed discharge (see - |EvaluatedValue| and |OutputCorrModel_V1.is_active|). The corrected - output of the *last* responsible submodel is taken as |CorrectedQ|. When - no submodel is attached or responsible, |CorrectedQ| equals |OriginalQ|. - Hence, attaching several submodels configured for mutually exclusive - discharge ranges lets only the one responsible for the current observed - discharge take effect. + """Let all |OutputCorrModel_V1| submodels correct the current simulated + discharge and take the result of the last responsible one. + + Each submodel decides on its own whether it is responsible (see + |OutputCorrModel_V1.is_active|). If none is, |CorrectedQ| equals |OriginalQ|. + In `forecast` mode (see |Options.simulationmode|), |Calc_OutputCorr_V1| passes + |numpy.nan| instead of |Discharge| to the submodels, which then rely on the + information logged during the preceding `historical` run (see |statcorr_main|). Examples: - Without any attached submodel, the corrected discharge equals the original - discharge: + Without any submodel, |CorrectedQ| equals |OriginalQ|: >>> from hydpy.models.statcorr_main import * >>> parameterstep() - >>> fluxes.originalq = 2.0 - >>> inputs.discharge = 3.0 - >>> model.calc_outputcorr_v1() - >>> fluxes.correctedq - correctedq(2.0) - - With a single attached |statcorr_arima010| submodel, the corrected - discharge is the original discharge plus the most recent residual (here: - ``3.0 - 2.0 = 1.0``, applied to the new original discharge ``2.5``). By - default, we make the submodel responsible for all discharges and disable - the stationarity check so that it never suppresses the correction: - - >>> from numpy import inf - >>> def configure(submodel, lowerlimit=0.0, upperlimit=inf): - ... submodel.parameters.control.active(True) - ... submodel.parameters.control.correctionmode(option="both") - ... submodel.parameters.control.lowerlimit(lowerlimit) - ... submodel.parameters.control.upperlimit(upperlimit) - ... submodel.parameters.control.evaluationwindow(1) - ... submodel.parameters.control.maxnanskip(2) - ... submodel.parameters.control.maxabsshift(100.0) - ... submodel.parameters.control.maxrelshift(10.0) - ... submodel.parameters.control.averagingwindow(0) - ... submodel.parameters.control.transitionsteps(0) - ... submodel.parameters.control.stationaritycheck(active=False) - ... submodel.parameters.control.reductionsteps(1) - - >>> nmbsubmodels(1) - >>> with model.add_outputcorrmodel_v1( - ... "statcorr_arima010", position=0 - ... ) as submodel: - ... configure(submodel) - >>> model.calc_outputcorr_v1() - >>> fluxes.correctedq - correctedq(3.0) - >>> from numpy import nan - >>> fluxes.originalq = 2.5 - >>> inputs.discharge = nan + >>> fluxes.originalq = 3.5 + >>> inputs.discharge = 2.5 >>> model.calc_outputcorr_v1() >>> fluxes.correctedq correctedq(3.5) - We now attach two submodels responsible for different discharge ranges. - The first one covers discharges below 3 m³/s, the second one all - discharges from 3 m³/s upwards: + We attach two |statcorr_arima010| submodels responsible for observed + discharges below and above 3 m³/s, respectively: + >>> from numpy import inf >>> nmbsubmodels(2) - >>> with model.add_outputcorrmodel_v1( - ... "statcorr_arima010", position=0 - ... ) as submodel: - ... configure(submodel, upperlimit=3.0) - >>> with model.add_outputcorrmodel_v1( - ... "statcorr_arima010", position=1 - ... ) as submodel: - ... configure(submodel, lowerlimit=3.0) - - The submodels decide based on the observed discharge. For an observed - discharge of 2.5 m³/s, only the first submodel is responsible, although the - original discharge of 3.5 m³/s lies within the range of the second one. - Hence, the corrected output of the first submodel wins, although the second - submodel comes later and returns the original discharge: + >>> for i, limits in enumerate(((0.0, 3.0), (3.0, inf))): + ... with model.add_outputcorrmodel_v1("statcorr_arima010", position=i): + ... active(True) + ... correctionmode(option="both") + ... lowerlimit(limits[0]) + ... upperlimit(limits[1]) + ... evaluationwindow(1) + ... maxnanskip(2) + ... maxabsshift(100.0) + ... maxrelshift(10.0) + ... averagingwindow(0) + ... transitionsteps(0) + ... stationaritycheck(active=False) + ... reductionsteps(1) + + For an observed discharge of 2.5 m³/s, only the first submodel is + responsible. The second one does not overwrite its result: - >>> fluxes.originalq = 3.5 - >>> inputs.discharge = 2.5 >>> model.calc_outputcorr_v1() >>> fluxes.correctedq correctedq(2.5) - >>> model.outputcorrmodels[0].sequences.fluxes.isactive - isactive(1.0) - >>> model.outputcorrmodels[1].sequences.fluxes.isactive - isactive(0.0) For an observed discharge of 4.0 m³/s, the second submodel takes over: @@ -184,84 +127,17 @@ class Calc_OutputCorr_V1(modeltools.Method): >>> model.calc_outputcorr_v1() >>> fluxes.correctedq correctedq(4.0) - >>> model.outputcorrmodels[0].sequences.fluxes.isactive - isactive(0.0) - >>> model.outputcorrmodels[1].sequences.fluxes.isactive - isactive(1.0) - - If no submodel is responsible, |CorrectedQ| equals |OriginalQ|: - - >>> model.outputcorrmodels[1].parameters.control.active(False) - >>> model.calc_outputcorr_v1() - >>> fluxes.correctedq - correctedq(2.5) - - While |Options.simulationmode| equals ``forecast``, |Calc_OutputCorr_V1| - ignores the actual value of |Discharge| and passes |numpy.nan| to the - submodels instead, relying on their logic to - keep applying the most recently logged residual (see |statcorr_arima010| - for the mechanism and the module docstring of |statcorr_main| for the - assumed workflow of a preceding `historical` run). The main model and - its submodels read the current simulation mode at runtime via - |Model.runsettings|, so changing |Options.simulationmode| takes effect - immediately without updating any parameters: - - >>> nmbsubmodels(1) - >>> with model.add_outputcorrmodel_v1( - ... "statcorr_arima010", position=0 - ... ) as submodel: - ... configure(submodel) - >>> model.parameters.update() - - Two `historical` steps establish a residual of ``0.5``: - - >>> fluxes.originalq = 1.0 - >>> inputs.discharge = 1.5 - >>> model.calc_outputcorr_v1() - >>> fluxes.correctedq - correctedq(1.5) - >>> fluxes.originalq = 2.0 - >>> inputs.discharge = 2.5 - >>> model.calc_outputcorr_v1() - >>> fluxes.correctedq - correctedq(2.5) - Switching to `forecast` mode and feeding an implausible |Discharge| - value (``999.0``, which would dominate the result if it were not - ignored) still reproduces the persisted residual of ``0.5``: + In `forecast` mode, the actual |Discharge| value is ignored, and the + responsible submodel applies its last residual: >>> from hydpy import pub + >>> fluxes.originalq = 3.0 + >>> inputs.discharge = 999.0 >>> with pub.options.simulationmode("forecast"): - ... fluxes.originalq = 3.0 - ... inputs.discharge = 999.0 - ... model.calc_outputcorr_v1() - >>> fluxes.correctedq - correctedq(3.5) - >>> with pub.options.simulationmode("forecast"): - ... fluxes.originalq = 4.0 - ... inputs.discharge = 999.0 ... model.calc_outputcorr_v1() >>> fluxes.correctedq correctedq(4.5) - - Even once the last real observation drops out of the submodel's log - (the current entry plus the two preceding ones due to |MaxNaNSkip|), the - persisted residual keeps applying without limit -- only |ReductionFactor| - (via |StationarityCheck| and |ReductionSteps|, disabled here) could still - fade it out: - - >>> with pub.options.simulationmode("forecast"): - ... fluxes.originalq = 5.0 - ... inputs.discharge = 999.0 - ... model.calc_outputcorr_v1() - >>> fluxes.correctedq - correctedq(5.5) - >>> with pub.options.simulationmode("forecast"): - ... fluxes.originalq = 6.0 - ... inputs.discharge = 999.0 - ... model.calc_outputcorr_v1() - >>> fluxes.correctedq - correctedq(6.5) """ SUBMODELINTERFACES = (statcorrinterfaces.OutputCorrModel_V1,) @@ -289,7 +165,7 @@ class Pass_CorrectedQ_V1(modeltools.Method): """Pass the corrected discharge on to the outlet link sequence, unless |Propagate| is |False|, in which case the original discharge is passed on instead. Either way, |CorrectedQ| remains available for local - output at the current gauge. + output. Basic equation: :math:`Q_{outlets} = CorrectedQ` (if |Propagate|) or @@ -405,7 +281,7 @@ class Calc_EvaluatedValue_V1(modeltools.Method): Examples: |Calc_EvaluatedValue_V1| always relies on the *most recently* logged values - (index ``0`` upwards) and never on the oldest ones sitting near the end of a + (index `0` upwards) and never on the oldest ones sitting near the end of a larger log: >>> from hydpy.models.statcorr import * @@ -595,9 +471,7 @@ class Calc_Residual_ResidualAnchor_V1(modeltools.Method): While |Options.simulationmode| is `forecast`, |Calc_Residual_ResidualAnchor_V1| does not repeat the search and keeps both values of the most recent `historical` - assessment. Hence, the correction persists for the entire forecast horizon - instead of vanishing as soon as the underlying log entry drops out of the - logging window. + assessment. Examples: @@ -681,23 +555,18 @@ class Calc_Stationary_V1(modeltools.Method): |Calc_Stationary_V1| takes the ratio of the minimum and the maximum |LoggedObservation| value within the most recent |StationarityWindow| log entries. Whenever this ratio falls below |RatioMinMax|, it considers the - conditions instationary (|Stationary| is ``0.0``), otherwise stationary - (|Stationary| is ``1.0``). If a |numpy.nan| value within the + conditions instationary (|Stationary| is `0.0`), otherwise stationary + (|Stationary| is `1.0`). If a |numpy.nan| value within the |StationarityWindow| prevents calculating the ratio, |Stationary| keeps the outcome of the previous assessment, so that a single missing observation does - not change the outcome of the stationarity check (which decides on the - reduction of the correction during forecast runs, see - |Calc_ReductionFactor_V1|). + not change the outcome of the stationarity check. While |Options.simulationmode| is `forecast`, |Calc_Stationary_V1| keeps the - outcome of the most recent `historical` assessment. Recomputing it would be - unreliable, as |LoggedObservation| keeps receiving |numpy.nan| values - throughout the forecast (see |Calc_OutputCorr_V1|), which would prevent any new - assessment as soon as the first of them enters the |StationarityWindow|. + outcome of the most recent `historical` assessment. Examples: - The ratio ``4.0 / 5.0 = 0.8`` is not below |RatioMinMax|: + The ratio `4.0 / 5.0 = 0.8` is not below |RatioMinMax|: >>> from hydpy.models.statcorr import * >>> parameterstep() @@ -713,7 +582,7 @@ class Calc_Stationary_V1(modeltools.Method): >>> states.stationary stationary(1.0) - The ratio ``0.5 / 5.0 = 0.1`` is: + The ratio `0.5 / 5.0 = 0.1` is: >>> logs.loggedobservation = 0.5, 5.0, 5.0 >>> model.calc_stationary_v1() @@ -787,19 +656,18 @@ class Calc_ReductionFactor_V1(modeltools.Method): :math:`ReductionFactor = \max \left( 0, 1 - \frac{ForecastStep}{ReductionSteps} \right)` - |ReductionFactor| is ``1.0`` while |Options.simulationmode| is `historical`, so + |ReductionFactor| is `1.0` while |Options.simulationmode| is `historical`, so the stationarity check never dampens the correction of `historical` runs. In - `forecast` mode, instationary conditions (|Stationary| is ``0.0``, as determined + `forecast` mode, instationary conditions (|Stationary| is `0.0`, as determined at the last `historical` step, see |Calc_Stationary_V1|) let |ReductionFactor| - decrease linearly from ``1.0`` in the first forecast step to zero after - |ReductionSteps| forecast steps (counted by |ForecastStep|). Hence, the forecast - starts with the unabated correction, avoiding a jump right at the start of the - forecast horizon. With stationary conditions or the stationarity check - disabled (see |StationarityCheck|), |ReductionFactor| is always ``1.0``. + decrease linearly from `1.0` in the first forecast step to zero after + |ReductionSteps| forecast steps (counted by |ForecastStep|). With stationary + conditions or the stationarity check disabled (see |StationarityCheck|), + |ReductionFactor| is always `1.0`. Examples: - In `historical` mode, |ReductionFactor| is ``1.0``, even under instationary + In `historical` mode, |ReductionFactor| is `1.0`, even under instationary conditions: >>> from hydpy.models.statcorr import * @@ -836,7 +704,7 @@ class Calc_ReductionFactor_V1(modeltools.Method): >>> states.reductionfactor reductionfactor(0.0) - Stationary conditions result in a |ReductionFactor| of ``1.0``: + Stationary conditions result in a |ReductionFactor| of `1.0`: >>> states.stationary(1.0) >>> model.calc_reductionfactor_v1() @@ -964,17 +832,16 @@ class Calc_LowVariability_V1(modeltools.Method): |StationaryAveragingWindow| instead of the |AveragingWindow| (see |Calc_AveragedResidual_V1|). - The variability check is only meaningful under stationary conditions. Hence, - it is part of the stationarity check (see |StationarityCheck|). If enabled, + The variability check is only meaningful under stationary conditions. If enabled, |Calc_LowVariability_V1| considers the variability low (|LowVariability| is - ``1.0``) if the stationarity check (see |Calc_Stationary_V1|) detects stationary + `1.0`) if the stationarity check (see |Calc_Stationary_V1|) detects stationary conditions and |RelSumDelta| does not exceed |MaxRelSumDelta|. Hence, the variability check never interferes with the linear reduction of the correction (see |Calc_ReductionFactor_V1|). A |numpy.nan| value of |RelSumDelta| results - in |LowVariability| being ``0.0``. Like |Calc_RelSumDelta_V1|, + in |LowVariability| being `0.0`. Like |Calc_RelSumDelta_V1|, |Calc_LowVariability_V1| reassesses |LowVariability| only while |Options.simulationmode| is `historical`. With the stationarity check or the - variability check disabled, |LowVariability| is always ``0.0``. + variability check disabled, |LowVariability| is always `0.0`. Examples: @@ -1024,7 +891,7 @@ class Calc_LowVariability_V1(modeltools.Method): lowvariability(1.0) Disabling the variability check or the stationarity check resets - |LowVariability| to ``0.0``, even in `forecast` mode: + |LowVariability| to `0.0`, even in `forecast` mode: >>> derived.stationaryaveragingwindow(0) >>> model.calc_lowvariability_v1() @@ -1067,21 +934,21 @@ class Calc_AveragedResidual_V1(modeltools.Method): |Calc_AveragedResidual_V1| averages the |LoggedObservation| and |LoggedSimulation| entries covering the |AveragingWindow| log positions - immediately preceding the current forecast run (log position ``0`` already holds - the current forecast step's own values, so averaging starts at position ``1``) + immediately preceding the current forecast run (log position `0` already holds + the current forecast step's own values, so averaging starts at position `1`) and stores their difference in |AveragedResidual|. It leaves |AveragedResidual| unchanged whenever |Options.simulationmode| is `historical`, |ForecastStep| is not zero (i.e., beyond the first forecast step), or |AveragingWindow| is zero (mean-value-based correction disabled). When the averaging window contains a |numpy.nan| value, it falls back to the pointwise |Residual| (see - |Calc_Residual_ResidualAnchor_V1|). While |LowVariability| is ``1.0`` (low + |Calc_Residual_ResidualAnchor_V1|). While |LowVariability| is `1.0` (low variability according to the variability check, see |StationarityCheck|), the |StationaryAveragingWindow| replaces the |AveragingWindow|. Examples: - On the first forecast step, the average is taken from log positions ``1`` - and ``2`` (mean observed ``4.0``, mean simulated ``3.0``): + On the first forecast step, the average is taken from log positions `1` + and `2` (mean observed `4.0`, mean simulated `3.0`): >>> from hydpy.models.statcorr import * >>> parameterstep() @@ -1134,8 +1001,8 @@ class Calc_AveragedResidual_V1(modeltools.Method): averagedresidual(-9.0) Under low variability conditions (see |Calc_LowVariability_V1|), the averaging - period covers the single log position ``1`` given by - |StationaryAveragingWindow| (``30.0 - 20.0``), even if |AveragingWindow| is + period covers the single log position `1` given by + |StationaryAveragingWindow| (`30.0 - 20.0`), even if |AveragingWindow| is zero: >>> control.averagingwindow(0) @@ -1197,46 +1064,30 @@ class Calc_CorrectedValue_V1(modeltools.Method): r"""Calculate the corrected value by shifting the current simulated value based on the (damped) residual. - If the submodel is not responsible (|IsActive| is ``0.0``), the corrected value - equals the current simulated value (:math:`sim_0`). Otherwise, how the residual - (:math:`r`) applies depends on how :math:`sim_0` compares to |ResidualAnchor| - (:math:`sim_k`, the simulated value at the time the residual was determined), - with :math:`f_{red}` denoting |ReductionFactor|: - - * If :math:`0 < sim_0 < sim_k`, |Calc_CorrectedValue_V1| shifts :math:`sim_0` - *multiplicatively*, expressing the damped residual as a fraction of - :math:`sim_k` and capping that fraction at |MaxRelShift|: - - :math:`CorrectedValue = sim_0 \cdot \left(1 + \mathrm{clip}\left(r \cdot - f_{red} / sim_k,\ \pm MaxRelShift\right) \right)` - - Applying the residual as a fraction rather than a constant offset keeps the - correction from overshooting or turning negative while the simulated values - recede towards zero. + If the submodel is not responsible (|IsActive| is `0.0`), the corrected value + equals the current simulated value (:math:`sim_0`). Otherwise, the residual + (:math:`r`), damped by |ReductionFactor| (:math:`f_{red}`), applies + multiplicatively if :math:`sim_0` recedes below |ResidualAnchor| + (:math:`sim_k`) and additively otherwise. The multiplicative variant keeps the + correction from overshooting or turning negative while the simulated values + recede towards zero. - * Otherwise (:math:`sim_0 \geq sim_k` or :math:`sim_0 \leq 0`), it shifts - :math:`sim_0` *additively*, capping the damped residual at |MaxAbsShift|: - - :math:`CorrectedValue = sim_0 + \mathrm{clip}\left(r \cdot f_{red},\ - \pm MaxAbsShift\right)` + Basic equations: + :math:`CorrectedValue = sim_0 \cdot \left(1 + \mathrm{clip}\left(r \cdot + f_{red} / sim_k,\ \pm MaxRelShift\right) \right) \quad | \quad 0 < sim_0 < + sim_k` - This includes the `historical` mode whenever the current observation is - available, as :math:`sim_k` then equals :math:`sim_0`. + :math:`CorrectedValue = sim_0 + \mathrm{clip}\left(r \cdot f_{red},\ + \pm MaxAbsShift\right) \quad | \quad else` In `historical` mode (see |Options.simulationmode|), :math:`r` is the pointwise - |Residual|. In `forecast` mode, setting |AveragingWindow| to a value greater - than zero (or |LowVariability| being ``1.0``) switches to the mean-value-based - |AveragedResidual| (see |Calc_AveragedResidual_V1|). Since it generally does - not equal the pointwise residual at the forecast's start, switching to it - abruptly would cause a jump in the corrected value right where the forecast - begins. To avoid this, |Calc_CorrectedValue_V1| starts every forecast run with the - pointwise residual (so the corrected value picks up smoothly where the last - measurement left off) and then linearly blends it towards the mean-value-based - residual over |TransitionSteps| forecast steps (counted by |ForecastStep|), - applying the mean-value-based residual unabated from then on: - - :math:`r = Residual + \min\left(1, \frac{ForecastStep}{TransitionSteps} - \right) \cdot (AveragedResidual - Residual)` + |Residual|. In `forecast` mode, a positive |AveragingWindow| (or |LowVariability| + being `1.0`) lets :math:`r` blend linearly from |Residual| to |AveragedResidual| + over |TransitionSteps| forecast steps, which avoids a jump at the forecast's + start: + + :math:`r = Residual + \min\left(1, \frac{ForecastStep}{TransitionSteps} + \right) \cdot (AveragedResidual - Residual)` Examples: @@ -1252,7 +1103,7 @@ class Calc_CorrectedValue_V1(modeltools.Method): >>> from hydpy import pub >>> pub.options.simulationmode = "historical" >>> fluxes.isactive = 0.0 - >>> states.reductionfactor(1.0) + >>> states.reductionfactor(0.5) >>> states.lowvariability(0.0) >>> states.forecaststep(0.0) >>> states.averagedresidual(0.0) @@ -1263,126 +1114,66 @@ class Calc_CorrectedValue_V1(modeltools.Method): >>> fluxes.correctedvalue correctedvalue(6.0) - The current simulated value exceeds |ResidualAnchor|, so the residual - applies additively: + The current simulated value exceeds |ResidualAnchor|, so the damped + residual applies additively, capped by |MaxAbsShift|: >>> fluxes.isactive = 1.0 >>> model.calc_correctedvalue_v1() >>> fluxes.correctedvalue - correctedvalue(7.0) - - |ReductionFactor| dampens the residual: - - >>> states.reductionfactor(0.5) - >>> model.calc_correctedvalue_v1() - >>> fluxes.correctedvalue correctedvalue(6.5) - - |MaxAbsShift| caps the additive shift: - - >>> states.reductionfactor(1.0) >>> control.maxabsshift(0.2) >>> model.calc_correctedvalue_v1() >>> fluxes.correctedvalue correctedvalue(6.2) - For a *receding* simulation (the current simulated value is below - |ResidualAnchor|), the residual applies multiplicatively: + For a receding simulation, the residual applies multiplicatively, capped by + |MaxRelShift|: - >>> control.maxabsshift(100.0) + >>> states.reductionfactor(1.0) >>> states.residual(2.0) >>> states.residualanchor(10.0) >>> logs.loggedsimulation = 2.0 >>> model.calc_correctedvalue_v1() >>> fluxes.correctedvalue correctedvalue(2.4) - - Limiting |MaxRelShift| to ``0.1`` caps that fraction at 10 % before it is - converted back into an absolute shift: - >>> control.maxrelshift(0.1) >>> model.calc_correctedvalue_v1() >>> fluxes.correctedvalue correctedvalue(2.2) - If the current simulated value equals |ResidualAnchor| (as in `historical` - mode whenever the current observation is available), the residual applies - additively, so |MaxRelShift| has no effect: - - >>> control.maxrelshift(0.0) - >>> logs.loggedsimulation = 10.0 - >>> model.calc_correctedvalue_v1() - >>> fluxes.correctedvalue - correctedvalue(12.0) - - The same holds for a non-positive current simulated value: - - >>> logs.loggedsimulation = 0.0 - >>> model.calc_correctedvalue_v1() - >>> fluxes.correctedvalue - correctedvalue(2.0) - >>> control.maxrelshift(10.0) - - Now, we demonstrate the transition from the pointwise residual (``1.0``) - to the mean-value-based residual (``2.5``) over two forecast steps. On the - first forecast step, |Calc_CorrectedValue_V1| applies the pointwise residual - unabated: + Halfway through a forecast transition from the pointwise residual (`1.0`) + to the mean-value-based residual (`2.5`), their average (`1.75`) applies: + >>> control.maxabsshift(100.0) >>> control.averagingwindow(2) >>> control.transitionsteps(2) >>> pub.options.simulationmode = "forecast" >>> states.residual(1.0) >>> states.residualanchor(8.0) >>> states.averagedresidual(2.5) - >>> logs.loggedsimulation = 10.0 - >>> model.calc_correctedvalue_v1() - >>> fluxes.correctedvalue - correctedvalue(11.0) - - Halfway through the transition, the applied residual is the average of both - (``1.75``): - >>> states.forecaststep(1.0) >>> logs.loggedsimulation = 11.0 >>> model.calc_correctedvalue_v1() >>> fluxes.correctedvalue correctedvalue(12.75) - Once the transition period has elapsed, the full mean-value-based residual - applies: - - >>> states.forecaststep(2.0) - >>> logs.loggedsimulation = 12.0 - >>> model.calc_correctedvalue_v1() - >>> fluxes.correctedvalue - correctedvalue(14.5) - - Setting |TransitionSteps| to zero applies the mean-value-based residual - immediately: - - >>> control.transitionsteps(0) - >>> states.forecaststep(0.0) - >>> model.calc_correctedvalue_v1() - >>> fluxes.correctedvalue - correctedvalue(14.5) - - Under low variability conditions, the - mean-value-based residual applies even if - |AveragingWindow| is zero: + Under low variability conditions, the mean-value-based residual also + applies for a zero |AveragingWindow|, and without delay for zero + |TransitionSteps|: >>> control.averagingwindow(0) + >>> control.transitionsteps(0) >>> states.lowvariability(1.0) >>> model.calc_correctedvalue_v1() >>> fluxes.correctedvalue - correctedvalue(14.5) + correctedvalue(13.5) - In `historical` mode, |Calc_CorrectedValue_V1| always relies on the pointwise - residual, so that the corrected value reproduces the current observation: + In `historical` mode, only the pointwise residual counts: >>> pub.options.simulationmode = "historical" >>> model.calc_correctedvalue_v1() >>> fluxes.correctedvalue - correctedvalue(13.0) + correctedvalue(12.0) """ CONTROLPARAMETERS = ( From d110bc02f2613eff99a34b1fe4165ec59a9f1879 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Thu, 12 Nov 2026 10:33:16 +0100 Subject: [PATCH 40/43] Harmonize docstrings in statcorr_model.py with other hydpy models --- hydpy/models/statcorr/statcorr_model.py | 92 ++----------------------- 1 file changed, 7 insertions(+), 85 deletions(-) diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 7b5cca373b..55b500053d 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -932,18 +932,11 @@ class Calc_AveragedResidual_V1(modeltools.Method): r"""Determine the mean-value-based residual once, at the first forecast step, and freeze it for the remainder of the current forecast horizon. - |Calc_AveragedResidual_V1| averages the |LoggedObservation| and - |LoggedSimulation| entries covering the |AveragingWindow| log positions - immediately preceding the current forecast run (log position `0` already holds - the current forecast step's own values, so averaging starts at position `1`) - and stores their difference in |AveragedResidual|. It leaves |AveragedResidual| - unchanged whenever |Options.simulationmode| is `historical`, |ForecastStep| is - not zero (i.e., beyond the first forecast step), or |AveragingWindow| is zero - (mean-value-based correction disabled). When the averaging window contains a - |numpy.nan| value, it falls back to the pointwise |Residual| (see - |Calc_Residual_ResidualAnchor_V1|). While |LowVariability| is `1.0` (low - variability according to the variability check, see |StationarityCheck|), the - |StationaryAveragingWindow| replaces the |AveragingWindow|. + This method averages |LoggedObservation| and |LoggedSimulation| over the + |AveragingWindow| and stores the difference in |AveragedResidual|. + If |Options.simulationmode| is `historical`, or |ForecastStep| is + not zero, |AveragedResidual| is unchanged. When the averaging window contains a + |numpy.nan| value, it falls back to the pointwise |Residual|. Examples: @@ -1265,79 +1258,8 @@ def __call__(model: modeltools.Model, /) -> None: class Determine_OutputCorrection_V1(modeltools.AutoMethod): - r"""Interface method that calculates the corrected value using an - ARIMA(0,1,0) error model. - - |Determine_OutputCorrection_V1| executes the following submethods, which take - the current simulation mode directly from |Options.simulationmode| (via - |Model.runsettings|): - - * |Calc_EvaluatedValue_V1| and |Calc_IsActive_V1| decide whether the submodel - is responsible for the current simulated value. - * |Calc_Residual_ResidualAnchor_V1| determines the most recent pointwise - residual. - * |Calc_Stationary_V1| and |Calc_ReductionFactor_V1| dampen the correction under - instationary conditions. - * |Calc_RelSumDelta_V1|, |Calc_LowVariability_V1|, and - |Calc_AveragedResidual_V1| determine the mean-value-based residual for - forecast runs. - * |Calc_CorrectedValue_V1| applies the resulting residual to the current simulated - value. - * |Update_ForecastStep_V1| counts the forecast steps. - - All submethods update the internal states even when the submodel is not - responsible, so that a submodel taking over responsibility starts with - up-to-date information. While |Options.simulationmode| is `forecast`, they keep - the outcomes of the most recent `historical` assessment (the responsibility, the - pointwise residual, and the stationarity and variability assessments), so that - only |ReductionFactor| and, if configured, the blend towards |AveragedResidual| - can still change the correction once a forecast run is underway. - - Example: - - In `historical` mode, the correction reproduces the most recent - observation: - - >>> from hydpy.models.statcorr import * - >>> parameterstep() - >>> from numpy import inf, nan - >>> derived.nmblogentries(3) - >>> control.evaluationwindow(3) - >>> control.active(True) - >>> control.correctionmode(option="both") - >>> control.lowerlimit(0.0) - >>> control.upperlimit(inf) - >>> control.stationaritycheck(active=False) - >>> derived.stationaritywindow.update() - >>> derived.ratiominmax.update() - >>> derived.maxrelsumdelta.update() - >>> derived.stationaryaveragingwindow.update() - >>> control.reductionsteps(2) - >>> control.maxnanskip(2) - >>> control.maxabsshift(100.0) - >>> control.maxrelshift(10.0) - >>> control.averagingwindow(0) - >>> control.transitionsteps(0) - >>> logs.loggedsimulation = 5.0, 3.0, 2.0 - >>> logs.loggedobservation = 6.0, 4.0, 3.0 - >>> model.determine_outputcorrection_v1() - >>> fluxes.isactive - isactive(1.0) - >>> fluxes.correctedvalue - correctedvalue(6.0) - - In `forecast` mode, the residual of the last `historical` step persists: - - >>> logs.loggedsimulation = 7.0, 5.0, 3.0 - >>> logs.loggedobservation = nan, 6.0, 4.0 - >>> from hydpy import pub - >>> with pub.options.simulationmode("forecast"): - ... model.determine_outputcorrection_v1() - >>> fluxes.correctedvalue - correctedvalue(8.0) - >>> states.forecaststep - forecaststep(1.0) - """ + """Determine the corrected value based on the residuals between the observed and + the simulated values.""" SUBMETHODS = ( Calc_EvaluatedValue_V1, From 1b8e1dc31651c3fb67b1f18177072dd6cda5f023 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Thu, 12 Nov 2026 13:27:44 +0100 Subject: [PATCH 41/43] Simplify docstrings and examples in statcorr_model.py --- hydpy/models/statcorr/statcorr_model.py | 317 +++++------------------- 1 file changed, 68 insertions(+), 249 deletions(-) diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 55b500053d..082cb5152b 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -261,62 +261,30 @@ def __call__(model: modeltools.Model, observedvalue: float, /) -> None: class Calc_EvaluatedValue_V1(modeltools.Method): - r"""Calculate the mean of the available (non-|numpy.nan|) values among the - |EvaluationWindow| most recent |LoggedObservation| values while - |Options.simulationmode| is `historical`. + r"""Calculate the mean of the most recent observed values. Basic equation: :math:`EvaluatedValue = \frac{1}{n} \sum_{i=0}^{EvaluationWindow-1} LoggedObservation_i` - The sum covers only the available values, and :math:`n` is their number. If all - values are |numpy.nan|, |EvaluatedValue| keeps its previous value, so the - responsible submodel (see |Calc_IsActive_V1|) does not change during gaps in the - observations. + If all values are |numpy.nan|, |EvaluatedValue| keeps its + previous value. The same holds in `forecast` mode. - While |Options.simulationmode| is `forecast`, |Calc_EvaluatedValue_V1| keeps the - value of the most recent `historical` assessment, so the responsible submodel - does not change throughout the forecast horizon. - - Examples: + Example: - |Calc_EvaluatedValue_V1| always relies on the *most recently* logged values - (index `0` upwards) and never on the oldest ones sitting near the end of a - larger log: + The mean of the first three log entries without the missing one is `3.0`: >>> from hydpy.models.statcorr import * >>> parameterstep() >>> from numpy import nan >>> control.evaluationwindow(3) >>> derived.nmblogentries(5) - >>> logs.loggedobservation = 1.0, 2.0, 6.0, 8.0, 9.0 + >>> logs.loggedobservation = 1.0, nan, 5.0, 8.0, 9.0 >>> from hydpy import pub >>> pub.options.simulationmode = "historical" >>> model.calc_evaluatedvalue_v1() >>> states.evaluatedvalue evaluatedvalue(3.0) - - Missing observations are left out: - - >>> logs.loggedobservation = 1.0, nan, 5.0, 8.0, 9.0 - >>> model.calc_evaluatedvalue_v1() - >>> states.evaluatedvalue - evaluatedvalue(3.0) - - If no observation is available, |EvaluatedValue| keeps its previous value: - - >>> logs.loggedobservation = nan, nan, nan, 8.0, 9.0 - >>> model.calc_evaluatedvalue_v1() - >>> states.evaluatedvalue - evaluatedvalue(3.0) - - In `forecast` mode, |EvaluatedValue| stays frozen: - - >>> pub.options.simulationmode = "forecast" - >>> logs.loggedobservation = 10.0, 10.0, 10.0, nan, nan - >>> model.calc_evaluatedvalue_v1() - >>> states.evaluatedvalue - evaluatedvalue(3.0) >>> del pub.options.simulationmode """ @@ -344,30 +312,24 @@ class Calc_IsActive_V1(modeltools.Method): r"""Decide whether the submodel is responsible for correcting the current simulated value. - Each submodel is responsible for a specific value range only. It corrects the - simulated values only while |Active| is |True|, |CorrectionMode| allows a + The submodel is responsible if |Active| is |True|, |CorrectionMode| allows a correction in the current simulation mode (see |Options.simulationmode|), and - |EvaluatedValue| (:math:`\overline{obs}`) lies within the range defined by - |LowerLimit| and |UpperLimit|: - - :math:`LowerLimit \leq \overline{obs} < UpperLimit` + |EvaluatedValue| (:math:`\overline{obs}`) lies within its value range: - As long as |EvaluatedValue| is |numpy.nan| (before the first observation is - available), the submodel is not active. + :math:`LowerLimit \leq \overline{obs} < UpperLimit` - |Calc_IsActive_V1| checks this condition in each simulation step, so changes of - |Active|, |CorrectionMode|, |LowerLimit|, or |UpperLimit| take effect - immediately. + For a |numpy.nan| value of |EvaluatedValue|, the submodel is not responsible. Examples: + |LowerLimit| is inclusive: + >>> from hydpy.models.statcorr import * >>> parameterstep() - >>> from numpy import inf >>> control.active(True) >>> control.correctionmode(option="both") - >>> control.lowerlimit(0.0) - >>> control.upperlimit(inf) + >>> control.lowerlimit(3.0) + >>> control.upperlimit(5.0) >>> states.evaluatedvalue(3.0) >>> from hydpy import pub >>> pub.options.simulationmode = "historical" @@ -375,52 +337,18 @@ class Calc_IsActive_V1(modeltools.Method): >>> fluxes.isactive isactive(1.0) - |UpperLimit| is exclusive, while |LowerLimit| is inclusive: - - >>> control.upperlimit(3.0) - >>> model.calc_isactive_v1() - >>> fluxes.isactive - isactive(0.0) - - >>> control.lowerlimit(3.0) - >>> control.upperlimit(inf) - >>> model.calc_isactive_v1() - >>> fluxes.isactive - isactive(1.0) - - Setting |Active| to |False| disables the correction completely: + With |CorrectionMode| set to `forecast`, the submodel is responsible only in + `forecast` mode: - >>> control.active(False) - >>> model.calc_isactive_v1() - >>> fluxes.isactive - isactive(0.0) - - |CorrectionMode| restricts the correction to one simulation mode. With - `forecast`, the submodel does not correct the simulated values in the - `historical` mode: - - >>> control.active(True) >>> control.correctionmode(option="forecast") >>> model.calc_isactive_v1() >>> fluxes.isactive isactive(0.0) - >>> pub.options.simulationmode = "forecast" >>> model.calc_isactive_v1() >>> fluxes.isactive isactive(1.0) - - With `historical`, it is the other way round: - - >>> control.correctionmode(option="historical") - >>> model.calc_isactive_v1() - >>> fluxes.isactive - isactive(0.0) - - >>> pub.options.simulationmode = "historical" - >>> model.calc_isactive_v1() - >>> fluxes.isactive - isactive(1.0) + >>> del pub.options.simulationmode """ CONTROLPARAMETERS = ( @@ -454,28 +382,23 @@ def __call__(model: modeltools.Model, /) -> None: class Calc_Residual_ResidualAnchor_V1(modeltools.Method): - r"""Determine the most recent pointwise residual (observed minus simulated - value) and the corresponding simulated value while |Options.simulationmode| is - `historical`. + r"""Determine the most recent residual (observed minus simulated value) and + the corresponding simulated value. Basic equations: :math:`Residual = LoggedObservation_k - LoggedSimulation_k` :math:`ResidualAnchor = LoggedSimulation_k` - :math:`k` denotes the most recent log index for which the observed value is not - |numpy.nan|. The search skips at most |MaxNaNSkip| preceding log entries with - missing observations (or searches the entire log, whichever is smaller). When - no observation is available within that range, |Residual| and |ResidualAnchor| - are set to zero, so no correction applies. - - While |Options.simulationmode| is `forecast`, |Calc_Residual_ResidualAnchor_V1| - does not repeat the search and keeps both values of the most recent `historical` - assessment. + :math:`k` is the most recent log index with an available observation. The + search skips at most |MaxNaNSkip| missing observations. If it finds no + observation, |Residual| and |ResidualAnchor| are zero. In `forecast` mode (see + |Options.simulationmode|), both keep their previous values. Examples: - If the most recent observation is available, it determines the residual: + The two most recent observations are missing, so the residual stems from + the third log entry: >>> from hydpy.models.statcorr import * >>> parameterstep() @@ -485,41 +408,17 @@ class Calc_Residual_ResidualAnchor_V1(modeltools.Method): >>> from hydpy import pub >>> pub.options.simulationmode = "historical" >>> logs.loggedsimulation = 5.0, 3.0, 2.0 - >>> logs.loggedobservation = 6.0, 4.0, 3.0 - >>> model.calc_residual_residualanchor_v1() - >>> states.residual, states.residualanchor - (residual(1.0), residualanchor(5.0)) - - If the two most recent observations are missing, the residual stems from - the third log entry: - >>> logs.loggedobservation = nan, nan, 3.0 >>> model.calc_residual_residualanchor_v1() >>> states.residual, states.residualanchor (residual(1.0), residualanchor(2.0)) - Restricting |MaxNaNSkip| so that the search does not reach this entry results - in zero values: + With |MaxNaNSkip| set to one, the search does not reach this entry: >>> control.maxnanskip(1) >>> model.calc_residual_residualanchor_v1() >>> states.residual, states.residualanchor (residual(0.0), residualanchor(0.0)) - - A |MaxNaNSkip| value exceeding the log length is no problem: - - >>> control.maxnanskip(5) - >>> model.calc_residual_residualanchor_v1() - >>> states.residual, states.residualanchor - (residual(1.0), residualanchor(2.0)) - - In `forecast` mode, both values stay frozen: - - >>> pub.options.simulationmode = "forecast" - >>> logs.loggedobservation = nan, nan, nan - >>> model.calc_residual_residualanchor_v1() - >>> states.residual, states.residualanchor - (residual(1.0), residualanchor(2.0)) >>> del pub.options.simulationmode """ @@ -548,21 +447,19 @@ def __call__(model: modeltools.Model, /) -> None: class Calc_Stationary_V1(modeltools.Method): - r"""Assess whether the observed values behave in a stationary way while the - stationarity check is enabled (see |StationarityCheck|) and - |Options.simulationmode| is `historical`. - - |Calc_Stationary_V1| takes the ratio of the minimum and the maximum - |LoggedObservation| value within the most recent |StationarityWindow| log - entries. Whenever this ratio falls below |RatioMinMax|, it considers the - conditions instationary (|Stationary| is `0.0`), otherwise stationary - (|Stationary| is `1.0`). If a |numpy.nan| value within the - |StationarityWindow| prevents calculating the ratio, |Stationary| keeps the - outcome of the previous assessment, so that a single missing observation does - not change the outcome of the stationarity check. - - While |Options.simulationmode| is `forecast`, |Calc_Stationary_V1| keeps the - outcome of the most recent `historical` assessment. + r"""Check whether the observed values are stationary. + + Basic equation: + :math:`Stationary = \begin{cases} + 0 &|\ min / max < RatioMinMax \ + 1 &|\ else + \end{cases}` + + :math:`min` and :math:`max` are the smallest and the largest |LoggedObservation| + value within the |StationarityWindow|. If this window contains a |numpy.nan| + value, |Stationary| keeps its previous value. The same holds in `forecast` mode + (see |Options.simulationmode|) and if the stationarity check is disabled (see + |StationarityCheck|). Examples: @@ -589,30 +486,14 @@ class Calc_Stationary_V1(modeltools.Method): >>> states.stationary stationary(0.0) - A single missing observation within the |StationarityWindow| prevents a new + A missing observation within the |StationarityWindow| prevents a new assessment: >>> logs.loggedobservation = 4.0, nan, 5.0 >>> model.calc_stationary_v1() >>> states.stationary stationary(0.0) - - In `forecast` mode, |Stationary| stays frozen: - - >>> pub.options.simulationmode = "forecast" - >>> logs.loggedobservation = 4.0, 5.0, 5.0 - >>> model.calc_stationary_v1() - >>> states.stationary - stationary(0.0) - - The same holds when the stationarity check is disabled: - - >>> control.stationaritycheck(active=False) - >>> derived.stationaritywindow.update() - >>> pub.options.simulationmode = "historical" - >>> model.calc_stationary_v1() - >>> states.stationary - stationary(0.0) + >>> del pub.options.simulationmode """ DERIVEDPARAMETERS = ( @@ -649,21 +530,18 @@ def __call__(model: modeltools.Model, /) -> None: class Calc_ReductionFactor_V1(modeltools.Method): - r"""Calculate the factor for damping the correction during forecast runs based - on the outcome of the stationarity check. + r"""Calculate the factor for reducing the correction in forecast mode under + instationary conditions. - Basic equation (under instationary conditions in `forecast` mode): + Basic equation: :math:`ReductionFactor = \max \left( 0, 1 - \frac{ForecastStep}{ReductionSteps} \right)` - |ReductionFactor| is `1.0` while |Options.simulationmode| is `historical`, so - the stationarity check never dampens the correction of `historical` runs. In - `forecast` mode, instationary conditions (|Stationary| is `0.0`, as determined - at the last `historical` step, see |Calc_Stationary_V1|) let |ReductionFactor| - decrease linearly from `1.0` in the first forecast step to zero after - |ReductionSteps| forecast steps (counted by |ForecastStep|). With stationary - conditions or the stationarity check disabled (see |StationarityCheck|), - |ReductionFactor| is always `1.0`. + The equation applies only in `forecast` mode (see |Options.simulationmode|) and + only if |Stationary| is `0.0` (see |Calc_Stationary_V1|). Then, + |ReductionFactor| decreases linearly from `1.0` to zero within |ReductionSteps| + forecast steps. In all other cases, including a disabled stationarity check + (see |StationarityCheck|), |ReductionFactor| is `1.0`. Examples: @@ -832,22 +710,20 @@ class Calc_LowVariability_V1(modeltools.Method): |StationaryAveragingWindow| instead of the |AveragingWindow| (see |Calc_AveragedResidual_V1|). - The variability check is only meaningful under stationary conditions. If enabled, - |Calc_LowVariability_V1| considers the variability low (|LowVariability| is - `1.0`) if the stationarity check (see |Calc_Stationary_V1|) detects stationary - conditions and |RelSumDelta| does not exceed |MaxRelSumDelta|. Hence, the - variability check never interferes with the linear reduction of the correction - (see |Calc_ReductionFactor_V1|). A |numpy.nan| value of |RelSumDelta| results - in |LowVariability| being `0.0`. Like |Calc_RelSumDelta_V1|, - |Calc_LowVariability_V1| reassesses |LowVariability| only while - |Options.simulationmode| is `historical`. With the stationarity check or the - variability check disabled, |LowVariability| is always `0.0`. + Basic equation: + :math:`LowVariability = \begin{cases} + 1 &|\ Stationary = 1 \ \land \ RelSumDelta \leq MaxRelSumDelta \ + 0 &|\ else + \end{cases}` + + With the stationarity check or the variability check disabled (see + |StationarityCheck|), |LowVariability| is always `0.0`. In `forecast` mode, it + keeps its previous value. Examples: >>> from hydpy.models.statcorr import * >>> parameterstep() - >>> from numpy import nan >>> derived.stationaryaveragingwindow(3) >>> derived.maxrelsumdelta(0.2) >>> derived.stationaritywindow(3) @@ -859,48 +735,17 @@ class Calc_LowVariability_V1(modeltools.Method): >>> states.lowvariability lowvariability(1.0) - >>> states.relsumdelta(0.4) - >>> model.calc_lowvariability_v1() - >>> states.lowvariability - lowvariability(0.0) - - >>> states.relsumdelta(nan) - >>> model.calc_lowvariability_v1() - >>> states.lowvariability - lowvariability(0.0) - - Instationary conditions according to the stationarity check prevent the - variability check from detecting low variability: - - >>> states.relsumdelta(0.2) >>> states.stationary(0.0) >>> model.calc_lowvariability_v1() >>> states.lowvariability lowvariability(0.0) - In `forecast` mode, |LowVariability| stays frozen: + Disabling the variability check resets |LowVariability| to `0.0`, even in + `forecast` mode: - >>> states.stationary(1.0) - >>> model.calc_lowvariability_v1() - >>> states.lowvariability - lowvariability(1.0) >>> pub.options.simulationmode = "forecast" - >>> states.relsumdelta(0.4) - >>> model.calc_lowvariability_v1() - >>> states.lowvariability - lowvariability(1.0) - - Disabling the variability check or the stationarity check resets - |LowVariability| to `0.0`, even in `forecast` mode: - - >>> derived.stationaryaveragingwindow(0) - >>> model.calc_lowvariability_v1() - >>> states.lowvariability - lowvariability(0.0) - - >>> derived.stationaryaveragingwindow(3) >>> states.lowvariability(1.0) - >>> derived.stationaritywindow(0) + >>> derived.stationaryaveragingwindow(0) >>> model.calc_lowvariability_v1() >>> states.lowvariability lowvariability(0.0) @@ -936,7 +781,8 @@ class Calc_AveragedResidual_V1(modeltools.Method): |AveragingWindow| and stores the difference in |AveragedResidual|. If |Options.simulationmode| is `historical`, or |ForecastStep| is not zero, |AveragedResidual| is unchanged. When the averaging window contains a - |numpy.nan| value, it falls back to the pointwise |Residual|. + |numpy.nan| value, it falls back to the pointwise |Residual|. If |LowVariability| + is `1.0`, |StationaryAveragingWindow| replaces |AveragingWindow|. Examples: @@ -960,46 +806,19 @@ class Calc_AveragedResidual_V1(modeltools.Method): >>> states.averagedresidual averagedresidual(1.0) - On any later forecast step and in `historical` mode, the previously - determined value remains unchanged, regardless of the current log contents: - - >>> logs.loggedsimulation = 3.0, 20.0, 40.0 - >>> logs.loggedobservation = nan, 30.0, 50.0 - >>> states.forecaststep(1.0) - >>> model.calc_averagedresidual_v1() - >>> states.averagedresidual - averagedresidual(1.0) - - >>> states.forecaststep(0.0) - >>> pub.options.simulationmode = "historical" - >>> model.calc_averagedresidual_v1() - >>> states.averagedresidual - averagedresidual(1.0) - - Setting |AveragingWindow| to zero disables mean-value-based correction: + A |numpy.nan| value within the averaging window results in |Residual|: - >>> pub.options.simulationmode = "forecast" - >>> control.averagingwindow(0) - >>> model.calc_averagedresidual_v1() - >>> states.averagedresidual - averagedresidual(1.0) - - A |numpy.nan| value within the averaging window makes - |Calc_AveragedResidual_V1| fall back to |Residual|: - - >>> control.averagingwindow(2) - >>> logs.loggedobservation = nan, nan, 50.0 + >>> logs.loggedobservation = nan, nan, 5.0 >>> model.calc_averagedresidual_v1() >>> states.averagedresidual averagedresidual(-9.0) - Under low variability conditions (see |Calc_LowVariability_V1|), the averaging - period covers the single log position `1` given by - |StationaryAveragingWindow| (`30.0 - 20.0`), even if |AveragingWindow| is - zero: + Under low variability conditions, |StationaryAveragingWindow| (here, the + single log position `1`) applies, even if |AveragingWindow| is zero: >>> control.averagingwindow(0) >>> states.lowvariability(1.0) + >>> logs.loggedsimulation = 3.0, 20.0, 40.0 >>> logs.loggedobservation = nan, 30.0, nan >>> model.calc_averagedresidual_v1() >>> states.averagedresidual From 9f53bed6330c7f35903d81dc299fc63b335fe188 Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Thu, 12 Nov 2026 18:03:45 +0100 Subject: [PATCH 42/43] Simplify docstrings and examples in statcorr_model.py --- hydpy/models/statcorr/statcorr_model.py | 95 ++++++++----------------- 1 file changed, 29 insertions(+), 66 deletions(-) diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 082cb5152b..4201881e87 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -46,9 +46,7 @@ def __call__(model: modeltools.Model, /) -> None: class Calc_OutputCorr_OutputCorrModel_V1(modeltools.Method): """Let a submodel that complies with the |OutputCorrModel_V1| interface correct - the current simulated discharge and take over its result if it is active. - - See |Calc_OutputCorr_V1| for examples. + the current simulated discharge and use its result if it is active. """ SUBMODELINTERFACES = (statcorrinterfaces.OutputCorrModel_V1,) @@ -72,14 +70,12 @@ def __call__( class Calc_OutputCorr_V1(modeltools.Method): - """Let all |OutputCorrModel_V1| submodels correct the current simulated - discharge and take the result of the last responsible one. + """Let all |OutputCorrModel_V1| submodels calculate the correction of the + current simulated discharge and take the result of the last responsible one. - Each submodel decides on its own whether it is responsible (see - |OutputCorrModel_V1.is_active|). If none is, |CorrectedQ| equals |OriginalQ|. - In `forecast` mode (see |Options.simulationmode|), |Calc_OutputCorr_V1| passes - |numpy.nan| instead of |Discharge| to the submodels, which then rely on the - information logged during the preceding `historical` run (see |statcorr_main|). + |Calc_OutputCorr_OutputCorrModel_V1| is called for each submodel in the order in + which the submodels are added. If a submodel is active, it overwrites |CorrectedQ|, + so the last active submodel determines the final corrected discharge. Examples: @@ -120,7 +116,7 @@ class Calc_OutputCorr_V1(modeltools.Method): >>> fluxes.correctedq correctedq(2.5) - For an observed discharge of 4.0 m³/s, the second submodel takes over: + For an observed discharge of 4.0 m³/s, the second submodel is responsible: >>> fluxes.originalq = 2.5 >>> inputs.discharge = 4.0 @@ -162,10 +158,9 @@ def __call__(model: modeltools.Model, /) -> None: class Pass_CorrectedQ_V1(modeltools.Method): - """Pass the corrected discharge on to the outlet link sequence, unless - |Propagate| is |False|, in which case the original discharge is - passed on instead. Either way, |CorrectedQ| remains available for local - output. + """Pass the corrected discharge to the outlet link sequence |statcorr_outlets.Q|, + unless |Propagate| is |False|, in which case the original discharge is + passed on instead. Basic equation: :math:`Q_{outlets} = CorrectedQ` (if |Propagate|) or @@ -234,8 +229,6 @@ class Set_ObservedValue_V1(modeltools.Method): by shifting the previously buffered values one position to the right and storing the new value at position 0. - The given value may be |numpy.nan| when no observation is available. - Example: >>> from hydpy.models.statcorr import * @@ -451,7 +444,7 @@ class Calc_Stationary_V1(modeltools.Method): Basic equation: :math:`Stationary = \begin{cases} - 0 &|\ min / max < RatioMinMax \ + 0 &|\ min / max < RatioMinMax \\ 1 &|\ else \end{cases}` @@ -540,8 +533,9 @@ class Calc_ReductionFactor_V1(modeltools.Method): The equation applies only in `forecast` mode (see |Options.simulationmode|) and only if |Stationary| is `0.0` (see |Calc_Stationary_V1|). Then, |ReductionFactor| decreases linearly from `1.0` to zero within |ReductionSteps| - forecast steps. In all other cases, including a disabled stationarity check - (see |StationarityCheck|), |ReductionFactor| is `1.0`. + forecast steps (or immediately, if |ReductionSteps| is zero). In all other + cases, including a disabled stationarity check (see |StationarityCheck|), + |ReductionFactor| is `1.0`. Examples: @@ -581,21 +575,6 @@ class Calc_ReductionFactor_V1(modeltools.Method): >>> model.calc_reductionfactor_v1() >>> states.reductionfactor reductionfactor(0.0) - - Stationary conditions result in a |ReductionFactor| of `1.0`: - - >>> states.stationary(1.0) - >>> model.calc_reductionfactor_v1() - >>> states.reductionfactor - reductionfactor(1.0) - - The same holds when the stationarity check is disabled: - - >>> states.stationary(0.0) - >>> derived.stationaritywindow(0) - >>> model.calc_reductionfactor_v1() - >>> states.reductionfactor - reductionfactor(1.0) >>> del pub.options.simulationmode """ @@ -622,11 +601,10 @@ def __call__(model: modeltools.Model, /) -> None: class Calc_RelSumDelta_V1(modeltools.Method): - r"""Calculate the relative sum of the absolute changes between successive - simulated values while the variability check is enabled (see - |StationarityCheck|) and |Options.simulationmode| is `historical`. + r"""Calculate the sum of the absolute changes between successive simulated + values relative to their mean. - Basic equation: + Basic equations: :math:`RelSumDelta = \frac{1}{\overline{sim}} \sum_{i=0}^{EvaluationWindow-2} |LoggedSimulation_i - LoggedSimulation_{i+1}|` @@ -634,12 +612,10 @@ class Calc_RelSumDelta_V1(modeltools.Method): :math:`\overline{sim} = \frac{1}{EvaluationWindow} \sum_{i=0}^{EvaluationWindow-1} LoggedSimulation_i` - The variability check assesses the simulated values only, so it relates their - changes to their own mean (:math:`\overline{sim}`) within the |EvaluationWindow|. - For a non-positive or missing :math:`\overline{sim}`, |RelSumDelta| is - |numpy.nan|. While |Options.simulationmode| is `forecast`, - |Calc_RelSumDelta_V1| keeps the value of the most recent `historical` - assessment. + If :math:`\overline{sim}` is not positive or |numpy.nan|, |RelSumDelta| is + |numpy.nan|. In `forecast` mode (see |Options.simulationmode|) and if the + variability check is disabled (see |StationarityCheck|), |RelSumDelta| keeps + its previous value. Examples: @@ -659,21 +635,7 @@ class Calc_RelSumDelta_V1(modeltools.Method): >>> model.calc_relsumdelta_v1() >>> states.relsumdelta relsumdelta(nan) - - In `forecast` mode or with the variability check disabled, |RelSumDelta| - stays unchanged: - - >>> logs.loggedsimulation = 9.0, 10.0, 11.0 - >>> pub.options.simulationmode = "forecast" - >>> model.calc_relsumdelta_v1() - >>> states.relsumdelta - relsumdelta(nan) - - >>> pub.options.simulationmode = "historical" - >>> derived.stationaryaveragingwindow(0) - >>> model.calc_relsumdelta_v1() - >>> states.relsumdelta - relsumdelta(nan) + >>> del pub.options.simulationmode """ CONTROLPARAMETERS = (statcorr_control.EvaluationWindow,) @@ -706,19 +668,20 @@ def __call__(model: modeltools.Model, /) -> None: class Calc_LowVariability_V1(modeltools.Method): - r"""Decide whether the simulated values vary little enough to use the - |StationaryAveragingWindow| instead of the |AveragingWindow| (see - |Calc_AveragedResidual_V1|). + r"""Check whether the simulated values vary only slightly. + + If so, |Calc_AveragedResidual_V1| uses the |StationaryAveragingWindow| instead + of the |AveragingWindow|. Basic equation: :math:`LowVariability = \begin{cases} - 1 &|\ Stationary = 1 \ \land \ RelSumDelta \leq MaxRelSumDelta \ + 1 &|\ Stationary = 1 \ \land \ RelSumDelta \leq MaxRelSumDelta \\ 0 &|\ else \end{cases}` With the stationarity check or the variability check disabled (see - |StationarityCheck|), |LowVariability| is always `0.0`. In `forecast` mode, it - keeps its previous value. + |StationarityCheck|), |LowVariability| is always `0.0`. In `forecast` mode (see + |Options.simulationmode|), it keeps its previous value. Examples: From e3e9648b7e970bdbad5551b7f67c9088773c98fb Mon Sep 17 00:00:00 2001 From: Thomas Recknagel Date: Fri, 13 Nov 2026 16:12:24 +0100 Subject: [PATCH 43/43] Implement new parameters MinValue and MaxValue --- hydpy/models/statcorr/statcorr_control.py | 22 ++++++++++++++++ hydpy/models/statcorr/statcorr_model.py | 28 ++++++++++++++++++++- hydpy/models/statcorr/statcorr_variables.py | 2 ++ hydpy/models/statcorr_arima010.py | 4 ++- hydpy/models/statcorr_main.py | 6 ++++- 5 files changed, 59 insertions(+), 3 deletions(-) diff --git a/hydpy/models/statcorr/statcorr_control.py b/hydpy/models/statcorr/statcorr_control.py index db6a467f0a..b8ddfbf9be 100644 --- a/hydpy/models/statcorr/statcorr_control.py +++ b/hydpy/models/statcorr/statcorr_control.py @@ -1,5 +1,7 @@ # pylint: disable=missing-module-docstring +import numpy + from hydpy.core import exceptiontools from hydpy.core import objecttools from hydpy.core import parametertools @@ -507,6 +509,26 @@ class MaxRelShift(parametertools.Parameter): SPAN = (0.0, None) +class MinValue(parametertools.Parameter): + """The minimum value after a correction is applied [unit of the corrected + variable].""" + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = float + SPAN = (None, None) + INIT = -numpy.inf + + +class MaxValue(parametertools.Parameter): + """The maximum value after a correction is applied [unit of the corrected + variable].""" + + NDIM: Final[Literal[0]] = 0 + TYPE: Final = float + SPAN = (None, None) + INIT = numpy.inf + + class AveragingWindow(parametertools.Parameter): """The length (in log entries) of the averaging period immediately preceding the current time step, used to determine the mean-value-based diff --git a/hydpy/models/statcorr/statcorr_model.py b/hydpy/models/statcorr/statcorr_model.py index 4201881e87..c9ebef286b 100644 --- a/hydpy/models/statcorr/statcorr_model.py +++ b/hydpy/models/statcorr/statcorr_model.py @@ -104,6 +104,8 @@ class Calc_OutputCorr_V1(modeltools.Method): ... maxnanskip(2) ... maxabsshift(100.0) ... maxrelshift(10.0) + ... minvalue(-inf) + ... maxvalue(inf) ... averagingwindow(0) ... transitionsteps(0) ... stationaritycheck(active=False) @@ -845,7 +847,7 @@ class Calc_CorrectedValue_V1(modeltools.Method): multiplicatively if :math:`sim_0` recedes below |ResidualAnchor| (:math:`sim_k`) and additively otherwise. The multiplicative variant keeps the correction from overshooting or turning negative while the simulated values - recede towards zero. + recede towards zero. Finally, |MinValue| and |MaxValue| limit the corrected value. Basic equations: :math:`CorrectedValue = sim_0 \cdot \left(1 + \mathrm{clip}\left(r \cdot @@ -855,6 +857,9 @@ class Calc_CorrectedValue_V1(modeltools.Method): :math:`CorrectedValue = sim_0 + \mathrm{clip}\left(r \cdot f_{red},\ \pm MaxAbsShift\right) \quad | \quad else` + :math:`CorrectedValue_{new} = \min \left( MaxValue, \max \left( MinValue, + CorrectedValue_{old} \right) \right)` + In `historical` mode (see |Options.simulationmode|), :math:`r` is the pointwise |Residual|. In `forecast` mode, a positive |AveragingWindow| (or |LowVariability| being `1.0`) lets :math:`r` blend linearly from |Residual| to |AveragedResidual| @@ -872,6 +877,9 @@ class Calc_CorrectedValue_V1(modeltools.Method): >>> parameterstep() >>> control.maxabsshift(100.0) >>> control.maxrelshift(10.0) + >>> from numpy import inf + >>> control.minvalue(-inf) + >>> control.maxvalue(inf) >>> control.averagingwindow(0) >>> control.transitionsteps(0) >>> derived.nmblogentries(1) @@ -949,11 +957,26 @@ class Calc_CorrectedValue_V1(modeltools.Method): >>> model.calc_correctedvalue_v1() >>> fluxes.correctedvalue correctedvalue(12.0) + + |MaxValue| and |MinValue| limit the corrected value: + + >>> control.maxvalue(11.5) + >>> model.calc_correctedvalue_v1() + >>> fluxes.correctedvalue + correctedvalue(11.5) + >>> control.minvalue(0.0) + >>> states.residual(-20.0) + >>> model.calc_correctedvalue_v1() + >>> fluxes.correctedvalue + correctedvalue(0.0) + >>> del pub.options.simulationmode """ CONTROLPARAMETERS = ( statcorr_control.MaxAbsShift, statcorr_control.MaxRelShift, + statcorr_control.MinValue, + statcorr_control.MaxValue, statcorr_control.AveragingWindow, statcorr_control.TransitionSteps, ) @@ -997,6 +1020,9 @@ def __call__(model: modeltools.Model, /) -> None: flu.correctedvalue = sim + min( con.maxabsshift, max(-con.maxabsshift, residual) ) + flu.correctedvalue = min( + max(flu.correctedvalue, con.minvalue), con.maxvalue + ) class Update_ForecastStep_V1(modeltools.Method): diff --git a/hydpy/models/statcorr/statcorr_variables.py b/hydpy/models/statcorr/statcorr_variables.py index 0d24258ff6..50e30e1092 100644 --- a/hydpy/models/statcorr/statcorr_variables.py +++ b/hydpy/models/statcorr/statcorr_variables.py @@ -4,8 +4,10 @@ from hydpy.core import parametertools from hydpy.core import variabletools + # from hydpy.models.statcorr import statcorr_derived actual import below + class MixinLogEntries(variabletools.Variable, abc.ABC): """Mixin class for 1-dimensional log sequences whose shape depends on the value of parameter |NmbLogEntries|. diff --git a/hydpy/models/statcorr_arima010.py b/hydpy/models/statcorr_arima010.py index 102f390ffd..5deda2d9aa 100644 --- a/hydpy/models/statcorr_arima010.py +++ b/hydpy/models/statcorr_arima010.py @@ -61,6 +61,8 @@ ... maxnanskip(2) ... maxabsshift(100.0) ... maxrelshift(1.0) + ... minvalue(-inf) + ... maxvalue(inf) ... averagingwindow(0) ... transitionsteps(0) ... stationaritycheck(active=False) @@ -260,7 +262,7 @@ Skipping NaN-Values ___________________ - When calculating the residual, NaN values can be skipped (up to |MaxNanSkip| + When calculating the residual, NaN values can be skipped (up to |MaxNaNSkip| time steps). We demonstrate this by setting the last three observations in the historical period to `nan` and using `maxnanskip(3)`. We see that the last residual (`1.8`) is used because three steps without observations are skipped. diff --git a/hydpy/models/statcorr_main.py b/hydpy/models/statcorr_main.py index dd791f67aa..c87bc6e103 100644 --- a/hydpy/models/statcorr_main.py +++ b/hydpy/models/statcorr_main.py @@ -50,6 +50,8 @@ ... control.maxnanskip(2) ... control.maxabsshift(100.0) ... control.maxrelshift(10.0) + ... control.minvalue(-inf) + ... control.maxvalue(inf) ... control.averagingwindow(0) ... control.transitionsteps(0) ... control.stationaritycheck(active=False) @@ -64,6 +66,8 @@ ... control.maxnanskip(2) ... control.maxabsshift(0.5) ... control.maxrelshift(0.05) + ... control.minvalue(-inf) + ... control.maxvalue(inf) ... control.averagingwindow(0) ... control.transitionsteps(0) ... control.stationaritycheck(active=False) @@ -80,7 +84,7 @@ ... [9.6, 10.8, 12.6, 12.0, 12.0] + 5 * [nan] ... ) - In operational use, a forecast consists of two separate simulation runs. First, + In operational use, a forecast consists of two separate simulation runs. First, a `historical` run covers the period with observations and ends with saving the current conditions (the states and logs of all submodels). Second, a `forecast` run starts from these conditions and covers the forecast horizon.