Algorithm Search⌘K

Techniqueadvanced

Whittle likelihood

Also called Whittle approximation, Whittle estimator.

Approximates the Gaussian likelihood of a stationary series by a sum over Fourier frequencies of log f plus the periodogram over f, with f the spectral density.

The Whittle likelihood replaces the Gaussian likelihood of a stationary series by a sum over the Fourier frequencies ωj=2πj/n\omega_j = 2\pi j/n:

−2log⁡LW(θ)=Nlog⁡(2π)+∑j∈J[log⁡(2πfθ(ωj))+I(ωj)fθ(ωj)],-2\log L_W(\theta) = N\log(2\pi) + \sum_{j \in J}\Big[\log\big(2\pi f_\theta(\omega_j)\big) + \frac{I(\omega_j)}{f_\theta(\omega_j)}\Big],

where fθf_\theta is the model spectral density, I(ωj)=∣∑t=1nXte−itωj∣2/(2πn)I(\omega_j) = \lvert\sum_{t=1}^n X_t e^{-it\omega_j}\rvert^2/(2\pi n) is the periodogram, and JJ is a set of NN frequencies. Whittle (1953) derived it by noting that the discrete Fourier transform nearly diagonalizes the covariance matrix of a stationary series. It is the exact likelihood of a circular version of the process, it costs O(nlog⁡n)O(n \log n) with the fast Fourier transform, and for short-memory models its minimizer has the same asymptotic law as the Gaussian maximum likelihood estimate. For short series and peaked spectra it is biased, and tapering or the debiased Whittle likelihood reduce the bias.

In plain words

A stationary series can be split into waves of different frequencies. The model says how much power each frequency should carry. The data say how much power each frequency actually carries, as measured by the periodogram. For a long series, the measured power at different frequencies is almost independent, and at each frequency it is about the model power times a random factor with mean 1. So you can score a model by comparing the two at every frequency and adding up, as if each frequency were its own small, independent experiment. This is much faster than working with the full matrix of covariances between all pairs of time points, and for long series it gives almost the same answer.

When it applies

  • The series is weakly stationary with a known mean, or with the mean removed. The model gives the spectral density fθf_\theta in closed form, for example the ARMA density f(λ)=σ22π∣θ(e−iλ)∣2/∣ϕ(e−iλ)∣2f(\lambda) = \frac{\sigma^2}{2\pi}\lvert\theta(e^{-i\lambda})\rvert^2/\lvert\phi(e^{-i\lambda})\rvert^2.
  • The data are equally spaced with no gaps. Missing values break the Fourier transform.
  • The asymptotic theory needs short memory: fθf_\theta continuous and bounded away from 0, as for a causal invertible ARMA model. Long-memory models need separate theory (see the classic examples).
  • nn is large enough for O(1)O(1) errors to be small next to nn. The method is most useful when the exact likelihood is expensive: long series, long-memory models, spatial grids and multivariate series.

The template

The data are x1,…,xnx_1, \ldots, x_n. The holes are the spectral family fθf_\theta for θ∈Θ\theta \in \Theta, the frequency set JJ, and the minimizer MINIMIZE.

  1. WHITTLE(x[1..n], f_θ, Θ, J, MINIMIZE) ▷ returns θ̂ and -2 log L_W(θ̂)
  2. 1I[j] ← |Σ_{t=1}^{n} x[t] e^{-itω_j}|² / (2πn) for j = 0, ..., n - 1 ▷ one FFT, ω_j = 2πj/n
  3. 2ℓ(θ): for each j ∈ J do f_j ← f_θ(ω_j)
  4. 3term_j ← log(2π f_j) + I[j] / f_j
  5. 4ℓ(θ) ← |J| log(2π) + Σ_{j ∈ J} term_j
  6. 5return θ̂ ← MINIMIZE(ℓ, Θ), with ℓ(θ̂)

Common choices for JJ:

  • Known mean 0: all j=0,…,n−1j = 0, \ldots, n - 1. Then N=nN = n and the scale matches the exact −2log⁡L-2\log L.
  • Mean removed: subtract xˉ\bar x and use j=1,…,n−1j = 1, \ldots, n - 1, because I(0)=0I(0) = 0 after centering. The code does this.
  • Half the frequencies: II and ff are symmetric, I(ωn−j)=I(ωj)I(\omega_{n-j}) = I(\omega_j), so many texts sum over 0<ωj<π0 < \omega_j < \pi only. This halves the objective and does not change the minimizer.
  • A band: only the lowest mm frequencies, for the local Whittle estimator.

