Warped Calendar Harmonics: PyTorch Architecture

Navigation:

Overview & Formula Tokens

Phase-warped calendar harmonics by regime indicator are exposed via wcal():

# Diffeomorphic phase-warped calendar harmonics by regime indicator
formula = "Y ~ wcal(tod, by='is_holiday', period=48.0, n_harmonics=8)"

Parameter Specification

WarpedCalendarEffect (wcal())

Parameter

Type

Default

Description

by

str

None

Regime indicator column name.

period

float

48.0

Cycle period length.

n_harmonics

int

6

Number of Fourier harmonics \(K\).

gamma_warp, gamma_amp

float

1.0

Penalty multipliers for phase-warping and amplitude blocks.

Complexity & Performance

  • Full-Rank Conditioning: WarpedCalendarEffect modulates phase derivatives with \((\tau - \pi)/\pi\) to preserve full \(6K\) column rank.

Grouped models

When the model is grouped by the column that wcal reads (for example group_col='tod' with wcal(tod, ...)), that column is constant inside each group. The base harmonic columns are then constant, and the remaining columns vary only through by, so they add nothing that a day-type term on the same by column does not already span. Use wcal in a model that is not grouped by its input column. Measured on the national load benchmark: no group gains rank under group_col='tod'; ungrouped, wcal lowers the static test RMSE by 12.8 % over the same reference terms.

State, Complexity and Limits

  • Class and file: WarpedCalendarEffect, src/tam/model/spectrum/_inertia.py. Label: (BETA).

  • State: none. Layout: (B, T) without regime, (B, T, 2) (phase, regime) with by= (or others=, or regime_feature=: the three spellings read the same column).

  • Time and memory: \(\mathcal{O}(B\,T\,K)\), pointwise.

  • Penalty coordinates: base, warp, amp with a regime, base alone without.

  • Extrapolation: 'periodic' (default) wraps the phase around the period; the other modes of the router are available.

  • Limits: see Grouped models above. The effect needs a column that varies inside a group, so it is meant for models that are not grouped by its own input column.

  • Collinearity guardrail: when group_col is the effect’s own phase column, the phase is constant inside a group and the columns are spanned by the per-group intercepts: the effect adds nothing (the rank argument of the note in the class docstring). In a model not grouped by that column, the derivative columns are multiplied by the phase envelope \(g(\tau) = (\tau - \pi)/\pi \in [-1, 1)\) (with \(\tau\) the angular phase), which keeps the base, warp and amplitude blocks of full column rank together: \(6K\) columns with a regime, rank \(6K\) (checked by test_warped_calendar_effect).

  • Smoothing criterion: the effect has three penalty coordinates. Prefer auto_fit(criterion="reml") to the default coordinate GCV. Signature: auto_fit(self, data_train, alpha_p_bounds=(-30.0, 6.0), number_of_steps=10, alpha_p_list=None, gamma=1.4, verbose=False, criterion="gcv"). This is a recommendation, not a measured result for this effect: the repository’s REML tests check the analytic gradient, the penalty basis of the multi-coordinate effects and that REML is more stable than GCV on autocorrelated noise (test_reml_criterion); no benchmark compares the two criteria on this effect.

Code

Feature map of WarpedCalendarEffect (build_feature_map):

    def build_feature_map(self, x_col: torch.Tensor) -> torch.Tensor:
        """Constructs base Fourier, phase-derivative warping, and amplitude interaction columns."""
        orig_shape = x_col.shape

        if self.has_regime and x_col.dim() >= 2 and x_col.shape[-1] >= 2:
            phase_in = x_col[..., 0]
            regime_in = x_col[..., 1:]
            batch_shape = orig_shape[:-1]
        else:
            phase_in = x_col
            regime_in = None
            batch_shape = orig_shape

        # The input is the phase normalized from [0, period] to [-1, 1] (fixed_ranges()): angular phase in [0, 2*pi)
        tau = (np.pi * (phase_in + 1.0)).unsqueeze(-1)
        k_vec = torch.arange(1, self.n_harmonics + 1, device=x_col.device, dtype=x_col.dtype)

        angles = tau * k_vec
        cos_part = torch.cos(angles)
        sin_part = torch.sin(angles)

        base_cols = torch.cat([cos_part, sin_part], dim=-1)

        if not self.has_regime or regime_in is None:
            return base_cols.reshape(*batch_shape, self._n_coeffs)

        d_cos = -k_vec * sin_part
        d_sin = k_vec * cos_part
        d_cols = torch.cat([d_cos, d_sin], dim=-1)

        # Diffeomorphic phase-modulation profile g(tau) = (tau - pi)/pi in [-1, 1)
        # prevents exact collinearity between phase-derivative warp_cols and amp_cols.
        phase_envelope = (tau - np.pi) / np.pi
        warp_cols = regime_in * phase_envelope * d_cols
        amp_cols = regime_in * base_cols

        full = torch.cat([base_cols, warp_cols, amp_cols], dim=-1)
        return full.reshape(*batch_shape, self._n_coeffs)

Penalty of WarpedCalendarEffect (build_penalty_matrix):

    def build_penalty_matrix(self) -> torch.Tensor:
        """Constructs block-diagonal Sobolev frequency penalty matrix."""
        k_vec = torch.arange(1, self.n_harmonics + 1, device=TORCH_DEVICE, dtype=torch.get_default_dtype())
        sob_weights = (k_vec ** self.sobolev_order)
        p_base = torch.cat([sob_weights, sob_weights])

        coords = self.penalty_coordinates()
        if not self.has_regime:
            return torch.diag(coords[0] * p_base)

        lam_base, lam_warp, lam_amp = coords
        return torch.diag(torch.cat([lam_base * p_base, lam_warp * p_base, lam_amp * p_base]))

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

        elif ttype in ('wcal', 'warped_calendar', 'calendar_warp'):
            period = float(params_resolved.get('period', params_resolved.get('p', 48.0)))
            n_harmonics = int(params_resolved.get('n_harmonics', params_resolved.get('k', 6)))
            regime_feature = params_resolved.get('by', params_resolved.get('others', params_resolved.get('regime_feature', None)))
            if regime_feature is not None:
                regime_feature = str(regime_feature).strip()
                if not regime_feature or regime_feature.lower() in ('none', 'null'):
                    regime_feature = None
            sobolev_order = float(params_resolved.get('sobolev_order', params_resolved.get('s', 2.0)))
            gamma_warp = float(params_resolved.get('gamma_warp', 1.0))
            gamma_amp = float(params_resolved.get('gamma_amp', 1.0))
            extrap_val = params_resolved.get('extrapolate', 'periodic')
            effects_list.append(WarpedCalendarEffect(
                feature_name=feature_name,
                regime_feature=regime_feature,
                period=period,
                n_harmonics=n_harmonics,
                sobolev_order=sobolev_order,
                gamma_warp=gamma_warp,
                gamma_amp=gamma_amp,
                lambda_p=lambda_p,
                extrapolate=extrap_val,
            ))