-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGLMM_interactive.html
More file actions
1976 lines (1798 loc) · 99.1 KB
/
Copy pathGLMM_interactive.html
File metadata and controls
1976 lines (1798 loc) · 99.1 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" data-theme="dark">
<head>
<meta charset="UTF-8">
<script>(function(){var t=localStorage.getItem('btl-theme');if(t)document.documentElement.setAttribute('data-theme',t);if(t==='light')document.addEventListener('DOMContentLoaded',function(){['btn-theme','btn-th','btn-th-nav','themeBtn'].forEach(function(id){var b=document.getElementById(id);if(b)b.textContent='🌙 Dark';});});})()</script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Gemischte Modelle (LMM und GLMM) interaktiv: Fixed und Random Effects, Intraklassenkorrelation und hierarchische Datenstrukturen visualisieren.">
<meta name="keywords" content="GLMM, LMM, Mixed Models, Random Effects, Multilevel, Hierarchisch, ICC, Statistik">
<meta property="og:title" content="Mixed Models – Interaktiv (LMM and GLMM)">
<meta property="og:description" content="Gemischte Modelle (LMM und GLMM) interaktiv: Fixed und Random Effects, Intraklassenkorrelation und hierarchische Datenstrukturen visualisieren.">
<meta property="og:type" content="website">
<meta property="og:url" content="https://www.bayes-thinking-lab.uni-osnabrueck.de/GLMM_interactive.html">
<meta property="og:site_name" content="Bayes Thinking Lab">
<link rel="canonical" href="https://www.bayes-thinking-lab.uni-osnabrueck.de/GLMM_interactive.html">
<title>Mixed Models – Interaktiv (LMM & GLMM)</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=Fraunces:ital,wght@0,300;0,600;1,300&display=swap');
:root {
--bg:#f5f0e8;--paper:#fdfaf4;--ink:#1a1410;--ink2:#4a3f35;
--accent5:#ED7F50;--accent:#c94a2a;--accent2:#2a6e8a;--accent3:#5a8a2a;
--grid:#e0d8cc;--panel:#eee8da;--border:#1a1410;
--shadow:rgba(0,0,0,0.06);
--chart-grid:rgba(0,0,0,0.07);--chart-tick:#2a2018;
--warn:#8a5a00;--warn-bg:#fff3cc;
--slider-track:#e0d8cc;--slider-thumb:#1a1410;
}
[data-theme="dark"] {
--bg:#0f1117;--paper:#171b25;--ink:#e8e2d8;--ink2:#9a9080;
--accent:#e8614a;--accent2:#4ab0d8;--accent3:#7ec850;--accent5:#F6C2AC;
--grid:#252a36;--panel:#1e2230;--border:#333a4a;
--shadow:rgba(0,0,0,0.4);
--chart-grid:rgba(255,255,255,0.06);--chart-tick:#c8c0b0;
--warn:#e8c040;--warn-bg:rgba(232,192,64,0.08);
--slider-track:#252a36;--slider-thumb:#e8e2d8;
}
html{font-size:18px;}
*{box-sizing:border-box;margin:0;padding:0;}
body{font-family:'Fraunces',Georgia,serif;background:var(--bg);color:var(--ink);height:100vh;overflow:hidden;display:flex;flex-direction:column;transition:background .25s,color .25s;}
/* ── HEADER (einheitlich, identisch zu Bayesian_model_architect) ── */
#hdr{background:var(--paper);border-bottom:1.5px solid var(--border);padding:.5rem 1.1rem;display:flex;align-items:center;justify-content:space-between;flex-shrink:0;gap:.5rem;line-height:normal}
.hdr-hrow{display:flex;justify-content:space-between;align-items:flex-start;padding:1rem 1.8rem .7rem;gap:1rem;flex-wrap:wrap;flex-shrink:0;border-bottom:1px solid var(--border)}
.hdr-h1{font-family:'Fraunces',Georgia,serif;font-size:1.55rem;font-weight:300;letter-spacing:-.02em;line-height:1.2}
.hdr-h1 em{font-style:italic;color:var(--accent5)}
.hdr-sub2{font-family:'DM Mono',monospace;font-size:.75rem;color:var(--ink2);margin-top:.2rem;letter-spacing:.03em}
.hdr-auth{font-family:'DM Mono',monospace;font-size:.75rem;color:var(--ink2);opacity:.5;margin-top:.1rem}
.hdr-btns{display:flex;gap:.4rem;align-items:center}
#shell{flex:1;overflow-y:auto;min-height:0;padding:1.2rem 1.8rem 2.5rem}
.header-row{display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:.9rem;gap:1rem;}
h1{font-size:1.55rem;font-weight:300;letter-spacing:-.02em;line-height:1.2;}
h1 em{font-style:italic;color:var(--accent5);}
.subtitle{font-family:'DM Mono',monospace;font-size:.75rem;color:var(--ink2);margin-top:.22rem;letter-spacing:.03em;}
.hbtns{display:flex;gap:.4rem;flex-wrap:wrap;align-items:flex-start;}
.icon-btn{font-family:'DM Mono',monospace;font-size:.75rem;padding:.22rem .6rem;border:1.5px solid var(--border);background:var(--panel);cursor:pointer;color:var(--ink2);display:flex;align-items:center;gap:.35rem;transition:all .15s;white-space:nowrap;}
.icon-btn:hover{border-color:var(--accent2);color:var(--accent2);}
#btn-theme:hover{background:transparent;border-color:var(--accent2);color:var(--accent2);}
.icon-btn.ib-on{border-color:var(--accent2);color:var(--accent2);}
.icon-btn.ib-on:hover{background:var(--accent2);color:var(--bg);}
/* ── MODEL / POOLING ROWS ── */
.control-rows{display:flex;flex-direction:column;gap:.38rem;margin-bottom:.9rem;}
.ctrl-row{display:flex;gap:.28rem;flex-wrap:wrap;align-items:center;}
.ctrl-label{font-family:'DM Mono',monospace;font-size:.75rem;color:var(--ink2);letter-spacing:.07em;margin-right:.2rem;white-space:nowrap;min-width:5.5rem;}
.ctab{font-family:'DM Mono',monospace;font-size:.75rem;padding:.3rem .8rem;border:1.5px solid var(--border);background:transparent;cursor:pointer;letter-spacing:.05em;transition:all .13s;color:var(--ink);}
.ctab:hover{background:var(--ink);color:var(--bg);}
.ctab.pp-on{background:var(--accent2);color:white;border-color:var(--accent2);}
.ctab.np-on{background:var(--accent3);color:#0f1117;border-color:var(--accent3);}
.ctab.cp-on{background:var(--accent);color:white;border-color:var(--accent);}
.ctab.mdl-on{background:var(--ink);color:var(--bg);}
/* ── OUTER GRID — sidebar fixed, charts fill rest ── */
.outer-grid{display:grid;grid-template-columns:300px 1fr;gap:1rem;align-items:start;width:100%;}
/* ── SIDEBAR ── */
.sidebar{display:flex;flex-direction:column;gap:.7rem;position:sticky;top:1rem;max-height:calc(100vh - 2rem);overflow-y:scroll;}
.sidebar::-webkit-scrollbar{width:6px}
.sidebar::-webkit-scrollbar-track{background:var(--bg)}
.sidebar::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px}
.sidebar::-webkit-scrollbar-thumb:hover{background:var(--accent2)}
.sb-card{background:var(--paper);border:1.5px solid var(--border);padding:.85rem 1rem;box-shadow:2px 2px 0 var(--shadow);}
.sb-card h3{font-family:'DM Mono',monospace;font-size:.58rem;letter-spacing:.1em;text-transform:uppercase;margin-bottom:.65rem;padding-bottom:.28rem;border-bottom:1px solid var(--grid);}
.h3a{color:var(--accent);} .h3b{color:var(--accent2);} .h3g{color:var(--accent3);}
.param-group{margin-bottom:.7rem;}
.param-group:last-child{margin-bottom:0;}
.param-label{display:flex;justify-content:space-between;align-items:baseline;margin-bottom:.18rem;}
.param-label span:first-child{font-family:'DM Mono',monospace;font-size:.67rem;color:var(--ink);}
.pval{font-family:'DM Mono',monospace;font-size:.76rem;font-weight:500;}
.pva{color:var(--accent);} .pvb{color:var(--accent2);} .pvg{color:var(--accent3);}
input[type=range]{width:100%;-webkit-appearance:none;height:3px;background:var(--slider-track);outline:none;cursor:pointer;border-radius:2px;}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:12px;height:12px;background:var(--slider-thumb);border-radius:50%;cursor:pointer;}
input[type=range]::-webkit-slider-thumb:hover{background:var(--accent);}
.re-mode-row{display:flex;gap:.25rem;margin-bottom:.65rem;}
.re-btn{font-family:'DM Mono',monospace;font-size:.75rem;padding:.22rem .55rem;border:1.5px solid var(--border);background:transparent;cursor:pointer;color:var(--ink2);transition:all .12s;}
.re-btn.re-on{background:var(--accent2);color:white;border-color:var(--accent2);}
.shrink-label-row{display:flex;justify-content:space-between;font-family:'DM Mono',monospace;font-size:.75rem;color:var(--ink2);margin-bottom:.18rem;}
.shrink-track{height:5px;background:var(--grid);border-radius:3px;overflow:hidden;}
.shrink-fill{height:100%;background:linear-gradient(90deg,var(--accent2),var(--accent3));transition:width .35s;}
.data-row{display:flex;align-items:center;gap:.45rem;margin-top:.35rem;}
.regen-btn{font-family:'DM Mono',monospace;font-size:.75rem;padding:.25rem .65rem;border:1.5px solid var(--border);background:transparent;cursor:pointer;color:var(--ink2);transition:all .15s;}
.regen-btn:hover{background:var(--accent);color:white;border-color:var(--accent);}
.nlabel{font-family:'DM Mono',monospace;font-size:.75rem;color:var(--ink2);}
.formula-box{background:var(--panel);border-left:3px solid var(--accent2);padding:.55rem .72rem;font-family:'DM Mono',monospace;font-size:.75rem;line-height:1.85;color:var(--ink);white-space:pre-wrap;}
.fxd{color:var(--accent);font-weight:500;}
.rnd{color:var(--accent2);font-weight:500;}
.gry{color:var(--ink2);}
/* ── CHARTS COLUMN ── */
.charts-col{display:flex;flex-direction:column;gap:.9rem;}
.chart-panel{background:var(--paper);border:1.5px solid var(--border);padding:.85rem 1rem;box-shadow:2px 2px 0 var(--shadow);}
.panel-label{font-family:'DM Mono',monospace;font-size:.75rem;letter-spacing:.1em;text-transform:uppercase;color:var(--accent2);margin-bottom:.24rem;}
.panel-title{font-size:.85rem;font-weight:300;margin-bottom:.2rem;line-height:1.3;}
.panel-title em{color:var(--accent);font-style:italic;}
.simp-warn{display:none;font-family:'DM Mono',monospace;font-size:.75rem;padding:.38rem .65rem;border:1.5px solid var(--warn);color:var(--warn);background:var(--warn-bg);margin-bottom:.45rem;gap:.38rem;align-items:flex-start;line-height:1.5;}
.simp-warn.on{display:flex;}
.legend-row{display:flex;gap:.45rem;flex-wrap:wrap;margin-bottom:.38rem;}
.legend-item{display:flex;align-items:center;gap:.25rem;font-family:'DM Mono',monospace;font-size:.75rem;color:var(--ink2);}
.ldot{width:10px;height:10px;border-radius:50%;}
.lline{width:16px;height:2px;border-radius:1px;}
.bottom-row{display:grid;grid-template-columns:1fr 1fr;gap:.9rem;}
.stats-grid{display:grid;grid-template-columns:1fr 1fr;gap:.35rem;margin-bottom:.7rem;}
.stat-box{background:var(--panel);padding:.38rem .52rem;border:1px solid var(--grid);}
.stat-lbl{font-family:'DM Mono',monospace;font-size:.75rem;color:var(--ink2);letter-spacing:.04em;margin-bottom:.08rem;}
.stat-val{font-family:'DM Mono',monospace;font-size:.75rem;font-weight:500;color:var(--ink);}
.vpc-track{height:11px;display:flex;border-radius:2px;overflow:hidden;margin:.3rem 0;}
.vpc-between{background:var(--accent2);transition:width .35s;}
.vpc-resid{background:var(--grid);flex:1;}
.vpc-labels{display:flex;justify-content:space-between;font-family:'DM Mono',monospace;font-size:.75rem;color:var(--ink2);}
.info-strip{padding:.6rem .82rem;background:var(--panel);border-left:3px solid var(--accent2);font-size:.75rem;line-height:1.62;color:var(--ink2);margin-top:.65rem;}
.info-strip strong{color:var(--ink);}
/* Results panel */
.res-section{margin-bottom:.7rem;padding-bottom:.55rem;border-bottom:1px solid var(--grid);}
.res-section:last-child{border-bottom:none;margin-bottom:0;}
.res-label{font-family:'DM Mono',monospace;font-size:.75rem;letter-spacing:.08em;text-transform:uppercase;color:var(--accent2);margin-bottom:.35rem;}
.res-row{display:flex;justify-content:space-between;align-items:baseline;font-family:'DM Mono',monospace;font-size:.75rem;color:var(--ink2);margin-bottom:.18rem;gap:.5rem;}
.res-row span:first-child{flex:1;}
.res-val{font-weight:500;color:var(--ink);white-space:nowrap;}
.res-val.active-mode{color:var(--accent2);font-weight:700;}
.re-table{width:100%;border-collapse:collapse;font-family:'DM Mono',monospace;font-size:.75rem;margin-top:.2rem;}
.re-table th{color:var(--ink2);font-weight:400;letter-spacing:.04em;padding:.18rem .3rem;border-bottom:1px solid var(--grid);text-align:left;}
.re-table td{padding:.2rem .3rem;border-bottom:1px solid var(--grid)+'44';color:var(--ink);transition: opacity .2s;}
.re-table tbody tr{transition: opacity .2s, background .2s;}
.re-table tbody tr:hover{background:var(--panel);}
.grp-dot{display:inline-block;width:8px;height:8px;border-radius:50%;margin-right:.3rem;vertical-align:middle;}
canvas{max-width:100%;display:block;}
@media(max-width:960px){.outer-grid{grid-template-columns:1fr}.bottom-row{grid-template-columns:1fr}}
.glmm-auth{font-family:'DM Mono',monospace;font-size:.75rem;color:var(--ink2);opacity:.5;margin-top:.1rem}
/* ── FLOATING HELP PANEL ── */
#help-float{
display:none;position:fixed;right:1.5rem;top:50%;transform:translateY(-50%);
width:300px;z-index:600;background:var(--paper);border:1.5px solid var(--border);
box-shadow:4px 4px 0 rgba(0,0,0,.18);
}
#help-float.open{display:block}
.hp-head{display:flex;justify-content:space-between;align-items:center;
padding:.5rem .85rem;border-bottom:1px solid var(--grid)}
.hp-title{font-family:'DM Mono',monospace;font-size:.58rem;letter-spacing:.1em;
text-transform:uppercase;font-weight:500;color:var(--accent)}
.hp-close{font-family:'DM Mono',monospace;font-size:.85rem;background:transparent;
border:none;cursor:pointer;color:var(--ink2);line-height:1;padding:0 .1rem}
.hp-close:hover{color:var(--ink)}
.hp-body{padding:.8rem .85rem;font-family:'DM Mono',monospace;font-size:.67rem;
line-height:1.8;color:var(--ink2);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(--grid);
padding-bottom:.18rem;color:var(--ink2)}
.hp-sect:first-child{margin-top:0}
.hp-body strong{color:var(--ink)}
.hp-body em{color:var(--accent2);font-style:normal}
.hp-seq{padding-left:.05rem}
.hp-seq li{list-style:none;padding:.08rem 0}
.hp-seq li::before{color:var(--accent2);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:'⑤'}
.hp-seq li:nth-child(6)::before{content:'⑥'}
.hp-seq li:nth-child(7)::before{content:'⑦'}
.hp-next{margin-top:.75rem;padding:.4rem .55rem;border-left:3px solid var(--accent2);
background:var(--panel);font-size:.65rem;color:var(--ink2)}
/* ── TUTORIAL LEARN CARDS ── */
.learn-section{margin:1.5rem 0 2.5rem;display:grid;grid-template-columns:1fr 1fr;gap:1px;background:var(--grid)}
.lcard{background:var(--paper);padding:.95rem 1.1rem}
.lcard-h{font-family:'DM Mono',monospace;font-size:.75rem;letter-spacing:.08em;text-transform:uppercase;margin-bottom:.45rem;padding-bottom:.22rem;border-bottom:1px solid var(--grid)}
.lcard-h.ca{color:var(--accent2)}.lcard-h.cg{color:var(--accent3)}.lcard-h.cr{color:var(--accent)}.lcard-h.co{color:var(--accent5)}
.lcard-body{font-family:'DM Mono',monospace;font-size:.75rem;color:var(--ink2);line-height:1.8}
.lcard-body b{color:var(--ink)}
.lcard-body code{background:var(--panel);border:1px solid var(--border);color:var(--accent2);padding:.02rem .3rem;font-size:.75rem}
</style>
</head>
<body>
<div id="hdr" class="hdr-hrow">
<div>
<div class="hdr-h1">(G)<em>LMM</em> — Mixed Models Interaktiv</div>
<div class="hdr-sub2">Gaussian · Poisson · Gamma · Logistisch · Partial/No/Complete Pooling · Shrinkage · ICC · Simpson</div>
<div class="hdr-auth">© Dr. Rainer Düsing · Interactive Tools by Claude</div>
</div>
<div class="hdr-btns">
<button class="icon-btn" onclick="window.open('index_de.html','_self')" style="border-color:var(--accent5);color:var(--accent5)">← Übersicht</button>
<button class="icon-btn" id="btn-outlier" onclick="toggleOutlier()" title="Ausreißer-Gruppe mit kleinem n hinzufügen">⚡ Ausreißer-Gruppe</button>
<button class="icon-btn" id="btn-true" onclick="toggleTrue()" title="Wahre Parameter anzeigen">🎯 Wahre Param.</button>
<button class="icon-btn" onclick="toggleHelpFloat()" style="border-color:var(--accent);color:var(--accent)">ℹ Hilfe</button>
<button class="icon-btn" id="btn-theme" onclick="toggleTheme()">☀ Light</button>
</div>
</div>
<div id="shell">
<p class="subtitle" style="margin:.2rem 1.4rem .1rem;color:var(--warn);font-size:.75rem;line-height:1.5">
⚠ Illustrations-Tool: Schätzungen via IRLS + Method-of-Moments — keine Laplace-Approximation (lme4/glmmTMB). Richtung und Größenordnung stimmen, exakte Werte weichen ab.
</p>
<div class="control-rows">
<div class="ctrl-row" style="flex-wrap:wrap;gap:.45rem">
<div style="display:flex;align-items:center;gap:.28rem;flex-wrap:wrap">
<span class="ctrl-label">LIKELIHOOD:</span>
<button class="ctab mdl-on" id="mdl-gauss" onclick="setModel('gauss')">Gaussian (LMM)</button>
<button class="ctab" id="mdl-poisson" onclick="setModel('poisson')">Poisson (GLMM)</button>
<button class="ctab" id="mdl-gamma" onclick="setModel('gamma')">Gamma (GLMM)</button>
<button class="ctab" id="mdl-logistic" onclick="setModel('logistic')">Logistisch (GLMM)</button>
</div>
<div style="display:flex;align-items:center;gap:.28rem;flex-wrap:wrap;padding-left:.65rem;border-left:1px solid var(--border)">
<span class="ctrl-label">POOLING:</span>
<button class="ctab pp-on" id="ptab-pp" onclick="setPooling('pp')">▸ Partial Pooling</button>
<button class="ctab" id="ptab-np" onclick="setPooling('np')">▸ No Pooling</button>
<button class="ctab" id="ptab-cp" onclick="setPooling('cp')">▸ Complete Pooling</button>
</div>
</div>
</div>
<div class="outer-grid">
<div class="sidebar">
<div class="sb-card">
<h3 class="h3a">Fixed Effects</h3>
<div class="param-group">
<div class="param-label"><span>γ₀₀ · Grand Intercept</span><span class="pval pva" id="v-g00">2.00</span></div>
<input type="range" id="g00" min="-2" max="6" step="0.1" value="2.0">
</div>
<div class="param-group">
<div class="param-label"><span>γ₁₀ · Fixed Slope</span><span class="pval pva" id="v-g10">0.60</span></div>
<input type="range" id="g10" min="-2" max="2" step="0.05" value="0.6">
</div>
</div>
<div class="sb-card">
<h3 class="h3b">Random Effects</h3>
<div class="re-mode-row">
<button class="re-btn re-on" id="re-int" onclick="setREMode('int')">Random Intercept</button>
<button class="re-btn" id="re-both" onclick="setREMode('both')">Intercept + Slope</button>
</div>
<div class="param-group" id="pg-tau0">
<div class="param-label"><span>τ₀ · SD Random Intercept</span><span class="pval pvb" id="v-tau0">1.00</span></div>
<input type="range" id="tau0" min="0" max="3" step="0.05" value="1.0">
</div>
<div class="param-group" id="pg-tau1" style="display:none">
<div class="param-label"><span>τ₁ · SD Random Slope</span><span class="pval pvb" id="v-tau1">0.30</span></div>
<input type="range" id="tau1" min="0" max="1.5" step="0.05" value="0.3">
</div>
<div class="param-group" id="pg-rho" style="display:none">
<div class="param-label">
<span>ρ · Korrelation u₀↔u₁</span><span class="pval pvb" id="v-rho">0.00</span>
</div>
<input type="range" id="rho" min="-0.95" max="0.95" step="0.05" value="0">
<div style="font-family:'DM Mono',monospace;font-size:.75rem;color:var(--ink2);margin-top:.2rem;line-height:1.5">
ρ>0: Gruppen mit hohem Intercept haben steilen Slope (Fan-out)<br>
ρ<0: Gruppen mit hohem Intercept haben flachen Slope (Fan-in)
</div>
</div>
<div class="param-group" id="pg-sigma">
<div class="param-label"><span>σ · Residual SD</span><span class="pval pvb" id="v-sigma">0.60</span></div>
<input type="range" id="sigma" min="0.1" max="2.5" step="0.05" value="0.6">
</div>
</div>
<div class="sb-card">
<h3 class="h3g">Datengenerierung</h3>
<div class="param-group">
<div class="param-label"><span>Gruppen J</span><span class="pval pvg" id="v-J">5</span></div>
<input type="range" id="J" min="2" max="8" step="1" value="5">
</div>
<div class="param-group">
<div class="param-label"><span>Beob. pro Gruppe n_j</span><span class="pval pvg" id="v-n">12</span></div>
<input type="range" id="n" min="4" max="30" step="1" value="12">
</div>
<div class="param-group">
<div class="param-label"><span>x-Bereich</span><span class="pval pvg" id="v-xr">±3.0</span></div>
<input type="range" id="xr" min="0.5" max="5" step="0.5" value="3">
</div>
<div class="param-group">
<div class="param-label">
<span>x-Gruppen-Versatz <span style="font-size:.75rem;color:var(--warn)">(Simpson)</span></span>
<span class="pval" style="color:var(--warn)" id="v-xoff">0.0</span>
</div>
<input type="range" id="xoff" min="0" max="3" step="0.1" value="0">
</div>
<div class="data-row">
<button class="regen-btn" onclick="regen()">⟳ Neue Daten</button>
<button class="regen-btn" onclick="downloadCSV()" title="Simulierte Daten als CSV herunterladen" style="border-color:var(--accent3);color:var(--accent3)">↓ CSV</button>
<button class="regen-btn" id="btn-simpson" onclick="setSimpson()" style="border-color:var(--warn);color:var(--warn)" title="Simpson-Szenario laden">⚠ Simpson</button>
<span class="nlabel" id="v-N">N = 60</span>
</div>
</div>
<div class="sb-card">
<h3 class="h3b">Modellformel</h3>
<div class="formula-box" id="formula-box">–</div>
</div>
</div><div class="charts-col">
<div class="chart-panel">
<div class="panel-label">HAUPTPLOT — DATEN & REGRESSIONSLINIEN</div>
<div class="panel-title" id="main-title">Partial Pooling: <em>Gruppenlinien mit Shrinkage</em></div>
<div class="simp-warn" id="simp-warn">
<span>⚠</span><span>Simpson-Risiko: Complete-Pooling-Linie zeigt eine <b>andere Richtung</b> als die gruppeninternen Effekte — Gruppenstruktur nicht ignorieren!</span>
</div>
<div class="legend-row" id="main-legend"></div>
<div style="position:relative;height:clamp(260px, 46vh, 520px)">
<canvas id="mainChart"></canvas>
</div>
</div>
<div class="bottom-row">
<div class="chart-panel">
<div class="panel-label">SHRINKAGE-DIAGRAMM</div>
<div class="panel-title">No Pooling <em>vs.</em> Partial Pooling Intercepts</div>
<div style="font-family:'DM Mono',monospace;font-size:.75rem;color:var(--ink2);margin-bottom:.35rem;line-height:1.6">
<b>Wie lesen?</b> Jede Zeile = eine Gruppe, sortiert nach No-Pooling-Intercept (oben = größter). ○ = No-Pooling · ● = Partial-Pooling. Pfeil zeigt Richtung und Stärke der Shrinkage zum Grand Mean (γ̂₀₀, gestrichelt).
<span id="outlier-note-cat" style="display:none;color:var(--accent)"> · ⚡ = Ausreißer-Gruppe</span>
</div>
<div style="display:none;position:relative;height:0">
<canvas id="shrinkChart"></canvas>
</div>
<div style="position:relative;">
<canvas id="caterpillarCanvas" style="display:block;width:100%;"></canvas>
</div>
<div id="grp-table-panel" style="margin-top:.6rem"></div>
</div>
<div class="chart-panel">
<div class="panel-label">MODELL-ERGEBNISSE</div>
<div class="panel-title">Geschätzte Parameter & <em>Kennzahlen</em></div>
<div id="results-panel" style="margin-top:.4rem"></div>
</div>
</div>
</div>
</div>
<!-- ═══ TUTORIAL LERNKARTEN ═══════════════════════════════ -->
<div class="learn-section">
<div class="lcard">
<div class="lcard-h ca">Was ist ein Mixed Model?</div>
<div class="lcard-body">
Ein Mixed Model kombiniert <b>Fixed Effects</b> (γ — gleich für alle Gruppen) mit <b>Random Effects</b> (u₀ⱼ — gruppenspezifische Abweichungen). Das Grundmodell lautet:<br><br>
<code>y_ij = γ₀₀ + γ₁₀·x_ij + u₀ⱼ + ε_ij</code><br><br>
Die u₀ⱼ werden nicht direkt geschätzt, sondern als Zufallsvariablen modelliert: <b>u₀ⱼ ~ Normal(0, τ₀²)</b>. Das ermöglicht <em>Informationsaustausch</em> zwischen den Gruppen — jede Gruppe profitiert von den Daten der anderen.
</div>
</div>
<div class="lcard">
<div class="lcard-h ca">Complete · No · Partial Pooling</div>
<div class="lcard-body">
<b>Complete Pooling:</b> Eine Gerade für alle — Gruppenstruktur wird ignoriert. Effizient, aber verzerrt wenn Gruppen wirklich unterschiedlich sind.<br><br>
<b>No Pooling:</b> Unabhängige Geraden je Gruppe. Kein Informationsaustausch — Overfit bei kleinem n_j.<br><br>
<b>Partial Pooling (Mixed Model):</b> Der goldene Mittelweg. Gruppenspezifische Schätzungen werden zum Grand Mean gezogen (<em>Shrinkage</em>). Gruppen mit wenig Daten werden stärker gezogen — das Modell „traut" ihnen weniger.
</div>
</div>
<div class="lcard">
<div class="lcard-h cg">ICC — Intraklassen-Korrelation</div>
<div class="lcard-body">
<b>ICC = τ₀² / (τ₀² + σ²)</b><br><br>
Der Anteil der Gesamtvarianz, der <em>zwischen Gruppen</em> liegt. Faustregel: ICC > 0.05 → LMM ist notwendig, da Beobachtungen innerhalb einer Gruppe nicht unabhängig sind.<br><br>
<b>Shrinkage-Faktor λ = τ₀² / (τ₀² + σ²/n_j)</b><br><br>
Bestimmt, wie stark die Gruppenspezifische Schätzung zum Grand Mean gezogen wird. Bei kleinem n_j oder kleinem τ₀ → starke Shrinkage. Im Shrinkage-Diagramm sichtbar als Pfeillänge.
</div>
</div>
<div class="lcard">
<div class="lcard-h cr">Simpson's Paradoxon</div>
<div class="lcard-body">
Wenn x mit der Gruppenzugehörigkeit korreliert (x-Gruppen-Versatz > 0), kann der <b>marginale Trend</b> (Complete Pooling über alle Daten) dem <b>gruppeninternen Trend</b> entgegengesetzt sein.<br><br>
<b>Beispiel:</b> Innerhalb jeder Gruppe steigt y mit x — aber Gruppen mit hohem x haben auch niedrigere Intercepts. Die Complete-Pooling-Linie sieht einen <em>negativen</em> Gesamttrend, obwohl der wahre Effekt positiv ist.<br><br>
<b>Lösung:</b> Partial Pooling trennt den Within-Group-Effekt (γ₁₀) vom Between-Group-Effekt.
</div>
</div>
<div class="lcard">
<div class="lcard-h co">Random Intercept vs. Intercept + Slope</div>
<div class="lcard-body">
<b>Random Intercept (τ₀ > 0):</b> Gruppen unterscheiden sich in ihrem Ausgangsniveau — parallele Linien mit verschiedenen y-Achsenabschnitten. Formel: <code>y ~ x + (1|Gruppe)</code><br><br>
<b>Random Intercept + Slope (τ₀, τ₁ > 0):</b> Gruppen haben auch unterschiedliche Steigungen — kein Fan-Out oder Fan-In. Formel: <code>y ~ x + (1+x|Gruppe)</code><br><br>
Der Parameter <b>ρ</b> steuert die Korrelation: ρ > 0 → Gruppen mit hohem Intercept haben auch steilen Slope (Fan-out). ρ < 0 → Linien kreuzen sich (Fan-in).
</div>
</div>
<div class="lcard">
<div class="lcard-h cg">GLMM — Wann welche Likelihood?</div>
<div class="lcard-body">
Das Mixed-Model-Prinzip gilt für alle Verteilungsfamilien:<br><br>
<b>Gaussian (LMM):</b> Stetige, symmetrische AV. <code>y ~ Normal(μ, σ)</code><br><br>
<b>Poisson (GLMM):</b> Zähldaten (0, 1, 2, …). Log-Link: <code>log(λ) = η</code> — λ bleibt positiv.<br><br>
<b>Gamma (GLMM):</b> Positive, rechtsschiefe Daten (Reaktionszeiten, Kosten). Log-Link.<br><br>
<b>Logistisch (GLMM):</b> Binäre AV (0/1). Logit-Link: <code>log(p/(1−p)) = η</code> — p bleibt in (0,1).<br><br>
In brms: <code>family = poisson()</code>, <code>family = Gamma(link="log")</code>, <code>family = bernoulli()</code>
</div>
</div>
</div>
</div><!-- /shell -->
<script>
// ═══════════════════════════════════════════════════════════════
// THEME / HELP
// ═══════════════════════════════════════════════════════════════
let isDark = localStorage.getItem('btl-theme') !== 'light';
function toggleTheme() {
isDark = !isDark;
document.documentElement.setAttribute('data-theme', isDark ? 'dark' : 'light');
document.getElementById('btn-theme').textContent = isDark ? '☀ Light' : '🌙 Dark';
localStorage.setItem('btl-theme', isDark ? 'dark' : 'light');
renderAll();
}
const css = v => getComputedStyle(document.documentElement).getPropertyValue(v).trim();
// ═══════════════════════════════════════════════════════════════
// TOGGLE OPTIONS & HOVER HIGHLIGHTING
// ═══════════════════════════════════════════════════════════════
let showTrue = false;
let showOutlier = false;
let activeGid = null;
function toggleTrue() {
showTrue = !showTrue;
document.getElementById('btn-true').classList.toggle('ib-on', showTrue);
renderAll();
}
function toggleOutlier() {
showOutlier = !showOutlier;
document.getElementById('btn-outlier').classList.toggle('ib-on', showOutlier);
document.getElementById('outlier-note-cat').style.display = showOutlier ? 'inline' : 'none';
genData(); renderAll();
}
function highlightGroup(gid) {
if (activeGid === gid) return;
activeGid = gid;
// Fade Charts
[charts.main, charts.shrink].forEach(chart => {
if (!chart) return;
chart.data.datasets.forEach(ds => {
if (ds.gid !== undefined) {
const isFaded = gid !== null && ds.gid !== gid;
if (!ds.origBorder) ds.origBorder = ds.borderColor;
if (!ds.origBg) ds.origBg = ds.backgroundColor;
ds.borderColor = isFaded ? ds.origBorder.substring(0, 7) + '22' : ds.origBorder;
if (typeof ds.origBg === 'string' && ds.origBg.length > 7 && ds.origBg !== 'transparent') {
ds.backgroundColor = isFaded ? ds.origBg.substring(0, 7) + '11' : ds.origBg;
} else if (ds.origBg !== 'transparent') {
ds.backgroundColor = isFaded ? ds.origBg + '22' : ds.origBg;
}
}
});
chart.update('none');
});
// Highlight Table
const rows = document.querySelectorAll('.re-table tbody tr');
rows.forEach((tr, j) => {
tr.style.opacity = (gid === null || j === gid) ? '1' : '0.25';
tr.style.background = (gid === j) ? 'var(--panel)' : '';
});
}
// Chart.js Plugin for drawing arrows on the shrinkage lines
const arrowPlugin = {
id: 'arrowPlugin',
afterDatasetsDraw(chart) {
const ctx = chart.ctx;
chart.data.datasets.forEach((meta, i) => {
if (meta.label && meta.label.startsWith('conn_')) {
const ds = chart.getDatasetMeta(i);
if(!ds.data || ds.data.length < 2) return;
const p1 = ds.data[0], p2 = ds.data[1]; // x, y are pixel coords
const dx = p2.x - p1.x, dy = p2.y - p1.y;
if (Math.abs(dx) < 1 && Math.abs(dy) < 1) return; // Point too close
const angle = Math.atan2(dy, dx);
const headlen = 5;
ctx.save();
ctx.strokeStyle = chart.data.datasets[i].borderColor;
ctx.fillStyle = chart.data.datasets[i].borderColor;
ctx.lineWidth = 1.5;
ctx.beginPath();
// Draw triangle head at p2
ctx.moveTo(p2.x, p2.y);
ctx.lineTo(p2.x - headlen * Math.cos(angle - Math.PI / 6), p2.y - headlen * Math.sin(angle - Math.PI / 6));
ctx.lineTo(p2.x - headlen * Math.cos(angle + Math.PI / 6), p2.y - headlen * Math.sin(angle + Math.PI / 6));
ctx.lineTo(p2.x, p2.y);
ctx.fill();
ctx.restore();
}
});
}
};
// ═══════════════════════════════════════════════════════════════
// COLORS
// ═══════════════════════════════════════════════════════════════
const GC = ['#e05a3a','#9b59d0','#2ecc8a','#e8880a','#e84a8a','#1ab8c8','#a0c020','#c87840'];
const FE_COLOR = '#f0d000';
// ═══════════════════════════════════════════════════════════════
// STATE
// ═══════════════════════════════════════════════════════════════
let poolMode = 'pp', reMode = 'int', modelKey = 'gauss', seed = 42;
let data = [], trueGrp = [];
let charts = {main: null, shrink: null};
// ═══════════════════════════════════════════════════════════════
// SEEDED RNG
// ═══════════════════════════════════════════════════════════════
function mkRng(s) {
let st = s >>> 0;
return () => { st = (Math.imul(st, 1664525) + 1013904223) >>> 0; return st / 0x100000000; };
}
function rnorm(rng) {
return Math.sqrt(-2 * Math.log(Math.max(rng(), 1e-10))) * Math.cos(2 * Math.PI * rng());
}
// ═══════════════════════════════════════════════════════════════
// MODEL DEFINITIONS
// ═══════════════════════════════════════════════════════════════
const MODELS = {
gauss: {
name: 'Gaussian (LMM)',
link: η => η,
invLink: μ => μ,
sample: (μ, sig, rng) => μ + rnorm(rng) * sig,
yLabel: 'y (stetig)',
formulaLink: 'μ = η (Identität)',
formulaDist: 'Y|x,u ~ N(μ, σ²)',
hasSigma: true,
yPositive: false,
yBinary: false,
},
poisson: {
name: 'Poisson (GLMM)',
link: μ => Math.log(Math.max(μ, 1e-9)),
invLink: η => Math.exp(η),
sample: (μ, sig, rng) => {
let λ = Math.max(μ, 1e-6), k = 0, p = 1, L = Math.exp(-λ);
if (λ > 30) return Math.max(0, Math.round(λ + rnorm(rng) * Math.sqrt(λ)));
do { k++; p *= rng(); } while (p > L);
return k - 1;
},
yLabel: 'y (Zählung)',
formulaLink: 'log(λ) = η → λ = exp(η)',
formulaDist: 'Y|x,u ~ Poisson(λ)',
hasSigma: false,
yPositive: true,
yBinary: false,
},
gamma: {
name: 'Gamma (GLMM)',
link: μ => Math.log(Math.max(μ, 1e-9)),
invLink: η => Math.exp(η),
sample: (μ, sig, rng) => {
const k = Math.max(1 / (sig * sig), 0.1);
if (k >= 1) {
const d = k - 1/3, c = 1 / Math.sqrt(9*d);
for (let i=0;i<200;i++) {
let x, v;
do { x = rnorm(rng); v = 1 + c*x; } while (v <= 0);
v = v*v*v;
const u = rng();
if (u < 1 - 0.0331*(x*x)*(x*x)) return μ * d * v / k;
if (Math.log(u) < 0.5*x*x + d*(1-v+Math.log(v))) return μ * d * v / k;
}
return μ;
}
return Math.abs(μ + rnorm(rng) * μ * sig);
},
yLabel: 'y (positiv stetig)',
formulaLink: 'log(μ) = η → μ = exp(η)',
formulaDist: 'Y|x,u ~ Gamma(k, θ)',
hasSigma: true,
yPositive: true,
yBinary: false,
},
logistic: {
name: 'Logistisch (GLMM)',
link: p => Math.log(Math.max(p, 1e-9) / Math.max(1 - p, 1e-9)),
invLink: η => 1 / (1 + Math.exp(-η)),
sample: (p, sig, rng) => rng() < p ? 1 : 0,
yLabel: 'y (0/1)',
formulaLink: 'logit(p) = η → p = σ(η)',
formulaDist: 'Y|x,u ~ Bernoulli(p)',
hasSigma: false,
yPositive: false,
yBinary: true,
},
};
// ═══════════════════════════════════════════════════════════════
// PARAMS
// ═══════════════════════════════════════════════════════════════
const P = () => ({
g00: +document.getElementById('g00').value,
g10: +document.getElementById('g10').value,
tau0: +document.getElementById('tau0').value,
tau1: +document.getElementById('tau1').value,
rho: +document.getElementById('rho').value,
sig: +document.getElementById('sigma').value,
J: +document.getElementById('J').value | 0,
n: +document.getElementById('n').value | 0,
xr: +document.getElementById('xr').value,
xoff: +document.getElementById('xoff').value,
});
// ═══════════════════════════════════════════════════════════════
// DATA GENERATION
// ═══════════════════════════════════════════════════════════════
function genData() {
const p = P(), m = MODELS[modelKey], rng = mkRng(seed);
data = []; trueGrp = [];
const rhoClamp = Math.max(-0.999, Math.min(0.999, p.rho));
const L00 = p.tau0;
const L10 = rhoClamp * p.tau1;
const L11 = p.tau1 * Math.sqrt(Math.max(0, 1 - rhoClamp * rhoClamp));
for (let j = 0; j < p.J; j++) {
const z0 = rnorm(rng), z1 = rnorm(rng);
const u0 = L00 * z0;
const u1 = reMode === 'both' ? L10 * z0 + L11 * z1 : 0;
trueGrp.push({u0, u1, nj: p.n, isOutlier: false});
const xCenter = (j - (p.J-1)/2) * p.xoff;
for (let i = 0; i < p.n; i++) {
const x = xCenter + (rng() * 2 - 1) * p.xr;
const eta = (p.g00 + u0) + (p.g10 + u1) * x;
const mu = m.invLink(eta);
data.push({gid: j, x, y: m.sample(mu, p.sig, rng)});
}
}
if (showOutlier) {
const j = p.J;
// Outlier group: extreme intercept + counter-trend slope → strong shrinkage in both
const u0o = Math.max(p.tau0, 1.0) * 4.0;
// Slope deviation: opposite to fixed slope (if g10>0, outlier goes negative, and vice versa)
const slopeSign = p.g10 >= 0 ? -1 : 1;
const u1o = slopeSign * (Math.abs(p.g10) + 0.4); // reverses AND amplifies slope
trueGrp.push({u0: u0o, u1: u1o, nj: 4, isOutlier: true});
for (let i = 0; i < 4; i++) {
const x = (rng() * 2 - 1) * p.xr;
const eta = (p.g00 + u0o) + (p.g10 + u1o) * x;
const mu = m.invLink(eta);
data.push({gid: j, x, y: m.sample(mu, p.sig, rng)});
}
}
document.getElementById('v-N').textContent = `N = ${data.length}`;
}
function regen() { seed = Math.random() * 1e8 | 0; genData(); renderAll(); }
function downloadCSV() {
if (!data || data.length === 0) return;
const m = MODELS[modelKey];
// Column names depend on model
const yName = modelKey === 'logistic' ? 'y_binary'
: modelKey === 'poisson' ? 'y_count'
: modelKey === 'gamma' ? 'y_positive'
: 'y';
const modelName = { gauss:'lmm_gaussian', poisson:'glmm_poisson',
gamma:'glmm_gamma', logistic:'glmm_logistic' }[modelKey];
// Header
const lines = ['group,x,' + yName + ',group_intercept_true,group_slope_true'];
data.forEach(d => {
const tg = trueGrp[d.gid] || {u0:0, u1:0};
const p2 = {
g00: +document.getElementById('g00').value,
g10: +document.getElementById('g10').value,
};
const true_int = (p2.g00 + tg.u0).toFixed(4);
const true_slope = (p2.g10 + (tg.u1||0)).toFixed(4);
lines.push(`${d.gid+1},${d.x.toFixed(4)},${modelKey==='logistic'||modelKey==='poisson'?d.y:d.y.toFixed(4)},${true_int},${true_slope}`);
});
// R comment header
const pars = {
g00: +document.getElementById('g00').value,
g10: +document.getElementById('g10').value,
tau0: +document.getElementById('tau0').value,
tau1: +document.getElementById('tau1').value,
sig: +document.getElementById('sigma').value,
J: +document.getElementById('J').value,
n: +document.getElementById('n').value,
};
const comment = [
'# Simulierte Daten aus GLMM Interactive Tool',
'# Modell: ' + modelName,
'# Datengenerator: ' + m.formulaLink,
'# Parameter: gamma00=' + pars.g00 + ', gamma10=' + pars.g10 +
', tau0=' + pars.tau0 + ', tau1=' + pars.tau1 +
(MODELS[modelKey].hasSigma ? ', sigma=' + pars.sig : '') +
', J=' + pars.J + ', n_per_group=' + pars.n,
'# R-Code-Vorlage:',
'# library(lme4)',
'# d <- read.csv("' + modelName + '_data.csv", comment.char="#")',
modelKey === 'gauss' ? '# m <- lmer(' + yName + ' ~ x + (1|group), data=d, REML=FALSE)' :
modelKey === 'logistic' ? '# m <- glmer(' + yName + ' ~ x + (1|group), data=d, family=binomial)' :
modelKey === 'poisson' ? '# m <- glmer(' + yName + ' ~ x + (1|group), data=d, family=poisson)' :
'# m <- glmer(' + yName + ' ~ x + (1|group), data=d, family=Gamma(link="log"))',
'# summary(m)',
'',
].join('\n');
const blob = new Blob([comment + lines.join('\n')], {type:'text/csv;charset=utf-8;'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = modelName + '_data.csv';
a.click();
URL.revokeObjectURL(url);
}
function setSimpson() {
document.getElementById('g00').value = '3.0';
document.getElementById('g10').value = '0.6';
document.getElementById('tau0').value = '0.3';
document.getElementById('tau1').value = '0.1';
document.getElementById('sigma').value = '0.35';
document.getElementById('J').value = '5';
document.getElementById('n').value = '20';
document.getElementById('xr').value = '1.5';
document.getElementById('xoff').value = '2.0';
document.getElementById('v-xoff').textContent = '2.0';
showOutlier = false;
document.getElementById('btn-outlier').classList.remove('ib-on');
reMode = 'int';
document.getElementById('re-int').classList.add('re-on');
document.getElementById('re-both').classList.remove('re-on');
document.getElementById('pg-tau1').style.display = 'none';
const rng = mkRng(42);
data = []; trueGrp = [];
const u0list = [3.5, 1.75, 0, -1.75, -3.5];
for (let j = 0; j < 5; j++) {
const u0 = u0list[j];
const xCenter = (j - 2) * 2.0;
trueGrp.push({u0, u1: 0, nj: 20, isOutlier: false});
for (let i = 0; i < 20; i++) {
const x = xCenter + (rng() * 2 - 1) * 1.5;
const y = (3.0 + u0) + 0.6 * x + rnorm(rng) * 0.35;
data.push({gid: j, x, y});
}
}
document.getElementById('v-N').textContent = `N = ${data.length}`;
poolMode = 'cp';
['pp','np','cp'].forEach(k => {
document.getElementById('ptab-'+k).className = 'ctab' + (k==='cp' ? ' cp-on' : '');
});
renderAll();
}
// ═══════════════════════════════════════════════════════════════
// GLM HELPERS (IRLS)
// ═══════════════════════════════════════════════════════════════
function wls(pts, weights) {
const n = pts.length;
if (n < 2) return {a: pts[0]?.y ?? 0, b: 0};
const sw = weights.reduce((s,w)=>s+w, 0);
const mx = pts.reduce((s,p,i)=>s+weights[i]*p.x, 0)/sw;
const my = pts.reduce((s,p,i)=>s+weights[i]*p.y, 0)/sw;
const sxx = pts.reduce((s,p,i)=>s+weights[i]*(p.x-mx)**2, 0);
const sxy = pts.reduce((s,p,i)=>s+weights[i]*(p.x-mx)*(p.y-my), 0);
const b = sxx > 1e-9 ? sxy/sxx : 0;
return {a: my - b*mx, b};
}
function glmFit(pts, invLink, linkDeriv, varFn, maxIter=25) {
if (pts.length === 0) return {a:0, b:0};
const my = pts.reduce((s,p)=>s+p.y,0)/pts.length;
// Detect logit link: sigmoid(0) = 0.5, exp(0) = 1 — cleanly distinguishes both
const isLogit = Math.abs(invLink(0) - 0.5) < 0.01;
const myC = Math.max(1e-4, Math.min(1-1e-4, my));
// Correct initialization: logit(my) for logistic, log(my) for log-link
// The original `invLink === (η=>η)` always evaluates to false in JS (function
// reference comparison), so the Gaussian branch never fired — irrelevant here
// since glmFit is never called for Gaussian, but fix the logistic case:
let a = isLogit ? Math.log(myC/(1-myC)) : Math.log(Math.max(myC, 1e-6));
let b = 0;
for (let iter = 0; iter < maxIter; iter++) {
const wpts = [], ws = [];
for (const pt of pts) {
const rawEta = a + b*pt.x;
// Clamp eta for logistic to prevent exact saturation (mu=0 or 1)
const eta = isLogit ? Math.max(-12, Math.min(12, rawEta)) : rawEta;
const mu = invLink(eta);
const dmu = linkDeriv(eta);
const v = varFn(mu);
const w = (dmu*dmu) / Math.max(v, 1e-10);
// For logistic: clamp denominator so working response stays bounded
// (dmu → 0 at saturation causes z → ±∞ and IRLS divergence)
const dmuSafe = isLogit ? Math.max(dmu, 0.005) : Math.max(dmu, 1e-10);
const z = eta + (pt.y - mu) / dmuSafe;
wpts.push({x: pt.x, y: z});
ws.push(Math.max(w, 1e-14));
}
const res = wls(wpts, ws);
if (!isFinite(res.a) || !isFinite(res.b)) break;
const diff = Math.abs(res.a-a)+Math.abs(res.b-b);
a = res.a; b = res.b;
if (diff < 1e-6) break;
}
return {a: isFinite(a) ? a : 0, b: isFinite(b) ? b : 0};
}
function fitGLM(pts) {
const m = MODELS[modelKey];
if (modelKey === 'gauss') {
const n = pts.length;
if (n < 2) return {a: pts[0]?.y ?? 0, b: 0};
const mx = pts.reduce((s,p)=>s+p.x,0)/n, my = pts.reduce((s,p)=>s+p.y,0)/n;
const sxx = pts.reduce((s,p)=>s+(p.x-mx)**2,0);
const sxy = pts.reduce((s,p)=>s+(p.x-mx)*(p.y-my),0);
const b = sxx > 1e-9 ? sxy/sxx : 0;
return {a: my-b*mx, b};
}
if (modelKey === 'poisson')
return glmFit(pts, η=>Math.exp(η), η=>Math.exp(η), μ=>Math.max(μ,1e-6));
if (modelKey === 'gamma')
return glmFit(pts, η=>Math.exp(η), η=>Math.exp(η), μ=>Math.max(μ*μ,1e-6));
if (modelKey === 'logistic')
return glmFit(pts, η=>1/(1+Math.exp(-η)), η=>{ const s=1/(1+Math.exp(-η)); return s*(1-s); }, μ=>Math.max(μ*(1-μ),1e-6));
return {a:0,b:0};
}
// ═══════════════════════════════════════════════════════════════
// LMM/GLMM EMPIRICAL BAYES ESTIMATES
// ═══════════════════════════════════════════════════════════════
// ── 1-D IRLS: estimate intercept for a group given fixed slope b ──────
function fitIntercept(pts, b, invLink, linkDeriv, varFn, startA) {
const isLogit = Math.abs(invLink(0) - 0.5) < 0.01;
let a = startA;
for (let iter = 0; iter < 20; iter++) {
let sw = 0, sz = 0;
for (const pt of pts) {
const rawEta = a + b * pt.x;
const eta = isLogit ? Math.max(-12, Math.min(12, rawEta)) : rawEta;
const mu = invLink(eta);
const dmu = linkDeriv(eta);
const v = varFn(mu);
const w = Math.max((dmu * dmu) / Math.max(v, 1e-10), 1e-12);
const dmuSafe = isLogit ? Math.max(dmu, 0.005) : Math.max(dmu, 1e-10);
const z = eta + (pt.y - mu) / dmuSafe;
sw += w; sz += w * (z - b * pt.x);
}
const na = sw > 1e-12 ? sz / sw : a;
if (!isFinite(na)) break;
if (Math.abs(na - a) < 1e-7) { a = na; break; }
a = na;
}
return isFinite(a) ? a : startA;
}
// ── Shared-slope IRLS: estimate common slope across all groups ──────────
// Groups have separate intercepts (fixed via current estimates), slope is common.
// Iterates: given current {a_j}, update b; then update each a_j given b.
function fitCommonSlope(grpPts, initAs, initB, invLink, linkDeriv, varFn) {
const isLogit = Math.abs(invLink(0) - 0.5) < 0.01;
let b = initB;
let as = [...initAs];
const J = grpPts.length;
for (let outer = 0; outer < 15; outer++) {
// ── Update b given current {a_j} ──
let sw = 0, sz = 0;
for (let j = 0; j < J; j++) {
for (const pt of grpPts[j]) {
const rawEta = as[j] + b * pt.x;
const eta = isLogit ? Math.max(-12, Math.min(12, rawEta)) : rawEta;
const mu = invLink(eta);
const dmu = linkDeriv(eta);
const v = varFn(mu);
const w = Math.max((dmu * dmu) / Math.max(v, 1e-10), 1e-12);
const dmuSafe = isLogit ? Math.max(dmu, 0.005) : Math.max(dmu, 1e-10);
const z = eta + (pt.y - mu) / dmuSafe;
sw += w * pt.x * pt.x;
sz += w * pt.x * (z - as[j]);
}
}
const nb = sw > 1e-12 ? sz / sw : b;
if (!isFinite(nb)) break;
const db = Math.abs(nb - b); b = nb;
// ── Update each a_j given b ──
let maxDA = 0;
for (let j = 0; j < J; j++) {
const na = fitIntercept(grpPts[j], b, invLink, linkDeriv, varFn, as[j]);
maxDA = Math.max(maxDA, Math.abs(na - as[j]));
as[j] = na;
}
if (db < 1e-7 && maxDA < 1e-7) break;
}
return {b, as};
}
function mmEst(p) {
const totalJ = trueGrp.length;
const m = MODELS[modelKey];
// Per-group free fits (used for no-pooling with random slopes, and for initialisation)
const grpFit = Array.from({length:totalJ}, (_,j) => fitGLM(data.filter(d=>d.gid===j)));
const cpFit = fitGLM(data);
const grpPts = Array.from({length:totalJ}, (_,j) => data.filter(d=>d.gid===j));
// ── Get link function details ──────────────────────────────────────
let invLink, linkDeriv, varFn;
if (modelKey === 'gauss') {
invLink = η => η; linkDeriv = η => 1; varFn = μ => 1;
} else if (modelKey === 'poisson') {
invLink = η => Math.exp(η); linkDeriv = η => Math.exp(η); varFn = μ => Math.max(μ,1e-9);
} else if (modelKey === 'gamma') {
invLink = η => Math.exp(η); linkDeriv = η => Math.exp(η); varFn = μ => Math.max(μ*μ,1e-9);
} else { // logistic
invLink = η => 1/(1+Math.exp(-η));
linkDeriv = η => { const s=1/(1+Math.exp(-η)); return Math.max(s*(1-s),1e-9); };
varFn = μ => Math.max(μ*(1-μ),1e-9);
}
let npFit, feA, feB;
if (reMode === 'int') {
// ── Estimate common slope + per-group intercepts (within estimator) ──
// This is the closest JavaScript approximation to lme4's Laplace MLE for γ₁₀.
// Gaussian: exact (OLS within). GLMMs: PQL-like approximation.
const initAs = grpFit.map(g => g.a);
const initB = grpFit.reduce((s,g,j)=>s+g.b*trueGrp[j].nj,0)/data.length;
const {b: commonB, as: groupAs} = fitCommonSlope(
grpPts, initAs, initB, invLink, linkDeriv, varFn
);
npFit = groupAs.map((a, j) => ({a, b: commonB}));
feB = commonB;
feA = npFit.reduce((s,g,j)=>s+g.a*trueGrp[j].nj,0)/data.length;
} else {
// ── Random slopes: use per-group free fits ──────────────────────
npFit = grpFit;
feA = grpFit.reduce((s,g,j)=>s+g.a*trueGrp[j].nj,0)/data.length;
feB = grpFit.reduce((s,g,j)=>s+g.b*trueGrp[j].nj,0)/data.length;
}
// ── Theoretical Level-1 Variance for Shrinkage λ and ICC/R² ──
// For Gaussian: Level-1 variance = σ² (free parameter, from slider)
// For Logistic: Theoretical logistic variance = π²/3 ≈ 3.29
// (Nakagawa & Schielzeth 2013, standard in R's performance::r2_nakagawa)
// For Poisson: Nakagawa log-normal approximation = log(1 + 1/λ̄)
// where λ̄ = exp(γ̂₀₀) is the mean count on response scale
// For Gamma: With log-link and dispersion φ, Level-1 var ≈ log(1 + φ)
// We estimate φ from data (φ̂ = σ² since we parameterise CV=σ)
// Approximation: log(1 + p.sig²)
let v_lvl1_est = p.sig**2; // Gaussian default
if (modelKey === 'logistic') {
v_lvl1_est = Math.PI * Math.PI / 3; // ≈ 3.290
} else if (modelKey === 'poisson') {
// Use actual data mean count for Nakagawa approximation (more stable than exp(feA))
const lambdaBarEst = Math.max(data.reduce((s,d)=>s+d.y,0)/Math.max(data.length,1), 0.1);
v_lvl1_est = Math.log(1 + 1 / lambdaBarEst);