Thermal Inertia: PyTorch Architecture

Navigation:

Overview & Formula Tokens

Multi-timescale physical thermal inertia is exposed via inertia() and thermal():

# Multi-timescale thermal inertia (exponentially smoothed B-splines)
formula = "Y ~ inertia(temperature, type='thermal', alphas='0.05|0.01|0.002', k=4)"

Parameter Specification

InertiaEffect (inertia() / thermal())

Parameter

Type

Default

Description

feature_name

str

required

Input feature column name.

type

str

'thermal'

Inertia regime ('thermal', 'rotational', 'behavioral').

alphas

Sequence[float] or str

(0.05, 0.01, 0.002)

Exponential smoothing decay constants \(\alpha_m \in (0, 1]\).

k

int

8

Spline knots per decay scale.

deg

int

3

B-spline polynomial degree.

p

int

2

Difference penalty order.

Complexity & Performance

State, Complexity and Limits

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

  • State: {"y": (B, M)}, the last smoothed value of every group and decay constant.

  • Layout: (B, T) in, (B, T, M (k + degree)) out.

  • Time and memory: \(\mathcal{O}(B\,T\,M)\) for the recurrences (loop below 64 steps, FFT convolution above) plus the spline evaluation; no scipy filter, no flattening of groups.

  • Penalty coordinates: M, labelled alpha=<value>, all starting at \(\lambda\); GCV and REML tune them separately.

  • Extrapolation: 'linear' and 'saturation' are refused at construction (the effect is temporal); the spline continues linearly outside the normalized range of the smoothed series.

  • Limits: the bounds of the input are frozen on the training period, so a temperature outside it reaches the linear continuation of the splines.

  • Smoothing criterion: the effect has several penalty coordinates (see above). 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.

  • Chunk equivalence bound: tests/spectrum/test_stateful_contract.py checks that the second of two chunks, started from the state of the first, equals the matching rows of the one-pass features within atol=1e-8 (float64), and that every group computed alone equals the same group inside a batch within atol=1e-10.

Code

Feature map of InertiaEffect (build_feature_map):

    def build_feature_map(self, x_col: torch.Tensor, state_in: Optional[Dict[str, Any]] = None) -> torch.Tensor:
        """Builds causal thermal inertia B-spline feature columns with domain normalization.

        ``(B, T)`` in, ``(B, T, M * (k + degree))`` out, with ``M`` the number of decay constants. Each group is smoothed on its
        own; the smoothed value at the last step (``{"y": (B, M)}``) is the state to carry.
        """
        x3, shape, layout = to_btd(x_col, self.multi_input)
        if self._x_bounds is None:
            self.initialize(x_col)
        device, dtype = x3.device, x3.dtype
        x = x3[..., 0]
        B, T = x.shape
        if self._x_bounds is not None:
            x_low, x_high = self._x_bounds
            x_norm = 2.0 * (x - x_low) / max(1e-6, x_high - x_low) - 1.0
        else:
            x_norm = x

        alphas = torch.tensor(self.alphas, dtype=torch.float64, device=device)
        if state_in is not None and "y" in state_in:
            y_prev = state_in["y"].to(device=device, dtype=dtype)
            if tuple(y_prev.shape) != (B, len(self.alphas)):
                raise ValueError(f"state 'y' has shape {tuple(y_prev.shape)}, expected {(B, len(self.alphas))}: continue_state needs the same groups and features as training")
        else:
            y_prev = x_norm[:, :1].expand(B, len(self.alphas)).clone()      # no history: the smoothed value starts at the first input
        y = causal_linear_recurrence(x_norm.unsqueeze(-1).expand(B, T, len(self.alphas)), 1.0 - alphas, alphas, y_prev)

        knots = self._build_knots(device=device, dtype=dtype)
        smoothed_blocks: List[torch.Tensor] = []
        for m in range(len(self.alphas)):
            y_m = y[..., m].reshape(-1)                                   # (B * T,) smoothed input of decay constant m
            smoothed_blocks.append(eval_clamped_spline_with_linear_tails(y_m, knots, self.spline_degree))   # (B * T, k + degree)

        self._state_out = {"y": y[:, -1, :].detach().clone()}
        phi = torch.cat(smoothed_blocks, dim=-1).reshape(B, T, self._n_coeffs)
        return from_btk(phi, shape, layout)

Penalty of InertiaEffect (build_penalty_matrix):

    def build_penalty_matrix(self) -> torch.Tensor:
        """Builds block-diagonal second-difference penalty matrix."""
        n_sp = self._n_spline_coeffs
        I = torch.eye(n_sp, device=TORCH_DEVICE, dtype=torch.get_default_dtype())
        if self.penalty_order == 0:
            D = I
        else:
            D = torch.diff(I, n=self.penalty_order, dim=0)
        DtD = D.T @ D
        return torch.block_diag(*[lam * DtD for lam in self.penalty_coordinates()])

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

        elif ttype in ('inertia', 'thermal', 'ti'):
            inertia_type = str(params_resolved.get('type', params_resolved.get('inertia_type', 'thermal'))).lower()
            k = int(params_resolved.get('k', 8))
            deg = int(params_resolved.get('deg', params_resolved.get('spline_degree', 3)))
            p = int(params_resolved.get('p', params_resolved.get('penalty_order', 2)))
            alphas_raw = params_resolved.get('alphas', params_resolved.get('alpha', (0.05, 0.01, 0.002)))
            extrap_val = params_resolved.get('extrapolate', 'continue')
            effects_list.append(InertiaEffect(
                feature_name=feature_name,
                inertia_type=inertia_type,
                alphas=alphas_raw,
                k=k,
                spline_degree=deg,
                penalty_order=p,
                lambda_p=lambda_p,
                extrapolate=extrap_val,
            ))