Profiling the scale. Write fθ=σ22πgβf_\theta = \frac{\sigma^2}{2\pi} g_\beta, where gβg_\beta does not depend on σ2\sigma^2. Minimizing over σ2\sigma^2 gives σ^2(β)=2πN∑j∈JI(ωj)/gβ(ωj)\hat\sigma^2(\beta) = \frac{2\pi}{N}\sum_{j \in J} I(\omega_j)/g_\beta(\omega_j), and the profiled objective Nlog⁡(2π)+Nlog⁡σ^2(β)+∑j∈Jlog⁡gβ(ωj)+NN\log(2\pi) + N\log\hat\sigma^2(\beta) + \sum_{j \in J}\log g_\beta(\omega_j) + N. The code minimizes this over β\beta. For a causal invertible ARMA model, 1n∑j=0n−1log⁡gβ(ωj)\frac1n\sum_{j=0}^{n-1}\log g_\beta(\omega_j) is within O(ρn)O(\rho^n) of 0 for some ρ<1\rho < 1, by Kolmogorov's formula on the grid (the tests check ∣⋅∣<10−12\lvert\cdot\rvert < 10^{-12} for n=512n = 512). So the minimizer is close to the minimizer of ∑jI(ωj)/gβ(ωj)\sum_j I(\omega_j)/g_\beta(\omega_j), a weighted least squares fit of the periodogram.

