This repository has been archived by the owner on Jun 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
kkl15.qmd
617 lines (497 loc) · 18 KB
/
kkl15.qmd
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
---
title: 'RePsychLing Kliegl, Kuschela, & Laubrock (2015)- Reduction of Model Complexity'
jupyter: julia-1.9
---
# Background
@Kliegl2015 is a follow-up to @Kliegl2011 (see also script `kwdyz11.qmd`) from an experiment looking at a variety of effects of visual cueing under four different cue-target relations (CTRs). In this experiment two rectangles are displayed (1) in horizontal orientation , (2) in vertical orientation, (3) in left diagonal orientation, or in (4) right diagonal orientation relative to a central fixation point. Subjects react to the onset of a small or a large visual target occurring at one of the four ends of the two rectangles. The target is cued validly on 70% of trials by a brief flash of the corner of the rectangle at which it appears; it is cued invalidly at the three other locations 10% of the trials each. This implies a latent imbalance in design that is not visible in the repeated-measures ANOVA, but we will show its effect in the random-effect structure and conditional modes.
There are a couple of differences between the first and this follow-up experiment, rendering it more a conceptual than a direct replication. First, the original experiment was carried out at Peking University and this follow-up at Potsdam University. Second, diagonal orientations of rectangles and large target sizes were not part of the design of @Kliegl2011.
We specify three contrasts for the four-level factor CTR that are derived from spatial, object-based, and attractor-like features of attention. They map onto sequential differences between appropriately ordered factor levels. Replicating @Kliegl2011, the attraction effect was not significant as a fixed effect, but yielded a highly reliable variance component (VC; i.e., reliable individual differences in positive and negative attraction effects cancel the fixed effect). Moreover, these individual differences in the attraction effect were negatively correlated with those in the spatial effect.
This comparison is of interest because a few years after the publication of @Kliegl2011, the theoretically critical correlation parameter (CP) between the spatial effect and the attraction effect was determined as the source of a non-singular LMM in that paper. The present study served the purpose to estimate this parameter with a larger sample and a wider variety of experimental conditions.
Here we also include two additional experimental manipulations of target size and orientation of cue rectangle. A similar analysis was reported in the parsimonious mixed-model paper [@Bates2015]; it was also used in a paper of GAMMs [@Baayen2017]. Data and R scripts of those analyses are also available in [R-package RePsychLing](https://github.com/dmbates/RePsychLing/tree/master/data/).
The analysis is based on log-transformed reaction times `lrt`, indicated by a _boxcox()_ check of model residuals.
In this vignette we focus on the reduction of model complexity. And we start with a quote:
“Neither the [maximal] nor the [minimal] linear mixed models are appropriate for most repeated measures analysis. Using the [maximal] model is generally wasteful and costly in terms of statiscal power for testing hypotheses. On the other hand, the [minimal] model fails to account for nontrivial correlation among repeated measurements. This results in inflated [T]ype I error rates when non-negligible correlation does in fact exist. We can usually find middle ground, a covariance model that adequately accounts for correlation but is more parsimonious than the [maximal] model. Doing so allows us full control over [T]ype I error rates without needlessly sacrificing power.”
Stroup, W. W. (2012, p. 185). _Generalized linear mixed models: Modern concepts, methods and applica?ons._ CRC Press, Boca Raton.
# Packages
```{julia}
#| code-fold: true
#| output: false
using Arrow
using AlgebraOfGraphics
using AlgebraOfGraphics: density
using BoxCox
using CairoMakie
using CategoricalArrays
using Chain
using DataFrameMacros
using DataFrames
using MixedModels
using MixedModelsMakie
using ProgressMeter
using Random
using SMLP2023: dataset
using StatsBase
ProgressMeter.ijulia_behavior(:clear)
CairoMakie.activate!(; type="svg")
```
# Read data, compute and plot means
```{julia}
dat = DataFrame(dataset(:kkl15))
describe(dat)
```
```{julia}
dat_subj = combine(
groupby(dat, [:Subj, :CTR]),
nrow => :n,
:rt => mean => :rt_m,
:rt => (c -> mean(log, c)) => :lrt_m,
)
dat_subj.CTR = categorical(dat_subj.CTR, levels=levels(dat.CTR))
describe(dat_subj)
```
```{julia}
#| code-fold: true
#| fig-cap: Comparative boxplots of mean log response time by subject under different conditions
#| label: fig-bxpltsubjcond
boxplot(
dat_subj.CTR.refs,
dat_subj.lrt_m;
orientation=:horizontal,
show_notch=true,
axis=(;
yticks=(
1:4,
[
"valid cue",
"same obj/diff pos",
"diff obj/same pos",
"diff obj/diff pos",
]
)
),
figure=(; resolution=(800, 300)),
)
```
Mean of log reaction times for four cue-target relations. Targets appeared at (a) the cued position (valid) in a rectangle, (b) in the same rectangle cue, but at its other end, (c) on the second rectangle, but at a corresponding horizontal/vertical physical distance, or (d) at the other end of the second rectangle, that is $\sqrt{2}$ of horizontal/vertical distance diagonally across from the cue, that is also at larger physical distance compared to (c).
We remove the outlier subject and replot, but we model the data points in `dat` and check whether this subject appears as an outlier in the caterpillar plot of conditional modes.
```{julia}
#| code-fold: true
#| fig-cap: 'Comparative boxplots of mean log response time by subject under different conditions without outlier'
#| label: fig-bxpltsubjcond2
let dat_subj = filter(r -> r.rt_m < 510, dat_subj)
boxplot(
dat_subj.CTR.refs,
dat_subj.lrt_m;
orientation=:horizontal,
show_notch=true,
axis=(;
yticks=(
1:4,
[
"valid cue",
"same obj/diff pos",
"diff obj/same pos",
"diff obj/diff pos",
]
)
),
figure=(; resolution=(800, 300)),
)
end
```
# Setup of linear mixed model
## Contrasts
```{julia}
contrasts = Dict(
:Subj => Grouping(),
:CTR => SeqDiffCoding(; levels=["val", "sod", "dos", "dod"]),
:cardinal => EffectsCoding(; levels=["cardinal", "diagonal"]),
:size => EffectsCoding(; levels=["big", "small"])
)
```
```{julia}
m_max_rt = let
form = @formula rt ~ 1 + CTR * size * cardinal +
(1 + CTR * size * cardinal | Subj)
fit(MixedModel, form, dat; contrasts)
end
```
```{julia}
m_cpx_rt = let
form = @formula rt ~ 1 + CTR * size * cardinal +
(1 + CTR + size + cardinal | Subj)
fit(MixedModel, form, dat; contrasts)
end
```
## Box-Cox
```{julia}
#| eval: false
bc1 = fit(BoxCoxTransformation, m_max_rt)
```
```{julia}
bc2 = fit(BoxCoxTransformation, m_cpx_rt)
```
```{julia}
#| eval: false
boxcoxplot(bc2; conf_level=0.95)
```
Clear evidence for skew. Traditionally, we used log transforms for reaction times. even stronger than log. We stay with log for now. Could try `1/sqrt(rt)`.
# Maximum LMM
This is the maximum LMM for the design.
```{julia}
m_max = let
form = @formula log(rt) ~ 1 + CTR * size * cardinal +
(1 + CTR * size * cardinal | Subj)
fit(MixedModel, form, dat; contrasts)
end
```
```{julia}
issingular(m_max)
```
```{julia}
only(MixedModels.PCA(m_max))
```
```{julia}
VarCorr(m_max)
```
# Reduction strategy 1
## Zero-correlation parameter LMM (1)
Force CPs to zero.
```{julia}
m_zcp1 = let
form = @formula log(rt) ~ 1 + CTR * size * cardinal +
zerocorr(1 + CTR * size * cardinal | Subj)
fit(MixedModel, form, dat; contrasts)
end
```
```{julia}
issingular(m_zcp1)
```
```{julia}
only(MixedModels.PCA(m_zcp1))
```
```{julia}
VarCorr(m_zcp1)
```
## Reduced zcp LMM
Take out VC for interactions.
```{julia}
m_zcp1_rdc = let
form = @formula log(rt) ~ 1 + CTR * size * cardinal +
zerocorr(1 + CTR + size + cardinal | Subj)
fit(MixedModel, form, dat; contrasts)
end
```
```{julia}
issingular(m_zcp1_rdc)
```
```{julia}
only(MixedModels.PCA(m_zcp1_rdc))
```
```{julia}
VarCorr(m_zcp1_rdc)
```
## Model comparison 1
Let's compare the three models.
```{julia}
gof_summary = let
nms = [:m_zcp1_rdc, :m_zcp1, :m_max]
mods = eval.(nms)
lrt = MixedModels.likelihoodratiotest(m_zcp1_rdc, m_zcp1, m_max)
DataFrame(;
name = nms,
dof=dof.(mods),
deviance=round.(deviance.(mods), digits=0),
AIC=round.(aic.(mods),digits=0),
AICc=round.(aicc.(mods),digits=0),
BIC=round.(bic.(mods),digits=0),
χ²=vcat(:., round.(lrt.tests.deviancediff, digits=0)),
χ²_dof=vcat(:., round.(lrt.tests.dofdiff, digits=0)),
pvalue=vcat(:., round.(lrt.tests.pvalues, digits=3))
)
end
```
## Parsimonious LMM (1)
Extend zcp-reduced LMM with CPs
```{julia}
m_prm1 = let
form = @formula log(rt) ~ 1 + CTR * size * cardinal +
(1 + CTR + size + cardinal | Subj)
fit(MixedModel, form, dat; contrasts)
end
```
```{julia}
issingular(m_prm1)
```
```{julia}
only(MixedModels.PCA(m_prm1))
```
```{julia}
VarCorr(m_prm1)
```
We note that the critical correlation parameter between spatial (`sod`) and attraction (`dod`) is now estimated at .60 -- not that close to the 1.0 boundary that caused singularity in @Kliegl2011.
## Model comparison 2
```{julia}
gof_summary = let
nms = [:m_zcp1_rdc, :m_prm1, :m_max]
mods = eval.(nms)
lrt = MixedModels.likelihoodratiotest(m_prm1, m_zcp1, m_max)
DataFrame(;
name = nms,
dof=dof.(mods),
deviance=round.(deviance.(mods), digits=0),
AIC=round.(aic.(mods),digits=0),
AICc=round.(aicc.(mods),digits=0),
BIC=round.(bic.(mods),digits=0),
χ²=vcat(:., round.(lrt.tests.deviancediff, digits=0)),
χ²_dof=vcat(:., round.(lrt.tests.dofdiff, digits=0)),
pvalue=vcat(:., round.(lrt.tests.pvalues, digits=3))
)
end
```
# Reduction strategy 2
## Complex LMM
Take out interaction VCs.
```{julia}
m_cpx = let
form = @formula log(rt) ~ 1 + CTR * size * cardinal +
(1 + CTR + size + cardinal | Subj)
fit(MixedModel, form, dat; contrasts)
end
```
## Zero-correlation parameter LMM (2)
Take out interaction VCs.
```{julia}
m_zcp2 = let
form = @formula log(rt) ~ 1 + CTR * size * cardinal +
zerocorr(1 + CTR + size + cardinal | Subj)
fit(MixedModel, form, dat; contrasts)
end
```
## Model comparison 3
```{julia}
gof_summary = let
nms = [:m_zcp2, :m_cpx, :m_max]
mods = eval.(nms)
lrt = MixedModels.likelihoodratiotest(m_zcp2, m_cpx, m_max)
DataFrame(;
name = nms,
dof=dof.(mods),
deviance=round.(deviance.(mods), digits=0),
AIC=round.(aic.(mods),digits=0),
AICc=round.(aicc.(mods),digits=0),
BIC=round.(bic.(mods),digits=0),
χ²=vcat(:., round.(lrt.tests.deviancediff, digits=0)),
χ²_dof=vcat(:., round.(lrt.tests.dofdiff, digits=0)),
pvalue=vcat(:., round.(lrt.tests.pvalues, digits=3))
)
end
```
# Check LMM for untransformed reaction times
We see the model is singular.
```{julia}
issingular(m_cpx_rt)
```
```{julia}
MixedModels.PCA(m_cpx_rt)
```
# Other checks
```{julia}
m_prm1.θ
m_prm1.lowerbd
m_prm1.λ
```
# Diagnostic plots of LMM residuals
Do model residuals meet LMM assumptions? Classic plots are
- Residual over fitted
- Quantiles of model residuals over theoretical quantiles of normal distribution
## Residual-over-fitted plot
The slant in residuals show a lower and upper boundary of reaction times, that is we have have too few short and too few long residuals. Not ideal, but at least width of the residual band looks similar across the fitted values, that is there is no evidence for heteroskedasticity.
```{julia}
#| code-fold: true
#| label: fig-m1fittedresid
#| fig-cap: Residuals versus fitted values for model m1
CairoMakie.activate!(; type="png")
scatter(fitted(m_prm1), residuals(m_prm1); alpha=0.3)
```
With many observations the scatterplot is not that informative. Contour plots or heatmaps may be an alternative.
```{julia}
#| code-fold: true
#| label: fig-m1fittedresid2
#| fig-cap: Heatmap of residuals versus fitted values for model m1
set_aog_theme!()
draw(
data((; f=fitted(m_prm1), r=residuals(m_prm1))) *
mapping(
:f => "Fitted values from m1", :r => "Residuals from m1"
) *
density();
)
```
## Q-Q plot
The plot of quantiles of model residuals over corresponding quantiles of the normal distribution should yield a straight line along the main diagonal.
```{julia}
#| code-fold: true
#| label: fig-qqnormm1
#| fig-cap: Quantile-quantile plot of the residuals for model m1 versus a standard normal
CairoMakie.activate!(; type="png")
qqnorm(
residuals(m_prm1);
qqline=:none,
axis=(;
xlabel="Standard normal quantiles",
ylabel="Quantiles of the residuals from model m1",
),
)
```
## Observed and theoretical normal distribution
******We****** can see this in this plot.
Overall, it does not look too bad.
```{julia}
#| code-fold: true
#| label: fig-stdresidm1dens
#| fig-cap: ' Kernel density plot of the standardized residuals for model m1 versus a standard normal'
CairoMakie.activate!(; type="svg")
let
n = nrow(dat)
dat_rz = (;
value=vcat(residuals(m_prm1) ./ std(residuals(m_prm1)), randn(n)),
curve=repeat(["residual", "normal"]; inner=n),
)
draw(
data(dat_rz) *
mapping(:value; color=:curve) *
density(; bandwidth=0.1);
)
end
```
# Conditional modes
## Caterpillar plot
```{julia}
#| code-fold: true
#| label: fig-caterpillarm1
#| fig-cap: Prediction intervals of the subject random effects in model m1
cm1 = only(ranefinfo(m_prm1))
caterpillar!(Figure(; resolution=(800, 1200)), cm1; orderby=2)
```
## Shrinkage plot
### Log-transformed reaction times (LMM `m_prm1`)
```{julia}
#| code-fold: true
#| label: fig-caterpillarm1L
#| fig-cap: Shrinkage plots of the subject random effects in model m1L
shrinkageplot!(Figure(; resolution=(1000, 1200)), m_prm1)
```
# Parametric bootstrap
Here we
- generate a bootstrap sample
- compute shortest covergage intervals for the LMM parameters
- plot densities of bootstrapped parameter estimates for residual, fixed effects, variance components, and correlation parameters
## Generate a bootstrap sample
We generate 2500 samples for the 15 model parameters (4 fixed effect, 7 VCs, 15 CPs, and 1 residual).
```{julia}
samp = parametricbootstrap(MersenneTwister(1234321), 2500, m_prm1;
optsum_overrides=(; ftol_rel=1e-8));
```
```{julia}
tbl = samp.tbl
```
## Shortest coverage interval
```{julia}
confint(samp)
```
We can also visualize the shortest coverage intervals for fixed effects with the `ridgeplot()` command:
```{julia}
#| code-fold: true
#| label: fig-bsridgem1
#| fig-cap: Ridge plot of fixed-effects bootstrap samples from model m1L
ridgeplot(samp; show_intercept=false)
```
## Comparative density plots of bootstrapped parameter estimates
### Residual
```{julia}
#| code-fold: true
#| label: fig-sigmadensitym1
#| fig-cap: ' Kernel density estimate from bootstrap samples of the residual standard deviation for model m_prm1'
draw(
data(tbl) *
mapping(:σ => "Residual") *
density();
figure=(; resolution=(800, 400)),
)
```
### Fixed effects and associated variance components (w/o GM)
The shortest coverage interval for the `GM` ranges from x to x ms and the associate variance component from .x to .x. To keep the plot range small we do not include their densities here.
```{julia}
#| code-fold: true
#| label: fig-betadensitym1
#| fig-cap: ' Kernel density estimate from bootstrap samples of the fixed effects for model m_prm1'
rn = renamer([
"(Intercept)" => "GM",
"CTR: sod" => "spatial effect",
"CTR: dos" => "object effect",
"CTR: dod" => "attraction effect",
"(Intercept), CTR: sod" => "GM, spatial",
"(Intercept), CTR: dos" => "GM, object",
"CTR: sod, CTR: dos" => "spatial, object",
"(Intercept), CTR: dod" => "GM, attraction",
"CTR: sod, CTR: dod" => "spatial, attraction",
"CTR: dos, CTR: dod" => "object, attraction",
])
draw(
data(tbl) *
mapping(
[:β02, :β03, :β04] .=> "Experimental effect size [ms]";
color=dims(1) =>
renamer(["spatial effect", "object effect", "attraction effect"]) =>
"Experimental effects",
) *
density();
figure=(; resolution=(800, 350)),
)
```
The densitiies correspond nicely with the shortest coverage intervals.
```{julia}
#| code-fold: true
#| label: fig-sigmasdensitym1
#| fig-cap: ' Kernel density estimate from bootstrap samples of the standard deviations for model m1L (excluding Grand Mean)'
draw(
data(tbl) *
mapping(
[:σ2, :σ3, :σ4] .=> "Standard deviations [ms]";
color=dims(1) =>
renamer(["spatial effect", "object effect", "attraction effect"]) =>
"Variance components",
) *
density();
figure=(; resolution=(800, 350)),
)
```
The VC are all very nicely defined.
### Correlation parameters (CPs)
```{julia}
#| code-fold: true
#| label: fig-corrdensitym1
#| fig-cap: ' Kernel density estimate from bootstrap samples of the standard deviations for model m1L'
draw(
data(tbl) *
mapping(
[:ρ01, :ρ02, :ρ03, :ρ04, :ρ05, :ρ06] .=> "Correlation";
color=dims(1) =>
renamer(["GM, spatial", "GM, object", "spatial, object",
"GM, attraction", "spatial, attraction", "object, attraction"]) =>
"Correlation parameters",
) *
density();
figure=(; resolution=(800, 350)),
)
```
Three CPs stand out positively, the correlation between GM and the spatial effect, GM and attraction effect, and the correlation between spatial and attraction effects.
The second CP was positive, but not significant in the first study.
The third CP replicates a CP that was judged questionable in script `kwdyz11.jl`.
The three remaining CPs are not well defined for log-transformed reaction times; they only fit noise and should be removed.
It is also possible that fitting the complex experimental design (including target size and rectangle orientation) will lead to more acceptable estimates.
The corresponding plot based on LMM `m1_rt` for raw reaction times still shows them with very wide distributions, but acceptable.
# References
::: {#refs}
:::