@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,489 @@
1
+ // stats' stl and supsmu, forecast's mstl (one seasonal period), seasadj, nsdiffs and ocsb.test. Written for rStats.js
2
+ // from the behaviour specification oracle/tsmeta-behaviour.md with the details found in experiments/tsmeta120-log.md
3
+ // (stl: items 19-27, from Cleveland, Cleveland, McRae and Terpenning 1990; supsmu: items 48-49, from Friedman 1984;
4
+ // mstl, nsdiffs, ocsb: items 39-42, 47). No R or package source was read.
5
+ import { lm } from "../models/lm.js";
6
+ import { OCSB_CRITICAL, OCSB_M } from "./ocsbCritical.js";
7
+ import { centred, powerOfTwoScale, shiftReference, standardise } from "./scale.js";
8
+ import { tsInput } from "./input.js";
9
+ import { naInterp } from "./forecastUtils.js";
10
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
11
+ import { checkOptions } from "../internal/checkOptions.js";
12
+ const STL_KEYS = /* @__PURE__ */ new Set([
13
+ "frequency", "sWindow", "sDegree", "tWindow", "tDegree", "lWindow", "lDegree", "sJump", "tJump", "lJump", "robust",
14
+ "inner", "outer",
15
+ ]);
16
+ const SUPSMU_KEYS = ["span", "bass"];
17
+ const MSTL_KEYS = ["frequency", "sWindow", "robust"];
18
+ const NSDIFFS_KEYS = ["frequency", "test", "maxD"];
19
+ const OCSB_TEST_KEYS = ["frequency", "maxlag", "lagMethod"];
20
+ // Generated by `node scripts/option-keys.mjs --write` (end)
21
+ // ---------------------------------------------------------------------------------------------------------------
22
+ // stl
23
+ const nextOdd = (x) => { const r = Math.round(x); return r % 2 === 0 ? r + 1 : r; };
24
+ /** loess on positions 1..n (the q nearest consecutive points) evaluated at the positions `at`. */
25
+ function loessAt(y, rw, at, q, degree) {
26
+ const n = y.length;
27
+ const qq = Math.min(q, n);
28
+ return at.map((x) => {
29
+ let left, right;
30
+ if (x < 1) {
31
+ left = 1;
32
+ right = qq;
33
+ }
34
+ else if (x > n) {
35
+ left = n - qq + 1;
36
+ right = n;
37
+ }
38
+ else {
39
+ left = Math.max(1, Math.min(Math.round(x) - Math.floor((qq - 1) / 2), n - qq + 1));
40
+ right = left + qq - 1;
41
+ }
42
+ let h = Math.max(x - left, right - x);
43
+ if (q > n)
44
+ h += Math.floor((q - n) / 2); // the window widened by (q - n) %/% 2 when q > n (log 19)
45
+ const w = [];
46
+ let sw = 0;
47
+ for (let j = left; j <= right; j++) {
48
+ const r = Math.abs(j - x);
49
+ // tricube weights with lowess's thresholds (1 at r <= 0.001 h, 0 beyond 0.999 h)
50
+ let v = r <= 0.001 * h ? 1 : r > 0.999 * h ? 0 : (1 - (r / h) ** 3) ** 3;
51
+ v *= rw[j - 1];
52
+ w.push(v);
53
+ sw += v;
54
+ }
55
+ if (!(sw > 0))
56
+ return NaN;
57
+ for (let k = 0; k < w.length; k++)
58
+ w[k] /= sw;
59
+ if (degree === 1) {
60
+ let a = 0;
61
+ for (let k = 0; k < w.length; k++)
62
+ a += w[k] * (left + k);
63
+ let c = 0;
64
+ for (let k = 0; k < w.length; k++)
65
+ c += w[k] * (left + k - a) ** 2;
66
+ if (Math.sqrt(c) > 0.001 * (n - 1))
67
+ for (let k = 0; k < w.length; k++)
68
+ w[k] *= 1 + ((x - a) * (left + k - a)) / c;
69
+ }
70
+ let s = 0;
71
+ for (let k = 0; k < w.length; k++)
72
+ s += w[k] * y[left + k - 1];
73
+ return s;
74
+ });
75
+ }
76
+ /** loess at 1, 1 + jump, ..., n, linearly interpolated in between. */
77
+ function smoothJump(y, rw, q, degree, jump) {
78
+ const n = y.length;
79
+ if (n <= 2)
80
+ return y.slice();
81
+ const at = [];
82
+ for (let t = 1; t <= n; t += jump)
83
+ at.push(t);
84
+ if (at[at.length - 1] !== n)
85
+ at.push(n);
86
+ const v = loessAt(y, rw, at, q, degree);
87
+ if (jump === 1)
88
+ return v;
89
+ return interpolate(at, v, n);
90
+ }
91
+ function interpolate(at, v, n) {
92
+ const out = new Array(n);
93
+ let k = 0;
94
+ for (let t = 1; t <= n; t++) {
95
+ while (k < at.length - 2 && at[k + 1] < t)
96
+ k++;
97
+ const x0 = at[k], x1 = at[k + 1] ?? x0;
98
+ out[t - 1] = x1 === x0 ? v[k] : v[k] + ((v[k + 1] - v[k]) * (t - x0)) / (x1 - x0);
99
+ }
100
+ return out;
101
+ }
102
+ /** A trailing moving average of length len (the first len - 1 positions dropped). */
103
+ function movAvg(x, len) {
104
+ const out = [];
105
+ let s = 0;
106
+ for (let i = 0; i < x.length; i++) {
107
+ s += x[i];
108
+ if (i >= len)
109
+ s -= x[i - len];
110
+ if (i >= len - 1)
111
+ out.push(s / len);
112
+ }
113
+ return out;
114
+ }
115
+ const median = (v) => {
116
+ const s = v.slice().sort((a, b) => a - b);
117
+ const m = s.length >> 1;
118
+ return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
119
+ };
120
+ /**
121
+ * Seasonal-trend decomposition by loess (Cleveland et al. 1990). Equivalent to R's `stl()`. It differs in that the
122
+ * robustness weights use the true median of |remainder| (R takes a wrong order statistic for some even-length series:
123
+ * R bug 19370, see the documentation's departures from R).
124
+ *
125
+ * @category Time series
126
+ */
127
+ export function stl(x, options) {
128
+ checkOptions(options, STL_KEYS, "stl"); // generated: option-keys.mjs
129
+ const y = tsInput(x, "stl");
130
+ const n = y.length;
131
+ const np = options.frequency;
132
+ if (!(np >= 2) || n <= 2 * np)
133
+ throw new RangeError("stl: series is not periodic or has less than two periods");
134
+ const periodic = options.sWindow === "periodic";
135
+ const sWindow = periodic ? 10 * n + 1 : nextOdd(options.sWindow);
136
+ const sDegree = periodic ? 0 : options.sDegree ?? 0;
137
+ const tDegree = options.tDegree ?? 1;
138
+ const lDegree = options.lDegree ?? tDegree;
139
+ const lWindow = nextOdd(options.lWindow ?? np);
140
+ const tWindow = nextOdd(options.tWindow ?? Math.ceil((1.5 * np) / (1 - 1.5 / sWindow)));
141
+ const sJump = options.sJump ?? Math.ceil(sWindow / 10);
142
+ const tJump = options.tJump ?? Math.ceil(tWindow / 10);
143
+ const lJump = options.lJump ?? Math.ceil(lWindow / 10);
144
+ const robust = options.robust ?? false;
145
+ const inner = options.inner ?? (robust ? 1 : 2);
146
+ const outer = options.outer ?? (robust ? 15 : 0);
147
+ let trend = new Array(n).fill(0);
148
+ let rw = new Array(n).fill(1);
149
+ let season = new Array(n).fill(0);
150
+ const ones = new Array(n).fill(1);
151
+ for (let o = 0; o <= outer; o++) {
152
+ for (let it = 0; it < inner; it++) {
153
+ const d = y.map((v, i) => v - trend[i]);
154
+ const C = new Array(n + 2 * np).fill(0);
155
+ for (let p = 0; p < np; p++) {
156
+ const idx = [];
157
+ for (let t = p; t < n; t += np)
158
+ idx.push(t);
159
+ const k = idx.length;
160
+ const dk = idx.map((t) => d[t]);
161
+ const wk = idx.map((t) => rw[t]);
162
+ let sm;
163
+ if (sJump > 1) {
164
+ const at = [];
165
+ for (let t = 1; t <= k; t += sJump)
166
+ at.push(t);
167
+ if (at[at.length - 1] !== k)
168
+ at.push(k);
169
+ const v = loessAt(dk, wk, at, sWindow, sDegree);
170
+ sm = [loessAt(dk, wk, [0], sWindow, sDegree)[0], ...interpolate(at, v, k), loessAt(dk, wk, [k + 1], sWindow, sDegree)[0]];
171
+ }
172
+ else
173
+ sm = loessAt(dk, wk, Array.from({ length: k + 2 }, (_, i) => i), sWindow, sDegree);
174
+ for (let j = 0; j < k + 2; j++)
175
+ C[p + np * j] = sm[j];
176
+ }
177
+ const L = smoothJump(movAvg(movAvg(movAvg(C, np), np), 3), ones, lWindow, lDegree, lJump);
178
+ season = y.map((_, i) => C[np + i] - L[i]);
179
+ trend = smoothJump(y.map((v, i) => v - season[i]), rw, tWindow, tDegree, tJump);
180
+ }
181
+ if (o < outer) {
182
+ const R = y.map((v, i) => Math.abs(v - season[i] - trend[i]));
183
+ // the true median (R bug 19370 takes a wrong order statistic for some even n, log 26-27)
184
+ const h = 6 * median(R);
185
+ // compared without dividing by h, so that an exact fit (h = 0: a constant series) keeps the weights 1 (log 107)
186
+ rw = R.map((r) => { if (r <= 0.001 * h)
187
+ return 1; if (r > 0.999 * h)
188
+ return 0; const u = r / h; return (1 - u * u) ** 2; });
189
+ }
190
+ }
191
+ if (periodic) {
192
+ // the seasonal replaced by its mean at each cycle position
193
+ const sums = new Array(np).fill(0), cnt = new Array(np).fill(0);
194
+ season.forEach((v, i) => { sums[i % np] += v; cnt[i % np]++; });
195
+ season = season.map((_, i) => sums[i % np] / cnt[i % np]);
196
+ }
197
+ return {
198
+ seasonal: season, trend, remainder: y.map((v, i) => v - season[i] - trend[i]), weights: rw,
199
+ win: [sWindow, tWindow, lWindow], deg: [sDegree, tDegree, lDegree], jump: [sJump, tJump, lJump], inner, outer,
200
+ };
201
+ }
202
+ // ---------------------------------------------------------------------------------------------------------------
203
+ // supsmu
204
+ function runLine(x, y, span, cv) {
205
+ const n = x.length;
206
+ let k = Math.max(2, Math.floor((span * n) / 2 + 0.5)); // rounded half up (log 49)
207
+ k = Math.min(k, Math.floor((n - 1) / 2));
208
+ const fit = new Array(n), res = new Array(n);
209
+ const tiny = (1e-3 * (x[n - 1] - x[0])) ** 2;
210
+ const m = 2 * k + 1;
211
+ // the window of 2k + 1 consecutive points kept at that size at the ends (log 48). Its sums are updated as it moves
212
+ // (one point in, one out: O(n) instead of O(n k), log 109), about origins cx, cy (the window's means when the sums
213
+ // are recomputed exactly, every 256 moves, so that rounding does not accumulate)
214
+ let curLo = -1;
215
+ let cx = 0, cy = 0, s1 = 0, t1 = 0, s2 = 0, st = 0;
216
+ let moves = 0;
217
+ const exact = (lo) => {
218
+ let a = 0, b = 0;
219
+ for (let j = lo; j < lo + m; j++) {
220
+ a += x[j];
221
+ b += y[j];
222
+ }
223
+ cx = a / m;
224
+ cy = b / m;
225
+ s1 = 0;
226
+ t1 = 0;
227
+ s2 = 0;
228
+ st = 0;
229
+ for (let j = lo; j < lo + m; j++) {
230
+ const u = x[j] - cx, v = y[j] - cy;
231
+ s1 += u;
232
+ t1 += v;
233
+ s2 += u * u;
234
+ st += u * v;
235
+ }
236
+ moves = 0;
237
+ };
238
+ for (let i = 0; i < n; i++) {
239
+ const lo = Math.max(0, Math.min(i - k, n - 1 - 2 * k));
240
+ if (lo !== curLo) {
241
+ if (curLo < 0 || lo !== curLo + 1 || moves >= 256)
242
+ exact(lo);
243
+ else {
244
+ const uo = x[curLo] - cx, vo = y[curLo] - cy, un = x[lo + m - 1] - cx, vn = y[lo + m - 1] - cy;
245
+ s1 += un - uo;
246
+ t1 += vn - vo;
247
+ s2 += un * un - uo * uo;
248
+ st += un * vn - uo * vo;
249
+ moves++;
250
+ }
251
+ curLo = lo;
252
+ }
253
+ const mu = s1 / m, mv = t1 / m;
254
+ const xm = cx + mu, ym = cy + mv;
255
+ const sxx = s2 - m * mu * mu, sxy = st - m * mu * mv;
256
+ const slope = sxx > tiny;
257
+ const b = slope ? sxy / sxx : 0;
258
+ fit[i] = ym + b * (x[i] - xm);
259
+ if (cv) {
260
+ const hh = 1 / m + (slope ? (x[i] - xm) ** 2 / sxx : 0);
261
+ res[i] = Math.abs(y[i] - fit[i]) / (1 - hh);
262
+ }
263
+ }
264
+ return { fit, res };
265
+ }
266
+ /**
267
+ * Friedman's super smoother (running lines with a cross-validated variable span). Equivalent to R's `supsmu()`.
268
+ * Tied x are not handled as R does.
269
+ *
270
+ * @category Time series
271
+ */
272
+ export function supsmu(x, y, options = {}) {
273
+ checkOptions(options, SUPSMU_KEYS, "supsmu"); // generated: option-keys.mjs
274
+ const ord = x.map((_, i) => i).filter((i) => Number.isFinite(x[i]) && Number.isFinite(y[i])).sort((a, b) => x[a] - x[b]);
275
+ const xs0 = ord.map((i) => x[i]), ys = ord.map((i) => y[i]);
276
+ // the smoother does not depend on the origin and scale of x: x less a large common value and divided by a power of
277
+ // two (exact), so that the span's threshold (1e-3 range)^2 stays in range at x near 1e+-300 (log 110)
278
+ const rx = shiftReference(xs0);
279
+ const cx = powerOfTwoScale(xs0.map((v) => v - rx));
280
+ const xs = rx === 0 && cx === 1 ? xs0 : xs0.map((v) => (v - rx) / cx);
281
+ const span = options.span ?? "cv";
282
+ const bass = options.bass ?? 0;
283
+ if (typeof span === "number")
284
+ return { x: xs0, y: runLine(xs, ys, span, false).fit };
285
+ const sp = [0.05, 0.2, 0.5];
286
+ const fits = sp.map((s) => runLine(xs, ys, s, true));
287
+ const rs = fits.map((f) => runLine(xs, f.res, 0.2, false).fit);
288
+ const n = xs.length;
289
+ const best = new Array(n);
290
+ for (let i = 0; i < n; i++) {
291
+ let b = 0;
292
+ for (let k = 1; k < 3; k++)
293
+ if (rs[k][i] < rs[b][i])
294
+ b = k;
295
+ best[i] = sp[b];
296
+ if (bass > 0) {
297
+ const rmin = rs[b][i], w = rs[2][i];
298
+ if (rmin < w && rmin > 0)
299
+ best[i] = best[i] + (0.5 - best[i]) * Math.max(1e-7, rmin / w) ** (10 - bass);
300
+ }
301
+ }
302
+ const bs = runLine(xs, best, 0.2, false).fit.map((v) => Math.min(0.5, Math.max(0.05, v)));
303
+ const mix = bs.map((s, i) => {
304
+ if (s >= 0.2) {
305
+ const f = (s - 0.2) / 0.3;
306
+ return (1 - f) * fits[1].fit[i] + f * fits[2].fit[i];
307
+ }
308
+ const f = (0.2 - s) / 0.15;
309
+ return (1 - f) * fits[1].fit[i] + f * fits[0].fit[i];
310
+ });
311
+ return { x: xs0, y: runLine(xs, mix, 0.05, false).fit };
312
+ }
313
+ /**
314
+ * forecast's `mstl()` for one seasonal period: stl(x, s.window = 11); for a non-seasonal series (or fewer than two
315
+ * periods) the trend is supsmu(1:n, x).
316
+ * Equivalent to `forecast::mstl()` in R.
317
+ *
318
+ * @category Time series
319
+ */
320
+ export function mstl(x, options = {}) {
321
+ checkOptions(options, MSTL_KEYS, "mstl"); // generated: option-keys.mjs
322
+ const m = options.frequency ?? 1;
323
+ const n = x.length;
324
+ const data = tsInput(x, "mstl", { missing: "allow" });
325
+ // missing values as R's (log 108): the decomposition of naInterp(x), with data and remainder missing there
326
+ if (data.some((v) => Number.isNaN(v))) {
327
+ const r = mstl(naInterp(data, { frequency: m }), options);
328
+ return { ...r, data, remainder: r.remainder.map((v, i) => (Number.isNaN(data[i]) ? NaN : v)) };
329
+ }
330
+ if (m > 1 && n > 2 * m) {
331
+ const r = stl(data, { frequency: m, sWindow: options.sWindow ?? 11, robust: options.robust ?? false });
332
+ return { data, trend: r.trend, seasonal: r.seasonal, remainder: r.remainder, frequency: m };
333
+ }
334
+ const t = supsmu(data.map((_, i) => i + 1), data).y;
335
+ return { data, trend: t, remainder: data.map((v, i) => v - t[i]), frequency: m };
336
+ }
337
+ /**
338
+ * The seasonally adjusted series of an mstl / stl decomposition (data - seasonal). Equivalent to `forecast::seasadj()` in R.
339
+ *
340
+ * @category Time series
341
+ */
342
+ export function seasadj(dec) {
343
+ return dec.seasonal ? dec.data.map((v, i) => v - dec.seasonal[i]) : dec.data.slice();
344
+ }
345
+ const variance = (v) => {
346
+ const m = v.reduce((a, b) => a + b, 0) / v.length;
347
+ return v.reduce((a, b) => a + (b - m) ** 2, 0) / (v.length - 1);
348
+ };
349
+ /**
350
+ * The number of seasonal differences: 1 when the seasonal strength of mstl, max(0, 1 - var(remainder) /
351
+ * var(seasonal + remainder)), exceeds 0.64 (test "seas"), or by the OCSB test. Equivalent to `forecast::nsdiffs()` in R.
352
+ *
353
+ * @category Time series
354
+ */
355
+ export function nsdiffs(x, options) {
356
+ checkOptions(options, NSDIFFS_KEYS, "nsdiffs"); // generated: option-keys.mjs
357
+ const m = options.frequency;
358
+ const maxD = options.maxD ?? 1;
359
+ const test = options.test ?? "seas";
360
+ // the tests do not depend on the scale: the series divided by a power of two (exact), so that 1e+-300 works
361
+ let y = standardise(centred(tsInput(x, "nsdiffs", { missing: "allow" }).filter(Number.isFinite)));
362
+ if (m <= 1 || y.every((v) => v === y[0]))
363
+ return 0;
364
+ let D = 0;
365
+ const dodiff = (v) => {
366
+ if (v.length < 2 * m + 1)
367
+ return false;
368
+ if (test === "seas") {
369
+ const dec = mstl(v, { frequency: m });
370
+ if (!dec.seasonal)
371
+ return false;
372
+ const sr = dec.seasonal.map((s, i) => s + dec.remainder[i]);
373
+ return Math.max(0, 1 - variance(dec.remainder) / variance(sr)) > 0.64;
374
+ }
375
+ // R's nsdiffs calls ocsb.test with lag.method "AIC" and maxlag 3, which fails (and nsdiffs returns 0) when the
376
+ // series has at most m + 5 values. The lag is chosen correctly here, unlike R's off-by-one (ocsbTest, log 89-90)
377
+ if (v.length <= m + 5)
378
+ return false;
379
+ const r = ocsbTest(v, { frequency: m, lagMethod: "AIC", maxlag: 3 });
380
+ return r.statistic > r.critical;
381
+ };
382
+ // a test that fails (a degenerate regression) stops the differencing, as R's (which warns; log 107)
383
+ const tryDiff = (v) => { try {
384
+ return dodiff(v);
385
+ }
386
+ catch {
387
+ return false;
388
+ } };
389
+ while (D < maxD && tryDiff(y)) {
390
+ D++;
391
+ y = y.slice(m).map((v, i) => v - y[i]);
392
+ if (y.every((v) => v === y[0]))
393
+ break;
394
+ }
395
+ return D;
396
+ }
397
+ /**
398
+ * 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.
399
+ *
400
+ * @category Time series
401
+ */
402
+ export function ocsbCritical(m) {
403
+ const i = OCSB_M.indexOf(m);
404
+ if (i >= 0)
405
+ return OCSB_CRITICAL[i];
406
+ const last = OCSB_M.length - 1;
407
+ if (m > OCSB_M[last])
408
+ return OCSB_CRITICAL[last];
409
+ let k = 0;
410
+ while (OCSB_M[k + 1] < m)
411
+ k++;
412
+ const a = Math.log(OCSB_M[k]), b = Math.log(OCSB_M[k + 1]);
413
+ return OCSB_CRITICAL[k] + ((OCSB_CRITICAL[k + 1] - OCSB_CRITICAL[k]) * (Math.log(m) - a)) / (b - a);
414
+ }
415
+ // The OCSB regression with L lags on the rows t >= t0 of y; the AR(L) prefilter of w = Delta_m Delta_1 y is fitted on
416
+ // w's rows from arFrom (L for the test itself, the largest candidate's lag when lags are compared on a common sample).
417
+ function ocsbRegression(y, m, L, t0, arFrom) {
418
+ const n = y.length;
419
+ const dd = (t) => y[t] - y[t - 1] - y[t - m] + y[t - m - 1];
420
+ const dm = (t) => y[t] - y[t - m];
421
+ const d1 = (t) => y[t] - y[t - 1];
422
+ let a = [];
423
+ if (L > 0) {
424
+ const w = [];
425
+ for (let t = m + 1; t < n; t++)
426
+ w.push(dd(t));
427
+ const X = [], Y = [];
428
+ for (let t = arFrom; t < w.length; t++) {
429
+ X.push(Array.from({ length: L }, (_, i) => w[t - 1 - i]));
430
+ Y.push(w[t]);
431
+ }
432
+ a = lm(X, Y, { intercept: false }).coefficients;
433
+ }
434
+ const rows = [], resp = [];
435
+ for (let t = t0; t < n; t++) {
436
+ let z4 = dm(t - 1), z5 = d1(t - m);
437
+ for (let i = 1; i <= L; i++) {
438
+ z4 -= a[i - 1] * dm(t - 1 - i);
439
+ z5 -= a[i - 1] * d1(t - m - i);
440
+ }
441
+ rows.push([...Array.from({ length: L }, (_, i) => dd(t - 1 - i)), z4, z5]);
442
+ resp.push(dd(t));
443
+ }
444
+ return lm(rows, resp, { intercept: false });
445
+ }
446
+ /**
447
+ * The Osborn-Chui-Smith-Birchenhall test for a seasonal unit root: with w = Delta_m Delta_1 y and L lags, the AR(L)
448
+ * coefficients a of w by least squares (no mean), then the regression of w_t on w_{t-1..L} and the two auxiliary
449
+ * 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
450
+ * is the t value of the second (log 41, 80). Equivalent to `forecast::ocsb.test()` in R. With `lagMethod` "fixed" (the
451
+ * default) L = `maxlag` (R's default 0). With "AIC", "BIC" or "AICc" the lags 0..maxlag are compared on a common
452
+ * sample (the rows of maxlag lags, the prefilter too) by the lm criterion with k = coefficients + 1 (AICc = AIC +
453
+ * 2k(k + 1) / (n - k - 1), forecast's help), and the chosen L is used. **This departs from R:** forecast 9.0.2 compares
454
+ * 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
455
+ * decision 2026-11-27 is not to imitate it). Candidates with a perfect fit (and for AICc, n <= k + 1) are skipped.
456
+ *
457
+ * @category Time series
458
+ */
459
+ export function ocsbTest(x, options) {
460
+ checkOptions(options, OCSB_TEST_KEYS, "ocsbTest"); // generated: option-keys.mjs
461
+ // missing values: an error, as R's (log 107)
462
+ const m = options.frequency;
463
+ const y = tsInput(x, "ocsbTest");
464
+ const maxlag = options.maxlag ?? 0;
465
+ const method = options.lagMethod ?? "fixed";
466
+ let L = maxlag;
467
+ if (method !== "fixed" && maxlag > 0) {
468
+ let best = Infinity;
469
+ L = 0;
470
+ for (let cand = 0; cand <= maxlag; cand++) {
471
+ const f = ocsbRegression(y, m, cand, m + 1 + maxlag, maxlag);
472
+ const nobs = f.residuals.length;
473
+ const k = f.rank + 1;
474
+ if (method === "AICc" && nobs - k - 1 <= 0)
475
+ continue;
476
+ const rss = f.residuals.reduce((s, e) => s + e * e, 0);
477
+ if (!(rss > 0))
478
+ continue;
479
+ const aic = nobs * (Math.log((2 * Math.PI * rss) / nobs) + 1) + 2 * k;
480
+ const crit = method === "AIC" ? aic : method === "BIC" ? aic - 2 * k + Math.log(nobs) * k : aic + (2 * k * (k + 1)) / (nobs - k - 1);
481
+ if (crit < best) {
482
+ best = crit;
483
+ L = cand;
484
+ }
485
+ }
486
+ }
487
+ const f = ocsbRegression(y, m, L, m + 1 + L, L);
488
+ return { statistic: f.coefTable.tValue[L + 1], critical: ocsbCritical(m), lagOrder: L };
489
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * A test result of the tseries functions.
3
+ *
4
+ * @category Time series
5
+ */
6
+ export interface TseriesTest {
7
+ statistic: number;
8
+ parameter: number | number[];
9
+ pValue: number;
10
+ method: string;
11
+ }
12
+ /**
13
+ * The augmented Dickey-Fuller test (tseries' `adf.test()`): Delta y_t on 1, t, y_{t-1} and k lagged differences
14
+ * (default k = trunc((n - 1)^(1/3))), the t value of y_{t-1}; p from Fuller's tau_tau table at n - 1 (clamped to
15
+ * [0.01, 0.99]); "explosive" gives 1 - p.
16
+ * Equivalent to `tseries::adf.test()` in R.
17
+ *
18
+ * @category Time series
19
+ */
20
+ export declare function adfTest(x: readonly number[], options?: {
21
+ alternative?: "stationary" | "explosive";
22
+ k?: number;
23
+ }): TseriesTest;
24
+ /**
25
+ * The KPSS test (tseries' `kpss.test()`): the null "Level" or "Trend", truncation lag trunc(4 (n/100)^0.25) (`lshort`)
26
+ * or trunc(12 (n/100)^0.25); p interpolated in the KPSS table (clamped to [0.01, 0.10]).
27
+ * Equivalent to `tseries::kpss.test()` in R.
28
+ *
29
+ * @category Time series
30
+ */
31
+ export declare function kpssTest(x: readonly number[], options?: {
32
+ null?: "Level" | "Trend";
33
+ lshort?: boolean;
34
+ }): TseriesTest;
35
+ /**
36
+ * The Phillips-Perron test (tseries' `pp.test()`): y_t on 1, t, y_{t-1}; Phillips and Perron's closed forms with
37
+ * det(X'X) (log 8), type "Z(alpha)" (default, as R) or "Z(t_alpha)", truncation lag trunc(4 (n/100)^0.25) (`lshort`)
38
+ * or trunc(12 (n/100)^0.25); p from Fuller's n(rho - 1) or tau_tau table at n - 1; "explosive" gives 1 - p.
39
+ * Equivalent to `tseries::pp.test()` in R.
40
+ *
41
+ * @category Time series
42
+ */
43
+ export declare function ppTest(x: readonly number[], options?: {
44
+ alternative?: "stationary" | "explosive";
45
+ type?: "Z(alpha)" | "Z(t_alpha)";
46
+ lshort?: boolean;
47
+ }): TseriesTest;
48
+ /**
49
+ * The Phillips-Ouliaris cointegration test (tseries' `po.test()`): x has 2 to 6 columns (variables) as rows of
50
+ * observations; u = the residuals of the first column on the others (with an intercept when `demean`, default),
51
+ * Z = (n - 1)(rho - 1) - (lambda^2 - s^2) / (2 sum u_{t-1}^2 / (n - 1)^2) from u_t on u_{t-1}; lag trunc((n - 1)/100)
52
+ * (`lshort`) or trunc((n - 1)/30); p from Table Ib / Ia (clamped to [0.01, 0.15]).
53
+ * Equivalent to `tseries::po.test()` in R.
54
+ *
55
+ * @category Time series
56
+ */
57
+ export declare function poTest(x: readonly (readonly number[])[], options?: {
58
+ demean?: boolean;
59
+ lshort?: boolean;
60
+ }): TseriesTest;
61
+ /**
62
+ * The Jarque-Bera test for normality (tseries' `jarque.bera.test()`): n (S^2/6 + (K - 3)^2/24) with the moments over n,
63
+ * chi-squared with 2 df.
64
+ * Equivalent to `tseries::jarque.bera.test()` in R.
65
+ *
66
+ * @category Time series
67
+ */
68
+ export declare function jarqueBeraTest(x: readonly number[]): TseriesTest;
69
+ /**
70
+ * The Wald-Wolfowitz runs test (tseries' `runs.test()`) of a two-valued sequence: z = (R - mean) / sd with mean 1 +
71
+ * 2 n1 n2 / n and variance 2 n1 n2 (2 n1 n2 - n) / (n^2 (n - 1)), normal p for "two.sided" (default), "less" or
72
+ * "greater".
73
+ * Equivalent to `tseries::runs.test()` in R.
74
+ *
75
+ * @category Time series
76
+ */
77
+ export declare function runsTest(x: readonly (boolean | number | string)[], options?: {
78
+ alternative?: "two.sided" | "less" | "greater";
79
+ }): TseriesTest;
80
+ /**
81
+ * Teraesvirta's neural network test for neglected nonlinearity (tseries' `terasvirta.test()`): y_t on 1 and its lags,
82
+ * then also on the second and third order products of the lags; Chisq = n log(SSR0 / SSR1) (n the series length) or
83
+ * F on (df, n - lag - df) (log 14). The series is standardised when `scale` (default).
84
+ * Equivalent to `tseries::terasvirta.test()` in R.
85
+ *
86
+ * @category Time series
87
+ */
88
+ export declare function terasvirtaTest(x: readonly number[], options?: {
89
+ lag?: number;
90
+ type?: "Chisq" | "F";
91
+ scale?: boolean;
92
+ }): TseriesTest;
93
+ /**
94
+ * White's neural network test for neglected nonlinearity (tseries' `white.test()`): q logistic hidden units with
95
+ * weights runif((lag + 1) q, -range/2, range/2) (by columns, the first row on the constant), their principal components
96
+ * 2..qstar + 1 (standardised), then the statistic as {@link terasvirtaTest} (log 15). The weights come from rStats.js's
97
+ * R-compatible generator: with `seed` (R's `set.seed`) the value equals R's; without, the current stream is used.
98
+ * Equivalent to `tseries::white.test()` in R.
99
+ *
100
+ * @category Time series
101
+ */
102
+ export declare function whiteTest(x: readonly number[], options?: {
103
+ lag?: number;
104
+ qstar?: number;
105
+ q?: number;
106
+ range?: number;
107
+ type?: "Chisq" | "F";
108
+ scale?: boolean;
109
+ seed?: number;
110
+ }): TseriesTest;