@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.
- package/CHANGELOG.md +52 -0
- package/README.ja.md +7 -7
- package/README.md +7 -7
- package/dist/causal.js +2 -2
- package/dist/chunks/chunk-33ODAPMR.js +2 -0
- package/dist/chunks/chunk-3ST6RZXG.js +2 -0
- package/dist/chunks/{chunk-JF4PXFJE.js → chunk-4EQN74JN.js} +2 -2
- package/dist/chunks/chunk-5RRFO4NU.js +2 -0
- package/dist/chunks/{chunk-3JFRDXN7.js → chunk-64DDDGJU.js} +2 -2
- package/dist/chunks/chunk-66TEOHPF.js +2 -0
- package/dist/chunks/chunk-6ISDROPG.js +2 -0
- package/dist/chunks/{chunk-EC77KAAM.js → chunk-6LAKI2QG.js} +2 -2
- package/dist/chunks/{chunk-5CTWYFMB.js → chunk-6QCH4LAL.js} +2 -2
- package/dist/chunks/{chunk-H6Z7JVSD.js → chunk-6RA73LXX.js} +2 -2
- package/dist/chunks/{chunk-KJMLQHCY.js → chunk-7C2ECGT6.js} +1 -1
- package/dist/chunks/{chunk-SCFFHEDZ.js → chunk-7KPFNJBE.js} +2 -2
- package/dist/chunks/chunk-ARPXG2PG.js +2 -0
- package/dist/chunks/chunk-AWXW4WSX.js +2 -0
- package/dist/chunks/{chunk-XQCHC3SH.js → chunk-B5GSH3AK.js} +1 -1
- package/dist/chunks/{chunk-2JB7F646.js → chunk-BLDLJHUG.js} +2 -2
- package/dist/chunks/{chunk-IKMW63BE.js → chunk-BU4I544S.js} +2 -2
- package/dist/chunks/{chunk-LCIX76FR.js → chunk-CAUNJ7S6.js} +2 -2
- package/dist/chunks/chunk-DFGW4QWU.js +2 -0
- package/dist/chunks/{chunk-WYVUCQO3.js → chunk-DPCCSFCG.js} +1 -1
- package/dist/chunks/chunk-EXS5QD7V.js +2 -0
- package/dist/chunks/chunk-FOCHNNP3.js +2 -0
- package/dist/chunks/{chunk-MXZ64QME.js → chunk-HEPGGURG.js} +2 -2
- package/dist/chunks/chunk-INNFAVT3.js +2 -0
- package/dist/chunks/chunk-JEELIABM.js +2 -0
- package/dist/chunks/chunk-KNF2GPJV.js +2 -0
- package/dist/chunks/chunk-L4ZS7MAX.js +2 -0
- package/dist/chunks/{chunk-RXYZQ3UX.js → chunk-LZAB4M7P.js} +2 -2
- package/dist/chunks/chunk-LZTDYQRS.js +3 -0
- package/dist/chunks/{chunk-N7BUE54L.js → chunk-MTSU2QHB.js} +2 -2
- package/dist/chunks/{chunk-GIK34P23.js → chunk-MXRN2G7O.js} +2 -2
- package/dist/chunks/chunk-OFDD4GTZ.js +2 -0
- package/dist/chunks/chunk-OOHFFLMY.js +2 -0
- package/dist/chunks/chunk-OOO5AAM7.js +2 -0
- package/dist/chunks/chunk-PJJJR3H6.js +2 -0
- package/dist/chunks/chunk-PVRNAOO7.js +2 -0
- package/dist/chunks/chunk-Q2JLU5YD.js +2 -0
- package/dist/chunks/{chunk-Z33Q545U.js → chunk-QCQBK5AC.js} +2 -2
- package/dist/chunks/chunk-RXK4KSKH.js +2 -0
- package/dist/chunks/chunk-UC3YYJHM.js +4 -0
- package/dist/chunks/chunk-UPACHZ4F.js +2 -0
- package/dist/chunks/{chunk-VATAUY7N.js → chunk-VCXPGCA4.js} +2 -2
- package/dist/chunks/chunk-VFL4GGYT.js +2 -0
- package/dist/chunks/chunk-VL72MQOQ.js +2 -0
- package/dist/chunks/chunk-VSV5QGXX.js +2 -0
- package/dist/chunks/{chunk-CTZUYKVL.js → chunk-WMEF5XWO.js} +2 -2
- package/dist/chunks/chunk-X6JS6ZZB.js +2 -0
- package/dist/chunks/chunk-YEDVOX5V.js +2 -0
- package/dist/chunks/chunk-ZCTB4N5J.js +3 -0
- package/dist/descriptive.js +2 -2
- package/dist/distributions/normal.d.ts +4 -0
- package/dist/distributions/normal.js +4 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/tests.d.ts +6 -0
- package/dist/entries/tests.js +6 -0
- package/dist/entries/timeseries.d.ts +11 -0
- package/dist/entries/timeseries.js +11 -0
- package/dist/htest/timeROC.d.ts +564 -0
- package/dist/htest/timeROC.js +1106 -0
- package/dist/linalg.js +2 -2
- package/dist/meta/metabin.d.ts +32 -0
- package/dist/meta/metabin.js +137 -0
- package/dist/meta/metaextra.d.ts +153 -0
- package/dist/meta/metaextra.js +290 -0
- package/dist/meta/metagen.d.ts +124 -0
- package/dist/meta/metagen.js +263 -0
- package/dist/meta/metaother.d.ts +87 -0
- package/dist/meta/metaother.js +342 -0
- package/dist/meta/netmeta.d.ts +256 -0
- package/dist/meta/netmeta.js +547 -0
- package/dist/mixed.js +3 -4
- package/dist/models/glmFamily.js +4 -1
- package/dist/models/metaAnalysis.d.ts +4 -0
- package/dist/models/metaAnalysis.js +100 -18
- package/dist/multivariate.js +2 -2
- package/dist/numerics.js +2 -2
- package/dist/regression.js +2 -2
- package/dist/rstats.js +20 -18
- package/dist/special.js +2 -2
- package/dist/tests.js +15 -15
- package/dist/timeseries/acf.js +5 -2
- package/dist/timeseries/arima.d.ts +154 -0
- package/dist/timeseries/arima.js +1007 -0
- package/dist/timeseries/autoArima.d.ts +70 -0
- package/dist/timeseries/autoArima.js +191 -0
- package/dist/timeseries/ets.d.ts +158 -0
- package/dist/timeseries/ets.js +883 -0
- package/dist/timeseries/forecastArima.d.ts +136 -0
- package/dist/timeseries/forecastArima.js +432 -0
- package/dist/timeseries/forecastDispatch.d.ts +83 -0
- package/dist/timeseries/forecastDispatch.js +130 -0
- package/dist/timeseries/forecastSimple.d.ts +177 -0
- package/dist/timeseries/forecastSimple.js +371 -0
- package/dist/timeseries/forecastUtils.d.ts +260 -0
- package/dist/timeseries/forecastUtils.js +619 -0
- package/dist/timeseries/holtWinters.d.ts +65 -0
- package/dist/timeseries/holtWinters.js +193 -0
- package/dist/timeseries/input.d.ts +8 -0
- package/dist/timeseries/input.js +27 -0
- package/dist/timeseries/ocsbCritical.d.ts +2 -0
- package/dist/timeseries/ocsbCritical.js +6 -0
- package/dist/timeseries/scale.d.ts +16 -0
- package/dist/timeseries/scale.js +48 -0
- package/dist/timeseries/statsTs.d.ts +128 -0
- package/dist/timeseries/statsTs.js +456 -0
- package/dist/timeseries/stl.d.ts +131 -0
- package/dist/timeseries/stl.js +489 -0
- package/dist/timeseries/tseries.d.ts +110 -0
- package/dist/timeseries/tseries.js +369 -0
- package/dist/timeseries.js +2 -2
- package/package.json +1 -1
- package/dist/chunks/chunk-53WQDB3C.js +0 -2
- package/dist/chunks/chunk-6I23C2YJ.js +0 -2
- package/dist/chunks/chunk-FLFNMSHI.js +0 -3
- package/dist/chunks/chunk-GEHMND3C.js +0 -2
- package/dist/chunks/chunk-HG4LJBNV.js +0 -2
- package/dist/chunks/chunk-HGAEVPVS.js +0 -2
- package/dist/chunks/chunk-HMLYEFQN.js +0 -2
- package/dist/chunks/chunk-HRRCC2BD.js +0 -2
- package/dist/chunks/chunk-IBHMM2SL.js +0 -2
- package/dist/chunks/chunk-ICDW3I2F.js +0 -2
- package/dist/chunks/chunk-IOJVFYHW.js +0 -2
- package/dist/chunks/chunk-IW4S634O.js +0 -2
- package/dist/chunks/chunk-JPWYGTUN.js +0 -2
- package/dist/chunks/chunk-KVJBCT3D.js +0 -2
- package/dist/chunks/chunk-LY5XGFPU.js +0 -2
- package/dist/chunks/chunk-MKZH65DK.js +0 -2
- package/dist/chunks/chunk-MVPHISOV.js +0 -2
- package/dist/chunks/chunk-NDZVVNBB.js +0 -2
- package/dist/chunks/chunk-NOTJ45G3.js +0 -4
- package/dist/chunks/chunk-QUD3374N.js +0 -2
- package/dist/chunks/chunk-V6FMGGUV.js +0 -2
- package/dist/chunks/chunk-W5M3R4NH.js +0 -2
- package/dist/chunks/chunk-XUMVTGMM.js +0 -2
- package/dist/chunks/chunk-YXMHWS5R.js +0 -2
|
@@ -0,0 +1,883 @@
|
|
|
1
|
+
// forecast's ets and forecast.ets. Written for rStats.js from the behaviour specification oracle/tsmeta-behaviour.md
|
|
2
|
+
// ("ets") with the details found in experiments/tsmeta120-log.md (items 33-38, 51), from Hyndman, Koehler, Ord and
|
|
3
|
+
// Snyder (2008, Forecasting with Exponential Smoothing): the recursions of table 2.3, the likelihood of section 5.2,
|
|
4
|
+
// the admissible region of chapter 10 and the forecast variances of chapter 6. No R or package source was read.
|
|
5
|
+
import { optim } from "../optim/optim.js";
|
|
6
|
+
import { qnorm } from "../distributions/normal.js";
|
|
7
|
+
import { rnorm } from "../random/continuous.js";
|
|
8
|
+
import { setSeed } from "../random/rng.js";
|
|
9
|
+
import { boxCox, invBoxCox } from "./forecastArima.js";
|
|
10
|
+
import { powerOfTwoScale, shiftReference } 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 ETS_KEYS = /* @__PURE__ */ new Set([
|
|
15
|
+
"frequency", "model", "damped", "alpha", "beta", "gamma", "phi", "additiveOnly", "allowMultiplicativeTrend",
|
|
16
|
+
"restrict", "ic", "lambda", "biasadj", "nmse", "optCrit",
|
|
17
|
+
]);
|
|
18
|
+
const FORECAST_ETS_KEYS = ["h", "level", "npaths", "seed", "biasadj"];
|
|
19
|
+
/** The seasonal initial states with the m-th one implied (additive: -sum; multiplicative: m - sum). */
|
|
20
|
+
function fullSeason(spec, s) {
|
|
21
|
+
if (spec.season === "N")
|
|
22
|
+
return [];
|
|
23
|
+
if (s.length === spec.m)
|
|
24
|
+
return s.slice();
|
|
25
|
+
const sum = s.reduce((a, b) => a + b, 0);
|
|
26
|
+
return [...s, spec.season === "A" ? -sum : spec.m - sum];
|
|
27
|
+
}
|
|
28
|
+
/** The filter of table 2.3 given the parameters and initial states (states rows 0..n: l, b, s1..sm). */
|
|
29
|
+
export function etsFilter(y, spec, par) {
|
|
30
|
+
const { error, trend, season, m } = spec;
|
|
31
|
+
const al = par.alpha, be = par.beta ?? 0, ga = par.gamma ?? 0, ph = spec.damped ? par.phi ?? 1 : 1;
|
|
32
|
+
let l = par.l;
|
|
33
|
+
let b = trend === "N" ? 0 : par.b ?? (trend === "M" ? 1 : 0);
|
|
34
|
+
let s = fullSeason(spec, par.s ?? []);
|
|
35
|
+
const n = y.length;
|
|
36
|
+
const e = new Array(n), mu = new Array(n);
|
|
37
|
+
const row = () => [l, ...(trend !== "N" ? [b] : []), ...s];
|
|
38
|
+
const states = [row()];
|
|
39
|
+
let sse = 0, sumLogMu = 0, nObs = 0;
|
|
40
|
+
for (let t = 0; t < n; t++) {
|
|
41
|
+
const T = trend === "N" ? l : trend === "A" ? l + ph * b : l * b ** ph;
|
|
42
|
+
const sm = season === "N" ? 0 : s[m - 1];
|
|
43
|
+
// a missing value: the states move on without a correction (the error 0), and it is left out of the likelihood (log 108)
|
|
44
|
+
const miss = Number.isNaN(y[t]);
|
|
45
|
+
const mt = season === "N" ? T : season === "A" ? T + sm : T * sm;
|
|
46
|
+
mu[t] = mt;
|
|
47
|
+
let ln, bn, sn = 0;
|
|
48
|
+
let ee;
|
|
49
|
+
if (error === "A") {
|
|
50
|
+
ee = miss ? 0 : y[t] - mt;
|
|
51
|
+
if (season === "M") {
|
|
52
|
+
ln = T + (al * ee) / sm;
|
|
53
|
+
bn = trend === "N" ? b : trend === "A" ? ph * b + (be * ee) / sm : b ** ph + (be * ee) / (sm * l);
|
|
54
|
+
sn = sm + (ga * ee) / T;
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
ln = T + al * ee;
|
|
58
|
+
bn = trend === "N" ? b : trend === "A" ? ph * b + be * ee : b ** ph + (be * ee) / l;
|
|
59
|
+
sn = sm + ga * ee;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
ee = miss ? 0 : (y[t] - mt) / mt;
|
|
64
|
+
if (season === "A") {
|
|
65
|
+
ln = T + al * mt * ee;
|
|
66
|
+
bn = trend === "N" ? b : trend === "A" ? ph * b + be * mt * ee : b ** ph + (be * mt * ee) / l;
|
|
67
|
+
sn = sm + ga * mt * ee;
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
ln = T * (1 + al * ee);
|
|
71
|
+
bn = trend === "N" ? b : trend === "A" ? ph * b + be * T * ee : b ** ph * (1 + be * ee);
|
|
72
|
+
sn = season === "M" ? sm * (1 + ga * ee) : sm;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
e[t] = miss ? NaN : ee;
|
|
76
|
+
if (!miss) {
|
|
77
|
+
nObs++;
|
|
78
|
+
sse += ee * ee;
|
|
79
|
+
if (error === "M")
|
|
80
|
+
sumLogMu += Math.log(Math.abs(mt));
|
|
81
|
+
}
|
|
82
|
+
l = ln;
|
|
83
|
+
b = bn;
|
|
84
|
+
if (season !== "N")
|
|
85
|
+
s = [sn, ...s.slice(0, m - 1)];
|
|
86
|
+
states.push(row());
|
|
87
|
+
}
|
|
88
|
+
// n the length including missing values, as R's (log 108: R's log-likelihood with an NA is -0.5 n log(sse) with n
|
|
89
|
+
// = 72 for 71 observations, equal to 1e-15)
|
|
90
|
+
void nObs;
|
|
91
|
+
const lik = n * Math.log(sse) + (error === "M" ? 2 * sumLogMu : 0);
|
|
92
|
+
return { e, mu, states, lik, sse };
|
|
93
|
+
}
|
|
94
|
+
/** lik only (no states kept; a circular seasonal buffer): the objective of the estimation. */
|
|
95
|
+
function etsLik(y, spec, par, sbuf) {
|
|
96
|
+
const { error, trend, season, m } = spec;
|
|
97
|
+
const al = par.alpha, be = par.beta ?? 0, ga = par.gamma ?? 0, ph = spec.damped ? par.phi ?? 1 : 1;
|
|
98
|
+
let l = par.l;
|
|
99
|
+
let b = trend === "N" ? 0 : par.b ?? (trend === "M" ? 1 : 0);
|
|
100
|
+
// sbuf[(head + i) % m] = s_{i+1} (s_1 the most recent)
|
|
101
|
+
let head = 0;
|
|
102
|
+
if (season !== "N") {
|
|
103
|
+
const s = fullSeason(spec, par.s ?? []);
|
|
104
|
+
for (let i = 0; i < m; i++)
|
|
105
|
+
sbuf[i] = s[i];
|
|
106
|
+
}
|
|
107
|
+
const n = y.length;
|
|
108
|
+
let sse = 0, sumLogMu = 0, nObs = 0;
|
|
109
|
+
for (let t = 0; t < n; t++) {
|
|
110
|
+
const T = trend === "N" ? l : trend === "A" ? l + ph * b : l * b ** ph;
|
|
111
|
+
const miss = Number.isNaN(y[t]);
|
|
112
|
+
const iOld = season === "N" ? 0 : (head + m - 1) % m;
|
|
113
|
+
const sm = season === "N" ? 0 : sbuf[iOld];
|
|
114
|
+
const mt = season === "N" ? T : season === "A" ? T + sm : T * sm;
|
|
115
|
+
let ln, bn, sn = 0, ee;
|
|
116
|
+
if (error === "A") {
|
|
117
|
+
ee = miss ? 0 : y[t] - mt;
|
|
118
|
+
if (season === "M") {
|
|
119
|
+
ln = T + (al * ee) / sm;
|
|
120
|
+
bn = trend === "N" ? b : trend === "A" ? ph * b + (be * ee) / sm : b ** ph + (be * ee) / (sm * l);
|
|
121
|
+
sn = sm + (ga * ee) / T;
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
ln = T + al * ee;
|
|
125
|
+
bn = trend === "N" ? b : trend === "A" ? ph * b + be * ee : b ** ph + (be * ee) / l;
|
|
126
|
+
sn = sm + ga * ee;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
else {
|
|
130
|
+
if (!(mt > 0))
|
|
131
|
+
return Infinity;
|
|
132
|
+
ee = miss ? 0 : (y[t] - mt) / mt;
|
|
133
|
+
if (season === "A") {
|
|
134
|
+
ln = T + al * mt * ee;
|
|
135
|
+
bn = trend === "N" ? b : trend === "A" ? ph * b + be * mt * ee : b ** ph + (be * mt * ee) / l;
|
|
136
|
+
sn = sm + ga * mt * ee;
|
|
137
|
+
}
|
|
138
|
+
else {
|
|
139
|
+
ln = T * (1 + al * ee);
|
|
140
|
+
bn = trend === "N" ? b : trend === "A" ? ph * b + be * T * ee : b ** ph * (1 + be * ee);
|
|
141
|
+
sn = season === "M" ? sm * (1 + ga * ee) : sm;
|
|
142
|
+
}
|
|
143
|
+
if (!miss)
|
|
144
|
+
sumLogMu += Math.log(mt);
|
|
145
|
+
}
|
|
146
|
+
if (!miss) {
|
|
147
|
+
nObs++;
|
|
148
|
+
sse += ee * ee;
|
|
149
|
+
}
|
|
150
|
+
l = ln;
|
|
151
|
+
b = bn;
|
|
152
|
+
if (season !== "N") {
|
|
153
|
+
head = iOld;
|
|
154
|
+
sbuf[head] = sn;
|
|
155
|
+
} // the oldest slot becomes the newest
|
|
156
|
+
}
|
|
157
|
+
void nObs;
|
|
158
|
+
return n * Math.log(sse) + (error === "M" ? 2 * sumLogMu : 0);
|
|
159
|
+
}
|
|
160
|
+
function etsMse(y, spec, par) {
|
|
161
|
+
const f = etsFilter(y, spec, par);
|
|
162
|
+
let s = 0;
|
|
163
|
+
let k = 0;
|
|
164
|
+
for (let t = 0; t < y.length; t++)
|
|
165
|
+
if (!Number.isNaN(y[t])) {
|
|
166
|
+
s += (y[t] - f.mu[t]) ** 2;
|
|
167
|
+
k++;
|
|
168
|
+
}
|
|
169
|
+
return s / k;
|
|
170
|
+
}
|
|
171
|
+
/** The zero-error point forecasts from a state row (l, b, s1..sm), h = 1..H. */
|
|
172
|
+
function zeroErrorPath(spec, par, state, H) {
|
|
173
|
+
const { trend, season, m } = spec;
|
|
174
|
+
const ph = spec.damped ? par.phi ?? 1 : 1;
|
|
175
|
+
let l = state[0];
|
|
176
|
+
let b = trend !== "N" ? state[1] : 0;
|
|
177
|
+
const s = state.slice(trend !== "N" ? 2 : 1);
|
|
178
|
+
const out = [];
|
|
179
|
+
for (let k = 1; k <= H; k++) {
|
|
180
|
+
const T = trend === "N" ? l : trend === "A" ? l + ph * b : l * b ** ph;
|
|
181
|
+
const sk = season === "N" ? 0 : s[m - 1 - ((k - 1) % m)];
|
|
182
|
+
out.push(season === "N" ? T : season === "A" ? T + sk : T * sk);
|
|
183
|
+
l = T;
|
|
184
|
+
if (trend === "A")
|
|
185
|
+
b = ph * b;
|
|
186
|
+
else if (trend === "M")
|
|
187
|
+
b = b ** ph;
|
|
188
|
+
}
|
|
189
|
+
return out;
|
|
190
|
+
}
|
|
191
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
192
|
+
// estimation
|
|
193
|
+
const LOWER = { alpha: 1e-4, beta: 1e-4, gamma: 1e-4, phi: 0.8 };
|
|
194
|
+
const UPPER = { alpha: 0.9999, beta: 0.9999, gamma: 0.9999, phi: 0.98 };
|
|
195
|
+
/** The admissible region (Hyndman et al. 2008, ch. 10): the discount matrix F - g w' of the linear model is stable. */
|
|
196
|
+
export function admissible(spec, al, be, ga, ph) {
|
|
197
|
+
const { trend, season, m } = spec;
|
|
198
|
+
if (trend === "M")
|
|
199
|
+
return true; // not linear; only the usual bounds
|
|
200
|
+
// the roots of the characteristic polynomial of D = F - g w' (state x = (l, b, s1..sm), y = w'x + e, x' = F x + g e),
|
|
201
|
+
// by the matrix determinant lemma det(zI - D) = det(zI - F) (1 + w' (zI - F)^-1 g):
|
|
202
|
+
// p(z) = (z - 1)(z - phi)(z^m - 1) + (z^m - 1)(alpha (z - phi) + phi beta) + phi beta (z - 1)(z^m - 1) + gamma (z - 1)(z - phi)
|
|
203
|
+
// (without a trend the factors z - phi and the beta terms dropped, without a season z^m - 1 and gamma). With a season
|
|
204
|
+
// p(1) = 0 (the level and the seasonal sum are not separately identified; the normalised model of ch. 10 does not
|
|
205
|
+
// have that root): divided out. All other roots of modulus below 1 - 1e-10, by the Schur-Cohn recursion
|
|
206
|
+
// (normalised at each step). The same decisions as the eigenvalues of D on 160000 random parameter sets, at a small
|
|
207
|
+
// fraction of the cost (log 108)
|
|
208
|
+
const hasB = trend !== "N";
|
|
209
|
+
const ms = season === "N" ? 0 : m;
|
|
210
|
+
const mul = (a, b) => {
|
|
211
|
+
const r = new Array(a.length + b.length - 1).fill(0);
|
|
212
|
+
for (let i = 0; i < a.length; i++)
|
|
213
|
+
for (let j = 0; j < b.length; j++)
|
|
214
|
+
r[i + j] += a[i] * b[j];
|
|
215
|
+
return r;
|
|
216
|
+
};
|
|
217
|
+
const addTo = (r, a, c) => { for (let i = 0; i < a.length; i++)
|
|
218
|
+
r[i] += c * a[i]; };
|
|
219
|
+
const zm1 = [-1, 1];
|
|
220
|
+
const T = hasB ? [-ph, 1] : [1];
|
|
221
|
+
const zM = ms ? [-1, ...new Array(ms - 1).fill(0), 1] : [1];
|
|
222
|
+
const p = mul(mul(zm1, T), zM);
|
|
223
|
+
addTo(p, mul(zM, hasB ? [al * -ph + ph * be, al] : [al]), 1);
|
|
224
|
+
if (hasB)
|
|
225
|
+
addTo(p, mul(zm1, zM), ph * be);
|
|
226
|
+
if (ms)
|
|
227
|
+
addTo(p, mul(zm1, T), ga);
|
|
228
|
+
let a = p;
|
|
229
|
+
if (ms) {
|
|
230
|
+
const d = p.length - 1;
|
|
231
|
+
const q = new Array(d).fill(0);
|
|
232
|
+
let r = p[d];
|
|
233
|
+
for (let k = d - 1; k >= 0; k--) {
|
|
234
|
+
q[k] = r;
|
|
235
|
+
r = p[k] + r;
|
|
236
|
+
}
|
|
237
|
+
a = q;
|
|
238
|
+
}
|
|
239
|
+
const rad = 1 - 1e-10;
|
|
240
|
+
a = a.map((v, k) => v * rad ** k);
|
|
241
|
+
while (a.length > 1) {
|
|
242
|
+
const d = a.length - 1;
|
|
243
|
+
const lead = a[d], c0 = a[0];
|
|
244
|
+
if (!(Math.abs(c0) < Math.abs(lead)))
|
|
245
|
+
return false;
|
|
246
|
+
const nb = new Array(d);
|
|
247
|
+
for (let k = 0; k < d; k++)
|
|
248
|
+
nb[k] = lead * a[k + 1] - c0 * a[d - k - 1];
|
|
249
|
+
const top = nb[d - 1];
|
|
250
|
+
a = nb.map((v) => v / top);
|
|
251
|
+
}
|
|
252
|
+
return true;
|
|
253
|
+
}
|
|
254
|
+
/** Missing values replaced by linear interpolation (constant beyond the ends): for the starting states only. */
|
|
255
|
+
function interpolated(y) {
|
|
256
|
+
if (!y.some((v) => Number.isNaN(v)))
|
|
257
|
+
return y;
|
|
258
|
+
const obs = y.map((_, i) => i).filter((i) => !Number.isNaN(y[i]));
|
|
259
|
+
return y.map((v, i) => {
|
|
260
|
+
if (!Number.isNaN(v))
|
|
261
|
+
return v;
|
|
262
|
+
let j = 0;
|
|
263
|
+
while (j < obs.length && obs[j] < i)
|
|
264
|
+
j++;
|
|
265
|
+
if (j === 0)
|
|
266
|
+
return y[obs[0]];
|
|
267
|
+
if (j === obs.length)
|
|
268
|
+
return y[obs[obs.length - 1]];
|
|
269
|
+
const a = obs[j - 1], b = obs[j];
|
|
270
|
+
return y[a] + ((y[b] - y[a]) * (i - a)) / (b - a);
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
function initialStates(y0, spec) {
|
|
274
|
+
const { trend, season, m } = spec;
|
|
275
|
+
const y = interpolated(y0);
|
|
276
|
+
const n = y.length;
|
|
277
|
+
let s = [];
|
|
278
|
+
let adj = y.slice();
|
|
279
|
+
if (season !== "N") {
|
|
280
|
+
// a classical decomposition of the first (up to four) full cycles, seasonal indices averaged
|
|
281
|
+
const nc = Math.max(2, Math.min(4, Math.floor(n / m)));
|
|
282
|
+
const z = y.slice(0, nc * m);
|
|
283
|
+
const ma = new Array(z.length).fill(NaN);
|
|
284
|
+
const half = Math.floor(m / 2);
|
|
285
|
+
for (let t = half; t < z.length - half; t++) {
|
|
286
|
+
let v = 0;
|
|
287
|
+
if (m % 2 === 0) {
|
|
288
|
+
for (let k = -half; k <= half; k++)
|
|
289
|
+
v += (Math.abs(k) === half ? 0.5 : 1) * z[t + k];
|
|
290
|
+
v /= m;
|
|
291
|
+
}
|
|
292
|
+
else {
|
|
293
|
+
for (let k = -half; k <= half; k++)
|
|
294
|
+
v += z[t + k];
|
|
295
|
+
v /= m;
|
|
296
|
+
}
|
|
297
|
+
ma[t] = v;
|
|
298
|
+
}
|
|
299
|
+
const idx = new Array(m).fill(0), cnt = new Array(m).fill(0);
|
|
300
|
+
z.forEach((v, t) => { if (Number.isFinite(ma[t])) {
|
|
301
|
+
idx[t % m] += season === "A" ? v - ma[t] : v / ma[t];
|
|
302
|
+
cnt[t % m]++;
|
|
303
|
+
} });
|
|
304
|
+
let si = idx.map((v, i) => (cnt[i] ? v / cnt[i] : season === "A" ? 0 : 1));
|
|
305
|
+
const mean = si.reduce((a, b) => a + b, 0) / m;
|
|
306
|
+
si = si.map((v) => (season === "A" ? v - mean : v / mean));
|
|
307
|
+
// states: s1 = the most recent before t = 1, i.e. the season of period m, ..., sm = period 1
|
|
308
|
+
s = si.slice().reverse();
|
|
309
|
+
adj = y.map((v, t) => (season === "A" ? v - si[t % m] : v / si[t % m]));
|
|
310
|
+
}
|
|
311
|
+
const k = Math.min(10, n);
|
|
312
|
+
const tt = Array.from({ length: k }, (_, i) => i + 1);
|
|
313
|
+
const tm = tt.reduce((a, b) => a + b, 0) / k;
|
|
314
|
+
const ym = adj.slice(0, k).reduce((a, b) => a + b, 0) / k;
|
|
315
|
+
let sxy = 0, sxx = 0;
|
|
316
|
+
for (let i = 0; i < k; i++) {
|
|
317
|
+
sxy += (tt[i] - tm) * (adj[i] - ym);
|
|
318
|
+
sxx += (tt[i] - tm) ** 2;
|
|
319
|
+
}
|
|
320
|
+
const slope = sxx > 0 ? sxy / sxx : 0;
|
|
321
|
+
let l = ym - slope * tm;
|
|
322
|
+
let b = slope;
|
|
323
|
+
if (trend === "N") {
|
|
324
|
+
l = ym;
|
|
325
|
+
b = 0;
|
|
326
|
+
}
|
|
327
|
+
// a fast-growing start can put the line's value at t = 0 below zero (uspop): start from the first value instead
|
|
328
|
+
if (trend === "A" && !(l > 0) && adj[0] > 0) {
|
|
329
|
+
l = adj[0];
|
|
330
|
+
b = k > 1 ? (adj[k - 1] - adj[0]) / (k - 1) : 0;
|
|
331
|
+
}
|
|
332
|
+
if (trend === "M") {
|
|
333
|
+
b = Math.max(0.5, Math.min(1.5, 1 + slope / Math.max(1e-8, Math.abs(l))));
|
|
334
|
+
if (!(l > 0))
|
|
335
|
+
l = Math.max(1e-8, adj[0]);
|
|
336
|
+
}
|
|
337
|
+
return { l, b, s };
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Fits one model by minimising lik (= -2 loglik) within the usual bounds and the admissible region. `bounds: "simple"`
|
|
341
|
+
* is forecast's initial = "simple" (its own Holt-Winters filter, log 91): alpha, beta* = beta / alpha and gamma in
|
|
342
|
+
* [0, 1], no admissibility check.
|
|
343
|
+
*/
|
|
344
|
+
export function fitModel(y, spec, fixed = {}, fixedInit, optCrit = "lik", bounds = "usual", start) {
|
|
345
|
+
const { trend, season, m } = spec;
|
|
346
|
+
const n = y.length;
|
|
347
|
+
const names = [];
|
|
348
|
+
if (fixed.alpha === undefined)
|
|
349
|
+
names.push("alpha");
|
|
350
|
+
if (trend !== "N" && fixed.beta === undefined)
|
|
351
|
+
names.push("beta");
|
|
352
|
+
if (season !== "N" && fixed.gamma === undefined)
|
|
353
|
+
names.push("gamma");
|
|
354
|
+
if (spec.damped && fixed.phi === undefined)
|
|
355
|
+
names.push("phi");
|
|
356
|
+
const nSmooth = names.length;
|
|
357
|
+
const init = fixedInit ?? initialStates(y, spec);
|
|
358
|
+
const nState = fixedInit ? 0 : 1 + (trend !== "N" ? 1 : 0) + (season !== "N" ? m - 1 : 0);
|
|
359
|
+
const yo = y.filter((v) => !Number.isNaN(v));
|
|
360
|
+
const scale = Math.max(1e-8, Math.sqrt(yo.reduce((a, v) => a + v * v, 0) / yo.length));
|
|
361
|
+
const sbuf = new Float64Array(Math.max(1, m));
|
|
362
|
+
const decode = (u) => {
|
|
363
|
+
let j = 0;
|
|
364
|
+
const v = { ...fixed };
|
|
365
|
+
for (const nm of names)
|
|
366
|
+
v[nm] = u[j++];
|
|
367
|
+
let l = init.l, b = init.b ?? (trend === "M" ? 1 : 0), s = init.s ?? [];
|
|
368
|
+
if (!fixedInit) {
|
|
369
|
+
l = u[j++] * scale;
|
|
370
|
+
if (trend !== "N")
|
|
371
|
+
b = trend === "M" ? u[j++] : u[j++] * scale;
|
|
372
|
+
if (season !== "N") {
|
|
373
|
+
s = [];
|
|
374
|
+
for (let i = 0; i < m - 1; i++)
|
|
375
|
+
s.push(season === "A" ? u[j++] * scale : u[j++]);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
return { alpha: v.alpha, ...(trend !== "N" ? { beta: v.beta } : {}), ...(season !== "N" ? { gamma: v.gamma } : {}),
|
|
379
|
+
...(spec.damped ? { phi: v.phi } : {}), l, ...(trend !== "N" ? { b } : {}), ...(season !== "N" ? { s } : {}) };
|
|
380
|
+
};
|
|
381
|
+
const objective = (u) => {
|
|
382
|
+
const p = decode(u);
|
|
383
|
+
const al = p.alpha, be = p.beta ?? 0, ga = p.gamma ?? 0, ph = p.phi ?? 1;
|
|
384
|
+
if (bounds === "simple") {
|
|
385
|
+
if (!(al >= 0 && al <= 1) || (trend !== "N" && !(be >= 0 && be <= al)) || (season !== "N" && !(ga >= 0 && ga <= 1)))
|
|
386
|
+
return Infinity;
|
|
387
|
+
if (spec.damped && !(ph >= LOWER.phi && ph <= UPPER.phi))
|
|
388
|
+
return Infinity;
|
|
389
|
+
if (season === "M" && fullSeason(spec, p.s ?? []).some((v) => !(v > 0)))
|
|
390
|
+
return Infinity;
|
|
391
|
+
const v = optCrit === "mse" ? etsMse(y, spec, p) : etsLik(y, spec, p, sbuf);
|
|
392
|
+
return Number.isFinite(v) ? v : Infinity;
|
|
393
|
+
}
|
|
394
|
+
if (!(al >= LOWER.alpha && al <= UPPER.alpha))
|
|
395
|
+
return Infinity;
|
|
396
|
+
if (trend !== "N" && !(be >= LOWER.beta && be <= al))
|
|
397
|
+
return Infinity;
|
|
398
|
+
if (season !== "N" && !(ga >= LOWER.gamma && ga <= 1 - al))
|
|
399
|
+
return Infinity;
|
|
400
|
+
if (spec.damped && !(ph >= LOWER.phi && ph <= UPPER.phi))
|
|
401
|
+
return Infinity;
|
|
402
|
+
if (!admissible(spec, al, be, ga, ph))
|
|
403
|
+
return Infinity;
|
|
404
|
+
if (season === "M" && fullSeason(spec, p.s ?? []).some((v) => !(v > 0)))
|
|
405
|
+
return Infinity;
|
|
406
|
+
if (trend === "M" && !((p.b ?? 1) > 0))
|
|
407
|
+
return Infinity;
|
|
408
|
+
// "mse": the mean squared one-step error y - mu (forecast's opt.crit = "mse", used by thetaf's ses)
|
|
409
|
+
const v = optCrit === "mse" ? etsMse(y, spec, p) : etsLik(y, spec, p, sbuf);
|
|
410
|
+
return Number.isFinite(v) ? v : Infinity;
|
|
411
|
+
};
|
|
412
|
+
const u0 = [];
|
|
413
|
+
for (const nm of names)
|
|
414
|
+
u0.push(start?.[nm] ?? (nm === "alpha" ? 0.5 : nm === "beta" ? 0.05 : nm === "gamma" ? 0.05 : 0.95));
|
|
415
|
+
if (!fixedInit) {
|
|
416
|
+
const ib = init.b ?? 0, is = init.s ?? [];
|
|
417
|
+
u0.push(init.l / scale);
|
|
418
|
+
if (trend !== "N")
|
|
419
|
+
u0.push(trend === "M" ? ib : ib / scale);
|
|
420
|
+
if (season !== "N")
|
|
421
|
+
for (let i = 0; i < m - 1; i++)
|
|
422
|
+
u0.push(season === "A" ? is[i] / scale : is[i]);
|
|
423
|
+
}
|
|
424
|
+
if (u0.length === 0) {
|
|
425
|
+
const p = decode([]);
|
|
426
|
+
const f = etsFilter(y, spec, p);
|
|
427
|
+
return { spec, par: p, filter: f, nParams: 0 };
|
|
428
|
+
}
|
|
429
|
+
// several starting values for the smoothing parameters, Nelder-Mead restarted until it stops improving
|
|
430
|
+
const starts = [u0];
|
|
431
|
+
if (nSmooth > 0)
|
|
432
|
+
for (const a of [0.1, 0.9]) {
|
|
433
|
+
const u = u0.slice();
|
|
434
|
+
u[0] = a;
|
|
435
|
+
if (names[1] === "beta")
|
|
436
|
+
u[1] = Math.min(u[1], a / 2);
|
|
437
|
+
if (names.includes("gamma"))
|
|
438
|
+
u[names.indexOf("gamma")] = Math.min(0.05, (1 - a) / 2);
|
|
439
|
+
starts.push(u);
|
|
440
|
+
}
|
|
441
|
+
// Nelder-Mead from each start (2000 iterations, as R's default), then refined from each: in the usual bounds,
|
|
442
|
+
// L-BFGS-B within the box of the bounds alternated with restarted Nelder-Mead until neither improves (log 105).
|
|
443
|
+
// Nelder-Mead alone stopped at different points of a flat optimum whose smoothing parameters sit at a bound
|
|
444
|
+
// (USAccDeaths AAA: beta and gamma at 1e-4; log-likelihoods 1e-2 apart after exact changes of scale), which the box
|
|
445
|
+
// handles exactly; refining every start, not only the best, finds the same one of several local optima (MAM) after
|
|
446
|
+
// such changes. The coupled limits (beta <= alpha, gamma <= 1 - alpha, admissibility, positive means) stay in the
|
|
447
|
+
// objective, as a large finite value for L-BFGS-B, which needs finite values; a polish that fails is dropped.
|
|
448
|
+
const lo = [...names.map((nm) => LOWER[nm]), ...new Array(u0.length - nSmooth).fill(-Infinity)];
|
|
449
|
+
const hi = [...names.map((nm) => UPPER[nm]), ...new Array(u0.length - nSmooth).fill(Infinity)];
|
|
450
|
+
const boxed = (u) => { const v = objective(u); return Number.isFinite(v) ? v : 1e100; };
|
|
451
|
+
const refine = (u, v) => {
|
|
452
|
+
for (let round = 0; round < 10; round++) {
|
|
453
|
+
const before = v;
|
|
454
|
+
if (bounds === "usual") {
|
|
455
|
+
try {
|
|
456
|
+
const r = optim(u, boxed, { method: "L-BFGS-B", lower: lo, upper: hi, control: { factr: 1, ndeps: 1e-7 } });
|
|
457
|
+
if (r.value < v) {
|
|
458
|
+
v = r.value;
|
|
459
|
+
u = r.par;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
catch { /* dropped */ }
|
|
463
|
+
}
|
|
464
|
+
const r2 = optim(u, objective, { method: "Nelder-Mead", control: { maxit: 4000, reltol: 1e-14 } });
|
|
465
|
+
if (r2.value < v) {
|
|
466
|
+
v = r2.value;
|
|
467
|
+
u = r2.par;
|
|
468
|
+
}
|
|
469
|
+
if (!(before - v > 1e-12 * Math.max(1, Math.abs(v))))
|
|
470
|
+
break;
|
|
471
|
+
}
|
|
472
|
+
return [u, v];
|
|
473
|
+
};
|
|
474
|
+
let best = null;
|
|
475
|
+
let bestV = Infinity;
|
|
476
|
+
for (const st of starts) {
|
|
477
|
+
if (!Number.isFinite(objective(st)))
|
|
478
|
+
continue;
|
|
479
|
+
const r = optim(st, objective, { method: "Nelder-Mead", control: { maxit: 2000, reltol: 1e-10 } });
|
|
480
|
+
const [u, v] = refine(r.par, r.value);
|
|
481
|
+
if (v < bestV) {
|
|
482
|
+
bestV = v;
|
|
483
|
+
best = u;
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
if (!best || !Number.isFinite(bestV))
|
|
487
|
+
return null;
|
|
488
|
+
const par = decode(best);
|
|
489
|
+
return { spec, par, filter: etsFilter(y, spec, par), nParams: nSmooth + nState };
|
|
490
|
+
}
|
|
491
|
+
function methodName(spec) {
|
|
492
|
+
return `ETS(${spec.error},${spec.trend}${spec.damped ? "d" : ""},${spec.season})`;
|
|
493
|
+
}
|
|
494
|
+
function finish(y, f, nmse, lambda, biasadj, x) {
|
|
495
|
+
const n = y.length;
|
|
496
|
+
const p = f.nParams;
|
|
497
|
+
const lik = f.filter.lik;
|
|
498
|
+
const loglik = -0.5 * lik;
|
|
499
|
+
const aic = -2 * loglik + 2 * (p + 1);
|
|
500
|
+
// the AICc is undefined (Infinity: not a candidate) without a positive denominator n - p - 2 (a model with as many
|
|
501
|
+
// parameters as observations reported a large negative AICc and was chosen; log 107)
|
|
502
|
+
const bic = aic + (p + 1) * (Math.log(n) - 2);
|
|
503
|
+
const aicc = n - p - 2 > 0 ? aic + (2 * (p + 1) * (p + 2)) / (n - p - 2) : Infinity;
|
|
504
|
+
const sigma2 = f.filter.sse / (n - p);
|
|
505
|
+
const obs = y.filter((v) => !Number.isNaN(v)).length;
|
|
506
|
+
const mse = y.reduce((a, v, t) => (Number.isNaN(v) ? a : a + (v - f.filter.mu[t]) ** 2), 0) / obs;
|
|
507
|
+
// amse: the mean over h = 1..nmse of the in-sample h-step mean squared errors along the zero-error path (log 51)
|
|
508
|
+
let amse = 0;
|
|
509
|
+
for (let h = 1; h <= nmse; h++) {
|
|
510
|
+
let s = 0, c = 0;
|
|
511
|
+
for (let t = 0; t + h <= n; t++) {
|
|
512
|
+
if (Number.isNaN(y[t + h - 1]))
|
|
513
|
+
continue;
|
|
514
|
+
const fc = zeroErrorPath(f.spec, f.par, f.filter.states[t], h)[h - 1];
|
|
515
|
+
s += (y[t + h - 1] - fc) ** 2;
|
|
516
|
+
c++;
|
|
517
|
+
}
|
|
518
|
+
amse += s / c;
|
|
519
|
+
}
|
|
520
|
+
amse /= nmse;
|
|
521
|
+
const fittedZ = f.filter.mu;
|
|
522
|
+
const fitted = lambda === null ? fittedZ.slice() : invBoxCox(fittedZ, lambda, { biasadj, fvar: sigma2 });
|
|
523
|
+
return { spec: f.spec, method: methodName(f.spec), par: f.par, nParams: p, loglik, aic, bic, aicc, sigma2, mse, amse,
|
|
524
|
+
fitted, residuals: f.filter.e.slice(), states: f.filter.states, x, lambda, biasadj };
|
|
525
|
+
}
|
|
526
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
527
|
+
// fitting on a standardised series (1.20.0, log 104): the series divided by a power of two c near its largest
|
|
528
|
+
// absolute value, so that the fit does not depend on the scale (the bounds, the floor of the internal scale and the
|
|
529
|
+
// optimiser's stopping rule are otherwise absolute, and squares leave the range at 1e+-150). Dividing by a power of
|
|
530
|
+
// two is exact; the result is mapped back below, and forecastEts forecasts from the standardised fit.
|
|
531
|
+
const ETS_SCALED = new WeakMap();
|
|
532
|
+
/** The fit of the standardised series z / c expressed on the scale of z (the states and the additive quantities). */
|
|
533
|
+
function unscaleFit(fs, c, lambda, biasadj, x, sh = 0) {
|
|
534
|
+
const { spec } = fs;
|
|
535
|
+
const tA = spec.trend === "A", sA = spec.season === "A", eA = spec.error === "A";
|
|
536
|
+
const nb = spec.trend !== "N" ? 1 : 0;
|
|
537
|
+
const par = { ...fs.par, l: fs.par.l * c + sh,
|
|
538
|
+
...(fs.par.b !== undefined ? { b: tA ? fs.par.b * c : fs.par.b } : {}),
|
|
539
|
+
...(fs.par.s ? { s: sA ? fs.par.s.map((v) => v * c) : fs.par.s.slice() } : {}) };
|
|
540
|
+
const states = fs.states.map((r) => r.map((v, j) => (j === 0 ? v * c + sh : (j === 1 && nb === 1 && tA) || (j > nb && sA) ? v * c : v)));
|
|
541
|
+
const n = fs.fitted.length;
|
|
542
|
+
const logc = Math.log(c);
|
|
543
|
+
const sigma2 = eA ? fs.sigma2 * c * c : fs.sigma2;
|
|
544
|
+
const fittedZ = fs.fitted.map((v) => v * c + sh);
|
|
545
|
+
const fitted = lambda === null ? fittedZ : invBoxCox(fittedZ, lambda, { biasadj, fvar: sigma2 });
|
|
546
|
+
// lik = n log(sum e^2) (+ 2 sum log mu for multiplicative errors) moves by 2 n log c in both cases
|
|
547
|
+
const r = { ...fs, par, loglik: fs.loglik - n * logc, aic: fs.aic + 2 * n * logc, bic: fs.bic + 2 * n * logc,
|
|
548
|
+
aicc: fs.aicc + 2 * n * logc, sigma2, mse: fs.mse * c * c, amse: fs.amse * c * c, fitted,
|
|
549
|
+
residuals: eA ? fs.residuals.map((v) => v * c) : fs.residuals.slice(), states, x, lambda, biasadj };
|
|
550
|
+
ETS_SCALED.set(r, { fit: fs, c, sh });
|
|
551
|
+
return r;
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* Exponential smoothing state space model (forecast's `ets()`): one model, or the smallest information criterion
|
|
555
|
+
* among the allowed models for the letters given as "Z". The parameters are estimated to the optimum of the
|
|
556
|
+
* likelihood within the usual bounds and the admissible region (R's optimiser can stop earlier).
|
|
557
|
+
* Equivalent to `forecast::ets()` in R.
|
|
558
|
+
*
|
|
559
|
+
* @category Time series
|
|
560
|
+
*/
|
|
561
|
+
export function ets(y, options = {}) {
|
|
562
|
+
checkOptions(options, ETS_KEYS, "ets"); // generated: option-keys.mjs
|
|
563
|
+
// missing values: skipped by the filter (the states move on without a correction), as R's (log 108)
|
|
564
|
+
const m0 = options.frequency ?? 1;
|
|
565
|
+
const x = tsInput(y, "ets", { missing: "allow", minLength: 1 });
|
|
566
|
+
const lambda = options.lambda ?? null;
|
|
567
|
+
const z = lambda === null ? x.slice() : boxCox(x, lambda);
|
|
568
|
+
const model = (options.model ?? "ZZZ").toUpperCase();
|
|
569
|
+
if (!/^[AMZ][ANMZ][ANMZ]$/.test(model))
|
|
570
|
+
throw new RangeError(`ets: invalid model '${options.model}'`);
|
|
571
|
+
const positive = z.every((v) => Number.isNaN(v) || v > 0);
|
|
572
|
+
const restrict = options.restrict ?? true;
|
|
573
|
+
const additiveOnly = options.additiveOnly ?? false;
|
|
574
|
+
const errs = model[0] === "Z" ? (additiveOnly || !positive ? ["A"] : ["A", "M"]) : [model[0]];
|
|
575
|
+
const trends = model[1] === "Z" ? (options.allowMultiplicativeTrend && !additiveOnly && positive ? ["N", "A", "M"] : ["N", "A"]) : [model[1]];
|
|
576
|
+
const seasonal = m0 > 1 && m0 <= 24;
|
|
577
|
+
const seasons = model[2] === "Z" ? (!seasonal ? ["N"] : additiveOnly || !positive ? ["N", "A"] : ["N", "A", "M"]) : [model[2]];
|
|
578
|
+
const fixed = {};
|
|
579
|
+
for (const k of ["alpha", "beta", "gamma", "phi"])
|
|
580
|
+
if (options[k] !== undefined)
|
|
581
|
+
fixed[k] = options[k];
|
|
582
|
+
const ic = options.ic ?? "aicc";
|
|
583
|
+
const nmse = options.nmse ?? 3;
|
|
584
|
+
const biasadj = options.biasadj ?? false;
|
|
585
|
+
// a large common value (beyond 1024 times the range) taken out when every candidate model is additive (they are
|
|
586
|
+
// exactly shift equivariant; the level then sits near 0, where the optimiser resolves it: AAdN on Nile + 1e8 had
|
|
587
|
+
// stopped 5e-4 lower in log-likelihood and 3e-4 off in the forecasts; log 110), added back to the level
|
|
588
|
+
const allAdditive = lambda === null && ![...errs, ...trends, ...seasons].includes("M");
|
|
589
|
+
const sh = allAdditive ? shiftReference(z) : 0;
|
|
590
|
+
const c = powerOfTwoScale(sh === 0 ? z : z.map((v) => v - sh));
|
|
591
|
+
const zs = z.map((v) => (v - sh) / c);
|
|
592
|
+
// a constant series: every model fits exactly (zero errors, the likelihood unbounded), so no criterion separates
|
|
593
|
+
// the parameters; the model asked for (A, N, N for the letters Z) at the starting values of the smoothing
|
|
594
|
+
// parameters and the constant level, sigma2 = 0 (R fits one with some parameters; log 107)
|
|
595
|
+
const zObs = zs.filter((v) => !Number.isNaN(v));
|
|
596
|
+
if (zObs.every((v) => v === zObs[0])) {
|
|
597
|
+
const error = model[0] === "M" && positive ? "M" : "A";
|
|
598
|
+
const trend = model[1] === "Z" ? "N" : model[1];
|
|
599
|
+
const season = model[2] === "Z" || m0 <= 1 ? "N" : model[2];
|
|
600
|
+
if ((trend === "M" || season === "M") && !positive)
|
|
601
|
+
throw new RangeError("ets: a multiplicative component needs positive data");
|
|
602
|
+
const spec = { error, trend, damped: trend !== "N" && (options.damped ?? false), season, m: season === "N" ? 1 : m0 };
|
|
603
|
+
const v0 = zObs[0];
|
|
604
|
+
const mult = (k) => k === "M";
|
|
605
|
+
const init = { l: v0, ...(trend !== "N" ? { b: mult(trend) ? 1 : 0 } : {}), ...(season !== "N" ? { s: new Array(m0 - 1).fill(mult(season) ? 1 : 0) } : {}) };
|
|
606
|
+
const start = { alpha: 0.5, ...(trend !== "N" ? { beta: 0.05 } : {}), ...(season !== "N" ? { gamma: 0.05 } : {}), ...(spec.damped ? { phi: 0.95 } : {}), ...fixed };
|
|
607
|
+
const f = fitModel(zs, spec, start, init);
|
|
608
|
+
if (!f)
|
|
609
|
+
throw new Error("ets: no model able to be fitted");
|
|
610
|
+
return unscaleFit(finish(zs, { ...f, nParams: Object.keys(start).length - Object.keys(fixed).length + 1 + (trend !== "N" ? 1 : 0) + (season !== "N" ? m0 - 1 : 0) }, nmse, null, false, zs), c, lambda, biasadj, x, sh);
|
|
611
|
+
}
|
|
612
|
+
// short series as R's (log 107-108): with n <= m the seasonal component is dropped; a model with n <= npars + 4
|
|
613
|
+
// (npars = the smoothing parameters and the initial states) is not fitted by the likelihood but by the one-step
|
|
614
|
+
// squared errors from simple starting values (forecast's initial = "simple": l = y_1, b = y_2 - y_1; seasonal: the
|
|
615
|
+
// first two cycles), damping dropped, a seasonal model with an additive trend and the season's kind of error, a
|
|
616
|
+
// non-seasonal one with additive errors; its log-likelihood and criteria are NaN (R's NA). A seasonal model needs
|
|
617
|
+
// 2m values there (R's starting trend is NA below, and so are all its forecasts): an error instead. With letters Z
|
|
618
|
+
// the likelihood fits are compared; only when none has a criterion, the simple fits by their mean squared error
|
|
619
|
+
const n = zs.length;
|
|
620
|
+
const zi = interpolated(zs);
|
|
621
|
+
const tried = new Set();
|
|
622
|
+
const fits = [];
|
|
623
|
+
let firstError = null;
|
|
624
|
+
let best = null;
|
|
625
|
+
let bestIc = Infinity;
|
|
626
|
+
for (const error0 of errs)
|
|
627
|
+
for (const trend0 of trends)
|
|
628
|
+
for (const season0 of seasons) {
|
|
629
|
+
if (season0 !== "N" && !seasonal)
|
|
630
|
+
continue;
|
|
631
|
+
if ((error0 === "M" || trend0 === "M" || season0 === "M") && !positive)
|
|
632
|
+
continue;
|
|
633
|
+
if (restrict && ((error0 === "A" && (trend0 === "M" || season0 === "M")) || (error0 === "M" && trend0 === "M" && season0 === "A")))
|
|
634
|
+
continue;
|
|
635
|
+
const dampedSet = trend0 === "N" ? [false] : options.damped === undefined ? (model[1] === "Z" ? [true, false] : [false]) : [options.damped];
|
|
636
|
+
for (const damped0 of dampedSet) {
|
|
637
|
+
const season = n <= m0 ? "N" : season0;
|
|
638
|
+
const m = season === "N" ? 1 : m0;
|
|
639
|
+
const nSmooth = 1 + (trend0 !== "N" ? 1 : 0) + (season !== "N" ? 1 : 0) + (damped0 ? 1 : 0)
|
|
640
|
+
- ["alpha", "beta", "gamma", "phi"].filter((k) => fixed[k] !== undefined && (k === "alpha" || (k === "beta" && trend0 !== "N") || (k === "gamma" && season !== "N") || (k === "phi" && damped0))).length;
|
|
641
|
+
const npars = nSmooth + 1 + (trend0 !== "N" ? 1 : 0) + (season !== "N" ? m - 1 : 0);
|
|
642
|
+
const simple = n <= npars + 4;
|
|
643
|
+
const spec = simple
|
|
644
|
+
? { error: season === "N" ? "A" : season, trend: season !== "N" ? "A" : trend0, damped: false, season, m }
|
|
645
|
+
: { error: error0, trend: trend0, damped: damped0, season, m };
|
|
646
|
+
const key = `${spec.error}${spec.trend}${spec.damped}${spec.season}${simple}`;
|
|
647
|
+
if (tried.has(key))
|
|
648
|
+
continue;
|
|
649
|
+
tried.add(key);
|
|
650
|
+
let r;
|
|
651
|
+
if (simple) {
|
|
652
|
+
try {
|
|
653
|
+
if (season !== "N" && n < 2 * m)
|
|
654
|
+
throw new RangeError(`ets: ${spec.error}${spec.trend}${spec.season} on ${n} values needs at least ${2 * m} (two seasonal periods)`);
|
|
655
|
+
if (spec.trend !== "N" && n < 2)
|
|
656
|
+
throw new RangeError("ets: a trend needs at least two values");
|
|
657
|
+
const mean = (a) => a.reduce((u, v) => u + v, 0) / a.length;
|
|
658
|
+
const init = season !== "N"
|
|
659
|
+
? (() => { const l = mean(zi.slice(0, m)); const b = (mean(zi.slice(m, 2 * m)) - l) / m; return { l, b, s: zi.slice(0, m).map((v) => (season === "M" ? v / l : v - l)).reverse() }; })()
|
|
660
|
+
: { l: zi[0], ...(spec.trend === "A" ? { b: zi[1] - zi[0] } : spec.trend === "M" ? { b: zi[1] / zi[0] } : {}) };
|
|
661
|
+
// R's starting values (alpha 0.2 / m, beta 0.1 alpha, gamma 0.05 (1 - alpha)): where the squared errors do not
|
|
662
|
+
// depend on a parameter (n = 2) the fit stays there, as R's
|
|
663
|
+
const a0 = 0.2 / m;
|
|
664
|
+
const f = fitModel(zs, spec, fixed, init, "mse", "simple", { alpha: a0, beta: 0.1 * a0, gamma: 0.05 * (1 - a0) });
|
|
665
|
+
if (!f)
|
|
666
|
+
continue;
|
|
667
|
+
const fr = finish(zs, { ...f, nParams: npars }, nmse, null, false, zs);
|
|
668
|
+
// sigma2 = SSE / n for the simple fits, as R's (n = 3: 811801 / 3; log 109)
|
|
669
|
+
const sse = fr.residuals.reduce((a, v) => (Number.isNaN(v) ? a : a + v * v), 0);
|
|
670
|
+
r = { ...fr, loglik: NaN, aic: NaN, bic: NaN, aicc: NaN, sigma2: sse / n };
|
|
671
|
+
}
|
|
672
|
+
catch (e) {
|
|
673
|
+
firstError ??= e;
|
|
674
|
+
continue;
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
else {
|
|
678
|
+
const f = fitModel(zs, spec, fixed, undefined, options.optCrit ?? "lik");
|
|
679
|
+
if (!f)
|
|
680
|
+
continue;
|
|
681
|
+
// the criteria of the standardised fits differ from the original ones by the same constant 2 n log c
|
|
682
|
+
r = finish(zs, f, nmse, null, false, zs);
|
|
683
|
+
}
|
|
684
|
+
fits.push({ r, simple });
|
|
685
|
+
const v = ic === "aic" ? r.aic : ic === "bic" ? r.bic : r.aicc;
|
|
686
|
+
if (!simple && Number.isFinite(v) && v < bestIc) {
|
|
687
|
+
bestIc = v;
|
|
688
|
+
best = r;
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
// one model asked for: its fit, also when its AICc is undefined (Infinity); otherwise the simple ANN (log 108)
|
|
693
|
+
if (!best && fits.length === 1)
|
|
694
|
+
best = fits[0].r;
|
|
695
|
+
// among simple fits only: the smallest mean squared error, the first on ties (R's choices at n = 2..6, log 108)
|
|
696
|
+
if (!best) {
|
|
697
|
+
let mse = Infinity;
|
|
698
|
+
for (const f of fits)
|
|
699
|
+
if (f.simple && f.r.mse < mse) {
|
|
700
|
+
mse = f.r.mse;
|
|
701
|
+
best = f.r;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
if (!best && firstError)
|
|
705
|
+
throw firstError;
|
|
706
|
+
if (!best)
|
|
707
|
+
throw new Error("ets: no model able to be fitted");
|
|
708
|
+
return unscaleFit(best, c, lambda, biasadj, x, sh);
|
|
709
|
+
}
|
|
710
|
+
/** Fits a given model with given smoothing parameters and initial states (no estimation): for ses/holt/hw "simple". */
|
|
711
|
+
export function etsFixedInitial(y, spec, init, fixed = {}, optCrit = "lik", bounds = "usual") {
|
|
712
|
+
const c = powerOfTwoScale(y);
|
|
713
|
+
const ys = y.map((v) => v / c);
|
|
714
|
+
const initS = { l: init.l / c, ...(init.b !== undefined ? { b: spec.trend === "A" ? init.b / c : init.b } : {}),
|
|
715
|
+
...(init.s ? { s: spec.season === "A" ? init.s.map((v) => v / c) : init.s.slice() } : {}) };
|
|
716
|
+
const f = fitModel(ys, spec, fixed, initS, optCrit, bounds);
|
|
717
|
+
if (!f)
|
|
718
|
+
throw new Error("ets: the model could not be fitted");
|
|
719
|
+
return unscaleFit(finish(ys, f, 3, null, false, ys), c, null, false, y.slice());
|
|
720
|
+
}
|
|
721
|
+
/** The fit at given parameters (no estimation; for checks against R's own estimates). */
|
|
722
|
+
export function etsAt(y, spec, par, nParams) {
|
|
723
|
+
const f = { spec, par, filter: etsFilter(y, spec, par), nParams };
|
|
724
|
+
return finish(y, f, 3, null, false, y.slice());
|
|
725
|
+
}
|
|
726
|
+
/**
|
|
727
|
+
* Point forecasts and prediction intervals from an {@link ets} fit (forecast's `forecast.ets()`): the analytic
|
|
728
|
+
* variances of classes 1 and 2, the exact moments of class 3 (MNM, MAM, MAdM), and simulation otherwise (npaths
|
|
729
|
+
* paths with rStats.js's R-compatible generator, seeded by `seed`). Two departures from R's forecast.ets (the
|
|
730
|
+
* model's formulas are used): damped class 3 forecasts use l + phi b at h = 1, and ANA / MNA put the seasonal term
|
|
731
|
+
* of c_j at j mod m = 0.
|
|
732
|
+
* Equivalent to `forecast::forecast()` in R.
|
|
733
|
+
*
|
|
734
|
+
* @category Time series
|
|
735
|
+
*/
|
|
736
|
+
export function forecastEts(fit, options = {}) {
|
|
737
|
+
checkOptions(options, FORECAST_ETS_KEYS, "forecastEts"); // generated: option-keys.mjs
|
|
738
|
+
// from the standardised fit when there is one (ets' fits), then back to the scale of the fit
|
|
739
|
+
const sc = ETS_SCALED.get(fit);
|
|
740
|
+
const c = sc?.c ?? 1;
|
|
741
|
+
let { mean, lower, upper, level, variance } = forecastEtsScaled(sc?.fit ?? fit, options);
|
|
742
|
+
const sh = sc?.sh ?? 0;
|
|
743
|
+
if (c !== 1 || sh !== 0) {
|
|
744
|
+
mean = mean.map((v) => v * c + sh);
|
|
745
|
+
lower = lower.map((r) => r.map((v) => v * c + sh));
|
|
746
|
+
upper = upper.map((r) => r.map((v) => v * c + sh));
|
|
747
|
+
if (variance)
|
|
748
|
+
variance = variance.map((v) => v * c * c);
|
|
749
|
+
}
|
|
750
|
+
const lam = fit.lambda;
|
|
751
|
+
if (lam !== null) {
|
|
752
|
+
const biasadj = options.biasadj ?? fit.biasadj;
|
|
753
|
+
mean = invBoxCox(mean, lam, { biasadj, ...(variance ? { fvar: variance } : {}) });
|
|
754
|
+
lower = lower.map((r) => invBoxCox(r, lam));
|
|
755
|
+
upper = upper.map((r) => invBoxCox(r, lam));
|
|
756
|
+
}
|
|
757
|
+
return { mean, lower, upper, level, method: fit.method, ...(variance ? { variance } : {}) };
|
|
758
|
+
}
|
|
759
|
+
/** forecastEts on the fit's own scale, before the inverse Box-Cox transformation. */
|
|
760
|
+
function forecastEtsScaled(fit, options) {
|
|
761
|
+
const spec = fit.spec;
|
|
762
|
+
const m = spec.m;
|
|
763
|
+
const h = options.h ?? (m > 1 ? 2 * m : 10);
|
|
764
|
+
const level = [...(options.level ?? [80, 95])];
|
|
765
|
+
const par = fit.par;
|
|
766
|
+
const last = fit.states[fit.states.length - 1];
|
|
767
|
+
const s2 = fit.sigma2;
|
|
768
|
+
const al = par.alpha, be = par.beta ?? 0, ga = par.gamma ?? 0, ph = spec.damped ? par.phi ?? 1 : 1;
|
|
769
|
+
let mean = zeroErrorPath(spec, par, last, h);
|
|
770
|
+
let variance = null;
|
|
771
|
+
const cj = (j) => {
|
|
772
|
+
const phj = spec.damped ? Array.from({ length: j }, (_, i) => ph ** (i + 1)).reduce((a, b) => a + b, 0) : j;
|
|
773
|
+
return al + (spec.trend !== "N" ? be * phj : 0) + (spec.season !== "N" && j % m === 0 ? ga : 0);
|
|
774
|
+
};
|
|
775
|
+
const cls1 = spec.error === "A" && spec.trend !== "M" && spec.season !== "M";
|
|
776
|
+
const cls2 = spec.error === "M" && spec.trend !== "M" && spec.season !== "M";
|
|
777
|
+
const cls3 = spec.error === "M" && spec.trend !== "M" && spec.season === "M";
|
|
778
|
+
if (cls1) {
|
|
779
|
+
variance = [];
|
|
780
|
+
let acc = 0;
|
|
781
|
+
for (let k = 1; k <= h; k++) {
|
|
782
|
+
variance.push(s2 * (1 + acc));
|
|
783
|
+
acc += cj(k) ** 2;
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
else if (cls2) {
|
|
787
|
+
const theta = [];
|
|
788
|
+
variance = [];
|
|
789
|
+
for (let k = 1; k <= h; k++) {
|
|
790
|
+
let th = mean[k - 1] ** 2;
|
|
791
|
+
for (let j = 1; j < k; j++)
|
|
792
|
+
th += s2 * cj(j) ** 2 * theta[k - j - 1];
|
|
793
|
+
theta.push(th);
|
|
794
|
+
variance.push((1 + s2) * th - mean[k - 1] ** 2);
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
else if (cls3) {
|
|
798
|
+
// exact first and second moments (log 37), with the model's T = l + phi b
|
|
799
|
+
const hasB = spec.trend !== "N";
|
|
800
|
+
const x0 = hasB ? [last[0], last[1]] : [last[0]];
|
|
801
|
+
const sv = last.slice(hasB ? 2 : 1);
|
|
802
|
+
const cv = hasB ? [1, ph] : [1];
|
|
803
|
+
const A = hasB ? [[1, ph], [0, ph]] : [[1]];
|
|
804
|
+
const B = hasB ? [[al, al * ph], [be, be * ph]] : [[al]];
|
|
805
|
+
const mv = (M, v) => M.map((r) => r.reduce((a, x, i) => a + x * v[i], 0));
|
|
806
|
+
const mm = (X, Y) => X.map((r) => Y[0].map((_, j) => r.reduce((a, x, i) => a + x * Y[i][j], 0)));
|
|
807
|
+
const tr = (X) => X[0].map((_, j) => X.map((r) => r[j]));
|
|
808
|
+
const add = (...Ms) => Ms[0][1].map((r, i) => r.map((_, j) => Ms.reduce((a, [c, M]) => a + c * M[i][j], 0)));
|
|
809
|
+
mean = [];
|
|
810
|
+
variance = [];
|
|
811
|
+
for (let hh = 1; hh <= h; hh++) {
|
|
812
|
+
const k = Math.floor((hh - 1) / m);
|
|
813
|
+
const paired = new Set(Array.from({ length: k }, (_, i) => hh - (i + 1) * m));
|
|
814
|
+
let M1 = x0.slice();
|
|
815
|
+
let M2 = x0.map((a) => x0.map((b) => a * b));
|
|
816
|
+
for (let j = 1; j <= hh - 1; j++) {
|
|
817
|
+
if (paired.has(j)) {
|
|
818
|
+
M1 = mv(add([1, A], [ga * s2, B]), M1);
|
|
819
|
+
const AMA = mm(mm(A, M2), tr(A)), AMB = mm(mm(A, M2), tr(B)), BMA = mm(mm(B, M2), tr(A)), BMB = mm(mm(B, M2), tr(B));
|
|
820
|
+
M2 = add([1 + ga * ga * s2, AMA], [2 * ga * s2, AMB], [2 * ga * s2, BMA], [s2 * (1 + 3 * ga * ga * s2), BMB]);
|
|
821
|
+
}
|
|
822
|
+
else {
|
|
823
|
+
M1 = mv(A, M1);
|
|
824
|
+
M2 = add([1, mm(mm(A, M2), tr(A))], [s2, mm(mm(B, M2), tr(B))]);
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
const sstar = sv[m - 1 - ((hh - 1) % m)];
|
|
828
|
+
const Ey = sstar * cv.reduce((a, c, i) => a + c * M1[i], 0);
|
|
829
|
+
const Ey2 = sstar * sstar * (1 + s2) * cv.reduce((a, ci, i) => a + ci * cv.reduce((b, cjj, j) => b + M2[i][j] * cjj, 0), 0);
|
|
830
|
+
mean.push(Ey);
|
|
831
|
+
variance.push(Ey2 - Ey * Ey);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
let lower, upper;
|
|
835
|
+
if (variance) {
|
|
836
|
+
const q = level.map((l) => qnorm(0.5 + l / 200));
|
|
837
|
+
lower = mean.map((mu, i) => q.map((qq) => mu - qq * Math.sqrt(variance[i])));
|
|
838
|
+
upper = mean.map((mu, i) => q.map((qq) => mu + qq * Math.sqrt(variance[i])));
|
|
839
|
+
}
|
|
840
|
+
else {
|
|
841
|
+
// simulation of the model from the last state (Choice 6: rStats.js's R-compatible generator, seeded)
|
|
842
|
+
const npaths = options.npaths ?? 5000;
|
|
843
|
+
if (options.seed !== undefined)
|
|
844
|
+
setSeed(options.seed);
|
|
845
|
+
const sims = Array.from({ length: h }, () => []);
|
|
846
|
+
const sd = Math.sqrt(s2);
|
|
847
|
+
for (let pth = 0; pth < npaths; pth++) {
|
|
848
|
+
const eps = rnorm(h, { sd });
|
|
849
|
+
const yy = simulatePath(spec, par, last, eps);
|
|
850
|
+
for (let k = 0; k < h; k++)
|
|
851
|
+
sims[k].push(yy[k]);
|
|
852
|
+
}
|
|
853
|
+
const quant = (v, pr) => { const s = v.slice().sort((a, b) => a - b); const idx = (s.length - 1) * pr; const lo = Math.floor(idx); return s[lo] + (s[Math.min(lo + 1, s.length - 1)] - s[lo]) * (idx - lo); };
|
|
854
|
+
lower = sims.map((v) => level.map((l) => quant(v, 0.5 - l / 200)));
|
|
855
|
+
upper = sims.map((v) => level.map((l) => quant(v, 0.5 + l / 200)));
|
|
856
|
+
}
|
|
857
|
+
return { mean, lower, upper, level, variance };
|
|
858
|
+
}
|
|
859
|
+
/** One simulated future path given the errors. */
|
|
860
|
+
function simulatePath(spec, par, state, eps) {
|
|
861
|
+
const { error, trend, season, m } = spec;
|
|
862
|
+
const ph = spec.damped ? par.phi ?? 1 : 1;
|
|
863
|
+
const al = par.alpha, be = par.beta ?? 0, ga = par.gamma ?? 0;
|
|
864
|
+
let l = state[0];
|
|
865
|
+
let b = trend !== "N" ? state[1] : 0;
|
|
866
|
+
let s = state.slice(trend !== "N" ? 2 : 1);
|
|
867
|
+
const out = [];
|
|
868
|
+
for (const ee of eps) {
|
|
869
|
+
const T = trend === "N" ? l : trend === "A" ? l + ph * b : l * b ** ph;
|
|
870
|
+
const sm = season === "N" ? 0 : s[m - 1];
|
|
871
|
+
const mt = season === "N" ? T : season === "A" ? T + sm : T * sm;
|
|
872
|
+
const yv = error === "A" ? mt + ee : mt * (1 + ee);
|
|
873
|
+
out.push(yv);
|
|
874
|
+
// the same updates as the filter with this error
|
|
875
|
+
const f = etsFilter([yv], spec, { alpha: al, beta: be, gamma: ga, phi: ph, l, b, s: s.slice() });
|
|
876
|
+
const st = f.states[1];
|
|
877
|
+
l = st[0];
|
|
878
|
+
if (trend !== "N")
|
|
879
|
+
b = st[1];
|
|
880
|
+
s = st.slice(trend !== "N" ? 2 : 1);
|
|
881
|
+
}
|
|
882
|
+
return out;
|
|
883
|
+
}
|