neural_lam.models.forecasters.deterministic
===========================================

.. py:module:: neural_lam.models.forecasters.deterministic

.. autoapi-nested-parse::

   Forecasters trained by scoring a single deterministic forecast.



Classes
-------

.. autoapisummary::

   neural_lam.models.forecasters.deterministic.BaseDeterministicForecaster
   neural_lam.models.forecasters.deterministic.DeterministicARForecaster


Module Contents
---------------

.. py:class:: BaseDeterministicForecaster(datastore: neural_lam.datastore.BaseDatastore, config: neural_lam.config.NeuralLAMConfig | None = None, loss: str = 'wmse')

   Bases: :py:obj:`neural_lam.models.forecasters.base.BaseForecaster`


   Forecaster whose ``forward`` is deterministic, trained by scoring it.

   Repeating a call returns the same forecast, so one call is the whole
   forecast; contrast ``BaseProbabilisticForecaster``, which samples a fresh
   one each call. How that forecast is produced stays open, ``forward``
   being inherited abstract; see ``DeterministicARForecaster`` for the
   auto-regressive one. ``compute_training_loss`` produces one forecast
   and scores it with ``self.loss``, and ``compute_loss_from_forecast``
   applies the same scoring rule to an already-produced forecast for
   reporting.

   Set up the scoring rule and the constant ``pred_std`` fallback.

   :param datastore: The datastore providing the state standardization statistics
                     used to compute ``per_var_std``.
   :type datastore: BaseDatastore
   :param config: Configuration used to compute the constant per-variable std
                  substituted for ``pred_std`` when the forecast carries no std of
                  its own. Needed only when ``loss`` is a scoring rule that uses a
                  std; without it in that case ``compute_loss_from_forecast`` and
                  ``compute_training_loss`` raise ``ValueError`` via
                  ``_resolve_pred_std``. Forecasters used purely for inference can
                  always omit it. Default ``None``.
   :type config: NeuralLAMConfig or None, optional
   :param loss: The scoring rule (from ``neural_lam.metrics``) applied by
                ``compute_training_loss``, stored as ``self.loss``. Default
                ``"wmse"``.
   :type loss: str, optional


   .. py:method:: compute_loss_from_forecast(prediction: torch.Tensor, target_states: torch.Tensor, pred_std: torch.Tensor | None, mask: torch.Tensor | None = None, average_grid: bool = True, sum_vars: bool = True) -> torch.Tensor

      Apply this forecaster's scoring rule to an already-produced forecast.

      Resolves ``pred_std`` via ``_resolve_pred_std`` (substituting
      ``self.per_var_std`` when ``None`` and ``self.loss`` needs one), then
      applies ``self.loss``. Used to report the loss on a forecast the
      caller already has, at a reduction of its choosing, without
      recomputing it.

      Only the loss goes through here. Metrics unrelated to the training
      objective depend on nothing but the shapes of the three tensors
      below, so callers compute those directly from
      ``neural_lam.metrics``.

      :param prediction: Shape ``(..., num_grid_nodes, num_state_vars)``. Forecast to
                         score.
      :type prediction: torch.Tensor
      :param target_states: Shape ``(..., num_grid_nodes, num_state_vars)``. True states to
                            score against. Dims: same as ``prediction``.
      :type target_states: torch.Tensor
      :param pred_std: Shape ``(..., num_grid_nodes, num_state_vars)``, or ``None``.
                       Predicted standard deviation for ``prediction``; ``None`` when
                       the forecast carries no std, in which case ``self.per_var_std``
                       is substituted if ``self.loss`` needs a std at all (see
                       ``_resolve_pred_std`` for when this raises instead).
      :type pred_std: torch.Tensor or None
      :param mask: Shape ``(num_grid_nodes,)``, boolean. Forwarded to ``self.loss``.
      :type mask: torch.Tensor or None, optional
      :param average_grid: Forwarded to ``self.loss``. Default ``True``.
      :type average_grid: bool, optional
      :param sum_vars: Forwarded to ``self.loss``. Default ``True``.
      :type sum_vars: bool, optional

      :returns: The scoring rule's output; shape depends on ``average_grid`` and
                ``sum_vars`` (see ``neural_lam.metrics``).
      :rtype: torch.Tensor

      :raises ValueError: If ``pred_std`` is ``None``, ``self.loss`` needs one and no
          ``per_var_std`` fallback is available; see ``_resolve_pred_std``.



   .. py:method:: compute_training_loss(init_states: torch.Tensor, forcing_features: torch.Tensor, target_states: torch.Tensor, interior_mask_bool: torch.Tensor) -> tuple[torch.Tensor, dict[str, torch.Tensor]]

      Score a single forecast with ``self.loss``.

      Produces one forecast over every predicted step, scores it against
      the target states on interior nodes and averages over batch and
      time. Callers that already hold a forecast should score that one
      with ``compute_loss_from_forecast`` rather than producing another
      here.

      :param init_states: Shape ``(B, 2, num_grid_nodes, num_state_vars)``. The two initial
                          states ``[X_{t-1}, X_t]`` used to start the forecast from. Dims:
                          ``B`` is batch size, ``2`` is the time index (``[X_{t-1}, X_t]``),
                          ``num_grid_nodes`` is the number of spatial nodes, and
                          ``num_state_vars`` is the state feature dimension.
      :type init_states: torch.Tensor
      :param forcing_features: Shape ``(B, pred_steps, num_grid_nodes, num_forcing_vars)``.
                               External forcings provided at each predicted step. Dims: ``B``
                               is batch size, ``pred_steps`` is the number of predicted steps,
                               ``num_grid_nodes`` is the number of spatial nodes, and
                               ``num_forcing_vars`` is the forcing feature dimension (already
                               concatenated past/current/future windows).
      :type forcing_features: torch.Tensor
      :param target_states: Shape ``(B, pred_steps, num_grid_nodes, num_state_vars)``. True
                            states at each predicted step, used both as the prediction
                            targets and to overwrite boundary nodes while forecasting.
                            Dims: same as the prediction.
      :type target_states: torch.Tensor
      :param interior_mask_bool: Shape ``(num_grid_nodes,)``, boolean. ``True`` for interior
                                 nodes; passed as ``mask`` to ``self.loss`` so that only interior
                                 nodes are scored.
      :type interior_mask_bool: torch.Tensor

      :returns: * **batch_loss** (*torch.Tensor*) -- Scalar. The scoring rule applied to the forecast, averaged over
                  batch and time.
                * **loss_components** (*dict of {str: torch.Tensor}*) -- Empty; the deterministic objective has no separate components.

      :raises ValueError: If ``self.loss`` needs a std, the forecast carries none of its
          own and no ``per_var_std`` fallback is available; see
          ``_resolve_pred_std``.

      .. rubric:: Notes

      Customize the deterministic objective by overriding
      ``compute_loss_from_forecast``. ``DeterministicForecastingModule``
      calls that method directly for its per-step training, validation
      and test losses. Overriding only ``compute_training_loss`` does not
      change those losses.



   .. py:attribute:: loss


   .. py:attribute:: per_var_std
      :type:  torch.Tensor | None


