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,52 @@
1
+ /**
2
+ * How wrong the model has been, measured the only honest way: refit it as of
3
+ * earlier days (rolling origins, one a week back from today) and compare what
4
+ * it would have said with what happened. The spread of those errors by lead
5
+ * time is the forecast's range; their size is its accuracy (WAPE).
6
+ *
7
+ * Forecast and actual are always compared on the same grain. Where the hourly
8
+ * table reaches back to an origin, ranges are read hour against hour and WAPE
9
+ * on local-day sums of those hours (what a planner reads as "the day"); an
10
+ * origin the hourly table does not reach is judged on UTC days of
11
+ * `explainedDay` against the daily table's UTC days. A UTC actual is never set
12
+ * against a local-day sum.
13
+ *
14
+ * Ranges are a negative binomial around the forecast: variance `f + c·f²`,
15
+ * Poisson counting noise plus a relative model error `c` fitted per lead
16
+ * bucket by moments, `c = max(0, Σ((a − f)² − f) ÷ Σf²)`, and held non-decreasing
17
+ * with lead (each bucket's `c` is at least the shorter bucket's). A ratio quantile of
18
+ * hours reads a quiet hour's Poisson noise as model error and spreads it over
19
+ * every busy hour, which is why ranges are not built that way.
20
+ */
21
+ import { ForecastCalendar } from './calendar';
22
+ import type { Occ } from './effects';
23
+ import { type PreparedHistory } from './model';
24
+ import type { ForecastAccuracy, LeadBucket } from './types';
25
+ export declare const LEAD_BUCKETS: ReadonlyArray<{
26
+ bucket: LeadBucket;
27
+ toHours: number;
28
+ }>;
29
+ /**
30
+ * Relative model error `c` used until a bucket has enough backtest samples: a p10–p90 of roughly ±20 %
31
+ * at 24 hours widening to ±40 % at 28 days, on top of Poisson noise.
32
+ */
33
+ export declare const DEFAULT_DISPERSION: Record<LeadBucket, number>;
34
+ /** Weekly total [p10, p90] of actual ÷ forecast, and the weekly `c`, used until four weeks were judged. */
35
+ export declare const DEFAULT_WEEK_RANGE: [number, number];
36
+ export declare const DEFAULT_WEEK_DISPERSION = 0.015;
37
+ /** A 72-hour WAPE above this makes the forecast low confidence. */
38
+ export declare const HIGH_ERROR_WAPE = 0.35;
39
+ export interface BacktestResult {
40
+ accuracy: Omit<ForecastAccuracy, 'lowConfidence' | 'reasons'>;
41
+ /** Per lead bucket: relative model error `c` (variance = f + c·f²). */
42
+ dispersion: Record<LeadBucket, number>;
43
+ /** Weekly total [p10, p90] of actual ÷ forecast, from complete weeks after each origin. */
44
+ weekRange: [number, number];
45
+ /** Relative model error `c` of weekly totals. */
46
+ weekDispersion: number;
47
+ }
48
+ /** What a series that is not backtested reports: nothing measured, the total's ranges. */
49
+ export declare function borrowed(from: BacktestResult): BacktestResult;
50
+ export declare const bucketOf: (leadHours: number) => LeadBucket;
51
+ export declare function backtest(history: PreparedHistory, occurrences: readonly Occ[], calendar: ForecastCalendar, now: number, origins: number): BacktestResult;
52
+ //# sourceMappingURL=backtest.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backtest.d.ts","sourceRoot":"","sources":["../../src/forecasting/backtest.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,OAAO,EAAE,gBAAgB,EAAW,MAAM,YAAY,CAAC;AAEvD,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACrC,OAAO,EAAwC,KAAK,eAAe,EAAE,MAAM,SAAS,CAAC;AACrF,OAAO,KAAK,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAG5D,eAAO,MAAM,YAAY,EAAE,aAAa,CAAC;IAAE,MAAM,EAAE,UAAU,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAK/E,CAAC;AACF;;;GAGG;AACH,eAAO,MAAM,kBAAkB,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM,CAA2D,CAAC;AACtH,2GAA2G;AAC3G,eAAO,MAAM,kBAAkB,EAAE,CAAC,MAAM,EAAE,MAAM,CAAgB,CAAC;AACjE,eAAO,MAAM,uBAAuB,QAAQ,CAAC;AAO7C,mEAAmE;AACnE,eAAO,MAAM,eAAe,OAAO,CAAC;AAGpC,MAAM,WAAW,cAAc;IAC3B,QAAQ,EAAE,IAAI,CAAC,gBAAgB,EAAE,eAAe,GAAG,SAAS,CAAC,CAAC;IAC9D,uEAAuE;IACvE,UAAU,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;IACvC,2FAA2F;IAC3F,SAAS,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC5B,iDAAiD;IACjD,cAAc,EAAE,MAAM,CAAC;CAC1B;AAED,0FAA0F;AAC1F,wBAAgB,QAAQ,CAAC,IAAI,EAAE,cAAc,GAAG,cAAc,CAQ7D;AAED,eAAO,MAAM,QAAQ,cAAe,MAAM,KAAG,UACwD,CAAC;AA+BtG,wBAAgB,QAAQ,CACpB,OAAO,EAAE,eAAe,EACxB,WAAW,EAAE,SAAS,GAAG,EAAE,EAC3B,QAAQ,EAAE,gBAAgB,EAC1B,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,MAAM,GAChB,cAAc,CA2GhB"}
@@ -0,0 +1,195 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.backtest = exports.bucketOf = exports.borrowed = exports.HIGH_ERROR_WAPE = exports.DEFAULT_WEEK_DISPERSION = exports.DEFAULT_WEEK_RANGE = exports.DEFAULT_DISPERSION = exports.LEAD_BUCKETS = void 0;
4
+ /**
5
+ * How wrong the model has been, measured the only honest way: refit it as of
6
+ * earlier days (rolling origins, one a week back from today) and compare what
7
+ * it would have said with what happened. The spread of those errors by lead
8
+ * time is the forecast's range; their size is its accuracy (WAPE).
9
+ *
10
+ * Forecast and actual are always compared on the same grain. Where the hourly
11
+ * table reaches back to an origin, ranges are read hour against hour and WAPE
12
+ * on local-day sums of those hours (what a planner reads as "the day"); an
13
+ * origin the hourly table does not reach is judged on UTC days of
14
+ * `explainedDay` against the daily table's UTC days. A UTC actual is never set
15
+ * against a local-day sum.
16
+ *
17
+ * Ranges are a negative binomial around the forecast: variance `f + c·f²`,
18
+ * Poisson counting noise plus a relative model error `c` fitted per lead
19
+ * bucket by moments, `c = max(0, Σ((a − f)² − f) ÷ Σf²)`, and held non-decreasing
20
+ * with lead (each bucket's `c` is at least the shorter bucket's). A ratio quantile of
21
+ * hours reads a quiet hour's Poisson noise as model error and spreads it over
22
+ * every busy hour, which is why ranges are not built that way.
23
+ */
24
+ const calendar_1 = require("./calendar");
25
+ const days_1 = require("./days");
26
+ const model_1 = require("./model");
27
+ const stats_1 = require("./stats");
28
+ exports.LEAD_BUCKETS = [
29
+ { bucket: '24h', toHours: 24 },
30
+ { bucket: '72h', toHours: 72 },
31
+ { bucket: '7d', toHours: 168 },
32
+ { bucket: '28d', toHours: 672 },
33
+ ];
34
+ /**
35
+ * Relative model error `c` used until a bucket has enough backtest samples: a p10–p90 of roughly ±20 %
36
+ * at 24 hours widening to ±40 % at 28 days, on top of Poisson noise.
37
+ */
38
+ exports.DEFAULT_DISPERSION = { '24h': 0.025, '72h': 0.035, '7d': 0.055, '28d': 0.1 };
39
+ /** Weekly total [p10, p90] of actual ÷ forecast, and the weekly `c`, used until four weeks were judged. */
40
+ exports.DEFAULT_WEEK_RANGE = [0.85, 1.18];
41
+ exports.DEFAULT_WEEK_DISPERSION = 0.015;
42
+ /** Samples a bucket needs before its own dispersion replaces the default. */
43
+ const MIN_SAMPLES = 48;
44
+ /** Complete weeks the weekly range and dispersion need. */
45
+ const MIN_WEEKS = 4;
46
+ /** An origin needs this many days of history before it. */
47
+ const MIN_HISTORY_DAYS = 21;
48
+ /** A 72-hour WAPE above this makes the forecast low confidence. */
49
+ exports.HIGH_ERROR_WAPE = 0.35;
50
+ const HORIZON_HOURS = 672;
51
+ /** What a series that is not backtested reports: nothing measured, the total's ranges. */
52
+ function borrowed(from) {
53
+ const none = { '24h': null, '72h': null, '7d': null, '28d': null };
54
+ return {
55
+ accuracy: { wape: none, origins: 0, rangesFrom: from.accuracy.rangesFrom === 'own' ? 'total' : 'default' },
56
+ dispersion: from.dispersion,
57
+ weekRange: from.weekRange,
58
+ weekDispersion: from.weekDispersion,
59
+ };
60
+ }
61
+ exports.borrowed = borrowed;
62
+ const bucketOf = (leadHours) => (exports.LEAD_BUCKETS.find((b) => leadHours < b.toHours) ?? exports.LEAD_BUCKETS[exports.LEAD_BUCKETS.length - 1]).bucket;
63
+ exports.bucketOf = bucketOf;
64
+ const perBucket = () => ({ '24h': 0, '72h': 0, '7d': 0, '28d': 0 });
65
+ /** Moment estimate of the negative binomial's `c`; 0 when the errors are no larger than Poisson. */
66
+ const dispersionOf = (excess, squares) => (squares > 0 ? Math.max(0, excess / squares) : 0);
67
+ /** One sample of the range: an hour (or, on the daily grain, a UTC day). */
68
+ function judgeRange(tally, bucket, a, f) {
69
+ if (f <= 0)
70
+ return;
71
+ tally.excess[bucket] += (a - f) ** 2 - f;
72
+ tally.squares[bucket] += f * f;
73
+ tally.samples[bucket] += 1;
74
+ }
75
+ /** One sample of the error: a local day of hours (or, on the daily grain, a UTC day). */
76
+ function judgeError(tally, bucket, a, f) {
77
+ tally.abs[bucket] += Math.abs(a - f);
78
+ tally.act[bucket] += a;
79
+ }
80
+ function backtest(history, occurrences, calendar, now, origins) {
81
+ const firstHour = history.hourlyPoints.length > 0 ? history.hourlyPoints[0].at : Infinity;
82
+ // Hours after the latest one the feed has delivered have not been drained yet; they are not zeros. As
83
+ // in `applyNowcast`, the hourly comparison reads up to the latest hourly point before `now`, plus its hour.
84
+ let latest = -Infinity;
85
+ for (const p of history.hourlyPoints)
86
+ if (p.at < now && p.at > latest)
87
+ latest = p.at;
88
+ const drainedUntil = Math.min(now, latest + calendar_1.HOUR_MS);
89
+ const earliest = history.daily.length > 0 ? history.firstDay * days_1.DAY_MS : Infinity;
90
+ const tally = {
91
+ excess: perBucket(),
92
+ squares: perBucket(),
93
+ samples: perBucket(),
94
+ abs: perBucket(),
95
+ act: perBucket(),
96
+ };
97
+ const weekRatios = [];
98
+ let weekExcess = 0;
99
+ let weekSquares = 0;
100
+ let judged = 0;
101
+ const today = calendar.slot(Math.floor(now / calendar_1.HOUR_MS) * calendar_1.HOUR_MS);
102
+ const todayMidnight = calendar.midnight(today.date);
103
+ for (let j = 1; j <= origins; j++) {
104
+ // Local midnight 7·j days back; the calendar settles any DST hour in between.
105
+ const origin = calendar.midnight(calendar.slot(todayMidnight - 7 * j * days_1.DAY_MS + 12 * calendar_1.HOUR_MS).date);
106
+ if (!Number.isFinite(earliest) || origin - earliest < MIN_HISTORY_DAYS * days_1.DAY_MS)
107
+ continue;
108
+ const model = (0, model_1.fitSeries)(history, occurrences, calendar, origin);
109
+ if (model.level <= 0)
110
+ continue;
111
+ judged += 1;
112
+ const horizonEnd = origin + HORIZON_HOURS * calendar_1.HOUR_MS;
113
+ // Weekly totals on the comparison's own grain, for weeks after the origin's.
114
+ const weekSums = new Map();
115
+ const addWeek = (week, end, a, f) => {
116
+ const sum = weekSums.get(week) ?? { a: 0, f: 0, end };
117
+ sum.a += a;
118
+ sum.f += f;
119
+ weekSums.set(week, sum);
120
+ };
121
+ if (firstHour <= origin) {
122
+ const originWeek = (0, days_1.mondayOfDay)(calendar.slot(origin).day);
123
+ let day = { day: calendar.slot(origin).day, lead: 0, a: 0, f: 0 };
124
+ for (let h = 0; h < HORIZON_HOURS; h++) {
125
+ const at = origin + h * calendar_1.HOUR_MS;
126
+ if (at >= drainedUntil)
127
+ break;
128
+ const slot = calendar.slot(at);
129
+ if (slot.day !== day.day) {
130
+ // A local day is complete: its sum is one error sample. The last, cut-off day never is.
131
+ judgeError(tally, (0, exports.bucketOf)(day.lead), day.a, day.f);
132
+ day = { day: slot.day, lead: h, a: 0, f: 0 };
133
+ }
134
+ const f = (0, model_1.projectHour)(model, calendar, at).likely;
135
+ const a = history.hourly.get(at) ?? 0;
136
+ judgeRange(tally, (0, exports.bucketOf)(h), a, f);
137
+ day.a += a;
138
+ day.f += f;
139
+ const week = (0, days_1.mondayOfDay)(slot.day);
140
+ if (week > originWeek)
141
+ addWeek(week, calendar.midnight((0, days_1.dateOf)(week + 7)), a, f);
142
+ }
143
+ }
144
+ else {
145
+ // The hourly table does not reach back this far: judge whole UTC days of the daily table.
146
+ const originWeek = (0, days_1.mondayOfDay)((0, days_1.utcDay)(origin));
147
+ for (let day = Math.ceil(origin / days_1.DAY_MS); (day + 1) * days_1.DAY_MS <= now; day++) {
148
+ const lead = (day * days_1.DAY_MS - origin) / calendar_1.HOUR_MS;
149
+ if (lead >= HORIZON_HOURS)
150
+ break;
151
+ const f = (0, model_1.explainedDay)(model, day);
152
+ const a = history.daily[day - history.firstDay] ?? 0;
153
+ judgeRange(tally, (0, exports.bucketOf)(lead), a, f);
154
+ judgeError(tally, (0, exports.bucketOf)(lead), a, f);
155
+ const week = (0, days_1.mondayOfDay)(day);
156
+ if (week > originWeek)
157
+ addWeek(week, (week + 7) * days_1.DAY_MS, a, f);
158
+ }
159
+ }
160
+ for (const sum of weekSums.values()) {
161
+ // A week `now` or the horizon cuts is partly elapsed: not a week's error.
162
+ if (sum.end > (firstHour <= origin ? drainedUntil : now) || sum.end > horizonEnd || sum.f < 1)
163
+ continue;
164
+ weekRatios.push(sum.a / sum.f);
165
+ weekExcess += (sum.a - sum.f) ** 2 - sum.f;
166
+ weekSquares += sum.f * sum.f;
167
+ }
168
+ }
169
+ const dispersion = {};
170
+ const wape = {};
171
+ // A forecast never gets surer further out: each bucket's `c` is at least the one before it, so a
172
+ // noisy short-lead estimate cannot leave the 72-hour band narrower than the 24-hour one.
173
+ let floor = 0;
174
+ for (const { bucket } of exports.LEAD_BUCKETS) {
175
+ const own = tally.samples[bucket] >= MIN_SAMPLES
176
+ ? dispersionOf(tally.excess[bucket], tally.squares[bucket])
177
+ : exports.DEFAULT_DISPERSION[bucket];
178
+ dispersion[bucket] = Math.max(floor, own);
179
+ floor = dispersion[bucket];
180
+ wape[bucket] = tally.act[bucket] > 0 ? Math.round((tally.abs[bucket] / tally.act[bucket]) * 1000) / 1000 : null;
181
+ }
182
+ const weeks = weekRatios.sort((a, b) => a - b);
183
+ const enoughWeeks = weeks.length >= MIN_WEEKS;
184
+ const weekRange = enoughWeeks
185
+ ? [Math.min(1, (0, stats_1.quantileSorted)(weeks, 0.1)), Math.max(1, (0, stats_1.quantileSorted)(weeks, 0.9))]
186
+ : exports.DEFAULT_WEEK_RANGE;
187
+ const own = exports.LEAD_BUCKETS.some(({ bucket }) => tally.samples[bucket] >= MIN_SAMPLES);
188
+ return {
189
+ accuracy: { wape, origins: judged, rangesFrom: own ? 'own' : 'default' },
190
+ dispersion,
191
+ weekRange,
192
+ weekDispersion: enoughWeeks ? dispersionOf(weekExcess, weekSquares) : exports.DEFAULT_WEEK_DISPERSION,
193
+ };
194
+ }
195
+ exports.backtest = backtest;
@@ -0,0 +1,44 @@
1
+ import { DAY_MS } from './days';
2
+ export { DAY_MS };
3
+ export declare const HOUR_MS = 3600000;
4
+ export interface LocalSlot {
5
+ /** Local date, `YYYY-MM-DD`. */
6
+ date: string;
7
+ /** Local date as a day number (days since 1970-01-01). */
8
+ day: number;
9
+ /** Local hour of the day, 0–23. */
10
+ hour: number;
11
+ /** ISO weekday of the local date, 1 (Mon) – 7 (Sun). */
12
+ weekday: number;
13
+ /** Hour of the week, 0–167. */
14
+ how: number;
15
+ }
16
+ /**
17
+ * Local slots for UTC hours, memoised. Construct one per run over the whole
18
+ * span it will be asked about and share it across every series of a
19
+ * workspace: they are all read in the same zone.
20
+ */
21
+ export declare class ForecastCalendar {
22
+ readonly timeZone: string;
23
+ private readonly clock;
24
+ private readonly originDay;
25
+ private readonly slots;
26
+ private readonly dayStarts;
27
+ private readonly dayHowLists;
28
+ constructor(timeZone: string, fromMs: number, toMs: number);
29
+ slot(atMs: number): LocalSlot;
30
+ /**
31
+ * Hour-of-week of every local hour of a local day (day number), in order: 24 on an ordinary
32
+ * day, 23 or 25 on a clock change (the repeated hour appears twice). Memoised per day.
33
+ */
34
+ dayHours(day: number): readonly number[];
35
+ /** Epoch ms of local midnight on a date. */
36
+ midnight(date: string): number;
37
+ private dayStart;
38
+ /**
39
+ * Local hour of a period minute. On an ordinary 24-hour day it is plain
40
+ * arithmetic; only a transition day asks the clock what the wall shows.
41
+ */
42
+ private hourOf;
43
+ }
44
+ //# sourceMappingURL=calendar.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"calendar.d.ts","sourceRoot":"","sources":["../../src/forecasting/calendar.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,MAAM,EAA4B,MAAM,QAAQ,CAAC;AAE1D,OAAO,EAAE,MAAM,EAAE,CAAC;AAClB,eAAO,MAAM,OAAO,UAAY,CAAC;AAEjC,MAAM,WAAW,SAAS;IACtB,gCAAgC;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,0DAA0D;IAC1D,GAAG,EAAE,MAAM,CAAC;IACZ,mCAAmC;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,wDAAwD;IACxD,OAAO,EAAE,MAAM,CAAC;IAChB,+BAA+B;IAC/B,GAAG,EAAE,MAAM,CAAC;CACf;AAED;;;;GAIG;AACH,qBAAa,gBAAgB;IACzB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAc;IACpC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAgC;IACtD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA6B;IACvD,OAAO,CAAC,QAAQ,CAAC,WAAW,CAA+B;gBAE/C,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM;IAQ1D,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS;IAa7B;;;OAGG;IACH,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE;IAWxC,4CAA4C;IAC5C,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;IAI9B,OAAO,CAAC,QAAQ;IAShB;;;OAGG;IACH,OAAO,CAAC,MAAM;CAKjB"}
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ForecastCalendar = exports.HOUR_MS = exports.DAY_MS = void 0;
4
+ /**
5
+ * Wall-clock reading of UTC hours for forecasting, through the scheduling
6
+ * module's `PeriodClock` — the one place the engine turns instants into local
7
+ * dates and times, so a DST week is read the same way here as in a roster.
8
+ *
9
+ * Hour-of-week (`how`) is `(isoWeekday − 1) × 24 + localHour`: 0 = Monday
10
+ * 00:00–01:00 local. On a fall-back night two UTC hours read as the same local
11
+ * hour; on a spring-forward night one local hour never happens. Both are
12
+ * honest readings of the wall clock people work to.
13
+ */
14
+ const time_1 = require("../scheduling/time");
15
+ const days_1 = require("./days");
16
+ Object.defineProperty(exports, "DAY_MS", { enumerable: true, get: function () { return days_1.DAY_MS; } });
17
+ exports.HOUR_MS = 3600000;
18
+ /**
19
+ * Local slots for UTC hours, memoised. Construct one per run over the whole
20
+ * span it will be asked about and share it across every series of a
21
+ * workspace: they are all read in the same zone.
22
+ */
23
+ class ForecastCalendar {
24
+ constructor(timeZone, fromMs, toMs) {
25
+ this.slots = new Map();
26
+ this.dayStarts = new Map();
27
+ this.dayHowLists = new Map();
28
+ this.timeZone = timeZone;
29
+ // A day either side: a local date can sit a day off the UTC one.
30
+ this.originDay = Math.floor(fromMs / days_1.DAY_MS) - 1;
31
+ const days = Math.max(1, Math.ceil((toMs - fromMs) / days_1.DAY_MS) + 3);
32
+ this.clock = new time_1.PeriodClock((0, days_1.dateOf)(this.originDay), days, timeZone);
33
+ }
34
+ slot(atMs) {
35
+ const cached = this.slots.get(atMs);
36
+ if (cached)
37
+ return cached;
38
+ const minute = this.clock.fromEpochMs(atMs);
39
+ const index = this.clock.dayIndexOfMinute(minute);
40
+ const day = this.originDay + index;
41
+ const hour = this.hourOf(index, minute);
42
+ const weekday = (0, days_1.weekdayOf)(day);
43
+ const slot = { date: (0, days_1.dateOf)(day), day, hour, weekday, how: (weekday - 1) * 24 + hour };
44
+ this.slots.set(atMs, slot);
45
+ return slot;
46
+ }
47
+ /**
48
+ * Hour-of-week of every local hour of a local day (day number), in order: 24 on an ordinary
49
+ * day, 23 or 25 on a clock change (the repeated hour appears twice). Memoised per day.
50
+ */
51
+ dayHours(day) {
52
+ let hows = this.dayHowLists.get(day);
53
+ if (!hows) {
54
+ hows = [];
55
+ const end = this.midnight((0, days_1.dateOf)(day + 1));
56
+ for (let at = this.midnight((0, days_1.dateOf)(day)); at < end; at += exports.HOUR_MS)
57
+ hows.push(this.slot(at).how);
58
+ this.dayHowLists.set(day, hows);
59
+ }
60
+ return hows;
61
+ }
62
+ /** Epoch ms of local midnight on a date. */
63
+ midnight(date) {
64
+ return this.clock.toEpochMs(this.dayStart((0, days_1.dayOf)(date) - this.originDay));
65
+ }
66
+ dayStart(index) {
67
+ let start = this.dayStarts.get(index);
68
+ if (start === undefined) {
69
+ start = this.clock.dayStartMinutes(index);
70
+ this.dayStarts.set(index, start);
71
+ }
72
+ return start;
73
+ }
74
+ /**
75
+ * Local hour of a period minute. On an ordinary 24-hour day it is plain
76
+ * arithmetic; only a transition day asks the clock what the wall shows.
77
+ */
78
+ hourOf(index, minute) {
79
+ const start = this.dayStart(index);
80
+ if (this.dayStart(index + 1) - start === 1440)
81
+ return Math.floor((minute - start) / 60);
82
+ return Math.floor(this.clock.localTimeOf(this.clock.toEpochMs(minute)).minuteOfDay / 60);
83
+ }
84
+ }
85
+ exports.ForecastCalendar = ForecastCalendar;
@@ -0,0 +1,69 @@
1
+ /**
2
+ * From people needed per hour to people per shift: the fewest heads on a
3
+ * day's shifts that cover every hour's need. Greedy left to right — at the
4
+ * first hour still short, add a person to the covering shift that runs
5
+ * latest — which is optimal for covering a line with intervals of equal cost
6
+ * when no shift has a ceiling. A shift's own minimum is a floor (never
7
+ * proposed below it) and its maximum a ceiling; an hour no shift can cover is
8
+ * reported, never silently dropped.
9
+ *
10
+ * A shift covers an hour when it overlaps it at all: a shift that starts at
11
+ * 13:30 counts for the 13:00 hour. Need is read in whole people (a fractional
12
+ * need rounds up).
13
+ *
14
+ * `counts` never exceeds a shift's `max`, so `counts` alone can read as
15
+ * "covered" on a day that is not: whatever an hour needs beyond what its
16
+ * overlapping shifts can hold is in `unmet` — with no shift there
17
+ * (`'no-shift'`) or with every covering shift full (`'at-max'`). A caller that
18
+ * shows `counts` must show `unmet` beside it.
19
+ */
20
+ export interface CoverShift {
21
+ id: string;
22
+ /** Epoch ms, `[startMs, endMs)`. */
23
+ startMs: number;
24
+ endMs: number;
25
+ /** Floor: the shift is never proposed with fewer people. */
26
+ min: number;
27
+ /**
28
+ * Ceiling. `null` or omitted means no ceiling — the shift takes as many people as the need asks. This
29
+ * differs from the scheduler, where an unstated `maxEmployees` is no room (`max = min`): here a caller
30
+ * that means "exactly the minimum" must say `max: min`.
31
+ */
32
+ max?: number | null;
33
+ }
34
+ /** An hour (or, from `coverPersonHours`, a day) whose need the shifts could not hold. */
35
+ export interface CoverUnmet {
36
+ /** Epoch ms of the hour (`coverPersonHours`: the first shift's start, or 0 without shifts). */
37
+ at: number;
38
+ /** Whole people (`coverPersonHours`: whole person-hours) missing. */
39
+ short: number;
40
+ /** `'no-shift'`: no shift overlaps the hour. `'at-max'`: every covering shift is at its `max`. */
41
+ reason: 'no-shift' | 'at-max';
42
+ /** Ids of the covering shifts that are at their `max` (empty for `'no-shift'`). */
43
+ atMax: string[];
44
+ }
45
+ export interface CoverResult {
46
+ /**
47
+ * People per shift id, between each shift's `min` and `max`. Capped at `max`: need beyond it is in
48
+ * `unmet`, never here, so `counts` must not be shown without `unmet`.
49
+ */
50
+ counts: Record<string, number>;
51
+ /**
52
+ * Every hour whose need exceeds what its overlapping shifts can hold, with how many were missing —
53
+ * including when every covering shift is full. Empty only when every hour's need is met.
54
+ */
55
+ unmet: CoverUnmet[];
56
+ }
57
+ export declare function coverNeed(need: ReadonlyArray<{
58
+ at: number;
59
+ people: number;
60
+ }>, shifts: readonly CoverShift[]): CoverResult;
61
+ /**
62
+ * Person-hours for the day (a rate conversion without an hourly pattern)
63
+ * spread over the day's shifts: raise the longest shift first, one person at a
64
+ * time and in turn, until their hours cover it. What no shift can take (every
65
+ * one at its ceiling, or no shifts at all) is reported as one shortfall in
66
+ * whole person-hours at the first shift's start.
67
+ */
68
+ export declare function coverPersonHours(personHours: number, shifts: readonly CoverShift[]): CoverResult;
69
+ //# sourceMappingURL=cover.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cover.d.ts","sourceRoot":"","sources":["../../src/forecasting/cover.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,MAAM,WAAW,UAAU;IACvB,EAAE,EAAE,MAAM,CAAC;IACX,oCAAoC;IACpC,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,4DAA4D;IAC5D,GAAG,EAAE,MAAM,CAAC;IACZ;;;;OAIG;IACH,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACvB;AAED,yFAAyF;AACzF,MAAM,WAAW,UAAU;IACvB,+FAA+F;IAC/F,EAAE,EAAE,MAAM,CAAC;IACX,qEAAqE;IACrE,KAAK,EAAE,MAAM,CAAC;IACd,kGAAkG;IAClG,MAAM,EAAE,UAAU,GAAG,QAAQ,CAAC;IAC9B,mFAAmF;IACnF,KAAK,EAAE,MAAM,EAAE,CAAC;CACnB;AAED,MAAM,WAAW,WAAW;IACxB;;;OAGG;IACH,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC/B;;;OAGG;IACH,KAAK,EAAE,UAAU,EAAE,CAAC;CACvB;AAID,wBAAgB,SAAS,CAAC,IAAI,EAAE,aAAa,CAAC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,EAAE,MAAM,EAAE,SAAS,UAAU,EAAE,GAAG,WAAW,CA+BzH;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,UAAU,EAAE,GAAG,WAAW,CAiChG"}
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+ /**
3
+ * From people needed per hour to people per shift: the fewest heads on a
4
+ * day's shifts that cover every hour's need. Greedy left to right — at the
5
+ * first hour still short, add a person to the covering shift that runs
6
+ * latest — which is optimal for covering a line with intervals of equal cost
7
+ * when no shift has a ceiling. A shift's own minimum is a floor (never
8
+ * proposed below it) and its maximum a ceiling; an hour no shift can cover is
9
+ * reported, never silently dropped.
10
+ *
11
+ * A shift covers an hour when it overlaps it at all: a shift that starts at
12
+ * 13:30 counts for the 13:00 hour. Need is read in whole people (a fractional
13
+ * need rounds up).
14
+ *
15
+ * `counts` never exceeds a shift's `max`, so `counts` alone can read as
16
+ * "covered" on a day that is not: whatever an hour needs beyond what its
17
+ * overlapping shifts can hold is in `unmet` — with no shift there
18
+ * (`'no-shift'`) or with every covering shift full (`'at-max'`). A caller that
19
+ * shows `counts` must show `unmet` beside it.
20
+ */
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.coverPersonHours = exports.coverNeed = void 0;
23
+ const HOUR_MS = 3600000;
24
+ function coverNeed(need, shifts) {
25
+ const counts = {};
26
+ for (const s of shifts)
27
+ counts[s.id] = Math.max(0, s.min);
28
+ const unmet = [];
29
+ const hours = [...need].sort((a, b) => a.at - b.at);
30
+ const covering = (at) => shifts.filter((s) => s.startMs < at + HOUR_MS && s.endMs > at);
31
+ for (const hour of hours) {
32
+ const want = Math.ceil(hour.people - 1e-9);
33
+ if (want <= 0)
34
+ continue;
35
+ const options = covering(hour.at);
36
+ let have = options.reduce((sum, s) => sum + counts[s.id], 0);
37
+ while (have < want) {
38
+ const open = options
39
+ .filter((s) => s.max == null || counts[s.id] < s.max)
40
+ .sort((a, b) => b.endMs - a.endMs || a.id.localeCompare(b.id));
41
+ if (open.length === 0)
42
+ break;
43
+ counts[open[0].id] += 1;
44
+ have += 1;
45
+ }
46
+ if (have < want)
47
+ unmet.push({
48
+ at: hour.at,
49
+ short: want - have,
50
+ reason: options.length === 0 ? 'no-shift' : 'at-max',
51
+ atMax: options
52
+ .filter((s) => s.max != null && counts[s.id] >= s.max)
53
+ .map((s) => s.id)
54
+ .sort(),
55
+ });
56
+ }
57
+ return { counts, unmet };
58
+ }
59
+ exports.coverNeed = coverNeed;
60
+ /**
61
+ * Person-hours for the day (a rate conversion without an hourly pattern)
62
+ * spread over the day's shifts: raise the longest shift first, one person at a
63
+ * time and in turn, until their hours cover it. What no shift can take (every
64
+ * one at its ceiling, or no shifts at all) is reported as one shortfall in
65
+ * whole person-hours at the first shift's start.
66
+ */
67
+ function coverPersonHours(personHours, shifts) {
68
+ const counts = {};
69
+ for (const s of shifts)
70
+ counts[s.id] = Math.max(0, s.min);
71
+ const hoursOf = (s) => (s.endMs - s.startMs) / HOUR_MS;
72
+ let have = shifts.reduce((sum, s) => sum + counts[s.id] * hoursOf(s), 0);
73
+ const byLength = [...shifts].sort((a, b) => hoursOf(b) - hoursOf(a) || a.id.localeCompare(b.id));
74
+ let i = 0;
75
+ let stuck = 0;
76
+ while (have < personHours - 1e-9 && byLength.length > 0 && stuck < byLength.length) {
77
+ const s = byLength[i % byLength.length];
78
+ i += 1;
79
+ if (s.max != null && counts[s.id] >= s.max) {
80
+ stuck += 1;
81
+ continue;
82
+ }
83
+ stuck = 0;
84
+ counts[s.id] += 1;
85
+ have += hoursOf(s);
86
+ }
87
+ const short = Math.max(0, Math.ceil(personHours - have - 1e-9));
88
+ if (short <= 0)
89
+ return { counts, unmet: [] };
90
+ const atMax = shifts.filter((s) => s.max != null && counts[s.id] >= s.max).map((s) => s.id);
91
+ return {
92
+ counts,
93
+ unmet: [
94
+ {
95
+ at: shifts[0]?.startMs ?? 0,
96
+ short,
97
+ reason: shifts.length === 0 ? 'no-shift' : 'at-max',
98
+ atMax: atMax.sort(),
99
+ },
100
+ ],
101
+ };
102
+ }
103
+ exports.coverPersonHours = coverPersonHours;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Day numbers: whole days since 1970-01-01, the integer the forecasting hot
3
+ * path works in. ISO strings stay at the edges (inputs, outputs); a fit over
4
+ * three years of history must not parse and format dates in its inner loops.
5
+ */
6
+ export declare const DAY_MS = 86400000;
7
+ export declare const dayOf: (date: string) => number;
8
+ export declare const dateOf: (day: number) => string;
9
+ /** ISO weekday of a day number: 1 (Mon) – 7 (Sun). 1970-01-01 was a Thursday. */
10
+ export declare const weekdayOf: (day: number) => number;
11
+ /** Monday on or before a day. */
12
+ export declare const mondayOfDay: (day: number) => number;
13
+ /** UTC day number of an epoch ms. */
14
+ export declare const utcDay: (ms: number) => number;
15
+ /** Week of the year (0–52) of a Monday, by days since 1 January. */
16
+ export declare function weekOfYear(monday: number): number;
17
+ //# sourceMappingURL=days.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"days.d.ts","sourceRoot":"","sources":["../../src/forecasting/days.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,eAAO,MAAM,MAAM,WAAa,CAAC;AAEjC,eAAO,MAAM,KAAK,SAAU,MAAM,KAAG,MAA8D,CAAC;AAEpG,eAAO,MAAM,MAAM,QAAS,MAAM,KAAG,MAA2D,CAAC;AAEjG,iFAAiF;AACjF,eAAO,MAAM,SAAS,QAAS,MAAM,KAAG,MAAyC,CAAC;AAElF,iCAAiC;AACjC,eAAO,MAAM,WAAW,QAAS,MAAM,KAAG,MAAoC,CAAC;AAE/E,qCAAqC;AACrC,eAAO,MAAM,MAAM,OAAQ,MAAM,KAAG,MAAiC,CAAC;AAItE,oEAAoE;AACpE,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CASjD"}
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.weekOfYear = exports.utcDay = exports.mondayOfDay = exports.weekdayOf = exports.dateOf = exports.dayOf = exports.DAY_MS = void 0;
4
+ /**
5
+ * Day numbers: whole days since 1970-01-01, the integer the forecasting hot
6
+ * path works in. ISO strings stay at the edges (inputs, outputs); a fit over
7
+ * three years of history must not parse and format dates in its inner loops.
8
+ */
9
+ exports.DAY_MS = 86400000;
10
+ const dayOf = (date) => Math.round(Date.parse(`${date}T00:00:00Z`) / exports.DAY_MS);
11
+ exports.dayOf = dayOf;
12
+ const dateOf = (day) => new Date(day * exports.DAY_MS).toISOString().slice(0, 10);
13
+ exports.dateOf = dateOf;
14
+ /** ISO weekday of a day number: 1 (Mon) – 7 (Sun). 1970-01-01 was a Thursday. */
15
+ const weekdayOf = (day) => ((((day + 3) % 7) + 7) % 7) + 1;
16
+ exports.weekdayOf = weekdayOf;
17
+ /** Monday on or before a day. */
18
+ const mondayOfDay = (day) => day - ((0, exports.weekdayOf)(day) - 1);
19
+ exports.mondayOfDay = mondayOfDay;
20
+ /** UTC day number of an epoch ms. */
21
+ const utcDay = (ms) => Math.floor(ms / exports.DAY_MS);
22
+ exports.utcDay = utcDay;
23
+ const weekOfYearCache = new Map();
24
+ /** Week of the year (0–52) of a Monday, by days since 1 January. */
25
+ function weekOfYear(monday) {
26
+ let week = weekOfYearCache.get(monday);
27
+ if (week === undefined) {
28
+ const year = new Date(monday * exports.DAY_MS).getUTCFullYear();
29
+ const jan1 = Math.round(Date.UTC(year, 0, 1) / exports.DAY_MS);
30
+ week = Math.min(52, Math.floor((monday - jan1) / 7));
31
+ weekOfYearCache.set(monday, week);
32
+ }
33
+ return week;
34
+ }
35
+ exports.weekOfYear = weekOfYear;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Seeded sampling for the staffing simulation: measured distributions by
3
+ * inverse CDF, Poisson counts, and the Gamma draw that overdisperses arrivals
4
+ * around the forecast. Every draw takes a `rand` from `createPrng`, so a run
5
+ * is reproducible from its seed.
6
+ */
7
+ import { createPrng } from '../scheduling/engine/prng';
8
+ import type { QuantileDistribution } from './types';
9
+ export { createPrng };
10
+ /** Validates a quantile distribution: ≥ 2 finite, non-negative, non-decreasing points. */
11
+ export declare function assertDistribution(d: QuantileDistribution, what: string): void;
12
+ /** Inverse CDF with linear interpolation between the evenly spaced quantiles. */
13
+ export declare function sampleQuantiles(d: QuantileDistribution, rand: () => number): number;
14
+ /** Mean of a quantile distribution (trapezoid over the evenly spaced points). */
15
+ export declare function meanOf(d: QuantileDistribution): number;
16
+ /** An exponential distribution as 101 quantiles (p100 capped at p99.9), for tests and defaults. */
17
+ export declare function exponentialQuantiles(meanValue: number, points?: number): QuantileDistribution;
18
+ /** Poisson count: Knuth for small means, a rounded normal approximation above 60. */
19
+ export declare function samplePoisson(lambda: number, rand: () => number): number;
20
+ /** Gamma(shape k, scale 1/k) — mean 1 — by Marsaglia–Tsang. */
21
+ export declare function sampleGammaMeanOne(k: number, rand: () => number): number;
22
+ /** Inverse standard normal CDF (Acklam's rational approximation, relative error < 1.2e-9). */
23
+ export declare function normalQuantile(p: number): number;
24
+ /** Quantile `p` of Gamma(shape k, scale 1/k) — mean 1 — by Wilson–Hilferty; 1 for k = Infinity. */
25
+ export declare function gammaMeanOneQuantile(k: number, p: number): number;
26
+ /**
27
+ * `count` strata of (0, 1), in an order whose every prefix is spread out (van der Corput, base 2): returns
28
+ * the stratum midpoints, so the first eight already sample the whole range and all `count` sample it evenly.
29
+ */
30
+ export declare function spreadStrata(count: number): number[];
31
+ //# sourceMappingURL=distributions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"distributions.d.ts","sourceRoot":"","sources":["../../src/forecasting/distributions.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AACvD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAEpD,OAAO,EAAE,UAAU,EAAE,CAAC;AAEtB,0FAA0F;AAC1F,wBAAgB,kBAAkB,CAAC,CAAC,EAAE,oBAAoB,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAO9E;AAED,iFAAiF;AACjF,wBAAgB,eAAe,CAAC,CAAC,EAAE,oBAAoB,EAAE,IAAI,EAAE,MAAM,MAAM,GAAG,MAAM,CAKnF;AAED,iFAAiF;AACjF,wBAAgB,MAAM,CAAC,CAAC,EAAE,oBAAoB,GAAG,MAAM,CAItD;AAED,mGAAmG;AACnG,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,SAAM,GAAG,oBAAoB,CAO1F;AAED,qFAAqF;AACrF,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,MAAM,GAAG,MAAM,CAgBxE;AAED,+DAA+D;AAC/D,wBAAgB,kBAAkB,CAAC,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,MAAM,GAAG,MAAM,CAwBxE;AAED,8FAA8F;AAC9F,wBAAgB,cAAc,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAyBhD;AAED,mGAAmG;AACnG,wBAAgB,oBAAoB,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAIjE;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAapD"}