assignment-user-matcher 1.16.0 → 1.22.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 (166) hide show
  1. package/README.md +312 -20
  2. package/dist/escalation/policy.d.ts +11 -0
  3. package/dist/escalation/policy.d.ts.map +1 -1
  4. package/dist/escalation/policy.js +22 -1
  5. package/dist/forecasting/backtest.d.ts +52 -0
  6. package/dist/forecasting/backtest.d.ts.map +1 -0
  7. package/dist/forecasting/backtest.js +195 -0
  8. package/dist/forecasting/calendar.d.ts +44 -0
  9. package/dist/forecasting/calendar.d.ts.map +1 -0
  10. package/dist/forecasting/calendar.js +85 -0
  11. package/dist/forecasting/cover.d.ts +69 -0
  12. package/dist/forecasting/cover.d.ts.map +1 -0
  13. package/dist/forecasting/cover.js +103 -0
  14. package/dist/forecasting/days.d.ts +17 -0
  15. package/dist/forecasting/days.d.ts.map +1 -0
  16. package/dist/forecasting/days.js +35 -0
  17. package/dist/forecasting/distributions.d.ts +31 -0
  18. package/dist/forecasting/distributions.d.ts.map +1 -0
  19. package/dist/forecasting/distributions.js +154 -0
  20. package/dist/forecasting/effects.d.ts +88 -0
  21. package/dist/forecasting/effects.d.ts.map +1 -0
  22. package/dist/forecasting/effects.js +303 -0
  23. package/dist/forecasting/erlang.d.ts +31 -0
  24. package/dist/forecasting/erlang.d.ts.map +1 -0
  25. package/dist/forecasting/erlang.js +86 -0
  26. package/dist/forecasting/forecast.d.ts +7 -0
  27. package/dist/forecasting/forecast.d.ts.map +1 -0
  28. package/dist/forecasting/forecast.js +221 -0
  29. package/dist/forecasting/index.d.ts +18 -0
  30. package/dist/forecasting/index.d.ts.map +1 -0
  31. package/dist/forecasting/index.js +54 -0
  32. package/dist/forecasting/model.d.ts +145 -0
  33. package/dist/forecasting/model.d.ts.map +1 -0
  34. package/dist/forecasting/model.js +583 -0
  35. package/dist/forecasting/nowcast.d.ts +26 -0
  36. package/dist/forecasting/nowcast.d.ts.map +1 -0
  37. package/dist/forecasting/nowcast.js +92 -0
  38. package/dist/forecasting/simulation.d.ts +91 -0
  39. package/dist/forecasting/simulation.d.ts.map +1 -0
  40. package/dist/forecasting/simulation.js +478 -0
  41. package/dist/forecasting/spikes.d.ts +6 -0
  42. package/dist/forecasting/spikes.d.ts.map +1 -0
  43. package/dist/forecasting/spikes.js +73 -0
  44. package/dist/forecasting/staffing.d.ts +64 -0
  45. package/dist/forecasting/staffing.d.ts.map +1 -0
  46. package/dist/forecasting/staffing.js +765 -0
  47. package/dist/forecasting/stats.d.ts +11 -0
  48. package/dist/forecasting/stats.d.ts.map +1 -0
  49. package/dist/forecasting/stats.js +45 -0
  50. package/dist/forecasting/types.d.ts +299 -0
  51. package/dist/forecasting/types.d.ts.map +1 -0
  52. package/dist/forecasting/types.js +8 -0
  53. package/dist/index.d.ts +3 -2
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +8 -1
  56. package/dist/learning/auto-weights.d.ts +1 -5
  57. package/dist/learning/auto-weights.d.ts.map +1 -1
  58. package/dist/learning/auto-weights.js +0 -3
  59. package/dist/lua/book-slot.lua +84 -0
  60. package/dist/lua/claim-queued.lua +47 -0
  61. package/dist/managers/DecisionTraceManager.d.ts +15 -0
  62. package/dist/managers/DecisionTraceManager.d.ts.map +1 -1
  63. package/dist/managers/DecisionTraceManager.js +117 -11
  64. package/dist/managers/LearningManager.d.ts +12 -0
  65. package/dist/managers/LearningManager.d.ts.map +1 -1
  66. package/dist/managers/LearningManager.js +21 -7
  67. package/dist/managers/ReliabilityManager.d.ts +1 -2
  68. package/dist/managers/ReliabilityManager.d.ts.map +1 -1
  69. package/dist/managers/ReliabilityManager.js +1 -1
  70. package/dist/managers/TelemetryManager.d.ts.map +1 -1
  71. package/dist/managers/TelemetryManager.js +9 -3
  72. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  73. package/dist/managers/WorkflowManager.js +3 -4
  74. package/dist/matcher.class.d.ts +319 -4
  75. package/dist/matcher.class.d.ts.map +1 -1
  76. package/dist/matcher.class.js +1428 -102
  77. package/dist/queries/lane-stats.d.ts +51 -0
  78. package/dist/queries/lane-stats.d.ts.map +1 -0
  79. package/dist/queries/lane-stats.js +78 -0
  80. package/dist/schedule/recurrence.d.ts +11 -0
  81. package/dist/schedule/recurrence.d.ts.map +1 -1
  82. package/dist/schedule/recurrence.js +19 -2
  83. package/dist/schedule/slot.d.ts +60 -0
  84. package/dist/schedule/slot.d.ts.map +1 -0
  85. package/dist/schedule/slot.js +86 -0
  86. package/dist/scheduling/constraints/availability.d.ts +2 -14
  87. package/dist/scheduling/constraints/availability.d.ts.map +1 -1
  88. package/dist/scheduling/constraints/availability.js +14 -15
  89. package/dist/scheduling/constraints/consecutive.d.ts +10 -0
  90. package/dist/scheduling/constraints/consecutive.d.ts.map +1 -1
  91. package/dist/scheduling/constraints/consecutive.js +64 -1
  92. package/dist/scheduling/constraints/contract.d.ts.map +1 -1
  93. package/dist/scheduling/constraints/contract.js +12 -3
  94. package/dist/scheduling/constraints/employee-scope.d.ts.map +1 -1
  95. package/dist/scheduling/constraints/employee-scope.js +10 -2
  96. package/dist/scheduling/constraints/group-composition.js +2 -2
  97. package/dist/scheduling/constraints/min-staffing.d.ts.map +1 -1
  98. package/dist/scheduling/constraints/min-staffing.js +51 -8
  99. package/dist/scheduling/constraints/rolling-hours.d.ts.map +1 -1
  100. package/dist/scheduling/constraints/rolling-hours.js +29 -4
  101. package/dist/scheduling/constraints/support.d.ts +4 -8
  102. package/dist/scheduling/constraints/support.d.ts.map +1 -1
  103. package/dist/scheduling/constraints/support.js +23 -2
  104. package/dist/scheduling/constraints/weekly-rest.d.ts +28 -0
  105. package/dist/scheduling/constraints/weekly-rest.d.ts.map +1 -1
  106. package/dist/scheduling/constraints/weekly-rest.js +108 -21
  107. package/dist/scheduling/engine/construction.d.ts.map +1 -1
  108. package/dist/scheduling/engine/construction.js +56 -7
  109. package/dist/scheduling/engine/objective.d.ts +0 -1
  110. package/dist/scheduling/engine/objective.d.ts.map +1 -1
  111. package/dist/scheduling/engine/objective.js +65 -6
  112. package/dist/scheduling/engine/search.d.ts +4 -0
  113. package/dist/scheduling/engine/search.d.ts.map +1 -1
  114. package/dist/scheduling/engine/search.js +2 -1
  115. package/dist/scheduling/engine/state.d.ts +14 -0
  116. package/dist/scheduling/engine/state.d.ts.map +1 -1
  117. package/dist/scheduling/engine/state.js +7 -0
  118. package/dist/scheduling/engine/timeline.d.ts +23 -1
  119. package/dist/scheduling/engine/timeline.d.ts.map +1 -1
  120. package/dist/scheduling/engine/timeline.js +85 -27
  121. package/dist/scheduling/engine/verdicts.d.ts +40 -1
  122. package/dist/scheduling/engine/verdicts.d.ts.map +1 -1
  123. package/dist/scheduling/engine/verdicts.js +177 -17
  124. package/dist/scheduling/index.d.ts +3 -2
  125. package/dist/scheduling/index.d.ts.map +1 -1
  126. package/dist/scheduling/index.js +7 -1
  127. package/dist/scheduling/model.d.ts +8 -4
  128. package/dist/scheduling/model.d.ts.map +1 -1
  129. package/dist/scheduling/model.js +239 -23
  130. package/dist/scheduling/operations.d.ts +174 -2
  131. package/dist/scheduling/operations.d.ts.map +1 -1
  132. package/dist/scheduling/operations.js +558 -21
  133. package/dist/scheduling/preference-report.d.ts +15 -0
  134. package/dist/scheduling/preference-report.d.ts.map +1 -0
  135. package/dist/scheduling/preference-report.js +111 -0
  136. package/dist/scheduling/preferences.d.ts +30 -0
  137. package/dist/scheduling/preferences.d.ts.map +1 -0
  138. package/dist/scheduling/preferences.js +85 -0
  139. package/dist/scheduling/resilience.d.ts +46 -0
  140. package/dist/scheduling/resilience.d.ts.map +1 -0
  141. package/dist/scheduling/resilience.js +45 -0
  142. package/dist/scheduling/scheduler.class.d.ts +12 -1
  143. package/dist/scheduling/scheduler.class.d.ts.map +1 -1
  144. package/dist/scheduling/scheduler.class.js +28 -4
  145. package/dist/scheduling/sites.d.ts +1 -1
  146. package/dist/scheduling/sites.d.ts.map +1 -1
  147. package/dist/scheduling/sites.js +34 -1
  148. package/dist/scheduling/time.d.ts +28 -6
  149. package/dist/scheduling/time.d.ts.map +1 -1
  150. package/dist/scheduling/time.js +59 -17
  151. package/dist/scheduling/types.d.ts +247 -7
  152. package/dist/scheduling/types.d.ts.map +1 -1
  153. package/dist/scoring/fair-arbitration.d.ts.map +1 -1
  154. package/dist/scoring/fair-arbitration.js +2 -1
  155. package/dist/tracing/decision-trace.d.ts +5 -0
  156. package/dist/tracing/decision-trace.d.ts.map +1 -1
  157. package/dist/tracing/decision-trace.js +3 -0
  158. package/dist/types/matcher.d.ts +369 -2
  159. package/dist/types/matcher.d.ts.map +1 -1
  160. package/dist/updates/assignment-update.d.ts +93 -0
  161. package/dist/updates/assignment-update.d.ts.map +1 -0
  162. package/dist/updates/assignment-update.js +91 -0
  163. package/dist/utils/keys.d.ts +10 -0
  164. package/dist/utils/keys.d.ts.map +1 -1
  165. package/dist/utils/keys.js +43 -0
  166. package/package.json +25 -3