.. py:class:: DeterministicARForecaster(predictor: neural_lam.models.step_predictors.base.StepPredictor, datastore: neural_lam.datastore.BaseDatastore, config: neural_lam.config.NeuralLAMConfig | None = None, loss: str = 'wmse', gradient_checkpointing: bool = False)

   Bases: :py:obj:`BaseDeterministicForecaster`


   Auto-regressive forecaster trained by scoring its single rollout.

   Produces its forecast by unrolling a ``StepPredictor``; the training
   objective is the one ``BaseDeterministicForecaster`` supplies.

   Initialize the DeterministicARForecaster.

   :param predictor: The predictor to use for each AR step.
   :type predictor: StepPredictor
   :param datastore: The datastore providing grid metadata and boundary masks.
   :type datastore: BaseDatastore
   :param config: Configuration used to compute the constant per-variable std
                  substituted for ``pred_std`` when ``predictor`` does not output
                  its own. Needed only when ``loss`` is a scoring rule that uses a
                  std; without it in that case ``compute_loss_from_forecast`` and
                  ``compute_training_loss`` raise ``ValueError``. Forecasters used
                  purely for inference (``forward``) can always omit it.
   :type config: NeuralLAMConfig or None
   :param loss: The scoring rule (from ``neural_lam.metrics``) applied by
                ``compute_training_loss``.
   :type loss: str, default "wmse"
   :param gradient_checkpointing: If True and in training mode, wrap each predictor call in
                                  ``torch.utils.checkpoint`` so its activations are recomputed in
                                  the backward pass instead of stored. Lowers peak memory when
                                  unrolling more than one step, at the cost of extra compute.
   :type gradient_checkpointing: bool, default False


   .. py:method:: forward(init_states: torch.Tensor, forcing_features: torch.Tensor, boundary_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor | None]

      Unroll one auto-regressive forecast.

      :param init_states: Shape ``(B, 2, num_grid_nodes, num_state_vars)``. The two initial
                          states ``[X_{t-1}, X_t]`` used to start the rollout from.
      :type init_states: torch.Tensor
      :param forcing_features: Shape ``(B, pred_steps, num_grid_nodes, num_forcing_vars)``.
                               Forcing features for each predicted step; ``pred_steps`` defines
                               the rollout length.
      :type forcing_features: torch.Tensor
      :param boundary_states: Shape ``(B, pred_steps, num_grid_nodes, num_state_vars)``. True
                              state values used ONLY to overwrite boundary nodes at each AR
                              step.
      :type boundary_states: torch.Tensor

      :returns: * **prediction** (*torch.Tensor*) -- Shape ``(B, pred_steps, num_grid_nodes, num_state_vars)``.
                  Stacked per-step forecasts. Dims: same as ``boundary_states``.
                * **pred_std** (*torch.Tensor or None*) -- Shape ``(B, pred_steps, num_grid_nodes, num_state_vars)`` when
                  the wrapped predictor outputs an std, otherwise ``None``. Dims:
                  same as ``prediction``.



   .. py:attribute:: gradient_checkpointing
      :type:  bool


   .. py:attribute:: predictor


   .. py:property:: predicts_std
      :type: bool


      Whether the forecaster predicts standard deviation.

      :returns: ``True`` if the wrapped predictor predicts standard deviation,
                ``False`` otherwise.
      :rtype: bool


