This repository was archived by the owner on Jun 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimplerSignatures_AdditionalMaterials_04_IdentityContent.Rmd
More file actions
1015 lines (792 loc) · 37.4 KB
/
SimplerSignatures_AdditionalMaterials_04_IdentityContent.Rmd
File metadata and controls
1015 lines (792 loc) · 37.4 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: <center style="font-size:30px;font-style:normal;color:black;">Additional Materials 04 :</center>
subtitle: <center style="font-size:30px;font-style:normal;color:#0E0E7D;">Comparing Individual Identity Content Between Ranges</center>
author: |
<center style="font-style:normal;">
<a style="font-size:22px;color:#337ab7;text-decoration: underline;"href="http://smith-vidaurre.com/">Grace Smith-Vidaurre</a><sup><span style="font-size:12px;color:black;text-decoration:none!important;">1,2,3,4*</span></sup>,
<a style="font-size:22px;color:#337ab7;text-decoration: underline;"href="http://wrightbehaviorlab.org">Valeria Perez-Marrufo</a><sup><span style="font-size:12px;color:black;text-decoration:none!important;">1</span></sup>,
<a style="font-size:22px;color:#337ab7;text-decoration: underline;"href="http://wrightbehaviorlab.org">Timothy F. Wright</a><sup><span style="font-size:12px;color:black;text-decoration:none!important;">1</span></sup></center>
<center style="font-size:18px;font-style:normal;color:black;"><sup><span style="font-size:12px;color:black;">1</span></sup>Department of Biology, New Mexico State University</center>
<center style="font-size:18px;font-style:normal;color:black;"><sup><span style="font-size:12px;color:black;">2</span></sup>Laboratory of Neurogenetics of Language, Rockefeller University</center>
<center style="font-size:18px;font-style:normal;color:black;"><sup><span style="font-size:12px;color:black;">3</span></sup>Field Research Center, Rockefeller University</center>
<center style="font-size:18px;font-style:normal;color:black;"><sup><span style="font-size:12px;color:black;">4</span></sup>Department of Biological Sciences, University of Cincinnati</center>
<br />
<center style="font-size:18px;"><sup style="font-size:12px;">*</sup>Corresponding author (gsvidaurre@gmail.com)</center>
date: <center style=font-size:22px;font-style:normal;>`r format(Sys.time(), '%d %B %Y')`</center>
<br />
output:
html_document:
toc: true
toc_depth: 4
toc_float:
collapsed: false
---
<style type="text/css">
a:hover {
color: #23527c !important;
}
h1.title {
font-size: 32px;
color: black;
font-weight: normal;
}
h1 {
color: black;
font-size: 26px;
font-weight: normal;
}
h2 {
color: black;
font-size: 24px;
font-weight: bold;
}
h3 {
color: black;
font-size: 20px;
font-weight: normal;
}
h4 {
color: black;
font-size: 20px;
font-weight: normal;
}
body{ /* Normal */
font-size: 18px;
}
code.r{ /* Code block */
font-size: 18px;
}
</style>
```{r setup, eval = TRUE, echo = FALSE}
knitr::opts_knit$set(root.dir = "/home/gsvidaurre/Desktop/GitHub_repos/vocal-learning-invasion")
```
Individual identity content was compared in contact calls of repeatedly sampled individuals per range. We used Beecher's statistic as a metric of individual identity content, and also used this statistic to calculate the possible number of unique individual signatures given the amount of identity content per range<a href='#References'><sup>[1]</sup></a>. The dataset of repeatedly sampled individuals per range was used here, and we validated the individuals used for this comparison between ranges.
The prefix "AM" stands for "Additional Material", used to indicate figures included here that are not present in the main figures or supplementary material, but are still valuable for reproducibility. Some of the code in this script may need to be updated in order to reproduce results with more recent versions of the packages used. Measurements needed to reproduce results here have been made available on figshare.
```{r echo = TRUE, eval = TRUE, message = FALSE}
rm(list = ls())
# load plyr before dplyr to avoid masking of certain functions
library(plyr)
X <- c("tidyverse", "pbapply", "dplyr", "data.table", "parallel", "scales", "ggplot2", "IDmeasurer", "knitr", "utils", "egg", "gridExtra", "grid", "ggplotify", "rgeos", "rgdal", "facetscales", "Rmisc", "caret")
invisible(lapply(X, library, character.only = TRUE))
path <- "/media/gsvidaurre/MYIOPSITTA/R/VocalLearning_PostInvasion/Data"
gpath <- "/home/gsvidaurre/Desktop/MANUSCRIPTS/SimplerSignatures_PostInvasion/FIGURES"
seed <- 401
cores <- parallel::detectCores() - 2
```
Read in extended selection table (EST). Throughout this and the subsequent script, you can reproduce analyses by reading in the file "nat_inv_indiv_site_seltbl.csv", which is a selection table that contains metadata needed for reproducing analyses presented here.
```{r echo = TRUE, eval = TRUE}
nat_inv_est <- readRDS(file.path(path, "nat_inv_indiv_site_EST.RDS"))
# glimpse(nat_inv_est)
```
# Choosing individuals
Get repeatedly sampled individual calls across ranges.
```{r echo = TRUE, eval = TRUE}
indiv_scale <- nat_inv_est %>%
as_tibble() %>%
filter(social_scale == "Individual") %>%
droplevels()
# glimpse(indiv_scale)
```
Determining how to calculate Beecher's statistic per range.
```{r echo = TRUE, eval = TRUE}
indiv_scale %>%
group_by(range) %>%
dplyr::summarise(n_indivs = n_distinct(Bird_ID))
```
How many individuals were sampled over time in the invasive range? Only a single bird in 2004. Two in 2011, 6 in 2019. Two site-years in 2019 have two individuals sampled each. All other site-years have a single bird. One of the 2019 repeatedly sampled individuals was the lone El Paso bird recorded at ASCA, and will not be included in subsequent analysis.
```{r echo = TRUE, eval = TRUE}
indiv_scale %>%
filter(range == "Invasive") %>%
group_by(range, year) %>%
dplyr::summarise(n_indivs = n_distinct(Bird_ID))
```
```{r echo = TRUE, eval = TRUE}
indiv_scale %>%
filter(range == "Invasive") %>%
group_by(range, invasive_city, site_year) %>%
dplyr::summarise(n_indivs = n_distinct(Bird_ID))
```
How many individuals for native range sites?
```{r echo = TRUE, eval = TRUE}
indiv_scale %>%
filter(range == "Native") %>%
group_by(site) %>%
dplyr::summarise(n_birds = n_distinct(Bird_ID))
```
How many individuals for Austin 2019?
```{r echo = TRUE, eval = TRUE}
indiv_scale %>%
filter(range == "Invasive") %>%
filter(invasive_city == "Austin" & year == 2019) %>%
dplyr::summarise(n_birds = n_distinct(Bird_ID))
```
Pairwise distances between sites at which we repeatedly sampled individuals in each range.
Native range, using spatial projection for Uruguay.
```{r echo = TRUE, eval = TRUE}
# Access EPSG codes to reproject in meters
# Used EPSG 5383 for Uruguay
epsg <- rgdal::make_EPSG()
# str(epsg)
# epsg[grep("^5383$", epsg$code), ]
# Get geographic coordinates for native range sites at which we repeatedly sampled individuals
# Note that there were two clusters of nests at which we recorded at site 1145, considered a single site because we frequently observed birds from these clusters of nests staging and interacting together
coords_df <- nat_inv_est %>%
as_tibble() %>%
filter(range == "Native" & social_scale == "Individual") %>%
dplyr::select(site, lat, lon) %>%
distinct()
# coords_df
# Convert to Spatial Points object
mat <- as.matrix(data.frame(lon = coords_df$lon, lat = coords_df$lat))
sp_pts <- SpatialPoints(mat, proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
# Reproject
sp_pts <- sp::spTransform(sp_pts, CRSobj = CRS(epsg$prj4[grep("^5383$", epsg$code)]))
# bbox(sp_pts)
# proj4string(sp_pts)
# Calculate pairwise distances among sites (meters)
nat_geo_dists <- rgeos::gDistance(sp_pts, byid = TRUE)
dimnames(nat_geo_dists) <- list(coords_df$site, coords_df$site)
# Shown in km
nat_geo_dists/1000
```
The closest geographic distance between unique sites at which we obtained calls from repeatedly sampled individuals was 11km in the native range, between EMBR and CHAC. Note that nest clusters at site 1145 were considered as a single nest site.
Invasive range, using spatial projection for U.S.
```{r echo = TRUE, eval = TRUE}
# Access EPSG codes to reproject in meters
# Used EPSG 2163 (U.S. National Atlas Equal Area projection)
epsg <- rgdal::make_EPSG()
# str(epsg)
# epsg[grep("^2163$", epsg$code), ]
coords_df <- nat_inv_est %>%
as_tibble() %>%
filter(range == "Invasive" & social_scale == "Individual") %>%
dplyr::select(site, lat, lon) %>%
distinct()
# coords_df
mat <- as.matrix(data.frame(lon = coords_df$lon, lat = coords_df$lat))
sp_pts <- SpatialPoints(mat, proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
sp_pts <- sp::spTransform(sp_pts, CRSobj = CRS(epsg$prj4[grep("^2163$", epsg$code)]))
# bbox(sp_pts)
# proj4string(sp_pts)
# Calculate pairwise distances among sites (meters)
inv_geo_dists <- rgeos::gDistance(sp_pts, byid = TRUE)
dimnames(inv_geo_dists) <- list(coords_df$site, coords_df$site)
# Shown in km
inv_geo_dists/1000
range(inv_geo_dists[!inv_geo_dists == 0]/1000)
```
The geographic distances among sites with repeatedly sampled individuals were much greater for the invasive range than the native range.
# Validation analysis
Previous work in this system indicates that parakeets separated by greater geographic distances are more likely to overlap in acoustic space, probably because they are less likely to interact within social groups when separated by greater distances<a href='#References'><sup>[2]</sup></a>. Given this, we felt it was important to compare individual identity information over geographic areas that were as similar as possible between the native and invasive ranges, and to use the same number of individuals per range.
The most similar geographic areas represented in the repeatedly sampled individual dataset per range, which also provided equal numbers of individuals per range, was site 1145 with 5 repeatedly sampled individuals for the native range, and 5 individuals recorded at 3 sites in Austin 2019.
The Austin 2019 individuals were recorded at sites 3 - 7km apart (sites ELEM, INTR, SOCC). These geographic distances were all smaller than the minimum distance between sites sampled in the native range (11.12km). While this comparison between ranges fits both requirements for restricted geographic area and equal numbers of individuals, a potential problem is that the native range individuals represented a single site, while the invasive range individuals represented 3 sites.
We performed a validation analysis to assess whether this comparison between ranges was fair for calculating Beecher's statistic. As previous work indicates that individuals do not converge on shared calls within sites, and are more likely to overlap in acoustic space over increasing geographic distance, we wanted to know whether the amount of overlap in acoustic space for repeatedly sampled individuals was similar between the 5 invasive range individuals recorded at 3 sites compared to the 5 native range individuals recorded at a single site. We also compared overlap among native range individuals recorded at the 3 native range sites separated by greater geographic distances than the invasive range sites. Dynamic time warping (DTW) acoustic distance of second harmonic frequency contours within and among individuals was compared via a resampling analysis.
Performed dynamic time warping (DTW) on second harmonic frequency contours and removed 5 timepoints on either end.
```{r, echo = TRUE, eval = TRUE}
# The EST with the manually tailored 2nd harmonic traces
freq_mod_est <- readRDS(file.path(path, "freq_mod_est_m2h.RDS"))
# glimpse(freq_mod_est)
freq_mod_est_indiv <- freq_mod_est %>%
as_tibble() %>%
filter(question == "indiv_scale") %>%
droplevels() %>%
dplyr::select(names(.)[grep("sound.files|range|Bird_ID|year|site|invasive_city|ffreq", names(.))])
# glimpse(freq_mod_est_indiv)
```
```{r, echo = TRUE, eval = FALSE}
# Get the frequency traces
tmp <- freq_mod_est_indiv[, grep("ffreq", names(freq_mod_est_indiv))]
# Drop 5 points on either end of frequency traces
tmp <- tmp[, -grep(paste(paste("^", paste("ffreq", c(seq(1, n_rem, 1), seq(n_tot - n_rem + 1, n_tot, 1)), sep = "."), "$", sep = ""), collapse = "|"), names(tmp))]
glimpse(tmp)
# Returns distances by default
freq_mod_DTW <- dtw::dtwDist(tmp, tmp, window.type = "none", open.end = FALSE, path = path)
str(freq_mod_DTW)
saveRDS(freq_mod_DTW, file.path(path, "freq_mod_DTW.RDS"))
```
Subset the DTW distance matrix to retain individuals for resampling.
```{r echo = TRUE, eval = TRUE}
freq_mod_DTW <- readRDS(file.path(path, "freq_mod_DTW.RDS"))
dimnames(freq_mod_DTW) <- list(as.character(freq_mod_est_indiv$sound.files), as.character(freq_mod_est_indiv$sound.files))
# Subset the matrix by all native range individuals, and the invasive range Austin 2019 individuals
freq_mod_est_indiv2 <- freq_mod_est_indiv %>%
filter(range == "Native" | invasive_city == "Austin" & year == "2019") %>%
droplevels()
indivs <- freq_mod_est_indiv2 %>%
pull(Bird_ID) %>%
unique()
indivs
calls <- freq_mod_est_indiv2 %>%
pull(sound.files)
# calls
freq_mod_DTW_tmp <- freq_mod_DTW[grep(paste(paste("^", calls, "$", sep = ""), collapse = "|"), dimnames(freq_mod_DTW)[[1]]), grep(paste(paste("^", calls, "$", sep = ""), collapse = "|"), dimnames(freq_mod_DTW)[[2]])]
str(freq_mod_DTW_tmp)
```
We resampled calls per bird, randomly selecting 4 calls per iteration, or the total per individual if only 4 calls were recorded. For the comparison of individuals over 3 native range sites, we also randomly sampled 5 individuals out of the 8 total in each iteration. Per iteration, we found the mean DTW difference within versus among individuals recorded over the 3 sites in each range.
Here, performed resampling for 5 of any of the 8 native range individuals recorded at 3 sites, and the 5 invasive range individuals recorded at 3 sites.
```{r echo = TRUE, eval = FALSE}
ranges <- c("Native", "Invasive")
iter <- 1000
rs_sim <- rbindlist(pblapply(1:iter, function(i){
# Randomly sample 5 individuals for the native range across the 3 sites
nat_indivs <- freq_mod_est_indiv2 %>%
filter(range == "Native") %>%
droplevels() %>%
pull(Bird_ID) %>%
unique() %>%
sample(5, replace = FALSE)
# Randomly sample 4 calls per individual per range
# Take the total calls if 4 or less were recorded
nat_calls <- freq_mod_est_indiv2 %>%
filter(Bird_ID %in% nat_indivs) %>%
droplevels() %>%
group_by(Bird_ID) %>%
nest() %>%
ungroup() %>%
inner_join(
freq_mod_est_indiv2 %>%
filter(range == "Native") %>%
group_by(Bird_ID) %>%
dplyr::summarise(
n_calls = length(sound.files)
) %>%
dplyr::mutate(
rc = ifelse(n_calls > 4, 4, n_calls)
),
by = "Bird_ID"
) %>%
dplyr::mutate(
rs = purrr::map2(data, rc, sample_n, replace = FALSE)
) %>%
dplyr::select(-data) %>%
unnest(rs) %>%
dplyr::select(sound.files, site, Bird_ID)
inv_calls <- freq_mod_est_indiv2 %>%
filter(range == "Invasive") %>%
droplevels() %>%
group_by(Bird_ID) %>%
nest() %>%
ungroup() %>%
inner_join(
freq_mod_est_indiv2 %>%
filter(range == "Invasive") %>%
group_by(Bird_ID) %>%
dplyr::summarise(
n_calls = length(sound.files)
) %>%
dplyr::mutate(
rc = ifelse(n_calls > 4, 4, n_calls)
),
by = "Bird_ID"
) %>%
dplyr::mutate(
rs = purrr::map2(data, rc, sample_n, replace = FALSE)
) %>%
dplyr::select(-data) %>%
unnest(rs) %>%
dplyr::select(sound.files, site, Bird_ID)
dfs <- list(nat_calls, inv_calls)
# Calculate the difference in DTW second harmonic similarity within and among individuals per range
indivs <- list(
nat_indivs,
inv_calls %>%
pull(Bird_ID) %>%
unique()
)
res_df2 <- rbindlist(lapply(1:length(ranges), function(r){
res_df <- rbindlist(lapply(1:length(indivs[[r]]), function(s){
# Get the site for the given individual
st <- dfs[[r]] %>%
filter(Bird_ID == indivs[[r]][s]) %>%
pull(site) %>%
unique()
# Get calls for the given individual
in_calls <- dfs[[r]] %>%
filter(Bird_ID == indivs[[r]][s]) %>%
pull(sound.files)
# Get calls for all other individuals (same or different sites)
amng_calls <- dfs[[r]] %>%
filter(Bird_ID != indivs[[r]][s]) %>%
pull(sound.files)
# Subset the DTW matrix by calls for the given individual
tmp_mat <- freq_mod_DTW_tmp[grep(paste(paste("^", in_calls, "$", sep = ""), collapse = "|"), dimnames(freq_mod_DTW_tmp)[[1]]), grep(paste(paste("^", in_calls, "$", sep = ""), collapse = "|"), dimnames(freq_mod_DTW_tmp)[[2]])]
w <- tmp_mat[lower.tri(tmp_mat, diag = FALSE)]
# Get similarity values for comparisons between calls for this individual to calls for all other individuals
a <- as.vector(freq_mod_DTW_tmp[-grep(paste(paste("^", in_calls, "$", sep = ""), collapse = "|"), dimnames(freq_mod_DTW_tmp)[[1]]), grep(paste(paste("^", in_calls, "$", sep = ""), collapse = "|"), dimnames(freq_mod_DTW_tmp)[[2]])])
# Return the difference in mean DTW distance within versus among sites
res <- data.frame(range = ranges[r], site = st, indiv = indivs[[r]][s], DTW_diff = (mean(a) - mean(w)))
return(res)
}))
return(res_df)
}))
return(res_df2)
}))
glimpse(rs_sim)
saveRDS(rs_sim, file.path(path, "m2H_resampling_DTW_3sites.RDS"))
```
We also performed resampling for the 5 repeatedly sampled individuals at the single native range site (1145). This allowed us to ask how DTW distance within versus among individuals at this single site compared to the differences in DTW distances for individuals at all 3 native and invasive range sites obtained above.
```{r echo = TRUE, eval = FALSE}
rs_sim_1145 <- rbindlist(pblapply(1:iter, function(i){
# Randomly sample 4 calls or the total per individual for 1145
nat_calls <- freq_mod_est_indiv2 %>%
filter(range == "Native" & site == "1145") %>%
droplevels() %>%
group_by(Bird_ID) %>%
nest() %>%
ungroup() %>%
inner_join(
freq_mod_est_indiv2 %>%
filter(range == "Native" & site == "1145") %>%
group_by(Bird_ID) %>%
dplyr::summarise(
n_calls = length(sound.files)
) %>%
dplyr::mutate(
rc = ifelse(n_calls > 4, 4, n_calls)
),
by = "Bird_ID"
) %>%
dplyr::mutate(
rs = purrr::map2(data, rc, sample_n, replace = FALSE)
) %>%
dplyr::select(-data) %>%
unnest(rs) %>%
dplyr::select(sound.files, Bird_ID)
# Then calculate the difference in DTW second harmonic similarity within and among individuals at 1145
indivs <- nat_calls %>%
pull(Bird_ID) %>%
unique()
res_df <- rbindlist(lapply(1:length(indivs), function(s){
in_calls <- nat_calls %>%
filter(Bird_ID == indivs[s]) %>%
pull(sound.files)
amng_calls <- nat_calls %>%
filter(Bird_ID != indivs[s]) %>%
pull(sound.files)
tmp_mat <- freq_mod_DTW_tmp[grep(paste(paste("^", in_calls, "$", sep = ""), collapse = "|"), dimnames(freq_mod_DTW_tmp)[[1]]), grep(paste(paste("^", in_calls, "$", sep = ""), collapse = "|"), dimnames(freq_mod_DTW_tmp)[[2]])]
w <- tmp_mat[lower.tri(tmp_mat, diag = FALSE)]
a <- as.vector(freq_mod_DTW_tmp[-grep(paste(paste("^", in_calls, "$", sep = ""), collapse = "|"), dimnames(freq_mod_DTW_tmp)[[1]]), grep(paste(paste("^", in_calls, "$", sep = ""), collapse = "|"), dimnames(freq_mod_DTW_tmp)[[2]])])
# Get the difference in mean DTW distance within and among individuals
return(data.frame(site = "1145", indiv = indivs[s], DTW_diff = (mean(a) - mean(w))))
}))
return(res_df)
}))
glimpse(rs_sim_1145)
saveRDS(rs_sim_1145, file.path(path, "m2H_resampling_DTW_1145.RDS"))
```
Combine resampling results.
```{r echo = TRUE, eval = TRUE, message = FALSE, warning = FALSE}
rs_sim <- readRDS(file.path(path, "m2H_resampling_DTW_3sites.RDS"))
# glimpse(rs_sim)
rs_sim_1145 <- readRDS(file.path(path, "m2H_resampling_DTW_1145.RDS"))
# glimpse(rs_sim_1145)
rs_all <- rs_sim %>%
dplyr::mutate(
type = "Three sites"
) %>%
bind_rows(
rs_sim_1145 %>%
dplyr::mutate(
range = "Native",
type = "Single site"
) %>%
dplyr::select(c(range, site, indiv, DTW_diff, type))
) %>%
dplyr::mutate(
range = factor(range, levels = c("Native", "Invasive"))
) %>%
group_by(range, type) %>%
dplyr::summarise(
mean = mean(DTW_diff),
upper_CI = CI(DTW_diff, 0.95)[["upper"]],
lower_CI = CI(DTW_diff, 0.95)[["lower"]]
)
rs_all %>%
dplyr::mutate(
mean = round(mean, 2),
upper_CI = round(upper_CI, 2),
lower_CI = round(lower_CI, 2)
) %>%
kable()
```
## Figure A2
```{r echo = TRUE, eval = TRUE}
fills <- scales::alpha(c("navy", "orange"), 0.85)
# x11()
rs_all %>%
ggplot(aes(x = type, y = mean)) +
geom_errorbar(aes(ymin = lower_CI, ymax = upper_CI, color = range), size = 1.5, width = 0.25) +
geom_point(aes(fill = range), shape = 21, color = "black", stroke = 0.25, size = 6) +
facet_wrap(~ range) +
scale_fill_manual(values = fills) +
scale_color_manual(values = fills) +
ylab("Mean DTW difference and 95% CI") + xlab("") +
theme_bw() +
guides(fill = FALSE, color = guide_legend(title = "")) +
theme(
axis.title = element_text(size = 14),
axis.text = element_text(size = 12),
strip.text = element_text(size = 14, margin = margin(1, 0, 1, 0, "lines")),
legend.position = "top",
legend.text = element_text(size = 14),
panel.grid.major = element_line(size = 0.15),
panel.grid.minor = element_blank()
)
# Animal Behavior 1.5 column figure
# ggsave(file.path(gpath, "SupplementaryFigure3_DTWdifference_Validation.jpeg"), units = "in", width = 5, height = 4, dpi = 300)
```
This validation analysis confirms that the 5 individuals at a single site in the native range and the 5 individuals at 3 sites in the invasive range represented similar patterns of overdispersion in acoustic space. We proceeded with Beecher's statistic calculations for these individuals per range.
# Beecher's statistic
Calculated Beecher's statistic using the IDmeasurer package on the cepstral coefficients and manually traced frequency curves of the second harmonic. Beecher's statistic was calculated with the same 5 calls per individual by each measurement type. Beecher's statistic was calculated by performing principal components analysis (PCA) on each acoustic measurement, and using the principal components significantly related to individual identity.
Here I made a modified version of IDmeasurer::calcHS. The math used to calculate Beecher's statistic is the same, but I changed the way the data is used to account for the objects I'm using (data frames, tibbles). I made these modifications to IDmeasurer::calcHS after finding that I could not reproduce previous results after updating R.
```{r echo = TRUE, eval = TRUE, message = FALSE, warning = FALSE}
# df needs to be a data frame with a single column specifying individual or group identity, and the location of this column in the data frame does not matter. All other columns should be numeric variables used to calculate Beecher's statistic. This function assumes that the identity column is already a factor, and also assumes that the number of samples per individual is the same across individuals
calcHS_mod <- function (df, sumHS = TRUE, id_col_name){
# nvars <- ncol(df) # original line
# vars <- names(df) # original line
nvars <- ncol(df[-grep(id_col_name, names(df))])
vars <- names(df)[-grep(id_col_name, names(df))]
n <- nrow(df)
# indivs <- levels(as.factor(df[, 1])) # original line
indivs <- levels(df[[id_col_name]])
nindiv <- length(indivs)
npergroup <- nrow(df)/nindiv # original line, sample size is assumed to be equal across individuals
fvalues <- rep(NA, nvars)
Pr <- rep(NA, nvars)
HS <- rep(NA, nvars)
# for (k in 2:nvars) { # original line
for (k in 1:nvars) {
# modelFormula <- paste(vars[k], "~", vars[1]) # original line
modelFormula <- paste(vars[k], "~", id_col_name)
fvalues[k] <- summary(stats::aov(stats::as.formula(modelFormula),
data = df))[[1]][["F value"]][[1]]
Pr[k] <- summary(stats::aov(stats::as.formula(modelFormula),
data = df))[[1]][["Pr(>F)"]][[1]]
HS[k] <- log2(sqrt((fvalues[k] + (npergroup - 1))/npergroup))
}
Pr <- round(Pr, 3)
HS <- round(HS, 2)
result <- data.frame(vars, Pr, HS)
# result <- result[-1, ] # original line, not needed because the ID column is excluded above
# if (sumHS == T) { # original line
if(sumHS){
# result <- c(sum(result$HS[result$Pr < 0.05], na.rm = T),
# sum(result$HS, na.rm = T)) # original line
result <- c(sum(result$HS[result$Pr < 0.05], na.rm = TRUE),
sum(result$HS, na.rm = TRUE))
names(result) <- c("HS for significant vars", "HS for all vars")
return(result)
}
else return(result)
}
# Also modified calcPCA from IDmeasurer
# For some reason, the id column is only renamed to "id" for the MFCC dataset, not the frequency contour dataset. Updated the code to be more general. The arguments df and id_col_name should be specified as above for calcHS_mod
calcPCA_mod <- function (df, id_col_name){
# id <- df[, 1] # original line
id <- df[[id_col_name]]
# pcscores <- stats::prcomp(df[, -1], center = T, scale = T,
# tol = 0)$x # original line
pcscores <- stats::prcomp(df[, -grep(id_col_name, names(df))], center = TRUE, scale = TRUE,
tol = 0)$x
temp <- data.frame(id = id, pcscores)
return(temp)
}
```
Calculate Beecher's statistic with the modified function above.
```{r echo = TRUE, eval = TRUE, message = FALSE, warning = FALSE}
cep_coeff <- read.csv(file.path(path, "Mel_freq_cepstral_coefficients.csv"))
# glimpse(cep_coeff)
# Add back metadata
cep_coeff <- cep_coeff %>%
inner_join(
nat_inv_est %>%
as_tibble() %>%
filter(social_scale == "Individual") %>%
dplyr::select(sound.files, range, year, site, invasive_city, Bird_ID),
by = "sound.files"
) %>%
# Make sure the selec column is not numeric so it isn't included in the PCA
dplyr::mutate(
selec = as.character(selec)
)
# glimpse(cep_coeff)
# The EST with the manually tailored 2nd harmonic traces
freq_mod_est <- readRDS(file.path(path, "freq_mod_est_m2h.RDS"))
# glimpse(freq_mod_est)
# Subset by the 84 calls selected for the repeatedly sampled individuals
freq_mod_est_indiv <- freq_mod_est %>%
as_tibble() %>%
filter(question == "indiv_scale") %>%
droplevels() %>%
dplyr::select(names(.)[grep("sound.files|range|Bird_ID|year|site|invasive_city|ffreq", names(.))])
# glimpse(freq_mod_est_indiv)
# 25 calls, 5 calls per each of 5 native range individuals
freq_mod_est_indiv %>%
filter(range == "Native" & site == "1145") %>%
group_by(Bird_ID) %>%
dplyr::summarise(
n_calls = length(sound.files)
)
# 25 calls, 5 calls per each of 5 invasive range individuals
freq_mod_est_indiv %>%
filter(range == "Invasive" & invasive_city == "Austin" & year == 2019) %>%
group_by(Bird_ID) %>%
dplyr::summarise(
n_calls = length(sound.files)
)
n_tot <- 100 # the number of timepoints per frequency trace
n_rem <- 5 # remove 5 points at the start and end of each call, for 90 frequency measurements total across each call
# the number of timepoints per frequency trace, minus 5 on either end
n <- n_tot - (n_rem*2)
# Remove 5 points on either end of the frequency traces
sec_harm <- freq_mod_est_indiv[, -grep(paste(paste("^", paste("ffreq", c(seq(1, n_rem, 1), seq(n_tot - n_rem + 1, n_tot, 1)), sep = "."), "$", sep = ""), collapse = "|"), names(freq_mod_est_indiv))]
# glimpse(sec_harm)
# names(sec_harm)
# Subset data frames representing these two measurements by the calls of interest per range
sec_harm2 <- sec_harm %>%
dplyr::mutate(
range = as.character(range)
) %>%
dplyr::filter(range == "Native" & site == "1145") %>%
droplevels() %>%
bind_rows(
sec_harm %>%
dplyr::mutate(
range = as.character(range)
) %>%
dplyr::filter(range == "Invasive" & invasive_city == "Austin" & year == 2019) %>%
droplevels()
)
# glimpse(sec_harm2)
# For MFCC, also filter to retain only the 5 sound files per bird in the frequency contour dataset, for direct comparisons of Beecher's statistic between the two measurements employed for calculating this statistic
cep_coeff2 <- cep_coeff %>%
dplyr::mutate(
range = as.character(range)
) %>%
dplyr::filter(range == "Native" & site == "1145") %>%
droplevels() %>%
bind_rows(
cep_coeff %>%
dplyr::mutate(
range = as.character(range)
) %>%
dplyr::filter(range == "Invasive" & invasive_city == "Austin" & year == 2019) %>%
droplevels()
) %>%
dplyr::filter(sound.files %in% sec_harm2$sound.files)
# glimpse(cep_coeff2)
# Check that sound files retained per dataset are the same, looks good
# all(cep_coeff2$sound.files %in% sec_harm2$sound.files)
# all(sec_harm2$sound.files %in% cep_coeff2$sound.files)
# Get Beecher's statistic (HS) by iterating over ranges and measurements
# Also calculate the number of possible unique individual signatures
ranges <- c("Native", "Invasive")
measurements <- c("MFCC", "Frequency\n contours")
mlist <- list(cep_coeff2, sec_harm2)
# r <- 1
# m <- 2
HS_df <- rbindlist(pblapply(1:length(ranges), function(r){
HS_df_tmp <- rbindlist(lapply(1:length(measurements), function(m){
# Get the given measurements
meas <- mlist[[m]]
# glimpse(meas)
if(grepl("Nat", ranges[r])){
meas_tmp <- meas %>%
dplyr::mutate(
range = as.character(range)
) %>%
dplyr::filter(range == "Native") %>%
droplevels()
} else if(grepl("Inv", ranges[r])){
meas_tmp <- meas %>%
dplyr::mutate(
range = as.character(range)
) %>%
dplyr::filter(range == "Invasive") %>%
droplevels()
}
# glimpse(meas_tmp)
# Get numeric columns only
col_nms <- names(meas_tmp)[sapply(meas_tmp, is.numeric)]
# col_nms
# Select just the ID column and numeric columns
meas_tmp2 <- meas_tmp %>%
dplyr::select(Bird_ID, all_of(col_nms))
# names(meas_tmp2)
#################### Calculate HS using PCA ####################
# Perform the PCA. The first column must indicate individual identity
pca_res <- calcPCA_mod(meas_tmp2, id_col_name = "Bird_ID")
# glimpse(pca_res)
# Convert the ID column to a factor
pca_res <- pca_res %>%
dplyr::mutate(
id = factor(id)
)
# glimpse(pca_res)
# Calculate Beecher's statistic
HS_pca <- calcHS_mod(pca_res, sumHS = TRUE, id_col_name = "id")
# HS_pca
# Get HS using PCs or variables significantly related to individual identity
HS <- HS_pca[["HS for significant vars"]]
indivs <- meas_tmp %>%
pull(Bird_ID) %>%
unique()
# indivs
HS_df <- data.frame(
range = ranges[r],
measurement = measurements[m],
num_indivs = length(indivs),
num_calls = nrow(meas_tmp),
calls_per_indiv = nrow(meas_tmp)/length(indivs),
vars_for_PCA = length(names(meas_tmp2[, sapply(meas_tmp2, is.numeric)])),
pcs = length(names(pca_res[, sapply(pca_res, is.numeric)])),
HS = round(HS, 2),
N_sigs = round(HS^2, 2)
)
return(HS_df)
}))
return(HS_df_tmp)
}))
HS_df %>%
dplyr::mutate(
measurement = gsub("\n", "", measurement)
) %>%
arrange(measurement) %>%
kable()
```
## Figure 2C
Beecher's statistic graphic for main manuscript, Figure 2C.
```{r echo = TRUE, eval = TRUE}
fills <- scales::alpha(c("navy", "orange"), 0.75)
cols <- scales::alpha(c("navy", "orange"), 1)
# x11()
HS_df2 <- HS_df %>%
pivot_longer(
cols = c(HS, N_sigs),
names_to = "statistic",
values_to = "values"
) %>%
dplyr::mutate(
statistic = ifelse(statistic == "HS", "Beecher's\n statistic", "Unique\n signatures"),
statistic_measurement = paste(statistic, measurement, sep = ":\n"),
statistic_measurement = factor(statistic_measurement),
range = factor(range, levels = c("Native", "Invasive")),
measurement = recode(
measurement,
`MFCC` = "Mel-frequency\n cepstral\n coeffients"
),
measurement = factor(measurement, levels = c("Mel-frequency\n cepstral\n coeffients", "Frequency\n contours"))
)
# glimpse(HS_df2)
scales_y <- list(
"Beecher's\n statistic" = scale_y_continuous(limits = c(0, 6), breaks = seq(0, 6, 2)),
"Unique\n signatures" = scale_y_continuous(limits = c(0, 10), breaks = seq(0, 10, 2))
)
HS_df2 %>%
ggplot(aes(x = range, y = values, fill = range, color = range)) +
geom_segment(aes(y = 0, yend = values, x = range, xend = range), color = gray.colors(12)[5], size = 2) +
geom_point(pch = 21, size = 5, stroke = 0.25, alpha = 1) +
facet_grid_sc(rows = vars(statistic), cols = vars(measurement), scales = list(y = scales_y), switch = "y") +
scale_fill_manual(values = fills) +
scale_color_manual(values = cols) +
ylab("Values") + xlab("") +
theme_bw() +
guides(fill = FALSE, color = FALSE) +
theme(
axis.title.y = element_text(size = 14),
axis.text.y = element_text(size = 14),
axis.text.x = element_text(size = 14),
strip.text = element_text(size = 15, margin = margin(1, 0.5, 1, 0.5, "lines")),
legend.position = "top",
legend.text = element_text(size = 14),
panel.grid.major.y = element_line(size = 0.15, linetype = "dotted", color = gray.colors(12)[3]),
panel.grid.major.x = element_blank(),
panel.grid.minor = element_blank()
)
# ggsave(file.path(gpath, "SimplerCalls_BeecherNPotSigs.jpeg"), units = "in", width = 4.52, height = 5.4, dpi = 300)
```
Visualize calls for individuals used to calculate Beecher's statistic per range in acoustic space of frequency contours (DTW on second harmonic frequency contours, then MDS).
```{r echo = TRUE, eval = TRUE}
freq_mod_DTW <- readRDS(file.path(path, "freq_mod_DTW.RDS"))
dimnames(freq_mod_DTW) <- list(as.character(freq_mod_est_indiv$Bird_ID), as.character(freq_mod_est_indiv$Bird_ID))
# Subset the matrix by individuals used for Beecher's statistic
indivs <- c(
freq_mod_est_indiv %>%
filter(site == "1145") %>%
pull(Bird_ID) %>%
unique(),
freq_mod_est_indiv %>%
filter(invasive_city == "Austin" & year == "2019") %>%
pull(Bird_ID) %>%
unique()
)
indivs
freq_mod_DTW_tmp <- freq_mod_DTW[grep(paste(paste("^", indivs, "$", sep = ""), collapse = "|"), dimnames(freq_mod_DTW)[[1]]), grep(paste(paste("^", indivs, "$", sep = ""), collapse = "|"), dimnames(freq_mod_DTW)[[2]])]
str(freq_mod_DTW_tmp)
```
Perform MDS, make a data frame to generate a 2D acoustic space plot.
```{r echo = TRUE, eval = TRUE}
# DTW is already a distance metric
iso <- invisible(MASS::isoMDS(stats::as.dist(freq_mod_DTW_tmp, diag = FALSE, upper = FALSE), k = 2, maxit = 1000, trace = FALSE))
# Join with metadata
mds_df <- data.frame(X = iso$points[, 1]) %>%
dplyr::mutate(
Y = iso$points[, 2],
sound.files = freq_mod_est_indiv %>%
filter(Bird_ID %in% indivs) %>%
pull(sound.files)
) %>%
inner_join(
freq_mod_est_indiv %>%
filter(Bird_ID %in% indivs) %>%
dplyr::select(c(sound.files, Bird_ID, range)),
by = "sound.files"
) %>%
dplyr::mutate(
indiv_ID = as.character(Bird_ID),
indiv_ID = factor(indiv_ID, levels = indivs),
range = as.character(range),
range = factor(range, c("Native", "Invasive"))
)
```
### AM4.1
Convex hull polygons indicate acoustic space encompassed per individual.
```{r, echo = TRUE, eval = TRUE, fig.width = 9, fig.height = 6}
# Initialize aesthetics
n <- 12
# Fill colors and shapes by individual, ordered by native and then invasive range
fills <- c("navy", "royalblue2", "turquoise", "dodgerblue", "cyan", "gold4", "darkorange3", "goldenrod2", "gold2", "yellow")
shps <- c(21, 22, 24, 23, 25, 23, 24, 22, 21, 22, 25)
# Convex hull polygons per indiviual
hulls <- plyr::ddply(mds_df, "indiv_ID", function(x){
x[chull(x$X, x$Y), ]
})
ggplot(mds_df, aes(x = X, y = Y)) +
# One point per call, with fill colors and shapes by individual
geom_point(aes(fill = indiv_ID, shape = indiv_ID), color = "black", size = 7) +
geom_polygon(data = hulls, aes(x = X, y = Y, fill = indiv_ID), alpha = 0.2, size = 0.2) +
scale_fill_manual(values = fills) +
scale_shape_manual(values = shps) +
guides(fill = guide_legend(title = "Individual"), shape = guide_legend(title = "Individual", override.aes = list(size = 4))) +
xlab("Dimension 1") + ylab("Dimension 2") +
theme_bw() +
theme(legend.position = "top") +
theme(
plot.title = element_text(hjust = 0.5, size = 16, face = "bold"),
axis.title = element_text(size = 14),
axis.text = element_text(size = 12),
legend.title = element_text(size = 14),
legend.text = element_text(size = 12)
)
```