-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_html.py
More file actions
2240 lines (2104 loc) · 116 KB
/
Copy pathbuild_html.py
File metadata and controls
2240 lines (2104 loc) · 116 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Build the standalone GitHub Pages HTML for the lifetime allocation engine.
The builder reads the institutional light-mode UI foundation
(``template_readonly.html``), replaces its mock dataset script with the full
WebGPU runtime, injects the calibrated model payload (``__MODEL_JSON__``) and
the WGSL shader sources, and writes ``index.html`` — a 100%
client-side, zero-backend application that runs entirely in the browser.
Usage:
py -3.14 build_html.py [--price-path downloaded_prices.csv] [--output index.html]
The generated file is fully standalone: all styles, SVG, JavaScript and
shaders are inline; fonts come from the Google Fonts CDN.
"""
from __future__ import annotations
import argparse
import json
import re
import time
from pathlib import Path
import calibration
import config as cfg
import engine
ROOT = Path(__file__).resolve().parent
TEMPLATE_PATH = ROOT / "template_readonly.html"
DEFAULT_PRICE_PATH = ROOT / "downloaded_prices.csv"
DEFAULT_OUTPUT_PATH = ROOT / "index.html"
# ---------------------------------------------------------------------------
# Markers replaced in the runtime JS and the template.
# ---------------------------------------------------------------------------
MODEL_MARKER = "__MODEL_JSON__"
SHADER_MARKER = "__SHADER_JSON__"
QUANTILES_MARKER = "__QUANTILES_JSON__"
BEQUEST_MARKER = "__BEQUEST_JSON__"
SOBOL_TABLE_MARKER = "__SOBOL_TABLE_B64__"
SOBOL_DIMS_MARKER = "__SOBOL_TABLE_DIMS__"
RUNTIME_JS = r"""
"use strict";
// ===========================================================================
// WebGPU runtime for the Wealth & Lifetime Allocation Engine.
//
// This script replaces the template's mock dataset with the real engine:
// 1. It reads the calibrated model payload from the #model-data script tag.
// 2. It builds the parameter buffers and runs the five WGSL compute passes
// (returns -> layoffs -> accumulation -> solver -> drawdowns) plus the
// GPU quantile reduction and the terminal-estate (bequest) ladders.
// 3. Risk Aversion (gamma), Drawdown Aversion (lambda), Bequest Intensity
// (theta) and Bequest Curvature (k) re-rank the table INSTANTLY from the
// cached 201-point quantile ladders (pure JavaScript, no GPU re-simulation):
// CE_adj = CE(gamma, theta, k) x exp(-lambda x Composite UI)
// where theta = k = 0 reduces CE(gamma, theta, k) to the base CE exactly.
// ===========================================================================
const MODEL = JSON.parse(document.getElementById("model-data").textContent);
const SHADER_SOURCE = __SHADER_JSON__;
const QUANTILES_SHADER_SOURCE = __QUANTILES_JSON__;
const BEQUEST_SHADER_SOURCE = __BEQUEST_JSON__;
const C = MODEL.constants;
const DEFAULTS = MODEL.defaults;
const TOTAL_ALLOCATIONS = MODEL.allocations.count;
const RUN_ALLOCATION_COUNT = Number(new URLSearchParams(location.search).get("allocations")) || TOTAL_ALLOCATIONS;
// The five underlying return series (VEQT, VEQT1.5, VEQT2, VGRO, VBAL).
// DECLINING/RISING accumulation glidepaths are monthly switching schedules,
// not return series, so they are sampled on-chip by the accumulate pass.
const RETURN_FUND_COUNT = 5;
// Upper bound (ms) for the per-batch progress-paint yield in the batch loop;
// see the comment at the await site.
const BATCH_YIELD_MS = 16;
const ALLOCATION_NAMES = MODEL.allocations.names;
const ALLOCATION_METADATA = new Uint32Array(MODEL.allocations.metadata);
// The "Leverage" checkbox in the settings window gates whether leveraged
// strategies (VEQT1.5 = code 1, VEQT2 = code 2) participate in a run. The
// compact metadata row is [accumCode, bridgeCode, postCode, flags] with fund
// codes VEQT=0..RISING=6 (see allocation_phase_code), so excluding codes 1/2
// from all three phase slots shrinks the strategy space from 5 houses x 7
// accumulation paths x 12 bridge x 12 post = 5,040 down to
// 5 x 5 x 8 x 8 = 1,600 strategies.
const LEVERAGED_FUND_CODES = [1, 2];
const state = {
results: null, // per-strategy simulation results (quantiles, ui, ...)
dynamic: null, // built dynamic model of the last run
applied: null, // control snapshot used for the last render
sort: { column: "ce", ascending: false, active: false },
deviceContext: null,
devicePromise: null,
activeRun: null,
adapterText: "pending"
};
let activeStrategy = null;
function byId(id) { return document.getElementById(id); }
function money(value) { return value == null ? "—" : "$" + Math.round(value).toLocaleString("en-US"); }
function escapeHtml(value) { return String(value).replace(/[&<>"']/g, ch => ({"&":"&","<":"<",">":">","\"":""","'":"'"}[ch])); }
function f2(value) { return Number(value).toFixed(1); }
function setText(id, text) { byId(id).textContent = text; }
// ---------------------------------------------------------------------------
// Console diagnostics: every failure path logs an "ENGINE" line with context,
// and window.dumpDiagnostics() prints a full snapshot for bug reports.
// ---------------------------------------------------------------------------
function engineLog(level, ...args) {
try {
const prefix = "%cENGINE%c";
const styles = ["background:#0f172a;color:#fff;border-radius:3px;padding:1px 6px;font-weight:700;", ""];
console[level](prefix, ...styles, ...args);
} catch (_) { /* console unavailable */ }
}
const logInfo = (...args) => engineLog("info", ...args);
const logDebug = (...args) => engineLog("debug", ...args);
const logWarn = (...args) => engineLog("warn", ...args);
const logError = (...args) => engineLog("error", ...args);
window.addEventListener("error", (event) => {
logError("Uncaught error:", event.message, "at", event.filename + ":" + event.lineno,
event.error && event.error.stack ? "\n" + event.error.stack : "");
});
window.addEventListener("unhandledrejection", (event) => {
const reason = event.reason || {};
logError("Unhandled promise rejection:", reason && reason.message ? reason.message : String(reason),
reason && reason.stack ? "\n" + reason.stack : "");
});
async function dumpDiagnostics() {
logInfo("=== ENGINE DIAGNOSTICS ===");
logInfo("User agent:", navigator.userAgent);
logInfo("WebGPU API present:", !!navigator.gpu);
logInfo("URL:", location.href);
logInfo("State:", JSON.stringify({
results: state.results ? state.results.length : null,
deviceReady: !!state.deviceContext,
adapterText: state.adapterText,
activeRun: !!state.activeRun,
deviceLostReason: state.deviceLostReason || null,
samplerRequested: new URLSearchParams(location.search).get("sampler") || null,
sobolTableBuiltIn: sobolTableAvailable(),
totals: {allocations: TOTAL_ALLOCATIONS, runAllocations: RUN_ALLOCATION_COUNT}
}));
if (navigator.gpu) {
try {
if (typeof navigator.gpu.requestAdapterInfo === "function") {
const infos = await navigator.gpu.requestAdapterInfo();
logInfo("Available adapters (" + infos.length + "):",
infos.map(i => ({vendor: i.vendor, architecture: i.architecture, device: i.device, description: i.description})));
} else {
logWarn("navigator.gpu.requestAdapterInfo() not available on this browser version; adapter enumeration skipped.");
}
} catch (err) {
logError("requestAdapterInfo() failed:", err);
}
}
logInfo("=== END ENGINE DIAGNOSTICS ===");
}
window.dumpDiagnostics = dumpDiagnostics;
function uiSeverity(ui) {
// Severity coloring for the mean Composite Ulcer Index: green = mild
// (VBAL/VGRO), amber = moderate (100% equity), red = severe (leveraged).
if (ui < 12) return "var(--brand-green)";
if (ui < 20) return "var(--brand-amber)";
return "#dc2626";
}
function setStatus(message, error) {
const element = byId("gpu-status");
element.textContent = message;
element.className = "engine-chip " + (error ? "bad" : "ok");
}
// ---------------------------------------------------------------------------
// Simulation path-count slider (simple linear range, 500..10,000).
// ---------------------------------------------------------------------------
const SIM_MIN = 500, SIM_MAX = 10000, SIM_STEP = 500;
function simulationCountFromSlider() {
const value = Number(byId("slider-sim-count").value);
return Math.min(SIM_MAX, Math.max(SIM_MIN, Math.round(value / SIM_STEP) * SIM_STEP));
}
function simulationSliderPosition(count) {
return Math.min(SIM_MAX, Math.max(SIM_MIN, Math.round(Number(count) / SIM_STEP) * SIM_STEP));
}
// ---------------------------------------------------------------------------
// Editable model inputs: schema-driven binding between the settings window's
// natural human formatting (20.0%, $88,000, 4.30% / yr) and the engine's raw
// decimals (0.2, 88000, 0.043).
// ---------------------------------------------------------------------------
function parseMoney(text) { return Number(String(text).replace(/[^0-9.\-]/g, "")); }
function parsePercent(text) { return Number(String(text).replace(/[^0-9.\-]/g, "")) / 100; }
function formatMoney(value) { return String(Math.round(value)); }
function formatPercent(value) { return (value * 100).toFixed(2); }
// Each entry: [tab id, input index within that tab, model field, kind]
// The input index is the flat position of the field inside the tab's
// .form-grid-2 containers, in DOM order. Kinds: years | money | pct | int | plain.
const INPUT_SCHEMA = [
["tab-career", 0, "currentAge", "years"],
["tab-career", 1, "careerStartAge", "years"],
["tab-career", 2, "retirementAge", "years"],
["tab-career", 3, "pensionStartAge", "years"],
["tab-career", 4, "deathAge", "years"],
["tab-career", 5, "startingSalary", "money"],
["tab-career", 6, "promotionPhase0", "pct"],
["tab-career", 7, "promotionPhase1", "pct"],
["tab-career", 8, "promotionPhase2", "pct"],
["tab-career", 9, "promotionPhase3", "pct"],
["tab-career", 10, "retirementSavingsStartAnnual", "money"],
["tab-career", 11, "retirementSavingsEscalationRate", "pct"],
["tab-career", 12, "savingsMaxFraction", "pct"],
["tab-career", 13, "employerMatchRate", "pct"],
["tab-career", 14, "employerMatchPercent", "pct"],
["tab-career", 15, "layoffAnnualProbability", "pct"],
["tab-re", 0, "propertyValue", "money"],
["tab-re", 1, "downPaymentFraction", "pct"],
["tab-re", 2, "closingCosts", "money"],
["tab-re", 3, "realMortgageRateAnnual", "pct"],
["tab-re", 4, "monthlyPropertyTaxesCondo", "money"],
["tab-re", 5, "monthlyMarketRent", "money"],
["tab-re", 6, "houseSavingsStartAnnual", "money"],
["tab-re", 7, "houseSavingsEscalationRate", "pct"],
["tab-re", 8, "houseSavingsMaxFraction", "pct"],
["tab-re", 9, "fhsaAnnualLimit", "money"],
["tab-re", 10, "fhsaMaxBalance", "money"],
["tab-re", 11, "hbpMaxWithdrawal", "money"],
["tab-re", 12, "hbpRepaymentYears", "years"],
["tab-tax", 0, "meltdownBracketAnnual", "money"],
["tab-tax", 1, "oasClawbackThreshold", "money"],
["tab-tax", 2, "capitalGainsInclusionRate", "pct"],
["tab-tax", 3, "capitalGainsTaxRate", "pct"],
["tab-tax", 4, "maxQppAge65", "money"],
["tab-tax", 5, "maxOasAge65", "money"],
["tab-tax", 6, "qppMaximumAnnual", "money"],
["tab-tax", 7, "qppMaximumMSGA", "money"],
["tab-tax", 8, "qppDeferralAnnual", "pct"],
["tab-tax", 9, "oasDeferralAnnual", "pct"],
["tab-cma", 0, "cmaVEQT", "pct"],
["tab-cma", 1, "cmaVGRO", "pct"],
["tab-cma", 2, "cmaVBAL", "pct"],
["tab-cma", 3, "hisaAnnualRealReturn", "pct"],
["tab-cma", 4, "annualDistributionYield", "pct"],
["tab-cma", 5, "taxOnDistributions", "pct"],
["tab-cma", 6, "realBorrowRateAnnual", "pct"],
["tab-cma", 7, "extraMer15", "pct"],
["tab-cma", 8, "extraMer20", "pct"],
["tab-cma", 9, "cashWedgeFraction", "pct"],
// Glide fields interleave Declining (left column) / Rising (right column)
// row by row so each grid row pairs the same fund: VEQT, then VGRO, then
// VBAL — Declining share on the left, Rising share on the right.
["tab-cma", 10, "glidepathDeclining0", "pct"],
["tab-cma", 11, "glidepathRising0", "pct"],
["tab-cma", 12, "glidepathDeclining1", "pct"],
["tab-cma", 13, "glidepathRising1", "pct"],
["tab-cma", 14, "glidepathDeclining2", "pct"],
["tab-cma", 15, "glidepathRising2", "pct"],
["tab-spend", 0, "smilePhase0", "pct"],
["tab-spend", 1, "smilePhase1", "pct"],
["tab-spend", 2, "smilePhase2", "pct"],
["tab-spend", 3, "smilePhase3", "pct"],
["tab-spend", 4, "skewDegreesFreedom", "int"],
["tab-spend", 5, "deltaCap", "plain"],
["tab-spend", 6, "mortalityReductionFactor", "plain"],
["tab-spend", 7, "discountRateAnnual", "pct"],
];
function schemaInputs() {
const inputs = {};
for (const tabId of ["tab-career", "tab-re", "tab-tax", "tab-cma", "tab-spend"]) {
const tab = byId(tabId);
const list = Array.from(tab.querySelectorAll(".form-grid-2 .input-field .form-input"));
list.forEach((element, index) => { inputs[tabId + ":" + index] = element; });
}
return inputs;
}
function formatForKind(kind, value) {
if (kind === "pct") return formatPercent(value);
if (kind === "money") return formatMoney(value);
if (kind === "plain") return Number(value).toFixed(2);
return String(value); // years / int
}
function parseForKind(kind, text) {
if (kind === "pct") return parsePercent(text);
if (kind === "money") return parseMoney(text);
return Number(text);
}
// Glidepath + cash-tent percentage fields round-trip through the same pct
// pipeline (50.0 <-> 0.50), so no special formatting is needed beyond making
// sure the parsed values land on the config arrays (readModelInputs) and
// formatting keeps two decimals (applyModelToInputs).
function applyModelToInputs(config) {
const inputs = schemaInputs();
INPUT_SCHEMA.forEach(([tabId, inputIndex, field, kind]) => {
const element = inputs[tabId + ":" + inputIndex];
if (!element) return;
element.value = formatForKind(kind, modelValue(config, field));
});
const cmaToggle = byId("inp-use-forward-cmas");
if (cmaToggle) cmaToggle.checked = !!config.useForwardLookingCmas;
}
function modelValue(config, field) {
if (field.startsWith("promotionPhase")) return config.promotionPhases[Number(field.slice(-1))].growth;
if (field.startsWith("smilePhase")) return config.smileSchedule[Number(field.slice(-1))].change;
if (field.startsWith("cma")) return config.cmas[field.slice(3)];
if (field.startsWith("glidepathDeclining")) return config.glidepathDeclining[Number(field.slice(-1))];
if (field.startsWith("glidepathRising")) return config.glidepathRising[Number(field.slice(-1))];
return config[field];
}
function readModelInputs() {
const input = JSON.parse(JSON.stringify(MODEL.inputs));
const inputs = schemaInputs();
for (let index = 0; index < INPUT_SCHEMA.length; index++) {
// NOTE: the schema stores the per-tab input index separately from the
// global schema position — the lookup key MUST use the input index.
const [tabId, inputIndex, field, kind] = INPUT_SCHEMA[index];
const element = inputs[tabId + ":" + inputIndex];
if (!element) continue;
const value = parseForKind(kind, element.value);
if (!Number.isFinite(value)) throw new Error("Invalid number in settings field " + field + ": '" + element.value + "'");
if (field.startsWith("promotionPhase")) input.promotionPhases[Number(field.slice(-1))].growth = value;
else if (field.startsWith("smilePhase")) input.smileSchedule[Number(field.slice(-1))].change = value;
else if (field.startsWith("cma")) input.cmas[field.slice(3)] = value;
else if (field.startsWith("glidepathDeclining")) input.glidepathDeclining[Number(field.slice(-1))] = value;
else if (field.startsWith("glidepathRising")) input.glidepathRising[Number(field.slice(-1))] = value;
else input[field] = value;
}
// The first promotion tier always begins at the career start age so the
// salary trajectory and the tier labels stay consistent.
input.promotionPhases[0].start = input.careerStartAge;
// Expected-return source: ON = the CMAs listed in the settings, OFF = the
// historical sample means of the calibrated price history.
input.useForwardLookingCmas = byId("inp-use-forward-cmas").checked;
const ages = [input.currentAge, input.careerStartAge, input.retirementAge, input.pensionStartAge, input.deathAge];
if (ages.some(age => !Number.isInteger(age)) || input.currentAge >= input.careerStartAge || input.careerStartAge >= input.retirementAge || input.retirementAge >= input.pensionStartAge || input.pensionStartAge >= input.deathAge) {
throw new Error("Ages must be ordered current < career start < retirement < pension < death.");
}
if (input.startingSalary <= 0 || input.skewDegreesFreedom <= 2 || input.skewDegreesFreedom % 1 !== 0) {
throw new Error("Starting salary must be positive and skew degrees of freedom must be an integer greater than 2.");
}
// Glidepath shares: each pair must sum to ~100% and no single fund share
// may exceed the max-share cap (mirrors config.glidepath_max_share).
const maxShare = C.glidepathMaxShare || 0.5;
const epsilon = 1e-6;
for (const [label, shares] of [["DECLINING", input.glidepathDeclining], ["RISING", input.glidepathRising]]) {
if (shares.some(v => !Number.isFinite(v) || v < 0)) throw new Error(label + " glidepath shares must be non-negative percentages.");
if (Math.abs(shares[0] + shares[1] + shares[2] - 1.0) > epsilon) {
throw new Error(label + " glidepath shares must sum to 100%.");
}
if (shares.some(v => v > maxShare + epsilon)) {
throw new Error(label + " glidepath shares: no single fund may exceed " + (maxShare * 100).toFixed(0) + "%.");
}
}
if (!Number.isFinite(input.cashWedgeFraction) || input.cashWedgeFraction < 0 || input.cashWedgeFraction > 1) {
throw new Error("Cash wedge must be a percentage between 0% and 100% of the retirement span.");
}
return input;
}
// ---------------------------------------------------------------------------
// Fiscal & calibration helpers (exact ports of the engine's math).
// ---------------------------------------------------------------------------
// (The single-regime runtime calibration — inverse3/cholesky3/calibrateReturnModel —
// was retired with the two-state Markov model: the regime fit happens in
// Python at build time; only the CMA mean-shift is recomputed live, below.)
function exactLnGammaInteger(n) {
let total = 0;
for (let i = 1; i < n; i++) total += Math.log(i);
return total;
}
function exactLnGammaHalfInteger(k) {
let total = 0.5 * Math.log(Math.PI);
for (let i = 1; i <= 2 * k; i++) total += Math.log(i);
total -= k * Math.log(4);
for (let i = 1; i <= k; i++) total -= Math.log(i);
return total;
}
function exactLogGamma(value) {
const rounded = Math.round(value);
const isHalf = Math.abs(value - rounded) > 1e-9;
const base = Math.floor(value);
return isHalf ? exactLnGammaHalfInteger(base) : exactLnGammaInteger(rounded);
}
function exactBNu(nu) {
if (nu <= 1) return 0;
return Math.sqrt(nu / Math.PI) * Math.exp(exactLogGamma((nu - 1) / 2) - exactLogGamma(nu / 2));
}
// Live CMA mean-shift for the two-state Markov return model. The regime
// fit (HMM + per-state skew-t sets) is calibrated in Python at build time and
// embedded in the payload; the toggle and the CMA inputs change the DRIFT only,
// exactly as in calibration.calibrate_two_state_markov: the stationary
// (regime-weighted) mean of the embedded states is shifted by the common
// constant that re-targets it on
// forward-looking: log1p(CMA)/12 + cov_ii/2 (moment-matched log-mean)
// historical: the sample mean of the embedded price history
// so only xi changes — omega/delta/Cholesky/p00/p11 stay build-time fixed.
function applyCmaMeanShift(rm, config) {
const values = MODEL.historicalReturns;
const count = MODEL.historicalReturnCount;
const covariance = new Array(3).fill(0);
const means = [0, 0, 0];
for (let row = 0; row < count; row++) for (let column = 0; column < 3; column++) means[column] += values[row * 3 + column];
for (let column = 0; column < 3; column++) means[column] /= count;
for (let row = 0; row < count; row++) for (let column = 0; column < 3; column++) covariance[column] += (values[row * 3 + column] - means[column]) * (values[row * 3 + column] - means[column]);
for (let column = 0; column < 3; column++) covariance[column] /= count - 1;
const targetMean = config.useForwardLookingCmas
? [Math.log1p(config.cmas.VEQT) / 12 + 0.5 * covariance[0],
Math.log1p(config.cmas.VGRO) / 12 + 0.5 * covariance[1],
Math.log1p(config.cmas.VBAL) / 12 + 0.5 * covariance[2]]
: means;
const prior0 = rm.prior0;
const s0 = rm.states[0], s1 = rm.states[1];
for (let column = 0; column < 3; column++) {
// xi = mu - omega*delta*b_nu => mu = xi + omega*delta*b_nu.
const weightedMu = prior0 * (s0.xi[column] + s0.omega[column] * s0.delta[column] * exactBNu(MODEL.returnModel.nu))
+ (1 - prior0) * (s1.xi[column] + s1.omega[column] * s1.delta[column] * exactBNu(MODEL.returnModel.nu));
const shift = targetMean[column] - weightedMu;
s0.xi[column] += shift; s1.xi[column] += shift;
}
return rm;
}
function monthlyTax(gross, config) {
const brackets = [0].concat(config.taxThresholdsAnnual.map(value => value / 12));
let tax = 0;
for (let index = 0; index < 5; index++) tax += Math.max(0, Math.min(gross, index < 4 ? brackets[index + 1] : gross) - brackets[index]) * config.taxRates[index];
return tax;
}
function annualTax(gross, config) {
const incomeTax = monthlyTax(gross / 12, config) * 12;
const qppTier1 = Math.max(0, Math.min(gross, config.qppMaximumAnnual) - config.qppBasicAnnual) * config.qppRate;
const qppTier2 = Math.max(0, Math.min(gross, config.qppMaximumMSGA || 81200) - config.qppMaximumAnnual) * (config.qppRateTier2 || 0.04);
const ei = Math.min(gross, config.eiMaximumAnnual) * config.eiRate;
const rqap = Math.min(gross, config.rqapMaximumAnnual) * config.rqapRate;
return incomeTax + qppTier1 + qppTier2 + ei + rqap;
}
function netTaxableIncome(gross, age, config, oas7074, oas75) {
const oasEligible = age >= config.pensionStartAge && age >= 65;
const oasMax = oasEligible ? (age >= 75 ? oas75 : oas7074) / 12 : 0;
const clawback = oasMax > 0 ? Math.min(oasMax, Math.max(0, gross - config.oasClawbackThreshold / 12) * config.oasClawbackRate) : 0;
return gross - monthlyTax(gross, config) - clawback;
}
function pensionAmounts(config) {
const careerYears = config.retirementAge - config.careerStartAge;
let salarySum = 0;
let salary = config.startingSalary;
for (let i = 0; i < careerYears; i++) {
const age = config.careerStartAge + i;
if (i > 0) {
const phase = config.promotionPhases.find(item => age >= item.start && age < item.end);
salary *= 1 + (phase ? phase.growth : 0);
}
salarySum += Math.min(1.0, salary / config.qppMaximumAnnual);
}
const qppEarningsRatio = careerYears > 0 ? (salarySum / careerYears) : 0;
const baseQpp = config.maxQppAge65 * Math.min(1, careerYears / 40) * qppEarningsRatio;
const effectiveQppAge = Math.min(72, Math.max(60, config.pensionStartAge));
const qppMultiplier = effectiveQppAge >= 65
? 1 + (effectiveQppAge - 65) * config.qppDeferralAnnual
: 1 - (65 - effectiveQppAge) * (config.qppEarlyPenaltyAnnual || 0.06);
const qpp = baseQpp * qppMultiplier;
const effectiveOasAge = Math.min(70, Math.max(65, config.pensionStartAge));
const oasMultiplier = Math.min(config.oasDeferralCap, 1 + (effectiveOasAge - 65) * config.oasDeferralAnnual);
const oas7074 = config.maxOasAge65 * oasMultiplier;
return {cpp: qpp, oas7074, oas75: oas7074 * config.oas75Increase};
}
function uniqueSorted(values) { return Array.from(new Set(values.map(value => Number(value.toFixed(6))))).sort((a, b) => a - b); }
function buildDynamicModel(config) {
const constants = {
currentAge: config.currentAge, careerStartAge: config.careerStartAge, retirementAge: config.retirementAge,
pensionStartAge: config.pensionStartAge, deathAge: config.deathAge,
accumMonths: (config.retirementAge - config.currentAge) * 12,
bridgeMonths: (config.pensionStartAge - config.retirementAge) * 12,
retireMonths: (config.deathAge - config.retirementAge) * 12,
totalMonths: (config.retirementAge - config.currentAge + config.deathAge - config.retirementAge) * 12,
careerYears: config.retirementAge - config.careerStartAge, funds: C.funds,
annualDistributionYield: config.annualDistributionYield, taxOnDistributions: config.taxOnDistributions,
capitalGainsInclusion: config.capitalGainsInclusionRate, capitalGainsTaxRate: config.capitalGainsTaxRate,
hisaMonthly: Math.pow(1 + config.hisaAnnualRealReturn, 1 / 12) - 1, cashWedgeFraction: config.cashWedgeFraction,
glidepathDeclining: config.glidepathDeclining || C.glidepathDeclining, glidepathRising: config.glidepathRising || C.glidepathRising,
meltdownMonthly: config.meltdownBracketAnnual / 12, oasThresholdMonthly: config.oasClawbackThreshold / 12, oasClawbackRate: config.oasClawbackRate,
employerMatchRate: config.employerMatchRate, employerMatchPercent: config.employerMatchPercent,
realBorrowRateAnnual: config.realBorrowRateAnnual, extraMer15: config.extraMer15, extraMer20: config.extraMer20,
layoffAnnualProbability: config.layoffAnnualProbability,
bisectionSteps: Number(MODEL.constants.bisectionSteps) || 24,
m75Start: Math.round((75 - config.retirementAge) * 12), postWedgeMonth: Math.round((config.pensionStartAge - config.retirementAge) * 12),
seed: MODEL.defaultSeed, skewDegreesFreedom: config.skewDegreesFreedom,
targetHouseCapital: config.propertyValue * config.downPaymentFraction + config.closingCosts,
mortgagePrincipal: config.propertyValue * (1 - config.downPaymentFraction),
mortgageMonthlyRate: Math.pow(1 + config.realMortgageRateAnnual, 1 / 12) - 1,
monthlyPropertyTaxesCondo: config.monthlyPropertyTaxesCondo,
monthlyMarketRent: config.monthlyMarketRent,
fhsaAnnualLimit: config.fhsaAnnualLimit,
fhsaMaxBalance: config.fhsaMaxBalance,
hbpMaxWithdrawal: config.hbpMaxWithdrawal,
hbpRepaymentYears: config.hbpRepaymentYears,
propertyValue: config.propertyValue,
estateGridFractions: MODEL.constants.estateGridFractions || [],
};
const career = new Float32Array(constants.careerYears * 6);
const salaries = new Array(constants.careerYears);
let salary = config.startingSalary;
for (let index = 0; index < constants.careerYears; index++) {
const age = config.careerStartAge + index;
if (index > 0) {
const phase = config.promotionPhases.find(item => age >= item.start && age < item.end);
salary *= 1 + (phase ? phase.growth : 0);
}
salaries[index] = salary;
}
const netSalaries = salaries.map(value => value - annualTax(value, config));
const retirementStartRate = config.retirementSavingsStartAnnual / netSalaries[0];
const houseStartRate = config.houseSavingsStartAnnual / netSalaries[0];
let cumulativeRrsp = 0;
for (let index = 0; index < constants.careerYears; index++) {
const salaryTaxRate = config.taxThresholdsAnnual.findIndex(threshold => salaries[index] < threshold);
const rate = salaryTaxRate < 0 ? config.taxRates[4] : config.taxRates[salaryTaxRate];
const retirementRate = Math.min(retirementStartRate + index * config.retirementSavingsEscalationRate, config.savingsMaxFraction);
const houseRate = Math.min(houseStartRate + index * config.houseSavingsEscalationRate, config.houseSavingsMaxFraction);
const tfsaRoom = (config.careerStartAge - 18 + 1) * config.tfsaAnnualLimit - config.otherTfsa + index * config.tfsaAnnualLimit;
career.set([retirementRate * netSalaries[index], houseRate * netSalaries[index], rate, tfsaRoom, cumulativeRrsp, salaries[index]], index * 6);
cumulativeRrsp += Math.min(config.rrspContributionRate * salaries[index], config.rrspMaxContribution);
}
const pension = pensionAmounts(config);
const grossPre = [0].concat(config.taxThresholdsAnnual.map(value => value / 12), [1_000_000 / 12]);
const netPre = grossPre.map(value => netTaxableIncome(value, config.pensionStartAge - 1, config, pension.oas7074, pension.oas75));
function postGrid(oas) {
const oasMonthly = oas / 12, threshold = config.oasClawbackThreshold / 12;
return uniqueSorted([0, config.taxThresholdsAnnual[0] / 12, config.taxThresholdsAnnual[1] / 12, threshold, config.taxThresholdsAnnual[2] / 12, threshold + oasMonthly / config.oasClawbackRate, config.taxThresholdsAnnual[3] / 12, 1_000_000 / 12]);
}
const gross70 = postGrid(pension.oas7074), gross75 = postGrid(pension.oas75);
const net70 = gross70.map(value => netTaxableIncome(value, Math.max(70, config.pensionStartAge), config, pension.oas7074, pension.oas75));
const net75 = gross75.map(value => netTaxableIncome(value, 75, config, pension.oas7074, pension.oas75));
const taxValues = new Float32Array(54);
taxValues.set(grossPre, 0); taxValues.set(netPre, 6); taxValues.set(gross70, 12); taxValues.set(net70, 20); taxValues.set(gross75, 28); taxValues.set(net75, 36);
taxValues.set(config.taxThresholdsAnnual.map(value => value / 12), 44); taxValues.set(config.taxRates, 49);
const month0 = new Float32Array(constants.retireMonths * 4), month1 = new Float32Array(constants.retireMonths * 4), smile = new Float32Array(constants.retireMonths);
let smileCurrent = 1;
for (let month = 0; month < constants.retireMonths; month++) {
const age = config.retirementAge + month / 12;
const smilePhase = config.smileSchedule.find(item => age >= item.start && age < item.end);
smile[month] = smileCurrent; if (smilePhase && smilePhase.change !== 0) smileCurrent *= 1 + smilePhase.change / 12;
const qppMonthly = (age >= config.pensionStartAge) ? (pension.cpp / 12) : 0;
const oasEligible = age >= config.pensionStartAge && age >= 65;
const oasMonthly = oasEligible ? ((age < 75 ? pension.oas7074 : pension.oas75) / 12) : 0;
const grossPension = qppMonthly + oasMonthly;
month0.set([
smile[month] / 12,
age < config.healthcareEndAge ? config.post50HealthcareAnnual / 12 : 0,
grossPension,
0
], month * 4);
month0[month * 4 + 3] = grossPension > 0 ? netTaxableIncome(grossPension, age, config, pension.oas7074, pension.oas75) : 0;
const wholeAge = Math.floor(age);
const rrif = wholeAge < 71 ? 0 : wholeAge >= 95 ? 0.2 : Number(config.rrifFactors[String(wholeAge)] || 0.2);
const oasMax = oasEligible ? ((age >= 75 ? pension.oas75 : pension.oas7074) / 12) : 0;
month1.set([rrif, oasMax, 0, 0], month * 4);
}
const cpmWeights = new Float32Array(constants.retireMonths);
const adjustedMortality = MODEL.mortalityAnnualProbability.map(value => Math.pow(value, config.mortalityReductionFactor));
let weightSum = 0;
for (let month = 0; month < constants.retireMonths; month++) {
const position = month * (adjustedMortality.length - 1) / Math.max(1, constants.retireMonths - 1), low = Math.floor(position), high = Math.ceil(position);
const survival = adjustedMortality[low] + (adjustedMortality[high] - adjustedMortality[low]) * (position - low);
cpmWeights[month] = Math.pow(1 + config.discountRateAnnual / 12, -month) * survival; weightSum += cpmWeights[month];
}
for (let month = 0; month < constants.retireMonths; month++) cpmWeights[month] /= weightSum;
// Two-state Markov switching return model: regime fit calibrated in Python
// at build time and embedded in the payload (MODEL.returnModel). Append the
// 36-word two-state skew-t block (2 x [xi, omega, delta, row-major
// Cholesky]) plus the two transition probabilities p00/p11 after the tax
// tail, then the 11 house constants (index 10 = target property value, read
// only by the bequest estate pass) and the bequest estate-grid tail [grid
// count, fractions...] (mirror of calibration.build_model_buffer /
// bequest.wgsl estate_grid_offset()). The CMA toggle + CMA inputs retarget
// the drift live via applyCmaMeanShift (a fresh copy each run — never
// mutate the embedded payload).
const rm = MODEL.returnModel;
const returnModel = {
kind: rm.kind || "two-state-markov",
nu: rm.nu, observations: rm.observations,
p00: rm.p00, p11: rm.p11, prior0: rm.prior0,
states: [
{ xi: rm.states[0].xi.slice(), omega: rm.states[0].omega, delta: rm.states[0].delta, cholesky: rm.states[0].cholesky },
{ xi: rm.states[1].xi.slice(), omega: rm.states[1].omega, delta: rm.states[1].delta, cholesky: rm.states[1].cholesky }
]
};
applyCmaMeanShift(returnModel, config);
const s0 = returnModel.states[0], s1 = returnModel.states[1];
const returnModelArray = [].concat(s0.xi, s0.omega, s0.delta, s0.cholesky,
s1.xi, s1.omega, s1.delta, s1.cholesky,
[returnModel.p00, returnModel.p11]);
const houseConstantsArray = [
constants.targetHouseCapital, constants.mortgagePrincipal, constants.mortgageMonthlyRate,
constants.monthlyPropertyTaxesCondo, constants.monthlyMarketRent,
constants.fhsaAnnualLimit, constants.fhsaMaxBalance, constants.hbpMaxWithdrawal,
constants.hbpRepaymentYears, C.houseCount, constants.propertyValue,
constants.estateGridFractions.length, ...constants.estateGridFractions
];
const staticValues = new Float32Array(career.length + month0.length + month1.length + taxValues.length + returnModelArray.length + houseConstantsArray.length);
staticValues.set(career, 0); staticValues.set(month0, career.length); staticValues.set(month1, career.length + month0.length); staticValues.set(taxValues, career.length + month0.length + month1.length); staticValues.set(returnModelArray, career.length + month0.length + month1.length + taxValues.length); staticValues.set(houseConstantsArray, career.length + month0.length + month1.length + taxValues.length + returnModelArray.length);
return {constants, career, month0, month1, taxValues, staticValues, smile, cpmWeights, returnModel, pension};
}
// ---------------------------------------------------------------------------
// RQMC (Sobol) sampler — the DEFAULT; ?sampler=threefry opts out to legacy.
// The page embeds the Joe-Kuo direction table truncated to its TOP 14 bits
// (bit-packed, base64); 14 bits cover simulation indices < 2^14 = 16,384
// (the UI caps runs at 10,000 paths per seed). The WGSL load-shifts each
// stored word back to its full 32-bit position (<< (32 - bits)), which
// reconstructs the exact direction number for every k <= 14, so the
// browser's stream is byte-identical to the Python engine's 20-bit
// digital-shift Sobol path. The default is ALWAYS Threefry; ?sampler=rqmc
// is the only way to switch. Non-default ages/horizons (coordinates
// beyond the embedded table) and runs >= 2^14 paths fall back to Threefry
// with a console warning.
// ---------------------------------------------------------------------------
const SOBOL_RQMC_BITS = 14;
const SOBOL_TABLE_DIMS = __SOBOL_TABLE_DIMS__;
const SOBOL_TABLE_B64 = "__SOBOL_TABLE_B64__";
function sobolTableAvailable() { return SOBOL_TABLE_B64.length > 8 && SOBOL_TABLE_DIMS > 0; }
let _sobolTableWords = null;
function sobolTableWords() {
if (_sobolTableWords) return _sobolTableWords;
const raw = Uint8Array.from(atob(SOBOL_TABLE_B64), c => c.charCodeAt(0));
const total = (raw.length * 8 / SOBOL_RQMC_BITS) | 0;
const words = new Uint32Array(total);
let bitPos = 0;
for (let i = 0; i < total; i++, bitPos += SOBOL_RQMC_BITS) {
const byteIdx = bitPos >> 3, shift = bitPos & 7;
let val = raw[byteIdx] >>> shift;
if (shift + SOBOL_RQMC_BITS > 8) val |= raw[byteIdx + 1] << (8 - shift);
if (shift + SOBOL_RQMC_BITS > 16) val |= raw[byteIdx + 2] << (16 - shift);
words[i] = val & ((1 << SOBOL_RQMC_BITS) - 1);
}
_sobolTableWords = words;
return words;
}
function rqmcSamplerEnabled(dynamic, simulations) {
// RQMC digital-shift Sobol is the DEFAULT (lower single-seed error at low
// simulation counts, same converged CEQ); ?sampler=threefry opts out to
// the legacy counter-based Threefry stream.
if (!sobolTableAvailable()) { logWarn("RQMC sampler unavailable: the build was made without the Sobol table (sobol_dirs_u32.npy / scipy missing at build time). Continuing with Threefry."); return false; }
const url = new URLSearchParams(location.search);
if (url.get("sampler") === "threefry") return false;
const dims = dynamic.constants.totalMonths * 10 + dynamic.constants.careerYears;
if (dims > SOBOL_TABLE_DIMS) {
logWarn("RQMC disabled: this configuration needs", dims, "Sobol coordinates but the embedded table only has", SOBOL_TABLE_DIMS, "(non-default ages/horizons). Continuing with Threefry.");
return false;
}
if (simulations >= (1 << SOBOL_RQMC_BITS)) {
logWarn("RQMC disabled: the run needs", simulations, "paths but the embedded 14-bit table covers up to", (1 << SOBOL_RQMC_BITS) - 1, ". Continuing with Threefry.");
return false;
}
return true;
}
// ---------------------------------------------------------------------------
// WebGPU pipeline
// ---------------------------------------------------------------------------
function makeParams(dynamic, simulations, allocations, batchSims, simOffset, columnsPerWorkgroup = 1, generateLeveraged = true, rqmcBits = 0) {
const dimensions = dynamic.constants;
const buffer = new ArrayBuffer(160);
new Uint32Array(buffer, 0, 4).set([simulations, allocations, dimensions.totalMonths, dimensions.accumMonths]);
new Uint32Array(buffer, 16, 4).set([dimensions.retireMonths, RETURN_FUND_COUNT, dimensions.bisectionSteps, dimensions.m75Start]);
new Uint32Array(buffer, 32, 4).set([dimensions.postWedgeMonth, dimensions.currentAge, dimensions.careerStartAge, dimensions.retirementAge]);
new Float32Array(buffer, 48, 4).set([dimensions.annualDistributionYield / 12, dimensions.taxOnDistributions, dimensions.hisaMonthly, dimensions.capitalGainsInclusion]);
// constants1.y: the cash-wedge FRACTION of the retirement span — the
// shaders multiply it by the retirement month count (solver.x).
new Float32Array(buffer, 64, 4).set([dimensions.capitalGainsTaxRate, dimensions.cashWedgeFraction, dimensions.meltdownMonthly, dimensions.oasThresholdMonthly]);
new Float32Array(buffer, 80, 4).set([dimensions.oasClawbackRate, dimensions.employerMatchRate, dimensions.employerMatchPercent, dimensions.funds.length]);
new Uint32Array(buffer, 96, 4).set([dimensions.seed, dimensions.skewDegreesFreedom, batchSims, simOffset]);
new Float32Array(buffer, 112, 4).set([dimensions.realBorrowRateAnnual / 12, dimensions.extraMer15 / 12, dimensions.extraMer20 / 12, dimensions.layoffAnnualProbability]);
// dispatch.y: 1 under ?sampler=rqmc (digital-shift Sobol), else Threefry.
// dispatch.z: 1 = generate the leveraged return series (VEQT1.5/VEQT2),
// 0 = skip them (leverage-off runs never read funds 1/2).
// dispatch.w: RQMC direction-bit width (14); 0 = RQMC off.
new Uint32Array(buffer, 128, 4).set([columnsPerWorkgroup, rqmcBits > 0 ? 1 : 0, generateLeveraged ? 1 : 0, rqmcBits]);
// glide: DECLINING .xy = (VEQT share, VGRO share), RISING .zw = (VBAL
// share, VGRO share); the third fund takes the remainder. One schedule for
// every glidepath phase (accumulation, bridge, post-pension).
new Float32Array(buffer, 144, 4).set([dimensions.glidepathDeclining[0], dimensions.glidepathDeclining[1], dimensions.glidepathRising[0], dimensions.glidepathRising[1]]);
return buffer;
}
function staticBuffer(device, data) {
const size = Math.max(4, data.byteLength);
const buffer = device.createBuffer({size, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST});
device.queue.writeBuffer(buffer, 0, data);
return buffer;
}
async function createDeviceContext() {
if (state.deviceContext) return state.deviceContext;
if (state.devicePromise) return state.devicePromise;
const promise = (async () => {
if (!navigator.gpu) {
const message = "WebGPU is unavailable in this browser. Use a current Chrome or Edge (113+) with hardware acceleration enabled (chrome://settings/system), or launch with --enable-unsafe-webgpu.";
logError(message);
await dumpDiagnostics();
throw new Error(message);
}
logInfo("Requesting WebGPU adapter (falling back across power preferences)...");
let adapter = null;
let lastAdapterError = null;
for (const powerPreference of ["high-performance", "low-power", undefined]) {
try {
const options = powerPreference ? {powerPreference} : undefined;
logDebug("navigator.gpu.requestAdapter(", powerPreference || "default", ")");
adapter = await navigator.gpu.requestAdapter(options);
if (adapter) {
logInfo("Adapter found with powerPreference =", powerPreference || "default");
break;
}
} catch (err) {
lastAdapterError = err;
logWarn("requestAdapter(", powerPreference || "default", ") threw:", err);
}
}
if (!adapter) {
const message = "No WebGPU adapter found. Possible causes: disabled hardware acceleration, an outdated or failing GPU driver, or WebGPU blocked by a browser flag. See the diagnostics above and try chrome://gpu.";
logError(message, lastAdapterError || "");
await dumpDiagnostics();
throw new Error(message);
}
const info = adapter.info || {};
state.adapterText = info.device || info.description || info.vendor || "high-performance adapter";
logInfo("Adapter selected:", state.adapterText, JSON.stringify(info));
setText("adapter-meta", state.adapterText);
logDebug("Adapter limits:", {
maxBufferSize: adapter.limits.maxBufferSize,
maxStorageBufferBindingSize: adapter.limits.maxStorageBufferBindingSize,
maxComputeWorkgroupsPerDimension: adapter.limits.maxComputeWorkgroupsPerDimension
});
// Large runs (30k paths x 5,040 strategies) need storage buffers above
// Chrome's default caps, so request the adapter's own maxima.
let device;
try {
device = await adapter.requestDevice({
requiredLimits: {
maxBufferSize: adapter.limits.maxBufferSize,
maxStorageBufferBindingSize: adapter.limits.maxStorageBufferBindingSize
}
});
} catch (err) {
logError("adapter.requestDevice() failed:", err);
throw err;
}
// Surface GPU-side failures instead of letting them fail silently.
device.addEventListener("uncapturederror", (event) => {
const error = event.error || {};
logError("GPU uncaptured error:", error.message, error.stack ? "\n" + error.stack : "");
});
device.lost.then((lostInfo) => {
state.deviceLostReason = lostInfo.reason + (lostInfo.message ? " (" + lostInfo.message + ")" : "");
logError("WebGPU device lost:", state.deviceLostReason);
setStatus("WebGPU device lost: " + state.deviceLostReason, true);
setText("run-message", "The GPU device was lost (" + state.deviceLostReason + "). Reload the page; if this repeats, check your GPU driver.");
});
const visibility = GPUShaderStage.COMPUTE;
// Main module: seven storage bindings (0-6). The Chrome D3D12 backend on
// AMD drivers silently drops dispatch writes beyond two read-write storage
// buffers per stage, so returns/layoffs/states share one packed scratch
// buffer (binding 1) and spending is the only other read-write binding (6).
let shader;
try {
shader = device.createShaderModule({code: SHADER_SOURCE});
} catch (err) {
logError("createShaderModule failed for the main pipeline:", err);
throw err;
}
const layout = device.createBindGroupLayout({entries: Array.from({length: 7}, (_, binding) => ({
binding, visibility, buffer: {type: binding === 1 || binding === 6 ? "storage" : "read-only-storage"}
}))});
const pipelineLayout = device.createPipelineLayout({bindGroupLayouts: [layout]});
const generateReturns = device.createComputePipeline({layout: pipelineLayout, compute: {module: shader, entryPoint: "generate_returns"}});
const generateLayoffs = device.createComputePipeline({layout: pipelineLayout, compute: {module: shader, entryPoint: "generate_layoffs"}});
const accumulate = device.createComputePipeline({layout: pipelineLayout, compute: {module: shader, entryPoint: "accumulate"}});
const solve = device.createComputePipeline({layout: pipelineLayout, compute: {module: shader, entryPoint: "solve"}});
const trackDrawdowns = device.createComputePipeline({layout: pipelineLayout, compute: {module: shader, entryPoint: "track_drawdowns"}});
// Quantile module: separate 3-binding layout with a single read-write
// binding.
let quantilesShader;
try {
quantilesShader = device.createShaderModule({code: QUANTILES_SHADER_SOURCE});
} catch (err) {
logError("createShaderModule failed for the quantile pipeline:", err);
throw err;
}
const quantileLayout = device.createBindGroupLayout({entries: [
{binding: 0, visibility, buffer: {type: "read-only-storage"}},
{binding: 1, visibility, buffer: {type: "read-only-storage"}},
{binding: 2, visibility, buffer: {type: "storage"}}
]});
const quantilePipelineLayout = device.createPipelineLayout({bindGroupLayouts: [quantileLayout]});
const quantiles = device.createComputePipeline({layout: quantilePipelineLayout, compute: {module: quantilesShader, entryPoint: "quantiles"}});
// Bequest module: separate 7-binding layout (0-4 read-only, 5-6 the
// read-write estate ladder output and the persistent accumulation
// histogram — two read-write bindings, within the AMD/D3D12 limit; the
// per-simulation inputs are packed into one sim_data buffer to stay
// within the max-8-storage-buffers-per-stage limit). Three entry points
// mirror the solver's batching so no single dispatch outlives the
// Windows TDR watchdog: bequest_reset zeroes the persistent histogram,
// bequest_walk accumulates one batch of lives per dispatch,
// bequest_final reduces the histogram to the 201-point ladders.
let bequestShader;
try {
bequestShader = device.createShaderModule({code: BEQUEST_SHADER_SOURCE});
} catch (err) {
logError("createShaderModule failed for the bequest pipeline:", err);
throw err;
}
const bequestLayout = device.createBindGroupLayout({entries: Array.from({length: 7}, (_, binding) => ({
binding, visibility, buffer: {type: binding === 5 || binding === 6 ? "storage" : "read-only-storage"}
}))});
const bequestPipelineLayout = device.createPipelineLayout({bindGroupLayouts: [bequestLayout]});
const bequestReset = device.createComputePipeline({layout: bequestPipelineLayout, compute: {module: bequestShader, entryPoint: "bequest_reset"}});
const bequestWalk = device.createComputePipeline({layout: bequestPipelineLayout, compute: {module: bequestShader, entryPoint: "bequest_walk"}});
const bequestFinal = device.createComputePipeline({layout: bequestPipelineLayout, compute: {module: bequestShader, entryPoint: "bequest_final"}});
const context = {device, layout, quantileLayout, generateReturns, generateLayoffs, accumulate, solve, trackDrawdowns, quantiles, bequestLayout, bequestReset, bequestWalk, bequestFinal, limits: device.limits};
state.deviceContext = context;
setStatus("WebGPU ready: " + state.adapterText, false);
logInfo("WebGPU device context ready on", state.adapterText);
return context;
})();
state.devicePromise = promise;
try { return await promise; }
catch (err) {
logError("createDeviceContext failed:", err);
throw err;
}
finally { if (state.devicePromise === promise) state.devicePromise = null; }
}
function leverageEnabled() {
const toggle = byId("chk-leverage");
return !toggle || toggle.checked;
}
function allocationPool(leverage) {
// Source indices into ALLOCATION_NAMES/METADATA for a run. With leverage
// ON the pool is every strategy (5,040); OFF it drops every strategy whose
// accumulation, bridge or post phase is VEQT1.5 or VEQT2 (1,600 remain).
if (leverage) return Array.from({length: TOTAL_ALLOCATIONS}, (_, i) => i);
const pool = [];
for (let i = 0; i < TOTAL_ALLOCATIONS; i++) {
const codes = ALLOCATION_METADATA.subarray(i * 4, i * 4 + 3);
if (LEVERAGED_FUND_CODES.includes(codes[0]) || LEVERAGED_FUND_CODES.includes(codes[1]) || LEVERAGED_FUND_CODES.includes(codes[2])) continue;
pool.push(i);
}
return pool;
}
function effectiveAllocationCount(leverage) {
// The ?allocations=N URL cap applies to the leverage-filtered pool.
return Math.min(RUN_ALLOCATION_COUNT, allocationPool(leverage).length);
}
function selectedAllocationIndices(count, leverage) {
const pool = allocationPool(leverage);
if (count === pool.length) return pool;
// count - 1 is the stride divisor below, so a single-allocation cap must be
// handled explicitly (pool[NaN] would silently zero the metadata row).
if (count <= 1) return [pool[0]];
return Array.from({length: count}, (_, i) => pool[Math.floor(i * (pool.length - 1) / (count - 1))]);
}
function glidepathBoundaries(code, months, constants) {
// Mirrors calibration._glidepath_boundaries exactly: the first two legs of
// the glidepath take their share of `months` (rounded to nearest month,
// remaining months reserved for the last leg). The shares come from
// dynamic.constants (the editable settings), one schedule for every
// glidepath phase.
const dec = constants.glidepathDeclining, ris = constants.glidepathRising;
const roundMonths = share => Math.round(Math.max(0, Math.min(1, share)) * months);
if (code === 5) {
const first = roundMonths(dec[0]);
return [first, first + roundMonths(dec[1])];
}
if (code === 6) {
const first = roundMonths(ris[0]);
return [first, first + roundMonths(ris[1])];
}
return [0, 0];
}
function selectedAllocationBuffer(count, constants, leverage) {
const indices = selectedAllocationIndices(count, leverage);
const data = new Uint32Array(count * 12);
for (let i = 0; i < count; i++) {
const metadata = ALLOCATION_METADATA.subarray(indices[i] * 4, indices[i] * 4 + 4);
const offset = i * 12;
data.set(metadata, offset);
data.set(glidepathBoundaries(metadata[0], constants.accumMonths, constants), offset + 4);
data.set(glidepathBoundaries(metadata[1], constants.bridgeMonths, constants), offset + 6);
data.set(glidepathBoundaries(metadata[2], constants.retireMonths - constants.bridgeMonths, constants), offset + 8);
}
return {indices, data};
}
function setProgress(done, total, detail) {
byId("progress-fill").style.width = (total ? (100 * done / total) : 0) + "%";
setText("progress-detail", detail);
}
async function simulate(settings, run) {
const context = await createDeviceContext();
const dynamic = buildDynamicModel(settings.model);
const device = context.device;
const batchSize = DEFAULTS.batchSize;
const leverage = leverageEnabled();
const allocationCount = effectiveAllocationCount(leverage);
// Dispatch shaping: each solve/track_drawdowns thread serially walks
// `columnsPerWorkgroup` allocation columns (stride = dispatch_y), keeping
// the grid ONE dispatch per pass - splitting the allocation space into
// multiple dispatches silently corrupts results on some AMD D3D12 drivers.
// The shaders mirror the stride math, so results are byte-identical for
// any column count. Measured (batch 250): at the full 5,040-strategy space
// the solve dispatch is throughput-bound and takes ~0.18 s regardless of
// the column count, while at small spaces (e.g. leverage off = 1,600)
// fewer columns give strictly shorter dispatches (61 ms at 1 column vs
// 121 ms at 16). The configured default is therefore 1 column per thread
// (maximum parallelism, shortest dispatches, most TDR headroom).
const columnsPerWorkgroup = Math.max(1, DEFAULTS.columnsPerWorkgroup | 0);
const dispatchAllocations = Math.max(1, Math.ceil(allocationCount / columnsPerWorkgroup));
const totalSims = settings.simulations;
const rqmcBits = rqmcSamplerEnabled(dynamic, totalSims) ? SOBOL_RQMC_BITS : 0;
logInfo("Simulation start:", {simulations: totalSims, allocations: allocationCount, leverage, batchSize,
columnsPerWorkgroup, dispatchAllocations,
totalMonths: dynamic.constants.totalMonths, careerYears: dynamic.constants.careerYears,
pathCount: dynamic.constants.funds.length, houseCount: C.houseCount,
retirementAge: settings.model.retirementAge, pensionStartAge: settings.model.pensionStartAge,
sampler: rqmcBits ? "rqmc-sobol (default)" : "threefry (legacy)"});
// Preflight: the spending and drawdown buffers are both
// allocationCount x totalSims x 4 bytes; a run that needs more than the
// GPU's storage-buffer binding limit would fail with an opaque WebGPU
// validation error (silently dropped dispatches -> zero results).
const neededBytes = allocationCount * totalSims * 4;
const bufferCap = Math.min(device.limits.maxBufferSize, device.limits.maxStorageBufferBindingSize);
if (neededBytes > bufferCap) {
throw new Error(
"This run needs " + Math.round(neededBytes / 1048576) + " MB per result buffer, but the GPU caps storage buffers at " +
Math.round(bufferCap / 1048576) + " MB. Reduce the simulation count (or load with fewer allocations, e.g. ?allocations=1000)."
);
}
const pathCount = dynamic.constants.funds.length;
const totalMonths = dynamic.constants.totalMonths;
const careerYears = dynamic.constants.careerYears;
const houseCount = C.houseCount;
// The estate grid is a config constant (the fractions live in the model
// buffer tail), independent of (theta, k).
const estateGrid = Math.max(1, (dynamic.constants.estateGridFractions || []).length);
// Packed global per-simulation data for the bequest pass (returns, states,
// house outcomes) - sized here so the buffer log below can reference it.
const simDataWords = totalSims * totalMonths * RETURN_FUND_COUNT + houseCount * pathCount * totalSims * 4 + houseCount * totalSims * 2;
const selected = selectedAllocationBuffer(allocationCount, dynamic.constants, leverage);
const allocationBuffer = staticBuffer(device, selected.data);
const modelBuffer = staticBuffer(device, dynamic.staticValues);
const scratchSize = (batchSize * totalMonths * RETURN_FUND_COUNT + batchSize * careerYears + houseCount * pathCount * batchSize * 4 + houseCount * batchSize * 2 + batchSize * allocationCount + pathCount * batchSize) * 4;
logDebug("GPU buffers (MB):", {
scratch: (scratchSize / 1048576).toFixed(1),
spending: (allocationCount * totalSims * 4 / 1048576).toFixed(1),
drawdownReadback: (allocationCount * totalSims * 4 / 1048576).toFixed(1),
quantileOutput: (allocationCount * 201 * 4 / 1048576).toFixed(1),
estateOutput: (allocationCount * estateGrid * 201 * 4 / 1048576).toFixed(1),
estateHist: (allocationCount * estateGrid * 514 * 4 / 1048576).toFixed(1),
estateInputs: (simDataWords * 4 / 1048576).toFixed(1),
limit: (Math.min(device.limits.maxBufferSize, device.limits.maxStorageBufferBindingSize) / 1048576).toFixed(0)
});
const scratchBuffer = device.createBuffer({size: scratchSize, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC});
const spendingBuffer = device.createBuffer({size: allocationCount * totalSims * 4, usage: GPUBufferUsage.STORAGE});
const quantileBuffer = device.createBuffer({size: allocationCount * 201 * 4, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC});
const quantileReadback = device.createBuffer({size: allocationCount * 201 * 4, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST});
const drawdownReadback = device.createBuffer({size: allocationCount * totalSims * 4, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST});
const houseReadback = device.createBuffer({size: houseCount * batchSize * 2 * 4, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST});
const houseOutcomes = {bought: [], buyMonth: []};
for (let h = 0; h < houseCount; h++) {
houseOutcomes.bought.push(new Uint8Array(totalSims));
houseOutcomes.buyMonth.push(new Float32Array(totalSims));