-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGLM_3D_visual.html
More file actions
1269 lines (1158 loc) · 46.9 KB
/
Copy pathGLM_3D_visual.html
File metadata and controls
1269 lines (1158 loc) · 46.9 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
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="GLM 3D-Visualisierung: Regressionsebenen, Praediktoren und Outcomeverteilungen dreidimensional explorieren.">
<meta name="keywords" content="GLM, 3D Visualisierung, Regression, Praediktoren, Statistik, Three.js">
<meta property="og:title" content="GLM 3D Visualisierung">
<meta property="og:description" content="GLM 3D-Visualisierung: Regressionsebenen, Praediktoren und Outcomeverteilungen dreidimensional explorieren.">
<meta property="og:type" content="website">
<meta property="og:url" content="https://www.bayes-thinking-lab.uni-osnabrueck.de/GLM_3D_visual.html">
<meta property="og:site_name" content="Bayes Thinking Lab">
<link rel="canonical" href="https://www.bayes-thinking-lab.uni-osnabrueck.de/GLM_3D_visual.html">
<title>GLM 3D Visualisierung</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=DM+Mono:wght@300;400;500&family=DM+Sans:wght@300;400;600&family=Fraunces:ital,wght@0,300;0,600;1,300&display=swap');
html{font-size:18px}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--a6: #E3846A;
--bg: #0d0f14;
--surface: #13161e;
--floatbox-bg: rgba(13,15,20,0.75);
--floatbox-bg-strong: rgba(13,15,20,0.82);
--border: #1f2433;
--accent1: #4fc3f7;
--accent2: #f06292;
--accent3: #81c784;
--accent4: #ffb74d;
--text: #e8eaf0;
--muted: #6b7280;
--renderer-bg: #0d0f14;
--ink2: #6b7280;
--hdr-ink: #e8e2d8;
--hdr-ink2: #9a9080;
--hdr-paper: #171b25;
--hdr-panel: #1e2230;
--hdr-border: #333a4a;
}
:root.light {
--a6: #D44E28;
--bg: #f4f6fa;
--surface: #ffffff;
--floatbox-bg: rgba(244,246,250,0.85);
--floatbox-bg-strong: rgba(244,246,250,0.9);
--border: #d1d5db;
--accent1: #0284c7;
--accent2: #e11d48;
--accent3: #16a34a;
--accent4: #d97706;
--text: #111827;
--muted: #6b7280;
--renderer-bg: #f0f2f8;
--ink2: #6b7280;
--hdr-ink: #18130e;
--hdr-ink2: #5a4f42;
--hdr-paper: #faf6ee;
--hdr-panel: #ece5d5;
--hdr-border: #c5bba8;
}
body {
background: var(--bg);
color: var(--text);
font-family: 'DM Sans', sans-serif;
height: 100vh;
overflow: hidden;
display: flex;
flex-direction: column;
}
header {
padding: .5rem 1.1rem;
border-bottom: 1.5px solid var(--hdr-border);
background: var(--hdr-paper);
display: flex;
align-items: center;
gap: .5rem;
justify-content: space-between;
flex-shrink: 0;
line-height: normal;
}
#shell{flex:1;overflow-y:auto;min-height:0}
.header-titles { display: flex; flex-direction: column; gap: 0; }
header h1 {
font-family: 'Fraunces', Georgia, serif;
font-size: 1.55rem;
font-weight: 300;
letter-spacing: -0.02em;
line-height: 1.2;
color: var(--hdr-ink);
}
header h1 em {
font-style: italic;
color: var(--a6);
}
header .sub {
font-family: 'DM Mono', monospace;
font-size: 0.75rem;
color: var(--hdr-ink2);
margin-top: 0.2rem;
letter-spacing: 0.03em;
}
header .author {
font-family: 'DM Mono', monospace;
font-size: 0.75rem;
color: var(--hdr-ink2);
opacity: 0.5;
margin-top: 0.1rem;
}
.controls-bar {
display: flex;
gap: 10px;
padding: 16px 40px;
border-bottom: 1px solid var(--border);
align-items: center;
flex-wrap: wrap;
}
.tab-group { display: flex; gap: 4px; }
.tab {
padding: 7px 18px;
border-radius: 6px;
border: 1px solid var(--border);
background: transparent;
color: var(--muted);
font-family: 'DM Mono', monospace;
font-size: 0.78rem;
cursor: pointer;
transition: all 0.2s;
}
.tab.active { background: var(--accent1); color: #0d0f14; border-color: var(--accent1); font-weight: 500; }
.tab:hover:not(.active) { color: var(--text); border-color: #374151; }
.sep { width: 1px; height: 28px; background: var(--border); margin: 0 6px; }
.param-group {
display: flex;
align-items: center;
gap: 10px;
font-size: 0.8rem;
color: var(--muted);
}
.param-group label { font-family: 'DM Mono', monospace; font-size: 0.75rem; }
.param-group input[type=range] {
accent-color: var(--accent2);
width: 90px;
cursor: pointer;
}
.param-val {
font-family: 'DM Mono', monospace;
color: var(--accent2);
font-size: 0.8rem;
min-width: 30px;
}
.viz-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0;
height: calc(100vh - 130px);
}
.panel {
position: relative;
border-right: 1px solid var(--border);
overflow: hidden;
}
.panel:last-child { border-right: none; }
.panel-label {
position: absolute;
top: 14px; left: 18px;
z-index: 10;
font-family: 'DM Mono', monospace;
font-size: 0.75rem;
color: var(--muted);
letter-spacing: 0.08em;
text-transform: uppercase;
background: var(--floatbox-bg);
padding: 4px 10px;
border-radius: 4px;
border: 1px solid var(--border);
pointer-events: none;
}
.panel-label span {
color: var(--accent1);
margin-right: 6px;
}
.hint {
position: absolute;
bottom: 12px; left: 50%;
transform: translateX(-50%);
font-size: 0.75rem;
color: var(--muted);
pointer-events: none;
white-space: nowrap;
}
canvas { display: block; }
.legend {
position: absolute;
bottom: 30px; right: 16px;
display: flex;
flex-direction: column;
gap: 5px;
font-size: 0.75rem;
color: var(--muted);
font-family: 'DM Mono', monospace;
background: var(--floatbox-bg);
padding: 8px 12px;
border-radius: 6px;
border: 1px solid var(--border);
pointer-events: none;
}
.legend-row { display: flex; align-items: center; gap: 7px; }
.legend-dot { width: 10px; height: 10px; border-radius: 2px; }
/* Info box — opposite corner to legend */
.infobox {
position: absolute;
bottom: 30px; left: 16px;
max-width: 230px;
font-size: 0.75rem;
color: var(--muted);
font-family: 'DM Mono', monospace;
background: var(--floatbox-bg-strong);
padding: 10px 13px;
border-radius: 6px;
border: 1px solid var(--border);
pointer-events: none;
line-height: 1.55;
}
.infobox .ib-title {
font-size: 0.75rem;
color: var(--accent1);
font-weight: 500;
letter-spacing: 0.06em;
margin-bottom: 6px;
text-transform: uppercase;
}
.infobox .ib-row {
display: flex; gap: 6px; margin-bottom: 3px;
}
.ib-label { color: var(--accent3); min-width: 58px; }
.ib-val { color: var(--text); }
.infobox .ib-sep {
border: none; border-top: 1px solid var(--border);
margin: 6px 0;
}
.infobox .ib-note {
color: #4b5563; font-size: 0.75rem; line-height: 1.4;
}
/* Data-points toggle button */
.btn-toggle {
padding: 7px 14px;
border-radius: 6px;
border: 1px solid var(--border);
background: transparent;
color: var(--muted);
font-family: 'DM Mono', monospace;
font-size: 0.75rem;
cursor: pointer;
transition: all 0.2s;
display: flex; align-items: center; gap: 6px;
}
.btn-toggle.on {
background: rgba(129,199,132,0.15);
color: var(--accent3);
border-color: var(--accent3);
}
.btn-toggle:hover:not(.on) { color: var(--text); border-color: #374151; }
.btn-toggle .dot {
width: 7px; height: 7px; border-radius: 50%;
background: currentColor;
}
/* Theme toggle */
.btn-theme {
padding: .22rem .6rem;
border: 1.5px solid var(--hdr-border);
background: var(--hdr-panel);
color: var(--hdr-ink2);
font-family: 'DM Mono', monospace;
font-size: 0.75rem;
cursor: pointer;
transition: all 0.15s;
display: flex; align-items: center; gap: 6px;
}
.btn-theme:hover { color: var(--accent1); border-color: var(--accent1); }
.light .btn-theme { color: var(--hdr-ink2); }
em{font-style:italic;color:var(--a6)}
/* ── FLOATING HELP PANEL ── */
#help-float{display:none;position:fixed;right:1.5rem;top:50%;transform:translateY(-50%);
width:300px;z-index:600;background:var(--surface);border:1.5px solid var(--border);
box-shadow:4px 4px 0 rgba(0,0,0,.35)}
#help-float.open{display:block}
.hp-head{display:flex;justify-content:space-between;align-items:center;
padding:.5rem .85rem;border-bottom:1px solid var(--border)}
.hp-title{font-family:'DM Mono',monospace;font-size:.58rem;letter-spacing:.08em;
text-transform:uppercase;color:var(--muted)}
.hp-close{font-family:'DM Mono',monospace;font-size:.85rem;background:none;border:none;
cursor:pointer;color:var(--muted);padding:0 .2rem;line-height:1}
.hp-close:hover{color:var(--text)}
.hp-body{padding:.8rem .85rem;font-family:'DM Mono',monospace;font-size:.67rem;
line-height:1.8;color:var(--muted);max-height:75vh;overflow-y:auto}
.hp-sect{font-size:.52rem;letter-spacing:.1em;text-transform:uppercase;
margin-top:.85rem;margin-bottom:.28rem;border-bottom:1px solid var(--border);
padding-bottom:.18rem;color:var(--muted)}
.hp-sect:first-child{margin-top:0}
.hp-body strong{color:var(--text)}
.hp-body em{color:var(--accent1);font-style:normal}
.hp-seq{padding-left:.05rem}
.hp-seq li{list-style:none;padding:.08rem 0}
.hp-seq li::before{color:var(--accent1);margin-right:.4rem;font-weight:600}
.hp-seq li:nth-child(1)::before{content:'①'}
.hp-seq li:nth-child(2)::before{content:'②'}
.hp-seq li:nth-child(3)::before{content:'③'}
.hp-seq li:nth-child(4)::before{content:'④'}
.hp-seq li:nth-child(5)::before{content:'⑤'}
</style>
</head>
<body>
<header>
<div class="header-titles">
<h1>GLM · <em>3D Distributions</em></h1>
<p class="sub">Generalisierte Lineare Modelle · 3D-Posterior-Landschaft · Interaktiv · Drehen · Zoom</p>
<p class="author">© Dr. Rainer Düsing · Interactive Tools by Claude</p>
</div>
<div style="display:flex;gap:.4rem;align-items:flex-start;flex-shrink:0">
<button class="btn-theme" onclick="window.open('index_de.html','_self')" style="border-color:var(--a6);color:var(--a6)">← Übersicht</button>
<button class="btn-theme" onclick="window.open('GLMM_interactive.html','_blank')" style="border-color:var(--a6);color:var(--a6)">Weiter → GLMM interaktiv</button>
<button class="btn-theme" onclick="toggleHelpFloat()" style="border-color:#e8614a;color:#e8614a">ℹ Hilfe</button>
<button class="btn-theme" id="btn-theme" onclick="toggleTheme()">☀ Light</button>
</div>
</header>
<div id="shell">
<div class="controls-bar">
<div class="tab-group">
<button class="tab active" onclick="setModel('normal', this)">Normal (OLS)</button>
<button class="tab" onclick="setModel('poisson', this)">Poisson</button>
<button class="tab" onclick="setModel('negbinom', this)">Neg. Binomial</button>
<button class="tab" onclick="setModel('gamma', this)">Gamma</button>
<button class="tab" onclick="setModel('binomial', this)">Binomial</button>
<button class="tab" onclick="setModel('logistic', this)">Logistisch</button>
</div>
<div class="sep"></div>
<div class="param-group">
<label>β₀</label>
<input type="range" id="b0" min="-3" max="5" step="0.1" value="0.5" oninput="updateParams()">
<span class="param-val" id="b0val">0.5</span>
</div>
<div class="param-group">
<label>β₁</label>
<input type="range" id="b1" min="-2" max="2" step="0.05" value="0.4" oninput="updateParams()">
<span class="param-val" id="b1val">0.4</span>
</div>
<div class="param-group" id="sigma-group" style="display:flex">
<div class="sep"></div>
<label>σ (Streuung)</label>
<input type="range" id="sigma" min="0.2" max="3.0" step="0.1" value="0.8" oninput="updateParams()">
<span class="param-val" id="sigmaval">0.8</span>
</div>
<div class="param-group" id="shape-group" style="display:none">
<div class="sep"></div>
<label>κ (Shape)</label>
<input type="range" id="shape" min="0.5" max="8.0" step="0.25" value="2.0" oninput="updateParams()">
<span class="param-val" id="shapeval">2.0</span>
</div>
<div class="param-group" id="ntrials-group" style="display:none">
<div class="sep"></div>
<label>n (Trials)</label>
<input type="range" id="ntrials" min="1" max="20" step="1" value="10" oninput="updateParams()">
<span class="param-val" id="ntrialsval">10</span>
</div>
<div class="param-group" id="nbr-group" style="display:none">
<div class="sep"></div>
<label>r (Dispersion)</label>
<input type="range" id="nbr" min="0.25" max="10" step="0.25" value="2" oninput="updateParams()">
<span class="param-val" id="nbrval">2.00</span>
</div>
<div class="sep"></div>
<button class="btn-toggle" id="btn-data" onclick="toggleData()">
<span class="dot"></span> Datenpunkte
</button>
<div class="param-group" id="nsamples-group" style="display:none">
<label>N</label>
<input type="range" id="nsamples" min="10" max="200" step="10" value="30" oninput="updateParams()">
<span class="param-val" id="nsamplesval">30</span>
</div>
</div>
<div class="viz-grid">
<div class="panel" id="panel1">
<div class="panel-label"><span>01</span> Balken-Histogramm</div>
<div class="infobox" id="infobox1"></div>
<div class="legend" id="legend1"></div>
<div class="hint">🖱 Drehen / Zoom</div>
</div>
<div class="panel" id="panel2">
<div class="panel-label"><span>02</span> Kurven / Flächen</div>
<div class="infobox" id="infobox2"></div>
<div class="legend" id="legend2"></div>
<div class="hint">🖱 Drehen / Zoom</div>
</div>
</div>
</div><!-- /shell -->
<script>
// ─── Math helpers ────────────────────────────────────────────────────────────
function poissonPMF(k, lambda) {
if (lambda <= 0) return k === 0 ? 1 : 0;
let logP = k * Math.log(lambda) - lambda;
for (let i = 2; i <= k; i++) logP -= Math.log(i);
return Math.exp(logP);
}
// Negative Binomial PMF: NB(r, p) parametrised by mean μ
// p_success = r/(r+μ), so Var(Y) = μ + μ²/r (→ Poisson as r→∞)
function negbinomPMF(k, mu, r) {
if (mu <= 0 || r <= 0) return k === 0 ? 1 : 0;
// log P(Y=k) = lgamma(k+r) - lgamma(r) - lgamma(k+1)
// + r*log(r/(r+mu)) + k*log(mu/(r+mu))
const pS = r / (r + mu);
const logP = logGammaFn(k + r) - logGammaFn(r) - logGammaFn(k + 1)
+ r * Math.log(pS) + k * Math.log(1 - pS);
return Math.exp(logP);
}
function normalPDF(x, mu, sigma) {
return Math.exp(-0.5 * ((x - mu) / sigma) ** 2) / (sigma * Math.sqrt(2 * Math.PI));
}
function logisticP(eta) { return 1 / (1 + Math.exp(-eta)); }
// Binomial PMF: B(n, p) — n trials, success prob p
function binomialPMF(k, n, p) {
if (k < 0 || k > n) return 0;
// log C(n,k) + k*log(p) + (n-k)*log(1-p)
let logC = 0;
for (let i = 0; i < k; i++) logC += Math.log(n - i) - Math.log(i + 1);
const lp = p > 0 ? Math.log(p) : -Infinity;
const l1p = (1 - p) > 0 ? Math.log(1 - p) : -Infinity;
return Math.exp(logC + k * lp + (n - k) * l1p);
}
// Gamma PDF: shape=k, scale=mu/k → mean=mu, var=mu²/k
function gammaPDF(x, mu, kShape) {
if (x <= 0 || mu <= 0 || kShape <= 0) return 0;
const scale = mu / kShape;
// Use log-space for numerical stability
return Math.exp((kShape - 1) * Math.log(x) - x / scale - kShape * Math.log(scale) - _logGammaCache(kShape));
}
// Cache log-gamma result — kShape only changes on slider release, not per-point
let _lgCache = { z: -1, val: 0 };
function _logGammaCache(z) {
if (z === _lgCache.z) return _lgCache.val;
_lgCache = { z, val: logGammaFn(z) };
return _lgCache.val;
}
// Lanczos approximation for log-gamma
function logGammaFn(z) {
const g = 7;
const c = [0.99999999999980993,676.5203681218851,-1259.1392167224028,
771.32342877765313,-176.61502916214059,12.507343278686905,
-0.13857109526572012,9.9843695780195716e-6,1.5056327351493116e-7];
if (z < 0.5) return Math.log(Math.PI / Math.sin(Math.PI * z)) - logGammaFn(1 - z);
z -= 1;
let x = c[0];
for (let i = 1; i < g + 2; i++) x += c[i] / (z + i);
const t = z + g + 0.5;
return 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(x);
}
// ─── Coordinate convention ───────────────────────────────────────────────────
// X-axis (Three X) = Prädiktor x
// Z-axis (Three Z) = Outcome y/k (negative Z = higher outcome values)
// Y-axis (Three Y) = Probability / density (up)
//
// Regression curve μ(x) lives on the FLOOR (Y=0) at position (x, 0, -mu*zScale)
// Distributions rise upward (Y > 0) from that floor point.
// ─── State ────────────────────────────────────────────────────────────────────
let model = 'normal';
let beta0 = 0.5, beta1 = 0.4, sigma = 0.8, kShape = 2.0, nTrials = 10, nSamples = 30, nbR = 2.0;
let showData = false;
let renderers = [], scenes = [], cameras = [];
// Per-model settings — each model remembers its own β₀, β₁ and extras independently
const modelSettings = {
normal: { beta0: 0.5, beta1: 0.4, sigma: 0.8 },
poisson: { beta0: 0.5, beta1: 0.4 },
negbinom: { beta0: 0.5, beta1: 0.4, nbR: 2.0 },
gamma: { beta0: 0.5, beta1: 0.4, kShape: 2.0 },
binomial: { beta0: 0.0, beta1: 0.8, nTrials: 10 },
logistic: { beta0: 0.0, beta1: 0.8 },
};
// ─── Model info definitions ───────────────────────────────────────────────────
const MODEL_INFO = {
normal: {
name: 'Normal (OLS)',
family: 'Gaussisch',
link: 'Identität',
linkFn: 'μ = η',
varFn: 'Var(Y) = σ²',
eta: 'η = β₀ + β₁x',
note: 'Konstante Varianz. Residuen ∼ N(0, σ²).',
},
poisson: {
name: 'Poisson',
family: 'Poisson',
link: 'Log',
linkFn: 'μ = exp(η)',
varFn: 'Var(Y) = μ',
eta: 'η = β₀ + β₁x',
note: 'Für Zähldaten (≥ 0). Varianz wächst mit μ.',
},
negbinom: {
name: 'Neg. Binomial',
family: 'Neg. Binomial',
link: 'Log',
linkFn: 'μ = exp(η)',
varFn: 'Var(Y) = μ + μ²/r',
eta: 'η = β₀ + β₁x',
note: 'Überdispergierte Zähldaten. r → ∞ = Poisson. Kleines r = starke Überdispersion.',
},
gamma: {
name: 'Gamma',
family: 'Gamma',
link: 'Log',
linkFn: 'μ = exp(η)',
varFn: 'Var(Y) = μ²/κ',
eta: 'η = β₀ + β₁x',
note: 'Positive stetige Werte. Rel. Varianz konstant.',
},
binomial: {
name: 'Binomial',
family: 'Binomial',
link: 'Logit',
linkFn: 'p = 1/(1+e⁻ᶯ)',
varFn: 'Var(Y) = np(1−p)',
eta: 'η = β₀ + β₁x',
note: 'Outcome = k/n ∈ [0,1]. k Erfolge aus n Versuchen.',
},
logistic: {
name: 'Logistisch',
family: 'Binomial (n=1)',
link: 'Logit',
linkFn: 'p = 1/(1+e⁻ᶯ)',
varFn: 'Var(Y) = p(1−p)',
eta: 'η = β₀ + β₁x',
note: 'Binär: Y ∈ {0,1}. Spezialfall Binomial.',
},
};
// ─── Simulated data points ────────────────────────────────────────────────────
// Fixed seed-like RNG so points don't jump on every rebuild
function seededRand(seed) {
let s = seed;
return () => { s = (s * 16807 + 0) % 2147483647; return (s - 1) / 2147483646; };
}
function generateDataPoints() {
const rng = seededRand(42);
const randn = () => {
const u = rng(), v = rng();
return Math.sqrt(-2 * Math.log(u + 1e-10)) * Math.cos(2 * Math.PI * v);
};
const points = [];
for (let i = 0; i < nSamples; i++) {
const xJitter = (rng() * 6) - 3; // uniform in [-3, 3]
const mu = getMuAt(xJitter);
let y;
if (model === 'normal') {
y = mu + randn() * sigma;
} else if (model === 'poisson') {
y = Math.max(0, Math.round(mu + randn() * Math.sqrt(mu)));
} else if (model === 'negbinom') {
// Approximate: NB via Gamma-Poisson mixture
const nbVar = mu + mu * mu / nbR;
y = Math.max(0, Math.round(mu + randn() * Math.sqrt(nbVar)));
} else if (model === 'gamma') {
const sd = mu / Math.sqrt(kShape);
y = Math.max(0.01, mu + randn() * sd);
} else if (model === 'binomial') {
if (nTrials === 1) {
y = rng() < mu ? 1 : 0;
} else {
let successes = 0;
for (let t = 0; t < nTrials; t++) if (rng() < mu) successes++;
y = successes / nTrials; // proportion k/n ∈ [0,1]
}
} else if (model === 'logistic') {
y = rng() < mu ? 1 : 0;
}
points.push({ x: xJitter, y });
}
return points;
}
// getMu at any x (not just grid) — used for data generation
function getMuAt(x) {
const eta = beta0 + beta1 * x;
if (model === 'poisson' || model === 'gamma' || model === 'negbinom') return Math.exp(eta);
if (model === 'normal') return eta;
if (model === 'binomial') return logisticP(eta);
if (model === 'logistic') return logisticP(eta);
return eta;
}
// ─── Setup Three.js for both panels ──────────────────────────────────────────
function makeRenderer(panelId) {
const panel = document.getElementById(panelId);
const w = panel.clientWidth, h = panel.clientHeight;
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setSize(w, h);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setClearColor(0x0d0f14, 1);
panel.appendChild(renderer.domElement);
return renderer;
}
function makeCamera(w, h) {
const cam = new THREE.PerspectiveCamera(45, w / h, 0.01, 1000);
cam.position.set(6, 5, 8);
cam.lookAt(0, 0, 0);
return cam;
}
// ─── Orbit Controls ───────────────────────────────────────────────────────────
function addOrbitControls(camera, domEl) {
let isDragging = false, isRightDrag = false;
let lastX = 0, lastY = 0;
let theta = 0.55, phi = 0.85, radius = 13;
let targetX = 0, targetY = 1;
function updateCam() {
camera.position.x = targetX + radius * Math.sin(phi) * Math.sin(theta);
camera.position.y = targetY + radius * Math.cos(phi);
camera.position.z = radius * Math.sin(phi) * Math.cos(theta);
camera.lookAt(targetX, targetY, 0);
}
updateCam();
domEl.addEventListener('mousedown', e => {
isDragging = true;
isRightDrag = e.button === 2;
lastX = e.clientX; lastY = e.clientY;
e.preventDefault();
});
domEl.addEventListener('contextmenu', e => e.preventDefault());
window.addEventListener('mouseup', () => isDragging = false);
window.addEventListener('mousemove', e => {
if (!isDragging) return;
const dx = e.clientX - lastX, dy = e.clientY - lastY;
lastX = e.clientX; lastY = e.clientY;
if (!isRightDrag) {
theta -= dx * 0.01;
phi = Math.max(0.1, Math.min(Math.PI - 0.1, phi + dy * 0.01));
} else {
targetX -= dx * 0.02;
targetY += dy * 0.02;
}
updateCam();
});
domEl.addEventListener('wheel', e => {
radius = Math.max(3, Math.min(30, radius + e.deltaY * 0.02));
updateCam();
e.preventDefault();
}, { passive: false });
}
// ─── Colors ───────────────────────────────────────────────────────────────────
// 9 perceptually distinct colors — one per x-value (−3 to +3, step 0.75)
// Chosen to avoid similar hues and remain readable on both dark and light bg
const BAR_COLORS_HEX = [
'#e05252', // x=−3.00 red
'#e8853a', // x=−2.25 orange
'#d4c23a', // x=−1.50 yellow
'#52b04a', // x=−0.75 green
'#3fc4c4', // x= 0.00 teal
'#4a90d9', // x=+0.75 blue
'#7b5ea7', // x=+1.50 purple
'#c45696', // x=+2.25 pink-magenta
'#a0785a', // x=+3.00 brown
];
function hexToInt(h) { return parseInt(h.replace('#',''), 16); }
const COLORS = {
bars: BAR_COLORS_HEX.map(hexToInt),
grid: 0x1f2433,
axis: 0x4b5563,
mu_line: 0xf06292,
mu_dot: 0xf06292,
};
let isLightMode = localStorage.getItem('btl-theme') === 'light';
function getThemeColors() {
return isLightMode
? { grid: 0xd1d5db, axis: 0x9ca3af, mu_line: 0xe11d48, mu_dot: 0xe11d48, rendererBg: 0xf0f2f8 }
: { grid: 0x1f2433, axis: 0x4b5563, mu_line: 0xf06292, mu_dot: 0xf06292, rendererBg: 0x0d0f14 };
}
// ─── Scales ───────────────────────────────────────────────────────────────────
const zScaleDefault = 0.42;
const zScaleLogistic = 3.0;
const zScaleBinomial = 0.38;
const pScale = 4.5;
function outcomeToZ(k) {
if (model === 'logistic' || model === 'binomial') return -k * zScaleLogistic;
return -k * zScaleDefault;
}
function probToY(p) { return p * pScale; }
function isContinuous() { return model === 'normal' || model === 'gamma'; }
function isBinary() { return model === 'logistic'; }
function isDiscrete() { return model === 'poisson' || model === 'negbinom' || model === 'binomial'; }
// ─── Dispose helper — frees GPU memory before removing objects ────────────────
function disposeObject(obj) {
if (obj.geometry) obj.geometry.dispose();
if (obj.material) {
if (Array.isArray(obj.material)) obj.material.forEach(m => m.dispose());
else obj.material.dispose();
}
}
function clearScene(scene) {
// Walk backwards so splice doesn't skip items
for (let i = scene.children.length - 1; i >= 0; i--) {
const obj = scene.children[i];
disposeObject(obj);
scene.remove(obj);
}
}
// ─── Debounced rebuild — prevents thrashing GPU on rapid slider moves ─────────
let _rebuildTimer = null;
function scheduleRebuild() {
if (_rebuildTimer) clearTimeout(_rebuildTimer);
_rebuildTimer = setTimeout(() => {
_rebuildTimer = null;
buildBars(scenes[0]);
buildCurves(scenes[1]);
}, 40); // ~25fps max rebuild rate, feels instant but won't pile up
}
function addGrid(scene) {
const tc = getThemeColors();
const isCompact = model === 'logistic' || model === 'binomial';
const zMax = isCompact ? 3.5 : 7;
const zStep = isCompact ? 0.5 : 1;
const axMat = new THREE.LineBasicMaterial({ color: tc.axis });
addLine(scene, [-5,0,0], [5,0,0], axMat);
addLine(scene, [0,0,0], [0,5,0], axMat);
addLine(scene, [0,0,0], [0,0,-zMax], axMat);
const gridMat = new THREE.LineBasicMaterial({ color: tc.grid, transparent: true, opacity: 0.6 });
for (let ix = -5; ix <= 5; ix++) addLine(scene, [ix,0,0], [ix,0,-zMax], gridMat);
for (let iz = 0; iz >= -zMax; iz -= zStep) addLine(scene, [-5,0,iz], [5,0,iz], gridMat);
}
function addLine(scene, a, b, mat) {
const geo = new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(...a), new THREE.Vector3(...b)]);
scene.add(new THREE.Line(geo, mat));
}
// Axis labels via sprites
function makeTextSprite(text, colorDark, colorLight) {
const color = isLightMode ? (colorLight || '#374151') : (colorDark || '#9ca3af');
const c = document.createElement('canvas'); c.width = 320; c.height = 72;
const ctx = c.getContext('2d');
ctx.fillStyle = color;
ctx.font = 'bold 38px monospace';
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillText(text, 160, 36);
const tex = new THREE.CanvasTexture(c);
const mat = new THREE.SpriteMaterial({ map: tex, transparent: true });
const sprite = new THREE.Sprite(mat);
sprite.scale.set(2.0, 0.45, 1);
return sprite;
}
// ─── Model computations ───────────────────────────────────────────────────────
function getXValues() {
const xs = [];
for (let x = -3; x <= 3; x += 0.75) xs.push(+x.toFixed(2));
return xs;
}
// Returns μ in outcome-space (used for placing regression curve on floor)
function getMu(x) {
const eta = beta0 + beta1 * x;
if (model === 'poisson' || model === 'gamma' || model === 'negbinom') return Math.exp(eta);
if (model === 'normal') return eta;
if (model === 'binomial') return logisticP(eta); // p = success probability
if (model === 'logistic') return logisticP(eta);
return eta;
}
// Returns distribution points {k, p} for the distribution at predictor value x
function getDistPoints(x) {
const mu = getMu(x);
const pts = [];
if (model === 'poisson') {
const kmax = Math.max(14, Math.ceil(mu * 2.5 + 6));
for (let k = 0; k <= kmax; k++) pts.push({ k, p: poissonPMF(k, mu) });
} else if (model === 'negbinom') {
// NB is more spread out — extend range by variance contribution μ²/r
const nbVar = mu + mu * mu / nbR;
const kmax = Math.max(20, Math.ceil(mu + 4 * Math.sqrt(nbVar) + 4));
for (let k = 0; k <= kmax; k++) {
const p = negbinomPMF(k, mu, nbR);
if (p > 0) pts.push({ k, p });
}
} else if (model === 'normal') {
for (let k = mu - 3.5 * sigma; k <= mu + 3.5 * sigma; k += sigma * 0.12)
pts.push({ k, p: normalPDF(k, mu, sigma) * sigma * 0.12 });
} else if (model === 'gamma') {
const sd = mu / Math.sqrt(kShape);
const kMax = mu + 4 * sd;
const N = 36;
const step = kMax / N;
for (let i = 1; i <= N; i++)
pts.push({ k: i * step, p: gammaPDF(i * step, mu, kShape) * step });
} else if (model === 'binomial') {
if (nTrials === 1) {
// n=1 is identical to logistic: only k/n = 0 or 1
pts.push({ k: 0, p: 1 - mu });
pts.push({ k: 1, p: mu });
} else {
// Outcome is proportion k/n ∈ [0,1] — each bar at k/n position
for (let k = 0; k <= nTrials; k++)
pts.push({ k: k / nTrials, p: binomialPMF(k, nTrials, mu) });
}
} else if (model === 'logistic') {
pts.push({ k: 0, p: 1 - mu });
pts.push({ k: 1, p: mu });
}
return pts;
}
// ─── Data points overlay ──────────────────────────────────────────────────────
function addDataPoints(scene) {
if (!showData) return;
const pts = generateDataPoints();
const geo = new THREE.SphereGeometry(0.055, 6, 6); // small
const mat = new THREE.MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.90 });
pts.forEach(({ x, y }) => {
const mesh = new THREE.Mesh(geo, mat);
mesh.position.set(x, 0.02, outcomeToZ(y));
scene.add(mesh);
});
}
// Helper: z label position depends on model
function zLabelZ() {
return (model === 'logistic' || model === 'binomial') ? -4.0 : -7.8;
}
// The key insight: μ(x) is drawn on the FLOOR (Y=0) as a curve in the X-Z plane.
// For each predictor x, μ(x) tells us the expected outcome → that's the Z position.
// The distributions then rise UPWARD (Y) from each (x, 0, outcomeToZ(k)) point.
function addRegressionFloorCurve(scene) {
const tc = getThemeColors();
const pts = [];
for (let x = -3; x <= 3.01; x += 0.08) {
const mu = getMu(x);
pts.push(new THREE.Vector3(x, 0.01, outcomeToZ(mu)));
}
const geo = new THREE.BufferGeometry().setFromPoints(pts);
scene.add(new THREE.Line(geo, new THREE.LineBasicMaterial({ color: tc.mu_line, linewidth: 3 })));
getXValues().forEach(x => {
const mu = getMu(x);
const dot = new THREE.Mesh(
new THREE.SphereGeometry(0.09, 10, 10),
new THREE.MeshBasicMaterial({ color: tc.mu_dot })
);
dot.position.set(x, 0.01, outcomeToZ(mu));
scene.add(dot);
});
}
// ─── Version 1: Bar Histograms ────────────────────────────────────────────────
function buildBars(scene) {
clearScene(scene);
addGrid(scene);
addRegressionFloorCurve(scene);
addDataPoints(scene);
const xs = getXValues();
xs.forEach((x, xi) => {
const pts = getDistPoints(x);
const color = COLORS.bars[xi % COLORS.bars.length];
// For continuous distributions (normal, gamma): use narrow bars as histogram approx
// For discrete (poisson, negbinom) and binary (logistic): use wider bars
const barWActual = isContinuous() ? 0.08 : 0.16;
pts.forEach(({ k, p }) => {
const h = probToY(p);
if (h < 0.008) return;
const zPos = outcomeToZ(k);
const geo = new THREE.BoxGeometry(barWActual, h, barWActual * 0.85);
const mat = new THREE.MeshPhongMaterial({
color,
transparent: true,
opacity: isContinuous() ? 0.65 : 0.78,
shininess: 50,
});
const mesh = new THREE.Mesh(geo, mat);
mesh.position.set(x, h / 2, zPos);
scene.add(mesh);
// Subtle wireframe edges
const wf = new THREE.LineSegments(
new THREE.EdgesGeometry(geo),
new THREE.LineBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.10 })
);
wf.position.copy(mesh.position);
scene.add(wf);
});
});
// Lights
scene.add(new THREE.AmbientLight(0xffffff, 0.55));
const dir = new THREE.DirectionalLight(0xffffff, 0.9);
dir.position.set(4, 9, 4); scene.add(dir);
const dir2 = new THREE.DirectionalLight(0x4fc3f7, 0.25);
dir2.position.set(-4, 3, -4); scene.add(dir2);
// Axis labels
const lx = makeTextSprite('x (Prädiktor)', '#4fc3f7', '#0284c7');
lx.position.set(5.8, 0.1, 0); scene.add(lx);
const ly = makeTextSprite('P(Y=k)', '#aaaaaa', '#6b7280');
ly.position.set(-0.5, 4.8, 0); scene.add(ly);
const lz = makeTextSprite('k (Outcome)', '#81c784', '#16a34a');
lz.position.set(0, 0.1, zLabelZ()); scene.add(lz);
updateInfobox(1);
updateLegend(1, xs);
}
// ─── Version 2: Curve Surfaces ────────────────────────────────────────────────
function buildCurves(scene) {
clearScene(scene);
addGrid(scene);
addRegressionFloorCurve(scene);
addDataPoints(scene);
const xs = getXValues();
xs.forEach((x, xi) => {
const pts = getDistPoints(x);
const color = new THREE.Color(COLORS.bars[xi % COLORS.bars.length]);
if (isContinuous()) {
const validPts = pts.filter(({ p }) => p > 0.002);
if (validPts.length < 2) return;
const curvePts = [
new THREE.Vector3(x, 0, outcomeToZ(validPts[0].k)),
...validPts.map(({ k, p }) => new THREE.Vector3(x, probToY(p), outcomeToZ(k))),
new THREE.Vector3(x, 0, outcomeToZ(validPts[validPts.length - 1].k)),
];
const lGeo = new THREE.BufferGeometry().setFromPoints(curvePts);
scene.add(new THREE.Line(lGeo, new THREE.LineBasicMaterial({ color, linewidth: 2 })));
const shapeVerts = [];
shapeVerts.push(new THREE.Vector3(x, 0, outcomeToZ(validPts[0].k)));
validPts.forEach(({ k, p }) => shapeVerts.push(new THREE.Vector3(x, probToY(p), outcomeToZ(k))));
shapeVerts.push(new THREE.Vector3(x, 0, outcomeToZ(validPts[validPts.length - 1].k)));
const positions = [];
for (let i = 1; i < shapeVerts.length - 1; i++) {
positions.push(...shapeVerts[0].toArray(), ...shapeVerts[i].toArray(), ...shapeVerts[i + 1].toArray());
}
const fillGeo = new THREE.BufferGeometry();
fillGeo.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
fillGeo.computeVertexNormals();
scene.add(new THREE.Mesh(fillGeo, new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.35, side: THREE.DoubleSide })));