@numero-uno-jpn/rstats 1.19.0 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.ja.md +6 -6
  3. package/README.md +6 -6
  4. package/dist/causal.js +2 -2
  5. package/dist/chunks/chunk-33ODAPMR.js +2 -0
  6. package/dist/chunks/chunk-3ST6RZXG.js +2 -0
  7. package/dist/chunks/{chunk-FAKOND5W.js → chunk-4EQN74JN.js} +2 -2
  8. package/dist/chunks/chunk-5RRFO4NU.js +2 -0
  9. package/dist/chunks/{chunk-ILQ4VWSD.js → chunk-64DDDGJU.js} +2 -2
  10. package/dist/chunks/chunk-66TEOHPF.js +2 -0
  11. package/dist/chunks/chunk-6ISDROPG.js +2 -0
  12. package/dist/chunks/{chunk-OTETSONJ.js → chunk-6LAKI2QG.js} +2 -2
  13. package/dist/chunks/{chunk-SJJJ7Y4X.js → chunk-6QCH4LAL.js} +2 -2
  14. package/dist/chunks/{chunk-FCGTZ6BD.js → chunk-6RA73LXX.js} +2 -2
  15. package/dist/chunks/{chunk-MPBFXHXT.js → chunk-7C2ECGT6.js} +1 -1
  16. package/dist/chunks/{chunk-QH4GK3JN.js → chunk-7KPFNJBE.js} +2 -2
  17. package/dist/chunks/chunk-ARPXG2PG.js +2 -0
  18. package/dist/chunks/chunk-AWXW4WSX.js +2 -0
  19. package/dist/chunks/{chunk-WWRKCRTZ.js → chunk-B5GSH3AK.js} +1 -1
  20. package/dist/chunks/{chunk-XHHDBEHB.js → chunk-BLDLJHUG.js} +2 -2
  21. package/dist/chunks/{chunk-ANFN3X2M.js → chunk-BU4I544S.js} +2 -2
  22. package/dist/chunks/{chunk-LWFKGF43.js → chunk-CAUNJ7S6.js} +2 -2
  23. package/dist/chunks/chunk-DFGW4QWU.js +2 -0
  24. package/dist/chunks/{chunk-MOYWWJP4.js → chunk-DPCCSFCG.js} +1 -1
  25. package/dist/chunks/chunk-EXS5QD7V.js +2 -0
  26. package/dist/chunks/chunk-FOCHNNP3.js +2 -0
  27. package/dist/chunks/{chunk-VNLSP22M.js → chunk-HEPGGURG.js} +2 -2
  28. package/dist/chunks/chunk-INNFAVT3.js +2 -0
  29. package/dist/chunks/chunk-JEELIABM.js +2 -0
  30. package/dist/chunks/chunk-KNF2GPJV.js +2 -0
  31. package/dist/chunks/chunk-L4ZS7MAX.js +2 -0
  32. package/dist/chunks/{chunk-7D7FBLWD.js → chunk-LZAB4M7P.js} +2 -2
  33. package/dist/chunks/chunk-LZTDYQRS.js +3 -0
  34. package/dist/chunks/{chunk-AS2XTRHH.js → chunk-MTSU2QHB.js} +2 -2
  35. package/dist/chunks/{chunk-5NW4WT4F.js → chunk-MXRN2G7O.js} +2 -2
  36. package/dist/chunks/chunk-OFDD4GTZ.js +2 -0
  37. package/dist/chunks/chunk-OOHFFLMY.js +2 -0
  38. package/dist/chunks/chunk-OOO5AAM7.js +2 -0
  39. package/dist/chunks/chunk-PJJJR3H6.js +2 -0
  40. package/dist/chunks/chunk-PVRNAOO7.js +2 -0
  41. package/dist/chunks/chunk-Q2JLU5YD.js +2 -0
  42. package/dist/chunks/{chunk-SAFH76DR.js → chunk-QCQBK5AC.js} +2 -2
  43. package/dist/chunks/chunk-RXK4KSKH.js +2 -0
  44. package/dist/chunks/chunk-UC3YYJHM.js +4 -0
  45. package/dist/chunks/chunk-UPACHZ4F.js +2 -0
  46. package/dist/chunks/{chunk-DXSVV47D.js → chunk-VCXPGCA4.js} +2 -2
  47. package/dist/chunks/chunk-VFL4GGYT.js +2 -0
  48. package/dist/chunks/chunk-VL72MQOQ.js +2 -0
  49. package/dist/chunks/chunk-VSV5QGXX.js +2 -0
  50. package/dist/chunks/{chunk-U6RXYALO.js → chunk-WMEF5XWO.js} +2 -2
  51. package/dist/chunks/chunk-X6JS6ZZB.js +2 -0
  52. package/dist/chunks/chunk-YEDVOX5V.js +2 -0
  53. package/dist/chunks/chunk-ZCTB4N5J.js +3 -0
  54. package/dist/descriptive.js +2 -2
  55. package/dist/distributions.js +2 -2
  56. package/dist/entries/tests.d.ts +5 -0
  57. package/dist/entries/tests.js +5 -0
  58. package/dist/entries/timeseries.d.ts +11 -0
  59. package/dist/entries/timeseries.js +11 -0
  60. package/dist/linalg.js +2 -2
  61. package/dist/meta/metabin.d.ts +32 -0
  62. package/dist/meta/metabin.js +137 -0
  63. package/dist/meta/metaextra.d.ts +153 -0
  64. package/dist/meta/metaextra.js +290 -0
  65. package/dist/meta/metagen.d.ts +124 -0
  66. package/dist/meta/metagen.js +263 -0
  67. package/dist/meta/metaother.d.ts +87 -0
  68. package/dist/meta/metaother.js +342 -0
  69. package/dist/meta/netmeta.d.ts +256 -0
  70. package/dist/meta/netmeta.js +547 -0
  71. package/dist/mixed.js +3 -4
  72. package/dist/models/glmFamily.js +4 -1
  73. package/dist/models/metaAnalysis.d.ts +4 -0
  74. package/dist/models/metaAnalysis.js +100 -18
  75. package/dist/multivariate.js +2 -2
  76. package/dist/numerics.js +2 -2
  77. package/dist/regression.js +2 -2
  78. package/dist/rstats.js +20 -18
  79. package/dist/special.js +2 -2
  80. package/dist/tests.js +15 -15
  81. package/dist/timeseries/acf.js +5 -2
  82. package/dist/timeseries/arima.d.ts +154 -0
  83. package/dist/timeseries/arima.js +1007 -0
  84. package/dist/timeseries/autoArima.d.ts +70 -0
  85. package/dist/timeseries/autoArima.js +191 -0
  86. package/dist/timeseries/ets.d.ts +158 -0
  87. package/dist/timeseries/ets.js +883 -0
  88. package/dist/timeseries/forecastArima.d.ts +136 -0
  89. package/dist/timeseries/forecastArima.js +432 -0
  90. package/dist/timeseries/forecastDispatch.d.ts +83 -0
  91. package/dist/timeseries/forecastDispatch.js +130 -0
  92. package/dist/timeseries/forecastSimple.d.ts +177 -0
  93. package/dist/timeseries/forecastSimple.js +371 -0
  94. package/dist/timeseries/forecastUtils.d.ts +260 -0
  95. package/dist/timeseries/forecastUtils.js +619 -0
  96. package/dist/timeseries/holtWinters.d.ts +65 -0
  97. package/dist/timeseries/holtWinters.js +193 -0
  98. package/dist/timeseries/input.d.ts +8 -0
  99. package/dist/timeseries/input.js +27 -0
  100. package/dist/timeseries/ocsbCritical.d.ts +2 -0
  101. package/dist/timeseries/ocsbCritical.js +6 -0
  102. package/dist/timeseries/scale.d.ts +16 -0
  103. package/dist/timeseries/scale.js +48 -0
  104. package/dist/timeseries/statsTs.d.ts +128 -0
  105. package/dist/timeseries/statsTs.js +456 -0
  106. package/dist/timeseries/stl.d.ts +131 -0
  107. package/dist/timeseries/stl.js +489 -0
  108. package/dist/timeseries/tseries.d.ts +110 -0
  109. package/dist/timeseries/tseries.js +369 -0
  110. package/dist/timeseries.js +2 -2
  111. package/package.json +1 -1
  112. package/dist/chunks/chunk-2S45NNTL.js +0 -2
  113. package/dist/chunks/chunk-4JFGT4PN.js +0 -2
  114. package/dist/chunks/chunk-4JRJU5F5.js +0 -2
  115. package/dist/chunks/chunk-6ZGEYAFC.js +0 -2
  116. package/dist/chunks/chunk-BJ5WAL2C.js +0 -2
  117. package/dist/chunks/chunk-CEOSH3H2.js +0 -2
  118. package/dist/chunks/chunk-CMNKXRZF.js +0 -3
  119. package/dist/chunks/chunk-CNJLPH6W.js +0 -2
  120. package/dist/chunks/chunk-FELX2TZZ.js +0 -2
  121. package/dist/chunks/chunk-G4B2SQR6.js +0 -4
  122. package/dist/chunks/chunk-HPIZAWMT.js +0 -2
  123. package/dist/chunks/chunk-I5XUWUEV.js +0 -2
  124. package/dist/chunks/chunk-JLFRYDYO.js +0 -2
  125. package/dist/chunks/chunk-JXKHFSGK.js +0 -2
  126. package/dist/chunks/chunk-LBU73UMS.js +0 -2
  127. package/dist/chunks/chunk-LSZTDKIB.js +0 -2
  128. package/dist/chunks/chunk-M5J3DHXB.js +0 -2
  129. package/dist/chunks/chunk-NWNJEAKI.js +0 -2
  130. package/dist/chunks/chunk-QVE7V5UG.js +0 -2
  131. package/dist/chunks/chunk-RMGEIU4Z.js +0 -2
  132. package/dist/chunks/chunk-TVU4N6BA.js +0 -2
  133. package/dist/chunks/chunk-W4EITKLJ.js +0 -2
  134. package/dist/chunks/chunk-XJMBX6A2.js +0 -2
  135. package/dist/chunks/chunk-YZ6SBFFG.js +0 -2
