@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,136 @@
1
+ import { type ArimaResult } from "./arima.js";
2
+ /**
3
+ * The Box-Cox transformation: log(x) for lambda = 0, (sign(x) |x|^lambda - 1) / lambda otherwise. Equivalent to
4
+ * `forecast::BoxCox()` in R.
5
+ *
6
+ * @category Time series
7
+ */
8
+ export declare function boxCox(x: readonly number[], lambda: number): number[];
9
+ /**
10
+ * The inverse Box-Cox transformation (sign-preserving where lambda z + 1 < 0), with forecast's bias adjustment when
11
+ * `fvar` (the forecast variances on the transformed scale) is given and `biasadj` is true. Equivalent to
12
+ * `forecast::InvBoxCox()` in R.
13
+ *
14
+ * @category Time series
15
+ */
16
+ export declare function invBoxCox(z: readonly number[], lambda: number, options?: {
17
+ biasadj?: boolean;
18
+ fvar?: number | readonly number[];
19
+ }): number[];
20
+ /**
21
+ * Chooses the Box-Cox lambda by Guerrero's method (default) or the profile log-likelihood. Equivalent to
22
+ * `forecast::BoxCox.lambda()` in R.
23
+ *
24
+ * @category Time series
25
+ */
26
+ export declare function boxCoxLambda(x: readonly number[], options?: {
27
+ method?: "guerrero" | "loglik";
28
+ lower?: number;
29
+ upper?: number;
30
+ frequency?: number;
31
+ }): number;
32
+ /**
33
+ * Options of {@link forecastArima}.
34
+ *
35
+ * @category Time series
36
+ */
37
+ export interface ForecastArimaOptions {
38
+ order?: readonly [number, number, number];
39
+ seasonal?: readonly [number, number, number];
40
+ frequency?: number;
41
+ xreg?: readonly (readonly number[])[];
42
+ xregNames?: readonly string[];
43
+ includeMean?: boolean;
44
+ includeDrift?: boolean;
45
+ includeConstant?: boolean;
46
+ /** A Box-Cox lambda, or "auto" for {@link boxCoxLambda}. */
47
+ lambda?: number | "auto";
48
+ biasadj?: boolean;
49
+ method?: "CSS-ML" | "ML" | "CSS";
50
+ }
51
+ /**
52
+ * Result of {@link forecastArima}: stats' fit plus forecast's quantities.
53
+ *
54
+ * @category Time series
55
+ */
56
+ export interface ForecastArimaResult extends ArimaResult {
57
+ /** forecast's innovations variance: sum of squared residuals / (nobs - number of coefficients). */
58
+ sigma2: number;
59
+ /** stats' MLE of the innovations variance. */
60
+ sigma2Mle: number;
61
+ aicc: number;
62
+ bic: number;
63
+ lambda: number | null;
64
+ biasadj: boolean;
65
+ /** Fitted values on the original scale. */
66
+ fitted: number[];
67
+ /** The series on the original scale. */
68
+ series: number[];
69
+ /** Whether a drift column was added (the last regressor). */
70
+ drift: boolean;
71
+ }
72
+ /**
73
+ * Fits an ARIMA model as forecast's `Arima()`: stats' arima on the Box-Cox transformed series, with a drift, and
74
+ * forecast's innovations variance, AICc and BIC.
75
+ * Equivalent to `forecast::Arima()` in R.
76
+ *
77
+ * @category Time series
78
+ */
79
+ export declare function forecastArima(y: readonly number[], options?: ForecastArimaOptions): ForecastArimaResult;
80
+ /** forecastArima with all coefficients fixed (autoArima's exact fits, log 108). Not exported from the entries. */
81
+ export declare function forecastArimaFixed(y: readonly number[], options: ForecastArimaOptions, fixed: readonly number[]): ForecastArimaResult;
82
+ /**
83
+ * Result of {@link forecast}.
84
+ *
85
+ * @category Time series
86
+ */
87
+ export interface ForecastResult {
88
+ mean: number[];
89
+ lower: number[][];
90
+ upper: number[][];
91
+ level: number[];
92
+ method: string;
93
+ /** Forecast standard errors on the transformed scale (where analytic). */
94
+ se?: number[];
95
+ }
96
+ /**
97
+ * Point forecasts and prediction intervals from a {@link forecastArima} fit (forecast's `forecast.Arima()`).
98
+ * Equivalent to `forecast::forecast()` in R.
99
+ *
100
+ * @category Time series
101
+ */
102
+ export declare function forecastFromArima(fit: ForecastArimaResult, options?: {
103
+ h?: number;
104
+ level?: readonly number[];
105
+ xreg?: readonly (readonly number[])[];
106
+ biasadj?: boolean;
107
+ }): ForecastResult;
108
+ /**
109
+ * The KPSS statistic with a given truncation lag (residuals on 1, or on 1 and t). Not an R function.
110
+ *
111
+ * @category Time series
112
+ */
113
+ export declare function kpssStatistic(x: readonly number[], type: "level" | "trend", lag: number): number;
114
+ /**
115
+ * The KPSS table's p-value, linear in the statistic between the 10%, 5%, 2.5%, 1% points, clamped to [0.01, 0.10]. Not an R function.
116
+ *
117
+ * @category Time series
118
+ */
119
+ export declare function kpssPValue(stat: number, type: "level" | "trend"): number;
120
+ /**
121
+ * The Phillips-Perron Z(t_alpha) with a constant (y_t on 1, y_{t-1}), lag trunc(4 (n/100)^0.25). Phillips and Perron's
122
+ * form with the lagged level in the sum of squares and det(X'X). R's ndiffs uses urca's ur.pp, which takes the current
123
+ * y_t there (an implementation error, log 88, 90; the user's policy: not imitated), up to 0.05 off in the statistic.
124
+ */
125
+ export declare function ppStatisticConst(y: readonly number[], type: "level" | "trend"): number;
126
+ /**
127
+ * The number of first differences needed for stationarity by a unit root test. Equivalent to `forecast::ndiffs()` in R.
128
+ *
129
+ * @category Time series
130
+ */
131
+ export declare function ndiffs(x: readonly number[], options?: {
132
+ alpha?: number;
133
+ test?: "kpss" | "adf" | "pp";
134
+ type?: "level" | "trend";
135
+ maxD?: number;
136
+ }): number;
@@ -0,0 +1,432 @@
1
+ // forecast's Arima, forecast() for ARIMA fits, the Box-Cox transformation and ndiffs. Written for rStats.js from the
2
+ // behaviour specification oracle/tsmeta-behaviour.md ("forecast's Arima and forecast()", "Simple methods and small
3
+ // functions", "ndiffs, nsdiffs, ocsb.test") with the details found in experiments/tsmeta120-log.md (items 5, 29-30,
4
+ // 39-41). No R or package source was read.
5
+ import { arima, predictArima, registerScaledArima, scaledArima, unscaleArima } from "./arima.js";
6
+ import { centred, powerOfTwoScale, standardise } from "./scale.js";
7
+ import { tsInput } from "./input.js";
8
+ import { optimize } from "../numerics/integrate.js";
9
+ import { lm } from "../models/lm.js";
10
+ import { qnorm } from "../distributions/normal.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 INV_BOX_COX_KEYS = ["biasadj", "fvar"];
14
+ const BOX_COX_LAMBDA_KEYS = ["method", "lower", "upper", "frequency"];
15
+ const FORECAST_ARIMA_KEYS = /* @__PURE__ */ new Set([
16
+ "order", "seasonal", "frequency", "xreg", "xregNames", "includeMean", "includeDrift", "includeConstant", "lambda",
17
+ "biasadj", "method",
18
+ ]);
19
+ const FORECAST_FROM_ARIMA_KEYS = ["h", "level", "xreg", "biasadj"];
20
+ const NDIFFS_KEYS = ["alpha", "test", "type", "maxD"];
21
+ // Generated by `node scripts/option-keys.mjs --write` (end)
22
+ // ---------------------------------------------------------------------------------------------------------------
23
+ // Box-Cox
24
+ /**
25
+ * The Box-Cox transformation: log(x) for lambda = 0, (sign(x) |x|^lambda - 1) / lambda otherwise. Equivalent to
26
+ * `forecast::BoxCox()` in R.
27
+ *
28
+ * @category Time series
29
+ */
30
+ export function boxCox(x, lambda) {
31
+ return x.map((v) => (lambda === 0 ? Math.log(v) : (Math.sign(v) * Math.abs(v) ** lambda - 1) / lambda));
32
+ }
33
+ /**
34
+ * The inverse Box-Cox transformation (sign-preserving where lambda z + 1 < 0), with forecast's bias adjustment when
35
+ * `fvar` (the forecast variances on the transformed scale) is given and `biasadj` is true. Equivalent to
36
+ * `forecast::InvBoxCox()` in R.
37
+ *
38
+ * @category Time series
39
+ */
40
+ export function invBoxCox(z, lambda, options = {}) {
41
+ checkOptions(options, INV_BOX_COX_KEYS, "invBoxCox"); // generated: option-keys.mjs
42
+ const base = z.map((v) => {
43
+ if (lambda === 0)
44
+ return Math.exp(v);
45
+ const t = lambda * v + 1;
46
+ return Math.sign(t) * Math.abs(t) ** (1 / lambda);
47
+ });
48
+ if (!options.biasadj || options.fvar === undefined)
49
+ return base;
50
+ const fv = options.fvar;
51
+ return base.map((b, i) => {
52
+ const v = typeof fv === "number" ? fv : fv[i];
53
+ return b * (1 + (v * (1 - lambda)) / (2 * (lambda * z[i] + 1) ** 2));
54
+ });
55
+ }
56
+ /**
57
+ * Chooses the Box-Cox lambda by Guerrero's method (default) or the profile log-likelihood. Equivalent to
58
+ * `forecast::BoxCox.lambda()` in R.
59
+ *
60
+ * @category Time series
61
+ */
62
+ export function boxCoxLambda(x, options = {}) {
63
+ checkOptions(options, BOX_COX_LAMBDA_KEYS, "boxCoxLambda"); // generated: option-keys.mjs
64
+ const lower = options.lower ?? -1, upper = options.upper ?? 2;
65
+ const m = options.frequency ?? 1;
66
+ // missing values keep their positions (the groups and the trend as R's, log 107); the series divided by a power
67
+ // of two (exact; lambda does not depend on the scale)
68
+ const xa = standardise(tsInput(x, "boxCoxLambda", { missing: "allow", minLength: 2 }));
69
+ if ((options.method ?? "guerrero") === "guerrero") {
70
+ // groups of length max(2, m) taken from the end, the coefficient of variation of sd / mean^(1 - lambda) (log 29-30)
71
+ const len = Math.max(2, m);
72
+ const ng = Math.floor(xa.length / len);
73
+ const tail = xa.slice(xa.length - ng * len);
74
+ const mu = [], sd = [];
75
+ for (let g = 0; g < ng; g++) {
76
+ const v = tail.slice(g * len, (g + 1) * len).filter((a) => !Number.isNaN(a));
77
+ const k = v.length;
78
+ const mean = v.reduce((a, b) => a + b, 0) / k;
79
+ mu.push(mean);
80
+ sd.push(Math.sqrt(v.reduce((a, b) => a + (b - mean) ** 2, 0) / (k - 1)));
81
+ }
82
+ const cv = (lam) => {
83
+ const r = sd.map((s, i) => s / mu[i] ** (1 - lam));
84
+ const mean = r.reduce((a, b) => a + b, 0) / r.length;
85
+ const s2 = r.reduce((a, b) => a + (b - mean) ** 2, 0) / (r.length - 1);
86
+ return Math.sqrt(s2) / mean;
87
+ };
88
+ return optimize(cv, lower, upper).optimum;
89
+ }
90
+ // the profile log-likelihood of lm on a trend (+ seasonal dummies), maximised on the grid seq(lower, upper, 0.05).
91
+ // The transform x^lambda / lambda (log x at 0): the Box-Cox transform without its constant -1 / lambda, which the
92
+ // intercept absorbs, so that x^lambda is not cancelled against 1 (the choice moved with the scale, log 107)
93
+ const tObs = xa.map((_, t) => t).filter((t) => !Number.isNaN(xa[t]));
94
+ const xs = tObs.map((t) => xa[t]);
95
+ const n = xs.length;
96
+ const rows = tObs.map((t) => {
97
+ const r = [t + 1];
98
+ if (m > 1)
99
+ for (let k = 2; k <= m; k++)
100
+ r.push(t % m === k - 1 ? 1 : 0);
101
+ return r;
102
+ });
103
+ const sumLog = xs.reduce((a, b) => a + Math.log(b), 0);
104
+ const pll = (lam) => {
105
+ const z = xs.map((v) => (lam === 0 ? Math.log(v) : v ** lam / lam));
106
+ const f = lm(rows, z, {});
107
+ const sse = f.residuals.reduce((a, b) => a + b * b, 0);
108
+ return (-n / 2) * Math.log(sse / n) + (lam - 1) * sumLog;
109
+ };
110
+ let best = lower, bestV = -Infinity;
111
+ const steps = Math.round((upper - lower) / 0.05);
112
+ for (let i = 0; i <= steps; i++) {
113
+ const lam = lower + 0.05 * i;
114
+ const v = pll(lam);
115
+ if (v > bestV) {
116
+ bestV = v;
117
+ best = lam;
118
+ }
119
+ }
120
+ return best;
121
+ }
122
+ /**
123
+ * Fits an ARIMA model as forecast's `Arima()`: stats' arima on the Box-Cox transformed series, with a drift, and
124
+ * forecast's innovations variance, AICc and BIC.
125
+ * Equivalent to `forecast::Arima()` in R.
126
+ *
127
+ * @category Time series
128
+ */
129
+ export function forecastArima(y, options = {}) {
130
+ checkOptions(options, FORECAST_ARIMA_KEYS, "forecastArima"); // generated: option-keys.mjs
131
+ return forecastArimaCore(y, options);
132
+ }
133
+ /** forecastArima with all coefficients fixed (autoArima's exact fits, log 108). Not exported from the entries. */
134
+ export function forecastArimaFixed(y, options, fixed) {
135
+ return forecastArimaCore(y, options, fixed);
136
+ }
137
+ function forecastArimaCore(y, options, fixed) {
138
+ const order = options.order ?? [0, 0, 0];
139
+ const seasonal = options.seasonal ?? [0, 0, 0];
140
+ const frequency = options.frequency ?? 1;
141
+ const lambda = options.lambda === "auto" ? boxCoxLambda(y, { frequency }) : options.lambda ?? null;
142
+ const z = lambda === null ? y.slice() : boxCox(y, lambda);
143
+ const dd = order[1] + seasonal[1];
144
+ let includeMean = options.includeMean ?? true;
145
+ let drift = options.includeDrift ?? false;
146
+ if (options.includeConstant === true) {
147
+ if (dd === 0)
148
+ includeMean = true;
149
+ else if (dd === 1)
150
+ drift = true;
151
+ }
152
+ else if (options.includeConstant === false) {
153
+ includeMean = false;
154
+ drift = false;
155
+ }
156
+ if (dd > 0)
157
+ includeMean = false;
158
+ if (dd > 1)
159
+ drift = false;
160
+ const n = y.length;
161
+ const xreg = [...(options.xreg ?? []).map((c) => c.slice())];
162
+ const names = [...(options.xregNames ?? (xreg.length === 1 ? ["xreg"] : xreg.map((_, i) => `xreg${i + 1}`)))];
163
+ if (drift) {
164
+ xreg.push(Array.from({ length: n }, (_, i) => i + 1));
165
+ names.push("drift");
166
+ }
167
+ // far from unit scale, the fit of z / c (a power of two) as in arima, and forecast's sigma2 from its residuals, so
168
+ // that the squares stay in range (1.20.0, log 104)
169
+ const c0 = powerOfTwoScale(z);
170
+ const c = Math.abs(Math.log2(c0)) > 200 ? c0 : 1;
171
+ const fitS = arima(c === 1 ? z : z.map((v) => v / c), { order, seasonal: { order: seasonal, period: frequency }, frequency, includeMean, method: options.method ?? "CSS-ML", ...(fixed ? { fixed: fixed.map((v) => v / c) } : {}),
172
+ ...(xreg.length ? { xreg, xregNames: names } : {}) });
173
+ const fit = c === 1 ? fitS : unscaleArima(fitS, c, z);
174
+ const ncoef = fit.coef.length;
175
+ // forecast's sigma2: the sum of all squared residuals (the first d + sD included) / (nobs - coefficients) (log 5)
176
+ const raw = fit.residuals;
177
+ const sigma2S = fitS.residuals.reduce((a, v) => (Number.isNaN(v) ? a : a + v * v), 0) / (fit.nobs - ncoef);
178
+ const sigma2 = sigma2S * c * c;
179
+ const npar = fit.mask.filter(Boolean).length + 1;
180
+ const nstar = fit.nobs;
181
+ const aicc = fit.aic + (2 * npar * (npar + 1)) / (nstar - npar - 1);
182
+ const bic = fit.aic + npar * (Math.log(nstar) - 2);
183
+ const fittedZ = z.map((v, i) => v - raw[i]);
184
+ const biasadj = options.biasadj ?? false;
185
+ const fitted = lambda === null ? fittedZ : invBoxCox(fittedZ, lambda, { biasadj, fvar: sigma2 });
186
+ const out = { ...fit, residuals: raw, sigma2, sigma2Mle: fit.sigma2, aicc, bic, lambda, biasadj, fitted, series: y.slice(), drift };
187
+ if (c !== 1)
188
+ registerScaledArima(out, { ...fitS, sigma2: sigma2S }, c);
189
+ return out;
190
+ }
191
+ /**
192
+ * Point forecasts and prediction intervals from a {@link forecastArima} fit (forecast's `forecast.Arima()`).
193
+ * Equivalent to `forecast::forecast()` in R.
194
+ *
195
+ * @category Time series
196
+ */
197
+ export function forecastFromArima(fit, options = {}) {
198
+ checkOptions(options, FORECAST_FROM_ARIMA_KEYS, "forecastFromArima"); // generated: option-keys.mjs
199
+ const h = options.h ?? (fit.arma[4] > 1 ? 2 * fit.arma[4] : 10);
200
+ const level = [...(options.level ?? [80, 95])];
201
+ const newx = [...(options.xreg ?? []).map((c) => c.slice())];
202
+ if (fit.drift)
203
+ newx.push(Array.from({ length: h }, (_, i) => fit.series.length + i + 1));
204
+ // a fit far from unit scale: from its standardised fit (forecast's sigma2 may be out of range as a square)
205
+ const sc = scaledArima(fit);
206
+ const p = sc
207
+ ? (({ pred, se }) => ({ pred: pred.map((v) => v * sc.c), se: se.map((v) => v * sc.c) }))(predictArima(sc.fit, h, { ...(newx.length ? { newxreg: newx } : {}), sigma2: sc.fit.sigma2 }))
208
+ : predictArima(fit, h, { ...(newx.length ? { newxreg: newx } : {}), sigma2: fit.sigma2 });
209
+ const q = level.map((l) => qnorm(0.5 + l / 200));
210
+ let lower = p.pred.map((m, i) => q.map((qq) => m - qq * p.se[i]));
211
+ let upper = p.pred.map((m, i) => q.map((qq) => m + qq * p.se[i]));
212
+ let mean = p.pred;
213
+ const lam = fit.lambda;
214
+ if (lam !== null) {
215
+ const biasadj = options.biasadj ?? fit.biasadj;
216
+ mean = invBoxCox(p.pred, lam, { biasadj, fvar: p.se.map((s) => s * s) });
217
+ lower = lower.map((row) => invBoxCox(row, lam));
218
+ upper = upper.map((row) => invBoxCox(row, lam));
219
+ }
220
+ return { mean, lower, upper, level, method: arimaMethodName(fit), se: p.se };
221
+ }
222
+ function arimaMethodName(fit) {
223
+ const [p, q, P, Q, s, d, D] = fit.arma;
224
+ let name = `ARIMA(${p},${d},${q})`;
225
+ if (P + D + Q > 0)
226
+ name += `(${P},${D},${Q})[${s}]`;
227
+ // with regressors of the caller's (the fixture shows the case without a mean or drift)
228
+ const userRegs = fit.coefNames.length - fit.arma.slice(0, 4).reduce((a, b) => a + b, 0) - (fit.includeMean ? 1 : 0) - (fit.drift ? 1 : 0);
229
+ if (userRegs > 0)
230
+ return `Regression with ${name} errors`;
231
+ if (fit.drift)
232
+ name += " with drift";
233
+ else if (fit.includeMean)
234
+ name += " with non-zero mean";
235
+ else if (d + D === 0)
236
+ name += " with zero mean";
237
+ return name;
238
+ }
239
+ // ---------------------------------------------------------------------------------------------------------------
240
+ // ndiffs
241
+ const KPSS_TABLE = { level: [0.347, 0.463, 0.574, 0.739], trend: [0.119, 0.146, 0.176, 0.216] };
242
+ const KPSS_P = [0.1, 0.05, 0.025, 0.01];
243
+ /**
244
+ * The KPSS statistic with a given truncation lag (residuals on 1, or on 1 and t). Not an R function.
245
+ *
246
+ * @category Time series
247
+ */
248
+ export function kpssStatistic(x, type, lag) {
249
+ const n = x.length;
250
+ let e;
251
+ if (type === "level") {
252
+ const m = x.reduce((a, b) => a + b, 0) / n;
253
+ e = x.map((v) => v - m);
254
+ }
255
+ else
256
+ e = lm(x.map((_, i) => [i + 1]), x, {}).residuals;
257
+ let v = e.reduce((a, b) => a + b * b, 0) / n;
258
+ for (let s = 1; s <= lag; s++) {
259
+ let c = 0;
260
+ for (let t = s; t < n; t++)
261
+ c += e[t] * e[t - s];
262
+ v += (2 * (1 - s / (lag + 1)) * c) / n;
263
+ }
264
+ let cum = 0, sum = 0;
265
+ for (const ei of e) {
266
+ cum += ei;
267
+ sum += cum * cum;
268
+ }
269
+ return sum / (n * n * v);
270
+ }
271
+ /**
272
+ * The KPSS table's p-value, linear in the statistic between the 10%, 5%, 2.5%, 1% points, clamped to [0.01, 0.10]. Not an R function.
273
+ *
274
+ * @category Time series
275
+ */
276
+ export function kpssPValue(stat, type) {
277
+ const T = KPSS_TABLE[type];
278
+ if (stat <= T[0])
279
+ return 0.1;
280
+ if (stat >= T[3])
281
+ return 0.01;
282
+ for (let i = 0; i < 3; i++)
283
+ if (stat <= T[i + 1])
284
+ return KPSS_P[i] + ((KPSS_P[i + 1] - KPSS_P[i]) * (stat - T[i])) / (T[i + 1] - T[i]);
285
+ return 0.01;
286
+ }
287
+ // Dickey-Fuller critical values by size class n <= 25, 50, 100, 250, 500, more (1%, 5%, 10%; Fuller 1976)
288
+ const DF_SIZES = [25, 50, 100, 250, 500, Infinity];
289
+ const TAU_MU = [[-3.75, -3.58, -3.51, -3.46, -3.44, -3.43], [-3.0, -2.93, -2.89, -2.88, -2.87, -2.86], [-2.63, -2.6, -2.58, -2.57, -2.57, -2.57]];
290
+ const TAU_TAU = [[-4.38, -4.15, -4.04, -3.99, -3.98, -3.96], [-3.6, -3.5, -3.45, -3.43, -3.42, -3.41], [-3.24, -3.18, -3.15, -3.13, -3.13, -3.12]];
291
+ function dfPValue(stat, n, type) {
292
+ const row = DF_SIZES.findIndex((b) => n <= b);
293
+ const tab = type === "level" ? TAU_MU : TAU_TAU;
294
+ const c = [tab[0][row], tab[1][row], tab[2][row]];
295
+ const P = [0.01, 0.05, 0.1];
296
+ if (stat <= c[0])
297
+ return 0.01;
298
+ if (stat >= c[2])
299
+ return 0.1;
300
+ for (let k = 0; k < 2; k++)
301
+ if (stat <= c[k + 1])
302
+ return P[k] + ((P[k + 1] - P[k]) * (stat - c[k])) / (c[k + 1] - c[k]);
303
+ return 0.1;
304
+ }
305
+ // MacKinnon's (1991) response surfaces b0 + b1/N + b2/N^2 for the 1%, 5%, 10% points (constant; constant and trend):
306
+ // R's ndiffs(test = "pp") interpolates in urca's ur.pp critical values, which equal these at N = n - 1 (log 85: 0
307
+ // difference in 80 series)
308
+ const MACKINNON = {
309
+ level: [[-3.4335, -5.999, -29.25], [-2.8621, -2.738, -8.36], [-2.5671, -1.438, -4.48]],
310
+ trend: [[-3.9638, -8.353, -47.44], [-3.4126, -4.039, -17.83], [-3.1279, -2.418, -7.58]],
311
+ };
312
+ function ppPValue(stat, n, type) {
313
+ const N = n - 1;
314
+ const c = MACKINNON[type].map(([b0, b1, b2]) => b0 + b1 / N + b2 / (N * N));
315
+ const P = [0.01, 0.05, 0.1];
316
+ if (stat <= c[0])
317
+ return 0.01;
318
+ if (stat >= c[2])
319
+ return 0.1;
320
+ for (let k = 0; k < 2; k++)
321
+ if (stat <= c[k + 1])
322
+ return P[k] + ((P[k + 1] - P[k]) * (stat - c[k])) / (c[k + 1] - c[k]);
323
+ return 0.1;
324
+ }
325
+ /** The t value of the lagged level in the ADF regression with one lagged difference. */
326
+ function adfStatisticK1(y, type) {
327
+ const n = y.length;
328
+ const rows = [];
329
+ const resp = [];
330
+ for (let t = 2; t < n; t++) {
331
+ const r = [y[t - 1], y[t - 1] - y[t - 2]];
332
+ if (type === "trend")
333
+ r.unshift(t);
334
+ rows.push(r);
335
+ resp.push(y[t] - y[t - 1]);
336
+ }
337
+ const f = lm(rows, resp, {});
338
+ const j = type === "trend" ? 2 : 1;
339
+ return f.coefTable.tValue[j];
340
+ }
341
+ /**
342
+ * The Phillips-Perron Z(t_alpha) with a constant (y_t on 1, y_{t-1}), lag trunc(4 (n/100)^0.25). Phillips and Perron's
343
+ * form with the lagged level in the sum of squares and det(X'X). R's ndiffs uses urca's ur.pp, which takes the current
344
+ * y_t there (an implementation error, log 88, 90; the user's policy: not imitated), up to 0.05 off in the statistic.
345
+ */
346
+ export function ppStatisticConst(y, type) {
347
+ const n = y.length;
348
+ const nn = n - 1;
349
+ const rows = [];
350
+ const resp = [];
351
+ for (let t = 1; t < n; t++) {
352
+ rows.push(type === "trend" ? [t, y[t - 1]] : [y[t - 1]]);
353
+ resp.push(y[t]);
354
+ }
355
+ const f = lm(rows, resp, {});
356
+ const j = type === "trend" ? 2 : 1;
357
+ const rho = f.coefficients[j];
358
+ const se = f.coefTable.stdError[j];
359
+ const u = f.residuals;
360
+ const l = Math.trunc(4 * (nn / 100) ** 0.25);
361
+ const su2 = u.reduce((a, b) => a + b * b, 0) / nn;
362
+ let lam = su2;
363
+ for (let s = 1; s <= l; s++) {
364
+ let c = 0;
365
+ for (let t = s; t < nn; t++)
366
+ c += u[t] * u[t - s];
367
+ lam += (2 * (1 - s / (l + 1)) * c) / nn;
368
+ }
369
+ const tr = (rho - 1) / se;
370
+ if (type === "trend") {
371
+ // Phillips and Perron's closed form with a trend (as tseries' pp.test, log 8): det(X'X) of X = (1, t, y_{t-1})
372
+ let s00 = 0, s01 = 0, s02 = 0, s11 = 0, s12 = 0, s22 = 0;
373
+ for (let t = 1; t < n; t++) {
374
+ const a = t, b = y[t - 1];
375
+ s00 += 1;
376
+ s01 += a;
377
+ s02 += b;
378
+ s11 += a * a;
379
+ s12 += a * b;
380
+ s22 += b * b;
381
+ }
382
+ const det = s00 * (s11 * s22 - s12 * s12) - s01 * (s01 * s22 - s12 * s02) + s02 * (s01 * s12 - s11 * s02);
383
+ return Math.sqrt(su2 / lam) * tr - ((lam - su2) * nn ** 3) / (4 * Math.sqrt(3) * Math.sqrt(det) * Math.sqrt(lam));
384
+ }
385
+ const yl = y.slice(0, n - 1);
386
+ const ym = yl.reduce((a, b) => a + b, 0) / nn;
387
+ const sxx = yl.reduce((a, b) => a + (b - ym) ** 2, 0);
388
+ return Math.sqrt(su2 / lam) * tr - ((lam - su2) * nn) / (2 * Math.sqrt(lam) * Math.sqrt(sxx));
389
+ }
390
+ /**
391
+ * The number of first differences needed for stationarity by a unit root test. Equivalent to `forecast::ndiffs()` in R.
392
+ *
393
+ * @category Time series
394
+ */
395
+ export function ndiffs(x, options = {}) {
396
+ checkOptions(options, NDIFFS_KEYS, "ndiffs"); // generated: option-keys.mjs
397
+ const alpha = options.alpha ?? 0.05;
398
+ const test = options.test ?? "kpss";
399
+ const type = options.type ?? "level";
400
+ const maxD = options.maxD ?? 2;
401
+ // the tests do not depend on the scale: the series divided by a power of two (exact), so that 1e+-300 works
402
+ let y = standardise(centred(tsInput(x, "ndiffs", { missing: "allow" }).filter(Number.isFinite)));
403
+ const isConstant = (v) => v.every((a) => a === v[0]);
404
+ if (isConstant(y))
405
+ return 0;
406
+ let d = 0;
407
+ const dodiff = (v) => {
408
+ // a statistic that is not finite (too few values for the regression) is a failed test (log 107)
409
+ const stat = test === "kpss" ? kpssStatistic(v, type, Math.trunc((3 * Math.sqrt(v.length)) / 13)) : test === "adf" ? adfStatisticK1(v, type) : ppStatisticConst(v, type);
410
+ if (!Number.isFinite(stat))
411
+ throw new RangeError("ndiffs: the test statistic is not finite");
412
+ if (test === "kpss")
413
+ return kpssPValue(stat, type) < alpha;
414
+ if (test === "adf")
415
+ return dfPValue(stat, v.length, type) > alpha;
416
+ return ppPValue(stat, v.length, type) > alpha;
417
+ };
418
+ // a test that fails (too short a series, a degenerate regression) stops the differencing, as R's (which warns; log 107)
419
+ const tryDiff = (v) => { try {
420
+ return dodiff(v);
421
+ }
422
+ catch {
423
+ return false;
424
+ } };
425
+ while (d < maxD && tryDiff(y)) {
426
+ d++;
427
+ y = y.slice(1).map((v, i) => v - y[i]);
428
+ if (isConstant(y))
429
+ break;
430
+ }
431
+ return d;
432
+ }
@@ -0,0 +1,83 @@
1
+ import type { ArimaResult } from "./arima.js";
2
+ import { type EtsResult } from "./ets.js";
3
+ import { type ForecastArimaResult } from "./forecastArima.js";
4
+ import { type HoltWintersResult } from "./holtWinters.js";
5
+ import { type ArResult } from "./statsTs.js";
6
+ import { type MstlResult } from "./stl.js";
7
+ /**
8
+ * Result of {@link stlm}.
9
+ *
10
+ * @category Time series
11
+ */
12
+ export interface StlmResult {
13
+ kind: "stlm";
14
+ /** The decomposition of the (Box-Cox transformed) series. */
15
+ stl: MstlResult;
16
+ /** The model of the seasonally adjusted series. */
17
+ model: EtsResult | ForecastArimaResult;
18
+ /** The seasonally adjusted series (transformed scale). */
19
+ adjusted: number[];
20
+ /** The in-sample fit on the original scale. */
21
+ fitted: number[];
22
+ residuals: number[];
23
+ frequency: number;
24
+ lambda: number | null;
25
+ biasadj: boolean;
26
+ }
27
+ /**
28
+ * A forecast of {@link forecast}.
29
+ *
30
+ * @category Time series
31
+ */
32
+ export interface ForecastOutput {
33
+ mean: number[];
34
+ lower: number[][];
35
+ upper: number[][];
36
+ level: number[];
37
+ method: string;
38
+ }
39
+ /**
40
+ * STL decomposition with a model of the seasonally adjusted series (forecast's `stlm()`): mstl of the series (Box-Cox
41
+ * transformed with `lambda`), then `ets(adjusted, etsModel)` (default "ZZN") or, with `method: "arima"`,
42
+ * `auto.arima(adjusted, seasonal = FALSE)` (log 93: R's model has no seasonal part).
43
+ * Equivalent to `forecast::stlm()` in R.
44
+ *
45
+ * @category Time series
46
+ */
47
+ export declare function stlm(y: readonly number[], options: {
48
+ frequency: number;
49
+ method?: "ets" | "arima";
50
+ etsModel?: string;
51
+ sWindow?: number | "periodic";
52
+ robust?: boolean;
53
+ lambda?: number;
54
+ biasadj?: boolean;
55
+ }): StlmResult;
56
+ /**
57
+ * Forecasts from an {@link stlm} fit (forecast's `forecast.stlm()`): the model's forecasts of the seasonally adjusted
58
+ * series plus the last cycle of the seasonal component, back-transformed with the fit's lambda.
59
+ * Equivalent to `forecast::forecast()` in R.
60
+ *
61
+ * @category Time series
62
+ */
63
+ export declare function forecastStlm(fit: StlmResult, options?: {
64
+ h?: number;
65
+ level?: readonly number[];
66
+ }): ForecastOutput;
67
+ /**
68
+ * Forecasts from a series or a fitted model (forecast's `forecast()`):
69
+ * - a series (`frequency` in the options): ets, or stlf when the period is 13 or more and the series is longer than
70
+ * two periods (forecast's help; log 93);
71
+ * - an {@link ets} fit, a {@link forecastArima} / {@link autoArima} fit, a stats {@link arima} fit (with its MLE
72
+ * innovations variance), an {@link stlm} fit, a {@link holtWinters} fit (stats' prediction intervals) or an
73
+ * {@link ar} fit (normal intervals from the prediction standard errors).
74
+ * `h` defaults to twice the period for seasonal data, else 10.
75
+ * Equivalent to `forecast::forecast()` in R.
76
+ *
77
+ * @category Time series
78
+ */
79
+ export declare function forecast(object: readonly number[] | EtsResult | ForecastArimaResult | ArimaResult | StlmResult | HoltWintersResult | ArResult, options?: {
80
+ h?: number;
81
+ level?: readonly number[];
82
+ frequency?: number;
83
+ }): ForecastOutput;