-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathg_flexmanip.Rmd
More file actions
3272 lines (2530 loc) · 240 KB
/
Copy pathg_flexmanip.Rmd
File metadata and controls
3272 lines (2530 loc) · 240 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
---
title: "Behavioral flexibility is manipulable and it improves flexibility and innovativeness in a new context"
author:
- "Logan CJ^1^"
- "Lukas D^1^"
- "Blaisdell AP^2^"
- "Johnson-Ulrich Z^3^"
- "MacPherson M^3^"
- "Seitz B^2^"
- "Sevchik A^4^"
- "McCune KB^3^"
bibliography: MyLibrary.bib
biblio-style: authoryear
csl: Peer-Community-Journal-PCI.csl
caption-side: bottom
output:
html_document:
toc: true
toc_depth: 5
toc_float:
collapsed: false
code_folding: hide
pdf_document:
keep_tex: yes
latex_engine: xelatex
bookdown::pdf_document2:
keep_tex: true
number_sections: TRUE
fig_caption: TRUE
urlcolor: blue
header-includes:
- \usepackage{pdflscape}
- \newcommand{\blandscape}{\begin{landscape}}
- \newcommand{\elandscape}{\end{landscape}}
- \usepackage{longtable} #set longtable = TRUE in kable() to have a long table break over multiple pages https://bookdown.org/yihui/bookdown/tables.html
preamble: >
\usepackage{amsmath} #NOTE: to make this yaml work, run install.packages("rticles")
base_format: rticles::amsmath
#For posting final version at EcoEvoRxiv: replace pre-introduction with https://docs.google.com/document/d/13b2FerqJbwuOMCUODrSMN1D3k_s3ve1plNU9rw_tAEk/edit?usp=sharing . The PCI templates are located at https://osf.io/hfdjc
---
```{r setup, include=FALSE}
library(knitr)
knitr::opts_chunk$set(echo=F, include=T, results='asis', warning=F, message=F)
#sets global options to display code along with the results https://exeter-data-analytics.github.io/LitProg/r-markdown.html
#set echo=F for knitting to PDF (hide code), and echo=T for knitting to HTML (show code)
#options(knitr.table.format = "latex") #the format="latex" argument is REQUIRED for proper table rendering in final pdf
#options(tinytex.verbose = TRUE) #turn this on when having problems knitting to pdf and need to see the full error message
```
[](https://doi.org/10.24072/pci.ecology.100407)
**Affiliations:** 1) Max Planck Institute for Evolutionary Anthropology, Leipzig, Germany, 2) University of California Los Angeles, USA, 3) University of California Santa Barbara, USA, 4) Arizona State University, Tempe, AZ USA. *Corresponding author: corina_logan@eva.mpg.de
**This research article has been peer reviewed and recommended by:**
Aurélie Coulon (2023) An experiment to improve our understanding of the link between behavioral flexibility and innovativeness. *Peer Community in Ecology*, 100407. [10.24072/pci.ecology.100407](https://doi.org/10.24072/pci.ecology.100407). Reviewers: Maxime Dahirel, Andrea Griffin, Aliza le Roux, and 1 anonymous reviewer
**Cite as:** Logan CJ, Lukas D, Blaisdell AP, Johnson-Ulrich Z, MacPherson M, Seitz BM, Sevchik A, McCune KB. 2023. Behavioral flexibility is manipulable and it improves flexibility and innovativeness in a new context. EcoEvoRxiv, version 5, peer reviewed and recommended by *Peer Community in Ecology*. doi: https://doi.org/10.32942/osf.io/5z8xs
**This article began as a preregistration, which was pre-study peer reviewed and received an In Principle Recommendation of the [version](https://github.com/corinalogan/grackles/blob/master/Files/Preregistrations/g_causalPassedPreStudyPeerReview31Jan2019.pdf) on 26 March 2019 by:**
Aurélie Coulon (2019) Can context changes improve behavioral flexibility? Towards a better understanding of species adaptability to environmental changes. *Peer Community in Ecology*, 100019. [10.24072/pci.ecology.100019](https://doi.org/10.24072/pci.ecology.100019). Reviewers: Maxime Dahirel and Andrea Griffin
# Abstract {-}
Behavioral flexibility, the ability to adapt behavior to new circumstances, is thought to play an important role in a species' ability to successfully adapt to new environments and expand its geographic range. However, flexibility is rarely directly tested in a way that would allow us to determine how flexibility works to predict a species' ability to adapt their behavior to new environments. We use great-tailed grackles (*Quiscalus mexicanus*; a bird species) as a model to investigate this question because they have recently rapidly expanded their range into North America. We attempted to manipulate grackle flexibility using shaded (light and dark gray) tube reversal learning to determine whether flexibility is generalizable across contexts (multi-access box), and what learning strategies grackles employ. We found that flexibility was manipulable: birds in the manipulated group took fewer trials to pass criterion with increasing reversal number, and they reversed a shade preference in fewer trials by the end of their serial reversals compared to control birds who had only one reversal. Birds that passed their last reversal faster were also more flexible (faster to switch between loci) and innovative (solved more loci) on a multi-access box. All grackles in the manipulated reversal learning group used one learning strategy (epsilon-decreasing) in all reversals, and none used a particular exploration or exploitation strategy earlier or later in their serial reversals. Understanding how flexibility causally relates to other traits will allow researchers to develop robust theory about what flexibility is and when to invoke it as a primary driver in a given context, such as a rapid geographic range expansion.
\newpage
# Introduction {-}
Behavioral flexibility, the ability to adapt behavior to new circumstances through packaging information and making it available to other cognitive processes [see @mikhalevich_is_2017 for the theoretical background on this definition], is thought to play an important role in a species' ability to successfully adapt to new environments and expand its geographic range [e.g., @lefebvre1997feeding; @sol2000behavioural; @sol2002behavioural; @sol2005big; @sol2007big]. The behavioral flexibility (hereafter referred to as flexibility) of individuals is considered an important trait that facilitates the capacity for learning, which is then associated with problem solving ability (applying what one has learned about the world to then attempt to access a resource that is not readily accessible) [see review in @lea2020behavioral]. It is hypothesized that, through flexibility, individuals can increase the diversity of their behaviors either via asocial learning (innovativeness) or social learning, leading to the establishment of the population in a new area [@wright2010behavioral].
It is predicted that flexibility should positively relate with innovativeness, the ability to create a new behavior or use an existing behavior in a new situation [@griffin2014innovation]. However, these predictions are based on species-level data and proxies for flexibility and for innovation (e.g., brain size, number of anecdotal reports of “novel” foods consumed) when examining such relationships [see @logan2018beyond]. Flexibility is rarely directly tested in species that are rapidly expanding their geographic ranges in a way that would allow us to determine how flexibility works and predict a species' ability to adapt their behavior to new areas. Those investigations that examine the relationship between flexibility and innovation or problem solving in species that are expanding their range show mixed results, with these variables correlating positively [e.g., grey squirrels: @chow2016practice], negatively [e.g., Indian mynas: @griffin2013tracking], or not at all [e.g., stick tool use and string pulling in great-tailed grackles: @logan2016behavioral]. Problem solving in these contexts involves experimental assays that do not necessarily require innovativeness to solve [e.g., the ability to solve tasks using pre-trained behaviors: @griffin2014innovation]. However, none of these experiments manipulated flexibility.
Here, we take the first step to improving our understanding of whether and how flexibility relates to innovativeness by starting with one population and performing a manipulative experiment on one of the variables to determine whether there is an associated change in the other. Once this association is known, future research can then investigate whether flexibility and innovativeness are involved in a range expansion. Manipulative experiments go beyond correlations to infer a cause and effect relationship between the manipulated variable and the variable(s) measured after the manipulation [@hernan2006instruments; @rethinking2020]. A manipulative experiment combined with the random assignment of subjects to a condition (manipulated group or control group), eliminates many confounds associated with internal and external variation (for example, season, motivation, sex, and so on). Such manipulative experiments in behavioral ecology have primarily been conducted in laboratory settings because of the increased feasibility, however such experiments are now also being conducted in wild settings [e.g., @aplin2015experimentally].
We focused our study on one population of great-tailed grackles (*Quiscalus mexicanus*, hereafter grackles), a bird species that is flexible [@logan2016behavioral]. While they are originally from Central America, grackles have rapidly expanded their geographic range across the US since 1880 [@wehtje2003range; @summers2023xpop]. We attempted to manipulate grackle flexibility using serial reversals of a shade (light or dark gray) preference to determine whether their flexibility is generalizable across additional experimental contexts (touchscreen reversal learning and multi-access box solution switching), whether improving flexibility also improves innovativeness (number of loci solved on a multi-access box), and what learning strategies grackles employ (Figure \ref{fig:figHypotheses}).
Reversal learning is a common way of measuring flexibility that has been used for many decades across many species, therefore lending itself well to comparative analyses and generalizations [see review in @lea2020behavioral]. In this test, an individual learns to prefer the rewarded option, which differs from the non-rewarded option in shade/color, shape, space, or another discriminable feature. Once this initial preference is formed, the previously non-rewarded option becomes the rewarded option and vice versa, and the preference is reversed. Individuals who are faster to reverse their preference are considered more flexible - better able to change their behavior when the circumstances change. Serial reversal learning involves continuing to reverse the preference back and forth to determine whether individuals learn a “win-stay, lose-shift” rule that, when the reward no longer follows the expected option, they should switch to preferring the other option [@spence1936nature; @warren1965primate; @warren1965comparative]. Once this rule is learned, it can then be applied to new contexts and result in improved performance over individuals who have not learned this rule [@warren1965comparative]. We randomly assigned individuals to a manipulated or control condition and used serial reversals (for the manipulated group) to attempt to manipulate flexibility and determine whether the manipulated individuals were then more flexible and more innovative in other contexts.
If grackle flexibility is manipulable using serial reversals, this would provide us with a useful tool for investigating the relationship between flexibility and any number of other variables implicated in geographic range expansions. It would provide researchers with a way to examine the direct links between, for example, flexibility and exploration, to determine whether they are connected and in which direction, which could provide insights into how populations establish in a new location if cross-population manipulations were conducted. If the flexibility manipulation is not successful, this could indicate either that we did not manipulate the right aspect of flexibility (e.g., perhaps training them to solve a variety of different types of tasks quickly would be more effective) or that grackle flexibility is not a trait that is trainable.
```{r figHypotheses, out.width="10cm",fig.align = "center", fig.cap="A visual illustration of Hypothesis 1 (A), Hypothesis 2 (B), and Hypothesis 4 (C). Longer black arrows indicate slower reversal times, the two yellow circles represent experience with the two yellow tubes that both contained food for the control group."}
knitr::include_graphics("g_flexmanipFig1.png")
```
## [Video summary](https://youtu.be/bALXB2S4OpI): https://youtu.be/bALXB2S4OpI
## PREREGISTERED HYPOTHESES
### H1: Behavioral flexibility, as measured by reversal learning using colored tubes, is manipulable.
- **Prediction 1:** Individuals improve their flexibility on a serial reversal learning task using shaded tubes by generally requiring fewer trials to reverse a preference as the number of reversals increases (manipulation condition). Their flexibility on this test is manipulated relative to control birds who do not undergo serial reversals. Instead, individuals in the control condition are matched to manipulated birds for experience (they experience a similar number of trials), but there is no possibility of a functional tube preference because both tubes are the same shade (yellow) and both contain food, therefore either choice is correct.
- **P1 alternative 1:** If the number of trials to reverse a preference does not correlate with or positively correlates with reversal number, which would account for all potential correlation outcomes, this suggests that some individuals may prefer to rely on information acquired previously (i.e., they are slow to reverse) rather than relying on current cues (e.g., the food is in a new location) [e.g., @manrique_repeated_2013; @griffin2014innovation; @liu2016learning; but see @homberg2007serotonin].
### H2: Manipulating behavioral flexibility (improving reversal learning speed through serial reversals using shaded tubes) improves flexibility (rule learning and/or switching) and innovativeness in a new context (two distinct multi-access boxes and serial reversals on a touchscreen).
- **P2:** Individuals that have improved their flexibility on a serial reversal learning task using shaded tubes (requiring fewer trials to reverse a preference as the number of reversals increases) are faster to switch between new methods of solving (latency to solve or attempt to solve a new way of accessing the food [locus]), and learn more new loci (higher total number of solved loci) on multi-access box flexibility tasks, and are faster to reverse preferences in a serial reversal task using a touchscreen than individuals in the control group where flexibility has not been manipulated. The positive correlation between reversal learning performance using shaded tubes and a touchscreen (faster birds have fewer trials) and the multi-access boxes (faster birds have lower latencies) indicates that all three tests measure the same ability even though the multi-access boxes require inventing new rules to solve new loci (while potentially learning a rule about switching: "when an option becomes non-functional, try a different option") while reversal learning requires switching between two rules ("choose light gray" or "choose dark gray") or learning the rule to "switch when the previously rewarded option no longer contains a reward". Serial reversals eliminate the confounds of exploration, inhibition, and persistence in explaining reversal learning speed because, after multiple reversals, what is being measured is the ability to learn one or more rules. If the manipulation works, this indicates that flexibility can be influenced by previous experience and might indicate that any individual has the potential to move into new environments (see relevant hypotheses in preregistrations on [genetics](http://corinalogan.com/Preregistrations/g_flexgenes.html) (R1) and [expansion](http://corinalogan.com/Preregistrations/g_expansion.html) (H1).
- **P2 alternative 1:** If the manipulation does not work in that those individuals in the experimental condition do not reverse faster than control individuals, then this experiment elucidates whether general individual variation in flexibility relates to flexibility in new contexts (two distinct multi-access boxes and serial reversals on a touchscreen) as well as innovativeness (multi-access boxes). The prediction is the same as in P2, but in this case variation in flexibility is constrained by traits inherent to the individual [some of which are tested in @mccune2019exploration], which suggests that certain individuals will be more likely to move into new environments.
- **P2 alternative 2:** If there is no correlation between reversal learning speed (shaded tubes) and the latency to solve/attempt a new locus on the multi-access boxes, this could be because the latency to solve not only measures flexibility but also innovativeness. In this case, an additional analysis is run with the latency to solve as the response variable, to determine whether the fit of the model (as determined by the lower AIC value) with reversal learning as an explanatory variable is improved if motor diversity (the number of different motor actions used when attempting to solve the multi-access box) is included as an explanatory variable [see @diquelou2015role; @griffin2016invading]. If the inclusion of motor diversity improves the model fit, then this indicates that the latency to solve a new locus on the multi-access box is influenced by flexibility (reversal learning speed) and innovation (motor diversity).
- **P2 alternative 3:** If there is a negative correlation or no correlation between reversal learning speed on shaded tubes and reversal learning speed on the touchscreen, then this indicates that it may be difficult for individuals to perceive and/or understand images on the touchscreen in contrast with physical objects (shaded tubes) [e.g., @ohara2015advantage].
### H3: Behavioral flexibility within a context is repeatable within individuals.
\
This hypothesis from the original preregistration is now being treated in a separate manuscript [@mccune2023flexmanip].
### H4: Individuals should converge on an epsilon-first learning strategy (learn the correct choice after one trial) as they progress through serial reversals.
- **P4:** Individuals prefer a mixture of learning strategies in the first serial reversals (an *epsilon-decreasing* strategy where individuals explore both options extensively before learning to prefer the rewarded option, and an *epsilon-first* strategy where the correct choice is consistently made after the first trial), and then move toward the epsilon-first learning strategy. The epsilon-first strategy works better later in the serial reversals where the reward is all or nothing because individuals have learned the environment is changing in predictable ways [@bergstrom2004shannon]: only one option is consistently rewarded, and if the reward isn't in the previously rewarded option, it must be in the other option.
- **P4 alternative 1:** Individuals continue to prefer a mixture of learning strategies, and/or they do not converge on the more functional epsilon-first learning strategy, regardless of how many reversals they participate in. This pattern could suggest that the grackles do not attend to functional meta-strategies, that is, they do not learn the overarching rule (once food is found in the non-preferred tube, one must switch to preferring that tube shade), but rather they learn each preference change as if it was new.
# Methods {-}
This study is based on a preregistration that received in principle acceptance at PCI Ecology ([PDF](https://github.com/corinalogan/grackles/blob/master/Files/Preregistrations/g_flexmanipPassedPreStudyPeerReview26Mar2019.pdf) version), which included a description of the analyses we initially planned to perform. In the following, we first outline the rationale for any changes from the preregistered methods before describing the methods that were used to derive the results presented here.
**Changes after pilot data were collected and before the actual data collection began**
1) We initially (in 2017) set the serial reversal passing criterion as the following. During the data collection period, the number of trials required to reverse a preference will be documented per bird, and reversals will continue until the first batch of birds tested reaches an asymptote (i.e., there are negligible further decreases in the number of trials required to reverse a preference). The number of reversals to reach the asymptote will be the number of reversals that subsequent birds experience. Due to delays in setting up the field site, we were only able to test two grackles in early 2018 (January through April) and, due to randomization, only one (Fajita) was in the experimental condition that involved undergoing the flexibility manipulation (Empanada was in the control condition). While Fajita’s reversal speeds generally improved with increasing serial reversals, she never reached an asymptote (which we defined as passing three consecutive reversals in the same number of trials), even after 38 reversals. These 38 reversals took 2.5 months, which is an impractical amount of time if birds are to participate in the rest of the test battery (multi-access box, detour, causal cognition, go no-go, reversal on a touchscreen) after undergoing the reversal manipulation (we were initially permitted to keep them in aviaries for up to three months per bird, which we extended to 6 months per bird in Dec 2018). Because our objective in this experiment was to manipulate an individual’s flexibility, we decided to revise our serial reversal passing criterion to something more species relevant based on Fajita’s serial reversal performance and the performance of seven grackles in Santa Barbara who underwent only one reversal in 2014 and 2015 (Logan, 2016). The **revised serial reversal passing criterion was: passing two reversals in a row at or under 50 trials**. 50 trials is fewer trials than any of the nine grackles required to pass their first reversal (range 70-130), therefore it should reflect an improvement in flexibility.
**Changes at the beginning of data collection**
2) Reversal learning shaded tube choice criterion. At the beginning of the second bird’s initial discrimination in the reversal learning shaded tube experiment (October 2018), we revised the criterion for what counts as a choice from A) the bird’s head needs to pass an invisible line on the table that ran perpendicular to the the tube opening to B) the **bird needs to bend its body or head down to look in the tube** (see B demonstrated in Figure \ref{fig:figTznatl}). Criterion A resulted in birds making more choices than the number of learning opportunities they were exposed to (because they could not see whether there was food in the tube unless they bent their head down to look in the tube) and appeared to result in slower learning. It is important that one choice equals one learning opportunity, therefore we revised the choice criterion to the latter. Anecdotally, this choice matters because the first three birds in the experiment (Tomatillo, Chalupa, and Queso) learned faster than the pilot birds (Empanada and Fajita) in their initial discriminations and first reversals. Thus, it was an important change to make at the beginning of the experiment (after testing the two pilot birds and before collecting any data that were included in analyses).
```{r figTznatl, out.width="10cm", fig.align = 'center', fig.cap="Tzanatl preciosa bending down to look into the dark gray tube."}
knitr::include_graphics("g_flexmanip_figTzanatl1.png")
```
3) Criterion to pass the control condition: Before collecting experimental data, we set the number of trials experienced by the birds in the control group as 1100 because this is how many trials it would have taken the pilot bird in the manipulated group, Fajita, to pass serial reversals 2-17 according to our revised serial reversal passing criterion. However, after 25 and 17 days (after Tomatillo and Queso’s first reversals, respectively) of testing the first two individuals in the control group, it became apparent that 1100 trials is impractical given the time constraints for how long we were permitted to keep each bird temporarily in captivity and would prevent birds from completing the test battery before their release. Additionally, after revising the choice criterion, it was going to be likely that birds in the manipulated group would require fewer than 1100 trials to meet the serial reversal passing criterion. Therefore, reducing the number of trials the control birds experience would result in a better match of experience with birds in the manipulated group. On 2 November 2018 we **set the number of trials control birds experience after their first (and only) reversal** to the number of trials it requires the first bird in the manipulated group to pass (the first bird had not passed yet, therefore we did not yet know what this number was). After more individuals in the manipulated group passed, we updated this number to the average number of trials to pass. This applied to all birds in the control condition, except Mofongo. Mofongo (control condition) was a slow participator and would not have finished his test battery by the time it got too hot to keep birds in the aviaries if we used the current average number of trials (420). Instead, we matched him with the fastest bird in the manipulated group (Habanero=290 trials) to make it more likely that Mofongo could get through the rest of the test battery in time.
**Changes in the middle of data collection**
4) 10 April 2019, we **discontinued the reversal learning experiment on the touchscreen** because it appeared to measure something other than what we intended to test and it required a huge time investment for each bird (which consequently reduced the number of other tests they were available to participate in). This is not necessarily surprising because this was the first time touchscreen tests have been conducted in this species, and also the first time (to our knowledge) this particular reversal experiment has been conducted on a touchscreen with birds. We based this decision on data from four grackles (2 in the flexibility manipulation group and 2 in the flexibility control group; 3 males and 1 female). All four of these individuals showed highly inconsistent learning curves and required hundreds more trials to form each preference when compared to the performance of these individuals on the shaded tube reversal experiment. It appeared that there was a confounding variable with the touchscreen such that they were extremely slow to learn a preference as indicated by passing our criterion of 17 correct trials out of the most recent 20. We did not include the data from this experiment when conducting the cross-test comparisons in the Analysis Plan section of the preregistration. Instead, in Supplementary Material 4, we provided summary results for this experiment and, in the Discussion, qualitatively compared it with performance on the shaded tube reversal test to explain what might have confounded the touchscreen experiment.
5) 16 April 2019, because we discontinued the touchscreen reversal learning experiment, we **added an additional but distinct multi-access box** task, which allowed us to continue to measure flexibility across three different experiments. There are two main differences between the first multi-access box, which is made of plastic, and the new multi-access box, which is made of wood. First, the wooden multi-access box is a natural log in which we carved out 4 compartments. As a result, the apparatus and solving options are more comparable to what grackles experience in the wild, though each compartment is covered by a transparent plastic door that requires different behaviors to open. Furthermore, there is only one food item available in the plastic multi-access box and the bird could use any of 4 loci to reach it. In contrast, the wooden multi-access box has a piece of food in each of the 4 separate compartments.
**Updates and changes post data collection, pre-data analysis**
6) We completed our simulation to explore the lower boundary of a minimum sample size and determined that **our sample size for the Arizona study site is above the minimum** (see details and code in Supplementary Material 1; 17 April 2020).
7) Please see our Alternative Analyses section in the preregistration where we stated that we would learn and implement Bayesian models, which resulted in our **changing the analysis for P2** and that we are replacing this analysis with the new models in the Ability to detect actual effects section (Supplementary Material 1; 14 May 2020). We also describe in SM1 that we realized that Condition (manipulated or control) does not need to be a variable in our models because our analyses in P1 demonstrate that the manipulation causally changed reversal speeds, which is the key assumption in P2.
8) We originally planned on testing only **adults** to have a better understanding of what the species is capable of, assuming the abilities we are testing are at their optimal levels in adulthood, and so we could increase our statistical power by eliminating the need to include age as an independent variable in the models. Because the grackles in Arizona were extremely difficult to catch, we ended up testing two juveniles: Taco and Chilaquile. We did not conduct the full test battery with Taco or put him in the flexibility manipulation or control groups (he received 1 reversal and then moved on to the next test) because he was the first juvenile and we wanted to see whether his performance was different from adult performances. His performances were similar to the adults, therefore we decided to put Chilaquile in the full test battery. Chilaquile's performances were also similar to the adults, therefore we decided not to add age as an independent variable in the models to avoid reducing our statistical power.
9) We **removed experimenter as a random effect** from all analyses because the interobserver reliability scores were so high, indicating there was no difference between experimenters, therefore we could keep our models simpler by leaving this variable out.
10) P2 alternative 2: We **used the average latency rather than the number of trials to attempt a new locus** because this would make the model comparable with the model in P2. Using the number of trials was an artifact from a previous version and we had missed updating this. We omitted the number of trials to solve a new locus as described in the deviation from the plan in P2 above. We used a GLM rather than a GLMM because there was only one data point per bird (note that there would have been only one data point per bird in the preregistration as well, but we didn’t realize this until after in principle acceptance).
11) P4 (Aug 2021): The grackles were tested in **10-trial blocks** and not 20-trial blocks as in Federspiel et al. (2017), which would mean that if there were <20 trials in the last block of a reversal, they would be omitted from the analysis. Therefore, we changed the block size to 10 trials and adjusted the sampling blocks to 2-9 correct choices, and the acquisition blocks to 9-10 correct choices using significance levels in the binomial test as did Federspiel et al. (2017).
**Changes post data collection, mid-data analysis**
12) P2 (April 2020): We realized that the average latency to solve a new locus after solving a different locus is confounded with the total number of loci solved because the measure of innovation is included in the definition. Therefore, we removed average latency to solve a locus from analyses so that we are only examining pure measures of flexibility (average latency to **attempt** to solve) and innovation (total number of loci solved).
13) P2: Removed aviary batch (random variable) from the original model for P2 (Table SM3: Model 1). Batch ended up confounding the analysis because control and manipulated individuals, while randomly assigned to these conditions, ended up in particular batches as a result of their willingness to participate in tests offered during their time in the aviary (Table SM3: Model 3). Several grackles never passed habituation or training such that their first experiment could begin, therefore we replaced these grackles in the aviaries with others who were willing to participate. This means that batch did not indicate a particular temporal period. Therefore, we **removed batch from the models** (post data collection, mid-data analysis).
14) P2: When making the bespoke Bayesian models, we realized that we had previously misinterpreted which variable should be the response variable in this analysis. We originally set the number of trials to reverse as the response variable, however we should have instead set the number of loci solved as the response variable and then planned to conduct a second model with the latency to attempt a new locus as the response variable and number of trials as the explanatory variable. This is because a) we manipulated the number of trials to reverse, therefore it must be the explanatory variable (Hernán & Robins, 2006); and b) they should be split into two models, **one each for average latency and number of loci solved**, because of a and because these are two very different relationships that should be considered in their own models. We also realized that Condition (manipulated or control) does not need to be a variable in any of our models because our analyses in P1 demonstrate that the manipulation causally changed reversal speeds, which is the key assumption in P2.
**Changes post data collection, post-data analysis**
15) We present the results from different hypotheses in separate articles: this one, @mccune2023flexmanip, and @lukas2022flexmanip.
## Sample
\
Grackles were caught in the wild in Tempe, Arizona, USA for individual identification (colored leg bands in unique combinations). Some individuals (34: 13 in the control group (they receive 1 reversal; only 11 completed the experiment) and 10 in the flexibility manipulation (they receive multiple reversals; only 8 completed the experiment), and 11 who did not participate enough to enter the experiments) were brought temporarily into aviaries for testing, and then released back to the wild.
## Data collection stopping rule
\
We stopped testing birds after we completed two full aviary seasons because the sample size was above the minimum suggested boundary of 15 (to detect a medium effect size) based on model simulations (see Supplementary Material 1).
## Summary of testing protocols (Figure \ref{fig:figPhotos})
- **Reversal learning with shaded tubes:** One light gray and one dark gray tube were placed such that the openings were not visible (shades were pseudorandomized for side). One shade always contained a food reward. The individual had the opportunity to choose to look inside one tube per trial. Once the individual chose correctly on 17 out of the most recent 20 trials, they were considered to have a shade preference, and then the food was always placed in the previously non-rewarded shade and the same passing criterion was used to determine their reversal learning performance. Individuals were randomly placed in the manipulated condition (serial reversals until they passed two consecutive reversals in 50 trials or less) or the control condition (receive only one reversal and then a similar number of total trials to the manipulated individuals, but with two yellow tubes, both of which always had food).
- **Plastic multi-access box:** This was a puzzlebox made of plexiglas and plastic, which contained one piece of food on a post in the center of the box. The box was placed in the aviary for up to 15 minutes per trial. Each plexiglas wall had one option (locus) for retrieving the food, but each option required a different method for obtaining the food. The individual had the opportunity to attempt (touch, but not obtain the food) or solve a locus. Once a locus was used successfully three times to get the food, it was considered solved and rendered non-functional in subsequent trials. The experiment ended when an individual solved all four loci or if they did not interact with or successfully solve a locus in three consecutive trials.
- **Wooden multi-access box:** This was a puzzlebox carved from a log to have four loci containing a food item. Each locus required a different motor action to solve. Three loci were covered with a plastic door on a hinge and one locus was a drawer that must be pulled out. Trials lasted for up to 15 minutes. The passing criterion and experiment ending criteria were the same as for the plastic multi-access box.
- **Reversal learning of shapes on a touchscreen:** This is the same experimental design as with the shaded tubes, except it was carried out on a touchscreen computer where the individual was presented with two white symbols that differed in shape (pentagon or diamond). Touching the screen over the rewarded shape resulted in food dropping from a food hopper into a dish accessible to the grackle, while touching the screen over the non-rewarded shape resulted in no food and a longer inter-trial interval.
```{r figPhotos, out.width="10cm", fig.align = 'center', fig.cap="The experimental apparatuses: reversal learning using dark gray and light gray tubes (A) or two different shapes on a touchscreen (B), and the plastic (C) and wooden (D) multi-access boxes (MAB). The plastic MAB has four loci that all provide access to one piece of food and each locus has a distinct way of being opened: open the window (left side), pull the string (top side), push the shovel (right side), or twist the shovel (bottom side). The wooden MAB has four loci, each containing food and each locus has a distinct way of being opened: swing open flap (locus B), pull out drawer (locus C), push in flap (locus D), or lift up flap (locus A)."}
knitr::include_graphics("g_flexmanip_figPhotos.png")
```
## Open materials
- [Design files](https://github.com/corinalogan/grackles/tree/master/Files/MultiaccessBoxDesignFiles) for the plastic multi-access box: 3D printer files and laser cutter files
- [Testing protocols](https://docs.google.com/document/d/18D80XZV_XCG9urVzR9WzbfOKFprDV62v3P74upu01xU/edit?usp=sharing) for all experiments: shaded tube reversal learning, plastic multi-access box, wooden multi-access box, and touchscreen reversal learning
## Open data
\
Data are publicly [available](https://doi.org/10.5063/F1XP73CJ) at the Knowledge Network for Biocomplexity [@logan2023flexmanipdata].
## Randomization and counterbalancing
\
H1: Subjects were randomly assigned to the manipulated or control group. In the reversal learning trials, the rewarded option is pseudorandomized for side (and the option on the left is always placed first). Pseudorandomization consisted of alternating location for the first two trials of a session and then keeping the same shade on the same side for at most two consecutive trials thereafter. A list of all 88 unique trial sequences for a 10-trial session, following the pseudorandomization rules, was generated in advance for experimenters to use during testing (e.g., a randomized trial sequence might look like: LRLLRRLRLR, where L and R refer to the location, left or right, of the rewarded tube). Randomized trial sequences were assigned randomly to any given 10-trial session using a random number generator (random.org) to generate a number from 1-88. The only exception to this randomization was when an individual exhibited a side bias (choosing one side 4 or more trials in a row). In these cases, we stopped the current random numbers for side and started putting the rewarded shade on the non-preferred side as much as possible while still following the pseudorandomization rules until the individual stopped exhibiting a side bias.
## Statistical analyses {-}
Analyses were conducted in R [current version `r getRversion()`, @rcoreteam], using several R packages: kableExtra [@kableextra], MCMCglmm [@hadfield2010mcmc], MuMIn [@mumin], rethinking [@rethinking2020], stan [@rstan], formatR [@formatr], Rstudioapi [@rstudioapi], rcpp [@rcpp], ggplot2 [@ggplot2], knitr [@xie2018knitr; @xie2017dynamic; @xie2013knitr], dplyr [@dplyr], cmdstanr [@cmdstanr], cowplot [@wilkecowplot], reactable [@reactable], DHARMa [@hartig2019dharma], and lme4 [@lme4; @bates2012lme4].
**Unregistered analyses:** We conducted unregistered interobserver reliability analyses on the video and live coding of the response variables. Scores indicated that the response variables are repeatable to a high or extremely high degree given our instructions and training for coders (see Supplementary Material 2).
### Data checking
\
The data were checked for overdispersion, underdispersion, zero-inflation, and heteroscedasticity with the DHARMa R package [@hartig2019dharma].
### P1: Negative relationship between the number of trials to reverse a preference and the number of reversals?
\
**Analysis:** Response variable: Number of trials to reverse a preference. We use a sliding window to look at the most recent 10 trials for a bird, regardless of when the testing sessions occurred. Explanatory variable: reversal number. Random variables: batch (batch is a test cohort, consisting of 8 birds being tested simultaneously and there were multiple batches included in the analysis) and ID (random effect because there were repeated measures on the same individuals). A Generalized Linear Mixed Model [GLMM, MCMCglmm function, MCMCglmm package, @hadfield2010mcmc] was used with a Poisson distribution and log link using 300,000 iterations with a thinning interval of 500, a burnin of 90,000, and minimal priors (V=1, nu=0) [@hadfield2014coursenotes]. We ensured the GLMM showed acceptable convergence [lag time autocorrelation values <0.01, @hadfield2010mcmc], and adjusted parameters as necessary.
We did not need a power analysis to estimate our ability to detect actual effects because, by definition, the individuals that complete this experiment must get faster at reversing in order to pass the stopping criterion (two consecutive reversals in 50 trials or less). According to previous grackle data [from the pilot birds, and from Santa Barbara @logan2016behavioral], the fastest grackle passed their first reversal in 70 trials, which means that passing our serial reversal stopping criterion would require them to have improved their passing speed.
```{r serial, eval=F}
d <- read.csv(url("https://raw.githubusercontent.com/corinalogan/grackles/master/Files/Preregistrations/g_flexmanip_data_reverse.csv"), header=T, sep=",", stringsAsFactors=F)
d <- d[!d$ID=="Fajita" & !d$ID=="Empanada",] #remove Fajita because she was a pilot bird
#remove NAs from the variables that will be in the model
d <- subset(d,!(is.na(d["TrialsToReverse"])))
d <- subset(d,!(is.na(d["ReverseNumber"])))
#include only those birds in the reversal tubes experiment and only those in the manipulation condition bc only these will have more than one reversal (and thus something to correlate). Exclude Memela because she never passed the manipulation criterion
d <- d[d$TubesOrTouchscreen=="TUBES" & d$ExperimentalGroup=="Manipulation" & !d$ID=="Memela",]
#factor variables
d$Batch <- as.factor(d$Batch)
d$ID <- as.factor(d$ID) #n=8 individuals
# DATA CHECKING
library(DHARMa)
library(lme4)
# using MCMCglmm
library(MCMCglmm)
prior = list(R = list(R1 = list(V = 1, nu = 0)), G = list(G1 = list(V = 1, nu = 0), G2 = list(V = 1, nu = 0)))
model <- MCMCglmm(TrialsToReverse ~ ReverseNumber, random = ~us(ReverseNumber):ID+Batch,
family = "poisson", data = d, verbose = F, prior = prior,
nitt = 300000, thin = 500, burnin = 90000)
### Making DHARMa work for MCMCglmm
# instructions on applying DHARMa to Bayesian models (using BRMS): https://frodriguezsanchez.net/post/using-dharma-to-check-bayesian-models-fitted-with-brms/. To get it to work for MCMCglmm, I had to change posterior_predict to predict (https://rdrr.io/cran/MCMCglmm/man/predict.MCMCglmm.html). Dieter Lukas then figured out the code for simulatedResponse
modelcheck <- createDHARMa(
simulatedResponse = simulate(model,nsim=250),
observedResponse = d$TrialsToReverse,
fittedPredictedResponse = apply(simulate(model,nsim=250), 1, mean),
integerResponse = TRUE)
plot(modelcheck)
#KS test p=0.47 so not heteroscedastic, dispersion test p=0.66 so not dispersed, outlier test p=0.92 so not zero inflated, residual vs predicted: no significant problems detected.
#compared to how we previously applied DHARMa to a glm (because we couldn't figure out how to apply it to a MCMCglmm), the results are the same except the MCMCglmm version is not dispersed, whereas the GLM version was.
# using glm - we did not use this in the article - we used the one for MCMCglmm above
simulationOutput <- simulateResiduals(fittedModel = glmer(TrialsToReverse ~ ReverseNumber + (1|ID) + (1|Batch), family=poisson, data=d), n=250) #250 simulations, but if want higher precision change n>1000
plot(simulationOutput$scaledResiduals) #Expect a flat distribution of the overall residuals, and uniformity in y direction if plotted against any predictor.
#Looks randomly scattered
testDispersion(simulationOutput) #if under- or over-dispersed, then p-value<0.05, but then check the dispersion parameter and try to determine what in the model could be the cause and address it there, also check for zero inflation.
#p=0.00, it is underdispersed according to the plot at https://cran.r-project.org/web/packages/DHARMa/vignettes/DHARMa.html.
testZeroInflation(simulationOutput) #compare expected vs observed zeros, not zero-inflated if p<0.05
#p=1 so not zero inflated
testUniformity(simulationOutput) #check for heteroscedasticity ("a systematic dependency of the dispersion / variance on another variable in the model" Hartig, https://cran.r-project.org/web/packages/DHARMa/vignettes/DHARMa.html), which is indicated if dots aren't on the red line and p<0.05.
#p=0.06 so it is not heteroscedastic
plot(simulationOutput) #...there should be no pattern in the data points in the right panel
#There is a pattern in the right panel
#January 2021: My interpretation of the statistically significant underdispersion in the data is that this was a manipulation, therefore, by definition the data will not be randomly (normally) distributed. Therefore, we will move forward with the glmm as planned.
# GLMM
library(MCMCglmm)
prior = list(R = list(R1 = list(V = 1, nu = 0)), G = list(G1 = list(V = 1, nu = 0), G2 = list(V = 1, nu = 0)))
serial <- MCMCglmm(TrialsToReverse ~ ReverseNumber, random = ~ID+Batch, family = "poisson", data = d, verbose = F, prior = prior, nitt = 300000, thin = 500, burnin = 90000)
#reverse number significantly negatively correlates with trials to reverse, as expected due to the manipulation
summary(serial)
#Did fixed effects converge (<0.1)? Yes
autocorr(serial$Sol)
#Did random effects converge (<0.1)? Yes except for 2 values: 0.11 and 0.12
autocorr(serial$VCV)
# with random slope for ID
priorr = list(R = list(R1 = list(V = 1, nu = 0.002)), G = list(G1 = list(V=diag(2), nu=0.002), G2 = list(V = 1, nu = 0.002))) #set nu to 0.002 (because it must be >0) according to p13 https://cran.microsoft.com/snapshot/2019-12-07/web/packages/MCMCglmm/vignettes/CourseNotes.pdf. nu is the belief parameter so a small nu means less belief (uninformed priors)
serialr <- MCMCglmm(TrialsToReverse ~ ReverseNumber, random = ~idh(1+ReverseNumber):ID+Batch, family = "poisson", data = d, verbose = F, prior = priorr, nitt = 300000, thin = 500, burnin = 90000)
summary(serialr)
#same result as without random slopes: a significant negative correlation between trials to reverse and reversal number
#AIC calculation
library(MuMIn)
options(na.action = "na.fail")
base <- dredge(MCMCglmm(TrialsToReverse ~ ReverseNumber, random = ~ID+Batch,
family = "poisson", data = d, verbose = F, prior = prior,
nitt = 300000, thin = 500, burnin = 90000))
library(knitr)
kable(base, caption="")
```
**Unregistered analyses:** We evaluated whether the individuals in both conditions (manipulated and control) required a similar number of trials to pass their first reversal (dependent variable: trials to reverse in first reversal, explanatory variable: condition, random variables: ID and batch; Table 1), and their last reversal (dependent variable: trials to reverse in last reversal, explanatory variable: condition, random variables: ID and batch; Table 3).
### P2: Serial reversal improves rule switching and innovativeness
\
**Analyses:** One model was run per response variable: average latency to attempt to solve a new locus after solving a different locus, and total number of loci solved. Explanatory variable: Number of trials to reverse a preference in the last reversal.
The model for the number of loci solved takes the form of:
$locisolved_{i,j}$ ~ Binomial(4, $p$) *[likelihood]*,
logit(*p*) ~ $\alpha$ + $\beta$trials$_{i,j}$ *[model]*,
where $locisolved_{i,j}$ is the number of loci solved on the multi-access box, 4 is the total number of loci on the multi-access box, $p$ is the probability of solving any one locus across the whole experiment, $\alpha$ is the intercept, $\beta$ is the expected amount of change in $locisolved_{i,j}$ for every one unit change in $trials_{i,j}$, and $trials_{i,j}$ is the number of trials to reverse a shade preference. See Supplementary Material 1 for more model details.
The model for the latency to switch options takes the form of:
$latency_{i,j}$ ~ gamma-Poisson($\lambda_{i,j}$, $\phi$) *[likelihood]*,
log($\lambda_{i,j}$) ~ $\alpha$ + $\beta$trials$_{i,j}$ *[model]*,
where $latency_{i,j}$ is the average latency to attempt a new locus on the multi-access box, $\lambda_i$ is the rate (probability of attempting a locus in each second) per bird (and we take the log of it to make sure it is always positive; birds with a higher rate have a smaller latency), $\phi$ is the dispersion of the rates across birds, $\alpha$ is the intercept for the rate, $\beta$ is the expected amount of change in the rate of attempting to solve in any given second for every one unit change in trials, and trials is the number of trials to reverse a shade preference. Note that a gamma-Poisson distribution is also known as negative binomial. See Supplementary Material 1 for more model details.
Note: As originally planned, we replaced the GLMs and GLMMs in May 2020 with more powerful models after learning how to make bespoke Bayesian models from @mcelreath2018statistical We made these models before analyzing the actual data (14 May 2020).
```{r improves, eval=F}
d <- read.csv(url("https://raw.githubusercontent.com/corinalogan/grackles/master/Files/Preregistrations/g_flexmanip_datasummary.csv"), header=T, sep=",", stringsAsFactors=F)
d <- data.frame(d)
colnames(d) <- c("Bird","Batch","Sex","Trials to learn","TrialsFirstReversal","TrialsLastReversal","ReversalsToPass","TotalLociSolvedMABplastic","TotalLociSolvedMABwooden","AverageLatencyAttemptNewLocusMABplastic","AverageLatencyAttemptNewLocusMABwooden","Trials to learn (touchscreen)","Trials to first reversal (touchscreen)","MotorActionsPlastic","MotorActionsWooden")
##### This is the model code from the ability to detect actual effects section, copied here for clarity
#remove pilot birds and Taco because he was the only one in batch "Juvenile"
d2 <- d[!d$Bird=="Fajita" & !d$Bird=="Empanada",]
#ulam doesn't like that batch is not consecutive (there is no batch 2 in this sample, only 1, 3 and 4), so renamed batches 3 and 4, 2 and 3, respectively
d2$Batch[d2$Batch==3]<-2
d2$Batch[d2$Batch==4]<-3
d2$Batch[d2$Batch=="3a"]<-4 #This is Taco bc he wasn't officially in a batch due to him being the first juvenile we ever tested so we wanted to see if he performed similarly to the adults and he did
d2$Batch<-as.integer(d2$Batch)
#load libraries
library(rethinking)
library(rstan)
library(formatR)
### MAB PLASTIC LOCI last reversal
#remove NAs from the variables that will be in the models. n=17
d3 <- subset(d2,!(is.na(d2["Trialstoreverselast"])) & !(is.na(d2["TotalLoci_plastic"])))
dlist <- list(locisolved = d3$TotalLoci_plastic,
trials = standardize(d3$Trialstoreverselast),
batch = as.integer(d3$Batch)
)
mloci <- ulam( alist(
locisolved ~ dbinom(4,p) , #4 loci, p=probability of solving a locus
logit(p) <- a[batch] + b*trials , #batch=random effect, standardize trials so 0=mean
a[batch] ~ dnorm(0,1) , #each batch gets its own intercept
b ~ dnorm(0,0.4) #our prior expectation for b is that it is around 0, can be negative or positive, and should not be larger than 1. normal distribution works for binomial (Rethinking p.341)
) , data=dlist , chains=4 , log_lik=TRUE )
precis(mloci,depth=2)
# a=number of loci solved: was there a difference betweeen batches? Yes, batch 1 solved more loci
#b=effect of trials to reverse last on the number of loci solved. Results show that there are no relationships between the number of loci solved and the trials to reverse last (across all batches)
#mean sd 5.5% 94.5% n_eff Rhat
#a[1] 0.61 0.39 0.01 1.22 3289 1
#a[2] 0.44 0.39 -0.19 1.06 2763 1
#a[3] -0.76 0.56 -1.65 0.11 3031 1
#a[4] -0.48 0.75 -1.70 0.65 3743 1
#b -0.28 0.26 -0.69 0.13 2905 1
### MAB LOG LOCI last reversal
#remove NAs from the variables that will be in the models. n=12
d4 <- subset(d2,!(is.na(d2["Trialstoreverselast"])) & !(is.na(d2["TotalLoci_wooden"])))
dlistLog <- list(locisolved = d4$TotalLoci_wooden,
trials = standardize(d4$Trialstoreverselast),
batch = as.integer(d4$Batch)
)
mlociw <- ulam( alist(
locisolved ~ dbinom(4,p) , #4 loci, p=probability of solving a locus
logit(p) <- a[batch] + b*trials , #batch=random effect, standardize trials so 0=mean
a[batch] ~ dnorm(0,1) , #each batch gets its own intercept
b ~ dnorm(0,0.4) #our prior expectation for b is that it is around 0, can be negative or positive, and should not be larger than 1. normal distribution works for binomial (Rethinking p.341)
) , data=dlistLog , chains=4 , log_lik=TRUE )
precis(mlociw,depth=2)
#a=number of loci solved: was there a difference betweeen batches? Yes, batches 2 and 3 (actually 3 and 4) solved more loci on the log. However, there was only 1 bird (Mole) in batch 1 (he solved all 4)
#b=effect of trials to reverse last on the number of loci solved. There was no relationship between trials to reverse the last preference and the number of loci solved
#mean sd 5.5% 94.5% n_eff Rhat
#a[1] 1.09 0.75 -0.09 2.35 2820 1
#a[2] 0.83 0.37 0.26 1.44 2595 1
#a[3] 1.45 0.63 0.47 2.49 2432 1
#a[4] 1.08 0.76 -0.10 2.36 2573 1
#b 0.14 0.29 -0.32 0.62 2539 1
#plot
op <- par(mfrow=c(1,1), oma=c(0,0,0,0), mar=c(4.5,4.5,2,0.2), cex.lab=1.8, cex.axis=2)
plot(jitter(d3$Trialstoreverselast),jitter(d3$TotalLoci_plastic), ylab="Number of loci solved", xlab="Trials in last reversal", ylim=c(0,5), xlim=c(0,170), cex=4, pch=2, yaxt="n")
points(jitter(d4$Trialstoreverselast),jitter(d4$TotalLoci_wooden), cex=4, pch=1, yaxt="n")
legend(x="topright", y=8, legend=c(pch2="Plastic", pch1="Wooden"), pch=c(2,1), box.lty=1, cex=2)
axis(side=2, at=c(1,2,3,4))
par(op)
### MAB PLASTIC SWITCH last reversal
#Load packages
library("Rcpp")
library(ggplot2)
#remove NAs from the variables that will be in the models. n=11
d5 <- subset(d2,!(is.na(d2["Trialstoreverselast"])) & !(is.na(d2["AvgLatencyAttemptNewLoci_plastic"])))
dlist5 <- list(latency = d5$AvgLatencyAttemptNewLoci_plastic,
trials = standardize(d5$Trialstoreverselast),
batch = as.integer(d5$Batch)
)
mswitchp <- ulam(
alist(
latency ~ dgampois(lambda, phi),
log(lambda) <- a[batch] + b*trials,
a[batch] ~ dnorm(1,1),
b ~ dnorm(0,1),
phi ~ dexp(1)
),data=dlist5, log_lik=TRUE, messages=FALSE)
precis(mswitchp,depth=2)
#phi=dispersion of gamma poisson, b=effect of trials to reverse on latency, a=were some batches faster to switch
#b=no correlation between average switch latencies and number of trials in last reversal
#mean sd 5.5% 94.5% n_eff Rhat
#a[1] 4.74 0.45 3.97 5.39 208 1
#a[2] 3.64 0.42 2.99 4.32 278 1
#a[3] 4.63 0.58 3.69 5.53 216 1
#b 0.32 0.26 -0.06 0.77 438 1
#phi 0.78 0.43 0.27 1.60 200 1
### MAB LOG SWITCH last reversal
#remove NAs from the variables that will be in the models. n=11
d6 <- subset(d2,!(is.na(d2["Trialstoreverselast"])) & !(is.na(d2["AvgLatencyAttemptNewLoci_wooden"])))
dlist6 <- list(latency = d6$AvgLatencyAttemptNewLoci_wooden,
trials = standardize(d6$Trialstoreverselast),
batch = as.integer(d6$Batch)
)
mswitchw <- ulam(
alist(
latency ~ dgampois(lambda, phi),
log(lambda) <- a[batch] + b*trials,
a[batch] ~ dnorm(1,1),
b ~ dnorm(0,1),
phi ~ dexp(1)
),data=dlist6, log_lik=TRUE, messages=FALSE)
precis(mswitchw,depth=2)
#phi=dispersion of gamma poisson, b=effect of trials to reverse on latency, a=were some batches faster to switch
#b=no correlation between average switch latencies and number of trials in last reversal
#mean sd 5.5% 94.5% n_eff Rhat
#a[1] 4.17 0.68 3.07 5.25 208 1
#a[2] 4.52 0.60 3.54 5.43 237 1
#a[3] 4.27 0.60 3.36 5.22 207 1
#a[4] 2.66 0.73 1.57 3.89 304 1
#b -0.27 0.36 -0.81 0.36 304 1
#phi 0.20 0.12 0.06 0.45 162 1
#plot
op <- par(mfrow=c(1,1), oma=c(0,0,0,0), mar=c(4.5,4.5,2,0.2), cex.lab=1.8, cex.axis=2)
plot(jitter(d5$Trialstoreverselast),jitter(d5$AvgLatencyAttemptNewLoci_plastic), ylab="Average seconds to attempt a new locus", xlab="Trials in last reversal", ylim=c(0,1500), xlim=c(0,170), cex=4, pch=2, yaxt="n")
points(jitter(d6$Trialstoreverselast),jitter(d6$AvgLatencyAttemptNewLoci_wooden), cex=4, pch=1, yaxt="n")
legend(x="topright", y=8, legend=c(pch2="Plastic", pch1="Wooden"), pch=c(2,1), box.lty=1, cex=2)
axis(side=2, at=c(100,200,300,400,500,600,700,800,900,1000,1100,1200,1300,1400,1500))
par(op)
###### BELOW was in the original preregistration ######
#Is performance on the two multi-access boxes correlated?
#cor(d$AvgLatencySolveNewLoci_plastic, d$AvgLatencySolveNewLoci_wooden) #we no longer run this analyses bc switching is about the next attempt, not the next solve
cor.test(d2$AverageLatencyAttemptNewLocusMABplastic, d2$AverageLatencyAttemptNewLocusMABwooden, use="pairwise.complete.obs", method="pearson")
#plastic and wooden are not significantly correlated cor=0.74 (95% Confidence Interval=-0.19-0.97), t=2.18, df=4, p=0.09
cor.test(d2$TotalLociSolvedMABplastic, d2$TotalLociSolvedMABwooden, use="pairwise.complete.obs", method="pearson")
#plastic and wooden are not significantly correlated cor=0.51 (95% Confidence Interval=-0.09-0.84), t=1.86, df=10, p=0.09
# DATA CHECKING
library(DHARMa)
library(lme4)
simulationOut <- simulateResiduals(fittedModel = glmer(TrialsToReverse ~ Condition + AvgLatencySolveNewLoci + AvgLatencyAttemptNewLoci + TotalLoci + (1|Batch), family=poisson, data=improve), n=250) #250 simulations, but if want higher precision change n>1000
simulationOut$scaledResiduals #Expect a flat distribution of the overall residuals, and uniformity in y direction if plotted against any predictor
testDispersion(simulationOut) #if under- or over-dispersed, then p-value<0.05, but then check the dispersion parameter and try to determine what in the model could be the cause and address it there, also check for zero inflation
testZeroInflation(simulationOut) #compare expected vs observed zeros, not zero-inflated if p<0.05
testUniformity(simulationOut) #check for heteroscedasticity ("a systematic dependency of the dispersion / variance on another variable in the model" Hartig, https://cran.r-project.org/web/packages/DHARMa/vignettes/DHARMa.html), which is indicated if dots aren't on the red line and p<0.05. Also...
plot(simulationOut) #...there should be no pattern in the data points in the right panel
plotResiduals(Condition, simulationOut$scaledResiduals) #plot the residuals against other predictors (in cases when there is more than 1 fixed effect) - can't get this code to work yet
# GLMM
library(MCMCglmm)
prior = list(R = list(R1 = list(V = 1, nu = 0)), G = list(G1 = list(V = 1,
nu = 0), G2 = list(V = 1, nu = 0)))
imp <- MCMCglmm(TrialsToReverse ~ Condition + AvgLatencySolveNewLoci +
AvgLatencyAttemptNewLoci + TotalLoci, random = ~Batch,
family = "poisson", data = improve, verbose = F, prior = prior,
nitt = 13000, thin = 10, burnin = 3000)
summary(imp)
# autocorr(imp$Sol) #Did fixed effects converge?
# autocorr(imp$VCV) #Did random effects converge?
```
**Unregistered analysis:** Because the wooden multi-access box was added after in principle recommendation, we conducted an unregistered analysis to determine whether the plastic and wooden multi-access box results correlated with each other, which would indicate that these tests are interchangeable. We found that they did not statistically significantly correlate with each other on either variable measured: the average latency to attempt a new locus (switching; Pearson's r=0.74, 89% confidence level=0.02-0.95, t=2.18, df=4, p=0.09, n=6) or the total number of loci solved (problem solving; Pearson's r=0.51, 89% confidence level=0.03-0.80, t=1.86, df=10, p=0.09, n=12). Therefore, while the performance on the two multi-access boxes might not be completely independent as indicated by the high r values, the two boxes appear not to be completely interchangeable either as indicated by the lack of statistical significance and high uncertainty in the r values. We therefore analyzed the plastic and wooden multi-access boxes separately.
```{r mabscorr, eval=TRUE}
#Is performance on the two multi-access boxes correlated?
d <- read.csv(url("https://raw.githubusercontent.com/corinalogan/grackles/master/Files/Preregistrations/g_flexmanip_datasummary.csv"), header=T, sep=",", stringsAsFactors=F)
d <- data.frame(d)
colnames(d) <- c("Bird","Batch","Sex","Trials to learn","TrialsFirstReversal","TrialsLastReversal","ReversalsToPass","TotalLociSolvedMABplastic","TotalLociSolvedMABwooden","AverageLatencyAttemptNewLocusMABplastic","AverageLatencyAttemptNewLocusMABwooden","Trials to learn (touchscreen)","Trials to first reversal (touchscreen)","MotorActionsPlastic","MotorActionsWooden")
##### This is the model code from the ability to detect actual effects section, copied here for clarity
#remove pilot birds and Taco because he was the only one in batch "Juvenile"
d2 <- d[!d$Bird=="Fajita" & !d$Bird=="Empanada",]
#cor(d$AvgLatencySolveNewLoci_plastic, d$AvgLatencySolveNewLoci_wooden) #we no longer run this analyses bc switching is about the next attempt, not the next solve
#cor.test(d2$AverageLatencyAttemptNewLocusMABplastic, d2$AverageLatencyAttemptNewLocusMABwooden, use="pairwise.complete.obs", method="pearson", conf.level=0.89)
#plastic and wooden are not significantly correlated cor=0.74 (89% Confidence level=0.02-0.95), t=2.18, df=4, p=0.09
#cor.test(d2$TotalLociSolvedMABplastic, d2$TotalLociSolvedMABwooden, use="pairwise.complete.obs", method="pearson", conf.level=0.89)
#plastic and wooden are not significantly correlated cor=0.51 (89% Confidence level=0.03-0.80), t=1.86, df=10, p=0.09
```
Post-data collection, we added an additional unregistered analysis comparing first versus last reversal performance for the individuals in the manipulated group (see r code chunk “posthoc_conditionalimprovement” at the rmd for model details).
### P2 alternative 2: Additional analysis: latency and motor diversity
\
**Analyses:** We ran one model per response variable: average latency to attempt a new locus on the multi-access boxes, and number of trials to solve (meet criterion) a new locus on the multi-access boxes. Explanatory variables: Number of trials to reverse a preference in the last reversal that an individual participated in, the number of different motor actions used when attempting to solve the multi-access boxes (motor diversity). A General Linear Model (GLM; glm function) was used with a Poisson distribution and log link.
```{r diversity1P, eval=F}
### NOTE: did not end up using this analysis because only the wooden MAB met the conditions for P2 alternative 2
#Latency to attempt to solve a new locus
dp <- read.csv(url("https://raw.githubusercontent.com/corinalogan/grackles/master/Files/Preregistrations/g_flexmanip_datasummary.csv"), header=F, sep=",", stringsAsFactors=F)
dp <- data.frame(dp)
colnames(dp) <- c("Bird","Batch","Sex","Trials to learn","TrialsFirstReversal","TrialsLastReversal","ReversalsToPass","TotalLociSolvedMABplastic","TotalLociSolvedMABwooden","AverageLatencyAttemptNewLocusMABplastic","AverageLatencyAttemptNewLocusMABwooden","Trials to learn (touchscreen)","Trials to first reversal (touchscreen)","MotorActionsPlastic","MotorActionsWooden")
# Remove NAs
dp <- subset(dp,!(is.na(dp["MotorActionsPlastic"])) & !(is.na(dp["TrialsLastReversal"])) & !(is.na(dp["AverageLatencyAttemptNewLocusMABplastic"])))
# n=11: 6 in manipulated group, 5 in control group
#length(dp$AverageLatencyAttemptNewLocusMABplastic)
# look at the data
#hist(dp$AverageLatencyAttemptNewLocusMABplastic)
#mean(dp$AverageLatencyAttemptNewLocusMABplastic) #208
#sd(dp$AverageLatencyAttemptNewLocusMABplastic) #226
#hist(dp$MotorActionsPlastic)
#mean(dp$MotorActionsPlastic) #14
#sd(dp$MotorActionsPlastic) #3
#mean(dp$TrialsLastReversal) #52
#sd(dp$TrialsLastReversal) #22
#mean(dp$TrialsFirstReversal) #70
#sd(dp$TrialsFirstReversal) #21
# PLASTIC MULTI-ACCESS BOX (P)
# DATA CHECKING
library(DHARMa)
library(lme4)
simulationOutp <- simulateResiduals(fittedModel = glmer(AverageLatencyAttemptNewLocusMABplastic ~ TrialsLastReversal + MotorActionsPlastic + (1|Bird), family=poisson, data=dp), n=250) #250 simulations, but if want higher precision change n>1000
plot(simulationOutp$scaledResiduals) #Expect a flat distribution of the overall residuals, and uniformity in y direction if plotted against any predictor. Looks randomly scattered
testDispersion(simulationOutp) #if under- or over-dispersed, then p-value<0.05, but then check the dispersion parameter and try to determine what in the model could be the cause and address it there, also check for zero inflation. p=0.992 so not over or under dispersed
testZeroInflation(simulationOutp) #compare expected vs observed zeros, not zero-inflated if p<0.05. p=1 so not zero inflated
testUniformity(simulationOutp) #check for heteroscedasticity ("a systematic dependency of the dispersion / variance on another variable in the model" Hartig, https://cran.r-project.org/web/packages/DHARMa/vignettes/DHARMa.html), which is indicated if dots aren't on the red line and p<0.05. p=0.45 so not heterscedastic
plot(simulationOutp) #...there should be no pattern in the data points in the right panel. There is no pattern
# GLM
motp <- glm(dp$AverageLatencyAttemptNewLocusMABplastic ~ dp$TrialsLastReversal + dp$MotorActionsPlastic, family = poisson)
# AIC calculation
library(MuMIn)
options(na.action = "na.fail")
dredgemp <- dredge(glm(dp$AverageLatencyAttemptNewLocusMABplastic ~ dp$TrialsLastReversal + dp$MotorActionsPlastic))
library(knitr)
kable(dredgemp, caption = "")
#Akaike weights are all >0.5, therefore the models are essentially the same
#22 Feb 2023: realized that the glm default family was used, which is gaussian and we specified in the preregistration that this was a poisson family. So I ran the model with both families and found the exact same results so nothing needs to be changed in the table
#gaussian family results
#(Intercept) dpMotorActionsPlastic|dpTrialsLastReversal df logLik AICc delta weight
#1 207.63636 NA NA 2 -74.69601 154.8920 0.0000000 0.49007426
#3 -60.94031 NA 5.155922 3 -72.96256 155.3537 0.4616654 0.38905637
#2 430.86441 -16.37006 NA 3 -74.40936 158.2473 3.3552730 0.09155322
#4 -161.40544 5.74627 5.580313 4 -72.92910 160.5249 5.6328367 0.02931615
#poisson family results
# (Intercept) dpMotorActionsPlastic|dpTrialsLastReversal df logLik AICc delta weight
#1 207.63636 NA NA 2 -74.69601 154.8920 0.0000000 0.49007426
#3 -60.94031 NA 5.155922 3 -72.96256 155.3537 0.4616654 0.38905637
#2 430.86441 -16.37006 NA 3 -74.40936 158.2473 3.3552730 0.09155322
#4 -161.40544 5.74627 5.580313 4 -72.92910 160.5249 5.6328367 0.02931615
### GLMM - can't use this because only 1 data point per bird
library(MCMCglmm)
prior = list(R = list(R1 = list(V = 1, nu = 0), R2 = list(V = 1, nu = 0)), G = list(G1 = list(V = 1,
nu = 0)))
div <- MCMCglmm(AverageLatencyAttemptNewLocusMABplastic ~ TrialsLastReversal + MotorActionsPlastic, random = ~Bird,
family = "poisson", data = diversity, verbose = F, prior = prior,
nitt = 13000, thin = 10, burnin = 3000)
summary(div)
# autocorr(div$Sol) #Did fixed effects converge?
# autocorr(div$VCV) #Did random effects converge?
# AIC calculation
library(MuMIn)
options(na.action = "na.fail")
base1 <- dredge(MCMCglmm(TrialsToSolveNewLociP ~ TrialsToReverseLast + NumberMotorActionsMultiP, random = ~ID,
family = "poisson", data = diversity, verbose = F, prior = prior,
nitt = 13000, thin = 10, burnin = 3000))
library(knitr)
kable(base1, caption = "")
```
```{r diversity1W, eval=F}
# WOODEN MULTI-ACCESS BOX (W)
dw <- read.csv(url("https://raw.githubusercontent.com/corinalogan/grackles/master/Files/Preregistrations/g_flexmanip_datasummary.csv"), header=F, sep=",", stringsAsFactors=F)
dw <- data.frame(dw)
colnames(dw) <- c("Bird","Batch","Sex","Trials to learn","TrialsFirstReversal","TrialsLastReversal","ReversalsToPass","TotalLociSolvedMABplastic","TotalLociSolvedMABwooden","AverageLatencyAttemptNewLocusMABplastic","AverageLatencyAttemptNewLocusMABwooden","Trials to learn (touchscreen)","Trials to first reversal (touchscreen)","MotorActionsPlastic","MotorActionsWooden")
# Remove NAs
dw <- subset(dw,!(is.na(dw["MotorActionsWooden"])) & !(is.na(dw["TrialsLastReversal"])) & !(is.na(dw["AverageLatencyAttemptNewLocusMABwooden"])))
# n=11: 5 in manipulated group, 6 in control group
#length(dw$AverageLatencyAttemptNewLocusMABwooden)
# look at the data
#hist(dw$AverageLatencyAttemptNewLocusMABwooden)
#mean(dw$AverageLatencyAttemptNewLocusMABwooden) #463
#sd(dw$AverageLatencyAttemptNewLocusMABwooden) #481
#hist(dw$MotorActionsWooden)
#mean(dw$MotorActionsWooden) #13
#sd(dw$MotorActionsWooden) #4
#mean(dw$TrialsLastReversal) #60
#sd(dw$TrialsLastReversal) #38
# DATA CHECKING
library(DHARMa)
library(lme4)
simulationOutw <- simulateResiduals(fittedModel = glm(dw$AverageLatencyAttemptNewLocusMABwooden ~ dw$TrialsLastReversal + dw$MotorActionsWooden), n=250) #250 simulations, but if want higher precision change n>1000
plot(simulationOutw$scaledResiduals) #Expect a flat distribution of the overall residuals, and uniformity in y direction if plotted against any predictor. Looks randomly scattered
testDispersion(simulationOutw) #if under- or over-dispersed, then p-value<0.05, but then check the dispersion parameter and try to determine what in the model could be the cause and address it there, also check for zero inflation. p=0.744 so not over or under dispersed
testZeroInflation(simulationOutw) #compare expected vs observed zeros, not zero-inflated if p<0.05. p=1 so not zero inflated
testUniformity(simulationOutw) #check for heteroscedasticity ("a systematic dependency of the dispersion / variance on another variable in the model" Hartig, https://cran.r-project.org/web/packages/DHARMa/vignettes/DHARMa.html), which is indicated if dots aren't on the red line and p<0.05. p=0.53 so not heteroscedastic
plot(simulationOutw) #...there should be no pattern in the data points in the right panel. It says "quantile deviations detected"
# GLM
motw <- glm(dw$AverageLatencyAttemptNewLocusMABwooden ~ dw$TrialsLastReversal + dw$MotorActionsWooden)
# AIC calculation
library(MuMIn)
options(na.action = "na.fail")
dredgemw <- dredge(glm(dw$AverageLatencyAttemptNewLocusMABwooden ~ dw$TrialsLastReversal + dw$MotorActionsWooden))
library(knitr)
kable(dredgemw, caption = "")
#Akaike weights = 0.71 null and <0.15 for the rest, therefore the models with or without motor actions are essentially the same
# GLMM - does not work because only one data point per bird
library(MCMCglmm)
prior = list(R = list(R1 = list(V = 1, nu = 0), R2 = list(V = 1, nu = 0)), G = list(G1 = list(V = 1,
nu = 0)))
div <- MCMCglmm(TrialsToSolveNewLociW ~ TrialsToReverseLast + NumberMotorActionsMultiW, random = ~ID,
family = "poisson", data = diversity, verbose = F, prior = prior,
nitt = 13000, thin = 10, burnin = 3000)
summary(div)
# autocorr(div$Sol) #Did fixed effects converge?
# autocorr(div$VCV) #Did random effects converge?
# AIC calculation
library(MuMIn)
options(na.action = "na.fail")
base1 <- dredge(MCMCglmm(TrialsToSolveNewLociW ~ TrialsToReverseLast + NumberMotorActionsMultiW, random = ~ID,
family = "poisson", data = diversity, verbose = F, prior = prior,
nitt = 13000, thin = 10, burnin = 3000))
library(knitr)
kable(base1, caption = "")
```
```{r diversity2P, eval=F}
### NOTE: did not end up using this analysis because only the wooden MAB met the conditions for P2 alternative 2
#Latency to solve a new locus
d <- read.csv(url("https://raw.githubusercontent.com/corinalogan/grackles/master/Files/Preregistrations/g_flexmanip_datasummary.csv"), header=F, sep=",", stringsAsFactors=F)
diversity <- read.csv ("/Users/corina/GTGR/data/data_reversemulti.csv", header=T, sep=",", stringsAsFactors=F)
# PLASTIC MULTI-ACCESS BOX (P)
# DATA CHECKING
library(DHARMa)
library(lme4)
simulationOutpu <- simulateResiduals(fittedModel = glmer(TrialsToAttemptNewLociP ~ TrialsToReverseLast + NumberMotorActionsMultiP + (1|ID), family=poisson, data=diversity), n=250) #250 simulations, but if want higher precision change n>1000
simulationOutpu$scaledResiduals #Expect a flat distribution of the overall residuals, and uniformity in y direction if plotted against any predictor
testDispersion(simulationOutpu) #if under- or over-dispersed, then p-value<0.05, but then check the dispersion parameter and try to determine what in the model could be the cause and address it there, also check for zero inflation
testZeroInflation(simulationOutpu) #compare expected vs observed zeros, not zero-inflated if p<0.05
testUniformity(simulationOutpu) #check for heteroscedasticity ("a systematic dependency of the dispersion / variance on another variable in the model" Hartig, https://cran.r-project.org/web/packages/DHARMa/vignettes/DHARMa.html), which is indicated if dots aren't on the red line and p<0.05. Also...
plot(simulationOutpu) ##...there should be no pattern in the data points in the right panel
plotResiduals(NumberMotorActionsMultiP, simulationOutpu$scaledResiduals) #plot the residuals against other predictors - can't get this code to work yet
plotResiduals(TrialsToReverseLast, simulationOutpu$scaledResiduals)
# GLMM
library(MCMCglmm)
prior = list(R = list(R1 = list(V = 1, nu = 0), R2 = list(V = 1, nu = 0)), G = list(G1 = list(V = 1,
nu = 0)))
div <- MCMCglmm(TrialsToAttemptNewLociP ~ TrialsToReverseLast + NumberMotorActionsMultiP, random = ~ID,
family = "poisson", data = diversity, verbose = F, prior = prior,
nitt = 13000, thin = 10, burnin = 3000)
summary(div)
# autocorr(div$Sol) #Did fixed effects converge?
# autocorr(div$VCV) #Did random effects converge?
# AIC calculation
library(MuMIn)
options(na.action = "na.fail")
base1 <- dredge(MCMCglmm(TrialsToAttemptNewLociP ~ TrialsToReverseLast + NumberMotorActionsMultiP, random = ~ID,
family = "poisson", data = diversity, verbose = F, prior = prior,
nitt = 13000, thin = 10, burnin = 3000))
library(knitr)
kable(base1, caption = "")
```
```{r diversity2W, eval=F}
### NOTE: did not end up using this analysis because the total number of loci solved on the wooden MAB did not meet the conditions for P2 alternative 2
# WOODEN MULTI-ACCESS BOX (W)
#Latency to solve a new locus
dw <- read.csv(url("https://raw.githubusercontent.com/corinalogan/grackles/master/Files/Preregistrations/g_flexmanip_datasummary.csv"), header=F, sep=",", stringsAsFactors=F)
dw <- data.frame(dw)
colnames(dw) <- c("Bird","Batch","Sex","Trials to learn","TrialsFirstReversal","TrialsLastReversal","ReversalsToPass","TotalLociSolvedMABplastic","TotalLociSolvedMABwooden","AverageLatencyAttemptNewLocusMABplastic","AverageLatencyAttemptNewLocusMABwooden","Trials to learn (touchscreen)","Trials to first reversal (touchscreen)","MotorActionsPlastic","MotorActionsWooden")
# Remove NAs
dw <- subset(dw,!(is.na(dw["MotorActionsWooden"])) & !(is.na(dw["TrialsLastReversal"])) & !(is.na(dw["TotalLociSolvedMABwooden"])))
# n=12: 6 in manipulated group, 6 in control group
#length(dw$TotalLociSolvedMABwooden)
# look at the data
#hist(dw$TotalLociSolvedMABwooden)
#mean(dw$TotalLociSolvedMABwooden) #3.25
#sd(dw$TotalLociSolvedMABwooden) #1.22
#hist(dw$MotorActionsWooden)
#mean(dw$MotorActionsWooden) #12.4
#sd(dw$MotorActionsWooden) #5.2
#mean(dw$TrialsLastReversal) #58
#sd(dw$TrialsLastReversal) #36
# DATA CHECKING
library(DHARMa)
library(lme4)
simulationOutpu <- simulateResiduals(fittedModel = glm(TotalLociSolvedMABwooden ~ TrialsLastReversal + MotorActionsWooden, family=poisson, data=dw), n=250) #250 simulations, but if want higher precision change n>1000
plot(simulationOutpu$scaledResiduals) #Expect a flat distribution of the overall residuals, and uniformity in y direction if plotted against any predictor
testDispersion(simulationOutpu) #if under- or over-dispersed, then p-value<0.05, but then check the dispersion parameter and try to determine what in the model could be the cause and address it there, also check for zero inflation. p<0.05 so under or overdispersed
testZeroInflation(simulationOutpu) #compare expected vs observed zeros, not zero-inflated if p<0.05. p=0.8 so not zero inflated
testUniformity(simulationOutpu) #check for heteroscedasticity ("a systematic dependency of the dispersion / variance on another variable in the model" Hartig, https://cran.r-project.org/web/packages/DHARMa/vignettes/DHARMa.html), which is indicated if dots aren't on the red line and p<0.05. p=0.2 so not heteroscedastic. Also...
plot(simulationOutpu) ##...there should be no pattern in the data points in the right panel. Dispersion test significant
plotResiduals(dw$MotorActionsWooden, simulationOutpu$scaledResiduals) #plot the residuals against other predictors - can't get this code to work yet
plotResiduals(dw$TrialsLastReversal, simulationOutpu$scaledResiduals)
# AIC calculation
library(MuMIn)
options(na.action = "na.fail")
base1 <- dredge(glm(TotalLociSolvedMABwooden ~ TrialsLastReversal + MotorActionsWooden, family=poisson, data=dw))
library(knitr)
kable(base1, caption = "")
### glmm doesn't work because only 1 data point per bird
# GLMM
library(MCMCglmm)
prior = list(R = list(R1 = list(V = 1, nu = 0), R2 = list(V = 1, nu = 0)), G = list(G1 = list(V = 1,
nu = 0)))
div <- MCMCglmm(TrialsToAttemptNewLociW ~ TrialsLastReversal + MotorActionsWooden, random = ~ID,
family = "poisson", data = diversity, verbose = F, prior = prior,
nitt = 13000, thin = 10, burnin = 3000)
summary(div)
# autocorr(div$Sol) #Did fixed effects converge?
# autocorr(div$VCV) #Did random effects converge?
# AIC calculation
library(MuMIn)
options(na.action = "na.fail")
base1 <- dredge(MCMCglmm(TotalLociSolvedMABwooden ~ TrialsLastReversal + MotorActionsWooden, random = ~ID,
family = "poisson", data = diversity, verbose = F, prior = prior,
nitt = 13000, thin = 10, burnin = 3000))
library(knitr)
kable(base1, caption = "")
```
### P4: Learning strategies (for birds in the manipulated group only)
\
**Analysis 1 (qualitative):** Learning strategies were identified by matching them to the two known approximate strategies of the contextual, binary multi-armed bandit: epsilon-first and epsilon-decreasing [@mcinerney2010; as in @logan2016behavioral]. We used the criterion for the epsilon-first strategy of learning the correct choice after one trial and then choosing correctly thereafter. Other patterns were classified as the epsilon-decreasing strategy where individuals gradually increase their number of successes as the number of trials increases. This method of qualitative inspection of learning curves is standard for this type of learning strategy assessment [@mcinerney2010]. The variable for visual inspection was the proportion of correct choices in a non-overlapping sliding window of 4-trial bins across the total number of trials required to reach the criterion of 17/20 correct choices per individual.
**Analysis 2 (quantitative):** We then quantitatively determined to what degree each bird used the exploration versus exploitation strategy using methods in @federspiel2017adjusting by calculating the number of 10-trial blocks where birds were choosing “randomly” (2-9 correct choices; called sampling blocks; akin to the exploration phase above) and dividing it by the total number of blocks to reach criterion per bird. This ratio was also calculated for “acquisition” blocks where birds made primarily correct choices (9-10 correct choices; akin to the exploitation phase above). These ratios, calculated for each bird for their serial reversals, quantitatively discern the exploration from the exploitation phases.
# Results {-}
Although 22 grackles completed their initial shaded tube discrimination, only 20 grackles participated in one or more reversal (Table SM5). The rest of the tests began only after a bird's reversal experiment was complete [@logan2023flexmanipdata].
## P1: Reversal speed gets faster with serial reversals
The birds in the manipulated group required a similar number of trials during their first reversal (R1 median=75 trials) as the birds in the control group needed during their first and only reversal (R1 median=70 trials) (see unregistered analysis in Table \ref{tab:tableunregisteredfirstrev}). The manipulated birds improved during the reversal manipulation to a median of 40 trials in their last reversal: there was a significant negative correlation between the number of trials to reverse (average=71 trials, standard deviation (sd)=28, Table \ref{tab:tablep1}) and the reversal number for those grackles in the flexibility manipulation condition (n=9, which included Memela who did not pass the manipulation condition of passing two consecutive reversals in 50 trials or less; Figure \ref{fig:p1table}).
```{r tableunregisteredfirstrev, eval=T}
tb <- read.csv(url("https://raw.githubusercontent.com/corinalogan/grackles/master/Files/Preregistrations/g_flexmanip_tableR1condition.csv"), header=F, sep=",", stringsAsFactors=F)
tb <- data.frame(tb)
colnames(tb) <- c("","Posterior mean","Lower 89 percentile compatibility interval (5.5%)","Upper 89 percentile compatibility interval (94.5%)","Effective sample size","pMCMC","Significance code: **=0.01")
library(kableExtra)
knitr::kable(tb, caption= "Unregistered analysis: the number of trials to reverse in the first reversal is similar between the manipulated and control groups.") %>%
kable_styling(full_width = T, position = "left", bootstrap_options = "condensed", font_size = 8, latex_options = "HOLD_position")
```
```{r p1unregistered, eval=F}
d <- read.csv(url("https://raw.githubusercontent.com/corinalogan/grackles/master/Files/Preregistrations/g_flexmanip_data_reverse.csv"), header=T, sep=",", stringsAsFactors=F)
d <- d[!d$ID=="Fajita" & !d$ID=="Empanada",] #remove Fajita because she was a pilot bird
#remove NAs from the variables that will be in the model
d <- subset(d,!(is.na(d["TrialsToReverse"])))
d <- subset(d,!(is.na(d["ReverseNumber"])))
#include only those birds in the reversal tubes experiment and only those in the manipulation condition bc only these will have more than one reversal (and thus something to correlate)
d <- d[d$TubesOrTouchscreen=="TUBES",]
#factor variables
d$Batch <- as.factor(d$Batch)
d$ID <- as.factor(d$ID)
d$ExperimentalGroup <- as.factor(d$ExperimentalGroup)
#rename Taco's "None" to "Control" to count him as a control bird for this analysis because he had only 1 reversal (and no yellow tube afterward)
levels(d$ExperimentalGroup) <- c("Control","Manipulation","Control")
# GLMM
library(MCMCglmm)
prior = list(R = list(R1 = list(V = 1, nu = 0)), G = list(G1 = list(V = 1,
nu = 0), G2 = list(V = 1, nu = 0)))
condition <- MCMCglmm(TrialsToReverse ~ ExperimentalGroup, random = ~ID+Batch,
family = "poisson", data = d, verbose = F, prior = prior,
nitt = 300000, thin = 500, burnin = 90000)
#reverse number significantly negatively correlates with trials to reverse, as expected due to the manipulation? Yes
output_condition <- summary(condition)
# post.mean l-95% CI u-95% CI eff.samp pMCMC
#(Intercept) 4.28760 4.09032 4.51160 420 <0.002 **
#ExperimentalGroupManipulation -0.07978 -0.31236 0.15703 420 0.457
#see whether removing batch makes a difference in the results (we removed batch for all P2 analyses)
prior2 = list(R = list(R1 = list(V = 1, nu = 0)), G = list(G1 = list(V = 1,
nu = 0)))
conditionwobatch <- MCMCglmm(TrialsToReverse ~ ExperimentalGroup, random = ~ID,
family = "poisson", data = d, verbose = F, prior = prior2,
nitt = 300000, thin = 500, burnin = 90000)
output_conditionwobatch <- summary(conditionwobatch) #results are very similar to and conclusions are not different from the "condition" model
# for output table
# FIRST: Extract 89 percentile compatibility interval from the model output and update the table's csv
library(rethinking)
#PI(condition$Sol[,1],prob=0.89) #4.12 to 4.46 percentile intervals
#PI(condition$Sol[,2],prob=0.89) #-0.27 to 0.11 percentile intervals
```
```{r tablep1, eval=T}
#Output table
tb <- read.csv(url("https://raw.githubusercontent.com/corinalogan/grackles/master/Files/Preregistrations/g_flexmanip_table2output.csv"), header=F, sep=",", stringsAsFactors=F)
tb <- data.frame(tb)
colnames(tb) <- c("","Posterior mean","Lower 89 percentile compatibility interval (5.5%)","Upper 89 percentile compatibility interval (94.5%)","Effective sample size","pMCMC","Significance code: **=0.01")
library(kableExtra)
knitr::kable(tb, caption= "In the manipulated birds, the number of trials to reverse decreases with increasing reversal number.") %>%
kable_styling(full_width = T, position = "left", bootstrap_options = "condensed", font_size = 8)
```
```{r p1table, eval=T, out.width="10cm", fig.align = 'center', fig.cap="Individuals in the manipulated condition (who received serial reversals) linearly decreased their reversal passing speeds with increasing reversal number (n=9 grackles)."}
d <- read.csv(url("https://raw.githubusercontent.com/corinalogan/grackles/master/Files/Preregistrations/g_flexmanip_data_reverse.csv"), header=T, sep=",", stringsAsFactors=F)
d <- d[!d$ID=="Fajita" & !d$ID=="Empanada",] #remove Fajita because she was a pilot bird
#remove NAs from the variables that will be in the model
d <- subset(d,!(is.na(d["TrialsToReverse"])))
d <- subset(d,!(is.na(d["ReverseNumber"])))
#include only those birds in the reversal tubes experiment and only those in the manipulation condition bc only these will have more than one reversal (and thus something to correlate)
d <- d[d$TubesOrTouchscreen=="TUBES" & d$ExperimentalGroup=="Manipulation",]
#factor variables
d$Batch <- as.factor(d$Batch)
d$ID <- as.factor(d$ID)
# GLMM
library(MCMCglmm)
prior = list(R = list(R1 = list(V = 1, nu = 0)), G = list(G1 = list(V = 1,
nu = 0), G2 = list(V = 1, nu = 0)))
serial <- MCMCglmm(TrialsToReverse ~ ReverseNumber, random = ~us(ReverseNumber):ID+Batch,
family = "poisson", data = d, verbose = F, prior = prior,
nitt = 300000, thin = 500, burnin = 90000)
# Extract 89 percentile compatibility interval from the model output
library(rethinking)
#PI(serial$Sol[,1],prob=0.89) #4.31 to 4.62
#PI(serial$Sol[,2],prob=0.89) #-0.10 to -0.03
#reverse number significantly negatively correlates with trials to reverse, as expected due to the manipulation? Yes
#summary(serial)
# post.mean l-95% CI u-95% CI eff.samp pMCMC
#(Intercept) 4.43636 4.25434 4.62631 635.3 <0.002 **
#ReverseNumber -0.05523 -0.08775 -0.02024 499.9 <0.002 **
#25 May 2022: nested ID within reverse number as a random effect per reviewer comment and the results are the same
# post.mean l-95% CI u-95% CI eff.samp pMCMC
#(Intercept) 4.46585 4.28078 4.66648 349.0 < 0.002 **
#ReverseNumber -0.06401 -0.11447 -0.02273 273.9 0.00952 **
#Did batch have an effect on the results? No.
priorNoBatch = list(R = list(R1 = list(V = 1, nu = 0)), G = list(G1 = list(V = 1,
nu = 0)))
serialNoBatch <- MCMCglmm(TrialsToReverse ~ ReverseNumber, random = ~us(ReverseNumber):ID,
family = "poisson", data = d, verbose = F, prior = priorNoBatch,
nitt = 300000, thin = 500, burnin = 90000)
#summary(serialNoBatch)
#22 Jun 2022: removed batch as a random effect per reviewer comment andn the results are the same
# post.mean l-95% CI u-95% CI eff.samp pMCMC
#(Intercept) 4.47231 4.30258 4.68142 420.0 < 0.002 **
#ReverseNumber -0.06477 -0.11364 -0.02472 315.3 0.00476 **
#Did fixed effects converge (<0.1)? Yes
#autocorr(serial$Sol)
#Did random effects converge (<0.1)? Yes except for 2 values: 0.11 and 0.12
#autocorr(serial$VCV)
#figure
op <- par(mfrow=c(1,1), mar=c(5.9,4.9,2,0.9))
plot(jitter(d$TrialsToReverse) ~ jitter(d$ReverseNumber), xlab="Reversal number", ylab="Number of trials to reverse", xlim=c(0.9,11.1), ylim=c(19,171), cex.lab=1.8, cex.axis=1.8, cex=1.8)
seq_reversalnumber=c(1:11)
predicted_trials=exp(summary(serialNoBatch)$solutions[1,1]+seq_reversalnumber*summary(serialNoBatch)$solutions[2,1])
lines(predicted_trials ~ seq_reversalnumber)
par(op)
#n, mean, sd
#length(levels(d$ID)) #9
#mean(d$TrialsToReverse) #71
#sd(d$TrialsToReverse) #28
```
**Unregistered analysis 1:** There was additionally a difference between manipulated and control reversal speeds when comparing their last reversals (Figure \ref{fig:p1figlast}; for the control birds, their last reversal was their first reversal; Table \ref{tab:p1tablecondition}). This analysis includes 19 grackles (8 manipulated condition - only those who actually passed the manipulation, 11 control condition) who had an overall average of 62 trials in their last reversal (sd=32).
```{r p1figlast, eval=T, out.width="10cm", fig.align = 'center', fig.cap="Individuals in the manipulated condition (who received serial reversals) passed their last reversal in fewer trials than individuals in the control condition (who only received 1 reversal). n=19 grackles: 11=control, 8=manipulated."}
d <- read.csv(url("https://raw.githubusercontent.com/corinalogan/grackles/master/Files/Preregistrations/g_flexmanip_datasummary.csv"), header=F, sep=",", stringsAsFactors=F)
d <- data.frame(d)
colnames(d) <- c("Bird","Batch","Sex","Trials to learn","TrialsFirstReversal","TrialsLastReversal","ReversalsToPass","TotalLociSolvedMABplastic","TotalLociSolvedMABwooden","AverageLatencyAttemptNewLocusMABplastic","AverageLatencyAttemptNewLocusMABwooden","Trials to learn (touchscreen)","Trials to first reversal (touchscreen)","MotorActionsPlastic","MotorActionsWooden")
# Remove NAs
d <- subset(d,!(is.na(d["TrialsLastReversal"])))
# exclude the bird who didn't pass serial
d <- d[!d$Bird=="Memela",]
#n, mean, and sd
#length(d$TrialsLastReversal) #19
#mean(d$TrialsLastReversal) #62