@@ -0,0 +1,583 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.projectDay = exports.projectHour = exports.dayFactors = exports.effectOn = exports.expectedDay = exports.seasonFor = exports.levelFor = exports.explainedDay = exports.isOutlier = exports.fitSeries = exports.LEVEL_SHIFT_DAYS = exports.fitYearly = exports.actualOn = exports.prepareHistory = exports.OUTLIER = exports.YEARLY_MIN_WEEKS = exports.HOLT = void 0;
4
+ /**
5
+ * The forecast model for one series: a weekly level with a damped trend, a
6
+ * yearly factor once there is a year of history, the share of a week each
7
+ * weekday carries, the share of a day each hour carries, and the effects of
8
+ * holidays and events — each a plain number a planner can read back.
9
+ *
10
+ * Fitting reads only history strictly before `asOf`, so a rolling-origin
11
+ * backtest is the same function called with an earlier `asOf`.
12
+ *
13
+ * Grains: level, trend, the yearly factor and effects read the daily table's
14
+ * UTC days (`utcDayShare`, `expectedDay`); what an hour is forecast at reads
15
+ * local days (`dayShare` and `hourShape` from hourly history), since a UTC day
16
+ * is up to a day off a local one outside Europe. Shares are pooled ratios, not
17
+ * medians, so a sparse series keeps its quiet hours; learned effects and
18
+ * one-year yearly factors are shrunk towards 1 by their evidence.
19
+ */
20
+ const calendar_1 = require("./calendar");
21
+ const days_1 = require("./days");
22
+ const effects_1 = require("./effects");
23
+ const stats_1 = require("./stats");
24
+ /** Level smoothing (recency weight), trend smoothing, trend damping per week. */
25
+ exports.HOLT = { alpha: 0.35, beta: 0.1, phi: 0.9 };
26
+ /** Weeks of daily history before a yearly factor is fitted (spec §7.1). */
27
+ exports.YEARLY_MIN_WEEKS = 56;
28
+ /** Recent weeks the weekday and hour shapes are read from. */
29
+ const SHAPE_WEEKS = 8;
30
+ /** The largest weekly trend, as a share of the level. */
31
+ const MAX_TREND = 0.05;
32
+ /** A day this far off the model, relatively and in Poisson terms, is an outlier (and a spike candidate). */
33
+ exports.OUTLIER = { relative: 0.35, sigmas: 3 };
34
+ function prepareHistory(history) {
35
+ const days = new Map();
36
+ for (const p of history.daily)
37
+ days.set((0, days_1.dayOf)(p.date), p.value);
38
+ const fromHourly = new Map();
39
+ const hourly = new Map();
40
+ for (const p of history.hourly) {
41
+ hourly.set(p.at, (hourly.get(p.at) ?? 0) + p.value);
42
+ const d = (0, days_1.utcDay)(p.at);
43
+ fromHourly.set(d, (fromHourly.get(d) ?? 0) + p.value);
44
+ }
45
+ for (const [d, v] of fromHourly)
46
+ if (!days.has(d))
47
+ days.set(d, v);
48
+ let firstDay = Infinity;
49
+ let lastDay = -Infinity;
50
+ for (const d of days.keys()) {
51
+ if (d < firstDay)
52
+ firstDay = d;
53
+ if (d > lastDay)
54
+ lastDay = d;
55
+ }
56
+ if (!Number.isFinite(firstDay))
57
+ firstDay = lastDay = 0;
58
+ const daily = new Float64Array(days.size > 0 ? lastDay - firstDay + 1 : 0);
59
+ for (const [d, v] of days)
60
+ daily[d - firstDay] = v;
61
+ const hourlyPoints = [...hourly].map(([at, value]) => ({ at, value })).sort((a, b) => a.at - b.at);
62
+ return { series: history.series, firstDay, daily, hourly, hourlyPoints };
63
+ }
64
+ exports.prepareHistory = prepareHistory;
65
+ /** Actual volume on a day inside the fitted span; null outside it. */
66
+ function actualOn(model, day) {
67
+ if (!model.span || day < model.span.from || day > model.span.to)
68
+ return null;
69
+ return model.history.daily[day - model.history.firstDay] ?? 0;
70
+ }
71
+ exports.actualOn = actualOn;
72
+ function spanOf(history, asOf) {
73
+ const today = (0, days_1.utcDay)(asOf);
74
+ for (let i = 0; i < history.daily.length; i++) {
75
+ const day = history.firstDay + i;
76
+ if (day >= today)
77
+ break;
78
+ if (history.daily[i] > 0)
79
+ return { from: day, to: today - 1 };
80
+ }
81
+ return null;
82
+ }
83
+ /**
84
+ * Share of a week per weekday as a pooled ratio (Σ weekday ÷ Σ week) over the
85
+ * last clean weeks. A pooled ratio, not a median of per-week shares: a median
86
+ * of shares is biased towards 0 wherever a day is empty in most weeks.
87
+ * Null under two clean weeks.
88
+ */
89
+ function pooledDayShare(weeks) {
90
+ const sums = Array(7).fill(0);
91
+ let total = 0;
92
+ let used = 0;
93
+ for (const days of weeks.slice(-SHAPE_WEEKS)) {
94
+ const week = days.reduce((a, b) => a + b, 0);
95
+ if (week <= 0)
96
+ continue;
97
+ days.forEach((v, i) => (sums[i] += v));
98
+ total += week;
99
+ used += 1;
100
+ }
101
+ return used < 2 ? null : sums.map((v) => v / total);
102
+ }
103
+ /** Weekday shares of the daily table's UTC days, for weekly totals and in-sample expectations. */
104
+ function fitUtcDayShare(weeks, history, special) {
105
+ const at = (d) => history.daily[d - history.firstDay] ?? 0;
106
+ const clean = weeks.filter((monday) => [0, 1, 2, 3, 4, 5, 6].every((i) => !special.has(monday + i)));
107
+ return (pooledDayShare(clean.map((monday) => Array.from({ length: 7 }, (_, i) => at(monday + i)))) ?? Array(7).fill(1 / 7));
108
+ }
109
+ /**
110
+ * Tasks' worth of pseudo-count spread evenly over the 24 hours of the pooled shape, so a sparse series
111
+ * keeps every hour.
112
+ */
113
+ const HOUR_PRIOR = 12;
114
+ /** Tasks a weekday needs before its own hour shape outweighs the pooled one (weight n / (n + HOUR_SHRINK)). */
115
+ const HOUR_SHRINK = 20;
116
+ /**
117
+ * The shapes read from hourly history on local days: the share of a day each
118
+ * local hour carries per weekday, and the share of a week each local weekday
119
+ * carries (null without two complete clean local weeks — the UTC table's
120
+ * shares stand in then; a UTC day is up to a day off a local one outside
121
+ * Europe, so hourly history is the only honest source for local weekdays).
122
+ *
123
+ * Hour shares are pooled ratios (Σ hour ÷ Σ day), shrunk towards the shape of
124
+ * all weekdays together by how many tasks the weekday saw, and that pooled
125
+ * shape carries a small even prior: medians of per-day shares collapse to 0
126
+ * on a sparse series, where most days have no task in a given hour.
127
+ */
128
+ function fitLocalShapes(history, asOf, calendar, special) {
129
+ const none = { shape: Array(168).fill(1 / 24), has: false, dayShare: null };
130
+ const from = asOf - SHAPE_WEEKS * 7 * days_1.DAY_MS;
131
+ const points = history.hourlyPoints.filter((p) => p.at >= from && p.at < asOf);
132
+ if (points.length === 0)
133
+ return none;
134
+ const today = calendar.slot(Math.floor(asOf / calendar_1.HOUR_MS) * calendar_1.HOUR_MS).day;
135
+ const firstAt = Math.ceil(points[0].at / calendar_1.HOUR_MS) * calendar_1.HOUR_MS;
136
+ // The first local day is partial (the window or the series starts mid-day).
137
+ const partial = calendar.slot(firstAt).day;
138
+ const byDay = new Map();
139
+ // Every local day from the first hourly point on counts, busy or not: a missing hour is a zero.
140
+ for (let at = firstAt; at < asOf; at += calendar_1.HOUR_MS) {
141
+ const slot = calendar.slot(at);
142
+ if (slot.day === partial || slot.day >= today || special.has(slot.day) || byDay.has(slot.day))
143
+ continue;
144
+ byDay.set(slot.day, { weekday: slot.weekday, hours: Array(24).fill(0) });
145
+ }
146
+ for (const p of points) {
147
+ const slot = calendar.slot(p.at);
148
+ const day = byDay.get(slot.day);
149
+ if (day)
150
+ day.hours[slot.hour] += p.value;
151
+ }
152
+ const sums = Array.from({ length: 7 }, () => Array(24).fill(0));
153
+ const totals = Array(7).fill(0);
154
+ const pooled = Array(24).fill(0);
155
+ let all = 0;
156
+ const weeks = new Map();
157
+ for (const [dayNumber, day] of byDay) {
158
+ const total = day.hours.reduce((a, b) => a + b, 0);
159
+ const monday = dayNumber - (day.weekday - 1);
160
+ let week = weeks.get(monday);
161
+ if (!week)
162
+ weeks.set(monday, (week = Array(7).fill(Number.NaN)));
163
+ week[day.weekday - 1] = total;
164
+ day.hours.forEach((v, h) => {
165
+ sums[day.weekday - 1][h] += v;
166
+ pooled[h] += v;
167
+ });
168
+ totals[day.weekday - 1] += total;
169
+ all += total;
170
+ }
171
+ if (all <= 0)
172
+ return none;
173
+ const base = pooled.map((v) => (v + HOUR_PRIOR / 24) / (all + HOUR_PRIOR));
174
+ const shape = [];
175
+ for (let wd = 0; wd < 7; wd++) {
176
+ const n = totals[wd];
177
+ const w = n / (n + HOUR_SHRINK);
178
+ for (let h = 0; h < 24; h++)
179
+ shape.push(n > 0 ? w * (sums[wd][h] / n) + (1 - w) * base[h] : base[h]);
180
+ }
181
+ const complete = [...weeks.keys()]
182
+ .sort((a, b) => a - b)
183
+ .map((monday) => weeks.get(monday))
184
+ .filter((week) => week.every((v) => Number.isFinite(v)));
185
+ return { shape, has: true, dayShare: pooledDayShare(complete) };
186
+ }
187
+ /** Weight of a week-of-year factor seen in `years` distinct years: 1 year → ½, 2 → ⅔, 3 → ¾. */
188
+ const yearlyWeight = (years) => years / (years + 1);
189
+ /**
190
+ * Yearly factor per week of year, once ≥ 56 weeks of weekly totals exist.
191
+ * Each week is read against a straight trend line fitted over whole years
192
+ * only (the most recent 52·k weeks), so the season cancels out of the slope
193
+ * and a growing series does not read its latest weeks as "high season".
194
+ * Neighbouring weeks of the year are pooled (±1) and the factors normalised
195
+ * to average 1.
196
+ */
197
+ function fitYearly(weekly) {
198
+ const known = weekly.filter((w) => Number.isFinite(w.total));
199
+ if (known.length === 0)
200
+ return null;
201
+ const last = known[known.length - 1].monday;
202
+ const spanWeeks = (last - known[0].monday) / 7 + 1;
203
+ if (spanWeeks < exports.YEARLY_MIN_WEEKS)
204
+ return null;
205
+ const years = Math.floor(spanWeeks / 52);
206
+ const window = known.filter((w) => (last - w.monday) / 7 < 52 * years);
207
+ const t = (monday) => (monday - last) / 7;
208
+ const windowStart = t(window[0].monday);
209
+ const mx = window.reduce((s, w) => s + t(w.monday), 0) / window.length;
210
+ const my = window.reduce((s, w) => s + w.total, 0) / window.length;
211
+ let sxy = 0;
212
+ let sxx = 0;
213
+ for (const w of window) {
214
+ sxy += (t(w.monday) - mx) * (w.total - my);
215
+ sxx += (t(w.monday) - mx) ** 2;
216
+ }
217
+ const slope = sxx > 0 ? sxy / sxx : 0;
218
+ const ratios = new Map();
219
+ const yearsSeen = new Map();
220
+ for (const w of known) {
221
+ // Weeks older than the whole-years window read the line at its start: a
222
+ // slope extrapolated backwards (a recent step makes it steep) would read
223
+ // an ordinary old week as deep season.
224
+ const line = my + slope * (Math.max(t(w.monday), windowStart) - mx);
225
+ if (line <= 0)
226
+ continue;
227
+ const k = (0, days_1.weekOfYear)(w.monday);
228
+ for (const near of [k - 1, k, k + 1]) {
229
+ const key = (near + 53) % 53;
230
+ let list = ratios.get(key);
231
+ if (!list)
232
+ ratios.set(key, (list = []));
233
+ list.push(w.total / line);
234
+ let seen = yearsSeen.get(key);
235
+ if (!seen)
236
+ yearsSeen.set(key, (seen = new Set()));
237
+ seen.add(Math.floor((last - w.monday) / 364));
238
+ }
239
+ }
240
+ const factors = new Map();
241
+ for (const [k, rs] of ratios) {
242
+ // One year behind a week of the year cannot tell a season from a step
243
+ // that happened to land there: trust it by `yearlyWeight`.
244
+ const f = (0, stats_1.clamp)((0, stats_1.median)(rs), 0.3, 3);
245
+ factors.set(k, 1 + (f - 1) * yearlyWeight(yearsSeen.get(k).size));
246
+ }
247
+ if (factors.size === 0)
248
+ return null;
249
+ const avg = [...factors.values()].reduce((a, b) => a + b, 0) / factors.size;
250
+ for (const [k, f] of factors)
251
+ factors.set(k, f / avg);
252
+ return factors;
253
+ }
254
+ exports.fitYearly = fitYearly;
255
+ /** Days a same-direction outlier run must span to be read as a level shift rather than a spike. */
256
+ exports.LEVEL_SHIFT_DAYS = 7;
257
+ /** Fits one series as of `asOf`, then once more without its outlier days. */
258
+ function fitSeries(history, occurrences, calendar, asOf) {
259
+ const first = fitWith(history, occurrences, calendar, asOf, new Set(), null);
260
+ const outliers = outlierDays(first);
261
+ if (outliers.size === 0)
262
+ return first;
263
+ // One refit with the outliers left out, so an unexplained spike cannot drag the level (and hide itself)
264
+ // before anybody has named it. A run of at least a week that still holds at the end of history is a
265
+ // level shift, not a spike: it stays in, and the level is re-anchored on it. Only a large step (about
266
+ // ×2 or ×0.5) makes every day an outlier, so only such a step re-anchors, once it has lasted a week. A
267
+ // moderate step leaves few or no outlier days and is followed by the level smoothing alone, which lags
268
+ // it by 2–4 weeks. The nowcast and "What was this?" spans are where a fresh step shows.
269
+ const shiftFrom = levelShiftFrom(first, outliers);
270
+ const excluded = new Set([...outliers.keys()].filter((day) => shiftFrom === null || day < shiftFrom));
271
+ return fitWith(history, occurrences, calendar, asOf, excluded, shiftFrom);
272
+ }
273
+ exports.fitSeries = fitSeries;
274
+ /**
275
+ * First day of a level shift, or null. The latest run of same-direction outlier days (one quiet day in
276
+ * between does not break it) spanning at least `LEVEL_SHIFT_DAYS` is a shift when volume at the end of
277
+ * history is still off the level from before the run, the same way: over the last week and over the last
278
+ * two days, each summed and judged as an outlier. Judged against the level before the run, not the first
279
+ * fit's, because that fit has half-followed the step by then and its late days no longer read as outliers.
280
+ * A week-long burst that ended yesterday is read as a shift until a second ordinary day says otherwise.
281
+ */
282
+ function levelShiftFrom(first, outliers) {
283
+ const days = [...outliers.keys()].sort((a, b) => a - b);
284
+ let run = null;
285
+ let latest = null;
286
+ for (const day of days) {
287
+ const direction = outliers.get(day);
288
+ if (run && run.direction === direction && day - run.to <= 2)
289
+ run.to = day;
290
+ else
291
+ run = { from: day, to: day, direction };
292
+ if (run.to - run.from + 1 >= exports.LEVEL_SHIFT_DAYS)
293
+ latest = { ...run };
294
+ }
295
+ if (!latest || !first.span)
296
+ return null;
297
+ const shift = latest;
298
+ const before = levelFor(first, (0, days_1.mondayOfDay)(shift.from));
299
+ const special = (0, effects_1.specialDays)(first.occurrences);
300
+ const window = (length) => {
301
+ let actual = 0;
302
+ let expected = 0;
303
+ let seen = 0;
304
+ for (let day = first.span.to; day >= shift.from && seen < length; day--) {
305
+ if (special.has(day))
306
+ continue;
307
+ actual += actualOn(first, day) ?? 0;
308
+ expected += before * seasonFor(first, (0, days_1.mondayOfDay)(day)) * first.utcDayShare[(0, days_1.weekdayOf)(day) - 1];
309
+ seen += 1;
310
+ }
311
+ return isOutlier(actual, expected) && Math.sign(actual - expected) === shift.direction;
312
+ };
313
+ return window(exports.LEVEL_SHIFT_DAYS) && window(2) ? shift.from : null;
314
+ }
315
+ /** Whether an actual is far enough from an expectation to be unexplained. */
316
+ function isOutlier(actual, expected) {
317
+ if (expected < 1)
318
+ return false;
319
+ const off = Math.abs(actual - expected);
320
+ return off >= exports.OUTLIER.relative * expected && off >= exports.OUTLIER.sigmas * Math.sqrt(expected);
321
+ }
322
+ exports.isOutlier = isOutlier;
323
+ /** Expected volume on a day with every known holiday and event applied. */
324
+ function explainedDay(model, day) {
325
+ const effect = effectOn(model, day);
326
+ let e = expectedDay(model, day) * effect.holiday;
327
+ for (const ev of effect.events)
328
+ e *= ev.factor;
329
+ return e;
330
+ }
331
+ exports.explainedDay = explainedDay;
332
+ /** Outlier days and their direction (1 above the expectation, −1 below). */
333
+ function outlierDays(model) {
334
+ const out = new Map();
335
+ if (!model.span || model.level <= 0)
336
+ return out;
337
+ const special = (0, effects_1.specialDays)(model.occurrences);
338
+ for (let day = model.span.from + 1; day <= model.span.to; day++) {
339
+ if (special.has(day))
340
+ continue;
341
+ const actual = actualOn(model, day) ?? 0;
342
+ const expected = explainedDay(model, day);
343
+ if (isOutlier(actual, expected))
344
+ out.set(day, actual > expected ? 1 : -1);
345
+ }
346
+ return out;
347
+ }
348
+ function fitWith(history, occurrences, calendar, asOf, outliers, shiftFrom) {
349
+ const span = spanOf(history, asOf);
350
+ const special = (0, effects_1.specialDays)(occurrences);
351
+ for (const day of outliers)
352
+ special.add(day);
353
+ // History rarely starts at midnight: the first day is partial by construction.
354
+ if (span)
355
+ special.add(span.from);
356
+ const local = fitLocalShapes(history, asOf, calendar, special);
357
+ const { shape: hourShape, has: hasHourlyShape } = local;
358
+ const base = {
359
+ series: history.series,
360
+ asOf,
361
+ history,
362
+ span,
363
+ dayShare: Array(7).fill(1 / 7),
364
+ utcDayShare: Array(7).fill(1 / 7),
365
+ hourShape,
366
+ hasHourlyShape,
367
+ level: 0,
368
+ trend: 0,
369
+ lastWeek: null,
370
+ levels: new Map(),
371
+ yearly: null,
372
+ historyWeeks: 0,
373
+ learned: new Map(),
374
+ effects: new Map(),
375
+ occurrences,
376
+ };
377
+ if (!span)
378
+ return withEffects(base, special);
379
+ let monday = (0, days_1.mondayOfDay)(span.from);
380
+ if (monday < span.from)
381
+ monday += 7;
382
+ const weeks = [];
383
+ for (; monday + 6 <= span.to; monday += 7)
384
+ weeks.push(monday);
385
+ const utcDayShare = fitUtcDayShare(weeks, history, special);
386
+ const at = (d) => history.daily[d - history.firstDay] ?? 0;
387
+ const weekly = weeks.map((m) => {
388
+ let sum = 0;
389
+ let covered = 0;
390
+ for (let i = 0; i < 7; i++) {
391
+ if (special.has(m + i))
392
+ continue;
393
+ sum += at(m + i);
394
+ covered += utcDayShare[i];
395
+ }
396
+ return { monday: m, total: covered >= 0.35 ? sum / covered : Number.NaN };
397
+ });
398
+ const yearly = fitYearly(weekly);
399
+ const season = (m) => yearly?.get((0, days_1.weekOfYear)(m)) ?? 1;
400
+ let level = Number.NaN;
401
+ let trend = 0;
402
+ const levels = new Map();
403
+ for (const w of weekly) {
404
+ if (!Number.isFinite(w.total)) {
405
+ if (Number.isFinite(level)) {
406
+ level = Math.max(0, level + exports.HOLT.phi * trend);
407
+ trend *= exports.HOLT.phi;
408
+ levels.set(w.monday, level);
409
+ }
410
+ continue;
411
+ }
412
+ const x = w.total / season(w.monday);
413
+ if (!Number.isFinite(level)) {
414
+ level = x;
415
+ levels.set(w.monday, level);
416
+ continue;
417
+ }
418
+ const previous = level;
419
+ // The in-sample expectation for a week is the one-step-ahead forecast,
420
+ // made before the week is seen: a week never explains itself.
421
+ levels.set(w.monday, Math.max(0, level + exports.HOLT.phi * trend));
422
+ level = Math.max(0, exports.HOLT.alpha * x + (1 - exports.HOLT.alpha) * (level + exports.HOLT.phi * trend));
423
+ trend = exports.HOLT.beta * (level - previous) + (1 - exports.HOLT.beta) * exports.HOLT.phi * trend;
424
+ trend = (0, stats_1.clamp)(trend, -MAX_TREND * level, MAX_TREND * level);
425
+ }
426
+ if (!Number.isFinite(level)) {
427
+ // Under a week of history: the ordinary days there are, as a weekly rate.
428
+ let sum = 0;
429
+ let n = 0;
430
+ for (let d = span.from; d <= span.to; d++) {
431
+ if (special.has(d))
432
+ continue;
433
+ sum += at(d);
434
+ n += 1;
435
+ }
436
+ level = n > 0 ? (sum / n) * 7 : 0;
437
+ trend = 0;
438
+ }
439
+ else if (shiftFrom !== null) {
440
+ // A level shift: the level is the shifted days' own weekly rate, and a step is not a trend.
441
+ let sum = 0;
442
+ let covered = 0;
443
+ for (let d = shiftFrom; d <= span.to; d++) {
444
+ if (special.has(d))
445
+ continue;
446
+ sum += at(d);
447
+ covered += utcDayShare[(0, days_1.weekdayOf)(d) - 1] * season((0, days_1.mondayOfDay)(d));
448
+ }
449
+ if (covered > 0) {
450
+ level = sum / covered;
451
+ trend = 0;
452
+ }
453
+ }
454
+ return withEffects({
455
+ ...base,
456
+ dayShare: local.dayShare ?? utcDayShare,
457
+ utcDayShare,
458
+ level,
459
+ trend,
460
+ lastWeek: weeks.length > 0 ? weeks[weeks.length - 1] : null,
461
+ levels,
462
+ yearly,
463
+ historyWeeks: weeks.length,
464
+ }, special);
465
+ }
466
+ /**
467
+ * Learns effects from past occurrences against the fitted baseline, and resolves every occurrence's effect.
468
+ * The knock-on gate and single-occurrence ranges allow for the series' own day-level dispersion, read off
469
+ * the recent ordinary days (`SHAPE_WEEKS`, not special, not an outlier left out) against `expectedDay`.
470
+ */
471
+ function withEffects(model, special) {
472
+ const today = (0, days_1.utcDay)(model.asOf);
473
+ const past = model.occurrences.filter((occ) => occ.from < today);
474
+ const recent = [];
475
+ if (model.span && model.lastWeek !== null) {
476
+ for (let day = Math.max(model.span.from, model.span.to - SHAPE_WEEKS * 7 + 1); day <= model.span.to; day++) {
477
+ if (special.has(day))
478
+ continue;
479
+ recent.push({ actual: actualOn(model, day) ?? 0, expected: expectedDay(model, day) });
480
+ }
481
+ }
482
+ const learned = (0, effects_1.learnEffects)(past, (day) => actualOn(model, day), (day) => expectedDay(model, day), (0, effects_1.dayDispersion)(recent));
483
+ const effects = new Map();
484
+ for (const occ of model.occurrences)
485
+ effects.set(occ, (0, effects_1.effectFor)(occ.o, learned));
486
+ return { ...model, learned, effects };
487
+ }
488
+ /** Deseasonalised weekly level for a week: one-step-ahead in-sample, damped trend beyond. */
489
+ function levelFor(model, monday) {
490
+ const k = model.lastWeek === null ? 1 : Math.round((monday - model.lastWeek) / 7);
491
+ if (k <= 0) {
492
+ const fitted = model.levels.get(monday);
493
+ if (fitted !== undefined)
494
+ return fitted;
495
+ const first = model.levels.values().next();
496
+ return first.done ? model.level : first.value;
497
+ }
498
+ let damp = 0;
499
+ let phi = 1;
500
+ for (let i = 1; i <= k; i++) {
501
+ phi *= exports.HOLT.phi;
502
+ damp += phi;
503
+ }
504
+ return Math.max(0, model.level + damp * model.trend);
505
+ }
506
+ exports.levelFor = levelFor;
507
+ function seasonFor(model, monday) {
508
+ return model.yearly?.get((0, days_1.weekOfYear)(monday)) ?? 1;
509
+ }
510
+ exports.seasonFor = seasonFor;
511
+ /**
512
+ * Baseline volume for a UTC day of the daily table — level × season × UTC weekday share, no holiday
513
+ * or event. It is the in-sample yardstick effects and outliers are judged against, so it reads the
514
+ * table's own grain; an hour's local forecast is `projectHour`.
515
+ */
516
+ function expectedDay(model, day) {
517
+ const monday = (0, days_1.mondayOfDay)(day);
518
+ return levelFor(model, monday) * seasonFor(model, monday) * model.utcDayShare[(0, days_1.weekdayOf)(day) - 1];
519
+ }
520
+ exports.expectedDay = expectedDay;
521
+ function effectOn(model, day) {
522
+ return (0, effects_1.dayEffect)(day, model.occurrences, model.effects);
523
+ }
524
+ exports.effectOn = effectOn;
525
+ function dayFactors(model, day) {
526
+ const monday = (0, days_1.mondayOfDay)(day);
527
+ const effect = effectOn(model, day);
528
+ let factor = 1;
529
+ let low = 1;
530
+ let high = 1;
531
+ for (const e of effect.events) {
532
+ factor *= e.factor;
533
+ low *= e.low;
534
+ high *= e.high;
535
+ }
536
+ return {
537
+ ahead: levelFor(model, monday),
538
+ season: seasonFor(model, monday),
539
+ holiday: effect.holiday,
540
+ factor,
541
+ low,
542
+ high,
543
+ events: effect.events,
544
+ };
545
+ }
546
+ exports.dayFactors = dayFactors;
547
+ /** One hour's expectation with its components (nowcast 1). */
548
+ function projectHour(model, calendar, at) {
549
+ const slot = calendar.slot(at);
550
+ const share = model.dayShare[slot.weekday - 1] * model.hourShape[slot.how];
551
+ const d = dayFactors(model, slot.day);
552
+ const current = model.level;
553
+ const plain = d.ahead * share * d.season * d.holiday;
554
+ return {
555
+ likely: plain * d.factor,
556
+ // Holiday uncertainty is not in low/high (DayEffect.holiday carries a factor only), so a first-time
557
+ // default holiday's wide range is not shown here; the backtest ranges must cover it.
558
+ low: plain * Math.min(d.low, d.factor),
559
+ high: plain * Math.max(d.high, d.factor),
560
+ components: {
561
+ base: current * share,
562
+ trend: current > 0 ? d.ahead / current : 1,
563
+ season: d.season,
564
+ holiday: d.holiday,
565
+ events: d.events.map(({ label, factor: f }) => ({ label, factor: f })),
566
+ nowcast: 1,
567
+ },
568
+ };
569
+ }
570
+ exports.projectHour = projectHour;
571
+ /**
572
+ * One local day's expectation: exactly the sum of `projectHour` over the day's local hours (23, 24 or 25),
573
+ * in closed form — every hour of a day shares its factors, so only the hour shape is summed.
574
+ */
575
+ function projectDay(model, calendar, day) {
576
+ let shape = 0;
577
+ for (const how of calendar.dayHours(day))
578
+ shape += model.hourShape[how];
579
+ const d = dayFactors(model, day);
580
+ const plain = d.ahead * model.dayShare[(0, days_1.weekdayOf)(day) - 1] * shape * d.season * d.holiday;
581
+ return { likely: plain * d.factor, low: plain * Math.min(d.low, d.factor), high: plain * Math.max(d.high, d.factor) };
582
+ }
583
+ exports.projectDay = projectDay;
@@ -0,0 +1,26 @@
1
+ import type { HourForecast, HourlyPoint } from './types';
2
+ export declare const NOWCAST_HOURS = 72;
3
+ /**
4
+ * Pseudo-tasks added to both sides of the ratio: twelve seen over six expected at 7am is Poisson noise, not
5
+ * a doubling, and must not double the afternoon. Near-neutral early in a quiet day, full strength once
6
+ * hundreds of tasks back it.
7
+ */
8
+ export declare const NOWCAST_PRIOR = 25;
9
+ /** The latest drained hour may start at most this many hours before the current one, or there is no nowcast. */
10
+ export declare const NOWCAST_MAX_LAG_HOURS = 3;
11
+ export declare function nowcastRatio(actualSoFar: number, expectedSoFar: number): number;
12
+ /**
13
+ * Re-applies the nowcast to a stored forecast. `hours` must start at local
14
+ * midnight today (as `forecastWorkspace` writes them); any nowcast already on
15
+ * them is taken off first, so calling this every few minutes with fresh
16
+ * actuals is safe.
17
+ *
18
+ * `actual` lags the clock (hours are drained, not streamed), so only hours up
19
+ * to the latest one present in it are counted: an hour after it has not been
20
+ * drained yet and is never read as zero, while a missing hour before it is a
21
+ * zero. With nothing drained, or a latest hour that starts more than
22
+ * `NOWCAST_MAX_LAG_HOURS` before the current one, there is no nowcast (`[]`
23
+ * returns the forecast without one).
24
+ */
25
+ export declare function applyNowcast(hours: readonly HourForecast[], actual: readonly HourlyPoint[], now: number): HourForecast[];
26
+ //# sourceMappingURL=nowcast.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nowcast.d.ts","sourceRoot":"","sources":["../../src/forecasting/nowcast.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAGzD,eAAO,MAAM,aAAa,KAAK,CAAC;AAChC;;;;GAIG;AACH,eAAO,MAAM,aAAa,KAAK,CAAC;AAChC,gHAAgH;AAChH,eAAO,MAAM,qBAAqB,IAAI,CAAC;AAEvC,wBAAgB,YAAY,CAAC,WAAW,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,GAAG,MAAM,CAG/E;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,SAAS,YAAY,EAAE,EAAE,MAAM,EAAE,SAAS,WAAW,EAAE,EAAE,GAAG,EAAE,MAAM,GAAG,YAAY,EAAE,CAuCxH"}