@numero-uno-jpn/rstats 1.18.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 (139) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.ja.md +7 -7
  3. package/README.md +7 -7
  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-JF4PXFJE.js → chunk-4EQN74JN.js} +2 -2
  8. package/dist/chunks/chunk-5RRFO4NU.js +2 -0
  9. package/dist/chunks/{chunk-3JFRDXN7.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-EC77KAAM.js → chunk-6LAKI2QG.js} +2 -2
  13. package/dist/chunks/{chunk-5CTWYFMB.js → chunk-6QCH4LAL.js} +2 -2
  14. package/dist/chunks/{chunk-H6Z7JVSD.js → chunk-6RA73LXX.js} +2 -2
  15. package/dist/chunks/{chunk-KJMLQHCY.js → chunk-7C2ECGT6.js} +1 -1
  16. package/dist/chunks/{chunk-SCFFHEDZ.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-XQCHC3SH.js → chunk-B5GSH3AK.js} +1 -1
  20. package/dist/chunks/{chunk-2JB7F646.js → chunk-BLDLJHUG.js} +2 -2
  21. package/dist/chunks/{chunk-IKMW63BE.js → chunk-BU4I544S.js} +2 -2
  22. package/dist/chunks/{chunk-LCIX76FR.js → chunk-CAUNJ7S6.js} +2 -2
  23. package/dist/chunks/chunk-DFGW4QWU.js +2 -0
  24. package/dist/chunks/{chunk-WYVUCQO3.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-MXZ64QME.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-RXYZQ3UX.js → chunk-LZAB4M7P.js} +2 -2
  33. package/dist/chunks/chunk-LZTDYQRS.js +3 -0
  34. package/dist/chunks/{chunk-N7BUE54L.js → chunk-MTSU2QHB.js} +2 -2
  35. package/dist/chunks/{chunk-GIK34P23.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-Z33Q545U.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-VATAUY7N.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-CTZUYKVL.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/normal.d.ts +4 -0
  56. package/dist/distributions/normal.js +4 -2
  57. package/dist/distributions.js +2 -2
  58. package/dist/entries/tests.d.ts +6 -0
  59. package/dist/entries/tests.js +6 -0
  60. package/dist/entries/timeseries.d.ts +11 -0
  61. package/dist/entries/timeseries.js +11 -0
  62. package/dist/htest/timeROC.d.ts +564 -0
  63. package/dist/htest/timeROC.js +1106 -0
  64. package/dist/linalg.js +2 -2
  65. package/dist/meta/metabin.d.ts +32 -0
  66. package/dist/meta/metabin.js +137 -0
  67. package/dist/meta/metaextra.d.ts +153 -0
  68. package/dist/meta/metaextra.js +290 -0
  69. package/dist/meta/metagen.d.ts +124 -0
  70. package/dist/meta/metagen.js +263 -0
  71. package/dist/meta/metaother.d.ts +87 -0
  72. package/dist/meta/metaother.js +342 -0
  73. package/dist/meta/netmeta.d.ts +256 -0
  74. package/dist/meta/netmeta.js +547 -0
  75. package/dist/mixed.js +3 -4
  76. package/dist/models/glmFamily.js +4 -1
  77. package/dist/models/metaAnalysis.d.ts +4 -0
  78. package/dist/models/metaAnalysis.js +100 -18
  79. package/dist/multivariate.js +2 -2
  80. package/dist/numerics.js +2 -2
  81. package/dist/regression.js +2 -2
  82. package/dist/rstats.js +20 -18
  83. package/dist/special.js +2 -2
  84. package/dist/tests.js +15 -15
  85. package/dist/timeseries/acf.js +5 -2
  86. package/dist/timeseries/arima.d.ts +154 -0
  87. package/dist/timeseries/arima.js +1007 -0
  88. package/dist/timeseries/autoArima.d.ts +70 -0
  89. package/dist/timeseries/autoArima.js +191 -0
  90. package/dist/timeseries/ets.d.ts +158 -0
  91. package/dist/timeseries/ets.js +883 -0
  92. package/dist/timeseries/forecastArima.d.ts +136 -0
  93. package/dist/timeseries/forecastArima.js +432 -0
  94. package/dist/timeseries/forecastDispatch.d.ts +83 -0
  95. package/dist/timeseries/forecastDispatch.js +130 -0
  96. package/dist/timeseries/forecastSimple.d.ts +177 -0
  97. package/dist/timeseries/forecastSimple.js +371 -0
  98. package/dist/timeseries/forecastUtils.d.ts +260 -0
  99. package/dist/timeseries/forecastUtils.js +619 -0
  100. package/dist/timeseries/holtWinters.d.ts +65 -0
  101. package/dist/timeseries/holtWinters.js +193 -0
  102. package/dist/timeseries/input.d.ts +8 -0
  103. package/dist/timeseries/input.js +27 -0
  104. package/dist/timeseries/ocsbCritical.d.ts +2 -0
  105. package/dist/timeseries/ocsbCritical.js +6 -0
  106. package/dist/timeseries/scale.d.ts +16 -0
  107. package/dist/timeseries/scale.js +48 -0
  108. package/dist/timeseries/statsTs.d.ts +128 -0
  109. package/dist/timeseries/statsTs.js +456 -0
  110. package/dist/timeseries/stl.d.ts +131 -0
  111. package/dist/timeseries/stl.js +489 -0
  112. package/dist/timeseries/tseries.d.ts +110 -0
  113. package/dist/timeseries/tseries.js +369 -0
  114. package/dist/timeseries.js +2 -2
  115. package/package.json +1 -1
  116. package/dist/chunks/chunk-53WQDB3C.js +0 -2
  117. package/dist/chunks/chunk-6I23C2YJ.js +0 -2
  118. package/dist/chunks/chunk-FLFNMSHI.js +0 -3
  119. package/dist/chunks/chunk-GEHMND3C.js +0 -2
  120. package/dist/chunks/chunk-HG4LJBNV.js +0 -2
  121. package/dist/chunks/chunk-HGAEVPVS.js +0 -2
  122. package/dist/chunks/chunk-HMLYEFQN.js +0 -2
  123. package/dist/chunks/chunk-HRRCC2BD.js +0 -2
  124. package/dist/chunks/chunk-IBHMM2SL.js +0 -2
  125. package/dist/chunks/chunk-ICDW3I2F.js +0 -2
  126. package/dist/chunks/chunk-IOJVFYHW.js +0 -2
  127. package/dist/chunks/chunk-IW4S634O.js +0 -2
  128. package/dist/chunks/chunk-JPWYGTUN.js +0 -2
  129. package/dist/chunks/chunk-KVJBCT3D.js +0 -2
  130. package/dist/chunks/chunk-LY5XGFPU.js +0 -2
  131. package/dist/chunks/chunk-MKZH65DK.js +0 -2
  132. package/dist/chunks/chunk-MVPHISOV.js +0 -2
  133. package/dist/chunks/chunk-NDZVVNBB.js +0 -2
  134. package/dist/chunks/chunk-NOTJ45G3.js +0 -4
  135. package/dist/chunks/chunk-QUD3374N.js +0 -2
  136. package/dist/chunks/chunk-V6FMGGUV.js +0 -2
  137. package/dist/chunks/chunk-W5M3R4NH.js +0 -2
  138. package/dist/chunks/chunk-XUMVTGMM.js +0 -2
  139. package/dist/chunks/chunk-YXMHWS5R.js +0 -2
@@ -0,0 +1,456 @@
1
+ // stats' filter, Box.test, diffinv, decompose, ar (yule-walker, burg, ols, mle), predict.ar and arima0. Written for
2
+ // rStats.js from the behaviour specification oracle/tsmeta-behaviour.md with the details found in
3
+ // experiments/tsmeta120-log.md (items 10-12). No R or package source was read.
4
+ import { pchisq } from "../distributions/chisq.js";
5
+ import { lm } from "../models/lm.js";
6
+ import { arima, expandArma, minRootModulus, stationaryCovariance } from "./arima.js";
7
+ import { optim } from "../optim/optim.js";
8
+ import { centred, powerOfTwoScale, standardise } from "./scale.js";
9
+ import { tsInput } from "./input.js";
10
+ import { acf } from "./acf.js";
11
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
12
+ import { checkOptions } from "../internal/checkOptions.js";
13
+ const TS_FILTER_KEYS = ["method", "sides", "circular", "init"];
14
+ const BOX_TEST_KEYS = ["lag", "type", "fitdf"];
15
+ const DIFFINV_KEYS = ["lag", "differences", "xi"];
16
+ const DECOMPOSE_KEYS = ["frequency", "type", "filter"];
17
+ const AR_KEYS = ["method", "orderMax", "aic", "demean", "varMethod"];
18
+ const ARIMA0_KEYS = ["order", "seasonal", "frequency", "includeMean", "delta"];
19
+ // Generated by `node scripts/option-keys.mjs --write` (end)
20
+ // ---------------------------------------------------------------------------------------------------------------
21
+ // filter
22
+ /**
23
+ * Linear filtering of a series (stats' `filter()`): convolution, y_i = sum_j f_j x_{i + o - (j - 1)} with o = 0 for
24
+ * `sides: 1` and floor(p / 2) for `sides: 2` (NaN where an index falls outside, or wrapped with `circular`), or
25
+ * recursive, y_i = x_i + sum_j f_j y_{i - j} with `init` (the most recent value first, as R).
26
+ * Equivalent to R's `filter()`.
27
+ *
28
+ * @category Time series
29
+ */
30
+ export function tsFilter(x, f, options = {}) {
31
+ checkOptions(options, TS_FILTER_KEYS, "tsFilter"); // generated: option-keys.mjs
32
+ const n = x.length;
33
+ const p = f.length;
34
+ const method = options.method ?? "convolution";
35
+ // R's rule (log 107): a convolution filter no longer than the series
36
+ if (method === "convolution" && p > n)
37
+ throw new RangeError("tsFilter: the filter is longer than the series");
38
+ if (method === "convolution") {
39
+ const o = (options.sides ?? 2) === 2 ? Math.floor(p / 2) : 0;
40
+ const circ = options.circular ?? false;
41
+ return Array.from({ length: n }, (_, i) => {
42
+ let s = 0;
43
+ for (let j = 0; j < p; j++) {
44
+ let k = i + o - j;
45
+ if (k < 0 || k >= n) {
46
+ if (!circ)
47
+ return NaN;
48
+ k = ((k % n) + n) % n;
49
+ }
50
+ const v = x[k];
51
+ if (Number.isNaN(v))
52
+ return NaN;
53
+ s += f[j] * v;
54
+ }
55
+ return s;
56
+ });
57
+ }
58
+ // init in reverse time order: init[0] is y_0, init[1] is y_{-1}, ...
59
+ const init = options.init ?? new Array(p).fill(0);
60
+ const prev = [...init];
61
+ const out = [];
62
+ for (let i = 0; i < n; i++) {
63
+ let s = x[i];
64
+ for (let j = 0; j < p; j++)
65
+ s += f[j] * (j < out.length ? out[out.length - 1 - j] : prev[j - out.length]);
66
+ out.push(s);
67
+ }
68
+ return out;
69
+ }
70
+ // ---------------------------------------------------------------------------------------------------------------
71
+ // Box.test
72
+ /**
73
+ * Box-Pierce or Ljung-Box test of white noise (stats' `Box.test()`): r_k the autocorrelations (mean removed, divided by
74
+ * n), Q = n sum r_k^2 or n (n + 2) sum r_k^2 / (n - k), chi-squared on lag - fitdf degrees of freedom.
75
+ * Equivalent to R's `Box.test()`.
76
+ *
77
+ * @category Time series
78
+ */
79
+ export function boxTest(x, options = {}) {
80
+ checkOptions(options, BOX_TEST_KEYS, "boxTest"); // generated: option-keys.mjs
81
+ const lag = options.lag ?? 1;
82
+ const type = options.type ?? "Box-Pierce";
83
+ const fitdf = options.fitdf ?? 0;
84
+ // divided by a power of two (exact; the statistic does not depend on the scale), so that 1e+-300 works. Missing
85
+ // values as R's (acf with na.pass: the products over the pairs both observed; n the number observed; log 107)
86
+ const v0 = standardise(centred(tsInput(x, "boxTest", { missing: "allow", minLength: 2 })));
87
+ const missing = v0.some((a) => Number.isNaN(a));
88
+ const ra = missing ? acf(v0, { lagMax: lag, naAction: "pass" }).acf : [];
89
+ const v = v0.filter((a) => !Number.isNaN(a));
90
+ const n = v.length;
91
+ const mean = v.reduce((a, b) => a + b, 0) / n;
92
+ const c0 = v.reduce((a, b) => a + (b - mean) ** 2, 0) / n;
93
+ let q = 0;
94
+ for (let k = 1; k <= lag; k++) {
95
+ let ck = 0;
96
+ for (let t = k; t < n; t++)
97
+ ck += (v[t] - mean) * (v[t - k] - mean);
98
+ ck /= n;
99
+ const r = missing ? ra[k] : ck / c0;
100
+ q += type === "Box-Pierce" ? r * r : (r * r) / (n - k);
101
+ }
102
+ const statistic = type === "Box-Pierce" ? n * q : n * (n + 2) * q;
103
+ const df = lag - fitdf;
104
+ return { statistic, parameter: df, pValue: pchisq(statistic, df, { lowerTail: false }), method: type === "Box-Pierce" ? "Box-Pierce test" : "Box-Ljung test" };
105
+ }
106
+ // ---------------------------------------------------------------------------------------------------------------
107
+ // diffinv
108
+ /**
109
+ * The inverse of differencing (stats' `diffinv()`): the cumulative sums at the given lag, repeated `differences`
110
+ * times, starting from `xi` (zeros by default).
111
+ * Equivalent to R's `diffinv()`.
112
+ *
113
+ * @category Time series
114
+ */
115
+ export function diffinv(x, options = {}) {
116
+ checkOptions(options, DIFFINV_KEYS, "diffinv"); // generated: option-keys.mjs
117
+ const lag = options.lag ?? 1;
118
+ const d = options.differences ?? 1;
119
+ const xi = options.xi ?? new Array(lag * d).fill(0);
120
+ if (xi.length !== lag * d)
121
+ throw new RangeError("'xi' does not have the right length");
122
+ if (d === 1) {
123
+ const out = xi.slice(0, lag);
124
+ for (let i = 0; i < x.length; i++)
125
+ out.push(x[i] + out[i]);
126
+ return out;
127
+ }
128
+ // recursively: the inner inverse starts from the lag-th differences of xi
129
+ const xiDiff = xi.slice(lag).map((v, i) => v - xi[i]);
130
+ const inner = diffinv(x, { lag, differences: d - 1, xi: xiDiff });
131
+ return diffinv(inner, { lag, differences: 1, xi: xi.slice(0, lag) });
132
+ }
133
+ /**
134
+ * Classical seasonal decomposition by moving averages (stats' `decompose()`). `start` is the position (1..frequency)
135
+ * of the first observation in the cycle; `figure` starts at that position, as R's.
136
+ * Equivalent to R's `decompose()`.
137
+ *
138
+ * @category Time series
139
+ */
140
+ export function decompose(x, options) {
141
+ checkOptions(options, DECOMPOSE_KEYS, "decompose"); // generated: option-keys.mjs
142
+ const f = options.frequency;
143
+ const type = options.type ?? "additive";
144
+ const n = x.length;
145
+ // missing values: an error, as R's (log 107)
146
+ x = tsInput(x, "decompose");
147
+ if (f <= 1 || n < 2 * f)
148
+ throw new RangeError("time series has no or less than 2 periods");
149
+ const filt = options.filter ?? (f % 2 === 0 ? [0.5, ...new Array(f - 1).fill(1), 0.5].map((v) => v / f) : new Array(f).fill(1 / f));
150
+ const trend = tsFilter(x, filt, { sides: 2 });
151
+ const detr = x.map((v, i) => (type === "additive" ? v - trend[i] : v / trend[i]));
152
+ const sums = new Array(f).fill(0), cnt = new Array(f).fill(0);
153
+ detr.forEach((v, i) => { if (!Number.isNaN(v)) {
154
+ sums[i % f] += v;
155
+ cnt[i % f]++;
156
+ } });
157
+ let figure = sums.map((s, i) => s / cnt[i]);
158
+ const mean = figure.reduce((a, b) => a + b, 0) / f;
159
+ figure = figure.map((v) => (type === "additive" ? v - mean : v / mean));
160
+ const seasonal = x.map((_, i) => figure[i % f]);
161
+ const random = x.map((v, i) => (type === "additive" ? v - seasonal[i] - trend[i] : v / (seasonal[i] * trend[i])));
162
+ return { x: x.slice(), seasonal, trend, random, figure, type };
163
+ }
164
+ /**
165
+ * Fits an autoregressive model with the order chosen by AIC (stats' `ar()`): Yule-Walker (default), Burg, OLS or MLE
166
+ * (arima0 for each order).
167
+ * Equivalent to R's `ar()`.
168
+ *
169
+ * @category Time series
170
+ */
171
+ export function ar(x, options = {}) {
172
+ checkOptions(options, AR_KEYS, "ar"); // generated: option-keys.mjs
173
+ // missing values and series of one value: errors, as R's (log 107)
174
+ x = tsInput(x, "ar", { minLength: 2 });
175
+ // far from unit scale (the squares near the ends of the range), the fit of x / c for a power of two c (exact), mapped
176
+ // back (1.20.0, log 104); at ordinary scales the series itself (the MLE's optimiser is R's)
177
+ const c = powerOfTwoScale(x.map(Number));
178
+ if (Math.abs(Math.log2(c)) <= 200)
179
+ return arFit(x, options);
180
+ const r = arFit(x.map((v) => Number(v) / c), options);
181
+ const out = { ...r, varPred: r.varPred * c * c, xMean: r.xMean * c, ...(r.xIntercept !== undefined ? { xIntercept: r.xIntercept * c } : {}),
182
+ residuals: r.residuals.map((v) => v * c), x: x.map(Number) };
183
+ // the standardised variance kept for predictAr's standard errors, in range where varPred itself is not (log 110)
184
+ AR_SCALED.set(out, { varPred: r.varPred, c });
185
+ return out;
186
+ }
187
+ const AR_SCALED = new WeakMap();
188
+ function arFit(x, options) {
189
+ const method = options.method ?? "yule-walker";
190
+ const xs = x.map(Number);
191
+ const n = xs.length;
192
+ const demean = options.demean ?? true;
193
+ const useAic = options.aic ?? true;
194
+ const xMean = demean ? xs.reduce((a, b) => a + b, 0) / n : 0;
195
+ const z = xs.map((v) => v - xMean);
196
+ const orderMax = Math.min(options.orderMax ?? Math.floor(Math.min(n - 1, 10 * Math.log10(n))), method === "mle" ? 12 : Infinity, n - 1);
197
+ const pickOrder = (aic) => { if (!useAic)
198
+ return orderMax; let b = 0; for (let k = 1; k < aic.length; k++)
199
+ if (aic[k] < aic[b])
200
+ b = k; return b; };
201
+ const rel = (a) => { const m = Math.min(...a); return a.map((v) => v - m); };
202
+ const residualsOf = (coef, mean, intercept = 0) => xs.map((_, t) => {
203
+ if (t < coef.length)
204
+ return NaN;
205
+ let v = xs[t] - mean - intercept;
206
+ for (let j = 0; j < coef.length; j++)
207
+ v -= coef[j] * (xs[t - j - 1] - mean);
208
+ return v;
209
+ });
210
+ if (method === "yule-walker" || method === "burg") {
211
+ const aicAll = [];
212
+ const coefs = [[]];
213
+ const vs = [];
214
+ const pacf = [];
215
+ if (method === "yule-walker") {
216
+ const c = Array.from({ length: orderMax + 1 }, (_, k) => { let s = 0; for (let t = k; t < n; t++)
217
+ s += z[t] * z[t - k]; return s / n; });
218
+ let v = c[0];
219
+ vs.push(v);
220
+ aicAll.push(n * Math.log(v));
221
+ let phi = [];
222
+ for (let k = 1; k <= orderMax; k++) {
223
+ let num = c[k];
224
+ for (let j = 0; j < phi.length; j++)
225
+ num -= phi[j] * c[k - 1 - j];
226
+ const a = num / v;
227
+ const next = phi.map((p, j) => p - a * phi[phi.length - 1 - j]);
228
+ next.push(a);
229
+ phi = next;
230
+ v *= 1 - a * a;
231
+ vs.push(v);
232
+ pacf.push(a);
233
+ coefs.push(phi.slice());
234
+ aicAll.push(n * Math.log(v) + 2 * k);
235
+ }
236
+ const order = pickOrder(aicAll);
237
+ const coef = coefs[order];
238
+ // var.pred = v_p n / (n - (p + 1)) (log 10)
239
+ return { order, ar: coef, varPred: (vs[order] * n) / (n - (order + 1)), xMean, aic: rel(aicAll), partialacf: pacf, residuals: residualsOf(coef, xMean), method: "Yule-Walker", orderMax, x: xs };
240
+ }
241
+ // Burg: forward and backward errors, reflection coefficients (log 11)
242
+ const varMethod = options.varMethod ?? 1;
243
+ let fwd = z.slice(), bwd = z.slice();
244
+ let phi = [];
245
+ let v1 = z.reduce((a, b) => a + b * b, 0) / n;
246
+ const v1s = [v1];
247
+ const v2s = [v1];
248
+ for (let k = 1; k <= orderMax; k++) {
249
+ let num = 0, den = 0;
250
+ for (let t = k; t < n; t++) {
251
+ num += fwd[t] * bwd[t - 1];
252
+ den += fwd[t] ** 2 + bwd[t - 1] ** 2;
253
+ }
254
+ const a = (2 * num) / den;
255
+ const next = phi.map((p, j) => p - a * phi[phi.length - 1 - j]);
256
+ next.push(a);
257
+ phi = next;
258
+ const nf = fwd.slice(), nb = bwd.slice();
259
+ for (let t = k; t < n; t++) {
260
+ nf[t] = fwd[t] - a * bwd[t - 1];
261
+ nb[t] = bwd[t - 1] - a * fwd[t];
262
+ }
263
+ fwd = nf;
264
+ bwd = nb;
265
+ v1 *= 1 - a * a;
266
+ v1s.push(v1);
267
+ let sf = 0, sb = 0;
268
+ for (let t = k; t < n; t++) {
269
+ sf += fwd[t] ** 2;
270
+ sb += bwd[t] ** 2;
271
+ }
272
+ v2s.push((sf + sb) / (2 * (n - k)));
273
+ pacf.push(a);
274
+ coefs.push(phi.slice());
275
+ }
276
+ const vv = varMethod === 1 ? v1s : v2s;
277
+ const aicB = vv.map((v, k) => n * Math.log(v) + 2 * k);
278
+ const order = pickOrder(aicB);
279
+ const coef = coefs[order];
280
+ return { order, ar: coef, varPred: vv[order], xMean, aic: rel(aicB), partialacf: pacf, residuals: residualsOf(coef, xMean), method: "Burg", orderMax, x: xs };
281
+ }
282
+ if (method === "ols") {
283
+ // each order on its own n - k rows: aic = n log(RSS_k / (n - k)) + 2k (log 11)
284
+ const fits = [];
285
+ const aicO = [];
286
+ for (let k = 0; k <= orderMax; k++) {
287
+ const rows = [], resp = [];
288
+ for (let t = k; t < n; t++) {
289
+ rows.push(Array.from({ length: k }, (_, j) => z[t - j - 1]));
290
+ resp.push(z[t]);
291
+ }
292
+ let coef = [], intercept, rss;
293
+ if (k === 0) {
294
+ intercept = resp.reduce((a, b) => a + b, 0) / resp.length;
295
+ rss = resp.reduce((a, b) => a + (b - intercept) ** 2, 0);
296
+ }
297
+ else {
298
+ const f = lm(rows, resp, {});
299
+ intercept = f.coefficients[0];
300
+ coef = f.coefficients.slice(1);
301
+ rss = f.residuals.reduce((a, b) => a + b * b, 0);
302
+ }
303
+ fits.push({ coef, intercept, rss });
304
+ aicO.push(n * Math.log(rss / (n - k)) + 2 * k);
305
+ }
306
+ const order = pickOrder(aicO);
307
+ const ff = fits[order];
308
+ return { order, ar: ff.coef, varPred: ff.rss / (n - order), xMean, xIntercept: ff.intercept, aic: rel(aicO), residuals: residualsOf(ff.coef, xMean, ff.intercept), method: "Unconstrained LS", orderMax, x: xs };
309
+ }
310
+ // mle: arima0 for each order (log 12)
311
+ const fits = Array.from({ length: orderMax + 1 }, (_, k) => arima0(xs, { order: [k, 0, 0], includeMean: demean }));
312
+ const aicM = fits.map((f) => f.aic);
313
+ const order = pickOrder(aicM);
314
+ const ff = fits[order];
315
+ const mean = demean ? ff.coef[ff.coef.length - 1] : 0;
316
+ return { order, ar: ff.coef.slice(0, order), varPred: ff.sigma2, xMean: mean, aic: rel(aicM), residuals: residualsOf(ff.coef.slice(0, order), mean), method: "MLE", orderMax, x: xs };
317
+ }
318
+ /**
319
+ * Predictions from an {@link ar} fit (stats' `predict.ar`): the AR recursion about the mean, se = sqrt(var.pred cumsum(psi^2)). Equivalent to R's `predict()`.
320
+ *
321
+ * @category Time series
322
+ */
323
+ export function predictAr(fit, nAhead = 1) {
324
+ const p = fit.order;
325
+ const x = fit.x;
326
+ const mu = fit.xMean;
327
+ const c = fit.xIntercept ?? 0;
328
+ const hist = x.map((v) => v - mu);
329
+ const pred = [];
330
+ for (let h = 0; h < nAhead; h++) {
331
+ let v = c;
332
+ for (let j = 0; j < p; j++)
333
+ v += fit.ar[j] * hist[hist.length - 1 - j];
334
+ hist.push(v);
335
+ pred.push(v + mu);
336
+ }
337
+ const psi = [1];
338
+ for (let j = 1; j < nAhead; j++) {
339
+ let v = 0;
340
+ for (let k = 1; k <= Math.min(j, p); k++)
341
+ v += fit.ar[k - 1] * psi[j - k];
342
+ psi.push(v);
343
+ }
344
+ const sc = AR_SCALED.get(fit);
345
+ let acc = 0;
346
+ const se = psi.map((ps) => { acc += ps * ps; return sc ? sc.c * Math.sqrt(sc.varPred * acc) : Math.sqrt(fit.varPred * acc); });
347
+ return { pred, se };
348
+ }
349
+ // ---------------------------------------------------------------------------------------------------------------
350
+ // arima0
351
+ /**
352
+ * The exact Gaussian likelihood of an ARMA model on w (mean already removed) with arima0's fast recursions (log 87):
353
+ * the Kalman filter until the first t >= 1 with F_t - 1 < delta (delta <= 0: never), then F = 1 and the innovations by
354
+ * the ARMA recursion, the past innovations being the standardised residuals. Returns -loglik / n's parts.
355
+ */
356
+ function arima0Filter(w, phi, theta, delta) {
357
+ const p = phi.length, q = theta.length, r = Math.max(p, q + 1);
358
+ const n = w.length;
359
+ const P0 = stationaryCovariance(phi, theta, r);
360
+ let P = P0.map((row) => row.slice());
361
+ let a = new Array(r).fill(0);
362
+ const Rv = [1, ...Array.from({ length: r - 1 }, (_, i) => theta[i] ?? 0)];
363
+ const T = (x) => Array.from({ length: r }, (_, i) => (phi[i] ?? 0) * x[0] + (i + 1 < r ? x[i + 1] : 0));
364
+ const resid = [];
365
+ let ssq = 0, sumlog = 0;
366
+ let fast = false;
367
+ // missing values force full recursions (the help page)
368
+ const useFast = delta > 0 && w.every((v) => !Number.isNaN(v));
369
+ for (let t = 0; t < n; t++) {
370
+ if (!fast) {
371
+ if (t > 0) {
372
+ a = T(a);
373
+ const TP = P.map((_, c) => T(P.map((row) => row[c])));
374
+ P = Array.from({ length: r }, (_, i) => T(TP.map((c) => c[i]))).map((row, i) => row.map((v, k) => v + Rv[i] * Rv[k]));
375
+ }
376
+ if (useFast && t > 0 && P[0][0] - 1 < delta)
377
+ fast = true;
378
+ }
379
+ if (fast) {
380
+ let v = w[t];
381
+ for (let i = 0; i < p; i++)
382
+ v -= phi[i] * (t - i - 1 >= 0 ? w[t - i - 1] : 0);
383
+ for (let k = 0; k < q; k++)
384
+ v -= theta[k] * (t - k - 1 >= 0 ? resid[t - k - 1] : 0);
385
+ resid.push(v);
386
+ ssq += v * v;
387
+ continue;
388
+ }
389
+ const F = P[0][0];
390
+ if (Number.isNaN(w[t])) {
391
+ resid.push(NaN);
392
+ continue;
393
+ }
394
+ const v = w[t] - a[0];
395
+ const e = v / Math.sqrt(F);
396
+ resid.push(e);
397
+ ssq += e * e;
398
+ sumlog += Math.log(F);
399
+ const PZ = P.map((row) => row[0]);
400
+ a = a.map((ak, k) => ak + (PZ[k] * v) / F);
401
+ P = P.map((row, i) => row.map((pv, k) => pv - (PZ[i] * PZ[k]) / F));
402
+ }
403
+ return { ssq, sumlog, n: resid.filter((v) => !Number.isNaN(v)).length, resid };
404
+ }
405
+ /**
406
+ * stats' `arima0()`: an ARIMA model by maximum likelihood of the differenced series (no diffuse prior; the mean with
407
+ * `includeMean` when d + D = 0), with R's fast recursions once the prediction variance is within `delta` of its limit
408
+ * (default 0.01, as R; a negative delta gives the exact likelihood, equal to arima's). Log 84, 87.
409
+ * Equivalent to R's `arima0()`.
410
+ *
411
+ * @category Time series
412
+ */
413
+ export function arima0(x, options = {}) {
414
+ checkOptions(options, ARIMA0_KEYS, "arima0"); // generated: option-keys.mjs
415
+ const order = options.order ?? [0, 0, 0];
416
+ const seasonal = options.seasonal ?? [0, 0, 0];
417
+ const s = options.frequency ?? 1;
418
+ const delta = options.delta ?? 0.01;
419
+ let w = tsInput(x, "arima0", { missing: "allow" });
420
+ for (let k = 0; k < order[1]; k++)
421
+ w = w.slice(1).map((v, i) => v - w[i]);
422
+ for (let k = 0; k < seasonal[1]; k++)
423
+ w = w.slice(s).map((v, i) => v - w[i]);
424
+ const includeMean = (options.includeMean ?? true) && order[1] + seasonal[1] === 0;
425
+ // the exact fit (arima's) as the start, then the arima0 likelihood optimised from there
426
+ const fit = arima(w, { order: [order[0], 0, order[2]], seasonal: { order: [seasonal[0], 0, seasonal[2]], period: s }, frequency: s, includeMean, method: "ML" });
427
+ const [p, q, P, Q] = [order[0], order[2], seasonal[0], seasonal[2]];
428
+ const narma = p + q + P + Q;
429
+ const obj = (c) => {
430
+ const ar = c.slice(0, p), ma = c.slice(p, p + q), sar = c.slice(p + q, p + q + P), sma = c.slice(p + q + P, narma);
431
+ const { phi, theta } = expandArma(ar, ma, sar, sma, s);
432
+ if (phi.length && minRootModulus(phi.map((v) => -v)) <= 1)
433
+ return Infinity;
434
+ const mu = includeMean ? c[narma] : 0;
435
+ const f = arima0Filter(w.map((v) => v - mu), phi, theta, delta);
436
+ return 0.5 * Math.log(f.ssq / f.n) + (0.5 * f.sumlog) / f.n;
437
+ };
438
+ let coef = fit.coef.slice();
439
+ if (delta > 0 && coef.length > 0) {
440
+ let best = obj(coef);
441
+ for (let round = 0; round < 3; round++) {
442
+ const r = optim(coef, (c) => { const v = obj(c); return Number.isFinite(v) ? v : 1e300; }, { method: "Nelder-Mead", control: { reltol: 1e-14, maxit: 5000 } });
443
+ if (!(r.value < best - 1e-15))
444
+ break;
445
+ best = r.value;
446
+ coef = r.par;
447
+ }
448
+ }
449
+ const ar = coef.slice(0, p), ma = coef.slice(p, p + q), sar = coef.slice(p + q, p + q + P), sma = coef.slice(p + q + P, narma);
450
+ const { phi, theta } = expandArma(ar, ma, sar, sma, s);
451
+ const mu = includeMean ? coef[narma] : 0;
452
+ const f = arima0Filter(w.map((v) => v - mu), phi, theta, delta);
453
+ const sigma2 = f.ssq / f.n;
454
+ const loglik = -0.5 * (f.n * Math.log(2 * Math.PI * sigma2) + f.sumlog + f.n);
455
+ return { ...fit, coef, sigma2, loglik, aic: -2 * loglik + 2 * (coef.length + 1), residuals: f.resid, arma: [p, q, P, Q, s, order[1], seasonal[1]] };
456
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Options of {@link stl}.
3
+ *
4
+ * @category Time series
5
+ */
6
+ export interface StlOptions {
7
+ /** The seasonal period (R's frequency). */
8
+ frequency: number;
9
+ /** The seasonal loess span (odd, >= 7 recommended) or "periodic". */
10
+ sWindow: number | "periodic";
11
+ sDegree?: 0 | 1;
12
+ tWindow?: number;
13
+ tDegree?: 0 | 1;
14
+ lWindow?: number;
15
+ lDegree?: 0 | 1;
16
+ sJump?: number;
17
+ tJump?: number;
18
+ lJump?: number;
19
+ robust?: boolean;
20
+ inner?: number;
21
+ outer?: number;
22
+ }
23
+ /**
24
+ * Result of {@link stl}.
25
+ *
26
+ * @category Time series
27
+ */
28
+ export interface StlResult {
29
+ seasonal: number[];
30
+ trend: number[];
31
+ remainder: number[];
32
+ /** The robustness weights of the last pass (all 1 without robustness iterations). */
33
+ weights: number[];
34
+ /** The windows (s, t, l), degrees, jumps and iteration counts used. */
35
+ win: [number, number, number];
36
+ deg: [number, number, number];
37
+ jump: [number, number, number];
38
+ inner: number;
39
+ outer: number;
40
+ }
41
+ /**
42
+ * Seasonal-trend decomposition by loess (Cleveland et al. 1990). Equivalent to R's `stl()`. It differs in that the
43
+ * robustness weights use the true median of |remainder| (R takes a wrong order statistic for some even-length series:
44
+ * R bug 19370, see the documentation's departures from R).
45
+ *
46
+ * @category Time series
47
+ */
48
+ export declare function stl(x: readonly number[], options: StlOptions): StlResult;
49
+ /**
50
+ * Friedman's super smoother (running lines with a cross-validated variable span). Equivalent to R's `supsmu()`.
51
+ * Tied x are not handled as R does.
52
+ *
53
+ * @category Time series
54
+ */
55
+ export declare function supsmu(x: readonly number[], y: readonly number[], options?: {
56
+ span?: number | "cv";
57
+ bass?: number;
58
+ }): {
59
+ x: number[];
60
+ y: number[];
61
+ };
62
+ /**
63
+ * Result of {@link mstl}.
64
+ *
65
+ * @category Time series
66
+ */
67
+ export interface MstlResult {
68
+ data: number[];
69
+ trend: number[];
70
+ /** The seasonal component (absent for a non-seasonal series). */
71
+ seasonal?: number[];
72
+ remainder: number[];
73
+ frequency: number;
74
+ }
75
+ /**
76
+ * forecast's `mstl()` for one seasonal period: stl(x, s.window = 11); for a non-seasonal series (or fewer than two
77
+ * periods) the trend is supsmu(1:n, x).
78
+ * Equivalent to `forecast::mstl()` in R.
79
+ *
80
+ * @category Time series
81
+ */
82
+ export declare function mstl(x: readonly number[], options?: {
83
+ frequency?: number;
84
+ sWindow?: number | "periodic";
85
+ robust?: boolean;
86
+ }): MstlResult;
87
+ /**
88
+ * The seasonally adjusted series of an mstl / stl decomposition (data - seasonal). Equivalent to `forecast::seasadj()` in R.
89
+ *
90
+ * @category Time series
91
+ */
92
+ export declare function seasadj(dec: MstlResult): number[];
93
+ /**
94
+ * The number of seasonal differences: 1 when the seasonal strength of mstl, max(0, 1 - var(remainder) /
95
+ * var(seasonal + remainder)), exceeds 0.64 (test "seas"), or by the OCSB test. Equivalent to `forecast::nsdiffs()` in R.
96
+ *
97
+ * @category Time series
98
+ */
99
+ export declare function nsdiffs(x: readonly number[], options: {
100
+ frequency: number;
101
+ test?: "seas" | "ocsb";
102
+ maxD?: number;
103
+ }): number;
104
+ /**
105
+ * The 5% critical value of the OCSB test for period m (the table read off R; log m interpolation beyond 400). Not an R function.
106
+ *
107
+ * @category Time series
108
+ */
109
+ export declare function ocsbCritical(m: number): number;
110
+ /**
111
+ * The Osborn-Chui-Smith-Birchenhall test for a seasonal unit root: with w = Delta_m Delta_1 y and L lags, the AR(L)
112
+ * coefficients a of w by least squares (no mean), then the regression of w_t on w_{t-1..L} and the two auxiliary
113
+ * series filtered by a, (1 - a(B)) Delta_m y_{t-1} and (1 - a(B)) Delta_1 y_{t-m}, without a constant; the statistic
114
+ * is the t value of the second (log 41, 80). Equivalent to `forecast::ocsb.test()` in R. With `lagMethod` "fixed" (the
115
+ * default) L = `maxlag` (R's default 0). With "AIC", "BIC" or "AICc" the lags 0..maxlag are compared on a common
116
+ * sample (the rows of maxlag lags, the prefilter too) by the lm criterion with k = coefficients + 1 (AICc = AIC +
117
+ * 2k(k + 1) / (n - k - 1), forecast's help), and the chosen L is used. **This departs from R:** forecast 9.0.2 compares
118
+ * L = 1..maxlag that way but reports and uses one lag fewer than the chosen L (log 89-90, an off-by-one; the user's
119
+ * decision 2026-11-27 is not to imitate it). Candidates with a perfect fit (and for AICc, n <= k + 1) are skipped.
120
+ *
121
+ * @category Time series
122
+ */
123
+ export declare function ocsbTest(x: readonly number[], options: {
124
+ frequency: number;
125
+ maxlag?: number;
126
+ lagMethod?: "fixed" | "AIC" | "BIC" | "AICc";
127
+ }): {
128
+ statistic: number;
129
+ critical: number;
130
+ lagOrder: number;
131
+ };