Why it works: the circulant approximation. Let Γn=[γ(s−t)]\Gamma_n = [\gamma(s - t)] be the covariance matrix and let CnC_n be the circulant matrix with first row γ~(h)=∑k∈Zγ(h+kn)\tilde\gamma(h) = \sum_{k \in \mathbb{Z}}\gamma(h + kn). Every circulant is diagonalized by the Fourier vectors, and the eigenvalue of CnC_n at ωj\omega_j is ∑h=0n−1γ~(h)e−ihωj=∑h∈Zγ(h)e−ihωj=2πf(ωj)\sum_{h=0}^{n-1}\tilde\gamma(h)e^{-ih\omega_j} = \sum_{h \in \mathbb{Z}}\gamma(h)e^{-ih\omega_j} = 2\pi f(\omega_j). With dj=∑txte−itωjd_j = \sum_t x_t e^{-it\omega_j}, this gives x⊤Cn−1x=1n∑j∣dj∣2/(2πf(ωj))=∑jI(ωj)/f(ωj)x^\top C_n^{-1}x = \frac1n\sum_j \lvert d_j\rvert^2/(2\pi f(\omega_j)) = \sum_j I(\omega_j)/f(\omega_j) and log⁡det⁡Cn=∑jlog⁡(2πf(ωj))\log\det C_n = \sum_j\log(2\pi f(\omega_j)). So with JJ all nn frequencies, −2log⁡LW-2\log L_W is exactly the Gaussian −2log⁡L-2\log L of a series with covariance CnC_n, a process that wraps around the circle. For short memory, Γn\Gamma_n and CnC_n differ mainly in the corners, and the two log likelihoods differ by Op(1)O_p(1) while each grows like nn (Brockwell and Davis 1991, Section 10.8). For white noise Cn=Γn=σ2IC_n = \Gamma_n = \sigma^2 I, and the Whittle likelihood is exact (this is Parseval's identity, checked in the tests).

What is proved and what is measured. For a causal invertible ARMA model with IID noise of finite variance, the Whittle estimator is consistent and n(β^−β)\sqrt{n}(\hat\beta - \beta) has the same normal limit as the Gaussian maximum likelihood estimator (Brockwell and Davis 1991, Section 10.8, cited, not proved here). Normal noise is not needed. The values below were measured with the code. At the true parameters of an AR(1) model with ϕ=0.6\phi = 0.6 and σ2=1\sigma^2 = 1 (seed 3), the exact −2log⁡L-2\log L was 180.574 and the Whittle value 180.065 for n=64n = 64, and 680.140 and 681.014 for n=256n = 256. The gap stays of order 1 while the values grow like nn.

Cost. Line L1 is one FFT, O(nlog⁡n)O(n\log n) when nn is a power of 2. The code uses its own radix-2 FFT, which falls back to the direct sum on an odd factor, and the tests check it against the direct transform. Each evaluation of ℓ\ell then costs O(N(p+q))O(N(p + q)) for an ARMA(pp, qq) model. The exact likelihood costs O(nmax⁡(p,q)2)O(n\max(p, q)^2) per evaluation with the innovations algorithm or a Kalman filter, O(n2)O(n^2) for a general stationary model by Durbin-Levinson, and O(n3)O(n^3) for a general covariance matrix by Cholesky. The gain is small for a low-order ARMA model and large for long-memory models, spatial grids and long multivariate series.

Classic examples

  • AR(1) has a closed form. With known mean 0 and all nn frequencies, g(ω)=∣1−ϕe−iω∣−2g(\omega) = \lvert 1 - \phi e^{-i\omega}\rvert^{-2} and ∑jI(ωj)/g(ωj)=12π[(1+ϕ2)c~0−2ϕc~1]\sum_j I(\omega_j)/g(\omega_j) = \frac{1}{2\pi}\big[(1 + \phi^2)\tilde c_0 - 2\phi\tilde c_1\big], with c~0=∑txt2\tilde c_0 = \sum_t x_t^2 and the circular sum c~1=∑t=1nxtxt+1\tilde c_1 = \sum_{t=1}^{n} x_t x_{t+1} (indices mod nn). The log term is ∑jlog⁡g(ωj)=−2log⁡∣1−ϕn∣\sum_j\log g(\omega_j) = -2\log\lvert 1 - \phi^n\rvert, which is exponentially small. Without it, the profiled objective is minimized at the circular lag-1 autocorrelation ϕ^W=c~1/c~0\hat\phi_W = \tilde c_1/\tilde c_0, which is at most 1 in absolute value. A numerical check on a series of length 200 (seed 9) gave c~1/c~0=0.53556015\tilde c_1/\tilde c_0 = 0.53556015 and the minimizer of the full Whittle objective 0.535560160.53556016. Compare the Yule-Walker estimate, which uses the ordinary lag-1 autocorrelation.

  • ARMA fitting. The code fits a causal invertible ARMA(pp, qq) model by Nelder-Mead over unconstrained parameters uu, mapped to ϕ\phi and θ\theta through partial autocorrelations tanh⁡(uk)\tanh(u_k) and the Durbin-Levinson step-up recursion, so every candidate is causal and invertible. For AR(1), 100 series per row (seed 21), comparing the Whittle estimate (W), the exact Gaussian maximum likelihood estimate (MLE) and the Yule-Walker estimate (YW):

    ϕ\phi nn mean W mean MLE mean YW RMSE W RMSE MLE RMSE YW mean ∣\lvertW - MLE∣\rvert
    0.6 128 0.5920 0.5834 0.5791 0.0756 0.0756 0.0761 0.0120
    0.6 512 0.5981 0.5962 0.5951 0.0365 0.0368 0.0371 0.0031
    0.9 128 0.8779 0.8687 0.8594 0.0577 0.0581 0.0651 0.0156
    0.9 512 0.8961 0.8949 0.8927 0.0203 0.0185 0.0205 0.0045

    The three estimators have nearly the same error. The difference between the Whittle and exact estimates falls by about 4 when nn grows by 4, faster than the error itself, as the Op(1/n)O_p(1/n) gap between them predicts. An ARMA(1,1) fit with ϕ=0.5\phi = 0.5, θ=0.4\theta = 0.4 and n=1024n = 1024 (seed 7) is also in the tests.

  • Long memory. For a fractionally integrated ARMA model, f(λ)=σ22π∣1−e−iλ∣−2d∣θ(e−iλ)∣2/∣ϕ(e−iλ)∣2f(\lambda) = \frac{\sigma^2}{2\pi}\lvert 1 - e^{-i\lambda}\rvert^{-2d}\lvert\theta(e^{-i\lambda})\rvert^2/\lvert\phi(e^{-i\lambda})\rvert^2 with 0<d<1/20 < d < 1/2. The process has no finite state space form, so the exact likelihood costs O(n2)O(n^2) per evaluation by Durbin-Levinson. The Whittle estimator costs O(nlog⁡n)O(n\log n) once and O(n)O(n) per evaluation. Fox and Taqqu (1986) proved that it stays consistent and asymptotically normal for Gaussian long-memory processes.

  • Spatial data on a grid. For a stationary random field on an n1×n2n_1 \times n_2 grid, the exact likelihood needs a factorization of an N×NN \times N matrix with N=n1n2N = n_1 n_2, which is O(N3)O(N^3). The Whittle likelihood uses a two-dimensional FFT, O(Nlog⁡N)O(N\log N). Here the edge effects are larger: on a dd-dimensional grid with side nn, the bias is of order 1/n1/n while the standard error is of order n−d/2n^{-d/2}. For d=2d = 2 they are of the same order, and for d≥3d \ge 3 the bias dominates, so tapering or a debiased form is needed for valid N\sqrt{N} inference (Guyon 1982; Dahlhaus and Künsch 1987).

Variations

  • Tapered Whittle. Multiply the data by a taper hth_t that goes smoothly to 0 at both ends before line L1. This reduces the leakage of power from strong frequencies into weak ones, at the cost of some variance (Dahlhaus 1988 for time series; Dahlhaus and Künsch 1987 for random fields).
  • Debiased Whittle. Sykulski et al. (2019) replace fθ(ωj)f_\theta(\omega_j) by the expected periodogram fˉθ(ωj)=Eθ[I(ωj)]\bar f_\theta(\omega_j) = \mathbb{E}_\theta[I(\omega_j)], which is fθf_\theta smoothed by the Fejér kernel. It can be computed from the autocovariance in O(nlog⁡n)O(n\log n). This removes the main bias term and keeps the cost.
  • Local Whittle. Use only the lowest mm frequencies and the model f(λ)≈Gλ−2df(\lambda) \approx G\lambda^{-2d} near 0, to estimate the memory parameter dd without modelling the short-range part (Künsch 1987; Robinson 1995).
  • Multivariate Whittle. For a kk-dimensional series, use ∑j[log⁡det⁡(2πFθ(ωj))+tr⁡(Fθ(ωj)−1I(ωj))]\sum_j[\log\det(2\pi F_\theta(\omega_j)) + \operatorname{tr}(F_\theta(\omega_j)^{-1}\mathcal{I}(\omega_j))] with the spectral density matrix FθF_\theta and the periodogram matrix I\mathcal{I}.
  • Frequency-domain least squares. Minimizing ∑jI(ωj)/gβ(ωj)\sum_j I(\omega_j)/g_\beta(\omega_j) alone, without the log term, gives the same first-order asymptotics for ARMA models, because the log term averages to about 0.

Pitfalls

  • The mean. The periodogram at ω0=0\omega_0 = 0 is nxˉ2/(2π)n\bar x^2/(2\pi). If the mean is not 0, remove it and drop j=0j = 0. Otherwise the fit tries to explain the mean by power at frequency 0.
  • Small samples and peaked spectra. E[I(ωj)]\mathbb{E}[I(\omega_j)] differs from f(ωj)f(\omega_j) by leakage from nearby frequencies. When the spectrum has a sharp peak or a large dynamic range, the bias can be much larger than the standard error. Use a taper or the debiased form.
  • Nonstationary data. A trend or a unit root puts huge power at the lowest frequencies, and the fit becomes meaningless. Difference or detrend first, as in the ARIMA approach.
  • Identifiability. The spectral density does not change when a root of θ(z)\theta(z) or ϕ(z)\phi(z) is replaced by its reciprocal (with a change of σ2\sigma^2). Restrict the search to causal and invertible parameters, as the code does with its partial autocorrelation map.
  • The value is not the exact likelihood. The Whittle value differs from the exact −2log⁡L-2\log L by Op(1)O_p(1). Do not mix Whittle and exact values in one likelihood ratio or information criterion. Within the Whittle family, likelihood ratio tests and AIC work to first order.
  • Sampled continuous-time processes. For data sampled every Δ\Delta time units, the model spectrum must be the aliased density ∑kfc(λ+2πk/Δ)\sum_k f_c(\lambda + 2\pi k/\Delta), not fcf_c itself.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

whittle_likelihood.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/whittle-likelihood/. The authors are listed in prov/F9TJBR.jsonl.

"""The Whittle likelihood of a stationary series and the Whittle estimate of an ARMA(p, q) model.

Conventions:
    omega_j = 2 pi j / n,  j = 0, ..., n - 1 (the Fourier frequencies)
    I(omega_j) = |sum_(t=1..n) X_t exp(-i t omega_j)|^2 / (2 pi n)   (the periodogram)
    f(lambda) = (1 / (2 pi)) sum_h gamma(h) exp(-i h lambda)          (the spectral density)
    -2 log L_W = N log(2 pi) + sum_j [log(2 pi f(omega_j)) + I(omega_j) / f(omega_j)]
The sum runs over N frequencies: all n of them for a known zero mean, or j = 1..n-1 after
the sample mean is removed (the periodogram at j = 0 is then 0).
"""

from __future__ import annotations

import cmath
import math
from typing import Callable, Sequence


def fft(x: Sequence[complex]) -> list[complex]:
    """The DFT y_k = sum_t x_t exp(-2 pi i t k / n), t = 0..n-1.

    Radix-2 splitting while n is even, and the direct O(m^2) sum on an odd factor m, so a
    power of two costs O(n log n).
    """
    n = len(x)
    if n == 0:
        return []
    if n % 2 == 1:
        w = [cmath.exp(-2j * math.pi * k / n) for k in range(n)]
        return [sum(x[t] * w[(t * k) % n] for t in range(n)) for k in range(n)]
    even = fft(x[0::2])
    odd = fft(x[1::2])
    half = n // 2
    out = [0j] * n
    for k in range(half):
        tw = cmath.exp(-2j * math.pi * k / n) * odd[k]
        out[k] = even[k] + tw
        out[k + half] = even[k] - tw
    return out


def periodogram(x: Sequence[float]) -> list[float]:
    """I(omega_j) for j = 0..n-1 with the 1 / (2 pi n) scaling."""
    n = len(x)
    d = fft([complex(v) for v in x])
    return [abs(z) ** 2 / (2 * math.pi * n) for z in d]  # @line L1


def arma_spectral_density(phi: Sequence[float], theta: Sequence[float], sigma2: float,
                          lam: float) -> float:
    """f(lam) = sigma2 / (2 pi) |theta(e^(-i lam))|^2 / |phi(e^(-i lam))|^2."""
    z = cmath.exp(-1j * lam)
    num = 1 + sum(t * z ** (k + 1) for k, t in enumerate(theta))
    den = 1 - sum(a * z ** (k + 1) for k, a in enumerate(phi))
    return sigma2 / (2 * math.pi) * abs(num) ** 2 / abs(den) ** 2


def whittle_neg2loglik(x: Sequence[float], f: Callable[[float], float],
                       demean: bool = False) -> float:
    """-2 log L_W for the spectral density f. With demean, the mean is removed and j = 0 is dropped."""
    n = len(x)
    if demean:
        m = math.fsum(x) / n
        x = [v - m for v in x]
    per = periodogram(x)
    js = range(1, n) if demean else range(n)
    terms = []
    for j in js:
        fj = f(2 * math.pi * j / n)  # @line L2
        terms.append(math.log(2 * math.pi * fj) + per[j] / fj)  # @line L3
    return len(terms) * math.log(2 * math.pi) + math.fsum(terms)  # @line L4


def pacf_to_ar(r: Sequence[float]) -> list[float]:
    """Step-up (Durbin-Levinson) map from partial autocorrelations in (-1, 1) to a causal AR."""
    a: list[float] = []
    for k, rk in enumerate(r, start=1):
        a = [a[j] - rk * a[k - 2 - j] for j in range(k - 1)] + [rk]
    return a


def _unpack(u: Sequence[float], p: int, q: int) -> tuple[list[float], list[float]]:
    phi = pacf_to_ar([math.tanh(v) for v in u[:p]])
    theta = [-c for c in pacf_to_ar([math.tanh(v) for v in u[p:p + q]])]
    return phi, theta


def profiled_objective(per: Sequence[float], n: int, phi: Sequence[float],
                       theta: Sequence[float]) -> tuple[float, float]:
    """(-2 log L_W with sigma^2 profiled out, sigma2_hat), over j = 1..n-1."""
    g = [2 * math.pi * arma_spectral_density(phi, theta, 1.0, 2 * math.pi * j / n)
         for j in range(1, n)]
    big_n = n - 1
    sigma2 = 2 * math.pi * math.fsum(per[j] / g[j - 1] for j in range(1, n)) / big_n
    value = big_n * math.log(2 * math.pi) + big_n * math.log(sigma2) + \
        math.fsum(math.log(gj) for gj in g) + big_n
    return value, sigma2


def nelder_mead(fun: Callable[[list[float]], float], x0: Sequence[float], step: float = 0.3,
                tol: float = 1e-10, max_iter: int = 2000) -> list[float]:
    """Minimize fun by the Nelder-Mead simplex method with the standard coefficients."""
    d = len(x0)
    pts = [list(x0)] + [[x0[i] + (step if i == k else 0.0) for i in range(d)] for k in range(d)]
    vals = [fun(p) for p in pts]
    for _ in range(max_iter):
        order = sorted(range(d + 1), key=vals.__getitem__)
        pts = [pts[i] for i in order]
        vals = [vals[i] for i in order]
        if abs(vals[-1] - vals[0]) <= tol * (1 + abs(vals[0])):
            break
        cen = [math.fsum(p[i] for p in pts[:-1]) / d for i in range(d)]
        xr = [cen[i] + (cen[i] - pts[-1][i]) for i in range(d)]
        fr = fun(xr)
        if fr < vals[0]:
            xe = [cen[i] + 2 * (cen[i] - pts[-1][i]) for i in range(d)]
            fe = fun(xe)
            pts[-1], vals[-1] = (xe, fe) if fe < fr else (xr, fr)
        elif fr < vals[-2]:
            pts[-1], vals[-1] = xr, fr
        else:
            xc = [cen[i] + 0.5 * (pts[-1][i] - cen[i]) for i in range(d)]
            fc = fun(xc)
            if fc < vals[-1]:
                pts[-1], vals[-1] = xc, fc
            else:
                for k in range(1, d + 1):
                    pts[k] = [pts[0][i] + 0.5 * (pts[k][i] - pts[0][i]) for i in range(d)]
                    vals[k] = fun(pts[k])
    best = min(range(d + 1), key=vals.__getitem__)
    return pts[best]


def whittle_fit_arma(x: Sequence[float], p: int, q: int) -> tuple[list[float], list[float], float]:
    """Whittle estimate (phi_hat, theta_hat, sigma2_hat) of a causal invertible ARMA(p, q).

    The mean is removed, the periodogram is computed once by the FFT, and the profiled
    objective is minimized over unconstrained u with phi and theta built from tanh(u).
    """
    n = len(x)
    m = math.fsum(x) / n
    per = periodogram([v - m for v in x])
    if p + q == 0:
        return [], [], profiled_objective(per, n, [], [])[1]
    u = nelder_mead(lambda w: profiled_objective(per, n, *_unpack(w, p, q))[0], [0.0] * (p + q))  # @line L5
    phi, theta = _unpack(u, p, q)
    return phi, theta, profiled_objective(per, n, phi, theta)[1]
test_whittle_likelihood.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/whittle-likelihood/. The authors are listed in prov/F9TJBR.jsonl.

import cmath
import math
import random

import pytest

from whittle_likelihood import (
    arma_spectral_density,
    fft,
    pacf_to_ar,
    periodogram,
    whittle_fit_arma,
    whittle_neg2loglik,
)


def simulate_arma(phi, theta, n, rng, burn=300):
    e = [rng.gauss(0.0, 1.0) for _ in range(n + burn)]
    x = [0.0] * (n + burn)
    for t in range(n + burn):
        s = e[t] + sum(theta[j] * e[t - 1 - j] for j in range(len(theta)) if t - 1 - j >= 0)
        s += sum(phi[j] * x[t - 1 - j] for j in range(len(phi)) if t - 1 - j >= 0)
        x[t] = s
    return x[burn:]


def ar1_exact_neg2loglik(x, phi, sigma2):
    """Exact -2 log L of a zero-mean Gaussian AR(1) (the reference)."""
    n = len(x)
    s = (1 - phi * phi) * x[0] ** 2 + math.fsum((x[t] - phi * x[t - 1]) ** 2 for t in range(1, n))
    return n * math.log(2 * math.pi * sigma2) - math.log(1 - phi * phi) + s / sigma2


def ar1_exact_mle(x):
    """Exact Gaussian MLE of phi for a demeaned AR(1), by golden-section search."""
    n = len(x)
    m = math.fsum(x) / n
    d = [v - m for v in x]

    def obj(a):
        s = (1 - a * a) * d[0] ** 2 + math.fsum((d[t] - a * d[t - 1]) ** 2 for t in range(1, n))
        return n * math.log(s / n) - math.log(1 - a * a)

    lo, hi, gr = -0.9999, 0.9999, (math.sqrt(5) - 1) / 2
    for _ in range(80):
        c, e = hi - gr * (hi - lo), lo + gr * (hi - lo)
        if obj(c) < obj(e):
            hi = e
        else:
            lo = c
    return (lo + hi) / 2


def test_fft_matches_direct_dft():
    rng = random.Random(1)
    for n in list(range(1, 41)) + [64, 96, 128]:
        x = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(n)]
        direct = [sum(x[t] * cmath.exp(-2j * math.pi * t * k / n) for t in range(n)) for k in range(n)]
        assert max(abs(a - b) for a, b in zip(fft(x), direct)) < 1e-9 * n