@@ -0,0 +1,1007 @@
1
+ // ARIMA models fitted by exact maximum likelihood or conditional sum of squares, and their forecasts: R's
2
+ // stats::arima and predict.Arima. Written for rStats.js from the behaviour specification oracle/tsmeta-behaviour.md
3
+ // (sections "stats' arima") and the textbooks R's help page cites (Brockwell and Davis 1996; Durbin and Koopman
4
+ // 2001; Gardner, Harvey and Phillips 1980; Jones 1980), with the details found in experiments/tsmeta120-log.md
5
+ // (items 1-4). No R source was read.
6
+ //
7
+ // The exact likelihood is computed by a Kalman filter on the state space form
8
+ // state alpha_t = (ARMA state of dimension r = max(p, q + 1); y_{t-1}, ..., y_{t-nd})
9
+ // y_t = alpha_t[0] + sum_k delta_k y_{t-k} (delta from (1 - B)^d (1 - B^s)^D)
10
+ // with the stationary ARMA covariance as the initial covariance of the ARMA block and kappa I (kappa = 1e6) for the
11
+ // presample values (R's finite diffuse prior; log 2-4). Observations whose prediction variance is at least 1e4 (still
12
+ // controlled by that prior) are left out of the likelihood. The innovations variance is concentrated out.
13
+ import { optim, optimHess } from "../optim/optim.js";
14
+ import { eigen } from "../linalg/eigen.js";
15
+ import { powerOfTwoScale } from "./scale.js";
16
+ import { tsInput } from "./input.js";
17
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
18
+ import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
19
+ const ARIMA_KEYS = /* @__PURE__ */ new Set([
20
+ "order", "seasonal", "frequency", "xreg", "xregNames", "includeMean", "transformPars", "fixed", "init", "method",
21
+ "nCond", "kappa", "hessian",
22
+ ]);
23
+ const ARIMA_SEASONAL_KEYS = ["order", "period"];
24
+ const PREDICT_ARIMA_KEYS = ["newxreg", "sigma2"];
25
+ // ---------------------------------------------------------------------------------------------------------------
26
+ // polynomials and parameter maps
27
+ function polyMul(a, b) {
28
+ const r = new Array(a.length + b.length - 1).fill(0);
29
+ for (let i = 0; i < a.length; i++)
30
+ for (let j = 0; j < b.length; j++)
31
+ r[i + j] += a[i] * b[j];
32
+ return r;
33
+ }
34
+ /** The full AR and MA coefficients (lags 1..) from the non-seasonal and seasonal ones. */
35
+ export function expandArma(ar, ma, sar, sma, s) {
36
+ const seasonalPoly = (c, sign) => {
37
+ const p = new Array(s * c.length + 1).fill(0);
38
+ p[0] = 1;
39
+ for (let i = 0; i < c.length; i++)
40
+ p[s * (i + 1)] = sign * c[i];
41
+ return p;
42
+ };
43
+ const arPoly = polyMul([1, ...ar.map((v) => -v)], sar.length ? seasonalPoly(sar, -1) : [1]);
44
+ const maPoly = polyMul([1, ...ma], sma.length ? seasonalPoly(sma, 1) : [1]);
45
+ return { phi: arPoly.slice(1).map((v) => -v), theta: maPoly.slice(1) };
46
+ }
47
+ /** (1 - B)^d (1 - B^s)^D as coefficients of lags 1.. (y_t = sum delta_k y_{t-k} + w_t). */
48
+ function differencingDelta(d, D, s) {
49
+ let p = [1];
50
+ for (let i = 0; i < d; i++)
51
+ p = polyMul(p, [1, -1]);
52
+ for (let i = 0; i < D; i++) {
53
+ const q = new Array(s + 1).fill(0);
54
+ q[0] = 1;
55
+ q[s] = -1;
56
+ p = polyMul(p, q);
57
+ }
58
+ return p.slice(1).map((v) => -v);
59
+ }
60
+ /** AR coefficients from partial autocorrelations (Durbin-Levinson). */
61
+ function pacfToAr(r) {
62
+ let a = [];
63
+ for (const rk of r) {
64
+ const prev = a.slice();
65
+ a = prev.map((v, i) => v - rk * prev[prev.length - 1 - i]);
66
+ a.push(rk);
67
+ }
68
+ return a;
69
+ }
70
+ /** Partial autocorrelations from AR coefficients (the inverse recursion); NaN when not stationary. */
71
+ function arToPacf(aIn) {
72
+ let a = aIn.slice();
73
+ const p = a.length;
74
+ const r = new Array(p).fill(0);
75
+ for (let k = p; k >= 1; k--) {
76
+ const rk = a[k - 1];
77
+ r[k - 1] = rk;
78
+ if (Math.abs(rk) >= 1)
79
+ return r.map(() => NaN);
80
+ if (k > 1) {
81
+ const denom = 1 - rk * rk;
82
+ const prev = a.slice(0, k - 1);
83
+ a = prev.map((v, i) => (v + rk * prev[k - 2 - i]) / denom);
84
+ }
85
+ }
86
+ return r;
87
+ }
88
+ /**
89
+ * The roots' smallest modulus of 1 + c_1 z + ... + c_k z^k (Infinity for a constant). Not an R function.
90
+ *
91
+ * @category Time series
92
+ */
93
+ export function minRootModulus(c) {
94
+ let k = c.length;
95
+ while (k > 0 && c[k - 1] === 0)
96
+ k--;
97
+ if (k === 0)
98
+ return Infinity;
99
+ // companion matrix of z^k + (c_{k-1}/c_k) z^{k-1} + ... + 1/c_k
100
+ const lead = c[k - 1];
101
+ const M = [];
102
+ for (let i = 0; i < k; i++) {
103
+ const row = new Array(k).fill(0);
104
+ if (i > 0)
105
+ row[i - 1] = 1;
106
+ M.push(row);
107
+ }
108
+ const coef = [1, ...c.slice(0, k - 1)];
109
+ for (let i = 0; i < k; i++)
110
+ M[i][k - 1] = -coef[i] / lead;
111
+ const e = eigen(M, { onlyValues: true });
112
+ let m = Infinity;
113
+ for (let i = 0; i < k; i++)
114
+ m = Math.min(m, Math.hypot(e.values[i], e.valuesIm?.[i] ?? 0));
115
+ return m;
116
+ }
117
+ /** The MA polynomial made invertible by reflecting roots inside the unit circle (R's "converted to invertible"). */
118
+ function maInvert(ma) {
119
+ let q = ma.length;
120
+ while (q > 0 && ma[q - 1] === 0)
121
+ q--;
122
+ if (q === 0)
123
+ return ma.slice();
124
+ const lead = ma[q - 1];
125
+ const M = [];
126
+ for (let i = 0; i < q; i++) {
127
+ const row = new Array(q).fill(0);
128
+ if (i > 0)
129
+ row[i - 1] = 1;
130
+ M.push(row);
131
+ }
132
+ const coef = [1, ...ma.slice(0, q - 1)];
133
+ for (let i = 0; i < q; i++)
134
+ M[i][q - 1] = -coef[i] / lead;
135
+ const e = eigen(M, { onlyValues: true });
136
+ const re = e.values.slice(0, q), im = (e.valuesIm ?? new Array(q).fill(0)).slice(0, q);
137
+ let changed = false;
138
+ for (let i = 0; i < q; i++) {
139
+ const m2 = re[i] ** 2 + im[i] ** 2;
140
+ if (m2 < 1) {
141
+ re[i] = re[i] / m2;
142
+ im[i] = -im[i] / m2;
143
+ changed = true;
144
+ }
145
+ }
146
+ if (!changed)
147
+ return ma.slice();
148
+ // rebuild prod (1 - z / root_i) with complex arithmetic
149
+ let pr = [1], pi = [0];
150
+ for (let i = 0; i < q; i++) {
151
+ const m2 = re[i] ** 2 + im[i] ** 2;
152
+ const ir = re[i] / m2, ii = -im[i] / m2; // 1 / root
153
+ const nr = new Array(pr.length + 1).fill(0), nim = new Array(pr.length + 1).fill(0);
154
+ for (let j = 0; j < pr.length; j++) {
155
+ nr[j] += pr[j];
156
+ nim[j] += pi[j];
157
+ nr[j + 1] -= pr[j] * ir - pi[j] * ii;
158
+ nim[j + 1] -= pr[j] * ii + pi[j] * ir;
159
+ }
160
+ pr = nr;
161
+ pi = nim;
162
+ }
163
+ const out = pr.slice(1);
164
+ return [...out, ...ma.slice(q)];
165
+ }
166
+ // ---------------------------------------------------------------------------------------------------------------
167
+ // the Kalman filter
168
+ /** Stationary covariance of the ARMA state (Harvey form) per unit innovations variance, by the doubling algorithm. */
169
+ function positiveDefinite(H) {
170
+ const k = H.length;
171
+ const L = H.map((r) => r.slice());
172
+ for (let j = 0; j < k; j++) {
173
+ let d = L[j][j];
174
+ for (let m = 0; m < j; m++)
175
+ d -= L[j][m] ** 2;
176
+ if (!(d > 0))
177
+ return false;
178
+ const ljj = Math.sqrt(d);
179
+ L[j][j] = ljj;
180
+ for (let i = j + 1; i < k; i++) {
181
+ let v = L[i][j];
182
+ for (let m = 0; m < j; m++)
183
+ v -= L[i][m] * L[j][m];
184
+ L[i][j] = v / ljj;
185
+ }
186
+ }
187
+ return true;
188
+ }
189
+ /**
190
+ * P0 of a stationary ARMA from its autocovariances, in O(r^2) after a (p + 1)-square solve (1.20.0, log 112: the
191
+ * doubling below ran at every likelihood evaluation and dominated autoArima's seasonal searches, 7 s of 12 for 48
192
+ * values). The state x_{i,t} = phi_i y_{t-1} + theta_{i-1} e_t + x_{i+1,t-1} gives
193
+ * P[i][j] = phi_i phi_j gamma(0) + theta_{i-1} theta_{j-1} + phi_i C[j+1] + phi_j C[i+1] + P[i+1][j+1],
194
+ * C[m] = Cov(y_t, x_{m,t}) = sum_{k >= m} (phi_k gamma(k - m + 1) + theta_{k-1} psi_{k-m}),
195
+ * with gamma(0..p) from gamma(h) - sum_k phi_k gamma(h - k) = sum_{j >= h} theta_j psi_{j-h} (theta_0 = 1, sigma2 = 1).
196
+ * Equal to the doubling to 1e-15 (also with roots of modulus 0.99). Undefined (null) where the solve fails or the
197
+ * variances are not positive: a non-stationary AR part, for which the doubling's partial sums are kept.
198
+ */
199
+ function stationaryCovarianceClosed(phi, theta, r) {
200
+ const p = phi.length, q = theta.length;
201
+ const ph = (k) => (k >= 1 && k <= p ? phi[k - 1] : 0);
202
+ const th = (k) => (k === 0 ? 1 : k >= 1 && k <= q ? theta[k - 1] : 0);
203
+ const H = r + 1;
204
+ const psi = new Float64Array(H + 1);
205
+ for (let j = 0; j <= H; j++) {
206
+ let v = th(j);
207
+ for (let k = 1; k <= Math.min(j, p); k++)
208
+ v += ph(k) * psi[j - k];
209
+ psi[j] = v;
210
+ }
211
+ const rhs = (h) => { let s0 = 0; for (let j = h; j <= q; j++)
212
+ s0 += th(j) * psi[j - h]; return s0; };
213
+ const gam = new Float64Array(H + 1);
214
+ if (p > 0) {
215
+ // (p + 1)-square system by Gaussian elimination with partial pivoting
216
+ const n = p + 1;
217
+ const M = Array.from({ length: n }, () => new Float64Array(n + 1));
218
+ for (let h = 0; h <= p; h++) {
219
+ M[h][h] += 1;
220
+ for (let k = 1; k <= p; k++)
221
+ M[h][Math.abs(h - k)] -= ph(k);
222
+ M[h][n] = rhs(h);
223
+ }
224
+ for (let c = 0; c < n; c++) {
225
+ let piv = c;
226
+ for (let i = c + 1; i < n; i++)
227
+ if (Math.abs(M[i][c]) > Math.abs(M[piv][c]))
228
+ piv = i;
229
+ if (!(Math.abs(M[piv][c]) > 0))
230
+ return null;
231
+ if (piv !== c) {
232
+ const t = M[c];
233
+ M[c] = M[piv];
234
+ M[piv] = t;
235
+ }
236
+ const mc = M[c];
237
+ for (let i = c + 1; i < n; i++) {
238
+ const mi = M[i];
239
+ const f = mi[c] / mc[c];
240
+ if (f === 0)
241
+ continue;
242
+ for (let j = c; j <= n; j++)
243
+ mi[j] -= f * mc[j];
244
+ }
245
+ }
246
+ for (let i = n - 1; i >= 0; i--) {
247
+ const mi = M[i];
248
+ let v = mi[n];
249
+ for (let j = i + 1; j < n; j++)
250
+ v -= mi[j] * gam[j];
251
+ gam[i] = v / mi[i];
252
+ }
253
+ }
254
+ else
255
+ gam[0] = rhs(0);
256
+ for (let h = p + 1; h <= H; h++) {
257
+ let v = rhs(h);
258
+ for (let k = 1; k <= p; k++)
259
+ v += ph(k) * gam[h - k];
260
+ gam[h] = v;
261
+ }
262
+ const C = new Float64Array(r + 2);
263
+ for (let m = 1; m <= r; m++) {
264
+ let v = 0;
265
+ for (let k = m; k <= r; k++)
266
+ v += ph(k) * gam[k - m + 1] + th(k - 1) * psi[k - m];
267
+ C[m] = v;
268
+ }
269
+ const P = Array.from({ length: r }, () => new Array(r).fill(0));
270
+ for (let i = r; i >= 1; i--)
271
+ for (let j = r; j >= 1; j--) {
272
+ P[i - 1][j - 1] = ph(i) * ph(j) * gam[0] + th(i - 1) * th(j - 1) + ph(i) * C[j + 1] + ph(j) * C[i + 1] + (i < r && j < r ? P[i][j] : 0);
273
+ }
274
+ for (let i = 0; i < r; i++)
275
+ if (!(P[i][i] > 0) || !Number.isFinite(P[i][i]))
276
+ return null;
277
+ return P;
278
+ }
279
+ export function stationaryCovariance(phi, theta, r) {
280
+ const closed = stationaryCovarianceClosed(phi, theta, r);
281
+ if (closed)
282
+ return closed;
283
+ return stationaryCovarianceDoubling(phi, theta, r);
284
+ }
285
+ function stationaryCovarianceDoubling(phi, theta, r) {
286
+ // S = sum_k T^k R R' T'^k by doubling: S <- S + A S A', A <- A^2 (flat arrays: this runs at every likelihood
287
+ // evaluation and dominated the seasonal fits)
288
+ const S = new Float64Array(r * r);
289
+ const R = new Float64Array(r);
290
+ R[0] = 1;
291
+ for (let i = 1; i < r; i++)
292
+ R[i] = theta[i - 1] ?? 0;
293
+ for (let i = 0; i < r; i++)
294
+ for (let j = 0; j < r; j++)
295
+ S[i * r + j] = R[i] * R[j];
296
+ let A = new Float64Array(r * r);
297
+ for (let i = 0; i < r; i++) {
298
+ A[i * r] = phi[i] ?? 0;
299
+ if (i + 1 < r)
300
+ A[i * r + i + 1] = 1;
301
+ }
302
+ let AS = new Float64Array(r * r), A2 = new Float64Array(r * r);
303
+ for (let it = 0; it < 200; it++) {
304
+ AS.fill(0);
305
+ for (let i = 0; i < r; i++)
306
+ for (let k = 0; k < r; k++) {
307
+ const aik = A[i * r + k];
308
+ if (aik === 0)
309
+ continue;
310
+ for (let j = 0; j < r; j++)
311
+ AS[i * r + j] += aik * S[k * r + j];
312
+ }
313
+ let maxAdd = 0, maxS = 0;
314
+ for (let i = 0; i < r; i++)
315
+ for (let j = 0; j < r; j++) {
316
+ let v = 0;
317
+ for (let k = 0; k < r; k++)
318
+ v += AS[i * r + k] * A[j * r + k];
319
+ const w = S[i * r + j] + v;
320
+ S[i * r + j] = w;
321
+ const av = Math.abs(v);
322
+ if (av > maxAdd)
323
+ maxAdd = av;
324
+ const aw = Math.abs(w);
325
+ if (aw > maxS)
326
+ maxS = aw;
327
+ }
328
+ A2.fill(0);
329
+ for (let i = 0; i < r; i++)
330
+ for (let k = 0; k < r; k++) {
331
+ const aik = A[i * r + k];
332
+ if (aik === 0)
333
+ continue;
334
+ for (let j = 0; j < r; j++)
335
+ A2[i * r + j] += aik * A[k * r + j];
336
+ }
337
+ const t = A;
338
+ A = A2;
339
+ A2 = t;
340
+ if (maxAdd <= 1e-17 * maxS)
341
+ break;
342
+ }
343
+ void AS;
344
+ const out = [];
345
+ for (let i = 0; i < r; i++) {
346
+ const row = new Array(r);
347
+ for (let j = 0; j < r; j++)
348
+ row[j] = (S[i * r + j] + S[j * r + i]) / 2;
349
+ out.push(row);
350
+ }
351
+ return out;
352
+ }
353
+ /** Kalman filter of y (NaN missing) for the model; prediction variances in units of sigma2. */
354
+ function kalman(y, phi, theta, delta, kappa, light = false) {
355
+ const p = phi.length, q = theta.length;
356
+ const r = Math.max(p, q + 1);
357
+ const nd = delta.length;
358
+ const rd = r + nd;
359
+ const P0 = stationaryCovariance(phi, theta, r);
360
+ const ph = new Float64Array(r);
361
+ for (let i = 0; i < p; i++)
362
+ ph[i] = phi[i];
363
+ const dl = Float64Array.from(delta);
364
+ let a = new Float64Array(rd);
365
+ let P = new Float64Array(rd * rd);
366
+ for (let i = 0; i < rd; i++)
367
+ for (let j = 0; j < rd; j++)
368
+ P[i * rd + j] = i < r && j < r ? P0[i][j] : i === j ? kappa : 0;
369
+ const Rv = new Float64Array(r);
370
+ Rv[0] = 1;
371
+ for (let i = 1; i < r; i++)
372
+ Rv[i] = theta[i - 1] ?? 0;
373
+ // light (the objective's evaluations): without the residuals and the final state, whose arrays took much of the time
374
+ const n = y.length;
375
+ const resid = light ? [] : new Array(n).fill(NaN);
376
+ let ssq = 0, sumlog = 0, nu = 0;
377
+ // (T x)_i = phi_i x_0 + x_{i+1} (i < r); (T x)_r = x_0 + sum_k delta_k x_{r+k}; (T x)_{r+k} = x_{r+k-1}
378
+ // applied to the vector x[off + stride * k], k = 0..rd-1, written to out[oo + ostride * i]
379
+ const applyT = (x, off, stride, out, oo, ostride) => {
380
+ const x0 = x[off];
381
+ for (let i = 0; i < r; i++)
382
+ out[oo + ostride * i] = ph[i] * x0 + (i + 1 < r ? x[off + stride * (i + 1)] : 0);
383
+ if (nd > 0) {
384
+ let z = x0;
385
+ for (let k = 0; k < nd; k++)
386
+ z += dl[k] * x[off + stride * (r + k)];
387
+ out[oo + ostride * r] = z;
388
+ for (let k = 1; k < nd; k++)
389
+ out[oo + ostride * (r + k)] = x[off + stride * (r + k - 1)];
390
+ }
391
+ };
392
+ const M = new Float64Array(rd * rd);
393
+ let a2 = new Float64Array(rd);
394
+ const PZ = new Float64Array(rd);
395
+ let Pn = new Float64Array(rd * rd);
396
+ for (let t = 0; t < n; t++) {
397
+ if (t > 0) {
398
+ applyT(a, 0, 1, a2, 0, 1);
399
+ {
400
+ const tmp = a;
401
+ a = a2;
402
+ a2 = tmp;
403
+ }
404
+ // M = T P (T on each column of P), then P = T M' (T on each row of M) = T P T'; plus R R' on the ARMA block.
405
+ // Written row by row over contiguous memory with the buffers reused (1.20.0, log 112: the same operations in the
406
+ // same order as applyT on each column, so the same bits; the Kalman filter dominated autoArima's seasonal
407
+ // searches): (T x)_i = phi_i x_0 + x_{i+1}, (T x)_r = x_0 + sum_k delta_k x_{r+k}, (T x)_{r+k} = x_{r+k-1}
408
+ for (let i = 0; i < r; i++) {
409
+ const pi = ph[i];
410
+ const o = i * rd;
411
+ if (i + 1 < r) {
412
+ const o1 = o + rd;
413
+ for (let j = 0; j < rd; j++)
414
+ M[o + j] = pi * P[j] + P[o1 + j];
415
+ }
416
+ else
417
+ for (let j = 0; j < rd; j++)
418
+ M[o + j] = pi * P[j] + 0;
419
+ }
420
+ if (nd > 0) {
421
+ const o = r * rd;
422
+ for (let j = 0; j < rd; j++) {
423
+ let z = P[j];
424
+ for (let k = 0; k < nd; k++)
425
+ z += dl[k] * P[(r + k) * rd + j];
426
+ M[o + j] = z;
427
+ }
428
+ for (let k = 1; k < nd; k++) {
429
+ const o2 = (r + k) * rd, o3 = (r + k - 1) * rd;
430
+ for (let j = 0; j < rd; j++)
431
+ M[o2 + j] = P[o3 + j];
432
+ }
433
+ }
434
+ // Pn = (T applied to each row of M) transposed into the columns: Pn[j][i] = (T M_i)_j
435
+ for (let i = 0; i < rd; i++) {
436
+ const o = i * rd;
437
+ const x0 = M[o];
438
+ for (let j = 0; j < r; j++)
439
+ Pn[j * rd + i] = ph[j] * x0 + (j + 1 < r ? M[o + j + 1] : 0);
440
+ if (nd > 0) {
441
+ let z = x0;
442
+ for (let k = 0; k < nd; k++)
443
+ z += dl[k] * M[o + r + k];
444
+ Pn[r * rd + i] = z;
445
+ for (let k = 1; k < nd; k++)
446
+ Pn[(r + k) * rd + i] = M[o + r + k - 1];
447
+ }
448
+ }
449
+ for (let i = 0; i < r; i++)
450
+ for (let j = 0; j < r; j++)
451
+ Pn[i * rd + j] += Rv[i] * Rv[j];
452
+ for (let i = 0; i < rd; i++)
453
+ for (let j = i + 1; j < rd; j++) {
454
+ const m = (Pn[i * rd + j] + Pn[j * rd + i]) / 2;
455
+ Pn[i * rd + j] = m;
456
+ Pn[j * rd + i] = m;
457
+ }
458
+ {
459
+ const tmp = P;
460
+ P = Pn;
461
+ Pn = tmp;
462
+ }
463
+ }
464
+ const yt = y[t];
465
+ if (Number.isNaN(yt))
466
+ continue;
467
+ // Z = (1, 0, ..., 0, delta_1, ..., delta_nd)
468
+ let fc = a[0];
469
+ for (let k = 0; k < nd; k++)
470
+ fc += dl[k] * a[r + k];
471
+ for (let i = 0; i < rd; i++) {
472
+ let v = P[i * rd];
473
+ for (let k = 0; k < nd; k++)
474
+ v += P[i * rd + r + k] * dl[k];
475
+ PZ[i] = v;
476
+ }
477
+ let F = PZ[0];
478
+ for (let k = 0; k < nd; k++)
479
+ F += PZ[r + k] * dl[k];
480
+ const v = yt - fc;
481
+ if (!light)
482
+ resid[t] = v / Math.sqrt(F);
483
+ if (F < 1e4) {
484
+ ssq += (v * v) / F;
485
+ sumlog += Math.log(F);
486
+ nu++;
487
+ }
488
+ for (let k = 0; k < rd; k++)
489
+ a[k] += (PZ[k] * v) / F;
490
+ for (let i = 0; i < rd; i++) {
491
+ const pi = PZ[i] / F;
492
+ for (let j = 0; j < rd; j++)
493
+ P[i * rd + j] -= pi * PZ[j];
494
+ }
495
+ }
496
+ void M;
497
+ if (light)
498
+ return { ssq, sumlog, nu, resid, a: [], P: [] };
499
+ const Pout = [];
500
+ for (let i = 0; i < rd; i++)
501
+ Pout.push(Array.from(P.subarray(i * rd, (i + 1) * rd)));
502
+ return { ssq, sumlog, nu, resid, a: Array.from(a), P: Pout };
503
+ }
504
+ /** CSS residuals of the differenced series w (mean / regression already removed before differencing). */
505
+ function cssResiduals(x, phi, theta, delta, nCond) {
506
+ const n = x.length;
507
+ const nd = delta.length;
508
+ const w = new Array(n).fill(NaN);
509
+ for (let t = 0; t < n; t++) {
510
+ if (t < nd)
511
+ continue;
512
+ let v = x[t];
513
+ for (let k = 0; k < nd; k++)
514
+ v -= delta[k] * x[t - k - 1];
515
+ w[t] = v;
516
+ }
517
+ const e = new Array(n).fill(0);
518
+ let ssq = 0, nu = 0;
519
+ for (let t = nCond; t < n; t++) {
520
+ let v = w[t];
521
+ for (let i = 0; i < phi.length; i++)
522
+ v -= phi[i] * (t - i - 1 >= 0 ? w[t - i - 1] : 0);
523
+ for (let j = 0; j < theta.length; j++)
524
+ v -= theta[j] * (t - j - 1 >= 0 ? e[t - j - 1] : 0);
525
+ e[t] = v;
526
+ if (!Number.isNaN(v)) {
527
+ ssq += v * v;
528
+ nu++;
529
+ }
530
+ else
531
+ e[t] = 0;
532
+ }
533
+ const resid = e.map((v, t) => (t < nCond ? 0 : Number.isNaN(w[t]) ? NaN : v));
534
+ return { ssq, nu, resid };
535
+ }
536
+ // ---------------------------------------------------------------------------------------------------------------
537
+ // the fit
538
+ function normalizeSeasonal(opt) {
539
+ const seas = opt.seasonal;
540
+ const order = Array.isArray(seas) ? seas : (seas?.order ?? [0, 0, 0]);
541
+ const period = (!Array.isArray(seas) && seas?.period) || opt.frequency || 1;
542
+ return { P: order[0], D: order[1], Q: order[2], s: period };
543
+ }
544
+ /**
545
+ * Fits an ARIMA model by exact maximum likelihood (Kalman filter) or conditional sum of squares. Equivalent to R's
546
+ * `arima()`. The estimates are taken to the optimum, where R's optimiser may stop slightly short.
547
+ *
548
+ * @example
549
+ * ```ts
550
+ * // R's lh (48 luteinizing hormone measurements)
551
+ * const lh = [2.4, 2.4, 2.4, 2.2, 2.1, 1.5, 2.3, 2.3, 2.5, 2.0, 1.9, 1.7, 2.2, 1.8, 3.2, 3.2, 2.7, 2.2, 2.2, 1.9, 1.9, 1.8, 2.7, 3.0,
552
+ * 2.3, 2.0, 2.0, 2.9, 2.9, 2.7, 2.7, 2.3, 2.6, 2.4, 1.8, 1.7, 1.5, 1.4, 2.1, 3.3, 3.5, 3.5, 3.1, 2.6, 2.1, 3.4, 3.0, 2.9];
553
+ * const fit = arima(lh, { order: [1, 0, 0] });
554
+ * fit.coef; // [0.5739243884, 2.413285608] (ar1, intercept; the last digits differ between platforms' math libraries)
555
+ * ```
556
+ *
557
+ * @category Time series
558
+ */
559
+ export function arima(xIn, options = {}) {
560
+ checkOptions(options, ARIMA_KEYS, "arima"); // generated: option-keys.mjs
561
+ checkOptions(nestedOptions(options, "seasonal"), ARIMA_SEASONAL_KEYS, "arima", "seasonal"); // generated: option-keys.mjs
562
+ // missing values allowed (the Kalman filter skips them); an infinite value an error (log 107)
563
+ const x = tsInput(xIn.map((v) => (v === null || v === undefined ? NaN : Number(v))), "arima", { missing: "allow" });
564
+ // far from unit scale (squares near the ends of the range: R and rStats.js failed at 1e+-300 and 2^1000, log 103),
565
+ // the fit of x / c for a power of two c (exact), mapped back (log 104). Not at ordinary scales, where the fit is
566
+ // R's: the kappa prior is absolute (the fits at 1e+-150 equal the unit-scale fit to 1e-7, as R's).
567
+ const c = powerOfTwoScale(x);
568
+ if (Math.abs(Math.log2(c)) <= 200)
569
+ return arimaFit(x, options);
570
+ const narma0 = (options.order?.[0] ?? 0) + (options.order?.[2] ?? 0) + (() => { const { P, Q } = normalizeSeasonal(options); return P + Q; })();
571
+ const regScale = (v) => v?.map((u, i) => (i >= narma0 ? u / c : u));
572
+ const fs = arimaFit(x.map((v) => v / c), { ...options,
573
+ ...(options.fixed ? { fixed: regScale(options.fixed) } : {}), ...(options.init ? { init: regScale(options.init) } : {}) });
574
+ return unscaleArima(fs, c, x);
575
+ }
576
+ const ARIMA_SCALED = new WeakMap();
577
+ /** The fit of x / c on the scale of x (the regression coefficients, the state, sigma2 and the likelihood). */
578
+ export function unscaleArima(fs, c, x) {
579
+ const narma = fs.arma[0] + fs.arma[1] + fs.arma[2] + fs.arma[3];
580
+ const free = fs.mask.map((m, i) => (m ? i : -1)).filter((i) => i >= 0).map((i) => (i >= narma ? c : 1));
581
+ const logc = Math.log(c);
582
+ const r = { ...fs, coef: fs.coef.map((v, i) => (i >= narma ? v * c : v)), sigma2: fs.sigma2 * c * c,
583
+ varCoef: fs.varCoef.map((row, i) => row.map((v, j) => v * free[i] * free[j])),
584
+ loglik: fs.loglik - fs.nobs * logc, aic: fs.aic + 2 * fs.nobs * logc, residuals: fs.residuals.map((v) => v * c),
585
+ model: { ...fs.model, a: fs.model.a.map((v) => v * c) }, x };
586
+ ARIMA_SCALED.set(r, { fit: fs, c });
587
+ return r;
588
+ }
589
+ /** Records that `r` is the fit `fs` (of the series / c) mapped back: forecasts are then made from `fs`. */
590
+ export function registerScaledArima(r, fs, c) { ARIMA_SCALED.set(r, { fit: fs, c }); }
591
+ /** The standardised fit behind `r`, when there is one. */
592
+ export function scaledArima(r) { return ARIMA_SCALED.get(r); }
593
+ function arimaFit(x, options) {
594
+ const n = x.length;
595
+ const [p, d, q] = (options.order ?? [0, 0, 0]);
596
+ const { P, D, Q, s } = normalizeSeasonal(options);
597
+ const delta = differencingDelta(d, D, s);
598
+ const xreg0 = (options.xreg ?? []).map((col) => col.map(Number));
599
+ const includeMean = (options.includeMean ?? true) && d + D === 0;
600
+ const xreg = includeMean ? [new Array(n).fill(1), ...xreg0] : xreg0;
601
+ const nreg = xreg.length;
602
+ const narma = p + q + P + Q;
603
+ const ncoef = narma + nreg;
604
+ const xregNames = options.xregNames ?? (xreg0.length === 1 ? ["xreg"] : xreg0.map((_, i) => `xreg${i + 1}`));
605
+ const coefNames = [...Array.from({ length: p }, (_, i) => `ar${i + 1}`), ...Array.from({ length: q }, (_, i) => `ma${i + 1}`),
606
+ ...Array.from({ length: P }, (_, i) => `sar${i + 1}`), ...Array.from({ length: Q }, (_, i) => `sma${i + 1}`),
607
+ ...(includeMean ? ["intercept"] : []), ...xregNames];
608
+ const fixed = options.fixed ? options.fixed.map(Number) : new Array(ncoef).fill(NaN);
609
+ if (fixed.length !== ncoef)
610
+ throw new RangeError(`wrong length for 'fixed' (${fixed.length} instead of ${ncoef})`);
611
+ const mask = fixed.map((v) => Number.isNaN(v));
612
+ let method = options.method ?? "CSS-ML";
613
+ if (method === "CSS-ML" && x.some((v) => Number.isNaN(v)))
614
+ method = "ML"; // R: ML when there are missing values
615
+ const kappa = options.kappa ?? 1e6;
616
+ let transformPars = (options.transformPars ?? true) && method !== "CSS";
617
+ if (transformPars && mask.slice(0, p).some((m) => !m) || transformPars && mask.slice(p + q, p + q + P).some((m) => !m))
618
+ transformPars = false;
619
+ const nCondCss = d + D * s + Math.max(options.nCond ?? 0, p + P * s) - (options.nCond !== undefined ? 0 : 0);
620
+ const nCond = Math.max(options.nCond ?? 0, d + D * s + p + P * s);
621
+ void nCondCss;
622
+ // regression starting values: least squares of the differenced series on the differenced regressors
623
+ const init = new Array(ncoef).fill(0);
624
+ const regScales = new Array(nreg).fill(1);
625
+ if (nreg > 0) {
626
+ const diffed = (v) => { const out = []; for (let t = delta.length; t < n; t++) {
627
+ let z = v[t];
628
+ for (let k = 0; k < delta.length; k++)
629
+ z -= delta[k] * v[t - k - 1];
630
+ out.push(z);
631
+ } return out; };
632
+ const yy = diffed(x);
633
+ const XX = xreg.map(diffed);
634
+ const ok = yy.map((v, i) => !Number.isNaN(v) && XX.every((c) => !Number.isNaN(c[i])));
635
+ const k = XX.length;
636
+ const A = Array.from({ length: k }, () => new Array(k).fill(0));
637
+ const b = new Array(k).fill(0);
638
+ for (let i = 0; i < yy.length; i++) {
639
+ if (!ok[i])
640
+ continue;
641
+ for (let a1 = 0; a1 < k; a1++) {
642
+ b[a1] += XX[a1][i] * yy[i];
643
+ for (let a2 = 0; a2 < k; a2++)
644
+ A[a1][a2] += XX[a1][i] * XX[a2][i];
645
+ }
646
+ }
647
+ const sol = solveSymmetric(A.map((r) => r.slice()), b);
648
+ for (let i = 0; i < k; i++)
649
+ init[narma + i] = Number.isFinite(sol[i]) ? sol[i] : 0;
650
+ let ssr = 0, m = 0;
651
+ for (let i = 0; i < yy.length; i++) {
652
+ if (!ok[i])
653
+ continue;
654
+ let e = yy[i];
655
+ for (let a1 = 0; a1 < k; a1++)
656
+ e -= init[narma + a1] * XX[a1][i];
657
+ ssr += e * e;
658
+ m++;
659
+ }
660
+ for (let a1 = 0; a1 < k; a1++) {
661
+ const sc = Math.sqrt(A[a1][a1] / (ssr > 0 ? ssr : m || 1));
662
+ regScales[a1] = Number.isFinite(sc) && sc > 0 ? sc : 1;
663
+ }
664
+ }
665
+ if (options.init)
666
+ options.init.forEach((v, i) => { if (!Number.isNaN(Number(v)))
667
+ init[i] = Number(v); });
668
+ for (let i = 0; i < ncoef; i++)
669
+ if (!mask[i])
670
+ init[i] = fixed[i];
671
+ const split = (cf) => ({
672
+ ar: cf.slice(0, p), ma: cf.slice(p, p + q), sar: cf.slice(p + q, p + q + P), sma: cf.slice(p + q + P, narma), reg: cf.slice(narma)
673
+ });
674
+ const residualSeries = (reg) => x.map((v, t) => { let z = v; for (let k = 0; k < nreg; k++)
675
+ z -= reg[k] * xreg[k][t]; return z; });
676
+ // transformed <-> natural parameters
677
+ const toNatural = (u) => {
678
+ if (!transformPars)
679
+ return u.slice();
680
+ const out = u.slice();
681
+ if (p > 0) {
682
+ const a = pacfToAr(u.slice(0, p).map(Math.tanh));
683
+ for (let i = 0; i < p; i++)
684
+ out[i] = a[i];
685
+ }
686
+ if (P > 0) {
687
+ const a = pacfToAr(u.slice(p + q, p + q + P).map(Math.tanh));
688
+ for (let i = 0; i < P; i++)
689
+ out[p + q + i] = a[i];
690
+ }
691
+ return out;
692
+ };
693
+ const toTransformed = (c) => {
694
+ if (!transformPars)
695
+ return c.slice();
696
+ const out = c.slice();
697
+ if (p > 0) {
698
+ const r = arToPacf(c.slice(0, p));
699
+ for (let i = 0; i < p; i++)
700
+ out[i] = Math.atanh(r[i]);
701
+ }
702
+ if (P > 0) {
703
+ const r = arToPacf(c.slice(p + q, p + q + P));
704
+ for (let i = 0; i < P; i++)
705
+ out[p + q + i] = Math.atanh(r[i]);
706
+ }
707
+ return out;
708
+ };
709
+ // the optimiser works on regression coefficients times sqrt(sum Xd^2 / SSR) (Xd the differenced regressor, SSR of the
710
+ // starting regression), so that the objective's curvature is of order 1 in every coordinate as for the ARMA terms (the
711
+ // regressors' sd instead left USAccDeaths with a trend and seasonal differencing ill-conditioned: BFGS ran to maxit)
712
+ const regScale = regScales;
713
+ const full = (free) => { const out = fixed.slice(); let j = 0; for (let i = 0; i < ncoef; i++)
714
+ if (mask[i])
715
+ out[i] = i >= narma ? free[j++] / regScale[i - narma] : free[j++]; return out; };
716
+ const freeOf = (all) => all.map((v, i) => (i >= narma ? v * regScale[i - narma] : v)).filter((_, i) => mask[i]);
717
+ const cssObjective = (cfNat) => {
718
+ const { ar, ma, sar, sma, reg } = split(cfNat);
719
+ const { phi, theta } = expandArma(ar, ma, sar, sma, s);
720
+ const r = cssResiduals(residualSeries(reg), phi, theta, delta, nCond);
721
+ return r.nu > 0 ? 0.5 * Math.log(r.ssq / r.nu) : Infinity;
722
+ };
723
+ const mlObjectiveNat = (cfNat) => {
724
+ const { ar, ma, sar, sma, reg } = split(cfNat);
725
+ const { phi, theta } = expandArma(ar, ma, sar, sma, s);
726
+ if (phi.length && minRootModulus(phi.map((v) => -v)) <= 1)
727
+ return Infinity;
728
+ const f = kalman(residualSeries(reg), phi, theta, delta, kappa, true);
729
+ return f.nu > 0 ? 0.5 * Math.log(f.ssq / f.nu) + (0.5 * f.sumlog) / f.nu : Infinity;
730
+ };
731
+ const tightBfgs = (fn, start) => {
732
+ if (start.length === 0)
733
+ return { par: [], code: 0 };
734
+ let cur = start.slice();
735
+ let code = 0;
736
+ let last = fn(cur);
737
+ // BFGS to near the optimum (a stricter reltol runs to maxit on the objective's rounding noise), then Newton below
738
+ for (let round = 0; round < 2; round++) {
739
+ const r = optim(cur, (v) => { const f = fn(v); return Number.isFinite(f) ? f : 1e300; }, { method: "BFGS", control: { reltol: 1e-12, maxit: 500 } });
740
+ code = r.convergence;
741
+ const improved = last - r.value;
742
+ cur = r.par;
743
+ last = r.value;
744
+ if (!(improved > 1e-15 * Math.max(1, Math.abs(last))))
745
+ break;
746
+ }
747
+ // BFGS with numerical gradients of step 1e-3 (as R) stops about 1e-6 short; finish with Newton steps whose gradient
748
+ // and Hessian are central differences with Richardson extrapolation
749
+ let damped = 0, slow = 0, lastGain = Infinity;
750
+ for (let it = 0; it < 30; it++) {
751
+ const g = convergedGradient(fn, cur);
752
+ const H = convergedHessian(fn, cur);
753
+ // only where the Hessian is positive definite: on a ridge or towards a boundary the steps crawl (a seasonal
754
+ // USAccDeaths model took 22 steps of 1e-7 each) and BFGS's point is kept
755
+ if (!positiveDefinite(H))
756
+ break;
757
+ const step = solveSymmetric(H.map((r) => r.slice()), g.map((v) => -v));
758
+ if (step.some((v) => !Number.isFinite(v)))
759
+ break;
760
+ let t = 1, accepted = false;
761
+ while (t > 1e-6) {
762
+ const cand = cur.map((v, i) => v + t * step[i]);
763
+ const fc = fn(cand);
764
+ if (Number.isFinite(fc) && fc <= last) {
765
+ const gain = last - fc;
766
+ cur = cand;
767
+ last = fc;
768
+ accepted = true;
769
+ if (gain <= 1e-16 * Math.max(1, Math.abs(fc)))
770
+ it = 1e9;
771
+ // not converging faster than linearly (the gain shrinking by less than 4x)
772
+ slow = gain > 0.25 * lastGain ? slow + 1 : 0;
773
+ lastGain = gain;
774
+ break;
775
+ }
776
+ t /= 2;
777
+ }
778
+ if (!accepted || Math.max(...step.map(Math.abs)) < 1e-12)
779
+ break;
780
+ // outside Newton's region: two damped steps, or two steps that did not converge faster than linearly, in a row
781
+ // (a seasonal USAccDeaths model crawled for 30 full steps of 1e-7 each)
782
+ damped = t < 1 ? damped + 1 : 0;
783
+ if (damped >= 2 || slow >= 2)
784
+ break;
785
+ }
786
+ return { par: cur, code };
787
+ };
788
+ let coefNat = init.slice();
789
+ let code = 0;
790
+ if (method === "CSS" || method === "CSS-ML") {
791
+ const res = tightBfgs((u) => cssObjective(full(u)), freeOf(coefNat));
792
+ coefNat = full(res.par);
793
+ code = res.code;
794
+ if (method === "CSS-ML") {
795
+ const { ar, sar } = split(coefNat);
796
+ if ((p > 0 && minRootModulus(ar.map((v) => -v)) <= 1) || (P > 0 && minRootModulus(sar.map((v) => -v)) <= 1))
797
+ throw new Error("non-stationary AR part from CSS");
798
+ }
799
+ }
800
+ let sigma2, loglik, resid, nobs, model;
801
+ if (method === "CSS") {
802
+ const { ar, ma, sar, sma, reg } = split(coefNat);
803
+ const { phi, theta } = expandArma(ar, ma, sar, sma, s);
804
+ const r = cssResiduals(residualSeries(reg), phi, theta, delta, nCond);
805
+ sigma2 = r.ssq / r.nu;
806
+ nobs = x.filter((v) => !Number.isNaN(v)).length - delta.length;
807
+ loglik = -0.5 * nobs * (Math.log(2 * Math.PI * sigma2) + 1);
808
+ resid = r.resid;
809
+ const f = kalman(residualSeries(reg), phi, theta, delta, kappa);
810
+ model = { phi, theta, delta, a: f.a, P: f.P };
811
+ }
812
+ else {
813
+ const startU = toTransformed(coefNat);
814
+ const res = tightBfgs((u) => mlObjectiveNat(toNatural(full(u))), freeOf(startU));
815
+ coefNat = toNatural(full(res.par));
816
+ code = res.code;
817
+ if (transformPars) {
818
+ const invertible = (c) => {
819
+ const { ma, sma } = split(c);
820
+ return (q === 0 || minRootModulus(ma) > 1) && (Q === 0 || minRootModulus(sma) > 1);
821
+ };
822
+ if (!invertible(coefNat)) {
823
+ const { ma, sma } = split(coefNat);
824
+ if (q > 0 && mask.slice(p, p + q).every(Boolean)) {
825
+ const m2 = maInvert(ma);
826
+ for (let i = 0; i < q; i++)
827
+ coefNat[p + i] = m2[i];
828
+ }
829
+ if (Q > 0 && mask.slice(p + q + P, narma).every(Boolean)) {
830
+ const m2 = maInvert(sma);
831
+ for (let i = 0; i < Q; i++)
832
+ coefNat[p + q + P + i] = m2[i];
833
+ }
834
+ // with a differenced model the kappa prior scales with sigma2, so the reflected MA is not an optimum: refit
835
+ // inside the invertible region from it (R's optimiser stays at the invertible local optimum, the fixture's
836
+ // first run)
837
+ if (invertible(coefNat)) {
838
+ const res2 = tightBfgs((u) => { const c = toNatural(full(u)); return invertible(c) ? mlObjectiveNat(c) : Infinity; }, freeOf(toTransformed(coefNat)));
839
+ coefNat = toNatural(full(res2.par));
840
+ code = res2.code;
841
+ }
842
+ }
843
+ }
844
+ const { ar, ma, sar, sma, reg } = split(coefNat);
845
+ const { phi, theta } = expandArma(ar, ma, sar, sma, s);
846
+ const f = kalman(residualSeries(reg), phi, theta, delta, kappa);
847
+ sigma2 = f.ssq / f.nu;
848
+ nobs = f.nu;
849
+ loglik = -0.5 * (f.nu * Math.log(2 * Math.PI * sigma2) + f.sumlog + f.nu);
850
+ resid = f.resid;
851
+ model = { phi, theta, delta, a: f.a, P: f.P };
852
+ }
853
+ // variance matrix (R's numerical Hessian, log 4): Hu = optimHess of n * objective at the transformed estimate,
854
+ // J the forward difference (step 1e-3) of the map back
855
+ const nFree = mask.filter(Boolean).length;
856
+ let varCoef = [];
857
+ if (nFree > 0) {
858
+ const objective = method === "CSS" ? (c) => cssObjective(c) : (c) => mlObjectiveNat(c);
859
+ // R scales the CSS objective by nobs (n - d - sD, n.cond not subtracted; log of the fixture's first run)
860
+ const scale = nobs;
861
+ const useTrans = transformPars && method !== "CSS";
862
+ const u0 = freeOf(useTrans ? toTransformed(coefNat) : coefNat);
863
+ const g = (u) => scale * objective(useTrans ? toNatural(full(u)) : full(u));
864
+ let H;
865
+ if ((options.hessian ?? "R") === "R")
866
+ H = optimHess(u0, g);
867
+ else
868
+ H = convergedHessian(g, u0);
869
+ const Hinv = invertSymmetric(H);
870
+ if (useTrans) {
871
+ const J = Array.from({ length: nFree }, () => new Array(nFree).fill(0));
872
+ const base = freeOf(toNatural(full(u0)));
873
+ for (let j = 0; j < nFree; j++) {
874
+ const uj = u0.slice();
875
+ uj[j] += 1e-3;
876
+ const nat = freeOf(toNatural(full(uj)));
877
+ for (let i = 0; i < nFree; i++)
878
+ J[i][j] = (nat[i] - base[i]) / 1e-3;
879
+ }
880
+ varCoef = J.map((row) => J.map((row2) => row.reduce((acc, v, a2) => acc + v * Hinv[a2].reduce((acc2, h, b2) => acc2 + h * row2[b2], 0), 0)));
881
+ }
882
+ else
883
+ varCoef = Hinv;
884
+ }
885
+ // back from the optimiser's scaled regression coefficients
886
+ if (nFree > 0) {
887
+ const freeIdx = mask.map((m, i) => (m ? i : -1)).filter((i) => i >= 0);
888
+ const sc = freeIdx.map((i) => (i >= narma ? regScale[i - narma] : 1));
889
+ varCoef = varCoef.map((row, a) => row.map((v, b) => v / (sc[a] * sc[b])));
890
+ }
891
+ const npar = nFree + 1;
892
+ const aic = method === "CSS" ? NaN : -2 * loglik + 2 * npar;
893
+ return { coef: coefNat, coefNames, sigma2, varCoef, loglik, aic, arma: [p, q, P, Q, s, d, D], residuals: resid, method,
894
+ nCond: method === "CSS" ? nCond : 0, nobs, code, mask, model, x, xreg: xreg0, includeMean };
895
+ }
896
+ function solveSymmetric(A, b) {
897
+ const n = b.length;
898
+ const M = A.map((row, i) => [...row, b[i]]);
899
+ for (let c = 0; c < n; c++) {
900
+ let piv = c;
901
+ for (let r = c + 1; r < n; r++)
902
+ if (Math.abs(M[r][c]) > Math.abs(M[piv][c]))
903
+ piv = r;
904
+ [M[c], M[piv]] = [M[piv], M[c]];
905
+ const d = M[c][c];
906
+ if (d === 0)
907
+ continue;
908
+ for (let r = 0; r < n; r++) {
909
+ if (r === c)
910
+ continue;
911
+ const f = M[r][c] / d;
912
+ for (let k = c; k <= n; k++)
913
+ M[r][k] -= f * M[c][k];
914
+ }
915
+ }
916
+ return M.map((row, i) => row[n] / row[i]);
917
+ }
918
+ function invertSymmetric(A) {
919
+ const n = A.length;
920
+ return Array.from({ length: n }, (_, j) => solveSymmetric(A.map((r) => r.slice()), Array.from({ length: n }, (_, i) => (i === j ? 1 : 0))))
921
+ .reduce((acc, col, j) => { col.forEach((v, i) => { acc[i][j] = v; }); return acc; }, Array.from({ length: n }, () => new Array(n).fill(0)));
922
+ }
923
+ /** A Hessian by central differences with Richardson extrapolation over halved steps (the "exact" option). */
924
+ function convergedHessian(f, u0) {
925
+ const k = u0.length;
926
+ const at = (h) => Array.from({ length: k }, (_, i) => Array.from({ length: k }, (_, j) => {
927
+ const e = (a, b) => { const v = u0.slice(); v[i] += a; v[j] += b; return f(v); };
928
+ return (e(h, h) - e(h, -h) - e(-h, h) + e(-h, -h)) / (4 * h * h);
929
+ }));
930
+ const h1 = at(1e-3), h2 = at(5e-4);
931
+ return h1.map((row, i) => row.map((v, j) => (4 * h2[i][j] - v) / 3));
932
+ }
933
+ /** A gradient by central differences with Richardson extrapolation. */
934
+ function convergedGradient(f, u0) {
935
+ return u0.map((_, i) => {
936
+ const d = (h) => { const a = u0.slice(), b = u0.slice(); a[i] += h; b[i] -= h; return (f(a) - f(b)) / (2 * h); };
937
+ const h = 1e-4 * Math.max(1, Math.abs(u0[i]));
938
+ return (4 * d(h / 2) - d(h)) / 3;
939
+ });
940
+ }
941
+ /**
942
+ * Forecasts from an {@link arima} fit by the Kalman filter (the exact predictor from the finite past). Equivalent to
943
+ * R's `predict.Arima()`.
944
+ *
945
+ * @category Time series
946
+ */
947
+ export function predictArima(fit, nAhead = 1, options = {}) {
948
+ checkOptions(options, PREDICT_ARIMA_KEYS, "predictArima"); // generated: option-keys.mjs
949
+ // a fit far from unit scale: from its standardised fit (sigma2 may be out of range as a square)
950
+ const sc = ARIMA_SCALED.get(fit);
951
+ if (sc) {
952
+ const r = predictArima(sc.fit, nAhead, { ...options, ...(options.sigma2 !== undefined ? { sigma2: options.sigma2 / sc.c / sc.c } : {}) });
953
+ return { pred: r.pred.map((v) => v * sc.c), se: r.se.map((v) => v * sc.c) };
954
+ }
955
+ const { phi, theta, delta } = fit.model;
956
+ let a = fit.model.a.slice();
957
+ let P = fit.model.P.map((r) => r.slice());
958
+ const p = phi.length, q = theta.length;
959
+ const r = Math.max(p, q + 1);
960
+ const nd = delta.length;
961
+ const rd = r + nd;
962
+ const Rv = [1, ...Array.from({ length: r - 1 }, (_, i) => theta[i] ?? 0)];
963
+ const Z = new Array(rd).fill(0);
964
+ Z[0] = 1;
965
+ for (let k = 0; k < nd; k++)
966
+ Z[r + k] = delta[k];
967
+ const transition = (x) => {
968
+ const out = new Array(rd).fill(0);
969
+ for (let i = 0; i < r; i++)
970
+ out[i] = (phi[i] ?? 0) * x[0] + (i + 1 < r ? x[i + 1] : 0);
971
+ if (nd > 0) {
972
+ let z = 0;
973
+ for (let k = 0; k < rd; k++)
974
+ z += Z[k] * x[k];
975
+ out[r] = z;
976
+ for (let k = 1; k < nd; k++)
977
+ out[r + k] = x[r + k - 1];
978
+ }
979
+ return out;
980
+ };
981
+ const narma = fit.arma[0] + fit.arma[1] + fit.arma[2] + fit.arma[3];
982
+ const reg = fit.coef.slice(narma);
983
+ const newx = options.newxreg ?? [];
984
+ if (fit.xreg.length > 0 && newx.length !== fit.xreg.length)
985
+ throw new RangeError("'xreg' and 'newxreg' have different numbers of columns");
986
+ const sigma2 = options.sigma2 ?? fit.sigma2;
987
+ const pred = [], se = [];
988
+ for (let h = 0; h < nAhead; h++) {
989
+ a = transition(a);
990
+ const TP = P.map((_, j) => transition(P.map((row) => row[j])));
991
+ const TPT = Array.from({ length: rd }, (_, i) => transition(TP.map((col) => col[i])));
992
+ P = TPT.map((row, i) => row.map((v, j) => v + (i < r && j < r ? Rv[i] * Rv[j] : 0)));
993
+ let fc = 0;
994
+ for (let k = 0; k < rd; k++)
995
+ fc += Z[k] * a[k];
996
+ const F = P.reduce((s, row, i) => s + Z[i] * row.reduce((s2, v, j) => s2 + v * Z[j], 0), 0);
997
+ let m = fc;
998
+ let k = 0;
999
+ if (fit.includeMean)
1000
+ m += reg[k++];
1001
+ for (let c = 0; c < newx.length; c++)
1002
+ m += reg[k++] * Number(newx[c][h]);
1003
+ pred.push(m);
1004
+ se.push(Math.sqrt(sigma2 * F));
1005
+ }
1006
+ return { pred, se };
1007
+ }