-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBrms_model_builder.html
More file actions
1831 lines (1690 loc) · 94.5 KB
/
Copy pathBrms_model_builder.html
File metadata and controls
1831 lines (1690 loc) · 94.5 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">
<meta name="description" content="brms Code-Generator fuer Bayesianische Regressionsmodelle: Gaussian, Bernoulli, Poisson, ordinal, Zero-inflated. Mit Random Effects und automatischer Prior-Spezifikation.">
<meta name="keywords" content="brms, Bayesianische Regression, R, Random Effects, Prior, Stan, Multilevel, GLMM, Code Generator">
<meta property="og:title" content="brms Model Builder">
<meta property="og:description" content="brms Code-Generator fuer Bayesianische Regressionsmodelle: Gaussian, Bernoulli, Poisson, ordinal, Zero-inflated. Mit Random Effects und automatischer Prior-Spezifikation.">
<meta property="og:type" content="website">
<meta property="og:url" content="https://www.bayes-thinking-lab.uni-osnabrueck.de/Brms_model_builder.html">
<meta property="og:site_name" content="Bayes Thinking Lab">
<link rel="canonical" href="https://www.bayes-thinking-lab.uni-osnabrueck.de/Brms_model_builder.html">
<title>brms Model Builder v17</title>
<script>
MathJax = {
tex: { inlineMath:[['$','$']], displayMath:[['$$','$$'],['\\[','\\]']], tags:'none' },
options: { skipHtmlTags:['script','noscript','style','textarea'] },
startup: {
typeset: false,
ready() {
MathJax.startup.defaultReady();
// Typeset the math content that was rendered before MathJax finished loading
const el = document.getElementById('math-content');
if (el && el.innerHTML) MathJax.typesetPromise([el]).catch(()=>{});
}
}
};
</script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.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');
html{font-size:18px}
:root {
--bg:#f5f0e8;--paper:#fdfaf4;--ink:#1a1410;--ink2:#4a3f35;--ink3:#8a7f72;
--accent:#c94a2a;--accent2:#748735;--accent3:#5a8a2a;--accent4:#8a3a8a;
--accent5:#b85c00;--accent6:#0e7c7b;
--grid:#e0d8cc;--panel:#eee8da;--border:#c0b8a8;--shadow:rgba(0,0,0,.06);
}
[data-theme="dark"] {
--bg:#0f1117;--paper:#171b25;--ink:#e8e2d8;--ink2:#9a9080;--ink3:#5a5448;
--accent:#e8614a;--accent2:#7F943A;--accent3:#7ec850;--accent4:#c87ad8;
--accent5:#e07830;--accent6:#2bc7c4;
--grid:#252a36;--panel:#1e2230;--border:#333a4a;--shadow:rgba(0,0,0,.4);
}
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:'Fraunces',Georgia,serif;background:var(--bg);color:var(--ink);
display:flex;flex-direction:column;height:100vh;overflow:hidden;transition:background .25s,color .25s}
#appmain{display:flex;flex:1;min-height:0;overflow:hidden}
#sidebar{width:340px;flex-shrink:0;background:var(--paper);border-right:1.5px solid var(--border);
overflow-y:auto;padding:.85rem .95rem 2rem;display:flex;flex-direction:column;gap:.6rem}
#preview{flex-grow:1;overflow-y:auto;padding:1.3rem 1.8rem 3rem;background:var(--bg)}
/* ── 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(--accent2)}
.hdr-sub2{font-family:'DM Mono',monospace;font-size:.75rem;color:var(--ink2);margin-top:.2rem;letter-spacing:.03em}
.hdr-btns{display:flex;gap:.4rem;align-items:center}
.hbtn{font-family:'DM Mono',monospace;font-size:.75rem;background:var(--panel);border:1.5px solid var(--border);color:var(--ink2);padding:.22rem .6rem;cursor:pointer;transition:all .15s}
.hbtn:hover{border-color:var(--accent2);color:var(--accent2)}
.hbtn.act{background:var(--accent2);color:var(--paper);border-color:var(--accent2)}
/* Sidebar-interner Header */
.hdr-title{font-size:1.3rem;font-weight:300;letter-spacing:-.02em;line-height:1.2}
.hdr-title em{font-style:italic;color:var(--accent2)}
.hdr-sub{font-family:'DM Mono',monospace;font-size:.75rem;color:var(--ink2);margin-top:.15rem;letter-spacing:.03em}
.hdr-auth{font-family:'DM Mono',monospace;font-size:.75rem;color:var(--ink2);opacity:.5;margin-top:.1rem}
.hbtns{display:flex;gap:.3rem;flex-wrap:wrap;margin-top:.5rem}
/* Buttons */
.ibtn{font-family:'DM Mono',monospace;font-size:.75rem;padding:.28rem .65rem;
border:1.5px solid var(--border);background:transparent;cursor:pointer;
letter-spacing:.04em;color:var(--ink);transition:all .15s;white-space:nowrap}
.ibtn:hover{background:var(--ink);color:var(--bg)}
.ibtn.xfer-out{border-color:var(--accent3);color:var(--accent3)}
.ibtn.xfer-out:hover{background:var(--accent3);color:white}
.ibtn.xfer-in{border-color:var(--accent4);color:var(--accent4)}
.ibtn.xfer-in:hover{background:var(--accent4);color:white}
/* Cards */
.scard{background:var(--paper);border:1.5px solid var(--border);padding:.75rem .9rem;
box-shadow:2px 2px 0 var(--shadow)}
.scard h3{font-family:'DM Mono',monospace;font-size:.75rem;letter-spacing:.11em;text-transform:uppercase;
color:var(--accent2);margin-bottom:.48rem;padding-bottom:.2rem;border-bottom:1px solid var(--grid)}
.scard h3.ha{color:var(--accent)}.scard h3.hg{color:var(--accent3)}.scard h3.hp{color:var(--accent4)}
/* Form elements */
.pg{margin-bottom:.42rem}
.lbl{font-family:'DM Mono',monospace;font-size:.75rem;color:var(--ink);display:block;margin-bottom:.15rem}
select,input[type=text]{width:100%;font-family:'DM Mono',monospace;font-size:.68rem;
background:var(--panel);border:1px solid var(--grid);color:var(--ink);
padding:.26rem .4rem;outline:none;cursor:pointer}
select:focus,input[type=text]:focus{border-color:var(--accent2)}
input[type=number]{font-family:'DM Mono',monospace;font-size:.72rem;background:var(--panel);
border:1px solid var(--grid);color:var(--ink);padding:.24rem .38rem;outline:none;width:100%}
input[type=number]:focus{border-color:var(--accent2)}
input[type=checkbox]{cursor:pointer;accent-color:var(--accent2);width:auto!important}
/* Model tabs */
.rbtn{font-family:'DM Mono',monospace;font-size:.75rem;padding:.24rem .6rem;
border:1.5px solid var(--border);background:transparent;cursor:pointer;
color:var(--ink2);transition:all .13s}
.rbtn:hover,.rbtn.sel{background:var(--accent2);color:white;border-color:var(--accent2)}
/* Tags (interactions) */
.tag{font-family:'DM Mono',monospace;font-size:.75rem;background:rgba(42,110,138,.1);
color:var(--accent2);padding:.16rem .48rem;border:1px solid var(--accent2);
cursor:pointer;display:inline-flex;align-items:center;gap:.3rem;margin:.1rem}
.tag:hover{background:var(--accent2);color:white}
/* Predictor blocks */
.pred-block{border:1px solid var(--grid);padding:.42rem .52rem;margin-bottom:.25rem}
.pred-hdr{display:flex;justify-content:space-between;align-items:center;margin-bottom:.28rem}
.pred-idx{font-family:'DM Mono',monospace;font-size:.75rem;color:var(--accent3)}
.pred-rm{font-family:'DM Mono',monospace;font-size:.75rem;border:1px solid var(--grid);
background:transparent;cursor:pointer;color:var(--ink2);padding:.05rem .28rem;transition:all .1s}
.pred-rm:hover{background:var(--accent);color:white;border-color:var(--accent)}
.add-pred{font-family:'DM Mono',monospace;font-size:.75rem;border:1px dashed var(--grid);
background:transparent;cursor:pointer;color:var(--ink2);padding:.22rem;
width:100%;transition:all .12s}
.add-pred:hover{border-color:var(--accent3);color:var(--accent3)}
/* Prior rows */
.prior-row{display:grid;grid-template-columns:1.1fr 1.6fr;gap:.3rem;align-items:center;margin-bottom:.3rem}
.prior-note{font-family:'DM Mono',monospace;font-size:.72rem;color:var(--ink2);line-height:1.6;
background:var(--panel);border-left:3px solid var(--accent4);
padding:.4rem .55rem;margin-bottom:.5rem}
.prior-note code{color:var(--ink)}
.prior-lbl{font-family:'DM Mono',monospace;font-size:.75rem;color:var(--ink2);
background:var(--panel);padding:.22rem .38rem;overflow:hidden;text-overflow:ellipsis;
white-space:nowrap;border:1px solid var(--grid);display:flex;align-items:center;gap:.2rem}
.prior-inp{font-family:'DM Mono',monospace;font-size:.72rem;background:var(--panel);
border:1px solid var(--grid);color:var(--ink);padding:.22rem .38rem;outline:none;width:100%}
.prior-inp:focus{border-color:var(--accent2)}
.prior-class{display:inline-block;font-family:'DM Mono',monospace;font-size:.75rem;
padding:.08rem .3rem;margin-right:.28rem;border-radius:0;opacity:.85}
.pc-b{background:rgba(90,138,42,.18);color:var(--accent3)}
.pc-i{background:rgba(42,110,138,.18);color:var(--accent2)}
.pc-s{background:rgba(184,92,0,.18);color:var(--accent5)}
.pc-n{background:rgba(14,124,123,.18);color:var(--accent6)}
.pc-sd{background:rgba(138,58,138,.18);color:var(--accent4)}
/* Sub-section */
.sub-section{background:var(--panel);border-left:3px solid var(--accent3);padding:.55rem .7rem;margin-top:.3rem}
/* Infobox */
.infobox{padding:.35rem .55rem;background:var(--panel);border-left:3px solid var(--accent2);
font-family:'DM Mono',monospace;font-size:.63rem;line-height:1.65;color:var(--ink2);margin-top:.32rem}
.infobox b{color:var(--ink)}
/* Grid layouts */
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:.5rem}
.grid4{display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:.4rem}
/* Code block */
.codewrap{background:#090c12;border:1.5px solid var(--border);box-shadow:2px 2px 0 var(--shadow);
overflow:hidden;margin-bottom:1rem}
[data-theme="light"] .codewrap{background:#1a1410}
.code-hdr{display:flex;justify-content:space-between;align-items:center;
padding:.38rem .7rem;border-bottom:1px solid #1e2535}
[data-theme="light"] .code-hdr{border-bottom-color:#2a2520}
.code-lbl{font-family:'DM Mono',monospace;font-size:.75rem;color:#556080;letter-spacing:.06em;text-transform:uppercase}
.copy-btn{font-family:'DM Mono',monospace;font-size:.75rem;padding:.15rem .48rem;border:1px solid #334;
background:transparent;cursor:pointer;color:#9eabc2;transition:all .12s}
.copy-btn:hover{border-color:var(--accent2);color:var(--accent2)}
.codeblk{padding:.7rem 1rem;font-family:'DM Mono',monospace;font-size:.76rem;line-height:1.9;
color:#9eabc2;white-space:pre;overflow-x:auto}
[data-theme="light"] .codeblk{color:#b0a890}
.kw{color:var(--accent5)}.fn{color:var(--accent2)}.str{color:var(--accent3)}.cm{color:var(--ink2)}.nm{color:#9a7a20}.num{color:var(--accent4)}
[data-theme="dark"] .nm{color:#c8a840}
/* Math block */
.math-block{background:var(--paper);border:1.5px solid var(--border);padding:1.2rem 1.5rem;
box-shadow:2px 2px 0 var(--shadow);margin-bottom:1rem;overflow-x:auto}
.math-sec{font-family:'DM Mono',monospace;font-size:.75rem;letter-spacing:.1em;text-transform:uppercase;
color:var(--ink2);margin-bottom:.6rem;padding-bottom:.2rem;border-bottom:1px solid var(--grid)}
.math-sec.ca{color:var(--accent2)}.math-sec.cg{color:var(--accent3)}.math-sec.cp{color:var(--accent4)}.math-sec.cr{color:var(--accent)}.math-sec.cs{color:var(--accent5)}.math-sec.cn{color:var(--accent6)}
.math-row{margin-bottom:.4rem}
/* Preview header */
.pvw-hdr{display:flex;justify-content:space-between;align-items:baseline;margin-bottom:1rem;flex-wrap:wrap;gap:.5rem}
.pvw-title{font-size:1.05rem;font-weight:300;letter-spacing:-.01em}
.pvw-title em{font-style:italic;color:var(--accent)}
/* panel header inline button */
.panel-btn{font-family:'DM Mono',monospace;font-size:.75rem;padding:.2rem .5rem;
border:1px solid var(--border);background:transparent;cursor:pointer;
color:var(--ink2);transition:all .15s;white-space:nowrap}
.panel-btn:hover{background:var(--ink);color:var(--bg)}
/* Toast */
#toast{position:fixed;bottom:1.2rem;right:1.2rem;background:var(--accent2);color:white;
font-family:'DM Mono',monospace;font-size:.75rem;padding:.52rem .95rem;
box-shadow:3px 3px 0 rgba(0,0,0,.25);z-index:9999;
transition:opacity .35s,transform .35s;opacity:0;transform:translateY(8px);pointer-events:none}
#toast.show{opacity:1;transform:translateY(0)}
/* ── Intercept-Prior Info Modal ─────────────────────────── */
#ipm-overlay{
position:fixed;inset:0;z-index:9800;
background:rgba(0,0,0,.68);backdrop-filter:blur(3px);
display:none;align-items:center;justify-content:center;padding:1.5rem;
}
#ipm-overlay.open{display:flex}
#ipm-modal{
max-width:600px;width:100%;
background:var(--paper);border:2px solid var(--accent);
box-shadow:0 0 40px rgba(232,97,74,.18),0 16px 48px rgba(0,0,0,.55);
position:relative;
}
#ipm-header{
display:flex;align-items:center;justify-content:space-between;
padding:.75rem 1.1rem .65rem;background:var(--accent);
}
#ipm-header span{font-family:'DM Mono',monospace;font-size:.78rem;font-weight:500;
color:white;letter-spacing:.04em;display:flex;align-items:center;gap:.45rem;}
#ipm-close{font-family:'DM Mono',monospace;font-size:.75rem;
border:1.5px solid rgba(255,255,255,.55);background:transparent;
cursor:pointer;color:white;padding:.2rem .6rem;transition:all .15s;}
#ipm-close:hover{background:rgba(255,255,255,.18)}
#ipm-body{padding:1.1rem 1.3rem 1.25rem;font-family:'DM Mono',monospace;
font-size:.75rem;line-height:1.85;color:var(--ink2)}
#ipm-body b{color:var(--ink)}
#ipm-body code{background:var(--panel);border:1px solid var(--border);
color:var(--accent2);padding:.06rem .38rem;font-size:.75rem;letter-spacing:.01em;}
#ipm-body .ipm-strong{display:block;margin-top:.85rem;padding:.5rem .75rem;
background:var(--accent);color:white;font-weight:500;font-size:.75rem;}
/* ── FLOATING HELP PANEL ─────────────────────────── */
@keyframes brms-slideIn { from{opacity:0;transform:translateX(10px)} to{opacity:1;transform:translateX(0)} }
/* .brms-help-btn dient nur noch als JS-Hook (Click-Outside); Styling kommt von .hbtn */
#brms-help-panel {
display:none; position:fixed; right:1.5rem; top:50%;
transform:translateY(-50%); width:320px; z-index:600;
background:var(--paper); border:1.5px solid var(--border);
box-shadow:4px 4px 0 rgba(0,0,0,.14);
animation:brms-slideIn .18s ease-out;
}
#brms-help-panel.open { display:block; }
.brms-hp-head {
display:flex; justify-content:space-between; align-items:center;
padding:.55rem .9rem; border-bottom:1px solid var(--border);
background:rgba(42,110,138,.08);
}
.brms-hp-label {
font-family:'DM Mono',monospace; font-size:.6rem;
letter-spacing:.1em; text-transform:uppercase; color:var(--accent2); font-weight:500;
}
.brms-hp-close {
font-family:'DM Mono',monospace; font-size:.85rem;
background:transparent; border:none; cursor:pointer;
color:var(--ink3); padding:0 .15rem; line-height:1;
}
.brms-hp-close:hover { color:var(--ink); }
.brms-hp-body {
padding:.85rem .9rem; font-family:'DM Mono',monospace;
font-size:.67rem; line-height:1.8; color:var(--ink2);
max-height:75vh; overflow-y:auto;
}
.brms-hp-sect {
font-size:.52rem; letter-spacing:.1em; text-transform:uppercase;
color:var(--accent2); margin-top:.9rem; margin-bottom:.3rem;
border-bottom:1px solid var(--border); padding-bottom:.18rem;
}
.brms-hp-sect:first-child { margin-top:0; }
.brms-hp-body strong { color:var(--ink); }
.brms-hp-body ul { padding-left:.1rem; }
.brms-hp-body li { list-style:none; padding:.08rem 0; }
.brms-hp-body li::before { content:'·'; color:var(--accent2); margin-right:.4rem; }
.brms-hp-tip {
margin-top:.8rem; padding:.45rem .6rem;
border-left:3px solid var(--accent2); background:var(--panel);
font-size:.65rem; color:var(--ink2);
}
</style>
</head>
<body>
<!-- ═══ TOP BAR ══════════════════════════════════════════════ -->
<div id="hdr" class="hdr-hrow">
<div>
<div class="hdr-h1">brms <em>Model Builder</em></div>
<div class="hdr-sub2">15 Likelihoods · Priors · Distributional Models · McElreath-Notation · brms-Code</div>
<div class="hdr-auth">© Dr. Rainer Düsing · Interactive Tools by Claude</div>
</div>
<div class="hdr-btns">
<button class="hbtn" onclick="window.open('index_de.html','_self')" style="border-color:var(--accent2);color:var(--accent2)">← Übersicht</button>
<button class="hbtn" onclick="window.open('Bayesian_PP_Check.html','_blank')" style="border-color:var(--accent2);color:var(--accent2)">Weiter → PP Check</button>
<button class="hbtn" id="btn-send-ppc" onclick="exportToPPC()" style="border-color:var(--accent3);color:var(--accent3)" title="Modell an PP-Check senden">⬡ → PP-Check</button>
<button class="hbtn" onclick="window.open('https://raduesing.shinyapps.io/btl-posterior-ppc/','_blank')" style="border-color:var(--accent5);color:var(--accent5)" title="Posterior Predictive Check — echtes Modell hochladen und prüfen">⬡ → Posterior PPC</button>
<button class="hbtn brms-help-btn" onclick="toggleBrmsHelp()" style="border-color:var(--accent);color:var(--accent)">ℹ Hilfe</button>
<button class="hbtn" id="btn-theme" onclick="toggleTheme()">☀ Light</button>
</div>
</div>
<div id="appmain">
<!-- ═══ SIDEBAR ═══════════════════════════════════════════════ -->
<div id="sidebar">
<!-- 1. Likelihood -->
<div class="scard">
<h3>1 · Likelihood</h3>
<div class="pg">
<span class="lbl">Verteilungsfamilie</span>
<select id="fam-select" onchange="setFamilyFromSelect()" style="font-size:.75rem">
<optgroup label="── Stetig ──────────────────────">
<option value="gaussian" selected>Gaussian — Normal(μ, σ)</option>
<option value="student">Student-t — t(ν, μ, σ)</option>
<option value="lognormal">Lognormal — LN(μ, σ)</option>
<option value="shifted_lognormal">Shifted Lognormal — SLN(μ, σ, δ)</option>
<option value="skew_normal">Skew-Normal — SN(μ, σ, ξ)</option>
<option value="Gamma">Gamma — Gamma(μ, φ)</option>
</optgroup>
<optgroup label="── Zähldaten ───────────────────">
<option value="poisson">Poisson — Poisson(λ)</option>
<option value="negbinomial">Neg. Binomial — NB(μ, φ)</option>
</optgroup>
<optgroup label="── Binär / Proportionen ────────">
<option value="bernoulli">Bernoulli — Bernoulli(p)</option>
<option value="Beta">Beta — Beta(μ, φ)</option>
<option value="binomial">Binomial — Binomial(n, p)</option>
<option value="beta_binomial">Beta-Binomial — BB(n, μ, φ)</option>
<option value="zero_inflated_beta">ZI-Beta — ZIBeta(μ, φ, π)</option>
<option value="zero_one_inflated_beta">ZOI-Beta — ZOIB(μ, φ, ζ, κ)</option>
</optgroup>
<optgroup label="── Ordinal / Nominal ───────────">
<option value="cumulative">Kumulativ (ordinal) — logit</option>
<option value="categorical">Kategorisch (nominal)</option>
</optgroup>
</select>
</div>
<div class="pg">
<span class="lbl">Outcome-Variable (y)</span>
<input type="text" id="outcome" value="Y" oninput="update()">
</div>
<div class="pg" id="trials-row" style="display:none">
<span class="lbl" title="Für beta_binomial: Anzahl Trials pro Beobachtung">Trials-Variable (| trials(...))</span>
<input type="text" id="trials-var" value="trials" oninput="update()">
</div>
</div>
<!-- 2. Prädiktoren -->
<div class="scard">
<h3 class="hg">2 · Prädiktoren (Fixed Effects)</h3>
<div id="pred-list"></div>
<button class="add-pred" onclick="addPredictor()">+ Prädiktor hinzufügen</button>
</div>
<!-- 3. Interaktionen -->
<div class="scard">
<h3 class="hg">3 · Interaktionen</h3>
<div class="pg">
<span class="lbl">Interaktion eingeben (z.B. x1:x2) + Enter</span>
<input type="text" id="inter-input" placeholder="z.B. age:sex"
onkeydown="if(event.key==='Enter')addInter()">
</div>
<div id="inter-tags" style="min-height:.5rem"></div>
</div>
<!-- 4. Distributional -->
<div class="scard" id="dist-card">
<h3 class="hp">4 · Distributional Model</h3>
<div class="infobox" style="margin-bottom:.5rem">
<b>Optional:</b> Auxiliary-Parameter (σ, ν) können selbst als Funktion von Prädiktoren modelliert werden — ein <em>distributional model</em> in brms.
</div>
<div id="dist-area"></div>
</div>
<!-- 5. Random Effects -->
<div class="scard">
<h3>5 · Random Effects</h3>
<label style="display:flex;align-items:center;gap:.5rem;cursor:pointer;font-family:'DM Mono',monospace;font-size:.75rem">
<input type="checkbox" id="has-re" onchange="update()"> Random Effects aktivieren
</label>
<div id="re-ui" style="display:none;margin-top:.5rem">
<div class="sub-section">
<div class="pg">
<span class="lbl">Gruppierungsvariable</span>
<input type="text" id="group-var" value="subject" oninput="update()">
</div>
<div class="pg">
<span class="lbl">Struktur</span>
<select id="re-type" onchange="update()">
<option value="int">Random Intercept only (1 | group)</option>
<option value="slope">Random Intercept + Slope (1 + x | group)</option>
</select>
</div>
<div id="re-slope-area" style="display:none">
<span class="lbl">Slope-Prädiktoren (Variablennamen, kommagetrennt)</span>
<input type="text" id="re-slope-vars" placeholder="z.B. time, age" oninput="update()">
</div>
</div>
</div>
</div>
<!-- 6. Priors -->
<div class="scard">
<h3 class="ha">6 · Priors</h3>
<div class="infobox" style="margin-bottom:.5rem;font-size:.75rem">
Priors im brms-Format: <b>normal(0,2.5)</b> · <b>exponential(1)</b> · <b>student_t(3,0,1)</b> · <b>cauchy(0,2.5)</b> · <b>gamma(2,0.1)</b> · <b>lkj(2)</b>
</div>
<div id="prior-list"></div>
</div>
<!-- 7. Sampling -->
<div class="scard">
<h3>7 · Sampling & Speichern</h3>
<div class="grid2">
<div class="pg"><span class="lbl">Iterationen</span><input type="number" id="iter" value="2000" oninput="update()"></div>
<div class="pg"><span class="lbl">Warmup</span><input type="number" id="warm" value="1000" oninput="update()"></div>
<div class="pg"><span class="lbl">Chains</span><input type="number" id="chains" value="4" oninput="update()"></div>
<div class="pg"><span class="lbl">Cores</span><input type="number" id="cores" value="4" oninput="update()"></div>
</div>
<div class="pg" style="margin-top:.3rem">
<span class="lbl">Backend</span>
<select id="backend" onchange="update()">
<option value="rstan">rstan</option>
<option value="cmdstanr">cmdstanr</option>
</select>
</div>
<div class="pg" style="margin-top:.3rem">
<span class="lbl" title="adapt_delta: Ziel-Akzeptanzrate (Standard 0.80). Bei Divergenzen auf 0.90–0.99 erhöhen.">adapt_delta</span>
<input type="number" id="adapt-delta" value="0.80" min="0.5" max="0.999" step="0.01" oninput="update()">
</div>
<div class="pg">
<span class="lbl" title="max_treedepth: Maximale NUTS-Baumtiefe. Standard 10. Bei Warnungen auf 12–15 erhöhen.">max_treedepth</span>
<input type="number" id="max-tree" value="10" min="5" max="20" step="1" oninput="update()">
</div>
<div class="pg" style="margin-top:.3rem">
<span class="lbl" title="Dateiname zum Cachen des Fits (ohne .rds). Leer = nicht speichern.">fit speichern als</span>
<input type="text" id="fit-file" placeholder="z.B. model_m1 (leer = kein file=)" oninput="update()" style="font-family:'DM Mono',monospace;font-size:.75rem">
</div>
<div class="pg">
<span class="lbl">Fit-Objekt</span>
<input type="text" id="fit-name" value="fit" placeholder="fit" oninput="update()" style="font-family:'DM Mono',monospace;font-size:.75rem">
</div>
</div>
</div><!-- /sidebar -->
<!-- ═══ PREVIEW ══════════════════════════════════════════════ -->
<div id="preview">
<div class="pvw-hdr">
<div class="pvw-title">Mathematisches <em>Modell</em></div>
<div style="display:flex;align-items:center;gap:.5rem">
<div style="font-family:'DM Mono',monospace;font-size:.75rem;color:var(--ink2)">McElreath-Notation · Live-Vorschau</div>
<button class="panel-btn" onclick="downloadLatex()" title="Formel als .tex exportieren">↓ LaTeX</button>
</div>
</div>
<!-- Math -->
<div class="math-block" id="math-block">
<div class="math-sec ca">Likelihood & Lineare Prädiktoren</div>
<div id="math-content" style="font-size:.92rem;line-height:2.2"></div>
</div>
<!-- R Code -->
<div class="codewrap">
<div class="code-hdr">
<span class="code-lbl">R · brms</span>
<div style="display:flex;gap:.35rem;align-items:center">
<button onclick="ipmOpen()" title="Hinweis: brms Intercept-Prior"
style="font-family:'DM Mono',monospace;font-size:.75rem;padding:.15rem .5rem;
border:1.5px solid var(--accent);background:transparent;cursor:pointer;
color:var(--accent);letter-spacing:.03em;transition:all .15s"
onmouseover="this.style.background=getComputedStyle(document.documentElement).getPropertyValue('--accent');this.style.color='white'"
onmouseout="this.style.background='transparent';this.style.color=getComputedStyle(document.documentElement).getPropertyValue('--accent')"
>⚠ Intercept-Prior</button>
<button class="copy-btn" onclick="copyCode()">📋 Kopieren</button>
<button class="panel-btn" onclick="downloadR()" title="Als .R Datei speichern">↓ .R</button>
</div>
</div>
<div class="codeblk" id="code-block">Code wird generiert …</div>
</div>
</div>
</div>
<div id="toast"></div>
<script>
'use strict';
// ═══════════════════════════════════════════════════════════
// STATE
// ═══════════════════════════════════════════════════════════
let FAMILY = 'gaussian';
let DARK = true;
let predictorNames = []; // empty = intercept-only model by default
let predictorDegrees = []; // polynomial degree per predictor (1 = linear)
let nextPredId = 1;
let inters = [];
let userPriors = {};
let trialsVar = 'trials'; // for beta_binomial
const DEF_PRIORS = {
Intercept: 'normal(0, 5)',
b: 'normal(0, 2)',
sigma: 'exponential(1)',
nu: 'gamma(2, 0.1)',
sd: 'normal(0, 1)',
cor: 'lkj(2)',
dist_int: 'normal(0, 1)',
dist_b: 'normal(0, 0.5)',
// New families
phi: 'exponential(1)', // Beta, ZI-Beta, ZOIB, beta_binomial
shape: 'exponential(1)', // Gamma, negbinomial
ndt: 'normal(0, 0.3)', // shifted_lognormal (lb=0)
alpha_skew: 'normal(0, 2)', // skew_normal skewness (dpar=alpha)
zi: 'beta(1, 1)', // zero_inflated_beta
zoi: 'beta(1, 1)', // zero_one_inflated_beta
coi: 'beta(1, 1)', // zero_one_inflated_beta
};
// family → PPC model name
const FAM2PPC = {
gaussian:'linear', student:'student',
bernoulli:'logistic', poisson:'poisson',
Gamma:'gamma', lognormal:'lognormal',
shifted_lognormal:'shifted_lognormal', skew_normal:'skew_normal',
negbinomial:'negbinomial', binomial:'binomial',
beta_binomial:'beta_binomial', Beta:'beta_reg',
zero_inflated_beta:'zero_inflated_beta',
zero_one_inflated_beta:'zero_one_inflated_beta',
cumulative:'cumulative', categorical:'categorical'
};
const PPC2FAM = {
linear:'gaussian', gaussian:'gaussian',
student:'student', logistic:'bernoulli',
poisson:'poisson', gamma:'Gamma',
lognormal:'lognormal', shifted_lognormal:'shifted_lognormal',
skew_normal:'skew_normal', negbinomial:'negbinomial',
beta_reg:'Beta', binomial:'binomial',
beta_binomial:'beta_binomial',
zero_inflated_beta:'zero_inflated_beta',
zero_one_inflated_beta:'zero_one_inflated_beta',
cumulative:'cumulative', categorical:'categorical'
};
// Parameter set membership — drives prior rows + distributional card
const HAS_SIGMA = new Set(['gaussian','student','lognormal','shifted_lognormal','skew_normal']);
const HAS_NU = new Set(['student']);
const HAS_SHAPE = new Set(['Gamma','negbinomial']); // class=shape in brms
const HAS_PHI = new Set(['Beta','beta_binomial','zero_inflated_beta','zero_one_inflated_beta']); // class=phi
const HAS_NDT = new Set(['shifted_lognormal']); // class=ndt
const HAS_ALPHA_SKEW = new Set(['skew_normal']); // class=alpha (skewness)
const HAS_ZI = new Set(['zero_inflated_beta']); // class=zi
const HAS_ZOI = new Set(['zero_one_inflated_beta']); // class=zoi
const HAS_COI = new Set(['zero_one_inflated_beta']); // class=coi
const IS_ORDINAL = new Set(['cumulative']);
const IS_CATEGORICAL = new Set(['categorical']);
// Distributional link info per parameter
const DIST_LINK = {
sigma:'log', phi:'log', shape:'log', ndt:'log',
alpha:'id',
// brms's student() family defaults to link_nu = "logm1" (η = log(ν−1), ensuring
// ν>1), NOT identity — confirmed via student()$link_nu in brms 2.x. The generated
// R code here never overrides it (no link_nu= argument), so brms's real default
// applies whenever ν is predicted via covariates; the notation must match that.
nu:'logm1',
zi:'logit', zoi:'logit', coi:'logit'
};
// Math display symbols for distributional parameters
const DIST_SYM = {
sigma:'\\sigma', phi:'\\phi', shape:'\\phi',
ndt:'\\delta', alpha:'\\xi', nu:'\\nu',
zi:'\\pi', zoi:'\\zeta', coi:'\\kappa'
};
// ═══════════════════════════════════════════════════════════
// THEME
// ═══════════════════════════════════════════════════════════
function toggleTheme() {
DARK = !DARK;
document.documentElement.setAttribute('data-theme', DARK ? 'dark' : 'light');
document.getElementById('btn-theme').textContent = DARK ? '☀ Light' : '🌙 Dark';
localStorage.setItem('btl-theme',DARK?'dark':'light');
}
// ═══════════════════════════════════════════════════════════
// FAMILY
// ═══════════════════════════════════════════════════════════
function setFamilyFromSelect() {
FAMILY = document.getElementById('fam-select').value;
// Reset Intercept and b priors so link-aware defaults apply for new family
delete userPriors['mu_int'];
Object.keys(userPriors).filter(k => k.startsWith('mu_b_')).forEach(k => delete userPriors[k]);
rebuildDistArea();
update();
}
function setFamily(val) {
// Called programmatically (e.g. from importFromPPC)
FAMILY = val;
const sel = document.getElementById('fam-select');
if (sel) sel.value = val;
rebuildDistArea();
update();
}
function gFamily() { return FAMILY; }
// ═══════════════════════════════════════════════════════════
// PREDICTORS
// ═══════════════════════════════════════════════════════════
function renderPredList() {
const c = document.getElementById('pred-list');
c.innerHTML = '';
predictorNames.forEach((name, i) => {
const div = document.createElement('div');
div.className = 'pred-block';
div.innerHTML = `
<div class="pred-hdr">
<span class="pred-idx">Prädiktor ${i+1}</span>
${predictorNames.length > 1 ? `<button class="pred-rm" onclick="removePredictor(${i})">✕</button>` : ''}
</div>
<input type="text" value="${name}" placeholder="Variablenname"
oninput="predictorNames[${i}]=this.value.trim()||'x${i+1}';update()">
<select style="font-size:.72rem;margin-top:.25rem;width:100%;font-family:'DM Mono',monospace"
onchange="predictorDegrees[${i}]=+this.value;update()">
<option value="1" ${(predictorDegrees[i]||1)===1?'selected':''}>linear (Grad 1)</option>
<option value="2" ${(predictorDegrees[i]||1)===2?'selected':''}>quadratisch — +I(x²)</option>
<option value="3" ${(predictorDegrees[i]||1)===3?'selected':''}>kubisch — +I(x²)+I(x³)</option>
</select>`;
c.appendChild(div);
});
}
function addPredictor() {
const n = predictorNames.length + 1;
predictorNames.push('x' + n);
predictorDegrees.push(1);
renderPredList();
update();
}
function removePredictor(idx) {
if (predictorNames.length <= 1) return;
predictorNames.splice(idx, 1);
predictorDegrees.splice(idx, 1);
renderPredList();
update();
}
// brms renames I(x^n)-style formula terms to valid Stan parameter names by dropping
// the parentheses and turning "^" into "E" (confirmed against brms::default_prior():
// "I(x1^2)" -> "Ix1E2"). Prior coef="..." strings must use this sanitized form, not
// the raw formula term, or brms rejects the prior as matching no model parameter.
function brmsCoefName(term) {
return term.replace(/[()]/g, '').replace(/\^/g, 'E');
}
// Expand predictor names to include polynomial terms: ['x1','I(x1^2)','I(x1^3)']
function expandPreds(names, degrees) {
const terms = [];
names.forEach((name, i) => {
terms.push(name);
const deg = (degrees && degrees[i]) || 1;
for (let d = 2; d <= deg; d++) terms.push(`I(${name}^${d})`);
});
return terms;
}
// Convert R polynomial term to LaTeX: 'I(x1^2)' → {betaSub:'x1^{2}', term:'x1_i^{2}'}
function predToLatex(p) {
const m = p.match(/^I\((\w+)\^(\d+)\)$/);
if (m) return { betaSub: `${m[1]}^{${m[2]}}`, term: `${m[1]}_i^{${m[2]}}` };
return { betaSub: p, term: `${p}_i` };
}
// ═══════════════════════════════════════════════════════════
// INTERACTIONS
// ═══════════════════════════════════════════════════════════
function addInter() {
const inp = document.getElementById('inter-input');
const v = inp.value.trim();
if (v && !inters.includes(v)) { inters.push(v); inp.value = ''; update(); }
}
function removeInter(idx) { inters.splice(idx, 1); update(); }
function renderInterTags() {
document.getElementById('inter-tags').innerHTML =
inters.map((t,i) => `<span class="tag" onclick="removeInter(${i})">${t} ✕</span>`).join('');
}
// ═══════════════════════════════════════════════════════════
// DISTRIBUTIONAL
// ═══════════════════════════════════════════════════════════
function rebuildDistArea() {
const f = gFamily();
// All distributional params per family
const DIST_PARAMS = {
gaussian: [{id:'sigma', label:'σ vorhersagen? (log-link)'}],
student: [{id:'sigma', label:'σ vorhersagen? (log-link)'}, {id:'nu', label:'ν vorhersagen? (logm1-Link: log(ν−1))'}],
lognormal: [{id:'sigma', label:'σ vorhersagen? (log-link)'}],
shifted_lognormal: [{id:'sigma', label:'σ vorhersagen? (log-link)'}, {id:'ndt', label:'δ (ndt) vorhersagen? (log-link)'}],
skew_normal: [{id:'sigma', label:'σ vorhersagen? (log-link)'}, {id:'alpha', label:'ξ (Schiefe) vorhersagen? (identity)'}],
Gamma: [{id:'shape', label:'φ (shape) vorhersagen? (log-link)'}],
negbinomial: [{id:'shape', label:'φ (shape) vorhersagen? (log-link)'}],
Beta: [{id:'phi', label:'φ (Präzision) vorhersagen? (log-link)'}],
beta_binomial: [{id:'phi', label:'φ (Präzision) vorhersagen? (log-link)'}],
zero_inflated_beta: [{id:'phi', label:'φ (Präzision) vorhersagen? (log-link)'}, {id:'zi', label:'π (Zero-Inflation) vorhersagen? (logit)'}],
zero_one_inflated_beta:[{id:'phi', label:'φ (Präzision) vorhersagen? (log-link)'}, {id:'zoi', label:'ζ (ZOI) vorhersagen? (logit)'}, {id:'coi', label:'κ (COI) vorhersagen? (logit)'}],
poisson: [], bernoulli: [], cumulative: [], categorical: [],
};
const params = DIST_PARAMS[f] || [];
const area = document.getElementById('dist-area');
const card = document.getElementById('dist-card');
card.style.display = params.length === 0 ? 'none' : '';
// Trials row for beta_binomial
const trow = document.getElementById('trials-row');
if (trow) trow.style.display = (f === 'beta_binomial' || f === 'binomial') ? '' : 'none';
area.innerHTML = params.map(p => `
<label style="display:flex;align-items:center;gap:.4rem;cursor:pointer;font-family:'DM Mono',monospace;font-size:.75rem;margin-bottom:.5rem">
<input type="checkbox" class="d-ck" data-p="${p.id}" onchange="update()" > ${p.label}
</label>
<div id="d-box-${p.id}" class="sub-section" style="display:none;margin-bottom:.4rem">
<span class="lbl">Prädiktoren für ${p.id} (kommagetrennt)</span>
<input type="text" class="d-pre" data-p="${p.id}" placeholder="z.B. x1, x2" oninput="update()">
</div>`).join('');
}
function getActiveDistParams() {
const out = [];
document.querySelectorAll('.d-ck').forEach(ck => {
const p = ck.dataset.p;
const box = document.getElementById('d-box-' + p);
if (box) box.style.display = ck.checked ? '' : 'none';
if (ck.checked) {
const inp = box.querySelector('input');
const preds = inp ? inp.value.split(',').map(s=>s.trim()).filter(Boolean) : [];
out.push({ n: p, preds });
}
});
return out;
}
// ═══════════════════════════════════════════════════════════
// PRIOR HELPERS
// ═══════════════════════════════════════════════════════════
function gPrior(id, cls, defOverride) {
if (!userPriors[id]) userPriors[id] = defOverride || DEF_PRIORS[cls] || 'normal(0, 1)';
return userPriors[id];
}
// Returns rows: [{id,label,cls,coef,dpar,sym}]
// Pure row computation, no DOM writes — safe to call on every keystroke inside a
// prior-value input. buildPriorSection() (below) additionally rebuilds the sidebar
// HTML from these rows; that rebuild destroys and recreates every <input> in the
// list (including the one currently focused), so it must NOT run on every keystroke
// — see schedPriorInput()/updatePriorDerived() for the keystroke-safe path.
function computePriorRows(preds, activeD, hasRE, g, reType, slopeVars) {
const rows = [];
const f = gFamily();
const addRow = (id, label, cls, coef, dpar, sym, defOverride, group) => {
rows.push({ id, label, cls, coef, dpar, sym, defOverride, group });
};
// Link-aware prior defaults
const LOG_LINK = new Set(['poisson','negbinomial','Gamma']);
const LOGIT_LINK = new Set(['bernoulli','binomial','Beta','beta_binomial',
'zero_inflated_beta','zero_one_inflated_beta']);
const defInt = LOG_LINK.has(f) ? 'normal(0, 1.0)'
: LOGIT_LINK.has(f) ? 'normal(0, 1.5)'
: 'normal(0, 2.5)'; // identity link
const defB = LOG_LINK.has(f) ? 'normal(0, 0.5)'
: LOGIT_LINK.has(f) ? 'normal(0, 1.0)'
: 'normal(0, 0.5)'; // identity link
// Intercept — explicit 0+Intercept parameterization (except ordinal thresholds)
const isOrdinal = f === 'cumulative' || f === 'categorical';
// categorical is NOT like cumulative here: brms fits one linear predictor per
// non-reference outcome category (dpar = "mu<category>"), so a single generic
// class=Intercept/class=b prior is invalid — brms rejects it ("do not correspond
// to any model parameter"). The number of categories depends on the user's actual
// data, which this tool never sees, so the correct dpar tags can't be generated
// here. Skip these rows entirely; buildRCode() adds an explanatory comment
// instead and lets brms fall back to its own per-category defaults.
const isCategoricalFam = f === 'categorical';
if (!isCategoricalFam) {
if (isOrdinal) {
addRow('mu_int', 'α Intercept', 'Intercept', null, null, '\\alpha', defInt);
} else {
addRow('mu_int', 'α Intercept', 'b', 'Intercept', null, '\\alpha', defInt);
}
// β per predictor (includes expanded polynomial terms like I(x1^2))
preds.forEach(p => {
const lt = predToLatex(p);
addRow('mu_b_' + p, 'β\u2009' + p, 'b', p, null, '\\beta_{' + lt.betaSub + '}', defB);
});
// β per interaction — coef uses : notation as required by brms
inters.forEach(ix =>
addRow('mu_b_' + ix, 'β\u2009' + ix, 'b', ix, null,
'\\beta_{' + ix.replace(/:/g, '\\!:\\!') + '}', defB));
}
// Distributional priors (log-scale) — use tighter defaults
activeD.forEach(d => {
const dLink = ['zi','zoi','coi'].includes(d.n) ? '(logit)'
: d.n === 'nu' ? '(logm1)'
: d.n === 'alpha' ? '(id)' : '(log)';
addRow(d.n + '_int', 'α\u2009' + d.n + ' ' + dLink, 'b', 'Intercept', d.n,
'\\alpha_{' + d.n + '}', DEF_PRIORS.dist_int);
d.preds.forEach(p =>
addRow(d.n + '_b_' + p, 'β\u2009' + d.n + '\u200B·\u200B' + p, 'b', p, d.n,
'\\beta_{' + d.n + ',' + p + '}', DEF_PRIORS.dist_b));
});
// Fixed scale params (only when NOT in distributional model)
if (HAS_SIGMA.has(f) && !activeD.find(d => d.n === 'sigma'))
addRow('fixed_sigma', 'σ', 'sigma', null, null, '\\sigma');
if (HAS_NU.has(f) && !activeD.find(d => d.n === 'nu'))
addRow('fixed_nu', 'ν', 'nu', null, null, '\\nu');
// New family parameters
if (HAS_SHAPE.has(f) && !activeD.find(d => d.n === 'shape'))
addRow('fixed_shape', 'φ · Shape', 'shape', null, null, '\\phi', DEF_PRIORS.shape);
if (HAS_PHI.has(f) && !activeD.find(d => d.n === 'phi'))
addRow('fixed_phi', 'φ · Präzision', 'phi', null, null, '\\phi', DEF_PRIORS.phi);
if (HAS_NDT.has(f) && !activeD.find(d => d.n === 'ndt'))
addRow('fixed_ndt', 'δ · ndt (lb=0)', 'ndt', null, null, '\\delta', DEF_PRIORS.ndt);
if (HAS_ALPHA_SKEW.has(f) && !activeD.find(d => d.n === 'alpha'))
addRow('fixed_alpha_skew', 'ξ · Schiefe (alpha)', 'alpha', null, null, '\\xi', DEF_PRIORS.alpha_skew);
if (HAS_ZI.has(f) && !activeD.find(d => d.n === 'zi'))
addRow('fixed_zi', 'π · Zero-Inflation (zi)', 'zi', null, null, '\\pi_0', DEF_PRIORS.zi);
if (HAS_ZOI.has(f) && !activeD.find(d => d.n === 'zoi'))
addRow('fixed_zoi', 'ζ · ZOI (zoi)', 'zoi', null, null, '\\zeta_0', DEF_PRIORS.zoi);
if (HAS_COI.has(f) && !activeD.find(d => d.n === 'coi'))
addRow('fixed_coi', 'κ · COI (coi)', 'coi', null, null, '\\kappa_0', DEF_PRIORS.coi);
// Notes for special families
if (IS_ORDINAL.has(f)) {
// Intercept class = K-1 thresholds in cumulative
// No extra params needed — the Intercept prior above covers thresholds
}
// Random effects priors — same dpar problem as the fixed effects above: brms needs
// sd(...)/cor(...) tagged per category for categorical models too (confirmed via
// default_prior()), and the category count still isn't known here. Skip these rows
// for categorical as well; the R-code comment covers both cases.
if (hasRE && !isCategoricalFam) {
// brms requires group= on sd(...) priors once a coef is specified — omitting it
// makes the prior match no model parameter (confirmed against brms directly).
addRow('re_sd_int', 'τ₀\u2009sd(Intercept)', 'sd', 'Intercept', null, '\\tau_0', undefined, g);
if (reType === 'slope') {
slopeVars.forEach((sv, idx) =>
addRow('re_sd_slp_' + sv, 'τ' + (idx+1) + '\u2009sd(' + sv + ')', 'sd', sv, null,
'\\tau_{' + (idx+1) + '}', undefined, g));
// Correlation prior
if (!userPriors['re_cor']) userPriors['re_cor'] = DEF_PRIORS.cor;
rows.push({ id:'re_cor', label:'ρ\u2009cor', cls:'cor', coef:null, dpar:null, sym:'\\rho' });
}
}
return rows;
}
// Rebuilds the #prior-list sidebar HTML from a rows array — destroys and recreates
// every <input> in the list, so this must only run on STRUCTURAL changes (family,
// predictor list, RE toggle, distributional-model toggle), never on a keystroke
// inside a prior-value input (that would steal focus back from the user mid-type —
// exactly the "jumps out after every character" bug this split fixes).
function renderPriorListUI(rows) {
const f = gFamily();
const isCategoricalFam = f === 'categorical';
// Build UI HTML — color-coded by parameter family
const clsBadge = (cls, dpar) => {
// For distributional rows, badge color matches the dpar type
let badgeCls;
if (dpar === 'sigma') badgeCls = 'pc-s';
else if (dpar === 'nu') badgeCls = 'pc-n';
else {
const map = { Intercept:'pc-i', b:'pc-b', sigma:'pc-s', nu:'pc-n', sd:'pc-sd', cor:'pc-sd',
shape:'pc-s', phi:'pc-s', ndt:'pc-n', alpha:'pc-n', zi:'pc-n', zoi:'pc-n', coi:'pc-n' };
badgeCls = map[cls] || 'pc-b';
}
return `<span class="prior-class ${badgeCls}">${dpar ? dpar+'·'+cls : cls}</span>`;
};
let pUI = '';
if (isCategoricalFam) {
pUI += `<div class="prior-note">Kategorisch (nominal) braucht pro Nicht-Referenzkategorie einen
eigenen, mit <code>dpar</code> getaggten Prior (z.B. <code>dpar = "mu2"</code>) — gilt auch für
Random-Effects-SDs. Die Kategorienanzahl hängt von deinen Daten ab, die dieser Builder nicht
kennt. Intercept/β/Random Effects bleiben daher ohne spezifischen Prior (brms-Defaults);
Details im Kommentar im generierten R-Code.</div>`;
}
rows.forEach(r => {
pUI += `<div class="prior-row">
<div class="prior-lbl">${clsBadge(r.cls, r.dpar)}${r.label}</div>
<input class="prior-inp" type="text" id="pi-${r.id}"
value="${gPrior(r.id, r.cls, r.defOverride)}"
oninput="userPriors['${r.id}']=this.value;schedPriorInput()">
</div>`;
});
document.getElementById('prior-list').innerHTML = pUI;
}
// Structural path: recompute rows AND rebuild the sidebar. Called from update()
// whenever something that changes the SET of prior rows happens (family switch,
// predictor added/removed, RE toggled, distributional model toggled, …).
function buildPriorSection(preds, activeD, hasRE, g, reType, slopeVars) {
const rows = computePriorRows(preds, activeD, hasRE, g, reType, slopeVars);
renderPriorListUI(rows);
return rows;
}
// ═══════════════════════════════════════════════════════════
// R CODE GENERATION
// ═══════════════════════════════════════════════════════════
function buildRCode(preds, inters, activeD, hasRE, g, reType, slopeVars, priorRows) {
const y = document.getElementById('outcome').value || 'Y';
const f = gFamily();
const iter = document.getElementById('iter').value;
const warm = document.getElementById('warm').value;
const ch = document.getElementById('chains').value;
const co = document.getElementById('cores').value;
const back = document.getElementById('backend').value;
const delta = parseFloat(document.getElementById('adapt-delta')?.value || 0.80).toFixed(2);
const tree = parseInt(document.getElementById('max-tree')?.value || 10);
const fileRaw = (document.getElementById('fit-file')?.value || '').trim();
const fitName = (document.getElementById('fit-name')?.value || 'fit').trim() || 'fit';
const fileLine = fileRaw ? `\n <span class="nm">file</span> = <span class="str">"${fileRaw}"</span>,` : '';
const needsControl = (parseFloat(delta) !== 0.80 || tree !== 10);
const controlLine = needsControl
? `\n <span class="nm">control</span> = <span class="fn">list</span>(<span class="nm">adapt_delta</span> = <span class="num">${delta}</span>, <span class="nm">max_treedepth</span> = <span class="num">${tree}</span>),`
: '';
// formula always in bf() to avoid errors
const trialsV = (document.getElementById('trials-var')?.value || 'trials').trim() || 'trials';
const trailsExpr = (f === 'beta_binomial' || f === 'binomial') ? ` | trials(${trialsV})` : '';
const expandedPreds = expandPreds(preds, predictorDegrees);
const isOrdinalCode = f === 'cumulative' || f === 'categorical';
const predTerms = [...expandedPreds, ...inters].join(' + ');
const muTerms = isOrdinalCode
? (predTerms || '1')
: (predTerms ? '0 + Intercept + ' + predTerms : '0 + Intercept');
let reC = '';
if (hasRE && g) {
if (reType === 'slope' && slopeVars.length > 0) {
reC = ` + (1 + ${slopeVars.join(' + ')} | ${g})`;
} else {
reC = ` + (1 | ${g})`;
}
}
let formCode;
if (activeD.length > 0) {
let lines = `bf(\n ${y}${trailsExpr} ~ ${muTerms}${reC}`;
activeD.forEach(d => {
lines += `,\n ${d.n} ~ ${d.preds.length > 0 ? '0 + Intercept + ' + d.preds.join(' + ') : '0 + Intercept'}`;
});
lines += '\n)';
formCode = lines;
} else {
formCode = `bf(${y}${trailsExpr} ~ ${muTerms}${reC})`;
}
// priors array — class without quotes (R convention), coef always with quotes
// Note: for class = sd, brms/Stan applies lb=0 automatically (truncation)
const pArr = priorRows.map(r => {
const cls = `class = ${r.cls}`;
const coef = r.coef ? `, coef = "${brmsCoefName(r.coef)}"` : '';
// group=: required by brms on sd(...) priors once a coef is given (e.g. sd(Intercept)) —
// without it the prior matches no model parameter. cor(...) works without it, so only
// emit this for rows that actually carry a group (currently just the sd rows).
const group = r.group ? `, group = "${r.group}"` : '';
const dpar = r.dpar ? `, dpar = "${r.dpar}"` : '';
return ` <span class="str">prior(${gPrior(r.id, r.cls, r.defOverride)}, ${cls}${coef}${group}${dpar})</span>`;
});
const famStr =
f === 'gaussian' ? 'gaussian()' :
f === 'student' ? 'student()' :
f === 'bernoulli' ? 'bernoulli("logit")' :
f === 'poisson' ? 'poisson("log")' :
f === 'Gamma' ? 'Gamma("log")' :
f === 'lognormal' ? 'lognormal()' :
f === 'shifted_lognormal' ? 'shifted_lognormal()' :
f === 'skew_normal' ? 'skew_normal()' :
f === 'negbinomial' ? 'negbinomial("log")' :
f === 'binomial' ? 'binomial("logit")' :
f === 'Beta' ? 'Beta("logit")' :
f === 'beta_binomial' ? 'beta_binomial("logit")' :
f === 'zero_inflated_beta' ? 'zero_inflated_beta("logit")' :
f === 'zero_one_inflated_beta' ? 'zero_one_inflated_beta("logit")' :
f === 'cumulative' ? 'cumulative("logit")' :
f === 'categorical' ? 'categorical("logit")' :
`${f}()`;
return `<span class="cm"># brms Model Builder — generierter Code</span>
<span class="cm"># Intercept: explizit via '0 + Intercept' modelliert (nicht brms-Default 'y ~ x')</span>
<span class="cm"># Warum: brms-Default zentriert Prädiktoren intern → class=Intercept-Prior wirkt auf</span>
<span class="cm"># verschobenen Parameter, nicht auf Rohskala. Mit '0 + Intercept' gilt der Prior direkt.</span>
<span class="cm">#</span>
<span class="cm"># EMPFEHLUNG: Metrische Prädiktoren vor der Analyse transformieren:</span>
<span class="cm"># Zentrieren: x_c <- scale(x, center = TRUE, scale = FALSE) # x - mean(x)</span>
<span class="cm"># Z-Standardisieren: x_z <- scale(x, center = TRUE, scale = TRUE) # (x - mean(x)) / sd(x)</span>
<span class="cm"># → Intercept = E[y] bei durchschnittlichem Prädiktor; Koeffizient pro SD (z-std.) oder Einheit (zentriert)</span>
<span class="nm">model_formula</span> <span class="kw"><-</span> ${formCode.replace(/</g,'<').replace(/>/g,'>')}
${f === 'categorical' ? `
<span class="cm"># Kategorisch (nominal): kein Intercept-/β-Prior generiert, auch keine Random-Effects-Priors.</span>
<span class="cm"># Warum: brms schätzt bei categorical() pro Nicht-Referenzkategorie einen eigenen</span>
<span class="cm"># linearen Prädiktor (dpar = "mu2", "mu3", ...) — das gilt auch für sd(...)/cor(...) bei</span>
<span class="cm"># Random Effects. Priors ohne dpar-Tag passen zu keinem Modellparameter und lassen brms</span>
<span class="cm"># mit einem Fehler abbrechen. Die Anzahl der Kategorien (und damit der nötigen dpar-Tags)</span>