def test_periodogram_parseval_and_symmetry():
    rng = random.Random(2)
    x = [rng.gauss(0, 1) for _ in range(50)]
    per = periodogram(x)
    assert math.fsum(per) == pytest.approx(math.fsum(v * v for v in x) / (2 * math.pi), rel=1e-12)
    assert all(per[j] == pytest.approx(per[50 - j], rel=1e-9, abs=1e-12) for j in range(1, 50))


def test_whittle_is_exact_for_white_noise():
    rng = random.Random(3)
    for n in (1, 7, 32, 45):
        x = [rng.gauss(0, 2) for _ in range(n)]
        s2 = 1.7
        exact = n * math.log(2 * math.pi * s2) + math.fsum(v * v for v in x) / s2
        assert whittle_neg2loglik(x, lambda lam: s2 / (2 * math.pi)) == pytest.approx(exact, rel=1e-12)


def test_spectral_density_integrates_to_the_autocovariance():
    phi, n = 0.6, 256
    for h in range(5):
        riemann = 2 * math.pi / n * math.fsum(
            arma_spectral_density([phi], [], 1.0, 2 * math.pi * j / n) * math.cos(h * 2 * math.pi * j / n)
            for j in range(n))
        assert riemann == pytest.approx(phi ** h / (1 - phi * phi), abs=1e-12)


