diff --git a/CHANGELOG.md b/CHANGELOG.md index d9c3438..802c7a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,16 @@ compiled C engine. ## Unreleased +**The own MA factors, each read alone, are said when outside the circle** — +the C's `own_ma_outside` (atsw-gui #223). The likelihood is evaluated only +where the MA operator of the system is invertible, and the ladder does not +take the invertible form of a coefficient (BUG-0030), so an own factor can +end outside the unit circle read alone, which fue never estimates. +`Fit.own_ma_outside` lists them (series, kind, order, coefficient, inverse +root modulus); the report adds the C's block, line for line, and the command +line its warning. Nothing else changes. The C's muskrat and mink files are +now among the fixtures, and that case is in the homologation record. + **The ladder follows the C along the MA wall (BUG-0030).** Where the search runs along the invertibility wall there is no interior maximum, and the port did not end where the C does. Three causes, all in the port, found by tracing diff --git a/src/drvarma/ladder.py b/src/drvarma/ladder.py index 0ce22f2..a3c76c1 100644 --- a/src/drvarma/ladder.py +++ b/src/drvarma/ladder.py @@ -52,6 +52,68 @@ def _lik_label(lik): MA_WALL_TOL = 5e-5 +def _own_ma_outside(series): + """The own MA factors of each series, each read ALONE, whose largest + inverse root has modulus >= 1 - MA_WALL_TOL: the C's own_ma_outside + (escalera.c), in its order -- series by series, the regular factors, the + seasonal ones, the fixed-frequency ones. + + The likelihood is evaluated only where the MA operator of the SYSTEM is + invertible, and the ladder does not take the invertible form of a + coefficient (BUG-0030): in a system, inverting one element of Theta is + not the same model. So an own factor can end outside the unit circle read + alone, which fue never estimates. It is said; nothing changes. + + Returns [(series, kind, order, coefficient text, modulus)]. + """ + from fue.forecast import _reconstruct_params + out = [] + + def modulus(c): + c = np.asarray(c, float) + q = c.size + if q == 0: + return 0.0 + if q == 1: + return abs(float(c[0])) + A = np.zeros((q, q)) + A[0, :] = c + A[1:, :-1] = np.eye(q - 1) + return float(np.max(np.abs(np.linalg.eigvals(A)))) + + for s in series: + (_om, _de, _ar, _ars, ma, ma_s, _arf, ma_f, _mu) = _reconstruct_params(s.model, s.x) + for kind, sym, facs in (("regular MA", "theta", ma), ("seasonal MA", "Theta", ma_s)): + for f in facs: + md = modulus(f) + if md >= 1.0 - MA_WALL_TOL: + coef = f"{sym} = {float(f[0]):.6f}" if len(f) == 1 else "" + out.append((s.name, kind, len(f), coef, md)) + for c2 in ma_f: + c2 = float(c2) + md = math.sqrt(-c2) if c2 < 0.0 else 0.0 + if md >= 1.0 - MA_WALL_TOL: + out.append((s.name, "fixed-frequency MA", 2, f"c2 = {c2:.6f}", md)) + return out + + +def _own_ma_text(own): + """The C's block of the .out for own_ma_outside, line for line.""" + if not own: + return [] + out = ["", "OWN MA FACTORS NOT INVERTIBLE, EACH READ ALONE:"] + for name, kind, q, coef, md in own: + what = kind if kind == "fixed-frequency MA" else f"{kind}({q})" + out.append(f" {name:<14} {what:<22} {coef:<20} inverse root modulus {md:.6f} " + f"({'beyond the unit circle' if md >= 1.0 + MA_WALL_TOL else 'on the unit circle'})") + out += [" The likelihood is evaluated only where the MA operator of the SYSTEM", + " is invertible, so this is a point of the joint model: each own factor", + " is one block of that operator, not a univariate model. Read alone it", + " is not invertible -- fue never estimates such a factor -- and it is", + " not to be read or reported as one."] + return out + + def _cast_us(x, spec): """fue's cast of one series, WITHOUT fue's flip (BUG-0030). @@ -679,6 +741,9 @@ class Fit: ma_boundary: int = 0 # MA inverse roots on the wall at the stop ma_nroots: int = 0 # (the C's est(): a stop on the invertibility wall) cov: np.ndarray = None # covariance of the estimates (se_method's Hessian) + # own MA factors not invertible read alone (the C's own_ma_outside): + # [(series, kind, order, coefficient text, inverse-root modulus)] + own_ma_outside: list = field(default_factory=list) @property def npar(self): @@ -1424,7 +1489,8 @@ def objective(vec): return Fit(names, xhat, se, float(logL), float(f1 / (n * m)), int(ifa), int(nit), int(termcode), mu, phi, theta, qq, w, np.asarray(a)[1:, 1:].copy(), # elf_c: 1-based out - se_method, None if fk is None else float(fk), nb, nr, cov) + se_method, None if fk is None else float(fk), nb, nr, cov, + _own_ma_outside([self.series[i] for i in self._act])) def _std_errors(self, objective, xhat, fk, n, bfac, nit=1): """Mauricio's fdhess at the optimum (drvarma.stderr), or the BFGS @@ -2369,6 +2435,7 @@ def write_report(L, path, forecasts=None, recursive=None): "Cross dynamics against the diagonal system (the univariates):"), f" logL diagonal {L.logL_diag:.6f}, logL full {r.logL:.6f}", f" LR = {lr:.4f} df = {df} p-value = {pv:.4f}"] + out += _own_ma_text(getattr(r, "own_ma_outside", None)) out += ["", f"Innovation covariance Sigma = sigma2 * Q (sigma2 = {r.sigma2:.8g}):"] for a, row in enumerate(r.sigma): out.append(f" {S[a].name:<14}" + "".join(f" {v:14.6g}" for v in row)) @@ -2488,6 +2555,10 @@ def main(argv): write_recursive(L, rec[0], a.forecast, name + ".recursive") write_report(L, name + ".out", fc, rec) print(f"Exact log-likelihood: {L.result.logL:.6f}") + own = L.result.own_ma_outside + if own: + print("WARNING: own MA factor(s) not invertible read alone: " + + ", ".join(f"{o[0][:40]} ({o[4]:.4f})" for o in own)) print(f"Full results written to {name}.out") return 0 diff --git a/tests/data/homologation.json b/tests/data/homologation.json index 499685f..6ab093e 100644 --- a/tests/data/homologation.json +++ b/tests/data/homologation.json @@ -2,7 +2,7 @@ "_": "The record of the homologation with the C engine. tests/test_c_oracle.py reads it; docs/HOMOLOGATION.md explains it.", "c_repository": "davidesg/atsw-gui", "c_path": "engines/drvarma", - "c_commit": "d38a71f0f3e13d5a296cf128bf856cbaad5aa1e9", + "c_commit": "29bd4f2f9724aea6994abf52499af86d0afb1b8f", "date": "2026-11-22", "cases": [ { @@ -259,6 +259,22 @@ "logL": -626.197302, "npar": 16, "nit": 212 + }, + { + "name": "route U, an own MA factor ends beyond the circle: muskrat and mink, VARMA(2,1), from zero", + "files": [ + "lib/outvarma/datos/MUSKRAT_m03.pre", + "lib/outvarma/datos/MINK_m02.pre" + ], + "c_args": "2 1 -start zero", + "port": { + "p": 2, + "q": 1, + "start": "zero" + }, + "logL": -551.715772, + "npar": 20, + "nit": 124 } ], "csrc": { diff --git a/tests/data/ladder/MINK_m02.pre b/tests/data/ladder/MINK_m02.pre new file mode 100644 index 0000000..b1c59d9 --- /dev/null +++ b/tests/data/ladder/MINK_m02.pre @@ -0,0 +1,99 @@ +************************************************ +* Input file for program DRVUS * +* Copyright (C) 1996 Jos? Alberto Mauricio * +************************************************ + +** Frequency of time series: either 1(A), 4(Q) or 12(M): + 1 +** Number of observations and starting date of time series: + 62 1911 1850 MINK +** Number of deterministic variables (including seasonal components): + 0 +**Number and orders of regular AR operators: +1 4 +** +0.8022 1 +-0.2131 1 +0.0029 1 +-0.2693 1 +** Number and orders of annual AR operators: +0 +** Number and orders of regular MA operators: +0 +** Number and orders of anual MA operators: +0 +** Number and frequencies of regular AR(2) operators with fixed frequency: +0 +** Number and frequencies of regular MA(2) operators with fixed frequency: +0 +** Mean parameter (mu): +1082.094484 1 +** Box-Cox lambda, regular differences and complete annual differences: +0.00 0 0 +** Individual factors of the annual difference (from freq 0.0): + 0 +** ACF/PACF bands (0 Automatic) and reescaling factor: + 0.00 100.00 +** Time series (stochastic and non-standard deterministic variables): +29619.0000000000 +21151.0000000000 +24859.0000000000 +25152.0000000000 +42375.0000000000 +50839.0000000000 +61581.0000000000 +61951.0000000000 +76231.0000000000 +63264.0000000000 +44730.0000000000 +31094.0000000000 +49452.0000000000 +43961.0000000000 +61727.0000000000 +60334.0000000000 +51404.0000000000 +58451.0000000000 +73575.0000000000 +74343.0000000000 +27708.0000000000 +31985.0000000000 +39266.0000000000 +44740.0000000000 +60429.0000000000 +72273.0000000000 +79214.0000000000 +79060.0000000000 +84244.0000000000 +62590.0000000000 +35072.0000000000 +36160.0000000000 +45600.0000000000 +47508.0000000000 +52290.0000000000 +110824.0000000000 +76503.0000000000 +64303.0000000000 +83023.0000000000 +40748.0000000000 +35396.0000000000 +29479.0000000000 +42264.0000000000 +58171.0000000000 +50815.0000000000 +51285.0000000000 +70229.0000000000 +76365.0000000000 +70407.0000000000 +41839.0000000000 +45978.0000000000 +47813.0000000000 +57620.0000000000 +66549.0000000000 +54673.0000000000 +55996.0000000000 +60053.0000000000 +39169.0000000000 +21534.0000000000 +17857.0000000000 +21788.0000000000 +33008.0000000000 diff --git a/tests/data/ladder/MUSKRAT_m03.pre b/tests/data/ladder/MUSKRAT_m03.pre new file mode 100644 index 0000000..d5b0a60 --- /dev/null +++ b/tests/data/ladder/MUSKRAT_m03.pre @@ -0,0 +1,103 @@ +************************************************ +* Input file for program DRVUS * +* Copyright (C) 1996 Jos? Alberto Mauricio * +************************************************ + +** Frequency of time series: either 1(A), 4(Q) or 12(M): + 1 +** Number of observations and starting date of time series: + 62 1911 1850 MUSKRAT +** Number of deterministic variables (including seasonal components): + 0 +**Number and orders of regular AR operators: +1 6 +** +0.6522 1 +-0.5833 1 +0.2178 1 +-0.3080 1 +-0.0395 1 +-0.3188 1 +** Number and orders of annual AR operators: +0 +** Number and orders of regular MA operators: +1 1 +** +0.5454 1 +** Number and orders of anual MA operators: +0 +** Number and frequencies of regular AR(2) operators with fixed frequency: +0 +** Number and frequencies of regular MA(2) operators with fixed frequency: +0 +** Mean parameter (mu): +0 +** Box-Cox lambda, regular differences and complete annual differences: +0.00 1 0 +** Individual factors of the annual difference (from freq 0.0): + 0 +** ACF/PACF bands (0 Automatic) and reescaling factor: + 0.00 100.00 +** Time series (stochastic and non-standard deterministic variables): +175472.0000000000 +194682.0000000000 +292530.0000000000 +493952.0000000000 +512291.0000000000 +345626.0000000000 +258806.0000000000 +302267.0000000000 +313502.0000000000 +254246.0000000000 +177291.0000000000 +206020.0000000000 +335385.0000000000 +357060.0000000000 +509769.0000000000 +418370.0000000000 +320824.0000000000 +412164.0000000000 +618081.0000000000 +404173.0000000000 +232251.0000000000 +443999.0000000000 +704789.0000000000 +767896.0000000000 +671982.0000000000 +523802.0000000000 +583319.0000000000 +437121.0000000000 +486030.0000000000 +499727.0000000000 +478078.0000000000 +829034.0000000000 +1029296.0000000000 +1069183.0000000000 +1083067.0000000000 +817003.0000000000 +347050.0000000000 +380132.0000000000 +344878.0000000000 +223614.0000000000 +322160.0000000000 +574742.0000000000 +806103.0000000000 +934646.0000000000 +648687.0000000000 +674811.0000000000 +813159.0000000000 +551716.0000000000 +568934.0000000000 +701487.0000000000 +767741.0000000000 +928199.0000000000 +1650214.0000000000 +1488287.0000000000 +924439.0000000000 +1056253.0000000000 +695070.0000000000 +407472.0000000000 +172418.0000000000 +302195.0000000000 +749142.0000000000 +963597.0000000000 diff --git a/tests/test_own_ma_outside.py b/tests/test_own_ma_outside.py new file mode 100644 index 0000000..f563d79 --- /dev/null +++ b/tests/test_own_ma_outside.py @@ -0,0 +1,69 @@ +"""An own MA factor read alone outside the unit circle: the C's +own_ma_outside (escalera.c, 23-nov-2026), said in the fit and in the report. + +The ladder does not take the invertible form of a coefficient (BUG-0030): +the likelihood is evaluated only where the system's MA operator is +invertible. So an own factor can end outside the circle read alone, which fue +never estimates. Muskrat and mink, VARMA(2,1), route U, from zero: the +optimiser stops (no lower point, termcode 3; not on the system's wall) +with theta_MUSKRAT = 1.5483 (the C: -551.715772); from +ols it stops on the wall at -545.562324, with no own factor outside. +""" +import os + +import numpy as np +import pytest + +from drvarma.ladder import Ladder, _own_ma_outside, _own_ma_text, write_report + +D = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "ladder") +MM = [os.path.join(D, "MUSKRAT_m03.pre"), os.path.join(D, "MINK_m02.pre")] # the C's files + + +def _kernel(): + """The compiled likelihood, on the platform of the record: this stop is + not an interior maximum, and the point is the path's (HOMOLOGATION.md).""" + import platform + import sys + from drvarma import _engine + return (_engine.engine_backend() == "c" and sys.platform.startswith("linux") + and platform.machine() in ("x86_64", "AMD64")) + + +@pytest.mark.skipif(not _kernel(), reason="the path to this point is the compiled likelihood's, on Linux x86-64") +def test_the_muskrat_factor_beyond_the_circle_is_said(tmp_path): + L = Ladder(MM, 2, 1, start="zero") + r = L.fit() + assert r.logL == pytest.approx(-551.715772, abs=1e-5) + assert len(r.own_ma_outside) == 1 + name, kind, q, coef, md = r.own_ma_outside[0] + assert (name, kind, q) == ("MUSKRAT", "regular MA", 1) + assert coef.startswith("theta = 1.5482") and md == pytest.approx(1.548284, abs=1e-5) + out = tmp_path / "r.out" + write_report(L, str(out)) + txt = out.read_text() + assert "OWN MA FACTORS NOT INVERTIBLE, EACH READ ALONE:" in txt + assert "beyond the unit circle" in txt and "fue never estimates such a factor" in txt + + +@pytest.mark.skipif(not _kernel(), reason="the path to this point is the compiled likelihood's, on Linux x86-64") +def test_nothing_is_said_when_no_own_factor_is_outside(): + L = Ladder(MM, 2, 1, start="ols") + r = L.fit() + assert r.logL == pytest.approx(-545.562324, abs=1e-5) + assert r.own_ma_outside == [] and _own_ma_text(r.own_ma_outside) == [] + + +def test_the_check_reads_each_factor_alone(): + """MA(1) by its coefficient, a higher order by its companion's roots, a + fixed-frequency MA by sqrt(-c2); the wall's tolerance as the C's.""" + L = Ladder(MM, 0, 0) + s = [x for x in L.series if x.name == "MUSKRAT"][0] + nm = s.param_names() + k = nm.index("theta_MUSKRAT[B^1]") + keep = s.x.copy() + for v, n in ((0.99, 0), (0.99996, 1), (-1.2, 1)): + s.x[k] = v + assert len(_own_ma_outside([s])) == n + s.x[:] = keep + assert _own_ma_outside([s]) == []