Parameter estimation¶
Three estimators: moment matching and joint maximum likelihood when both \(X\) and \(Y\) are observed, and maximum likelihood from \(Y\) alone through the Kalman likelihood. From \(Y\) alone the tuple is only identifiable up to a two-dimensional class (same \((c, \operatorname{tr}A, \det A)\)): only the forecasts of \(Y\) are meaningful.
Estimators¶
estimate_pmm_from_moments ¶
estimate_pmm_from_moments(x: ArrayLike, y: ArrayLike) -> ParamPMM
Estimate the (a, b, c, d, e) tuple from sample lag-1 covariances.
Matches the empirical 4×4 covariance of (X_n, Y_n, X_{n+1}, Y_{n+1})
to Γ_PMM ; rescales the inputs to unit variance to enforce the PMM
stationarity assumption. O(n) cost, no optimisation, deterministic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ArrayLike
|
Two 1-D arrays of equal length carrying the observed state and observation trajectories. |
required |
y
|
ArrayLike
|
Two 1-D arrays of equal length carrying the observed state and observation trajectories. |
required |
Returns:
| Type | Description |
|---|---|
class:`ParamPMM`
|
Reconstructed PMM. May not coincide with any "ground-truth" PMM if the data is not actually generated by a PMM (see Tutorial 05); in that case the recovered tuple is the closest PMM in the L² sense of the lag-1 cross-covariances. |
Raises:
| Type | Description |
|---|---|
:class:`~pmmforecast.utils.exceptions.ParamPMMError`
|
If the estimated tuple yields a non-positive-definite Γ — happens when the empirical moments are inconsistent with any stationary PMM (e.g. very short or pathological series). |
estimate_pmm_mle ¶
estimate_pmm_mle(x: ArrayLike, y: ArrayLike, *, x0: tuple[float, float, float, float, float] | None = None, method: str = 'Nelder-Mead', max_iter: int = 2000) -> tuple[ParamPMM, sp_opt.OptimizeResult]
Estimate (a, b, c, d, e) by maximum likelihood. Experimental.
Optimises -log L(a, b, c, d, e | X, Y) via scipy.optimize.minimize
starting from the moments estimate (or from x0 if supplied). Series
are auto-standardised to unit variance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ArrayLike
|
Observed state and observation trajectories. |
required |
y
|
ArrayLike
|
Observed state and observation trajectories. |
required |
x0
|
tuple[float, float, float, float, float] | None
|
Optional initial guess. Defaults to the moments estimator. |
None
|
method
|
str
|
Any |
'Nelder-Mead'
|
max_iter
|
int
|
Forwarded as |
2000
|
Returns:
| Type | Description |
|---|---|
(params, result)
|
The MLE :class: |
Notes
Assumes both X and Y are observed. The "Y only" case is covered by
:func:estimate_pmm_mle_y_only.
estimate_pmm_mle_y_only ¶
estimate_pmm_mle_y_only(y: ArrayLike, *, x0: tuple[float, float, float, float, float] | None = None, n_restarts: int = 1, method: str = 'Nelder-Mead', max_iter: int = 2000, seed: int = 0) -> tuple[ParamPMM, sp_opt.OptimizeResult]
Estimate (a, b, c, d, e) from observations Y alone.
Optimises the marginal log-likelihood log p(Y_1^N | theta) via
the innovations / Kalman-likelihood decomposition — equivalent
to EM in the limit, but more direct since the PMM filter already
yields the prediction means and variances. Experimental.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
ArrayLike
|
1-D observation series. Auto-standardised to mean 0 / variance 1.
|
required |
x0
|
tuple[float, float, float, float, float] | None
|
Optional initial guess for the first restart. Defaults to a
neutral well-conditioned PMM tuple (Tutorial 07's
|
None
|
n_restarts
|
int
|
Number of optimiser restarts (default 1, no restart). The
first restart starts from |
1
|
method
|
str
|
Forwarded to :func: |
'Nelder-Mead'
|
max_iter
|
str
|
Forwarded to :func: |
'Nelder-Mead'
|
seed
|
int
|
RNG seed for the random restart draws (default 0). Set to
|
0
|
Returns:
| Type | Description |
|---|---|
(params, result)
|
MLE :class: |
Notes
Identifiability: weak. With Q₁ = [[1, b], [b, 1]],
Q₂ = [[a, e], [d, c]] and A = Q₂ Q₁⁻¹, the law of Y (a
Gaussian ARMA(2, 1)) depends on the tuple only through
c,tr A = (a + c - b (d + e)) / (1 - b²),det A = (a c - d e) / (1 - b²),
since γ(k) = tr A · γ(k-1) - det A · γ(k-2) for k ≥ 2 with
γ(0) = 1, γ(1) = c. A 2-dimensional set of tuples therefore
shares exactly the same likelihood ; it contains the sign flip
(b, d, e) -> -(b, d, e) and the swap d <-> e, but is much
larger. The estimated tuple is not interpretable on its own ; only
the resulting forecasts of Y are. The post-processing b >= 0 is
a cosmetic convention that selects one member of that set.
Starting points (M2): unless x0 is given, the optimiser is also
started from an AR(1)-like tuple (0.5, 0.3, r, 0.3 r, 0.3 r), where
r is the lag-1 autocorrelation of the standardised series clipped
to [-0.999, 0.999], in addition to the default start and the
n_restarts - 1 random ones. On persistent series (r close to 1)
the default start otherwise converges to a spurious region whose
likelihood can be below that of the AR(1) sub-model. A warning is
logged if the returned fit is still worse than that sub-model.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Likelihoods¶
neg_log_likelihood_xy ¶
neg_log_likelihood_xy(params_tuple: ndarray, x_arr: ndarray, y_arr: ndarray) -> float
Negative log-likelihood of an observed trajectory under PMM(params).
Returns +inf for tuples that fail the strict PMM constructor
(non-PD Γ or non-PD BBᵀ), so the optimiser is naturally repelled from
the algebraic boundary. Internally the joint Gaussian density is
factored as p(z_1) · ∏ p(z_n | z_{n-1}) since this is exactly the
form the PMM dynamics provide (eqs. (2)-(4) of the LaTeX intro).
neg_log_likelihood_y_only ¶
neg_log_likelihood_y_only(params_tuple: ndarray, y_arr: ndarray) -> float
Negative log-likelihood of Y_1^N alone under the PMM.
Uses the prediction-error decomposition (a.k.a. "Kalman likelihood"):
.. math:: \log p(y_1^N|\theta) = \sum_{n=1}^N \log p(y_n | y_1^{n-1}, \theta).
The conditional p(Y_n | Y_1^{n-1}, theta) is Gaussian with mean
m_n^Y = alpha_3 * E[X_{n-1}|Y_1^{n-1}] + alpha_4 * Y_{n-1} and
variance S_n^{YY} = alpha_3^2 * Var[X_{n-1}|Y_1^{n-1}] + beta_3,
both given by the PMM filter recursions (:class:PMMFilter1D). Y_1
itself has marginal N(0, 1) since the PMM is zero-mean unit-variance.
Implementation: the variance recursion is data-independent and converges
geometrically, so it is run in scalars up to its fixed point ; the mean
recursion is then a first-order linear filter (scipy.signal.lfilter on
the converged tail) and the likelihood terms are summed in one vectorised
pass. It matches the step-by-step :class:PMMFilter1D computation to
about 1e-14 (relative) and is roughly 250x faster at n = 21 600
(0.26 s down to 1 ms per evaluation).
NaN entries of y_arr are missing values : they contribute
nothing and the filter predicts through them (general Kalman pass of
:meth:PMMFilter1D.filter_state, about 25 ms at n = 21 600, vs
about 1 ms for the complete-data fast path below).
Returns +inf for tuples that fail the strict constructor or
drive the filter to non-finite values, so the optimiser is repelled
from the algebraic boundary.
Uncertainty and model selection¶
compute_standard_errors ¶
compute_standard_errors(nll_fn: Callable[..., float], params_tuple: ArrayLike, args: tuple, *, eps: float | None = None) -> tuple[np.ndarray, np.ndarray]
Asymptotic standard errors of MLE parameters via numerical Hessian.
At the MLE point, the asymptotic covariance of the parameter
estimates is approximately inv(Hessian of NLL). sqrt of its
diagonal gives one-σ standard errors. This is the textbook
sandwich-formula simplification valid under regularity conditions
(smooth interior of the parameter space, well-conditioned Hessian).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nll_fn
|
Callable[..., float]
|
Negative log-likelihood function with signature
|
required |
params_tuple
|
ArrayLike
|
MLE point (1-D array, |
required |
args
|
tuple
|
Extra positional arguments forwarded to |
required |
eps
|
float | None
|
Finite-difference step. Defaults to |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
standard_errors |
(ndarray, shape(K))
|
|
covariance |
(ndarray, shape(K, K))
|
|
Raises:
| Type | Description |
|---|---|
LinAlgError
|
If the Hessian is exactly singular and cannot be inverted — typically indicates that the optimiser stopped before reaching a true local minimum, or that the model is non-identifiable on the data. |
confidence_intervals ¶
confidence_intervals(params_tuple: ArrayLike, standard_errors: ArrayLike, *, alpha: float = 0.05) -> np.ndarray
Symmetric Wald confidence intervals from MLE standard errors.
Returns a (K, 2) array of [lower, upper] bounds at the
requested confidence level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params_tuple
|
ArrayLike
|
MLE estimate (1-D, length |
required |
standard_errors
|
ArrayLike
|
Output of :func: |
required |
alpha
|
float
|
Confidence level complement: |
0.05
|
Returns:
| Type | Description |
|---|---|
(ndarray, shape(K, 2))
|
Each row is |
aic_bic ¶
aic_bic(log_likelihood: float, n_params: int, n_obs: int) -> tuple[float, float]
Akaike and Bayesian Information Criteria from a maximised log-likelihood.
Both criteria penalise model complexity ; lower is better. They are useful to compare non-nested fits — e.g. two PMMs estimated from different starting points, or PMM vs HMM when Wilks' theorem regularity conditions are doubtful.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
log_likelihood
|
float
|
Maximised log-likelihood |
required |
n_params
|
int
|
Number of free parameters. |
required |
n_obs
|
int
|
Number of independent observations (typically the joint-trajectory
length |
required |
Returns:
| Type | Description |
|---|---|
aic, bic : tuple[float, float]
|
|
Helpers¶
standardise ¶
standardise(arr: ArrayLike, *, allow_missing: bool = False) -> np.ndarray
Centre and rescale arr to mean 0 / variance 1 (population stddev).
With allow_missing=True, NaN entries are treated as missing :
the mean and standard deviation are computed on the observed values
and the NaN are kept in place.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input contains infinite values, NaN values (unless
|
empirical_moments ¶
empirical_moments(x: ArrayLike, y: ArrayLike) -> tuple[float, float, float, float, float]
Return (a, b, c, d, e) from the empirical lag-0/lag-1 covariances.
The mapping follows directly from Γ_PMM (pmmforecast.models.param_pmm):
a = E[X_n X_{n+1}], b = E[X_n Y_n], c = E[Y_n Y_{n+1}],
d = E[X_n Y_{n+1}], e = E[Y_n X_{n+1}].
The series are auto-standardised to unit variance before matching,
so the PMM assumption Var[X_n] = Var[Y_n] = 1 holds by
construction.