def test_kolmogorov_formula_on_the_grid():
    # For a causal invertible ARMA, each factor (1 - a z) with |a| < 1 of phi or theta gives
    # prod_j (1 - a exp(-i omega_j)) = 1 - a^n, so the average of log(2 pi f / sigma^2) over the
    # n Fourier frequencies is a sum of terms (2 / n) log|1 - a^n|, which is tiny.
    for phi, theta in (([0.5], [0.4]), ([0.9], []), ([1.0, -0.5], [-0.3])):
        n = 512
        avg = math.fsum(math.log(2 * math.pi * arma_spectral_density(phi, theta, 1.0, 2 * math.pi * j / n))
                        for j in range(n)) / n
        assert abs(avg) < 1e-12


def test_pacf_to_ar_round_trip():
    rng = random.Random(4)
    for _ in range(50):
        p = rng.randint(1, 5)
        r = [rng.uniform(-0.95, 0.95) for _ in range(p)]
        a = pacf_to_ar(r)
        # step down: recover the partial autocorrelations
        back = []
        cur = a[:]
        for k in range(p, 0, -1):
            rk = cur[k - 1]
            back.append(rk)
            cur = [(cur[j] + rk * cur[k - 2 - j]) / (1 - rk * rk) for j in range(k - 1)]
        assert back[::-1] == pytest.approx(r, abs=1e-9)


