@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,130 @@
1
+ // forecast's stlm and the forecast() methods (forecast.ts, forecast.ets, forecast.Arima, forecast.stlm,
2
+ // forecast.HoltWinters, forecast.ar). Written for rStats.js from the behaviour specification oracle/tsmeta-behaviour.md
3
+ // with the details found in experiments/tsmeta120-log.md (item 93) and forecast's help pages. No R or package source
4
+ // was read.
5
+ import { qnorm } from "../distributions/normal.js";
6
+ import { autoArima } from "./autoArima.js";
7
+ import { ets, forecastEts } from "./ets.js";
8
+ import { boxCox, forecastFromArima, invBoxCox } from "./forecastArima.js";
9
+ import { predictHoltWinters } from "./holtWinters.js";
10
+ import { predictAr } from "./statsTs.js";
11
+ import { mstl } from "./stl.js";
12
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
13
+ import { checkOptions } from "../internal/checkOptions.js";
14
+ const STLM_KEYS = ["frequency", "method", "etsModel", "sWindow", "robust", "lambda", "biasadj"];
15
+ const FORECAST_STLM_KEYS = ["h", "level"];
16
+ const FORECAST_KEYS = ["h", "level", "frequency"];
17
+ /**
18
+ * STL decomposition with a model of the seasonally adjusted series (forecast's `stlm()`): mstl of the series (Box-Cox
19
+ * transformed with `lambda`), then `ets(adjusted, etsModel)` (default "ZZN") or, with `method: "arima"`,
20
+ * `auto.arima(adjusted, seasonal = FALSE)` (log 93: R's model has no seasonal part).
21
+ * Equivalent to `forecast::stlm()` in R.
22
+ *
23
+ * @category Time series
24
+ */
25
+ export function stlm(y, options) {
26
+ checkOptions(options, STLM_KEYS, "stlm"); // generated: option-keys.mjs
27
+ const m = options.frequency;
28
+ const lambda = options.lambda ?? null;
29
+ const biasadj = options.biasadj ?? false;
30
+ const x = lambda === null ? y.map(Number) : boxCox(y, lambda);
31
+ const dec = mstl(x, { frequency: m, ...(options.sWindow !== undefined ? { sWindow: options.sWindow } : {}), ...(options.robust !== undefined ? { robust: options.robust } : {}) });
32
+ const seas = dec.seasonal ?? new Array(x.length).fill(0);
33
+ const adjusted = x.map((v, i) => v - seas[i]);
34
+ const model = options.method === "arima"
35
+ ? autoArima(adjusted, { frequency: m, seasonal: false })
36
+ : ets(adjusted, { model: options.etsModel ?? "ZZN" });
37
+ const fitAdj = model.fitted;
38
+ const fittedT = fitAdj.map((v, i) => v + seas[i]);
39
+ const fitted = lambda === null ? fittedT : invBoxCox(fittedT, lambda);
40
+ return { kind: "stlm", stl: dec, model, adjusted, fitted, residuals: y.map((v, i) => v - fitted[i]), frequency: m, lambda, biasadj };
41
+ }
42
+ /**
43
+ * Forecasts from an {@link stlm} fit (forecast's `forecast.stlm()`): the model's forecasts of the seasonally adjusted
44
+ * series plus the last cycle of the seasonal component, back-transformed with the fit's lambda.
45
+ * Equivalent to `forecast::forecast()` in R.
46
+ *
47
+ * @category Time series
48
+ */
49
+ export function forecastStlm(fit, options = {}) {
50
+ checkOptions(options, FORECAST_STLM_KEYS, "forecastStlm"); // generated: option-keys.mjs
51
+ const m = fit.frequency;
52
+ const h = options.h ?? 2 * m;
53
+ const level = [...(options.level ?? [80, 95])];
54
+ const fc = "spec" in fit.model ? forecastEts(fit.model, { h, level }) : forecastFromArima(fit.model, { h, level });
55
+ const seas = fit.stl.seasonal ?? new Array(fit.adjusted.length).fill(0);
56
+ const last = seas.slice(seas.length - m);
57
+ const add = (i) => last[i % m] ?? 0;
58
+ let mean = fc.mean.map((v, i) => v + add(i));
59
+ let lower = fc.lower.map((r, i) => r.map((v) => v + add(i)));
60
+ let upper = fc.upper.map((r, i) => r.map((v) => v + add(i)));
61
+ if (fit.lambda !== null) {
62
+ const lam = fit.lambda;
63
+ mean = invBoxCox(mean, lam);
64
+ lower = lower.map((r) => invBoxCox(r, lam));
65
+ upper = upper.map((r) => invBoxCox(r, lam));
66
+ }
67
+ return { mean, lower, upper, level, method: `STL + ${fc.method}` };
68
+ }
69
+ const isEts = (o) => "spec" in o && "par" in o;
70
+ const isForecastArima = (o) => "arma" in o && "sigma2Mle" in o;
71
+ const isArima = (o) => "arma" in o && "mask" in o;
72
+ const isHoltWinters = (o) => "SSE" in o && "coefficientNames" in o;
73
+ const isAr = (o) => "varPred" in o && "order" in o;
74
+ const isStlm = (o) => o.kind === "stlm";
75
+ /**
76
+ * Forecasts from a series or a fitted model (forecast's `forecast()`):
77
+ * - a series (`frequency` in the options): ets, or stlf when the period is 13 or more and the series is longer than
78
+ * two periods (forecast's help; log 93);
79
+ * - an {@link ets} fit, a {@link forecastArima} / {@link autoArima} fit, a stats {@link arima} fit (with its MLE
80
+ * innovations variance), an {@link stlm} fit, a {@link holtWinters} fit (stats' prediction intervals) or an
81
+ * {@link ar} fit (normal intervals from the prediction standard errors).
82
+ * `h` defaults to twice the period for seasonal data, else 10.
83
+ * Equivalent to `forecast::forecast()` in R.
84
+ *
85
+ * @category Time series
86
+ */
87
+ export function forecast(object, options = {}) {
88
+ checkOptions(options, FORECAST_KEYS, "forecast"); // generated: option-keys.mjs
89
+ const level = [...(options.level ?? [80, 95])];
90
+ const hFor = (m) => options.h ?? (m > 1 ? 2 * m : 10);
91
+ if (Array.isArray(object)) {
92
+ const y = object.map(Number);
93
+ const m = options.frequency ?? 1;
94
+ if (m > 12 && y.length > 2 * m)
95
+ return forecastStlm(stlm(y, { frequency: m }), { h: hFor(m), level });
96
+ const f = ets(y, { frequency: m });
97
+ const fc = forecastEts(f, { h: hFor(m), level });
98
+ return { mean: fc.mean, lower: fc.lower, upper: fc.upper, level, method: fc.method };
99
+ }
100
+ const o = object;
101
+ if (isStlm(o))
102
+ return forecastStlm(o, { h: hFor(o.frequency), level });
103
+ if (isEts(o)) {
104
+ const fc = forecastEts(o, { h: hFor(o.spec.m), level });
105
+ return { mean: fc.mean, lower: fc.lower, upper: fc.upper, level, method: fc.method };
106
+ }
107
+ if (isForecastArima(o)) {
108
+ const fc = forecastFromArima(o, { h: hFor(o.arma[4]), level });
109
+ return { mean: fc.mean, lower: fc.lower, upper: fc.upper, level, method: fc.method };
110
+ }
111
+ if (isArima(o)) {
112
+ // a stats arima: no transformation or drift, its MLE variance
113
+ const fa = { ...o, sigma2Mle: o.sigma2, aicc: NaN, bic: NaN, lambda: null, biasadj: false, fitted: o.x.map((v, i) => v - o.residuals[i]), series: o.x.slice(), drift: false };
114
+ const fc = forecastFromArima(fa, { h: hFor(o.arma[4]), level });
115
+ return { mean: fc.mean, lower: fc.lower, upper: fc.upper, level, method: fc.method };
116
+ }
117
+ if (isHoltWinters(o)) {
118
+ const h = hFor(o.frequency);
119
+ const mean = predictHoltWinters(o, { nAhead: h }).fit;
120
+ const bands = level.map((l) => predictHoltWinters(o, { nAhead: h, predictionInterval: true, level: l / 100 }));
121
+ return { mean, lower: mean.map((_, i) => bands.map((b) => b.lwr[i])), upper: mean.map((_, i) => bands.map((b) => b.upr[i])), level, method: "HoltWinters" };
122
+ }
123
+ if (isAr(o)) {
124
+ const h = hFor(1);
125
+ const p = predictAr(o, h);
126
+ const q = level.map((l) => qnorm(0.5 + l / 200));
127
+ return { mean: p.pred, lower: p.pred.map((v, i) => q.map((z) => v - z * p.se[i])), upper: p.pred.map((v, i) => q.map((z) => v + z * p.se[i])), level, method: `AR(${o.order})` };
128
+ }
129
+ throw new TypeError("forecast: unsupported object");
130
+ }
@@ -0,0 +1,177 @@
1
+ import { type EtsResult } from "./ets.js";
2
+ /**
3
+ * A forecast with intervals and the in-sample fit.
4
+ *
5
+ * @category Time series
6
+ */
7
+ export interface SimpleForecast {
8
+ mean: number[];
9
+ lower: number[][];
10
+ upper: number[][];
11
+ level: number[];
12
+ fitted: number[];
13
+ residuals: number[];
14
+ method: string;
15
+ /** The ets model behind ses / holt / hw / stlf. */
16
+ model?: EtsResult;
17
+ }
18
+ /**
19
+ * Forecasts by the mean (forecast's `meanf()`): intervals mean +- qt(level, n - 1) sd(y) sqrt(1 + 1/n).
20
+ * Equivalent to `forecast::meanf()` in R.
21
+ *
22
+ * @category Time series
23
+ */
24
+ export declare function meanf(y: readonly number[], options?: {
25
+ h?: number;
26
+ level?: readonly number[];
27
+ }): SimpleForecast;
28
+ /**
29
+ * Random walk forecasts (forecast's `rwf()`), with a drift (y_n - y_1)/(n - 1) when `drift`. sigma = sqrt(mean(res^2))
30
+ * without a drift, sd(res) with one; se_h = sigma sqrt(h) or sigma sqrt(h (1 + h/(n - 1))).
31
+ * Equivalent to `forecast::rwf()` in R.
32
+ *
33
+ * @category Time series
34
+ */
35
+ export declare function rwf(y: readonly number[], options?: {
36
+ h?: number;
37
+ drift?: boolean;
38
+ level?: readonly number[];
39
+ lag?: number;
40
+ }): SimpleForecast;
41
+ /**
42
+ * Naive forecasts (forecast's `naive()`): {@link rwf} without a drift. Equivalent to `forecast::naive()` in R.
43
+ *
44
+ * @category Time series
45
+ */
46
+ export declare function naive(y: readonly number[], options?: {
47
+ h?: number;
48
+ level?: readonly number[];
49
+ }): SimpleForecast;
50
+ /**
51
+ * Seasonal naive forecasts (forecast's `snaive()`): y_{n - m + ...}, se_h = sigma sqrt(floor((h - 1)/m) + 1). Equivalent to `forecast::snaive()` in R.
52
+ *
53
+ * @category Time series
54
+ */
55
+ export declare function snaive(y: readonly number[], options: {
56
+ frequency: number;
57
+ h?: number;
58
+ level?: readonly number[];
59
+ }): SimpleForecast;
60
+ /**
61
+ * Simple exponential smoothing (forecast's `ses()`): ets(y, "ANN"), or with `initial: "simple"` the level started at
62
+ * y_1 and alpha minimising the one-step SSE.
63
+ * Equivalent to `forecast::ses()` in R.
64
+ *
65
+ * @category Time series
66
+ */
67
+ export declare function ses(y: readonly number[], options?: {
68
+ h?: number;
69
+ level?: readonly number[];
70
+ initial?: "optimal" | "simple";
71
+ alpha?: number;
72
+ }): SimpleForecast;
73
+ /**
74
+ * Holt's linear trend method (forecast's `holt()`): ets AAN (AAdN damped, MMN exponential); `initial: "simple"`
75
+ * starts at l = y_1, b = y_2 - y_1.
76
+ * Equivalent to `forecast::holt()` in R.
77
+ *
78
+ * @category Time series
79
+ */
80
+ export declare function holt(y: readonly number[], options?: {
81
+ h?: number;
82
+ level?: readonly number[];
83
+ damped?: boolean;
84
+ exponential?: boolean;
85
+ initial?: "optimal" | "simple";
86
+ }): SimpleForecast;
87
+ /**
88
+ * Holt-Winters seasonal method (forecast's `hw()`): ets AAA or MAM (damped: AAdA, MAdM); `initial: "simple"` starts at
89
+ * l = mean(y[1:m]), b = (mean(y[m+1:2m]) - mean(y[1:m]))/m, s = y[1:m] - l (or / l).
90
+ * Equivalent to `forecast::hw()` in R.
91
+ *
92
+ * @category Time series
93
+ */
94
+ export declare function hw(y: readonly number[], options: {
95
+ frequency: number;
96
+ h?: number;
97
+ level?: readonly number[];
98
+ seasonal?: "additive" | "multiplicative";
99
+ damped?: boolean;
100
+ initial?: "optimal" | "simple";
101
+ }): SimpleForecast;
102
+ /**
103
+ * The theta method (forecast's `thetaf()`): a seasonality test |r_m| > qnorm(0.95) sqrt((1 + 2 sum_{i<m} r_i^2)/n), a
104
+ * multiplicative decompose when seasonal, ses by MSE, mean = ses mean + b/2 (h - 1 + 1/alpha - (1 - alpha)^n / alpha)
105
+ * with b the slope of lm(y ~ t), reseasonalised. Departs from R when seasonal: the interval bounds are reseasonalised
106
+ * (R adds the adjusted-scale width to the reseasonalised mean) and the residuals are y - fitted (R's are on the
107
+ * adjusted scale); the user's decision, log 91-92.
108
+ * Equivalent to `forecast::thetaf()` in R.
109
+ *
110
+ * @category Time series
111
+ */
112
+ export declare function thetaf(y: readonly number[], options?: {
113
+ frequency?: number;
114
+ h?: number;
115
+ level?: readonly number[];
116
+ }): SimpleForecast;
117
+ /**
118
+ * Croston's method for intermittent demand (forecast's `croston()`): SES with alpha on the non-zero demands and on the
119
+ * intervals between them (counted from time 0), each started at its first value; forecast k z / p with k = 1 (croston),
120
+ * 1 - alpha/2 (sba) or 1 - alpha/(2 - alpha) (sbj). No intervals. Departs from R when the last observation is a
121
+ * demand: R's forecast is the state before it (the last fitted value, the last observation unused; log 91), rStats.js
122
+ * forecasts from the state after it.
123
+ * Equivalent to `forecast::croston()` in R.
124
+ *
125
+ * @category Time series
126
+ */
127
+ export declare function croston(y: readonly number[], options?: {
128
+ h?: number;
129
+ alpha?: number;
130
+ type?: "croston" | "sba" | "sbj";
131
+ }): {
132
+ mean: number[];
133
+ fitted: number[];
134
+ method: string;
135
+ };
136
+ /**
137
+ * STL + ETS forecasts (forecast's `stlf()`): mstl(y), forecast(ets(seasonally adjusted, "ZZN")), plus the last cycle of
138
+ * the seasonal component repeated.
139
+ * Equivalent to `forecast::stlf()` in R.
140
+ *
141
+ * @category Time series
142
+ */
143
+ export declare function stlf(y: readonly number[], options: {
144
+ frequency: number;
145
+ h?: number;
146
+ level?: readonly number[];
147
+ }): SimpleForecast;
148
+ /**
149
+ * Result of {@link tslm}.
150
+ *
151
+ * @category Time series
152
+ */
153
+ export interface TslmResult {
154
+ coefficients: number[];
155
+ coefficientNames: string[];
156
+ fitted: number[];
157
+ residuals: number[];
158
+ /** Forecasts with t intervals from the regression. */
159
+ forecast: (h: number, level?: readonly number[]) => {
160
+ mean: number[];
161
+ lower: number[][];
162
+ upper: number[][];
163
+ level: number[];
164
+ };
165
+ }
166
+ /**
167
+ * Linear regression on a trend (1..n) and seasonal dummies (forecast's `tslm(y ~ trend + season)`), the first season
168
+ * the baseline.
169
+ * Equivalent to `forecast::tslm()` in R.
170
+ *
171
+ * @category Time series
172
+ */
173
+ export declare function tslm(y: readonly number[], options?: {
174
+ frequency?: number;
175
+ trend?: boolean;
176
+ season?: boolean;
177
+ }): TslmResult;
@@ -0,0 +1,371 @@
1
+ // forecast's simple methods: meanf, naive, snaive, rwf, ses, holt, hw, thetaf, croston, stlf / stlm and tslm. Written
2
+ // for rStats.js from the behaviour specification oracle/tsmeta-behaviour.md ("Simple methods and small functions") with
3
+ // the details found in experiments/tsmeta120-log.md (items 28-35, 47, 51). No R or package source was read.
4
+ import { qnorm } from "../distributions/normal.js";
5
+ import { qt } from "../distributions/t.js";
6
+ import { lm } from "../models/lm.js";
7
+ import { ets, etsFixedInitial, forecastEts } from "./ets.js";
8
+ import { decompose } from "./statsTs.js";
9
+ import { mstl } from "./stl.js";
10
+ import { centred, powerOfTwoScale, shiftReference, standardise } from "./scale.js";
11
+ import { tsInput } from "./input.js";
12
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
13
+ import { checkOptions } from "../internal/checkOptions.js";
14
+ const MEANF_KEYS = ["h", "level"];
15
+ const RWF_KEYS = ["h", "drift", "level", "lag"];
16
+ const NAIVE_KEYS = ["h", "level"];
17
+ const SNAIVE_KEYS = ["frequency", "h", "level"];
18
+ const SES_KEYS = ["h", "level", "initial", "alpha"];
19
+ const HOLT_KEYS = ["h", "level", "damped", "exponential", "initial"];
20
+ const HW_KEYS = ["frequency", "h", "level", "seasonal", "damped", "initial"];
21
+ const THETAF_KEYS = ["frequency", "h", "level"];
22
+ const CROSTON_KEYS = ["h", "alpha", "type"];
23
+ const STLF_KEYS = ["frequency", "h", "level"];
24
+ const TSLM_KEYS = ["frequency", "trend", "season"];
25
+ const meanOf = (v) => v.reduce((a, b) => a + b, 0) / v.length;
26
+ const sdOf = (v) => { const m = meanOf(v); return Math.sqrt(v.reduce((a, b) => a + (b - m) ** 2, 0) / (v.length - 1)); };
27
+ const intervals = (mean, se, level, q) => ({
28
+ lower: mean.map((m, i) => level.map((l) => m - q(l) * se[i])), upper: mean.map((m, i) => level.map((l) => m + q(l) * se[i])),
29
+ });
30
+ const zq = (l) => qnorm(0.5 + l / 200);
31
+ /**
32
+ * Forecasts by the mean (forecast's `meanf()`): intervals mean +- qt(level, n - 1) sd(y) sqrt(1 + 1/n).
33
+ * Equivalent to `forecast::meanf()` in R.
34
+ *
35
+ * @category Time series
36
+ */
37
+ export function meanf(y, options = {}) {
38
+ checkOptions(options, MEANF_KEYS, "meanf"); // generated: option-keys.mjs
39
+ const h = options.h ?? 10;
40
+ const level = [...(options.level ?? [80, 95])];
41
+ const x = tsInput(y, "meanf", { missing: "allow" }).filter(Number.isFinite);
42
+ const n = x.length;
43
+ // sd of the series divided by a power of two c (exact), times c: no overflow of the squares
44
+ const c = powerOfTwoScale(x);
45
+ const mu = meanOf(x);
46
+ const s = c * sdOf(x.map((v) => v / c)) * Math.sqrt(1 + 1 / n);
47
+ const mean = new Array(h).fill(mu);
48
+ const iv = intervals(mean, new Array(h).fill(s), level, (l) => qt(0.5 + l / 200, n - 1));
49
+ return { mean, ...iv, level, fitted: y.map(() => mu), residuals: y.map((v) => v - mu), method: "Mean" };
50
+ }
51
+ /**
52
+ * Random walk forecasts (forecast's `rwf()`), with a drift (y_n - y_1)/(n - 1) when `drift`. sigma = sqrt(mean(res^2))
53
+ * without a drift, sd(res) with one; se_h = sigma sqrt(h) or sigma sqrt(h (1 + h/(n - 1))).
54
+ * Equivalent to `forecast::rwf()` in R.
55
+ *
56
+ * @category Time series
57
+ */
58
+ export function rwf(y, options = {}) {
59
+ checkOptions(options, RWF_KEYS, "rwf"); // generated: option-keys.mjs
60
+ const h = options.h ?? 10;
61
+ const level = [...(options.level ?? [80, 95])];
62
+ const drift = options.drift ?? false;
63
+ const lag = options.lag ?? 1;
64
+ // a missing value is skipped by the residual sd; at least lag + 1 values (R fails at n <= lag; log 107)
65
+ y = tsInput(y, "rwf", { missing: "allow", minLength: lag + 1 });
66
+ // with missing values as R's (log 108): the fitted value is the last observed value of the same season (y_{t - j lag},
67
+ // the smallest j with it observed), and the drift the mean of those steps (equal to 1e-16 in the intervals)
68
+ const n = y.length;
69
+ const prev = y.map((_, t) => { for (let k = t - lag; k >= 0; k -= lag)
70
+ if (!Number.isNaN(y[k]))
71
+ return y[k]; return NaN; });
72
+ const steps = y.map((v, t) => v - prev[t]).filter(Number.isFinite);
73
+ const b = drift ? steps.reduce((a, v) => a + v, 0) / steps.length : 0;
74
+ const fitted = prev.map((v) => v + b);
75
+ const residuals = y.map((v, t) => v - fitted[t]);
76
+ const res = residuals.filter(Number.isFinite);
77
+ // on the residuals divided by a power of two c (exact), times c: no overflow of the squares
78
+ const c = powerOfTwoScale(res);
79
+ const rs = res.map((r) => r / c);
80
+ const sigma = c * (drift ? sdOf(rs) : Math.sqrt(meanOf(rs.map((r) => r * r))));
81
+ const mean = Array.from({ length: h }, (_, i) => (lag === 1 ? y[n - 1] + (i + 1) * b : y[n - lag + (i % lag)]));
82
+ const se = Array.from({ length: h }, (_, i) => {
83
+ const k = i + 1;
84
+ if (lag > 1)
85
+ return sigma * Math.sqrt(Math.floor((k - 1) / lag) + 1);
86
+ return drift ? sigma * Math.sqrt(k * (1 + k / steps.length)) : sigma * Math.sqrt(k);
87
+ });
88
+ return { mean, ...intervals(mean, se, level, zq), level, fitted, residuals,
89
+ method: lag > 1 ? "Seasonal naive method" : drift ? "Random walk with drift" : "Random walk" };
90
+ }
91
+ /**
92
+ * Naive forecasts (forecast's `naive()`): {@link rwf} without a drift. Equivalent to `forecast::naive()` in R.
93
+ *
94
+ * @category Time series
95
+ */
96
+ export function naive(y, options = {}) {
97
+ checkOptions(options, NAIVE_KEYS, "naive"); // generated: option-keys.mjs
98
+ return { ...rwf(y, options), method: "Naive method" };
99
+ }
100
+ /**
101
+ * Seasonal naive forecasts (forecast's `snaive()`): y_{n - m + ...}, se_h = sigma sqrt(floor((h - 1)/m) + 1). Equivalent to `forecast::snaive()` in R.
102
+ *
103
+ * @category Time series
104
+ */
105
+ export function snaive(y, options) {
106
+ checkOptions(options, SNAIVE_KEYS, "snaive"); // generated: option-keys.mjs
107
+ return rwf(y, { h: options.h ?? 2 * options.frequency, lag: options.frequency, ...(options.level ? { level: options.level } : {}) });
108
+ }
109
+ function fromEts(fit, h, level, method, simple = false) {
110
+ // initial = "simple": R's sigma2 is SSE / n (log 91). R's hw(initial = "simple") also puts its Holt-Winters beta*
111
+ // (beta = alpha beta*) into the ets variance as if it were beta; rStats.js uses the model's beta (a departure)
112
+ if (simple)
113
+ fit.sigma2 = fit.residuals.reduce((a, v) => a + v * v, 0) / fit.x.length;
114
+ const fc = forecastEts(fit, { h, level });
115
+ // as R's: the model's innovations (relative for multiplicative errors) for an ets fit, y - fitted with
116
+ // initial = "simple" (log 91)
117
+ const residuals = simple ? fit.x.map((v, i) => v - fit.fitted[i]) : fit.residuals.slice();
118
+ return { mean: fc.mean, lower: fc.lower, upper: fc.upper, level, fitted: fit.fitted, residuals, method, model: fit };
119
+ }
120
+ /**
121
+ * Simple exponential smoothing (forecast's `ses()`): ets(y, "ANN"), or with `initial: "simple"` the level started at
122
+ * y_1 and alpha minimising the one-step SSE.
123
+ * Equivalent to `forecast::ses()` in R.
124
+ *
125
+ * @category Time series
126
+ */
127
+ export function ses(y, options = {}) {
128
+ checkOptions(options, SES_KEYS, "ses"); // generated: option-keys.mjs
129
+ const h = options.h ?? 10;
130
+ const level = [...(options.level ?? [80, 95])];
131
+ const fixed = options.alpha !== undefined ? { alpha: options.alpha } : {};
132
+ const fit = options.initial === "simple"
133
+ ? etsFixedInitial(y, { error: "A", trend: "N", damped: false, season: "N", m: 1 }, { l: y[0] }, fixed, "mse", "simple")
134
+ : ets(y, { model: "ANN", ...fixed });
135
+ return fromEts(fit, h, level, "Simple exponential smoothing", options.initial === "simple");
136
+ }
137
+ /**
138
+ * Holt's linear trend method (forecast's `holt()`): ets AAN (AAdN damped, MMN exponential); `initial: "simple"`
139
+ * starts at l = y_1, b = y_2 - y_1.
140
+ * Equivalent to `forecast::holt()` in R.
141
+ *
142
+ * @category Time series
143
+ */
144
+ export function holt(y, options = {}) {
145
+ checkOptions(options, HOLT_KEYS, "holt"); // generated: option-keys.mjs
146
+ const h = options.h ?? 10;
147
+ const level = [...(options.level ?? [80, 95])];
148
+ const damped = options.damped ?? false;
149
+ const expo = options.exponential ?? false;
150
+ const spec = { error: expo ? "M" : "A", trend: expo ? "M" : "A", damped, season: "N", m: 1 };
151
+ const fit = options.initial === "simple"
152
+ ? etsFixedInitial(y, spec, expo ? { l: y[0], b: y[1] / y[0] } : { l: y[0], b: y[1] - y[0] }, {}, "mse", "simple")
153
+ : ets(y, { model: expo ? "MMN" : "AAN", damped });
154
+ const method = damped ? (expo ? "Damped Holt's method with exponential trend" : "Damped Holt's method") : expo ? "Holt's method with exponential trend" : "Holt's method";
155
+ return fromEts(fit, h, level, method, options.initial === "simple");
156
+ }
157
+ /**
158
+ * Holt-Winters seasonal method (forecast's `hw()`): ets AAA or MAM (damped: AAdA, MAdM); `initial: "simple"` starts at
159
+ * l = mean(y[1:m]), b = (mean(y[m+1:2m]) - mean(y[1:m]))/m, s = y[1:m] - l (or / l).
160
+ * Equivalent to `forecast::hw()` in R.
161
+ *
162
+ * @category Time series
163
+ */
164
+ export function hw(y, options) {
165
+ checkOptions(options, HW_KEYS, "hw"); // generated: option-keys.mjs
166
+ const m = options.frequency;
167
+ const h = options.h ?? 2 * m;
168
+ const level = [...(options.level ?? [80, 95])];
169
+ const mult = options.seasonal === "multiplicative";
170
+ const damped = options.damped ?? false;
171
+ // R's minimum (log 109: "I need at least m + 3 observations to estimate seasonality", 15 for m = 12, 7 for m = 4)
172
+ if (y.length < m + 3)
173
+ throw new RangeError(`hw: at least ${m + 3} observations are needed to estimate seasonality (got ${y.length})`);
174
+ const spec = { error: mult ? "M" : "A", trend: "A", damped, season: mult ? "M" : "A", m };
175
+ let fit;
176
+ if (options.initial === "simple") {
177
+ const l = meanOf(y.slice(0, m));
178
+ const b = (meanOf(y.slice(m, 2 * m)) - l) / m;
179
+ // s1 = the most recent (period m), ..., sm = period 1
180
+ const s = y.slice(0, m).map((v) => (mult ? v / l : v - l)).reverse();
181
+ fit = etsFixedInitial(y, spec, { l, b, s }, {}, "mse", "simple");
182
+ }
183
+ else
184
+ fit = ets(y, { frequency: m, model: mult ? "MAM" : "AAA", damped });
185
+ const method = `${damped ? "Damped " : ""}Holt-Winters' ${mult ? "multiplicative" : "additive"} method`;
186
+ return fromEts(fit, h, level, method, options.initial === "simple");
187
+ }
188
+ /** The lag-k autocorrelations (mean removed, over n). */
189
+ function acfValues(x0, maxLag) {
190
+ const x = standardise(centred(x0));
191
+ const n = x.length;
192
+ const m = meanOf(x);
193
+ const c0 = x.reduce((a, v) => a + (v - m) ** 2, 0) / n;
194
+ return Array.from({ length: maxLag }, (_, k) => { let s = 0; for (let t = k + 1; t < n; t++)
195
+ s += (x[t] - m) * (x[t - k - 1] - m); return s / n / c0; });
196
+ }
197
+ /**
198
+ * The theta method (forecast's `thetaf()`): a seasonality test |r_m| > qnorm(0.95) sqrt((1 + 2 sum_{i<m} r_i^2)/n), a
199
+ * multiplicative decompose when seasonal, ses by MSE, mean = ses mean + b/2 (h - 1 + 1/alpha - (1 - alpha)^n / alpha)
200
+ * with b the slope of lm(y ~ t), reseasonalised. Departs from R when seasonal: the interval bounds are reseasonalised
201
+ * (R adds the adjusted-scale width to the reseasonalised mean) and the residuals are y - fitted (R's are on the
202
+ * adjusted scale); the user's decision, log 91-92.
203
+ * Equivalent to `forecast::thetaf()` in R.
204
+ *
205
+ * @category Time series
206
+ */
207
+ export function thetaf(y, options = {}) {
208
+ checkOptions(options, THETAF_KEYS, "thetaf"); // generated: option-keys.mjs
209
+ const m = options.frequency ?? 1;
210
+ const h = options.h ?? (m > 1 ? 2 * m : 10);
211
+ const level = [...(options.level ?? [80, 95])];
212
+ // missing values: an error, as R's (log 107)
213
+ y = tsInput(y, "thetaf");
214
+ const n = y.length;
215
+ let seasonal = false;
216
+ if (m > 1 && n >= 2 * m) {
217
+ const r = acfValues(y, m);
218
+ const stat = Math.abs(r[m - 1]);
219
+ const crit = qnorm(0.95) * Math.sqrt((1 + 2 * r.slice(0, m - 1).reduce((a, v) => a + v * v, 0)) / n);
220
+ seasonal = stat > crit;
221
+ }
222
+ let adj = y.slice();
223
+ let sidx = [];
224
+ if (seasonal) {
225
+ const d = decompose(y, { frequency: m, type: "multiplicative" });
226
+ sidx = d.figure;
227
+ adj = y.map((v, i) => v / sidx[i % m]);
228
+ }
229
+ const fit = ets(adj, { model: "ANN", optCrit: "mse" });
230
+ const alpha = fit.par.alpha;
231
+ const fc = forecastEts(fit, { h, level });
232
+ const b = lm(adj.map((_, t) => [t + 1]), adj, {}).coefficients[1];
233
+ const add = Array.from({ length: h }, (_, i) => (b / 2) * (i + 1 - 1 + 1 / alpha - (1 - alpha) ** n / alpha));
234
+ const seasonOf = (k) => (seasonal ? sidx[(n + k) % m] : 1);
235
+ const mean = fc.mean.map((v, i) => (v + add[i]) * seasonOf(i));
236
+ const lower = fc.lower.map((row, i) => row.map((v) => (v + add[i]) * seasonOf(i)));
237
+ const upper = fc.upper.map((row, i) => row.map((v) => (v + add[i]) * seasonOf(i)));
238
+ const fitted = fit.fitted.map((v, i) => v * (seasonal ? sidx[i % m] : 1));
239
+ return { mean, lower, upper, level, fitted, residuals: y.map((v, i) => v - fitted[i]), method: "Theta" };
240
+ }
241
+ /**
242
+ * Croston's method for intermittent demand (forecast's `croston()`): SES with alpha on the non-zero demands and on the
243
+ * intervals between them (counted from time 0), each started at its first value; forecast k z / p with k = 1 (croston),
244
+ * 1 - alpha/2 (sba) or 1 - alpha/(2 - alpha) (sbj). No intervals. Departs from R when the last observation is a
245
+ * demand: R's forecast is the state before it (the last fitted value, the last observation unused; log 91), rStats.js
246
+ * forecasts from the state after it.
247
+ * Equivalent to `forecast::croston()` in R.
248
+ *
249
+ * @category Time series
250
+ */
251
+ export function croston(y, options = {}) {
252
+ checkOptions(options, CROSTON_KEYS, "croston"); // generated: option-keys.mjs
253
+ const h = options.h ?? 10;
254
+ const alpha = options.alpha ?? 0.1;
255
+ const type = options.type ?? "croston";
256
+ const k = type === "croston" ? 1 : type === "sba" ? 1 - alpha / 2 : 1 - alpha / (2 - alpha);
257
+ // at least two demands (the first starts the smoothing of the sizes and of the intervals), as R's; missing values
258
+ // an error (log 107)
259
+ y = tsInput(y, "croston");
260
+ if (y.filter((v) => v !== 0).length < 2)
261
+ throw new RangeError("croston: at least two non-zero values are needed");
262
+ const n = y.length;
263
+ const fitted = new Array(n).fill(NaN);
264
+ let z = NaN, p = NaN;
265
+ let last = 0; // time of the last demand (time 0 before the series)
266
+ for (let t = 0; t < n; t++) {
267
+ if (t > 0)
268
+ fitted[t] = Number.isNaN(z) ? 0 : (k * z) / p;
269
+ if (y[t] !== 0) {
270
+ const interval = t + 1 - last;
271
+ last = t + 1;
272
+ if (Number.isNaN(z)) {
273
+ z = y[t];
274
+ p = interval;
275
+ }
276
+ else {
277
+ z += alpha * (y[t] - z);
278
+ p += alpha * (interval - p);
279
+ }
280
+ }
281
+ }
282
+ const f = Number.isNaN(z) ? 0 : (k * z) / p;
283
+ return { mean: new Array(h).fill(f), fitted, method: "Croston's method" };
284
+ }
285
+ /**
286
+ * STL + ETS forecasts (forecast's `stlf()`): mstl(y), forecast(ets(seasonally adjusted, "ZZN")), plus the last cycle of
287
+ * the seasonal component repeated.
288
+ * Equivalent to `forecast::stlf()` in R.
289
+ *
290
+ * @category Time series
291
+ */
292
+ export function stlf(y, options) {
293
+ checkOptions(options, STLF_KEYS, "stlf"); // generated: option-keys.mjs
294
+ const m = options.frequency;
295
+ const h = options.h ?? 2 * m;
296
+ const level = [...(options.level ?? [80, 95])];
297
+ const d = mstl(y, { frequency: m });
298
+ const seas = d.seasonal ?? new Array(y.length).fill(0);
299
+ const adj = y.map((v, i) => v - seas[i]);
300
+ const fit = ets(adj, { model: "ZZN" });
301
+ const fc = forecastEts(fit, { h, level });
302
+ // without a seasonal component (fewer than two periods: mstl's trend only) the forecasts are not reseasonalised
303
+ const n = y.length;
304
+ const lastCycle = seas.slice(n - m);
305
+ const sAt = (i) => (d.seasonal ? lastCycle[i % m] : 0);
306
+ const fitted = fit.fitted.map((v, i) => v + seas[i]);
307
+ return { mean: fc.mean.map((v, i) => v + sAt(i)), lower: fc.lower.map((r, i) => r.map((v) => v + sAt(i))), upper: fc.upper.map((r, i) => r.map((v) => v + sAt(i))),
308
+ level, fitted, residuals: y.map((v, i) => v - fitted[i]), method: `STL + ${fit.method}`, model: fit };
309
+ }
310
+ /**
311
+ * Linear regression on a trend (1..n) and seasonal dummies (forecast's `tslm(y ~ trend + season)`), the first season
312
+ * the baseline.
313
+ * Equivalent to `forecast::tslm()` in R.
314
+ *
315
+ * @category Time series
316
+ */
317
+ export function tslm(y, options = {}) {
318
+ checkOptions(options, TSLM_KEYS, "tslm"); // generated: option-keys.mjs
319
+ const m = options.frequency ?? 1;
320
+ const useT = options.trend ?? true;
321
+ const useS = (options.season ?? true) && m > 1;
322
+ const row = (t) => [...(useT ? [t + 1] : []), ...(useS ? Array.from({ length: m - 1 }, (_, k) => (t % m === k + 1 ? 1 : 0)) : [])];
323
+ y = tsInput(y, "tslm", { missing: "allow", minLength: 2 });
324
+ // fitted to (y - r) / c (r a large common value, c a power of two; exact) and mapped back: the sums of squares stay in
325
+ // range at 1e+-300 and the seasonal coefficients keep their digits at y + 1e15 (log 110)
326
+ const r0 = shiftReference(y);
327
+ const c0 = powerOfTwoScale(y.map((v) => v - r0));
328
+ const n = y.length;
329
+ const X = y.map((_, t) => row(t));
330
+ const fs = lm(X, y.map((v) => (v - r0) / c0), {});
331
+ const f = { coefficients: fs.coefficients.map((b, j) => b * c0 + (j === 0 ? r0 : 0)), fittedValues: fs.fittedValues.map((v) => v * c0 + r0),
332
+ residuals: fs.residuals.map((v) => v * c0) };
333
+ const names = ["(Intercept)", ...(useT ? ["trend"] : []), ...(useS ? Array.from({ length: m - 1 }, (_, k) => `season${k + 2}`) : [])];
334
+ const Xf = X.map((r) => [1, ...r]);
335
+ const k = Xf[0].length;
336
+ // (X'X)^{-1} for the prediction variances
337
+ const A = Array.from({ length: k }, (_, i) => Array.from({ length: k }, (_, j) => Xf.reduce((s, r) => s + r[i] * r[j], 0)));
338
+ const inv = invert(A);
339
+ const s2 = fs.residuals.reduce((a, v) => (Number.isNaN(v) ? a : a + v * v), 0) / (n - k);
340
+ return {
341
+ coefficients: f.coefficients, coefficientNames: names, fitted: f.fittedValues, residuals: f.residuals,
342
+ forecast: (h, lev = [80, 95]) => {
343
+ const rows = Array.from({ length: h }, (_, i) => [1, ...row(n + i)]);
344
+ const mean = rows.map((r) => r0 + c0 * r.reduce((s, v, j) => s + v * fs.coefficients[j], 0));
345
+ const se = rows.map((r) => c0 * Math.sqrt(s2 * (1 + r.reduce((s, v, i) => s + v * r.reduce((s2_, w, j) => s2_ + inv[i][j] * w, 0), 0))));
346
+ const level = [...lev];
347
+ return { mean, ...intervals(mean, se, level, (l) => qt(0.5 + l / 200, n - k)), level };
348
+ },
349
+ };
350
+ }
351
+ function invert(A) {
352
+ const k = A.length;
353
+ const M = A.map((r, i) => [...r, ...Array.from({ length: k }, (_, j) => (i === j ? 1 : 0))]);
354
+ for (let i = 0; i < k; i++) {
355
+ let p = i;
356
+ for (let r = i + 1; r < k; r++)
357
+ if (Math.abs(M[r][i]) > Math.abs(M[p][i]))
358
+ p = r;
359
+ [M[i], M[p]] = [M[p], M[i]];
360
+ const d = M[i][i];
361
+ for (let c = 0; c < 2 * k; c++)
362
+ M[i][c] /= d;
363
+ for (let r = 0; r < k; r++)
364
+ if (r !== i) {
365
+ const f = M[r][i];
366
+ for (let c = 0; c < 2 * k; c++)
367
+ M[r][c] -= f * M[i][c];
368
+ }
369
+ }
370
+ return M.map((r) => r.slice(k));
371
+ }