From d09c059595c0d98353fad43382ab87ba30bfa214 Mon Sep 17 00:00:00 2001 From: warriord Date: Sat, 28 Nov 2026 01:05:02 +0100 Subject: [PATCH] BUG-0002: the compiled engine is the C of record; BUG-0033 registered csrc/internal/ was an old copy of the C, and its .inp path (estimate_w, Model) had drifted from atsw-gui's: the line search, the boundary sentinel, the MA wall count. Every vendored file is now atsw-gui's at d603ea1, identical: drvmlest.c, qnewtopt.c, nlatools.c, elfvarma.c, main.h, likhost.h, optimhost.h, and lib/lik/{lik.c, lik.h, multshea.c}, lib/optim/lnsrch.c and lib/fuepre/tusmodel.h, which they now need. drvarma_api.c reads the verdict from opt_termcode/opt_iters, holds qq[1,1] as the C's .inp path (est_fixed) and returns se_how and the MA wall count. estimate_w(hessian="fd") asks the C for its own fdhess; with the compiled engine Model uses it, without it fdhess in Python as before. - tests/data/homologation.json: each file's sha256, identical to the C's; test_c_oracle.py passes whole against d603ea1 (36 passed, ATSW_GUI). - tests/test_inp_path_as_the_c.py: six cases of the C's battery (tests/banco/ref); with the compiled engine the parameter table is the C's line for line. - BUG-0033: the pure-Python .inp estimator is not the C's on four of them (PSW ARMA(1,1) stops 0.22 below). Repro; the cases are xfail. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LHFMF3teQWFeXfDJVGj2p5 --- CHANGELOG.md | 10 + ...ces-are-copies-and-have-already-drifted.md | 24 +- ...-de-la-via-inp-no-llega-al-optimo-del-c.md | 62 +++++ bugs/BUG-0033-repro/PSW.inp | 228 ++++++++++++++++++ bugs/BUG-0033-repro/repro.py | 37 +++ bugs/README.md | 7 +- csrc/drvarma_api.c | 14 +- csrc/drvarma_api.h | 5 + csrc/internal/drvmlest.c | 201 +++++++++++++-- csrc/internal/lik.c | 165 +++++++++++++ csrc/internal/lik.h | 35 +++ csrc/internal/likhost.h | 6 + csrc/internal/lnsrch.c | 145 +++++++++++ csrc/internal/main.h | 42 ++-- csrc/internal/multshea.c | 5 +- csrc/internal/nlatools.c | 34 +-- csrc/internal/optimhost.h | 6 + csrc/internal/qnewtopt.c | 205 +++++----------- csrc/internal/tusmodel.h | 55 +++++ docs/HOMOLOGATION.md | 33 +-- src/drvarma/_build_cffi.py | 6 + src/drvarma/_engine.py | 31 ++- src/drvarma/model.py | 8 +- tests/data/homologation.json | 74 ++++-- tests/data/inp_c/IPC.inp | 228 ++++++++++++++++++ tests/data/inp_c/IPC_eu_levels.inp | 228 ++++++++++++++++++ tests/data/inp_c/PSW.inp | 228 ++++++++++++++++++ tests/data/inp_c/cases.json | 185 ++++++++++++++ tests/test_inp_path_as_the_c.py | 88 +++++++ 29 files changed, 2139 insertions(+), 256 deletions(-) create mode 100644 bugs/BUG-0033-el-port-puro-de-la-via-inp-no-llega-al-optimo-del-c.md create mode 100644 bugs/BUG-0033-repro/PSW.inp create mode 100644 bugs/BUG-0033-repro/repro.py create mode 100644 csrc/internal/lik.c create mode 100644 csrc/internal/lik.h create mode 100644 csrc/internal/likhost.h create mode 100644 csrc/internal/lnsrch.c create mode 100644 csrc/internal/optimhost.h create mode 100644 csrc/internal/tusmodel.h create mode 100644 tests/data/inp_c/IPC.inp create mode 100644 tests/data/inp_c/IPC_eu_levels.inp create mode 100644 tests/data/inp_c/PSW.inp create mode 100644 tests/data/inp_c/cases.json create mode 100644 tests/test_inp_path_as_the_c.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 8bf06fe..be07fa5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,16 @@ The binary wheels were per minor version and stopped at cp314; on CPython abi3audit). The pure `py3-none-any` wheel stays, for every platform without a binary (free-threaded builds, 32-bit Windows, others). +**The compiled engine is the C of record (BUG-0002).** `csrc/` was an old +copy of the C: its `.inp` path (`estimate_w`, `Model`) had drifted from +atsw-gui's (the optimizer's line search, the boundary sentinel, the MA wall +count). Every vendored file is now atsw-gui's, identical, with `lib/lik` and +`lib/optim/lnsrch.c`, and with the compiled engine `Model` takes its fdhess +standard errors from the C itself (`estimate_w(hessian="fd")`): on six cases +of the C's battery the parameter table is the C's line for line +(`tests/test_inp_path_as_the_c.py`). The pure-Python `.inp` estimator is not +yet the C's on four of them (BUG-0033). + **DRVARMA_NO_ENGINE reaches `elf_c` and `marma_c` (BUG-0032).** Only `estimate_w` read it, so the ladder went on computing in C while `engine_backend()` said "python". diff --git a/bugs/BUG-0002-c-sources-are-copies-and-have-already-drifted.md b/bugs/BUG-0002-c-sources-are-copies-and-have-already-drifted.md index 406b56c..57abe4e 100644 --- a/bugs/BUG-0002-c-sources-are-copies-and-have-already-drifted.md +++ b/bugs/BUG-0002-c-sources-are-copies-and-have-already-drifted.md @@ -1,11 +1,11 @@ --- id: BUG-0002 title: The C sources are three unsynchronised COPIES, and they have already drifted — the termcode fix lives in the embedded copy only -status: open +status: fixed severity: high component: csrc found_in: 0.1.3 -fixed_in: +fixed_in: unreleased (after 0.3.4) reported: 2026-08-12 reporter: Revisión de defectos del ecosistema tags: @@ -91,3 +91,23 @@ entra en el `diff` automático. ## Validation El test de (2) pasa hoy solo después de aplicar (1). Es su propia comprobación. + +## Resolution (2026-11-28) + +Resynced, not waited for 6.0: the path is still distributed, and the port +does not part from the C while it is. `csrc/internal/` is now atsw-gui's at +d603ea1, every file identical (`drvmlest.c`, `qnewtopt.c`, `nlatools.c`, +`elfvarma.c`, `main.h`, `likhost.h`, `optimhost.h`, and `lib/lik/{lik.c, +lik.h, multshea.c}`, `lib/optim/lnsrch.c`, `lib/fuepre/tusmodel.h`, which +they now need). `drvarma_api.c` reads the verdict from `opt_termcode` / +`opt_iters`, holds `qq[1,1]` (`est_fixed`) and returns `se_how` and the MA +wall count; `estimate_w(hessian="fd")` asks the C for its own fdhess. + +- `tests/data/homologation.json` records each file's sha256 and that it is + identical to the C's; `test_c_oracle.py` passes whole against d603ea1 + (36 passed, with `ATSW_GUI`). +- `tests/test_inp_path_as_the_c.py`: six cases of the C's battery; with the + compiled engine the parameter table is the C's line for line. +- What the resync uncovered: the pure-Python `.inp` estimator is not the + C's on four of those cases (BUG-0033). + diff --git a/bugs/BUG-0033-el-port-puro-de-la-via-inp-no-llega-al-optimo-del-c.md b/bugs/BUG-0033-el-port-puro-de-la-via-inp-no-llega-al-optimo-del-c.md new file mode 100644 index 0000000..eaad30c --- /dev/null +++ b/bugs/BUG-0033-el-port-puro-de-la-via-inp-no-llega-al-optimo-del-c.md @@ -0,0 +1,62 @@ +--- +id: BUG-0033 +title: The pure-Python .inp path is not the C's — on PSW VARMA(1,1) it stops 0.22 below the C's optimum, and on the boundary its BFGS standard errors are another path's +status: open +severity: medium +component: engine +found_in: 0.3.4 +fixed_in: +reported: 2026-11-28 +reporter: David / Claude — the resync of csrc with the C (BUG-0002) +tags: [inp-path, estimate_py, homologation, pure-python] +references: + - bugs/BUG-0033-repro/repro.py + - tests/test_inp_path_as_the_c.py (the four cases marked xfail) + - tests/data/inp_c/cases.json (the C's numbers) + - src/drvarma/estimate_py.py + - BUG-0002 +--- + +## Summary + +The deprecated `.inp` path (`estimate_w`, `Model`) was homologated against +the frozen 0.4.1 program, not the current C. With `csrc/` resynced to the C +of record (BUG-0002), the port with the compiled engine gives the C's +parameter table line for line on six cases of the C's battery. The +pure-Python estimator (`estimate_py`) does not, on four of them: + +| case | ΔlogL (pure − C) | what | +|---|---|---| +| c1 IPC AR(1) | 0 | fdhess SEs to 1.6e-4: fine | +| c2 IPC ARMA(2,1) diag Σ | −0.00005 | on the boundary: BFGS SEs up to 2× | +| c3 PSW ARMA(1,1) | **−0.218** | stops elsewhere | +| c5 EU diag AR/MA | 0 | same logL, estimates 1e-2 apart (a flat direction?) | +| c6 IPC AR(1), method 2 | 0 | fine | +| c7 IPC ARMA(1,1) twostep | +0.0016 | the C stops lower | + +## Impact + +Medium. Only the deprecated `.inp` path and only without the compiled engine +(no binary wheel: free-threaded builds, 32-bit Windows, DRVARMA_NO_ENGINE). +The ladder, what sima uses, is homologated separately and is not affected. + +## Reproduction + +`bugs/BUG-0033-repro/repro.py`: PSW VARMA(1,1) with DRVARMA_NO_ENGINE=1 +gives logL −871.542051; the C, −871.32401308. Exits 1 while open. + +## Root cause + +Not studied. The C's `.inp` path moved after 0.4.1 (the line-search +objective, the boundary sentinel in `objcfunc`, `varma_lik`, the start +`init_varma`/`twostep`), and `estimate_py` followed 0.4.1. To be found by +following the two paths iteration by iteration on c3, as BUG-0030 did for +the ladder. + +## Fix + +— + +## Validation + +— diff --git a/bugs/BUG-0033-repro/PSW.inp b/bugs/BUG-0033-repro/PSW.inp new file mode 100644 index 0000000..699781a --- /dev/null +++ b/bugs/BUG-0033-repro/PSW.inp @@ -0,0 +1,228 @@ +* DRVARMA example input file - PSW (raw levels) +* 2 monthly series; modelled in log first differences +*********************************************************** +** Frequency (1=A, 4=Q, 12=M): + 12 +** Series, observations, start (subperiod year): + 2 216 1 2005 +** Series names: + PSW_a PSW_b +** Box-Cox lambda, regular differences, annual differences: + 0.0 1 0 +** Data: +69.53 19.670 +69.59 20.740 +70.165 24.420 +71.118 26.270 +71.374 27.020 +71.377 25.520 +70.882 26.940 +71.085 28.380 +71.351 29.670 +72.058 28.850 +72.169 26.270 +72.409 29.420 +72.111 32.940 +72.264 35.870 +72.765 33.550 +73.357 28.250 +73.289 28.140 +73.338 30.720 +72.878 30.760 +73.213 31.590 +73.431 28.290 +73.926 30.330 +74.167 31.090 +74.294 32.150 +73.773 34.270 +73.807 34.740 +74.322 36.760 +75.34 36.690 +75.784 40.280 +75.904 38.020 +75.328 40.690 +75.661 44.940 +75.796 45.950 +76.575 53.130 +76.767 48.460 +76.692 43.330 +76.046 46.840 +76.243 47.970 +76.846 54.310 +77.953 53.040 +78.102 49.830 +78.284 56.260 +77.805 58.700 +78.147 64.970 +78.627 65.570 +79.266 62.370 +79.386 58.300 +79.557 59.430 +79.234 65.510 +79.272 61.630 +79.833 62.900 +80.959 69.690 +81.251 70.940 +81.374 70.960 +80.89 74.410 +81.055 73.050 +80.922 63.870 +81.254 58.880 +81.455 59.370 +81.678 62.030 +81.129 54.570 +81.184 59.260 +81.8 60.560 +82.93 63.970 +83.158 63.460 +83.311 67.480 +82.704 74.180 +82.818 72.390 +83.09 79.930 +84.167 86.200 +84.77 94.620 +85.125 91.730 +84.598 92.950 +84.73 95.350 +85.482 105.560 +86.402 112.570 +86.985 125.390 +87.486 133.930 +87.066 133.440 +86.879 116.610 +86.861 103.900 +87.16 76.650 +86.79 57.440 +86.345 41.020 +85.281 41.740 +85.29 39.160 +85.43 47.980 +86.264 49.790 +86.234 59.160 +86.614 69.680 +85.874 64.090 +86.174 71.060 +85.971 69.460 +86.584 75.820 +87.053 78.080 +87.031 74.300 +86.158 78.220 +86.001 76.420 +86.639 81.240 +87.562 84.480 +87.756 73.840 +87.913 75.350 +87.519 76.370 +87.74 76.820 +87.801 75.310 +88.603 81.900 +89.084 84.140 +89.631 89.040 +88.975 89.420 +89.088 89.580 +89.754 102.940 +90.871 110.040 +90.841 101.330 +90.713 96.290 +90.226 97.190 +90.338 86.330 +90.559 85.610 +91.273 86.410 +91.643 97.210 +91.762 98.570 +90.753 100.240 +90.847 102.250 +91.458 106.190 +92.743 103.330 +92.606 94.700 +92.433 82.410 +92.217 87.930 +92.736 94.160 +93.649 94.720 +94.445 89.570 +94.328 86.660 +94.394 88.250 +93.188 94.690 +93.349 95.320 +93.678 93.050 +94.028 92.070 +94.201 94.800 +94.34 95.800 +93.853 104.610 +94.145 106.570 +93.969 106.290 +94.351 100.540 +94.547 93.860 +94.632 97.630 +93.373 94.620 +93.333 100.820 +93.541 100.800 +94.373 102.070 +94.395 102.180 +94.421 105.790 +93.533 103.590 +93.681 96.540 +93.824 93.210 +94.261 84.400 +94.195 75.790 +93.646 59.290 +92.141 47.220 +92.331 50.580 +92.92 47.820 +93.774 54.450 +94.222 59.270 +94.474 59.820 +93.597 50.900 +93.286 42.870 +92.999 45.480 +93.595 46.220 +93.937 42.440 +93.663 37.190 +91.876 31.680 +91.552 30.320 +92.139 37.550 +92.785 40.750 +93.292 46.710 +93.723 48.760 +93.041 44.650 +93.161 44.720 +93.165 45.180 +94.23 49.780 +94.572 45.660 +95.132 51.970 +94.609 52.500 +94.269 53.470 +94.249 49.330 +95.154 51.060 +95.097 48.480 +95.138 45.180 +94.482 46.630 +94.67 48.040 +94.835 49.820 +95.71 51.580 +96.147 56.640 +96.19 57.880 +95.153 63.700 +95.281 62.230 +95.393 62.730 +96.181 66.250 +97.048 69.980 +97.302 67.870 +96.604 70.980 +96.742 68.060 +96.978 70.230 +97.875 70.750 +97.768 56.960 +97.329 49.520 +96.085 51.380 +96.32 54.950 +96.669 58.150 +97.644 63.860 +97.834 60.830 +97.719 54.660 +97.113 57.350 +97.059 54.810 +97.059 56.950 +98.001 53.960 +98.167 57.030 +98.096 59.880 diff --git a/bugs/BUG-0033-repro/repro.py b/bugs/BUG-0033-repro/repro.py new file mode 100644 index 0000000..2302dec --- /dev/null +++ b/bugs/BUG-0033-repro/repro.py @@ -0,0 +1,37 @@ +"""BUG-0033: the pure-Python .inp path does not reach the C's optimum. + +PSW, VARMA(1,1) (the C battery's case c3_psw_arma11). The C (atsw-gui +engines/drvarma, tests/banco/ref) and the port with the compiled engine end +at logL -871.32401308; the pure-Python estimator (DRVARMA_NO_ENGINE=1) at +-871.542051, 0.22 lower. + +Exits 1 while the pure-Python logL is more than 1e-5 from the C's, 0 when +it is not. + + python3 bugs/BUG-0033-repro/repro.py # exits 1 while open +""" +import os +import re +import shutil +import subprocess +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +SRC = os.path.join(HERE, "..", "..", "src") +C_LOGL = -871.32401308 + +with tempfile.TemporaryDirectory() as t: + shutil.copy(os.path.join(HERE, "PSW.inp"), t) + env = dict(os.environ, DRVARMA_NO_ENGINE="1", + PYTHONPATH=SRC + os.pathsep + os.environ.get("PYTHONPATH", "")) + subprocess.run([sys.executable, "-m", "drvarma.cli", "PSW", "1", "1"], cwd=t, + env=env, capture_output=True, text=True, timeout=1800) + out = open(os.path.join(t, "PSW.out"), errors="replace").read() +logl = float(re.findall(r"Log-likelihood = (-?[\d.]+)", out)[-1]) +print(f"pure-Python logL {logl:.6f}, the C's {C_LOGL:.6f}") +if abs(logl - C_LOGL) > 1e-5: + print("OPEN: the pure-Python .inp path stops elsewhere") + sys.exit(1) +print("closed") +sys.exit(0) diff --git a/bugs/README.md b/bugs/README.md index e2edd8f..92b362d 100644 --- a/bugs/README.md +++ b/bugs/README.md @@ -1,17 +1,18 @@ # Bug reports -In-repo bug tracker for **drvarma**. One Markdown file per bug (`BUG-NNNN-slug.md`); this index is generated by `art-bug index`. +In-repo bug tracker for **drvarma-csrc**. One Markdown file per bug (`BUG-NNNN-slug.md`); this index is generated by `art-bug index`. New report: `art-bug new` (or copy `TEMPLATE.md`). Validate: `art-bug check`. A fix commit references the id, e.g. `fix(pipeline): BUG-0001 …`. -**32 report(s), 4 open.** +**33 report(s), 4 open.** | id | status | sev | component | title | fixed in | |----|--------|-----|-----------|-------|----------| | [BUG-0001](BUG-0001-deseason-phase-still-unpatched-in-the-c-engine.md) | open | high | deseason | The seasonal-adjustment phase off-by-one is fixed in the Python port but STILL LIVE in the C engine, which the standalone executable uses | — | -| [BUG-0002](BUG-0002-c-sources-are-copies-and-have-already-drifted.md) | open | high | csrc | The C sources are three unsynchronised COPIES, and they have already drifted — the termcode fix lives in the embedded copy only | — | | [BUG-0020](BUG-0020-la-puerta-falla-con-un-ma-en-la-pared.md) | open | low | ladder | The diagonal gate fails with NaN when a univariate optimum sits on the MA wall; the same polynomial is admissible alone and ifault 3 in the joint elf | — | +| [BUG-0033](BUG-0033-el-port-puro-de-la-via-inp-no-llega-al-optimo-del-c.md) | open | medium | engine | The pure-Python .inp path is not the C's — on PSW VARMA(1,1) it stops 0.22 below the C's optimum, and on the boundary its BFGS standard errors are another path's | — | | [BUG-0003](BUG-0003-seasonal-adjustment-applied-in-levels-before-box-cox.md) | in-progress | medium | deseason | The seasonal component is estimated and subtracted in LEVELS, before the Box-Cox log, so a multiplicative pattern on a trending index is adjusted at the wrong scale | 0.2.0 (Python; the C pending) | +| [BUG-0002](BUG-0002-c-sources-are-copies-and-have-already-drifted.md) | fixed | high | csrc | The C sources are three unsynchronised COPIES, and they have already drifted — the termcode fix lives in the embedded copy only | unreleased (after 0.3.4) | | [BUG-0004](BUG-0004-el-docstring-dice-que-el-respaldo-en-python-solo-hace-q0.md) | fixed | low | engine | El docstring de `estimate_w` dice que el respaldo en Python sólo hace q=0, y hace VARMA completo desde junio | 0.2.0 | | [BUG-0005](BUG-0005-el-respaldo-en-python-puro-entra-sin-avisar.md) | fixed | medium | packaging | Donde no hay rueda binaria se instala la de Python puro y el motor C no se usa, sin ningún aviso | 0.2.0 | | [BUG-0006](BUG-0006-la-busqueda-lineal-no-vuelve-con-un-objetivo-no-finito.md) | fixed | high | optimizer | La búsqueda lineal no vuelve nunca si el objetivo es NaN o infinito — el optimizador (C y Python) se queda girando, sin error ni salida | 0.1.7 | diff --git a/csrc/drvarma_api.c b/csrc/drvarma_api.c index df97287..4c16da8 100644 --- a/csrc/drvarma_api.c +++ b/csrc/drvarma_api.c @@ -10,7 +10,8 @@ #include #include -extern int qn_last_termcode, qn_last_nit; /* set by raxopt (qnewtopt.c) */ +/* opt_termcode/opt_iters (qnewtopt.c), est_se_how and est_ma_* (drvmlest.c): + main.h, as in the C engine of record (atsw-gui engines/drvarma). */ real macheps; FILE *outputv; @@ -994,6 +995,10 @@ DrvarmaResult *drvarma_estimate(const DrvarmaModelSpec *spec) xitol = (met == 2) ? -1.0e-3 : 1.0e-3; varma1.xitol = xitol; + /* As the C's .inp path (drvarma.c): fdhess by default, with qq[1,1] held + (Q -> cQ leaves the likelihood unchanged: a flat direction). */ + est_fdhess = spec->bfgs_se ? 0 : 1; + est_fixed = npar - (global_diag_cov ? nser : nser * (nser + 1) / 2) + 1; shootx(x, &varma1, &ifault, 1, 0); est(&shootx, npar, x, dev, cov, maxits, nrits, grtol, sptol, xitol, varma1.a, &varma1.sigma2, &varma1.logelf, &ifault); @@ -1009,8 +1014,11 @@ DrvarmaResult *drvarma_estimate(const DrvarmaModelSpec *spec) returned no termination code and every convergence diagnosis downstream was silently inert, while the pure-Python estimator reported it. Both engines must say the same thing about the same fit. */ - r->termcode = qn_last_termcode; - r->nit = qn_last_nit; + r->termcode = opt_termcode; + r->nit = opt_iters; + r->se_how = est_se_how; + r->ma_boundary = est_ma_boundary; + r->ma_nroots = est_ma_nroots; r->params = (double *) malloc((size_t)npar * sizeof(double)); r->std_errors = (double *) malloc((size_t)npar * sizeof(double)); r->cov_matrix = (double *) malloc((size_t)npar * npar * sizeof(double)); diff --git a/csrc/drvarma_api.h b/csrc/drvarma_api.h index 1974979..d7f6619 100644 --- a/csrc/drvarma_api.h +++ b/csrc/drvarma_api.h @@ -16,6 +16,8 @@ typedef struct { int twostep; int maxits; /* 0 -> default 500 */ double grtol, sptol; /* 0 -> defaults */ + int bfgs_se; /* 0: standard errors from fdhess at the optimum, the + C's default; 1: the BFGS factor (-hessian bfgs) */ } DrvarmaModelSpec; typedef struct { @@ -36,6 +38,9 @@ typedef struct { double logelf; int termcode; /* raxopt: 1 gradient, 2 step, 3-5 no convergence */ int nit; /* raxopt iterations */ + int se_how; /* est_se_how: 0 bfgs, 1 fdhess, 2-5 why not fdhess */ + int ma_boundary; /* MA inverse roots on the wall at the stop */ + int ma_nroots; /* of how many (m*q) */ } DrvarmaResult; void drvarma_defaults(DrvarmaModelSpec *spec); diff --git a/csrc/internal/drvmlest.c b/csrc/internal/drvmlest.c index da6fc2c..37b87d2 100644 --- a/csrc/internal/drvmlest.c +++ b/csrc/internal/drvmlest.c @@ -16,16 +16,142 @@ /* Copyright (C) Jos‚ Alberto Mauricio, 1995. */ /*****************************************************************************/ -#include "main.h" /* Header file (prototype declarations) */ +#include "main.h" +#include /* Header file (prototype declarations) */ extern real macheps; /* Machine epsilon (global: declared in DRV.C) */ extern FILE *outputv; /* Output file (global: declared in DRV.C) */ /*****************************************************************************/ real pi10x, pi20x, xitolx; +int est_ma_boundary = 0; /* MA inverse roots on the wall at the stop (lik.h) */ +int est_ma_nroots = 0; +int est_fdhess = 0; /* 1: standard errors from fdhess at the optimum */ +int est_fixed = 0; /* >0: parameter held while fdhess runs (flat dir.) */ +int est_se_how = EST_SE_BFGS;/* <- which Hessian gave the standard errors */ +extern int opt_iters; /* qnewtopt.c: iterations of the last raxopt */ +static int objc_rejects; /* points objcfunc refused (boundary sentinel) */ +static real *fix_full; /* full vector behind the reduced objective */ +static int fix_n; struct Tvarma varmax; void (*castx)( real *, struct Tvarma *,int *, int, int ); +/*****************************************************************************/ + +void fdhess( real (*func)(real *), int n, real *x, real f, real eta, real **H ); +real objcfunc( real *x ); + +/* The Hessian behind the standard errors, as the reports write it. */ +const char *est_se_label( int how ) +{ + switch ( how ) + { + case EST_SE_FDHESS: return "fdhess"; + case EST_SE_BOUNDARY: return "bfgs (fdhess: the optimum is on the boundary " + "of the admissible region)"; + case EST_SE_NOTPD: return "bfgs (fdhess: the Hessian is not positive definite)"; + case EST_SE_NONE_BOUNDARY: + return "none (fdhess: the optimum is on the boundary of the admissible " + "region; the search did not move, so it built no BFGS Hessian)"; + case EST_SE_NONE_NOTPD: + return "none (fdhess: the Hessian is not positive definite; the search " + "did not move, so it built no BFGS Hessian)"; + default: return "bfgs"; + } +} + +/* The objective with parameter est_fixed held at fix_full[est_fixed]. */ +static real objcfix( real *z ) +{ + int i, k = 1; + for ( i = 1; i <= fix_n; i++ ) + if ( i != est_fixed ) fix_full[i] = z[k++]; + return objcfunc( fix_full ); +} + +/* 1 if H (k x k, symmetric) is positive definite by a plain Cholesky. */ +static int strict_pd( real **H, int k ) +{ + int i, j, l, ok = 1; + real s, **L = matrix( 1, k, 1, k ); + for ( j = 1; j <= k && ok; j++ ) + { + s = H[j][j]; + for ( l = 1; l < j; l++ ) s -= L[j][l] * L[j][l]; + if ( !(s > 0.0) || !isfinite( s ) ) { ok = 0; break; } + L[j][j] = sqrt( s ); + for ( i = j + 1; i <= k; i++ ) + { + s = H[i][j]; + for ( l = 1; l < j; l++ ) s -= L[i][l] * L[j][l]; + L[i][j] = s / L[j][j]; + } + } + free_matrix( L, 1, k, 1, k ); + return ok; +} + +/* Covariance 2 F H^-1 / n from fdhess at par. Sets est_se_how; fills cov */ +/* and dev only when it is EST_SE_FDHESS (otherwise the caller uses BFGS). */ +static void fdhess_cov( int npar, real *par, real f, real **cov, real *dev ) +{ + int i, j, ii, jj, k = npar - ( est_fixed > 0 ), pfault; + real d1, d2, *z, *v, **H; + + z = vector( 1, k ); v = vector( 1, k ); H = matrix( 1, k, 1, k ); + for ( i = 1, ii = 1; i <= npar; i++ ) if ( i != est_fixed ) z[ii++] = par[i]; + fix_full = vector( 1, npar ); fix_n = npar; + for ( i = 1; i <= npar; i++ ) fix_full[i] = par[i]; + + objc_rejects = 0; + fdhess( est_fixed > 0 ? objcfix : objcfunc, k, z, f, macheps, H ); + + if ( objc_rejects > 0 ) + est_se_how = EST_SE_BOUNDARY; + else if ( !strict_pd( H, k ) ) + est_se_how = EST_SE_NOTPD; + else + { + pfault = 0; + choldcp( H, k, &d1, &d2, &pfault ); + if ( pfault ) est_se_how = EST_SE_NOTPD; + else + { + est_se_how = EST_SE_FDHESS; + for ( i = 1; i <= npar; i++ ) + { dev[i] = NAN; for ( j = 1; j <= npar; j++ ) cov[i][j] = NAN; } + for ( i = 1, ii = 1; i <= npar; i++ ) + { + if ( i == est_fixed ) continue; + for ( j = 1; j <= k; j++ ) v[j] = 0.0; + v[ii] = 1.0; + cholsol( H, k, v ); + for ( j = 1, jj = 1; j <= npar; j++ ) + { + if ( j == est_fixed ) continue; + cov[j][i] = ( 2.0 * f * v[jj] ) / varmax.n; + jj++; + } + dev[i] = sqrt( cov[i][i] ); + ii++; + } + } + } + /* raxopt starts b at the identity: with no iteration there is no BFGS */ + /* Hessian to fall back on (a .pre that already is the optimum), and the */ + /* identity would give sqrt(2F/n) for every parameter. Say so instead. */ + if ( ( est_se_how == EST_SE_BOUNDARY || est_se_how == EST_SE_NOTPD ) && + opt_iters == 0 ) + { + est_se_how = ( est_se_how == EST_SE_BOUNDARY ) ? EST_SE_NONE_BOUNDARY + : EST_SE_NONE_NOTPD; + for ( i = 1; i <= npar; i++ ) + { dev[i] = NAN; for ( j = 1; j <= npar; j++ ) cov[i][j] = NAN; } + } + free_vector( fix_full, 1, npar ); + free_matrix( H, 1, k, 1, k ); free_vector( v, 1, k ); free_vector( z, 1, k ); +} + /*****************************************************************************/ /*****************************************************************************/ @@ -71,14 +197,13 @@ void est( void (*cast)( real *, struct Tvarma *, int *, int, int ), void raxopt( real (*func)( real [] ), real *fk, int n, real *xk, real **b, int maxits, int nrits, real gradtol, real steptol ); - void fdhess( real (*func)(real *), int n, real *x, real f, - real eta, real **H ); real objcfunc( real *x ); /* [1]: First computation of the log-likelihood: initialize pi10x & pi20x: */ *ifault = 0; /* Initialize fault indicator. */ + est_se_how = EST_SE_BFGS; /* until the Hessian is taken */ varmax.xitol = xitol; /* Estimation method. */ @@ -86,7 +211,7 @@ void est( void (*cast)( real *, struct Tvarma *, int *, int, int ), if ( *ifault > 0 ) return; /* Bad initial estimates (1). */ - elf( varmax.m, varmax.n, varmax.p, varmax.q, varmax.mu, varmax.phi, + varma_lik( varmax.m, varmax.n, varmax.p, varmax.q, varmax.mu, varmax.phi, varmax.theta, varmax.qq, varmax.w, 1.0, varmax.xitol, TRUE, varmax.a, &pi10x, &pi20x, &pi3, ifault ); @@ -99,15 +224,53 @@ void est( void (*cast)( real *, struct Tvarma *, int *, int, int ), vtmp = vector( 1, npar ); castx = cast; /* Assign casting routine. */ + opt_report_deferred = 1; /* report_stop, below, once the MA */ raxopt( objcfunc, &pi1, npar, par, mtmp, maxits, nrits, grtol, sptol ); + opt_report_deferred = 0; /* roots at the stop are known */ + est_ma_boundary = 0; + est_ma_nroots = 0; + { + int cf = 0, ir; + (*cast)( par, &varmax, &cf, 0, 0 ); + if ( cf == 0 && varmax.q > 0 ) + { + int nr = varmax.m * varmax.q; + real *wr = vector( 1, nr ), *wi = vector( 1, nr ), *wmod = vector( 1, nr ); + chekma( varmax.m, varmax.q, varmax.theta, wr, wi, wmod, &cf ); + est_ma_nroots = nr; + for ( ir = 1; ir <= nr; ir++ ) if ( wmod[ir] >= 1.0 - MA_WALL_TOL ) est_ma_boundary++; + free_vector( wmod, 1, nr ); free_vector( wi, 1, nr ); free_vector( wr, 1, nr ); + } + } + report_stop( est_ma_boundary, est_ma_nroots ); /* This is an alternative way of computing the second derivative matrix: */ +/* */ +/* raxopt leaves in mtmp the Hessian ACCUMULATED by BFGS along the path: */ +/* good to steer the search, but not the curvature at the optimum -- it */ +/* depends on the path and degrades in the flattest directions, which are */ +/* those with the largest standard errors. With est_fdhess the Hessian is */ +/* recomputed by finite differences AT the optimum, as drtran does. The */ +/* ladder (.pre input) sets it; the .inp path keeps the 0.4.1 behaviour. */ -/* fdhess( objcfunc, npar, par, pi1, macheps, mtmp ); */ -/* choldcp( mtmp, npar, &pi2, &pi3, ifault ); */ +/* */ +/* Two guards (docs/STUDY-standard-errors.md in drvarma-python): */ +/* - a neighbour objcfunc refuses (Q not PD, unit root, non-invertible) */ +/* means the optimum is on the boundary: no unrestricted Hessian; */ +/* - choldcp is a MODIFIED Cholesky that patches small pivots, so the */ +/* Hessian is first checked with a plain one. */ +/* Either way the BFGS factor is kept and est_se_how says why. With */ +/* est_fixed = k, parameter k (qq[1,1] in the .inp path: Q -> cQ leaves */ +/* the likelihood unchanged) is held; its dev and cov are NAN. */ + + est_se_how = EST_SE_BFGS; + if ( est_fdhess ) + fdhess_cov( npar, par, pi1, cov, dev ); /* [3]: Sample estimation of the variance-covariance matrix: */ + if ( est_se_how == EST_SE_BFGS || est_se_how == EST_SE_BOUNDARY || + est_se_how == EST_SE_NOTPD ) for ( i = 1; i <= npar; i++ ) { for ( j = 1; j <= npar; j++ ) vtmp[j] = 0.0; @@ -126,7 +289,7 @@ void est( void (*cast)( real *, struct Tvarma *, int *, int, int ), (*cast)( par, &varmax, ifault, 0, 0 ); - elf( varmax.m, varmax.n, varmax.p, varmax.q, varmax.mu, varmax.phi, + varma_lik( varmax.m, varmax.n, varmax.p, varmax.q, varmax.mu, varmax.phi, varmax.theta, varmax.qq, varmax.w, 1.0, varmax.xitol, TRUE, a, &pi1, &pi2, &pi3, ifault ); @@ -154,25 +317,25 @@ real objcfunc( real *x ) ifault = 0; (*castx)( x, &varmax, &ifault, 0, 0 ); if ( ifault > 0 ) /* ifault = 6-7-8- ... */ - return( 1.0 ); + { objc_rejects++; return( 1.0 ); } /* [2]: Compute objective function and return: */ - elf( varmax.m, varmax.n, varmax.p, varmax.q, varmax.mu, varmax.phi, + varma_lik( varmax.m, varmax.n, varmax.p, varmax.q, varmax.mu, varmax.phi, varmax.theta, varmax.qq, varmax.w, 1.0, varmax.xitol, FALSE, varmax.a, &pi1, &pi2, &pi3, &ifault ); if ( ifault > 0 ) /* ifault = 1-2-3-4-5. */ - return( 1.0 ); - else - { - /* BUG-0006: a non-finite objective is an inadmissible point, exactly - like an elf ifault (drtran's guard, the same line). pi1 overflowing - while pi2 underflows gives inf*0 = NaN. */ - real f = pow( (pi1 / pi10x), varmax.m ) * (pi2 / pi20x); - if ( !isfinite( f ) ) return( 1.0 ); - return( f ); - } + { objc_rejects++; return( 1.0 ); } + +/* A point whose objective is not finite is inadmissible, exactly like an */ +/* elf ifault: return 1.0 (the article's strategy, sec. 3). Without this the */ +/* line search received the NaN and never returned (BUGS.md). As in drtran. */ + { + real f = pow( (pi1 / pi10x), varmax.m ) * (pi2 / pi20x); + if ( !isfinite( f ) ) { objc_rejects++; return( 1.0 ); } + return( f ); + } } /*****************************************************************************/ \ No newline at end of file diff --git a/csrc/internal/lik.c b/csrc/internal/lik.c new file mode 100644 index 0000000..b954302 --- /dev/null +++ b/csrc/internal/lik.c @@ -0,0 +1,165 @@ +/*****************************************************************************/ +/* lik.c -- part of drvarma (multivariate VARMA modelling). + * + * Copyright (C) 1995-2026 A.B. Treadway, J.A. Mauricio & D.E. Guerrero. + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. Distributed WITHOUT ANY WARRANTY; see the + * GNU General Public License (file COPYING) for details. + *****************************************************************************/ + +/*****************************************************************************/ +/* LIK.C -- which exact likelihood the program evaluates. */ +/* */ +/* drvarma computes the exact likelihood of a VARMA model with Mauricio's */ +/* algorithm (elf, AS 311). Its source also carried, compiled and never */ +/* called since 1996, Shea's (marma, AS 242, 1989): the other of the two */ +/* efficient exact methods, and the benchmark Mauricio's papers compare */ +/* against. -lik shea makes it the objective: */ +/* */ +/* - two independent algorithms must give the same likelihood, so each is */ +/* an oracle for the other (and for the Python port); */ +/* - elf truncates the xi sequence when its norm falls below xitol (-m 1, */ +/* the default); with -m 2 it does not. Shea is always run EXACT (its own */ +/* shortcut is a different approximation), so with -m 2 the two must */ +/* agree to rounding -- measured, 1e-9 to 1e-13 in logL at every point the */ +/* optimizer visits -- and with -m 1 -lik both measures elf's truncation. */ +/* */ +/* What Shea does NOT replace: */ +/* - the RESIDUALS. marma returns the one-step innovations; drvarma's */ +/* forecasts and diagnostics use elf's exact residuals (atf = TRUE), and */ +/* confusing the two is drtran's BUG-55. With atf = TRUE the residuals */ +/* come from elf and the likelihood from marma; */ +/* - the admissible region. marma does not test the MA operator; the same */ +/* check elf applies (chekma, modulus >= 1.00005 -> ifault 4) is applied */ +/* first, so both objectives refuse the same points. */ +/*****************************************************************************/ + +#include "likhost.h" /* the engine: real, elf, chekma, allocators */ + +int est_lik = LIK_ELF; + +/* -lik both: elf is the objective and Shea is evaluated at every point too. */ +static long chk_n = 0, chk_only_one = 0; +static double chk_max = 0.0, chk_last = 0.0; + +const char *lik_label( void ) +{ + return est_lik == LIK_SHEA ? "exact, Shea (1989), AS 242" + : est_lik == LIK_BOTH ? "exact, Mauricio (1997), AS 311; checked " + "against Shea (1989), AS 242" + : "exact, Mauricio (1997), AS 311"; +} + +/* The concentrated log-likelihood from (f1, f2), as est() writes it. */ +static double loglik_of( int m, int n, real f1, real f2 ) +{ + const real LOG2PI = 1.837877066; + return -0.5 * m * n * ( LOG2PI - log( m ) - log( n ) + 1.0 ) + - 0.5 * n * ( m * log( f1 ) + log( f2 ) ); +} + +static void shea_only( int m, int n, int p, int q, real *mu, real ***phi, + real ***theta, real **qq, real **w, real sigma2, + real xitol, real *f1, real *f2, real *logelf, + int *ifault ); + +void lik_check_report( FILE *f ) +{ + if ( est_lik != LIK_BOTH ) return; + fprintf( f, "Shea check : %ld points; max |dlogL| = %.3e, at the " + "optimum %.3e", chk_n, chk_max, chk_last ); + if ( chk_only_one ) + fprintf( f, "; %ld points admissible for one algorithm only", chk_only_one ); + fprintf( f, "\n" ); +} + +void varma_lik( int m, int n, int p, int q, real *mu, real ***phi, + real ***theta, real **qq, real **w, real sigma2, real xitol, + int atf, real **a, real *f1, real *f2, real *logelf, + int *ifault ) +{ + int i, t; + real r1, r2, rlogl, **wt, **v; + + if ( est_lik == LIK_BOTH ) + { + real g1, g2, glog; + int gf = 0; + elf( m, n, p, q, mu, phi, theta, qq, w, sigma2, xitol, atf, a, + f1, f2, logelf, ifault ); + shea_only( m, n, p, q, mu, phi, theta, qq, w, sigma2, xitol, + &g1, &g2, &glog, &gf ); + if ( ( *ifault > 0 ) != ( gf > 0 ) ) chk_only_one++; + else if ( *ifault == 0 && *f1 > 0.0 && *f2 > 0.0 && g1 > 0.0 && g2 > 0.0 ) + { + double d = fabs( loglik_of( m, n, *f1, *f2 ) - loglik_of( m, n, g1, g2 ) ); + chk_n++; + if ( d > chk_max ) chk_max = d; + if ( atf ) chk_last = d; /* the final evaluation is atf */ + } + return; + } + if ( est_lik != LIK_SHEA ) + { + elf( m, n, p, q, mu, phi, theta, qq, w, sigma2, xitol, atf, a, + f1, f2, logelf, ifault ); + return; + } + + *ifault = 0; + if ( atf ) /* the residuals are elf's */ + { + elf( m, n, p, q, mu, phi, theta, qq, w, sigma2, xitol, TRUE, a, + f1, f2, logelf, ifault ); + if ( *ifault > 0 ) return; + } + shea_only( m, n, p, q, mu, phi, theta, qq, w, sigma2, xitol, + f1, f2, logelf, ifault ); +} + +/* Shea's likelihood alone: elf's MA frontier (chekma), then marma. */ +static void shea_only( int m, int n, int p, int q, real *mu, real ***phi, + real ***theta, real **qq, real **w, real sigma2, + real xitol, real *f1, real *f2, real *logelf, + int *ifault ) +{ + int i, t; + real r1, r2, rlogl, **wt, **v; + + *ifault = 0; + if ( q > 0 ) /* the same MA frontier as elf */ + { + real *wr = vector( 1, m * q ), *wi = vector( 1, m * q ), + *wmod = vector( 1, m * q ); + chekma( m, q, theta, wr, wi, wmod, ifault ); + free_vector( wmod, 1, m * q ); + free_vector( wi, 1, m * q ); + free_vector( wr, 1, m * q ); + if ( *ifault > 0 ) { *ifault = 4; return; } + } + + /* marma takes the series as w[series][time]; elf as w[time][series]. */ + wt = matrix( 1, m, 1, n ); + v = matrix( 1, m, 1, n ); + for ( t = 1; t <= n; t++ ) + for ( i = 1; i <= m; i++ ) wt[i][t] = w[t][i]; + + /* Shea is the REFERENCE, so it never truncates: its own shortcut (the */ + /* steady-state recursion once F(t) is within xtol of Q) is a different */ + /* approximation from elf's xi truncation, and with -m 1 it made the m6 */ + /* gate fail by 0.118. Exact, -lik both -m 1 measures elf's truncation. */ + (void) xitol; + marma( m, n, p, q, mu, phi, theta, qq, wt, sigma2, -1.0, TRUE, FALSE, + v, &r1, &r2, &rlogl, ifault ); + + free_matrix( v, 1, m, 1, n ); + free_matrix( wt, 1, m, 1, n ); + if ( *ifault > 0 ) return; + + *f1 = r1; + *f2 = r2; + *logelf = rlogl; +} diff --git a/csrc/internal/lik.h b/csrc/internal/lik.h new file mode 100644 index 0000000..e4b0d6a --- /dev/null +++ b/csrc/internal/lik.h @@ -0,0 +1,35 @@ +/* lik.h -- lib/lik: which exact likelihood the engine evaluates. + * + * Mauricio's elf (AS 311, the engine's own elfvarma.c) or Shea's marma + * (AS 242, multshea.c here), or elf checked against Shea at every point. + * Shared by drvarma and drtran. Include it from the host's main.h, after + * `real` is defined: the host provides elf(), chekma() and the allocators + * (likhost.h). */ +#ifndef LIK_H +#define LIK_H +#include + +/* Which exact likelihood (lib/lik/lik.c): Mauricio's elf (default) or Shea's marma. */ +#define LIK_ELF 0 +#define LIK_SHEA 1 +#define LIK_BOTH 2 /* elf is the objective; Shea checked at every point */ + +/* The MA invertibility wall, one tolerance for both sides (2026-09-28). */ +/* chekma refuses a point with an MA inverse root at modulus >= 1 + 5e-5; */ +/* a stop with a root at modulus >= 1 - 5e-5 is reported as on the wall. A */ +/* root at 1.000048 and one at 0.99999999 are the same fact: the unit circle */ +/* to chekma's own precision. Before, only >= 1 counted, so an optimizer */ +/* that reached the wall from inside said "converged". */ +#define MA_WALL_TOL 5e-5 +extern int est_lik; +const char *lik_label( void ); +void lik_check_report( FILE *f ); +void varma_lik( int m, int n, int p, int q, real *mu, real ***phi, + real ***theta, real **qq, real **w, real sigma2, real xitol, + int atf, real **a, real *f1, real *f2, real *logelf, + int *ifault ); +void marma( int k, int n, int p, int q, real *mu, real ***phi, real ***theta, + real **qq, real **w, real sigma2, real xtol, int chkma, int atf, + real **v, real *r1, real *r2, real *rlogl, int *ifault ); + +#endif diff --git a/csrc/internal/likhost.h b/csrc/internal/likhost.h new file mode 100644 index 0000000..387da1a --- /dev/null +++ b/csrc/internal/likhost.h @@ -0,0 +1,6 @@ +/* likhost.h -- what lib/lik needs from this engine: `real`, elf(), chekma() + and the allocators. */ +#ifndef LIKHOST_H +#define LIKHOST_H +#include "main.h" +#endif diff --git a/csrc/internal/lnsrch.c b/csrc/internal/lnsrch.c new file mode 100644 index 0000000..69933bb --- /dev/null +++ b/csrc/internal/lnsrch.c @@ -0,0 +1,145 @@ +/* + * lnsrch.c -- the backtracking line search of the quasi-Newton optimiser + * (Dennis & Schnabel, algorithm A6.3.1), shared by drvarma, drtran, fue and + * fuf. + * + * It lived in each engine's qnewtopt.c, four copies of one function that + * differed in a single "a == 0" against "a == 0.0". The defect below was + * fixed in one of them (drvarma 5.0) and hung the other three; one source + * fixes all of them. The rest of qnewtopt.c (raxopt, its report) stays in + * each engine: those copies have diverged in what they print. + * + * A NON-FINITE objective is an inadmissible point. With a NaN every + * comparison in the loop is false: the step was neither accepted nor + * abandoned, lambda became NaN and the search never returned (drvarma + * BUGS.md; drtran met it on real data and ran for an hour and a half). + * Such a point shrinks the step without interpolating, and the search + * gives up like any other failed one once lambda is below minlam. + * + * On a finite trajectory the arithmetic is the original's, operation for + * operation: drvarma's .inp bench and fue/fuf's golden files are + * byte-identical before and after. + * + * The host provides optimhost.h: `real`, rmax() and nrerror(). + * + * Copyright (C) 1995-2026 A.B. Treadway, J.A. Mauricio & D.E. Guerrero. + * GPL v2 or later; see COPYING. + */ + +#include "optimhost.h" +#include + +real lnsrch( int n, real *xk, real fk, real *gk, real *dk, real *xkp1, + real *fkp1, real maxstep, real steptol, int *retcode, + int *maxtaken, real (*func)(real *) ) + +{ + real alpha, newtlen, tmp, initslp, rellen, minlam, lambda, tlambda; + real prelam, pfkp1, t1, t2, t3, a, b, disc; + int haveprev = 0; /* a previous backtrack to interpolate */ + int i; + + *maxtaken = 0; + *retcode = 2; + alpha = 1.0e-4; + + for ( newtlen = 0.0, i = 1; i <= n; i++ ) newtlen += dk[i] * dk[i]; + newtlen = sqrt( newtlen ); + if ( newtlen > maxstep ) /* Scale if attempted step is too large: */ + { + tmp = maxstep / newtlen; + for ( i = 1; i <= n; i++ ) dk[i] *= tmp; + newtlen = maxstep; + } + + for ( initslp = 0.0, i = 1; i <= n; i++ ) initslp += gk[i] * dk[i]; + + rellen = 0.0; /* Compute minlam: */ + for ( i = 1; i <= n; i++ ) + { + tmp = fabs( dk[i] ) / rmax( fabs( xk[i] ), 1.0 ); + if ( tmp > rellen ) rellen = tmp; + } + minlam = steptol / rellen; + lambda = 1.0; /* Always try full step first. */ + + do /* Start of iteration loop: */ + { + for ( i = 1; i <= n; i++ ) xkp1[i] = xk[i] + lambda * dk[i]; + *fkp1 = (*func)( xkp1 ); + + /* A non-finite objective is an inadmissible point. With a NaN every */ + /* comparison below is false: the step was neither accepted nor */ + /* abandoned, lambda became NaN and the loop spun for ever (BUGS.md, the */ + /* line search that never returns). Shrink without interpolating, and */ + /* give up like any other failed search once lambda is below minlam. */ + if ( !isfinite( *fkp1 ) ) + { + if ( lambda < minlam ) + { + *retcode = 1; + for ( i = 1; i <= n; i++ ) xkp1[i] = xk[i]; + *fkp1 = fk; + } + else + lambda = 0.1 * lambda; + continue; + } + + if ( *fkp1 <= fk + alpha * lambda * initslp ) + { + /* Sufficient function decrease: */ + *retcode = 0; + if ( (lambda == 1.0) && (newtlen > 0.99 * maxstep) ) *maxtaken = 1; + } + else if ( lambda < minlam ) + { + /* Convergence on x values: */ + /* The point goes back to xk, and so must its value: *fkp1 still held */ + /* the rejected trial's, and raxopt returned it as the optimum's */ + /* (drvec BUG-41, item 2; fue's Python port already did this). */ + *retcode = 1; + for ( i = 1; i <= n; i++ ) xkp1[i] = xk[i]; + *fkp1 = fk; + } + else + { + /* Backtrack: */ + /* First time (not "lambda == 1.0": after a non-finite point lambda */ + /* is already below 1 with nothing to interpolate from): */ + if ( !haveprev ) + tlambda = -initslp / (2.0 * (*fkp1 - fk - initslp)); + /* Subsequent backtracks: */ + else + { + t1 = *fkp1 - fk - lambda * initslp; + t2 = pfkp1 - fk - prelam * initslp; + t3 = 1.0 / (lambda - prelam); + a = (t1 / (lambda * lambda) - t2 / (prelam * prelam)) * t3; + b = (t2 * lambda / (prelam * prelam) - + t1 * prelam / (lambda * lambda)) * t3; + if ( a == 0.0 ) + tlambda = -initslp / (2.0 * b); + else + { + disc = b * b - 3.0 * a * initslp; + if ( disc < 0.0 ) + /* Probably, dk is not a direction of descent (initslp > 0): */ + nrerror( "ROUNDOFF PROBLEM IN LINE SEARCH" ); + else + tlambda = (-b + sqrt( disc )) / (3.0 * a); + } + if ( tlambda > 0.5 * lambda ) tlambda = 0.5 * lambda; + } + prelam = lambda; + pfkp1 = *fkp1; + haveprev = 1; + if ( tlambda <= 0.1 * lambda ) + lambda = 0.1 * lambda; + else + lambda = tlambda; + } + } + while ( *retcode == 2 ); /* Try again */ + return( lambda ); +} diff --git a/csrc/internal/main.h b/csrc/internal/main.h index 676eaf4..4fa360f 100644 --- a/csrc/internal/main.h +++ b/csrc/internal/main.h @@ -75,24 +75,45 @@ struct Tseries int max; /* ?ndice del m?ximo */ int min; /* ?ndice del m?nimo */ real *data; /* Vector de datos */ + int numbering; /* 1 = numeracion simple, 0 = fechas (.pre) */ + real refactor; /* reescalado de fue, del .pre */ }; +/* El modelo univariante de un .pre (lib/fuepre): la escalera, desde 5.0. */ +#include "tusmodel.h" + /*****************************************************************************/ /* Funciones de estimaci?n (de elfvarma.c y drvmlest.c) */ /*****************************************************************************/ +/* Which Hessian gave the standard errors (est_se_how, set by est): */ +#define EST_SE_BFGS 0 /* the one BFGS accumulated (fdhess not asked) */ +#define EST_SE_FDHESS 1 /* fdhess at the optimum */ +#define EST_SE_BOUNDARY 2 /* BFGS kept: the optimum is on the boundary */ +#define EST_SE_NOTPD 3 /* BFGS kept: fdhess not positive definite */ +#define EST_SE_NONE_BOUNDARY 4 /* neither: boundary, and BFGS never built */ +#define EST_SE_NONE_NOTPD 5 /* neither: not PD, and BFGS never built */ +extern int est_fdhess, est_fixed, est_se_how; +const char *est_se_label( int how ); + void est( void (*cast)( real *, struct Tvarma *, int *, int, int ), int npar, real *par, real *dev, real **cov, int maxits, int nrits, real grtol, real sptol, real xitol, real **a, real *sigma2, real *logelf, int *ifault ); -void marma( int k, int n, int p, int q, real *mu, real ***phi, real ***theta, - real **qq, real **w, real sigma2, real xtol, int chkma, int atf, - real **v, real *r1, real *r2, real *rlogl, int *ifault ); +/* The optimizer's stop (qnewtopt.c) and where the MA roots ended (drvmlest.c). */ +extern int opt_termcode, opt_iters, opt_report_deferred; +extern int est_ma_boundary, est_ma_nroots; +void report_stop( int nboundary, int nroots ); + +#include "lik.h" /* lib/lik: Shea (AS 242) beside elf, -lik */ + void elf( int m, int n, int p, int q, real *mu, real ***phi, real ***theta, real **qq, real **w, real sigma2, real delta, int atf, real **a, real *f1, real *f2, real *logelf, int *ifault ); +/* nlatools.c; lib/fuepre calls it for the easter regressor (host-provided). */ +void Easter( int *day, int *month, int year ); void chekma( int m, int q, real ***theta, real *wr, real *wi, real *wmod, int *ifault ); @@ -153,6 +174,8 @@ void DateToObs( int beg_per, int beg_sub, int per, int sub, int freq, int *obs_no ); real Mean( real *data, int nobs ); real Stdev( real *data, int nobs ); +void Ccf( real *data1, real *data2, int nobs, int lags, real *corr, + real mean1, real mean2, real sd1, real sd2 ); int MaxVal( real *data, int nobs ); int MinVal( real *data, int nobs ); real Skew( real *data, int nobs ); @@ -170,10 +193,8 @@ void PlotCor( real *corr, int lags, int isacf, struct Tseries *ser, int npar ); void PlotCCF( real *corr, int lags, struct Tseries *ser ); void ccf( struct Tseries *ser1, struct Tseries *ser2, int lags, real *corr ); real ChiTestC( real *corr, int lags, int nobs ); -void hosking_test(real **res, int nobs, int m, int s, real *Q, real *pval); -void jarque_bera_multivariate(real **res, int nobs, int m, real *JB, real *pval); -void multivariate_diagnostics(real **res, int nobs, int m, FILE *outputv); -void diagnose(struct Tvarma *varma); +/* Hosking and the multivariate Jarque-Bera: lib/diagmv/diagmv.h */ +void diagnose(struct Tvarma *varma, const int *npar_ser); /* Funciones de diagn?stico adicionales (declaradas en diagnose.c) */ void test_last_lag_significance(real *x, real **cov, int npar, int m, int p, int q, @@ -214,13 +235,6 @@ real chisq( real x, int df ); /* Distribuci?n Chi?cuadrado acumulada */ real tdist( real t, int df ); /* Distribuci?n t?Student acumulada */ real normal_cdf( real z ); /* Distribuci?n normal est?ndar acumulada */ -/*****************************************************************************/ -/* Funciones auxiliares para el operador de convergencia (no usadas en */ -/* la versi?n actual, pero se mantienen por compatibilidad) */ -/*****************************************************************************/ - -void calcnu( double omega, int s, double delta, int r, double *nu, int lags ); - /*****************************************************************************/ /* Funciones propias de drvarma.c (declaradas para completitud) */ /*****************************************************************************/ diff --git a/csrc/internal/multshea.c b/csrc/internal/multshea.c index 41272af..f741b7a 100644 --- a/csrc/internal/multshea.c +++ b/csrc/internal/multshea.c @@ -1,6 +1,5 @@ /*****************************************************************************/ -/* multshea.c -- part of drvarma. COPY of atsw-gui lib/lik/multshea.c - * (the source of truth since 2026-09-28; sync from there, never edit here) (multivariate VARMA modelling). +/* multshea.c -- part of drvarma (multivariate VARMA modelling). * * Copyright (C) 1995-2026 A.B. Treadway, J.A. Mauricio & D.E. Guerrero. * @@ -18,7 +17,7 @@ /* Copyright (C) Jos‚ Alberto Mauricio, 1996. */ /*****************************************************************************/ -#include "main.h" /* Header file (prototype declarations) */ +#include "likhost.h" /* the engine: real, elf, chekma, allocators */ /* Header file (prototype declarations) */ /*****************************************************************************/ /*****************************************************************************/ diff --git a/csrc/internal/nlatools.c b/csrc/internal/nlatools.c index 15eeab5..9536cbe 100644 --- a/csrc/internal/nlatools.c +++ b/csrc/internal/nlatools.c @@ -2,10 +2,10 @@ /* nlatools.c -- part of drvarma (multivariate VARMA modelling). * * SHARED, Numerical-Recipes-free version: kept byte-identical to - * drvarma_v.04.1/src/nlatools.c and to drtran/src/nlatools.c. Three - * independent NR cleanups each dropped the same base offset in the memory - * routines; one shared copy is the answer to that. If you fix something here, - * fix it there. + * drtran/src/nlatools.c and to the copy embedded in the Python package + * (csrc/internal/). Three independent NR cleanups each dropped the same base + * offset in the memory routines; one shared copy is the answer to that. If + * you fix something here, fix it there. * * Copyright (C) 1995-2026 A.B. Treadway, J.A. Mauricio & D.E. Guerrero. * @@ -724,25 +724,8 @@ void Easter( int *day, int *month, int year ) /****************************************************************************/ /****************************************************************************/ -void calcnu( double omega, int s, double delta, int r, double *nu, int lags ) - -{ - int i, j; - double sum1, sum2; - - nu[0] = omega; - for ( j = 1; j <= lags; j++ ) - { - sum1 = 0.0; - if ( r > 0 ) - for ( i = 1; i <= j; i++ ) - if ( i <= r ) sum1 = sum1 + delta * nu[j-i]; - sum2 = 0.0; - if ( s > 0 ) - if ( j <= s ) sum2 = omega; - nu[j] = sum1 - sum2; - } -} +/* calcnu (escalar) quitada 2026-10-16: nadie la llamaba. El filtro + determinista de la suite es lib/fuedet (BUG-40 de drvec). */ /****************************************************************************/ /*****************************************************************************/ @@ -823,7 +806,10 @@ static real gammap(real a, real x) { real chisq(real x, int df) { if (df <= 0) return 0.0; if (x <= 0.0) return 0.0; - if (x > 1000.0) return 1.0; /* L�mite superior */ + /* BUG-42(2): here was `if (x > 1000.0) return 1.0;`, which put every + * p-value at 0 once Hosking's df = m^2*s neared 1000. No cap is + * needed: Wilson-Hilferty below holds at any x for df >= 30, and + * gammap() handles df < 30. */ /* Para df peque�os, c�lculo exacto */ if (df < 30) { diff --git a/csrc/internal/optimhost.h b/csrc/internal/optimhost.h new file mode 100644 index 0000000..c80ae44 --- /dev/null +++ b/csrc/internal/optimhost.h @@ -0,0 +1,6 @@ +/* optimhost.h -- what lib/optim/lnsrch.c needs from this engine: + `real`, rmax() and nrerror(). */ +#ifndef OPTIMHOST_H +#define OPTIMHOST_H +#include "main.h" +#endif diff --git a/csrc/internal/qnewtopt.c b/csrc/internal/qnewtopt.c index d4773b9..21f70dd 100644 --- a/csrc/internal/qnewtopt.c +++ b/csrc/internal/qnewtopt.c @@ -18,29 +18,21 @@ /* Copyright (C) Jos� Alberto Mauricio, 1995. */ /*****************************************************************************/ -#include "main.h" /* Header file (prototype declarations) */ +#include "main.h" +#include /* Header file (prototype declarations) */ extern real macheps; /* Machine epsilon (global: declared in DRV.C) */ extern FILE *outputv; /* Output file (global: declared in DRV.C) */ extern int quiet_mode; /* added */ -/* The optimizer's verdict, recorded for callers that cannot read `outputv`. - - `report()` announces the termination code and the iteration count, but it - writes to `outputv`, and `quiet_mode` was introduced to silence the trace for - batch simulations. In the Python binding `outputv` is /dev/null, so the - announcement was produced and thrown away: the C engine returned no termcode - at all while the pure-Python estimator did, and every convergence diagnosis - downstream was inert on the DEFAULT engine. - - These two globals only RECORD what raxopt already computed -- no criterion, - no announcement and no numerical behaviour changes. They exist so both - engines can say the same thing about the same fit. */ -int qn_last_termcode = 0; -int qn_last_nit = 0; - /*****************************************************************************/ /*****************************************************************************/ +int opt_termcode = 0; /* the last raxopt's verdict, and its objective: */ +real opt_fk = 0.0; /* est() writes the report once it has checked */ +int opt_report_deferred = 0; /* the MA roots (report_stop) */ +int opt_iters = 0; /* iterations of the last raxopt (est: 0 means the */ + /* BFGS factor was never updated from I) */ + void raxopt( real (*func)(real *), real *fk, int n, real *xk, real **b, int maxits, int nrits, real gradtol, real steptol ) @@ -127,9 +119,11 @@ void raxopt( real (*func)(real *), real *fk, int n, real *xk, real **b, *fk = fkp1; } /* Back for another iteration. */ - qn_last_termcode = termcode; /* Record before announcing: */ - qn_last_nit = k; /* report() may be silenced. */ - report( n, k, xk, gk, *fk, termcode ); /* Report on convergence. */ + opt_iters = k; + opt_termcode = termcode; + opt_fk = *fk; + if ( !opt_report_deferred ) + report( n, k, xk, gk, *fk, termcode ); /* Report on convergence. */ if (!quiet_mode) printf( "%4d F: %0.10f\n", k, *fk ); /* Deallocate temporary storage and return: */ @@ -142,26 +136,29 @@ void raxopt( real (*func)(real *), real *fk, int n, real *xk, real **b, /*****************************************************************************/ +static const char *criterion( int termcode ) +{ + switch ( termcode ) + { + case 1: return "norm of scaled gradient <= gradtol"; + case 2: return "scaled distance between last two steps <= steptol"; + case 3: return "last global step failed to locate a lower point"; + case 4: return "iteration limit reached"; + case 5: return "five consecutive steps of maximum length taken"; + default: return NULL; + } +} + void report( int n, int k, real *x, real *g, real f, int termcode ) { - const char *crit; + const char *crit = criterion( termcode ); (void) n; (void) x; (void) g; /* per-parameter x/g dump removed: */ /* the estimates already appear in the */ /* "Estimated Parameters" table. */ if ( quiet_mode ) return; - switch ( termcode ) - { - case 1: crit = "norm of scaled gradient <= gradtol"; break; - case 2: crit = "scaled distance between last two steps <= steptol"; break; - case 3: crit = "last global step failed to locate a lower point"; break; - case 4: crit = "iteration limit reached"; break; - case 5: crit = "five consecutive steps of maximum length taken"; break; - default: crit = NULL; break; - } - fprintf( outputv, "\n=============================================================\n" ); fprintf( outputv, " OPTIMIZER %s after %d iterations\n", ( termcode == 1 || termcode == 2 ) ? "CONVERGED" : "STOPPED", k ); @@ -170,6 +167,35 @@ void report( int n, int k, real *x, real *g, real f, int termcode ) fprintf( outputv, "=============================================================\n\n" ); } +/* The report est() writes once it knows where the MA roots ended (2026-09-28). + A stop with MA inverse roots within MA_WALL_TOL (5e-5, lik.h) of the unit + circle is on the edge of the admissible region -- chekma refuses beyond + 1 + MA_WALL_TOL -- so "CONVERGED" would + be false there, whatever the termcode. The facts only: no verdict on the + model, which is the assistant's to study (sima; -lik shea for a second + path). */ +void report_stop( int nboundary, int nroots ) +{ + const char *crit = criterion( opt_termcode ); + + if ( quiet_mode ) return; + + fprintf( outputv, "\n=============================================================\n" ); + if ( nboundary > 0 ) + fprintf( outputv, " OPTIMIZER STOPPED at the MA invertibility boundary after %d iterations\n", + opt_iters ); + else + fprintf( outputv, " OPTIMIZER %s after %d iterations\n", + ( opt_termcode == 1 || opt_termcode == 2 ) ? "CONVERGED" : "STOPPED", + opt_iters ); + fprintf( outputv, " Objective function = %.12f\n", opt_fk ); + if ( crit ) fprintf( outputv, " Convergence criterion: %s\n", crit ); + if ( nboundary > 0 ) + fprintf( outputv, " MA boundary: %d of %d inverse roots within 5e-5 of the unit circle\n", + nboundary, nroots ); + fprintf( outputv, "=============================================================\n\n" ); +} + /*****************************************************************************/ int umstop0( int n, real *x, real f, real *g, real gradtol, @@ -470,124 +496,7 @@ void fdhess( real (*func)(real *), int n, real *x, real f, real eta, real **H ) /*****************************************************************************/ -real lnsrch( int n, real *xk, real fk, real *gk, real *dk, real *xkp1, - real *fkp1, real maxstep, real steptol, int *retcode, - int *maxtaken, real (*func)(real *) ) - -{ - real alpha, newtlen, tmp, initslp, rellen, minlam, lambda, tlambda; - real prelam, pfkp1, t1, t2, t3, a, b, disc; - int i, haveprev = 0; /* A finite trial point to interpolate */ - /* with exists (BUG-0006). */ - - *maxtaken = 0; - *retcode = 2; - alpha = 1.0e-4; - - for ( newtlen = 0.0, i = 1; i <= n; i++ ) newtlen += dk[i] * dk[i]; - newtlen = sqrt( newtlen ); - if ( newtlen > maxstep ) /* Scale if attempted step is too large: */ - { - tmp = maxstep / newtlen; - for ( i = 1; i <= n; i++ ) dk[i] *= tmp; - newtlen = maxstep; - } - - for ( initslp = 0.0, i = 1; i <= n; i++ ) initslp += gk[i] * dk[i]; - - rellen = 0.0; /* Compute minlam: */ - for ( i = 1; i <= n; i++ ) - { - tmp = fabs( dk[i] ) / rmax( fabs( xk[i] ), 1.0 ); - if ( tmp > rellen ) rellen = tmp; - } - minlam = steptol / rellen; - lambda = 1.0; /* Always try full step first. */ - - do /* Start of iteration loop: */ - { - for ( i = 1; i <= n; i++ ) xkp1[i] = xk[i] + lambda * dk[i]; - *fkp1 = (*func)( xkp1 ); - - /* BUG-0006: a NaN or infinite objective is an INADMISSIBLE point, not a - value. Every comparison below is false for a NaN, so the step was - neither accepted nor abandoned, tlambda and then lambda became NaN, - and the search never returned (drtran met it on real data and spun - for an hour and a half). An infinity reaches the same loop one step - later, through inf/inf in the cubic fit. Shrink the step without - interpolating -- there is nothing to interpolate with -- and give up - at minlam exactly as for a step that never decreases. On a path of - finite values nothing changes: `haveprev` is false exactly when - `lambda == 1.0` was, the first time through. */ - if ( !isfinite( *fkp1 ) ) - { - if ( lambda < minlam ) - { - *retcode = 1; - for ( i = 1; i <= n; i++ ) xkp1[i] = xk[i]; - *fkp1 = fk; /* The value at the point returned. */ - } - else - lambda = 0.1 * lambda; - continue; /* To the `while`: retcode decides. */ - } - - if ( *fkp1 <= fk + alpha * lambda * initslp ) - { - /* Sufficient function decrease: */ - *retcode = 0; - if ( (lambda == 1.0) && (newtlen > 0.99 * maxstep) ) *maxtaken = 1; - } - else if ( lambda < minlam ) - { - /* Convergence on x values: */ - /* The point goes back to xk, and so must its value: *fkp1 still held */ - /* the rejected trial's, and raxopt returned it as the optimum's */ - /* (drvec BUG-41, item 2; atsw-gui lib/optim/lnsrch.c). */ - *retcode = 1; - for ( i = 1; i <= n; i++ ) xkp1[i] = xk[i]; - *fkp1 = fk; - } - else - { - /* Backtrack: */ - /* First time (no finite point to interpolate with yet): */ - if ( !haveprev ) - tlambda = -initslp / (2.0 * (*fkp1 - fk - initslp)); - /* Subsequent backtracks: */ - else - { - t1 = *fkp1 - fk - lambda * initslp; - t2 = pfkp1 - fk - prelam * initslp; - t3 = 1.0 / (lambda - prelam); - a = (t1 / (lambda * lambda) - t2 / (prelam * prelam)) * t3; - b = (t2 * lambda / (prelam * prelam) - - t1 * prelam / (lambda * lambda)) * t3; - if ( a == 0.0 ) - tlambda = -initslp / (2.0 * b); - else - { - disc = b * b - 3.0 * a * initslp; - if ( disc < 0.0 ) - /* Probably, dk is not a direction of descent (initslp > 0): */ - nrerror( "ROUNDOFF PROBLEM IN LINE SEARCH" ); - else - tlambda = (-b + sqrt( disc )) / (3.0 * a); - } - if ( tlambda > 0.5 * lambda ) tlambda = 0.5 * lambda; - } - prelam = lambda; - pfkp1 = *fkp1; - haveprev = 1; - if ( tlambda <= 0.1 * lambda ) - lambda = 0.1 * lambda; - else - lambda = tlambda; - } - } - while ( *retcode == 2 ); /* Try again */ - return( lambda ); -} +/* lnsrch lives in lib/optim/lnsrch.c: one source for the four engines. */ /*****************************************************************************/ /*****************************************************************************/ diff --git a/csrc/internal/tusmodel.h b/csrc/internal/tusmodel.h new file mode 100644 index 0000000..0fea83b --- /dev/null +++ b/csrc/internal/tusmodel.h @@ -0,0 +1,55 @@ +/* + * tusmodel.h -- el modelo univariante de un .pre, tal como lo deja el lector. + * + * Vivia en engines/drtran/include/main.h. Sale aqui porque ya no es de + * drtran: lo llenan read_fue_pre y lo consumen drtran, su GUI y drvarma, y + * dos copias de una estructura que un lector llena campo a campo son dos + * lectores esperando a divergir. + * + * El anfitrion lo incluye desde su main.h, DESPUES de definir `real`. + */ + +#ifndef ATSW_TUSMODEL_H +#define ATSW_TUSMODEL_H + +struct Tusmodel +{ + int NdetVar; /* numero de variables deterministas */ + char **detspec; /* especificacion de cada detvar tal como viene + en el .pre ("cos 2", "step 6 2008", ...). + Se guarda para poder REGENERARLAS en fechas + futuras al prever: son funciones del tiempo. */ + int *Nomega, *Ndelta; /* ordenes de omega y delta para cada detvar */ + real **Omega, **Delta; /* coeficientes omega y delta */ + int **Imega, **Ielta; /* indicadores: 1=estimado, 0=fijo */ + + int NumAr1, NumAr2; /* numero de factores AR regulares y anuales */ + int *p1, *p2; /* ordenes de cada factor AR */ + real **Ar1, **Ar2; /* coeficientes AR */ + int **Ia1, **Ia2; /* flags estimacion */ + + int NumMa1, NumMa2; /* numero de factores MA regulares y anuales */ + int *q1, *q2; /* ordenes de cada factor MA */ + real **Ma1, **Ma2; /* coeficientes MA */ + int **Im1, **Im2; /* flags estimacion */ + + int NumAr1f, NumMa1f; /* numero de factores AR/MA de frecuencia fija */ + int *pfre1, *qfre1; /* frecuencias de los factores fijos */ + real **Ar1f, **Ma1f; /* coeficientes AR/MA de frecuencia fija */ + int *Ia1f, *Im1f; /* flags estimacion */ + + int Imu; /* flag para la media */ + real mu; /* valor de la media */ + + real boxlam; /* parametro lambda de Box-Cox */ + int nrdiff; /* diferencias regulares */ + int nadiff; /* diferencias anuales completas */ + int *ifadf; /* factores irreducibles de la dif. anual */ + int sper; /* periodo estacional (freq) */ + int ornsop; /* orden del operador no estacionario */ + real *rnsop; /* coeficientes del operador no estacionario */ + char *residuals; /* nombre de la serie de residuos */ + real cbands; /* bandas de confianza para ACF */ +}; + +#endif /* ATSW_TUSMODEL_H */ diff --git a/docs/HOMOLOGATION.md b/docs/HOMOLOGATION.md index d2dafd0..caee449 100644 --- a/docs/HOMOLOGATION.md +++ b/docs/HOMOLOGATION.md @@ -89,20 +89,25 @@ measured: the C has only been run on Linux for this record. Changing a file under `csrc/` makes `test_the_vendored_c_is_the_recorded_one` fail until the record is updated: the same steps. +## The `.inp` path (deprecated) + +`csrc/` is the C's: every vendored file is identical to atsw-gui's at the +recorded commit (`identical_to_c` in the record), only `drvarma_api.c` and +`.h`, the binding, are the package's own (BUG-0002, 2026-11-28). +`tests/test_inp_path_as_the_c.py` holds six cases of the C's battery +(`tests/banco/ref`, `tests/data/inp_c/cases.json`): with the compiled engine +the port's parameter table is the C's line for line, the standard errors +fdhess's computed by the C itself (`estimate_w(hessian="fd")`). The +pure-Python estimator matches on two of them and not yet on four (BUG-0033). + ## What is not homologated against the current C -- **The deprecated multivariate `.inp` path.** Its tests - (`test_estimate_cffi.py`, `test_estimate_py.py`, `test_deseason.py`, - `test_diagnostics.py`, `test_forecast.py`, `test_irf.py`, - `test_recursive.py`, `test_report.py`, `test_residual_report.py`, - `test_volatility.py`, `test_pure_python_out.py`, `test_io_transform.py`, - `test_reliability.py`) compare against the frozen 0.4.1 program - (`drvarma_v.04.1`) and its saved outputs, and are skipped where that - checkout is missing. The C's `.inp` path has moved since (fdhess standard - errors, the MA wall report): pointing them at it means regenerating their - references. The path is removed in drvarma 6.0. -- **`csrc/`.** Only `elfvarma.c` is identical to the C's. `drvmlest.c`, - `qnewtopt.c`, `nlatools.c` and `main.h` differ (BUG-0002), and - `multshea.c` in its header. The record pins what they are; bringing them - to the C's is pending. +- **The pure-Python `.inp` path** on the four cases of BUG-0033. +- **The older `.inp` tests** (`test_estimate_cffi.py`, `test_estimate_py.py`, + `test_deseason.py`, `test_diagnostics.py`, `test_forecast.py`, + `test_irf.py`, `test_recursive.py`, `test_report.py`, + `test_residual_report.py`, `test_volatility.py`, `test_pure_python_out.py`, + `test_io_transform.py`, `test_reliability.py`) compare against the frozen + 0.4.1 program (`drvarma_v.04.1`) and its saved outputs, and are skipped + where that checkout is missing. The path is removed in drvarma 6.0. - **What exists in one engine only**: `docs/ARCHITECTURE.md` §8. diff --git a/src/drvarma/_build_cffi.py b/src/drvarma/_build_cffi.py index ff11bda..84c00ba 100644 --- a/src/drvarma/_build_cffi.py +++ b/src/drvarma/_build_cffi.py @@ -65,6 +65,7 @@ def _discover_gsl_dirs(): int twostep; int maxits; double grtol, sptol; + int bfgs_se; } DrvarmaModelSpec; typedef struct { @@ -85,6 +86,9 @@ def _discover_gsl_dirs(): double logelf; int termcode; int nit; + int se_how; + int ma_boundary; + int ma_nroots; } DrvarmaResult; void drvarma_defaults(DrvarmaModelSpec *spec); @@ -113,7 +117,9 @@ def _discover_gsl_dirs(): os.path.join(_INT, "nlatools.c"), os.path.join(_INT, "elfvarma.c"), os.path.join(_INT, "multshea.c"), + os.path.join(_INT, "lik.c"), os.path.join(_INT, "qnewtopt.c"), + os.path.join(_INT, "lnsrch.c"), os.path.join(_INT, "drvmlest.c"), ] diff --git a/src/drvarma/_engine.py b/src/drvarma/_engine.py index 025a7ce..431a961 100644 --- a/src/drvarma/_engine.py +++ b/src/drvarma/_engine.py @@ -75,11 +75,32 @@ def _warn_python_fallback(what="", stacklevel=3): RuntimeWarning, stacklevel=stacklevel) +# The C's est_se_label (drvmlest.c), and stderr.legacy_fd_std_errors' words. +_SE_LABEL = { + 0: "bfgs", + 1: "fdhess", + 2: "bfgs (fdhess: the optimum is on the boundary of the admissible region)", + 3: "bfgs (fdhess: the Hessian is not positive definite)", + 4: "none (fdhess: the optimum is on the boundary of the admissible region; " + "the search did not move, so it built no BFGS Hessian)", + 5: "none (fdhess: the Hessian is not positive definite; the search did not " + "move, so it built no BFGS Hessian)", +} + + def estimate_w(w, p, q, include_mean=False, diag_ar=False, diag_ma=False, diag_cov=False, - method=1, twostep=False, maxits=0, grtol=0.0, sptol=0.0): + method=1, twostep=False, maxits=0, grtol=0.0, sptol=0.0, + hessian="bfgs"): """Estimate VARMA(p,q) on the stationary series w (nobs x m). + ``hessian``: "bfgs" (the default) returns the BFGS factor's standard + errors, from either engine. "fd" asks the C engine for its own fdhess at + the optimum, as the C's CLI (``-hessian fd``), and adds ``se_method`` + (the C's ``est_se_label``); the pure-Python estimator ignores it and + returns BFGS, and Model then takes fdhess in Python + (``stderr.legacy_fd_std_errors``), the port of the same routine. + Uses the compiled C engine when available; otherwise falls back to the pure-Python exact-ML estimator (`estimate_py.estimate_w_py`), a faithful port of the C engine: same logelf and estimates to ~1e-10, std errors to @@ -114,6 +135,10 @@ def estimate_w(w, p, q, include_mean=False, spec.diag_cov = 1 if diag_cov else 0 spec.method = method spec.twostep = 1 if twostep else 0 + # The vendored C (atsw-gui's, BUG-0002) takes fdhess unless told not to. + if hessian not in ("bfgs", "fd"): + raise ValueError("hessian must be 'bfgs' or 'fd'") + spec.bfgs_se = 0 if hessian == "fd" else 1 if maxits: spec.maxits = maxits if grtol: @@ -141,6 +166,8 @@ def estimate_w(w, p, q, include_mean=False, # built on it was inert. "termcode": res.termcode, "nit": res.nit, + "ma_boundary": res.ma_boundary, + "ma_nroots": res.ma_nroots, "params": np.frombuffer(ffi.buffer(res.params, npar * 8), float).copy() if npar else np.zeros(0), "std_errors": np.frombuffer(ffi.buffer(res.std_errors, npar * 8), float).copy() @@ -157,6 +184,8 @@ def estimate_w(w, p, q, include_mean=False, "sigma": np.frombuffer(ffi.buffer(res.sigma, rm * rm * 8), float) .reshape(rm, rm).copy(), } + if hessian == "fd": + out["se_method"] = _SE_LABEL.get(res.se_how, "bfgs") finally: lib.drvarma_result_free(res) _ = _wbuf # keep buffer alive until here diff --git a/src/drvarma/model.py b/src/drvarma/model.py index cd3a753..d6f199a 100644 --- a/src/drvarma/model.py +++ b/src/drvarma/model.py @@ -95,10 +95,12 @@ def fit(self): self.result = estimate_w( w, p=self.p, q=self.q, include_mean=self.include_mean, diag_ar=self.diag_ar, diag_ma=self.diag_ma, diag_cov=self.diag_cov, - method=self.method, twostep=self.twostep, + method=self.method, twostep=self.twostep, hessian=self.hessian, ) - self.se_method = "bfgs" - if self.hessian == "fd" and self.result.get("npar"): + self.se_method = self.result.pop("se_method", "bfgs") + if (self.hessian == "fd" and self.result.get("npar") + and self.se_method == "bfgs"): + # The pure-Python estimator: fdhess here, the port of the C's. from .stderr import legacy_fd_std_errors cov, std, how, info = legacy_fd_std_errors( self.result, w, self.p, self.q, self.include_mean, self.diag_ar, diff --git a/tests/data/homologation.json b/tests/data/homologation.json index 6ab093e..f51869c 100644 --- a/tests/data/homologation.json +++ b/tests/data/homologation.json @@ -2,8 +2,8 @@ "_": "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": "29bd4f2f9724aea6994abf52499af86d0afb1b8f", - "date": "2026-11-22", + "c_commit": "d603ea1ee75cf2ee486b5fba040b633cc05151bb", + "date": "2026-11-28", "cases": [ { "name": "route U, monetary pair, VAR(1), deterministic terms by class", @@ -279,44 +279,74 @@ ], "csrc": { "csrc/internal/drvmlest.c": { - "sha256": "199be2d72cafabe36a702876d8aea30cbef65c38a2316b03c97d838e65c84959", "c_file": "engines/drvarma/src/drvmlest.c", - "identical_to_c": false + "identical_to_c": true, + "sha256": "f39b4fc424264d79e4df81cc3b12edc95dfbd5851ca06dafc938bcd1be8df5a2" + }, + "csrc/internal/qnewtopt.c": { + "c_file": "engines/drvarma/src/qnewtopt.c", + "identical_to_c": true, + "sha256": "6481fc56e245d680e6f496467c2752fec0d54195b56c7f86d1e8b636eb566b7a" + }, + "csrc/internal/nlatools.c": { + "c_file": "engines/drvarma/src/nlatools.c", + "identical_to_c": true, + "sha256": "a663d4d86640fa6e54ebf245629ea6a08e517cf253e9742d637639b0cd717fc2" }, "csrc/internal/elfvarma.c": { - "sha256": "bce5e718b0ad87eca01a519b43c190c24f59df0b4de81bcdb13049353d1523a7", "c_file": "engines/drvarma/src/elfvarma.c", - "identical_to_c": true + "identical_to_c": true, + "sha256": "bce5e718b0ad87eca01a519b43c190c24f59df0b4de81bcdb13049353d1523a7" }, "csrc/internal/main.h": { - "sha256": "d1b4b133016545d7e4ddbf41c950c1d4ae8576bca0acdddea44f9bf46c2c31db", "c_file": "engines/drvarma/include/main.h", - "identical_to_c": false + "identical_to_c": true, + "sha256": "e7df119de543ed6ca104252aac7aca503e3ec6aeb392f2c67e29a9ce571cce24" + }, + "csrc/internal/likhost.h": { + "c_file": "engines/drvarma/include/likhost.h", + "identical_to_c": true, + "sha256": "15daf84c05cf3f5d6b39ef2df3dcc9cc2fc3ee5865ed1542b16d7d49a1f08f3f" + }, + "csrc/internal/optimhost.h": { + "c_file": "engines/drvarma/include/optimhost.h", + "identical_to_c": true, + "sha256": "80842bb44674f1806aecd020369312a966841b84f8d4ab969b2bd35e0c675bb4" }, "csrc/internal/multshea.c": { - "sha256": "8eebd784c50514679099225212f033226af3a9d135bfb4ed296029b2745acc15", "c_file": "lib/lik/multshea.c", - "identical_to_c": false + "identical_to_c": true, + "sha256": "5a0e0f5613f1e254f155b6ba99e0c1dd0387276da05399ce67dcc4df3972ade1" }, - "csrc/internal/nlatools.c": { - "sha256": "c67df33692fdb22e1b48fcb1c7c89d70a16689cc732faea8275a711f8aed6225", - "c_file": "engines/drvarma/src/nlatools.c", - "identical_to_c": false + "csrc/internal/lik.c": { + "c_file": "lib/lik/lik.c", + "identical_to_c": true, + "sha256": "37a9ff1fc3fa7dbba042dd159c71f8127f0ddc8d9902a59df5bbc9fd13411e98" }, - "csrc/internal/qnewtopt.c": { - "sha256": "1374e8b07ac11ec3e798a1050d77ad0f53554230cf6080aa947635e894ca2d70", - "c_file": "engines/drvarma/src/qnewtopt.c", - "identical_to_c": false + "csrc/internal/lik.h": { + "c_file": "lib/lik/lik.h", + "identical_to_c": true, + "sha256": "4e42771972989411647848962271502e924d7fdf20bfee4c453ea65da37dfda0" + }, + "csrc/internal/lnsrch.c": { + "c_file": "lib/optim/lnsrch.c", + "identical_to_c": true, + "sha256": "4c7bcb7a398b820c0e61071fc54b2d971d0d466090c9595183e9172004dffabc" + }, + "csrc/internal/tusmodel.h": { + "c_file": "lib/fuepre/tusmodel.h", + "identical_to_c": true, + "sha256": "8ba9262ab7fafbc3dafaa82a62db02436a3fb906e46080b75b564e28c2298163" }, "csrc/drvarma_api.c": { - "sha256": "01b6e48f38101eeacadb22b4ab17672c76c5c964235a17e2b28fe8da1c16df03", "c_file": null, - "identical_to_c": null + "identical_to_c": null, + "sha256": "00f6a36e2576e26a1f71a7ee3171b8e8c35077f3224cbd72bdd177cca8b34fba" }, "csrc/drvarma_api.h": { - "sha256": "5a6fa08c84dea40b4e56feac70aad98925684a1d82cf319cf1e5c433dc181df0", "c_file": null, - "identical_to_c": null + "identical_to_c": null, + "sha256": "d5325c2576a2174d71e7319d05457aa0926dc60adc08f89ce60fab0fc618a052" } } } diff --git a/tests/data/inp_c/IPC.inp b/tests/data/inp_c/IPC.inp new file mode 100644 index 0000000..16ffd70 --- /dev/null +++ b/tests/data/inp_c/IPC.inp @@ -0,0 +1,228 @@ +* DRVARMA input generated by drvarma_gui +* series seasonally adjusted (harmonic), s=12 +********************************************************** +** Frequency (1=A, 4=Q, 12=M): + 12 +** Series, observations, start (subperiod year): + 3 216 1 2002 +** Series names: + y1 y2 y3 +** Box-Cox lambda, regular differences, annual differences: + 0 1 0 +** Data: +70.192892 82.991721 82.446017 +70.340050 82.669826 82.324435 +70.580318 82.636819 82.224519 +70.752865 82.531590 82.465159 +70.913078 82.609695 82.500244 +70.911180 82.571133 82.518106 +71.113894 82.499237 82.875413 +71.279607 82.488453 82.811608 +71.546153 82.611002 83.170581 +71.689811 82.611329 83.335110 +71.728358 82.622767 83.439639 +72.059793 83.056427 83.469168 +72.773892 83.591721 84.076017 +73.014050 83.769826 84.434435 +73.180318 83.536819 84.314519 +72.991865 83.331590 84.125159 +72.828078 83.109695 83.960244 +72.872180 83.371133 84.148106 +73.109894 83.299237 84.415413 +73.407607 83.388453 84.361608 +73.626153 83.511002 84.890581 +73.557811 83.611329 85.105110 +73.726358 83.722767 85.309639 +73.944793 83.956427 85.289168 +74.435892 84.491721 85.736017 +74.557050 84.369826 85.874435 +74.737318 84.436819 85.754519 +74.974865 84.731590 85.905159 +75.323078 84.909695 86.160244 +75.438180 84.871133 86.218106 +75.559894 84.799237 86.435413 +75.855607 84.988453 86.371608 +75.991153 84.911002 86.660581 +76.206811 85.111329 86.915110 +76.326358 85.322767 87.069639 +76.342793 85.856427 87.059168 +76.708892 85.791721 87.026017 +76.993050 85.769826 87.334435 +77.261318 85.936819 87.424519 +77.587865 85.731590 87.525159 +77.641078 85.809695 87.520244 +77.818180 85.971133 87.648106 +78.036894 86.099237 87.875413 +78.341607 86.288453 87.961608 +78.822153 86.511002 88.510581 +78.897811 86.711329 88.525110 +78.945358 86.722767 88.449639 +79.207793 87.056427 88.449168 +79.896892 87.291721 88.806017 +80.022050 87.369826 88.924435 +80.248318 87.136819 88.714519 +80.593865 87.431590 89.025159 +80.790078 87.409695 89.340244 +80.908180 87.571133 89.368106 +81.121894 87.699237 89.575413 +81.249607 87.688453 89.621608 +81.117153 87.511002 89.630581 +80.885811 87.611329 89.465110 +81.014358 87.922767 89.669639 +81.328793 88.256427 89.769168 +81.791892 88.791721 89.906017 +81.934050 88.869826 89.854435 +82.215318 88.836819 89.774519 +82.564865 89.231590 90.145159 +82.697078 89.209695 90.300244 +82.845180 89.271133 90.438106 +82.935894 89.499237 90.565413 +83.012607 89.488453 90.681608 +83.285153 89.811002 90.990581 +83.798811 90.111329 91.255110 +84.329358 90.922767 91.859639 +84.775793 91.056427 92.089168 +85.260892 91.291721 92.426017 +85.480050 91.369826 92.404435 +85.897318 91.636819 92.634519 +86.036865 91.431590 92.875159 +86.524078 91.909695 93.310244 +87.020180 92.171133 93.678106 +87.297894 92.499237 93.835413 +87.073607 92.288453 93.551608 +87.056153 92.311002 93.700581 +86.791811 92.211329 93.685110 +86.349358 92.122767 93.349639 +85.995793 92.056427 93.009168 +85.943892 92.191721 93.076017 +86.040050 92.369826 93.204435 +85.845318 91.936819 92.914519 +85.898865 92.031590 92.995159 +85.773078 91.909695 93.070244 +86.148180 92.171133 93.218106 +86.105894 91.999237 93.155413 +86.368607 92.288453 93.381608 +86.166153 92.111002 93.360581 +86.215811 92.311329 93.485110 +86.612358 92.422767 93.719639 +86.681793 92.856427 93.859168 +86.820892 92.791721 94.096017 +86.751050 92.869826 94.394435 +87.054318 93.136819 94.394519 +87.196865 93.131590 94.565159 +87.295078 93.109695 94.610244 +87.447180 93.071133 94.628106 +87.750894 92.999237 94.715413 +87.934607 93.188453 94.681608 +87.996153 93.211002 94.820581 +88.234811 93.411329 94.975110 +88.643358 93.922767 95.189639 +89.281793 94.056427 95.509168 +89.637892 94.391721 95.726017 +89.838050 94.669826 95.954435 +90.169318 94.936819 96.274519 +90.505865 95.031590 96.535159 +90.380078 94.909695 96.520244 +90.247180 94.971133 96.628106 +90.457894 94.999237 96.555413 +90.532607 95.188453 96.801608 +90.754153 95.511002 96.940581 +90.904811 95.611329 97.205110 +91.202358 96.022767 97.579639 +91.412793 95.956427 97.859168 +91.415892 96.291721 97.966017 +91.597050 96.669826 98.144435 +91.873318 97.036819 98.494519 +92.377865 96.831590 98.555159 +92.145078 96.709695 98.440244 +91.967180 96.571133 98.498106 +92.448894 96.799237 98.425413 +92.930607 97.188453 98.821608 +93.844153 97.411002 98.790581 +94.076811 97.511329 99.005110 +93.887358 97.922767 98.959639 +94.044793 97.856427 99.159168 +93.850892 97.891721 99.106017 +94.099050 98.169826 99.164435 +94.093318 98.336819 99.454519 +93.662865 97.931590 99.235159 +93.740078 98.309695 99.230244 +93.874180 98.371133 99.418106 +94.084894 98.599237 99.475413 +94.339607 98.688453 99.681608 +94.164153 98.811002 99.660581 +93.982811 98.711329 99.565110 +94.106358 99.222767 99.629639 +94.282793 99.256427 99.859168 +94.035892 99.291721 99.746017 +94.083050 99.369826 100.074435 +93.956318 99.436819 100.064519 +94.007865 99.331590 99.955159 +93.934078 99.109695 99.910244 +93.955180 99.371133 99.898106 +93.764894 99.399237 99.935413 +93.875607 99.588453 100.121608 +94.019153 99.711002 99.950581 +93.892811 99.511329 100.015110 +93.754358 99.822767 99.949639 +93.296793 99.456427 99.919168 +92.803892 98.991721 99.366017 +93.081050 99.369826 99.804435 +93.335318 99.636819 99.994519 +93.408865 100.131590 100.035159 +93.761078 100.309695 100.210244 +94.008180 100.271133 100.158106 +93.828894 100.299237 100.105413 +93.480607 100.388453 100.171608 +93.194153 100.311002 99.980581 +93.226811 100.411329 100.075110 +93.496358 100.022767 99.989639 +93.313793 99.656427 100.099168 +92.538892 99.491721 99.586017 +92.302050 99.469826 99.614435 +92.554318 99.936819 99.844519 +92.419865 100.031590 99.845159 +92.831078 100.509695 100.190244 +93.257180 100.571133 100.348106 +93.272894 100.799237 100.325413 +93.355607 100.788453 100.401608 +93.360153 100.911002 100.370581 +93.861811 101.211329 100.435110 +94.131358 100.822767 100.519639 +94.782793 101.156427 100.709168 +95.271892 101.091721 100.916017 +95.019050 101.369826 100.814435 +94.664318 101.336819 100.994519 +94.788865 101.731590 101.015159 +94.636078 101.709695 101.000244 +94.672180 101.971133 101.038106 +94.713894 102.199237 101.045413 +94.864607 102.388453 101.311608 +95.030153 102.611002 101.360581 +95.341811 102.511329 101.495110 +95.706358 102.422767 101.699639 +95.840793 102.556427 101.909168 +95.815892 102.491721 102.256017 +96.031050 102.469826 102.004435 +95.808318 102.836819 102.574519 +95.815865 103.031590 102.675159 +96.587078 103.809695 103.050244 +96.836180 103.871133 103.088106 +96.835894 104.099237 103.355413 +96.936607 104.288453 103.601608 +97.173153 104.611002 103.590581 +97.506811 104.911329 103.735110 +97.327358 104.522767 103.619639 +96.979793 104.156427 103.529168 +96.747892 103.891721 103.516017 +97.070050 103.969826 103.344435 +97.084318 104.136819 103.714519 +97.278865 105.131590 103.975159 +97.373078 105.309695 104.020244 +97.253180 105.571133 104.298106 +97.344894 105.899237 104.455413 +97.253607 105.788453 104.681608 +97.254153 105.911002 104.530581 +97.632811 106.111329 104.525110 +97.726358 105.622767 104.689639 +97.746793 105.756427 105.039168 diff --git a/tests/data/inp_c/IPC_eu_levels.inp b/tests/data/inp_c/IPC_eu_levels.inp new file mode 100644 index 0000000..8776d24 --- /dev/null +++ b/tests/data/inp_c/IPC_eu_levels.inp @@ -0,0 +1,228 @@ +* DRVARMA input generated by drvarma_gui +* series seasonally adjusted (harmonic), s=12 +********************************************************** +** Frequency (1=A, 4=Q, 12=M): + 12 +** Series, observations, start (subperiod year): + 3 216 1 2002 +** Series names: + y1 y2 y3 +** Box-Cox lambda, regular differences, annual differences: + 0 1 0 +** Data: +70.192892 82.446017 78.174455 +70.340050 82.324435 78.153595 +70.580318 82.224519 78.138290 +70.752865 82.465159 78.050763 +70.913078 82.500244 78.107680 +70.911180 82.518106 78.075708 +71.113894 82.875413 78.004847 +71.279607 82.811608 77.995098 +71.546153 83.170581 78.118682 +71.689811 83.335110 78.114488 +71.728358 83.439639 78.099183 +72.059793 83.469168 78.467211 +72.773892 84.076017 78.974455 +73.014050 84.434435 79.153595 +73.180318 84.314519 78.938290 +72.991865 84.125159 78.750763 +72.828078 83.960244 78.507680 +72.872180 84.148106 78.775708 +73.109894 84.415413 78.704847 +73.407607 84.361608 78.795098 +73.626153 84.890581 78.918682 +73.557811 85.105110 79.014488 +73.726358 85.309639 79.099183 +73.944793 85.289168 79.367211 +74.435892 85.736017 79.874455 +74.557050 85.874435 79.753595 +74.737318 85.754519 79.838290 +74.974865 85.905159 80.050763 +75.323078 86.160244 80.207680 +75.438180 86.218106 80.175708 +75.559894 86.435413 80.104847 +75.855607 86.371608 80.295098 +75.991153 86.660581 80.218682 +76.206811 86.915110 80.414488 +76.326358 87.069639 80.599183 +76.342793 87.059168 81.167211 +76.708892 87.026017 81.074455 +76.993050 87.334435 81.053595 +77.261318 87.424519 81.238290 +77.587865 87.525159 80.950763 +77.641078 87.520244 81.107680 +77.818180 87.648106 81.175708 +78.036894 87.875413 81.404847 +78.341607 87.961608 81.595098 +78.822153 88.510581 81.818682 +78.897811 88.525110 81.914488 +78.945358 88.449639 81.999183 +79.207793 88.449168 82.267211 +79.896892 88.806017 82.474455 +80.022050 88.924435 82.553595 +80.248318 88.714519 82.338290 +80.593865 89.025159 82.650763 +80.790078 89.340244 82.607680 +80.908180 89.368106 82.775708 +81.121894 89.575413 82.904847 +81.249607 89.621608 82.795098 +81.117153 89.630581 82.618682 +80.885811 89.465110 82.814488 +81.014358 89.669639 83.099183 +81.328793 89.769168 83.467211 +81.791892 89.906017 83.974455 +81.934050 89.854435 83.953595 +82.215318 89.774519 83.938290 +82.564865 90.145159 84.350763 +82.697078 90.300244 84.307680 +82.845180 90.438106 84.375708 +82.935894 90.565413 84.604847 +83.012607 90.681608 84.595098 +83.285153 90.990581 84.818682 +83.798811 91.255110 85.114488 +84.329358 91.859639 85.899183 +84.775793 92.089168 86.067211 +85.260892 92.426017 86.274455 +85.480050 92.404435 86.353595 +85.897318 92.634519 86.538290 +86.036865 92.875159 86.350763 +86.524078 93.310244 86.807680 +87.020180 93.678106 87.075708 +87.297894 93.835413 87.404847 +87.073607 93.551608 87.195098 +87.056153 93.700581 87.318682 +86.791811 93.685110 87.214488 +86.349358 93.349639 87.099183 +85.995793 93.009168 86.967211 +85.943892 93.076017 87.074455 +86.040050 93.204435 87.253595 +85.845318 92.914519 86.938290 +85.898865 92.995159 86.950763 +85.773078 93.070244 86.907680 +86.148180 93.218106 87.175708 +86.105894 93.155413 87.004847 +86.368607 93.381608 87.295098 +86.166153 93.360581 87.018682 +86.215811 93.485110 87.214488 +86.612358 93.719639 87.399183 +86.681793 93.859168 87.767211 +86.820892 94.096017 87.774455 +86.751050 94.394435 87.753595 +87.054318 94.394519 88.038290 +87.196865 94.565159 88.050763 +87.295078 94.610244 88.007680 +87.447180 94.628106 87.975708 +87.750894 94.715413 87.904847 +87.934607 94.681608 88.095098 +87.996153 94.820581 88.118682 +88.234811 94.975110 88.314488 +88.643358 95.189639 88.699183 +89.281793 95.509168 88.967211 +89.637892 95.726017 89.174455 +89.838050 95.954435 89.453595 +90.169318 96.274519 89.738290 +90.505865 96.535159 89.750763 +90.380078 96.520244 89.707680 +90.247180 96.628106 89.775708 +90.457894 96.555413 89.804847 +90.532607 96.801608 89.995098 +90.754153 96.940581 90.218682 +90.904811 97.205110 90.414488 +91.202358 97.579639 90.799183 +91.412793 97.859168 90.667211 +91.415892 97.966017 91.074455 +91.597050 98.144435 91.353595 +91.873318 98.494519 91.638290 +92.377865 98.555159 91.550763 +92.145078 98.440244 91.407680 +91.967180 98.498106 91.275708 +92.448894 98.425413 91.404847 +92.930607 98.821608 91.895098 +93.844153 98.790581 92.118682 +94.076811 99.005110 92.214488 +93.887358 98.959639 92.499183 +94.044793 99.159168 92.467211 +93.850892 99.106017 92.574455 +94.099050 99.164435 92.753595 +94.093318 99.454519 92.938290 +93.662865 99.235159 92.550763 +93.740078 99.230244 92.907680 +93.874180 99.418106 92.975708 +94.084894 99.475413 93.204847 +94.339607 99.681608 93.295098 +94.164153 99.660581 93.418682 +93.982811 99.565110 93.314488 +94.106358 99.629639 93.799183 +94.282793 99.859168 93.867211 +94.035892 99.746017 93.774455 +94.083050 100.074435 93.953595 +93.956318 100.064519 93.938290 +94.007865 99.955159 93.850763 +93.934078 99.910244 93.707680 +93.955180 99.898106 93.875708 +93.764894 99.935413 94.004847 +93.875607 100.121608 94.095098 +94.019153 99.950581 94.218682 +93.892811 100.015110 94.114488 +93.754358 99.949639 94.399183 +93.296793 99.919168 93.967211 +92.803892 99.366017 93.574455 +93.081050 99.804435 93.953595 +93.335318 99.994519 94.238290 +93.408865 100.035159 94.650763 +93.761078 100.210244 94.807680 +94.008180 100.158106 94.775708 +93.828894 100.105413 94.804847 +93.480607 100.171608 94.795098 +93.194153 99.980581 94.818682 +93.226811 100.075110 94.914488 +93.496358 99.989639 94.599183 +93.313793 100.099168 94.267211 +92.538892 99.586017 94.074455 +92.302050 99.614435 94.053595 +92.554318 99.844519 94.438290 +92.419865 99.845159 94.550763 +92.831078 100.190244 95.007680 +93.257180 100.348106 95.075708 +93.272894 100.325413 95.204847 +93.355607 100.401608 95.195098 +93.360153 100.370581 95.418682 +93.861811 100.435110 95.614488 +94.131358 100.519639 95.299183 +94.782793 100.709168 95.567211 +95.271892 100.916017 95.574455 +95.019050 100.814435 95.753595 +94.664318 100.994519 95.738290 +94.788865 101.015159 96.150763 +94.636078 101.000244 96.107680 +94.672180 101.038106 96.375708 +94.713894 101.045413 96.604847 +94.864607 101.311608 96.795098 +95.030153 101.360581 96.918682 +95.341811 101.495110 96.914488 +95.706358 101.699639 96.799183 +95.840793 101.909168 96.867211 +95.815892 102.256017 96.874455 +96.031050 102.004435 96.853595 +95.808318 102.574519 97.138290 +95.815865 102.675159 97.450763 +96.587078 103.050244 98.107680 +96.836180 103.088106 98.175708 +96.835894 103.355413 98.404847 +96.936607 103.601608 98.595098 +97.173153 103.590581 98.918682 +97.506811 103.735110 99.114488 +97.327358 103.619639 98.799183 +96.979793 103.529168 98.467211 +96.747892 103.516017 98.174455 +97.070050 103.344435 98.253595 +97.084318 103.714519 98.438290 +97.278865 103.975159 99.350763 +97.373078 104.020244 99.507680 +97.253180 104.298106 99.775708 +97.344894 104.455413 100.004847 +97.253607 104.681608 99.995098 +97.254153 104.530581 100.118682 +97.632811 104.525110 100.214488 +97.726358 104.689639 99.799183 +97.746793 105.039168 99.967211 diff --git a/tests/data/inp_c/PSW.inp b/tests/data/inp_c/PSW.inp new file mode 100644 index 0000000..699781a --- /dev/null +++ b/tests/data/inp_c/PSW.inp @@ -0,0 +1,228 @@ +* DRVARMA example input file - PSW (raw levels) +* 2 monthly series; modelled in log first differences +*********************************************************** +** Frequency (1=A, 4=Q, 12=M): + 12 +** Series, observations, start (subperiod year): + 2 216 1 2005 +** Series names: + PSW_a PSW_b +** Box-Cox lambda, regular differences, annual differences: + 0.0 1 0 +** Data: +69.53 19.670 +69.59 20.740 +70.165 24.420 +71.118 26.270 +71.374 27.020 +71.377 25.520 +70.882 26.940 +71.085 28.380 +71.351 29.670 +72.058 28.850 +72.169 26.270 +72.409 29.420 +72.111 32.940 +72.264 35.870 +72.765 33.550 +73.357 28.250 +73.289 28.140 +73.338 30.720 +72.878 30.760 +73.213 31.590 +73.431 28.290 +73.926 30.330 +74.167 31.090 +74.294 32.150 +73.773 34.270 +73.807 34.740 +74.322 36.760 +75.34 36.690 +75.784 40.280 +75.904 38.020 +75.328 40.690 +75.661 44.940 +75.796 45.950 +76.575 53.130 +76.767 48.460 +76.692 43.330 +76.046 46.840 +76.243 47.970 +76.846 54.310 +77.953 53.040 +78.102 49.830 +78.284 56.260 +77.805 58.700 +78.147 64.970 +78.627 65.570 +79.266 62.370 +79.386 58.300 +79.557 59.430 +79.234 65.510 +79.272 61.630 +79.833 62.900 +80.959 69.690 +81.251 70.940 +81.374 70.960 +80.89 74.410 +81.055 73.050 +80.922 63.870 +81.254 58.880 +81.455 59.370 +81.678 62.030 +81.129 54.570 +81.184 59.260 +81.8 60.560 +82.93 63.970 +83.158 63.460 +83.311 67.480 +82.704 74.180 +82.818 72.390 +83.09 79.930 +84.167 86.200 +84.77 94.620 +85.125 91.730 +84.598 92.950 +84.73 95.350 +85.482 105.560 +86.402 112.570 +86.985 125.390 +87.486 133.930 +87.066 133.440 +86.879 116.610 +86.861 103.900 +87.16 76.650 +86.79 57.440 +86.345 41.020 +85.281 41.740 +85.29 39.160 +85.43 47.980 +86.264 49.790 +86.234 59.160 +86.614 69.680 +85.874 64.090 +86.174 71.060 +85.971 69.460 +86.584 75.820 +87.053 78.080 +87.031 74.300 +86.158 78.220 +86.001 76.420 +86.639 81.240 +87.562 84.480 +87.756 73.840 +87.913 75.350 +87.519 76.370 +87.74 76.820 +87.801 75.310 +88.603 81.900 +89.084 84.140 +89.631 89.040 +88.975 89.420 +89.088 89.580 +89.754 102.940 +90.871 110.040 +90.841 101.330 +90.713 96.290 +90.226 97.190 +90.338 86.330 +90.559 85.610 +91.273 86.410 +91.643 97.210 +91.762 98.570 +90.753 100.240 +90.847 102.250 +91.458 106.190 +92.743 103.330 +92.606 94.700 +92.433 82.410 +92.217 87.930 +92.736 94.160 +93.649 94.720 +94.445 89.570 +94.328 86.660 +94.394 88.250 +93.188 94.690 +93.349 95.320 +93.678 93.050 +94.028 92.070 +94.201 94.800 +94.34 95.800 +93.853 104.610 +94.145 106.570 +93.969 106.290 +94.351 100.540 +94.547 93.860 +94.632 97.630 +93.373 94.620 +93.333 100.820 +93.541 100.800 +94.373 102.070 +94.395 102.180 +94.421 105.790 +93.533 103.590 +93.681 96.540 +93.824 93.210 +94.261 84.400 +94.195 75.790 +93.646 59.290 +92.141 47.220 +92.331 50.580 +92.92 47.820 +93.774 54.450 +94.222 59.270 +94.474 59.820 +93.597 50.900 +93.286 42.870 +92.999 45.480 +93.595 46.220 +93.937 42.440 +93.663 37.190 +91.876 31.680 +91.552 30.320 +92.139 37.550 +92.785 40.750 +93.292 46.710 +93.723 48.760 +93.041 44.650 +93.161 44.720 +93.165 45.180 +94.23 49.780 +94.572 45.660 +95.132 51.970 +94.609 52.500 +94.269 53.470 +94.249 49.330 +95.154 51.060 +95.097 48.480 +95.138 45.180 +94.482 46.630 +94.67 48.040 +94.835 49.820 +95.71 51.580 +96.147 56.640 +96.19 57.880 +95.153 63.700 +95.281 62.230 +95.393 62.730 +96.181 66.250 +97.048 69.980 +97.302 67.870 +96.604 70.980 +96.742 68.060 +96.978 70.230 +97.875 70.750 +97.768 56.960 +97.329 49.520 +96.085 51.380 +96.32 54.950 +96.669 58.150 +97.644 63.860 +97.834 60.830 +97.719 54.660 +97.113 57.350 +97.059 54.810 +97.059 56.950 +98.001 53.960 +98.167 57.030 +98.096 59.880 diff --git a/tests/data/inp_c/cases.json b/tests/data/inp_c/cases.json new file mode 100644 index 0000000..70ed059 --- /dev/null +++ b/tests/data/inp_c/cases.json @@ -0,0 +1,185 @@ +{ + "_": "The C's .inp path (atsw-gui engines/drvarma tests/banco/ref, byte goldens of its battery): the port reproduces them. tests/test_inp_path_as_the_c.py.", + "c_commit": "d603ea1ee75cf2ee486b5fba040b633cc05151bb", + "cases": [ + { + "name": "c1_ipc_ar1", + "file": "IPC.inp", + "c_args": "1 0 -mean", + "logL": 123.78853685, + "se_method": "fdhess", + "table": [ + "mu[1] 0.154322 0.027920 5.527 0.0000 ***", + "mu[2] 0.113181 0.017940 6.309 0.0000 ***", + "mu[3] 0.112552 0.015179 7.415 0.0000 ***", + "phi[1]_11 0.332947 0.078103 4.263 0.0000 ***", + "phi[1]_12 0.197687 0.085168 2.321 0.0203 *", + "phi[1]_13 -0.071896 0.110714 -0.649 0.5161", + "phi[1]_21 -0.010186 0.074922 -0.136 0.8919", + "phi[1]_22 0.024699 0.081731 0.302 0.7625", + "phi[1]_23 0.099411 0.106257 0.936 0.3495", + "phi[1]_31 0.242424 0.056297 4.306 0.0000 ***", + "phi[1]_32 0.178760 0.061369 2.913 0.0036 **", + "phi[1]_33 -0.269179 0.079747 -3.375 0.0007 ***", + "cov[1,1] 1.221510 (normalised)", + "cov[2,1] 0.591307 0.068367 8.649 0.0000 ***", + "cov[2,2] 1.104672 0.129687 8.518 0.0000 ***", + "cov[3,1] 0.430090 0.052055 8.262 0.0000 ***", + "cov[3,2] 0.432722 0.064559 6.703 0.0000 ***", + "cov[3,3] 0.627578 0.074570 8.416 0.0000 ***" + ] + }, + { + "name": "c2_ipc_arma21", + "file": "IPC.inp", + "c_args": "2 1 -mean -diagcov", + "logL": 66.89629914, + "se_method": "bfgs (fdhess: the optimum is on the boundary of the admissible region)", + "table": [ + "mu[1] 0.153026 0.027596 5.545 0.0000 ***", + "mu[2] 0.114990 0.023776 4.836 0.0000 ***", + "mu[3] 0.113074 0.031444 3.596 0.0003 ***", + "phi[1]_11 0.181139 0.303430 0.597 0.5505", + "phi[1]_12 0.074702 0.155071 0.482 0.6300", + "phi[1]_13 1.062730 0.293094 3.626 0.0003 ***", + "phi[1]_21 0.669440 1.026255 0.652 0.5142", + "phi[1]_22 -0.264800 0.814189 -0.325 0.7450", + "phi[1]_23 0.438867 0.131494 3.338 0.0008 ***", + "phi[1]_31 0.722979 0.073409 9.849 0.0000 ***", + "phi[1]_32 -1.113667 0.252626 -4.408 0.0000 ***", + "phi[1]_33 1.069938 0.138672 7.716 0.0000 ***", + "phi[2]_11 -0.249648 0.073731 -3.386 0.0007 ***", + "phi[2]_12 -0.198719 0.078469 -2.532 0.0113 *", + "phi[2]_13 0.379840 0.664119 0.572 0.5674", + "phi[2]_21 -0.272801 0.703469 -0.388 0.6982", + "phi[2]_22 -0.177185 1.190963 -0.149 0.8817", + "phi[2]_23 0.114939 0.659032 0.174 0.8615", + "phi[2]_31 -0.461468 0.599872 -0.769 0.4417", + "phi[2]_32 -0.372725 1.222799 -0.305 0.7605", + "phi[2]_33 0.550970 0.289805 1.901 0.0573 .", + "theta[1]_11 -0.179391 0.202023 -0.888 0.3746", + "theta[1]_12 -0.073876 0.856232 -0.086 0.9312", + "theta[1]_13 1.170257 1.624792 0.720 0.4714", + "theta[1]_21 0.649935 1.421162 0.457 0.6474", + "theta[1]_22 -0.216533 1.421055 -0.152 0.8789", + "theta[1]_23 0.390685 0.000012 33356.908 0.0000 ***", + "theta[1]_31 0.432226 0.343427 1.259 0.2082", + "theta[1]_32 -1.244556 0.000020 -61533.772 0.0000 ***", + "theta[1]_33 1.423004 0.000001 2599140.123 0.0000 ***", + "cov[1,1] 1.344670 0.400819 3.355 0.0008 ***", + "cov[2,2] 1.141178 0.203487 5.608 0.0000 ***", + "cov[3,3] 0.653281 0.379368 1.722 0.0851 ." + ] + }, + { + "name": "c3_psw_arma11", + "file": "PSW.inp", + "c_args": "1 1", + "logL": -871.32401308, + "se_method": "bfgs (fdhess: the optimum is on the boundary of the admissible region)", + "table": [ + "phi[1]_11 0.932628 0.122407 7.619 0.0000 ***", + "phi[1]_12 1.147974 0.091205 12.587 0.0000 ***", + "phi[1]_21 -0.815344 0.028442 -28.667 0.0000 ***", + "phi[1]_22 0.067615 0.123984 0.545 0.5855", + "theta[1]_11 0.910742 0.131074 6.948 0.0000 ***", + "theta[1]_12 1.146984 0.090203 12.716 0.0000 ***", + "theta[1]_21 -0.817923 0.045205 -18.093 0.0000 ***", + "theta[1]_22 0.068024 0.123175 0.552 0.5808", + "cov[1,1] 0.004895 0.000704 6.954 0.0000 ***", + "cov[2,1] 0.041263 0.006195 6.660 0.0000 ***", + "cov[2,2] 2.143993 0.009599 223.358 0.0000 ***" + ] + }, + { + "name": "c5_eu_diag", + "file": "IPC_eu_levels.inp", + "c_args": "1 0 -mean -diagar -diagma", + "logL": 106.98159683, + "se_method": "fdhess", + "table": [ + "mu[1] 0.154388 0.024037 6.423 0.0000 ***", + "mu[2] 0.112874 0.013054 8.646 0.0000 ***", + "mu[3] 0.114658 0.015237 7.525 0.0000 ***", + "phi[1]_11 0.259907 0.055936 4.646 0.0000 ***", + "phi[1]_12 (fixed 0.0)", + "phi[1]_13 (fixed 0.0)", + "phi[1]_21 (fixed 0.0)", + "phi[1]_22 -0.040814 0.058648 -0.696 0.4865", + "phi[1]_23 (fixed 0.0)", + "phi[1]_31 (fixed 0.0)", + "phi[1]_32 (fixed 0.0)", + "phi[1]_33 -0.080493 0.059674 -1.349 0.1774", + "cov[1,1] 1.220120 (normalised)", + "cov[2,1] 0.478337 0.055712 8.586 0.0000 ***", + "cov[2,2] 0.709208 0.083829 8.460 0.0000 ***", + "cov[3,1] 0.600078 0.066712 8.995 0.0000 ***", + "cov[3,2] 0.440961 0.066975 6.584 0.0000 ***", + "cov[3,3] 1.040975 0.122671 8.486 0.0000 ***" + ] + }, + { + "name": "c6_ipc_aprox", + "file": "IPC.inp", + "c_args": "1 0 -mean -m 2", + "logL": 123.78853685, + "se_method": "fdhess", + "table": [ + "mu[1] 0.154322 0.027920 5.527 0.0000 ***", + "mu[2] 0.113181 0.017940 6.309 0.0000 ***", + "mu[3] 0.112552 0.015179 7.415 0.0000 ***", + "phi[1]_11 0.332947 0.078103 4.263 0.0000 ***", + "phi[1]_12 0.197687 0.085168 2.321 0.0203 *", + "phi[1]_13 -0.071896 0.110714 -0.649 0.5161", + "phi[1]_21 -0.010186 0.074922 -0.136 0.8919", + "phi[1]_22 0.024699 0.081731 0.302 0.7625", + "phi[1]_23 0.099411 0.106257 0.936 0.3495", + "phi[1]_31 0.242424 0.056297 4.306 0.0000 ***", + "phi[1]_32 0.178760 0.061369 2.913 0.0036 **", + "phi[1]_33 -0.269179 0.079747 -3.375 0.0007 ***", + "cov[1,1] 1.221510 (normalised)", + "cov[2,1] 0.591307 0.068367 8.649 0.0000 ***", + "cov[2,2] 1.104672 0.129687 8.518 0.0000 ***", + "cov[3,1] 0.430090 0.052055 8.262 0.0000 ***", + "cov[3,2] 0.432722 0.064559 6.703 0.0000 ***", + "cov[3,3] 0.627578 0.074570 8.416 0.0000 ***" + ] + }, + { + "name": "c7_ipc_twostep", + "file": "IPC.inp", + "c_args": "1 1 -mean -twostep", + "logL": 134.22956045, + "se_method": "bfgs (fdhess: the optimum is on the boundary of the admissible region)", + "table": [ + "mu[1] 0.153429 0.024459 6.273 0.0000 ***", + "mu[2] 0.112878 0.018021 6.264 0.0000 ***", + "mu[3] 0.112092 0.014867 7.540 0.0000 ***", + "phi[1]_11 -0.608418 0.141490 -4.300 0.0000 ***", + "phi[1]_12 2.356557 0.349580 6.741 0.0000 ***", + "phi[1]_13 0.549854 0.177499 3.098 0.0019 **", + "phi[1]_21 -0.814982 0.062426 -13.055 0.0000 ***", + "phi[1]_22 2.016743 0.158443 12.729 0.0000 ***", + "phi[1]_23 0.789878 0.145376 5.433 0.0000 ***", + "phi[1]_31 1.272105 0.245720 5.177 0.0000 ***", + "phi[1]_32 -3.057387 0.290008 -10.542 0.0000 ***", + "phi[1]_33 -1.086022 0.085515 -12.700 0.0000 ***", + "theta[1]_11 -1.005341 0.157738 -6.373 0.0000 ***", + "theta[1]_12 2.174946 0.343475 6.332 0.0000 ***", + "theta[1]_13 0.730394 0.094080 7.764 0.0000 ***", + "theta[1]_21 -0.870721 0.071913 -12.108 0.0000 ***", + "theta[1]_22 1.982877 0.156611 12.661 0.0000 ***", + "theta[1]_23 0.790530 0.110643 7.145 0.0000 ***", + "theta[1]_31 0.982845 0.236528 4.155 0.0000 ***", + "theta[1]_32 -3.246985 0.301412 -10.773 0.0000 ***", + "theta[1]_33 -0.821665 0.155112 -5.297 0.0000 ***", + "cov[1,1] 1.358769 0.091825 14.797 0.0000 ***", + "cov[2,1] 0.647299 0.056096 11.539 0.0000 ***", + "cov[2,2] 1.239690 0.097241 12.749 0.0000 ***", + "cov[3,1] 0.517848 0.068457 7.565 0.0000 ***", + "cov[3,2] 0.525213 0.054981 9.553 0.0000 ***", + "cov[3,3] 0.703713 0.068618 10.256 0.0000 ***" + ] + } + ] +} diff --git a/tests/test_inp_path_as_the_c.py b/tests/test_inp_path_as_the_c.py new file mode 100644 index 0000000..a01e9ab --- /dev/null +++ b/tests/test_inp_path_as_the_c.py @@ -0,0 +1,88 @@ +"""The deprecated .inp path against the C of record (BUG-0002). + +``tests/data/inp_c/cases.json`` holds, for six cases of the C's battery +(atsw-gui ``engines/drvarma/tests/banco``, whose references are byte goldens), +the C's log-likelihood, how it got the standard errors and its parameter +table. The vendored C (``csrc/``) is the C's, so with the compiled engine the +port's table is the C's line for line. The pure-Python estimator is held to +the numbers where the standard errors are fdhess's; where the optimum is on +the boundary they are BFGS's, path-dependent, and the port's path is not yet +the C's (BUG-0033).""" +import json +import os +import re +import shutil +import subprocess +import sys + +import pytest + +import drvarma + +HERE = os.path.dirname(os.path.abspath(__file__)) +D = os.path.join(HERE, "data", "inp_c") +REC = json.load(open(os.path.join(D, "cases.json"), encoding="utf-8")) +SRC = os.path.join(HERE, "..", "src") + + +def _run(case, tmp_path, no_engine): + shutil.copy(os.path.join(D, case["file"]), tmp_path) + env = dict(os.environ, PYTHONPATH=SRC + os.pathsep + os.environ.get("PYTHONPATH", "")) + if no_engine: + env["DRVARMA_NO_ENGINE"] = "1" + else: + env.pop("DRVARMA_NO_ENGINE", None) + base = case["file"][:-4] + subprocess.run([sys.executable, "-m", "drvarma.cli", base, *case["c_args"].split()], + cwd=tmp_path, env=env, capture_output=True, text=True, timeout=1800) + t = open(os.path.join(tmp_path, base + ".out"), errors="replace").read() + logl = float(re.findall(r"Log-likelihood = (-?[\d.]+)", t)[-1]) + se = re.search(r"^Standard errors: (.*)$", t, re.M).group(1).strip() + rows = [] + for line in t[t.index("Std.Error t-stat"):].splitlines()[2:]: + if not line.strip() or line.startswith("---") or line.startswith("Standard errors"): + break + rows.append(line.rstrip()) + return logl, se, rows + + +def _numbers(rows): + out = {} + for line in rows: + x = line.split() + try: + out[x[0]] = (float(x[1]), float(x[2])) + except (ValueError, IndexError): + pass + return out + + +@pytest.mark.skipif(drvarma.engine_backend() != "c", reason="needs the compiled engine") +@pytest.mark.parametrize("case", REC["cases"], ids=[c["name"] for c in REC["cases"]]) +def test_with_the_engine_the_table_is_the_cs(case, tmp_path): + logl, se, rows = _run(case, tmp_path, no_engine=False) + assert logl == pytest.approx(case["logL"], abs=1e-5) + assert se == case["se_method"] + assert rows == case["table"] + + +# The pure-Python estimator is not yet the C's on these (BUG-0033): on PSW +# ARMA(1,1) it stops 0.22 lower, on the twostep case 0.0016 higher, on the +# boundary its BFGS standard errors are another path's, and on c5 it reaches +# the same logL at other estimates (a flat direction). +BUG_0033 = {"c2_ipc_arma21", "c3_psw_arma11", "c5_eu_diag", "c7_ipc_twostep"} + + +@pytest.mark.parametrize("case", REC["cases"], ids=[c["name"] for c in REC["cases"]]) +def test_the_pure_python_estimator_gives_the_cs_numbers(case, tmp_path): + if case["name"] in BUG_0033: + pytest.xfail("BUG-0033: the pure-Python .inp path is not yet the C's here") + logl, se, rows = _run(case, tmp_path, no_engine=True) + assert logl == pytest.approx(case["logL"], abs=1e-5) + assert se == case["se_method"] + got, want = _numbers(rows), _numbers(case["table"]) + assert got.keys() == want.keys() + for k in want: + assert got[k][0] == pytest.approx(want[k][0], abs=2e-6), k + # fdhess by finite differences in Python and in C: the last digits + assert got[k][1] == pytest.approx(want[k][1], rel=5e-4), k