def test_whittle_close_to_exact_likelihood_at_true_parameters():
    # Measured: the gap is O(1) while both values grow like n.
    rng = random.Random(5)
    for n in (128, 512):
        x = simulate_arma([0.6], [], n, rng)
        exact = ar1_exact_neg2loglik(x, 0.6, 1.0)
        wh = whittle_neg2loglik(x, lambda lam: arma_spectral_density([0.6], [], 1.0, lam))
        assert abs(wh - exact) / n < 0.02


def test_whittle_estimate_agrees_with_exact_mle():
    # Measured: r = 15 series of n = 256 from AR(1) with phi = 0.6, seed 6.
    rng = random.Random(6)
    diffs = []
    for _ in range(15):
        x = simulate_arma([0.6], [], 256, rng)
        phi_w = whittle_fit_arma(x, 1, 0)[0][0]
        diffs.append(abs(phi_w - ar1_exact_mle(x)))
    assert sum(diffs) / len(diffs) < 0.02


def test_arma11_fit_is_causal_invertible_and_near_truth():
    rng = random.Random(7)
    x = simulate_arma([0.5], [0.4], 1024, rng)
    phi, theta, s2 = whittle_fit_arma(x, 1, 1)
    assert abs(phi[0]) < 1 and abs(theta[0]) < 1
    # Asymptotic standard deviations are about 0.04 here; allow 4 of them.
    assert abs(phi[0] - 0.5) < 0.16 and abs(theta[0] - 0.4) < 0.16
    assert abs(s2 - 1.0) < 0.15

