Macro-Trend (hp_trend): PyTorch Architecture

Navigation:

Overview & Formula Token

# Natural cubic Hodrick-Prescott macro-trend with linear extrapolation
formula = "Y ~ hp_trend(trend, k=20, ap=-6)"

Parameter Specification

MacroTrendEffect (hp_trend())

Parameter

Type

Default

Description

k

int

20

Number of natural cubic B-spline knots.

lambda_p

float

1600.0

HP second-difference smoothing weight.

extrapolate

str

'linear'

Extrapolation mode.

The class lives in src/tam/model/spectrum/_inertia.py with the other load effects.

State, Complexity and Limits

  • Class and file: MacroTrendEffect, src/tam/model/spectrum/_inertia.py; _load_forecasting.py re-exports it under the old module name. Label: (BETA).

  • State: none. Layout: any shape, one row of features per input value. Time and memory: \(\mathcal{O}(B\,T\,k)\).

  • Penalty: \(\lambda\,D_2^\top D_2\) with the default \(\lambda = 1600\) of the Hodrick–Prescott filter; ap in a formula replaces it.

  • Extrapolation: only 'linear' is implemented for hp_trend: build_feature_map always continues the basis by its tangent beyond the training range, whatever value extrapolate has; the argument is kept for API symmetry.

  • Horizon: the linear continuation carries the slope of the trend at the end of the training period over the whole horizon, so over a long static horizon the extrapolated level can drift far from the actual one. On the national load benchmark (a static fit on the years before the test year) the test RMSE of the model with this term was about four times that of the spline reference (+320 %), while its adaptive variant, which refits and extrapolates one step at a time, was -1.38 % on validation and +0.39 % on test. Use the effect in AdaptiveTAM, or refit often, rather than as a static term over a long horizon.

Code

Feature map of MacroTrendEffect (build_feature_map):

    def build_feature_map(self, x_col: torch.Tensor) -> torch.Tensor:
        """Builds B-spline trend columns with linear extrapolation beyond bounds."""
        orig_shape = x_col.shape
        x_flat = x_col.flatten()
        device = x_col.device
        dtype = x_col.dtype

        knots = build_clamped_knots(self.k, self.spline_degree, device, dtype)

        if self._x_bounds is None:
            self.initialize(x_col)
        x_low, x_high = self._x_bounds
        x_norm = 2.0 * (x_flat - x_low) / max(1e-6, x_high - x_low) - 1.0

        phi = eval_clamped_spline_with_linear_tails(x_norm, knots, self.spline_degree)      # (N, k + degree)

        return phi.reshape(*orig_shape, self._n_coeffs)

Penalty of MacroTrendEffect (build_penalty_matrix):

    def build_penalty_matrix(self) -> torch.Tensor:
        """Constructs exact second-difference penalty D_2^T D_2."""
        p = self.get_n_coeffs()
        d2 = torch.zeros(p - 2, p, device=TORCH_DEVICE, dtype=torch.get_default_dtype())
        for i in range(p - 2):
            d2[i, i] = 1.0
            d2[i, i + 1] = -2.0
            d2[i, i + 2] = 1.0
        return self.lambda_p * (d2.T @ d2)

Parsing of the hp_trend(...) token in the factory:

        elif ttype in ('hp_trend', 'macro_trend', 'trend_hp'):
            k = int(params_resolved.get('k', 20))
            extrap_val = params_resolved.get('extrapolate', 'linear')
            effects_list.append(MacroTrendEffect(
                feature_name=feature_name,
                k=k,
                lambda_p=lambda_p,
                extrapolate=extrap_val,
            ))