-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathui.mjs
More file actions
1988 lines (1803 loc) · 78.7 KB
/
Copy pathui.mjs
File metadata and controls
1988 lines (1803 loc) · 78.7 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
/**
* UI module for BOxCrete interactive demo.
* Handles sliders, canvas rendering (scatter + strength curve),
* and interaction between views.
*/
import { predictStrengthCurve, predictStrengthMeanOnly, predictGWP, predictCost, initStrengthModel, initWASM } from "./gp.mjs";
import {
UNITS,
compToDisplay,
compFromDisplay,
sliderUnitLabel as sliderUnitLabelFor,
} from "./units.mjs";
// --- Shared Helpers ---
function easeInOutCubic(t) {
return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
}
// Generate `nPts` log-spaced curing times in [0, 28] days. Denser at early
// times where strength changes fastest — inverse of `log10(t+1)/log10(29)`.
// Used by `drawStrengthCurve` (32 pts interactive / 64 pts idle), the
// Material Source curve transition (64 pts), and the always-on preview
// curve (PREVIEW_PTS pts).
function logSpacedTimes(nPts) {
return Array.from({ length: nPts }, (_, i) => {
const t01 = i / (nPts - 1);
return Math.pow(29, t01) - 1;
});
}
// Convert GP variances to standard deviations including model noise.
// `variances` is the array returned by `predictStrengthCurve`; we add the
// noise variance (in the GP's normalised target space) before sqrt.
function computeStds(variances, params) {
const noiseVar = params.noise_variance * params.y_std * params.y_std;
return variances.map((v) => Math.sqrt(v + noiseVar));
}
// --- Cached DOM Elements & Indices ---
let _sliderInputs = null; // cached after buildSliders()
let COL_MS = -1; // "Material Source" column index
let COL_TEMP = -1; // "Temp (C)" column index
// --- State ---
let strengthParams = null;
let gwpParams = null;
let costParams = null;
let compositionsData = null;
let currentComposition = null; // current slider values (without time)
let scatterDay = 28;
let scatterXAxis = "gwp"; // "gwp" or "cost"
let curveObsPositions = []; // [{px, py, time, strength}] for tooltip hit-testing
let animationId = null; // for smooth transitions
// Most recent animation TARGET (intended end state). When the user commits a
// click-to-edit value during an in-flight animation, we build the new target
// from this — not from mid-lerp `currentComposition` — so other still-animating
// sliders land at their intended positions.
let _lastAnimTarget = null;
let scatterFilter = null; // [{colIdx, min, max}] array or null
let mixAnalyses = null; // pre-computed mix descriptions
let animLoopId = null; // unified animation loop frame ID
let lastFrameTime = 0; // for frame-rate-independent interpolation
let scatterTransition = null; // {startTime, duration, fromX, fromY, toX, toY, fromPareto, toPareto}
let _curveYMax = null; // smoothly interpolated y-axis max for strength curve
let _curveYMaxTarget = null; // target y-max (for animation loop convergence check)
// Material Source curve transition: when the user toggles Material Source, we
// snapshot the pre-toggle strength curve and blend it linearly with the
// post-toggle curve over `duration` ms. Because Material Source is binary,
// composition-level interpolation would feed the GP non-categorical values
// and yield a noisy intermediate prediction. Curve-level interpolation keeps
// the visual aesthetic smooth without violating the GP's input domain.
let _msCurveTransition = null; // {startTime, duration, times, fromMeans, fromStds}
// --- Unit System ---
let unitSystem = "metric"; // "metric" or "imperial"
// `UNITS` is imported from `./units.mjs` (single source of truth, also used
// by the Node-based `test/test_js_units.mjs` parity tests).
function U() { return UNITS[unitSystem]; }
// Animated unit transition
let unitTransition = null; // {startTime, duration, from, to}
function getDisplayFactors() {
if (!unitTransition) return U();
const elapsed = performance.now() - unitTransition.startTime;
const t = Math.min(elapsed / unitTransition.duration, 1);
const ease = easeInOutCubic(t);
const from = unitTransition.from;
const to = unitTransition.to;
if (t >= 1) { unitTransition = null; return to; }
return {
strength: to.strength,
strengthFactor: from.strengthFactor + (to.strengthFactor - from.strengthFactor) * ease,
mass: to.mass,
massFactor: from.massFactor + (to.massFactor - from.massFactor) * ease,
gwp: to.gwp,
gwpFactor: from.gwpFactor + (to.gwpFactor - from.gwpFactor) * ease,
cost: to.cost,
costFactor: from.costFactor + (to.costFactor - from.costFactor) * ease,
};
}
// Listen for unit toggle
document.addEventListener("toggle-units", () => {
// Blur any in-progress click-to-edit before the unit transition. Otherwise,
// a number typed in (e.g.) kg/m³ would be interpreted in lb/yd³ on commit.
// Blur fires the input's blur listener, which commits the edit in the
// pre-toggle unit context.
const active = document.activeElement;
if (active && active.classList && active.classList.contains("slider-value")) {
active.blur();
}
const oldFactors = { ...U() };
unitSystem = unitSystem === "metric" ? "imperial" : "metric";
const newFactors = { ...U() };
unitTransition = { startTime: performance.now(), duration: 350, from: oldFactors, to: newFactors };
document.getElementById("unit-label").textContent = unitSystem === "metric" ? "SI" : "US";
const mobileUnitLabel = document.getElementById("mobile-unit-label");
if (mobileUnitLabel) mobileUnitLabel.textContent = unitSystem === "metric" ? "SI" : "US";
// Update composition toggle button label with current unit
const mobileSlidersBtn = document.getElementById("mobile-show-sliders");
if (mobileSlidersBtn) {
mobileSlidersBtn.textContent = unitSystem === "metric" ? "Composition (kg/m³)" : "Composition (lb/yd³)";
}
document.getElementById("gwp-unit").textContent = U().gwp;
document.getElementById("cost-unit").textContent = U().cost;
document.getElementById("sliders-title").textContent =
unitSystem === "metric" ? "Composition (kg/m³)" : "Composition (lb/yd³)";
updateSliderLabels();
startAnimLoop();
});
// --- Load model data ---
async function loadJSON(path) {
const resp = await fetch(path);
return resp.json();
}
async function init() {
[strengthParams, gwpParams, costParams, compositionsData] = await Promise.all([
loadJSON("model/strength.json"),
loadJSON("model/gwp.json"),
loadJSON("model/cost.json"),
loadJSON("model/compositions.json"),
]);
// Load mix analyses (non-blocking, optional)
loadJSON("model/mix_analyses.json").then(d => { mixAnalyses = d; updateMixInsight(); }).catch(() => {});
// Compute Cholesky and alpha from training data + kernel params
initStrengthModel(strengthParams);
// Initialize WASM BLAS for accelerated variance (non-blocking, falls back to JS)
initWASM(strengthParams);
buildSliders();
_sliderInputs = document.querySelectorAll("#sliders input[type=range]");
COL_MS = compositionsData.column_names.indexOf("Material Source");
COL_TEMP = compositionsData.column_names.indexOf("Temp (C)");
setupEventListeners();
update();
startAnimLoop();
updateMixInsight(); // initial insight for default composition
}
// --- Sliders ---
// Ingredient descriptions — shown when clicking the ingredient name
const ingredientInfo = {
"Cement": "Portland cement (OPC) is the primary binder in concrete. Hydration of its clinker minerals (C₃S, C₂S, C₃A, C₄AF) produces calcium silicate hydrate (C-S-H) gel, which gives concrete its strength. High early strength contribution but the most carbon-intensive ingredient — producing 1 tonne of cement releases ~0.6–0.9 tonnes of CO₂ from calcination and kiln fuel.",
"Fly Ash": "A pozzolanic byproduct of coal combustion. Glassy silica spheres react slowly with calcium hydroxide from cement hydration to form additional C-S-H gel. Improves long-term strength and durability, reduces permeability, and has near-zero embodied carbon (it's a waste product). The spherical particles also improve workability (ball-bearing effect). Slower early strength gain than cement.",
"Slag": "Ground granulated blast furnace slag (GGBFS) — a latent hydraulic byproduct of iron production. Activated by the alkaline environment from cement hydration, it produces C-S-H gel independently. Excellent late-age strength development, lower heat of hydration (reducing thermal cracking risk), and significantly lower GWP than cement. Can replace 30–70% of cement in typical mixes.",
"Water": "Controls the water-to-binder (W/B) ratio, the single most important factor for concrete strength and durability. Lower W/B produces a denser, stronger, more durable matrix with less capillary porosity — but reduces workability. Superplasticizers (HRWR) allow low W/B while maintaining flowability.",
"HRWR": "High-range water reducer (superplasticizer). A chemical admixture that disperses cement particles via electrostatic or steric repulsion, dramatically improving flowability without adding water. Enables ultra-low W/B ratios (0.20–0.25) that would otherwise be unworkable. Essential for high-performance concrete.",
"Fine Aggregate": "Sand — provides bulk volume, dimensional stability, and load transfer in the morite matrix. Particle size distribution (gradation) affects packing density and paste demand. Typically river sand or manufactured sand from crushed rock.",
"Coarse Aggregates": "Gravel or crushed stone (>4.75 mm) — forms the structural skeleton of concrete. The interfacial transition zone (ITZ) between paste and aggregate is often the weakest link. Well-graded aggregates improve packing and reduce paste demand. Typically 60–75% of concrete by volume.",
"Material Source": "Identifies the source of raw materials. Different sources have varying mineral compositions, particle size distributions, and reactivity — all of which affect strength development, workability, and durability. Source-specific models account for this variability.",
"Temperature": "Curing temperature significantly affects hydration kinetics. Higher temperatures accelerate early hydration (faster early strength) but can reduce ultimate strength due to non-uniform hydrate distribution. Low temperatures slow hydration but can improve long-term microstructure. The Arrhenius-based maturity concept links time and temperature to strength development.",
};
function buildSliders() {
const container = document.getElementById("sliders");
const bounds = compositionsData.slider_bounds;
const colNames = compositionsData.column_names;
// Skip MRWR (always 0 in dataset — no range)
const skipCols = new Set(["MRWR (kg/m3)"]);
// Use median composition as initial values
const compositions = compositionsData.compositions;
const n = compositions.length;
const medianIdx = Math.floor(n / 2);
currentComposition = [...compositions[medianIdx]];
displayPreviewComp = [...currentComposition];
for (let i = 0; i < colNames.length; i++) {
const col = colNames[i];
if (skipCols.has(col)) continue;
// Material Source gets a toggle instead of a slider
if (col === "Material Source") {
const group = document.createElement("div");
// `material-source-group` lets mobile CSS hide the redundant value-span
// and span the toggle-row across cols 2–3 without a `:has()` selector
// (Safari < 15.4 still hits this page).
group.className = "slider-group material-source-group";
const label = document.createElement("label");
const nameSpan = document.createElement("span");
nameSpan.textContent = "Material Source";
nameSpan.className = "ingredient-name";
nameSpan.addEventListener("click", (e) => {
e.preventDefault();
toggleIngredientInfo(group, "Material Source");
});
const valueSpan = document.createElement("span");
valueSpan.id = `val-${i}`;
valueSpan.textContent = currentComposition[i] === 0 ? "Source A" : "Source B";
label.append(nameSpan, valueSpan);
const toggle = document.createElement("div");
toggle.className = "toggle-row";
const btn0 = document.createElement("button");
btn0.textContent = "Source A";
btn0.className = currentComposition[i] === 0 ? "toggle-btn active" : "toggle-btn";
btn0.addEventListener("click", () => {
// Smooth curve-level transition (see `triggerMaterialSourceTransition`).
// Updates `currentComposition[i]` and `displayPreviewComp[i]` internally.
triggerMaterialSourceTransition(i, 0);
btn0.className = "toggle-btn active";
btn1.className = "toggle-btn";
document.getElementById(`val-${i}`).textContent = "Source A";
update();
// Refresh mix insight: the new composition (median + other MS) is
// typically NOT in the training set, so the previous mix's description
// would otherwise persist stale. Schedule with the same delay used by
// `animateToComposition` so the insight settles after the curve does.
scheduleInsightUpdate();
checkExtrapolationWarning();
});
const btn1 = document.createElement("button");
btn1.textContent = "Source B";
btn1.className = currentComposition[i] === 1 ? "toggle-btn active" : "toggle-btn";
btn1.addEventListener("click", () => {
triggerMaterialSourceTransition(i, 1);
btn0.className = "toggle-btn";
btn1.className = "toggle-btn active";
document.getElementById(`val-${i}`).textContent = "Source B";
update();
scheduleInsightUpdate();
checkExtrapolationWarning();
});
toggle.append(btn0, btn1);
group.append(label, toggle);
container.appendChild(group);
continue;
}
const b = bounds[col];
if (b.min === b.max) continue; // skip zero-range sliders
const group = document.createElement("div");
group.className = "slider-group";
const label = document.createElement("label");
const nameSpan = document.createElement("span");
// Display name: strip unit suffix and rename "Temp" → "Temperature" for
// a friendlier label. The underlying column name in `compositionsData`
// is unchanged (still "Temp (C)") so model code keeps working.
let shortName = col.replace(" (kg/m3)", "").replace(" (C)", "");
if (shortName === "Temp") shortName = "Temperature";
nameSpan.textContent = shortName;
// Make ingredient names clickable for info
const infoKey = shortName;
if (ingredientInfo[infoKey]) {
nameSpan.className = "ingredient-name";
nameSpan.addEventListener("click", (e) => {
e.preventDefault();
toggleIngredientInfo(group, infoKey);
});
}
const valueInput = document.createElement("input");
valueInput.id = `val-${i}`;
valueInput.className = "slider-value";
valueInput.type = "text";
// `decimal` is safe here: all composition columns have b.min >= 0, so no
// negative values are ever entered (no need for `-` key on iOS Safari).
valueInput.inputMode = "decimal";
valueInput.setAttribute("aria-label", `${shortName} value`);
valueInput.value = displayCompValue(col, currentComposition[i]).toFixed(1);
valueInput.dataset.idx = i;
valueInput.dataset.col = col;
attachValueEditHandlers(valueInput, i, col, b);
// Per-row unit suffix (kg/m³ ↔ lb/yd³ on toggle; °C for Temperature).
// Wrapped in a flex container so the label keeps its two-child
// `space-between` layout (name on the left, value+unit packed on the right).
const valueWrap = document.createElement("span");
valueWrap.className = "slider-value-wrap";
const unitSpan = document.createElement("span");
unitSpan.className = "slider-unit";
unitSpan.id = `unit-${i}`;
unitSpan.textContent = sliderUnitLabel(col);
valueWrap.append(valueInput, unitSpan);
label.append(nameSpan, valueWrap);
const input = document.createElement("input");
input.type = "range";
input.min = b.min;
input.max = b.max;
input.step = (b.max - b.min) / 200;
input.value = currentComposition[i];
input.dataset.idx = i;
input.dataset.col = col;
input.addEventListener("input", onSliderChange);
const infoRow = document.createElement("div");
infoRow.className = "info-row";
infoRow.innerHTML = `<span>${b.min.toFixed(0)}</span><span>${b.max.toFixed(0)}</span>`;
group.append(label, input, infoRow);
container.appendChild(group);
}
}
// Show ingredient info in the dedicated panel
let _activeIngredientKey = null;
function animateContentSwap(bodyEl, textEl, newHTML) {
const prevHeight = bodyEl.offsetHeight;
textEl.classList.add("fade-out");
setTimeout(() => {
textEl.innerHTML = newHTML;
bodyEl.style.height = "auto";
const newHeight = bodyEl.offsetHeight;
bodyEl.style.height = prevHeight + "px";
requestAnimationFrame(() => {
bodyEl.style.height = newHeight + "px";
});
textEl.classList.remove("fade-out");
textEl.classList.add("fade-in");
requestAnimationFrame(() => textEl.classList.remove("fade-in"));
setTimeout(() => { bodyEl.style.height = "auto"; }, 300);
}, 300);
}
function toggleIngredientInfo(group, key) {
const textEl = document.getElementById("ingredient-insight-text");
const bodyEl = document.querySelector(".ingredient-insight-body");
// Toggle off if same ingredient clicked again
if (_activeIngredientKey === key) {
animateContentSwap(bodyEl, textEl, '<span class="mix-insight-placeholder">Click an ingredient name in the Composition panel to learn more.</span>');
_activeIngredientKey = null;
for (const el of document.querySelectorAll(".ingredient-name.active")) {
el.classList.remove("active");
}
return;
}
// Update active highlight
for (const el of document.querySelectorAll(".ingredient-name.active")) {
el.classList.remove("active");
}
const nameSpan = group.querySelector(".ingredient-name");
if (nameSpan) nameSpan.classList.add("active");
// FLIP: measure current height, crossfade content, animate to new height
animateContentSwap(bodyEl, textEl, `<strong>${key}</strong> — ${ingredientInfo[key]}`);
_activeIngredientKey = key;
}
// --- Slider Preview (hover composition preview) ---
// Update both the range input position and the editable value display.
// The value display is an <input> for regular sliders (click-to-edit) and a
// <span> for the Material Source row. We must use `.value` for inputs and
// `.textContent` for spans, and we must NOT clobber an in-progress edit
// (the focused element).
function syncSliderDOM(comp, updateValues = true) {
if (!_sliderInputs) return;
for (const slider of _sliderInputs) {
const idx = parseInt(slider.dataset.idx);
if (updateValues) slider.value = comp[idx];
setValueDisplay(idx, displayCompValue(slider.dataset.col, comp[idx]).toFixed(1));
}
}
function setValueDisplay(idx, formatted) {
const el = document.getElementById(`val-${idx}`);
if (!el) return;
// Don't clobber an in-progress click-to-edit. The blur/Enter handlers will
// refresh the display once the edit commits or reverts.
if (el === document.activeElement) return;
if (el.tagName === "INPUT") {
el.value = formatted;
} else {
el.textContent = formatted;
}
}
function showSliderPreview(comp) {
if (!_sliderInputs) return;
for (const slider of _sliderInputs) {
const idx = parseInt(slider.dataset.idx);
const val = comp[idx];
const min = parseFloat(slider.min);
const max = parseFloat(slider.max);
const fraction = (val - min) / (max - min);
// Get or create preview marker
let marker = slider.parentElement.querySelector(".slider-preview-marker");
if (!marker) {
marker = document.createElement("div");
marker.className = "slider-preview-marker";
slider.parentElement.insertBefore(marker, slider.nextSibling);
}
// Account for range input thumb inset (thumb center at min is `thumbHalf`
// px from each edge of the input box). The half-width is exposed as a
// CSS variable on `.slider-group` so the desktop (9 px) and mobile
// (8 px, smaller thumb) values stay in sync with the actual rendered
// thumb size — falls back to 9 if the variable isn't set.
// `slider.offsetLeft` is 0 on desktop (the slider is a full-width child of
// `.slider-group`), but on mobile the slider lives in column 2 of a CSS grid
// so we must include its offset within the positioning parent.
const thumbHalfRaw = getComputedStyle(slider.parentElement).getPropertyValue("--thumb-half");
const thumbHalf = parseFloat(thumbHalfRaw) || 9;
const trackWidth = slider.offsetWidth - 2 * thumbHalf;
const leftPx = slider.offsetLeft + thumbHalf + fraction * trackWidth;
marker.style.left = leftPx + "px";
// Align vertically with the slider thumb center
marker.style.top = `${slider.offsetTop + slider.offsetHeight / 2}px`;
marker.style.display = "block";
}
const panel = document.getElementById("sliders-panel");
panel.classList.add("previewing");
}
function hideSliderPreview() {
const markers = document.querySelectorAll(".slider-preview-marker");
for (const m of markers) m.style.display = "none";
const panel = document.getElementById("sliders-panel");
panel.classList.remove("previewing");
}
let _sliderActive = false;
let _sliderIdleTimer = null;
function onSliderChange(e) {
const idx = parseInt(e.target.dataset.idx);
currentComposition[idx] = parseFloat(e.target.value);
displayPreviewComp[idx] = currentComposition[idx];
const displayVal = displayCompValue(e.target.dataset.col, currentComposition[idx]);
setValueDisplay(idx, displayVal.toFixed(1));
_sliderActive = true;
if (_sliderIdleTimer) clearTimeout(_sliderIdleTimer);
_sliderIdleTimer = setTimeout(() => { _sliderActive = false; update(); }, 150);
update();
startAnimLoop(); // keep loop alive for smooth y-axis expansion
updateMixInsight(); // immediate for manual slider adjustments
checkExtrapolationWarning();
}
// Display value for a composition column under the active unit system.
// Handles both mass (factor) and temperature (factor + offset).
function displayCompValue(colName, internal) {
return compToDisplay(colName, internal, unitSystem);
}
// Inverse of `displayCompValue`: parse a user-typed display value back to
// the model-native (kg/m³ or °C) value before clamping/storage.
function internalCompValue(colName, display) {
return compFromDisplay(colName, display, unitSystem);
}
// Unit suffix label for a slider column (delegates to `units.mjs`).
function sliderUnitLabel(colName) {
return sliderUnitLabelFor(colName, unitSystem);
}
function updateSliderLabels() {
syncSliderDOM(currentComposition, false);
// Update info rows (min/max labels) and per-row unit suffixes
const bounds = compositionsData.slider_bounds;
const colNames = compositionsData.column_names;
const infoRows = document.querySelectorAll("#sliders .info-row");
let rowIdx = 0;
for (let i = 0; i < colNames.length; i++) {
const col = colNames[i];
if (col === "MRWR (kg/m3)" || col === "Material Source") continue;
const b = bounds[col];
if (b.min === b.max) continue;
if (rowIdx < infoRows.length) {
// Use offset-aware converter so temperature bounds render correctly
// in °F (e.g. -20°C → -4°F, 22°C → 72°F) under imperial.
const minDisp = displayCompValue(col, b.min).toFixed(0);
const maxDisp = displayCompValue(col, b.max).toFixed(0);
infoRows[rowIdx].innerHTML = `<span>${minDisp}</span><span>${maxDisp}</span>`;
rowIdx++;
}
// Refresh per-row unit suffix (kg/m³ ↔ lb/yd³, °C ↔ °F)
const unitEl = document.getElementById(`unit-${i}`);
if (unitEl) unitEl.textContent = sliderUnitLabel(col);
}
}
// --- Animated transition to a new composition ---
function animateToComposition(targetComp) {
if (animationId) cancelAnimationFrame(animationId);
// A scatter-click animation supersedes any in-flight Material Source curve
// transition: the new composition takes over and we recompute the curve
// from the lerped composition each frame.
_msCurveTransition = null;
hideExtrapolationWarning(); // suppress during transition
startAnimLoop();
// Track the *intended* end state so a click-to-edit during this animation
// can build the new target from un-clobbered values. Cleared on completion.
_lastAnimTarget = [...targetComp];
const startComp = [...currentComposition];
const duration = 350; // ms
const startTime = performance.now();
function step(now) {
const t = Math.min((now - startTime) / duration, 1);
// Smooth easing (ease-in-out: starts at zero velocity, ends at zero velocity)
const ease = easeInOutCubic(t);
// Lerp each dimension
for (let i = 0; i < startComp.length; i++) {
currentComposition[i] = startComp[i] + (targetComp[i] - startComp[i]) * ease;
}
syncSliderDOM(currentComposition);
update();
if (t < 1) {
animationId = requestAnimationFrame(step);
} else {
animationId = null;
_lastAnimTarget = null;
// Snap to exact target and update toggle
setComposition(targetComp);
// Sequenced: update insight after the curve has settled
scheduleInsightUpdate();
checkExtrapolationWarning();
}
}
animationId = requestAnimationFrame(step);
}
// --- Material Source curve-level transition ---
// Material Source is a binary categorical input; feeding the GP fractional
// values (0.5) gives a noisy intermediate prediction outside the training
// distribution. Instead, snapshot the pre-toggle posterior curve, commit the
// new MS value to `currentComposition`, and let `drawStrengthCurve` blend
// the cached `from` curve with each frame's freshly computed `to` curve over
// `MS_TRANSITION_MS`. The result is a smooth visual that respects the GP's
// input domain.
const MS_TRANSITION_MS = 350;
function triggerMaterialSourceTransition(idx, newVal) {
if (!strengthParams) {
// Predictor not yet initialized — fall back to instant commit so the UI
// still responds. (Should not happen in practice; init() awaits params.)
currentComposition[idx] = newVal;
displayPreviewComp[idx] = newVal;
return;
}
if (currentComposition[idx] === newVal) return; // no-op
// Snapshot pre-toggle curve at fixed 64-point log-spaced times. Same time
// grid is reused throughout the blend so per-frame work is just a lerp.
const times = logSpacedTimes(64);
const { means: fromMeans, variances: fromVars } = predictStrengthCurve(
currentComposition, times, strengthParams
);
const fromStds = computeStds(fromVars, strengthParams);
// Commit the new MS value before kicking off the visual blend so the GP
// calls during the transition use the post-toggle composition.
currentComposition[idx] = newVal;
displayPreviewComp[idx] = newVal;
_msCurveTransition = {
startTime: performance.now(),
duration: MS_TRANSITION_MS,
times,
fromMeans,
fromStds,
};
startAnimLoop();
}
// --- Click-to-edit value handlers (regular sliders only) ---
// The plan: focus selects all; Enter commits; Escape reverts; blur commits.
// On commit, parse the displayed (unit-aware) number, divide by the column's
// display factor, clamp to [b.min, b.max], and animate to the new state.
function attachValueEditHandlers(inputEl, idx, col, b) {
function commit() {
const raw = inputEl.value.trim();
const parsed = parseFloat(raw);
if (!Number.isFinite(parsed)) {
// Non-numeric → revert displayed text
inputEl.value = displayCompValue(col, currentComposition[idx]).toFixed(1);
return;
}
// Convert displayed value back to internal units, then clamp.
// For Temperature this also handles the °F → °C offset.
const internal = internalCompValue(col, parsed);
const clamped = Math.max(b.min, Math.min(b.max, internal));
// Build target from the most recent intended end state to avoid landing
// mid-animation values for sliders that are currently in flight.
const base = animationId !== null && _lastAnimTarget !== null
? [..._lastAnimTarget]
: [...currentComposition];
base[idx] = clamped;
animateToComposition(base);
// Refresh display in case clamping or rounding changed it (the animation
// will overwrite, but we want the input to read correctly during the lerp
// since `setValueDisplay` skips focused elements — and this element is
// still focused if commit was triggered by Enter).
inputEl.value = displayCompValue(col, clamped).toFixed(1);
}
inputEl.addEventListener("focus", () => inputEl.select());
inputEl.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
commit();
inputEl.blur();
} else if (e.key === "Escape") {
e.preventDefault();
// Revert without committing
inputEl.value = displayCompValue(col, currentComposition[idx]).toFixed(1);
inputEl.blur();
}
});
inputEl.addEventListener("blur", () => {
// Blur commits the edit (same as Enter), but only if the value was changed.
// If the value matches the current displayed state, do nothing.
const expected = displayCompValue(col, currentComposition[idx]).toFixed(1);
if (inputEl.value.trim() !== expected) commit();
});
}
// --- Set sliders from a composition (instant) ---
function setComposition(comp) {
currentComposition = [...comp];
displayPreviewComp = [...comp];
syncSliderDOM(comp);
// Update Material Source toggle (val-${msIdx} is a <span>, not an <input>,
// so we write textContent directly. syncSliderDOM only iterates range
// sliders, which doesn't include Material Source.)
const msIdx = COL_MS;
if (msIdx >= 0) {
const msVal = Math.round(comp[msIdx]);
const msEl = document.getElementById(`val-${msIdx}`);
if (msEl) msEl.textContent = msVal === 0 ? "Source A" : "Source B";
const buttons = document.querySelectorAll(".toggle-btn");
if (buttons.length >= 2) {
buttons[0].className = msVal === 0 ? "toggle-btn active" : "toggle-btn";
buttons[1].className = msVal === 1 ? "toggle-btn active" : "toggle-btn";
}
}
update();
}
// --- Update everything ---
function update() {
updateReadouts();
drawStrengthCurve();
drawScatter();
// Mix insight updates are triggered separately with delay (see animateToComposition)
}
// Delayed mix insight update — called after strength curve animation settles
function scheduleInsightUpdate() {
setTimeout(updateMixInsight, 300); // delay after curve settles for sequenced feel
}
let _currentInsightIdx = null; // track which mix is currently displayed
const _placeholderHTML = '<span class="mix-insight-placeholder">Click a data point to see mix analysis.</span>';
function updateMixInsight() {
const textEl = document.getElementById("mix-insight-text");
const bodyEl = document.querySelector(".mix-insight-body");
const paretoPill = document.getElementById("pareto-pill");
if (!mixAnalyses) return;
const nearIdx = findNearestCompositionIdx(currentComposition);
// Update Pareto pill independently (instant, no content swap needed)
if (nearIdx !== null) {
const paretoTag = getParetoTag(nearIdx);
if (paretoTag) {
paretoPill.textContent = paretoTag;
paretoPill.classList.add("visible");
} else {
paretoPill.classList.remove("visible");
}
} else {
paretoPill.classList.remove("visible");
}
if (nearIdx !== null && mixAnalyses[String(nearIdx)]) {
if (_currentInsightIdx === nearIdx) return;
animateContentSwap(bodyEl, textEl, buildInsightHTML(nearIdx));
_currentInsightIdx = nearIdx;
} else if (nearIdx !== null) {
if (_currentInsightIdx !== nearIdx) {
animateContentSwap(bodyEl, textEl, '<span class="mix-insight-placeholder">Mix insight not available for this composition.</span>');
_currentInsightIdx = nearIdx;
}
} else {
if (_currentInsightIdx !== null) {
animateContentSwap(bodyEl, textEl, _placeholderHTML);
_currentInsightIdx = null;
}
}
}
function buildInsightHTML(idx) {
let desc = mixAnalyses[String(idx)];
desc = desc.replace(/\*\*(.+?)\*\*/g, (_, text) => `<strong>${text}</strong>`);
return desc;
}
// Dynamically compute Pareto label for the current scatter objectives
function getParetoTag(idx) {
if (!compositionsData) return null;
const gwpPreds = compositionsData.gwp_predictions;
const costPreds = compositionsData.cost_predictions;
const strDay = String(scatterDay);
const strPreds = compositionsData.strength_predictions[strDay];
if (!strPreds) return null;
const n = gwpPreds.length;
// Check if idx is Pareto-optimal for current x-axis vs strength
const xVals = scatterXAxis === "cost"
? costPreds.map(v => -v)
: gwpPreds.map(v => -v);
const yVals = strPreds;
// Is idx dominated by any other point?
const xi = xVals[idx], yi = yVals[idx];
for (let j = 0; j < n; j++) {
if (j === idx) continue;
if (xVals[j] <= xi && yVals[j] >= yi && (xVals[j] < xi || yVals[j] > yi)) {
return null; // dominated
}
}
return "Pareto-optimal";
}
function updateReadouts() {
const u = U();
// GWP — use fixed Temp=22°C since GWP is a material property, not temperature-dependent
const msIdx = COL_MS;
const tempIdx = COL_TEMP;
const ms = msIdx >= 0 ? Math.round(currentComposition[msIdx]) : 0;
const compForGWP = [...currentComposition];
if (tempIdx >= 0) compForGWP[tempIdx] = 22; // reference temperature
const gwp = predictGWP(compForGWP, gwpParams, ms);
// GWP model predicts -GWP (negated), so negate to get positive GWP
document.getElementById("gwp-value").textContent =
(Math.abs(gwp.mean) * u.gwpFactor).toFixed(1);
// Cost (with uncertainty)
const cost = predictCost(compForGWP, costParams);
const costMean = Math.abs(cost.mean) * u.costFactor;
const costStd = Math.sqrt(cost.variance) * u.costFactor;
document.getElementById("cost-value").textContent = costMean.toFixed(1);
document.getElementById("cost-uncertainty").textContent = `± ${costStd.toFixed(1)}`;
// W/B ratio
const cols = compositionsData.column_names;
const cement = currentComposition[cols.indexOf("Cement (kg/m3)")] || 0;
const flyAsh = currentComposition[cols.indexOf("Fly Ash (kg/m3)")] || 0;
const slag = currentComposition[cols.indexOf("Slag (kg/m3)")] || 0;
const water = currentComposition[cols.indexOf("Water (kg/m3)")] || 0;
const binder = cement + flyAsh + slag;
const wb = binder > 0 ? (water / binder).toFixed(3) : "–";
document.getElementById("wb-value").textContent = wb;
// TODO: Slump prediction — requires model/slump.json with trained GP params.
// Once available: load slumpParams in init(), add predictSlump to gp.mjs,
// then: const slump = predictSlump(compForGWP, slumpParams);
// Display in "slump-value" element with unit conversion (mm ↔ in).
}
// --- HiDPI Canvas Helpers ---
// Cache canvas dimensions to avoid forced reflow on every frame
const _canvasCache = new WeakMap();
let _resizeObserver = null;
function setupHiDPICanvas(canvas) {
const dpr = window.devicePixelRatio || 1;
// Use cached dimensions if available (avoids forced reflow from getBoundingClientRect)
let rect = _canvasCache.get(canvas);
if (!rect) {
rect = canvas.getBoundingClientRect();
_canvasCache.set(canvas, { width: rect.width, height: rect.height });
rect = _canvasCache.get(canvas);
// Observe resize to invalidate cache and trigger redraw
if (!_resizeObserver) {
let resizeRAF = null;
_resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
_canvasCache.delete(entry.target);
}
// Debounce redraw to next animation frame for snappy resize
if (!resizeRAF) {
resizeRAF = requestAnimationFrame(() => {
resizeRAF = null;
update();
});
}
});
}
_resizeObserver.observe(canvas);
}
canvas.width = rect.width * dpr;
canvas.height = rect.height * dpr;
const ctx = canvas.getContext("2d");
ctx.scale(dpr, dpr);
return { ctx, W: rect.width, H: rect.height };
}
/**
* Generate nice round tick values for an axis range.
*/
function niceTickValues(min, max, approxCount) {
const range = max - min;
const rawStep = range / approxCount;
// Round step to 1, 2, or 5 × 10^n
const mag = Math.pow(10, Math.floor(Math.log10(rawStep)));
let step;
if (rawStep / mag < 1.5) step = mag;
else if (rawStep / mag < 3.5) step = 2 * mag;
else if (rawStep / mag < 7.5) step = 5 * mag;
else step = 10 * mag;
const ticks = [];
const start = Math.ceil(min / step) * step;
for (let v = start; v <= max; v += step) {
ticks.push(Math.round(v * 1e6) / 1e6); // avoid floating point drift
}
return ticks;
}
/**
* Compute Pareto non-dominated mask for minimizing x and maximizing y.
* A point is Pareto-optimal if no other point has both lower x AND higher y.
*/
function computeParetoMask(xVals, yVals) {
const n = xVals.length;
const mask = new Array(n).fill(true);
for (let i = 0; i < n; i++) {
if (!mask[i]) continue;
for (let j = 0; j < n; j++) {
if (i === j || !mask[j]) continue;
// j dominates i if j has lower-or-equal x AND higher-or-equal y (with at least one strict)
if (xVals[j] <= xVals[i] && yVals[j] >= yVals[i] &&
(xVals[j] < xVals[i] || yVals[j] > yVals[i])) {
mask[i] = false;
break;
}
}
}
return mask;
}
// --- Find nearest composition index in the dataset ---
function findNearestCompositionIdx(comp) {
if (!compositionsData || !compositionsData.compositions) return null;
const compositions = compositionsData.compositions;
let bestDist = Infinity;
let bestIdx = null;
for (let i = 0; i < compositions.length; i++) {
let dist = 0;
for (let j = 0; j < comp.length; j++) {
const d = comp[j] - compositions[i][j];
dist += d * d;
}
if (dist < bestDist) {
bestDist = dist;
bestIdx = i;
}
}
// Only match if essentially exact (squared distance < 1e-6)
return bestDist < 1e-6 ? bestIdx : null;
}
// --- Extrapolation Warning ---
// Shows a warning when the current composition is far from any training data point.
// Uses normalized Euclidean distance (each dimension / its range) to the nearest point.
//
// The threshold is defined as a per-dimension average normalized difference.
// With EXTRAPOLATION_PER_DIM_THRESHOLD = 0.13, the warning fires when the nearest
// training point differs by ~13% of each dimension's range on average. The actual
// L2 threshold scales as: per_dim_threshold * sqrt(n_active_dims), adapting
// automatically to datasets with different dimensionality.
const EXTRAPOLATION_PER_DIM_THRESHOLD = 0.13;
function getExtrapolationThreshold() {
if (!compositionsData) return Infinity;
const bounds = compositionsData.slider_bounds;
const colNames = compositionsData.column_names;
let nActiveDims = 0;
for (const col of colNames) {
const b = bounds[col];
if (b.max - b.min > 0) nActiveDims++;
}
return EXTRAPOLATION_PER_DIM_THRESHOLD * Math.sqrt(nActiveDims);
}
function checkExtrapolationWarning() {
const warningEl = document.getElementById("extrapolation-warning");
if (!warningEl || !compositionsData) return;
const bounds = compositionsData.slider_bounds;
const colNames = compositionsData.column_names;
const compositions = compositionsData.compositions;
const threshold = getExtrapolationThreshold();
// Compute normalized distance to nearest training point
let minDist = Infinity;
for (let i = 0; i < compositions.length; i++) {
let dist = 0;
for (let j = 0; j < currentComposition.length; j++) {
const col = colNames[j];
const b = bounds[col];
const range = b.max - b.min;
if (range === 0) continue;
const diff = (currentComposition[j] - compositions[i][j]) / range;
dist += diff * diff;
}
dist = Math.sqrt(dist);
if (dist < minDist) minDist = dist;
}
if (minDist > threshold) {
warningEl.classList.add("visible");
} else {
warningEl.classList.remove("visible");
}
}
// Hide warning during animated transitions (scatter click)
function hideExtrapolationWarning() {
const warningEl = document.getElementById("extrapolation-warning");
if (warningEl) warningEl.classList.remove("visible");
}
// --- Strength Curve Canvas ---
function drawStrengthCurve() {
const canvas = document.getElementById("curve-canvas");
const { ctx, W, H } = setupHiDPICanvas(canvas);
const pad = { top: 20, right: 20, bottom: 40, left: 70 };
// Compute predictions (use log-spaced time points for smooth early-time resolution).
// Two paths:
// (1) Material Source transition active — blend cached pre-toggle curve
// with freshly computed post-toggle curve over MS_TRANSITION_MS.
// (2) Otherwise — standard predict at current composition.
let times, means, stds, nPts;
if (_msCurveTransition !== null) {
const elapsed = performance.now() - _msCurveTransition.startTime;
const t = Math.min(elapsed / _msCurveTransition.duration, 1);
if (t >= 1) {
_msCurveTransition = null; // fall through to standard path
} else {
const ease = easeInOutCubic(t);
times = _msCurveTransition.times;
nPts = times.length;
const { means: toMeans, variances: toVars } = predictStrengthCurve(
currentComposition, times, strengthParams
);
const toStds = computeStds(toVars, strengthParams);
const { fromMeans, fromStds } = _msCurveTransition;
means = fromMeans.map((m, i) => m + (toMeans[i] - m) * ease);
stds = fromStds.map((s, i) => s + (toStds[i] - s) * ease);
}
}
if (means === undefined) {
const isAnimating = animationId !== null;
const isInteracting = _sliderActive || isAnimating;
nPts = isInteracting ? 32 : 64;
times = logSpacedTimes(nPts);
const { means: m, variances } = predictStrengthCurve(
currentComposition, times, strengthParams
);
means = m;
stds = computeStds(variances, strengthParams);
}