Exercises

  1. Show that for white noise, f≡σ2/(2π)f \equiv \sigma^2/(2\pi), the Whittle value with all nn frequencies equals the exact Gaussian −2log⁡L-2\log L. Hint: Parseval's identity gives ∑jI(ωj)=12π∑txt2\sum_j I(\omega_j) = \frac{1}{2\pi}\sum_t x_t^2.
  2. Derive the profiled scale σ^2(β)=2πN∑j∈JI(ωj)/gβ(ωj)\hat\sigma^2(\beta) = \frac{2\pi}{N}\sum_{j \in J} I(\omega_j)/g_\beta(\omega_j) and the profiled objective.
  3. Show that ∑j=0n−1log⁡∣1−ae−iωj∣2=2log⁡∣1−an∣\sum_{j=0}^{n-1}\log\lvert 1 - a e^{-i\omega_j}\rvert^2 = 2\log\lvert 1 - a^n\rvert for ∣a∣<1\lvert a\rvert < 1. Hint: ∏j(z−e−iωj)=zn−1\prod_j(z - e^{-i\omega_j}) = z^n - 1.
  4. Prove that the AR(1) Whittle estimate with known mean, without the term −2log⁡∣1−ϕn∣-2\log\lvert 1 - \phi^n\rvert, is c~1/c~0\tilde c_1/\tilde c_0, and that ∣c~1/c~0∣≤1\lvert\tilde c_1/\tilde c_0\rvert \le 1.
  5. Show that the circulant CnC_n with first row γ~(h)=∑kγ(h+kn)\tilde\gamma(h) = \sum_k\gamma(h + kn) has eigenvalues 2πf(ωj)2\pi f(\omega_j).

References

  1. Peter Whittle, Estimation and information in stationary time series, Arkiv för Matematik 2(5), 1953, pp. 423 to 434 (the frequency-domain approximation of the Gaussian likelihood and the asymptotic information)
  2. Peter J. Brockwell and Richard A. Davis, Time Series: Theory and Methods, second edition, Springer, 1991, Section 10.3 (asymptotic properties of the periodogram, p. 342), Section 10.7 (the fast Fourier transform, p. 373) and Section 10.8 (asymptotic behaviour of the maximum likelihood and Whittle estimators of ARMA coefficients, p. 375)
  3. Peter J. Brockwell and Richard A. Davis, Introduction to Time Series and Forecasting, third edition, Springer, 2016, Section 4.2 (the periodogram, p. 106)
  4. Adam M. Sykulski, Sofia C. Olhede, Arthur P. Guillaumin, Jonathan M. Lilly and Jeffrey J. Early, The debiased Whittle likelihood, Biometrika 106(2), 2019, the expected periodogram in place of the spectral density, its O(n log n) computation, and the reduction of the small-sample bias

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • five exercises