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[1]. 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.

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.

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.

indiv_scale <- nat_inv_est %>%
  as_tibble() %>%
  filter(social_scale == "Individual") %>%
  droplevels()
# glimpse(indiv_scale)

Determining how to calculate Beecher’s statistic per range.

indiv_scale %>%
  group_by(range) %>%
  dplyr::summarise(n_indivs = n_distinct(Bird_ID))
## # A tibble: 2 x 2
##   range    n_indivs
##   <fct>       <int>
## 1 Native          8
## 2 Invasive        9

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.

indiv_scale %>%
  filter(range == "Invasive") %>%
  group_by(range, year) %>%
  dplyr::summarise(n_indivs = n_distinct(Bird_ID))
## `summarise()` has grouped output by 'range'. You can override using the `.groups` argument.
## # A tibble: 3 x 3
## # Groups:   range [1]
##   range    year  n_indivs
##   <fct>    <chr>    <int>
## 1 Invasive 2004         1
## 2 Invasive 2011         2
## 3 Invasive 2019         6
indiv_scale %>%
  filter(range == "Invasive") %>%
  group_by(range, invasive_city, site_year) %>%
  dplyr::summarise(n_indivs = n_distinct(Bird_ID))
## `summarise()` has grouped output by 'range', 'invasive_city'. You can override using the `.groups` argument.
## # A tibble: 7 x 4
## # Groups:   range, invasive_city [3]
##   range    invasive_city site_year n_indivs
##   <fct>    <chr>         <chr>        <int>
## 1 Invasive Austin        BART_2011        1
## 2 Invasive Austin        ELEM_2019        2
## 3 Invasive Austin        INTR_2019        1
## 4 Invasive Austin        SOCC_2019        2
## 5 Invasive El Paso       ASCA_2019        1
## 6 Invasive New Orleans   CAME_2004        1
## 7 Invasive New Orleans   ROBE_2011        1

How many individuals for native range sites?

indiv_scale %>%
  filter(range == "Native") %>%
  group_by(site) %>%
  dplyr::summarise(n_birds = n_distinct(Bird_ID))
## # A tibble: 3 x 2
##   site  n_birds
##   <chr>   <int>
## 1 1145        5
## 2 CHAC        1
## 3 EMBR        2

How many individuals for Austin 2019?

indiv_scale %>%
  filter(range == "Invasive") %>%
  filter(invasive_city == "Austin" & year == 2019) %>%
  dplyr::summarise(n_birds = n_distinct(Bird_ID))
## # A tibble: 1 x 1
##   n_birds
##     <int>
## 1       5

Pairwise distances between sites at which we repeatedly sampled individuals in each range.

Native range, using spatial projection for Uruguay.

# 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
##          EMBR      1145      1145     CHAC
## EMBR  0.00000 22.261826 22.413144 11.12075
## 1145 22.26183  0.000000  0.261952 31.70988
## 1145 22.41314  0.261952  0.000000 31.90408
## CHAC 11.12075 31.709884 31.904077  0.00000

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.

# 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
##            BART         ROBE      ASCA       ELEM       INTR       SOCC
## BART   0.000000  739.0314390  851.2830   5.428640   3.436971   7.453898
## ROBE 739.031439    0.0000000 1578.8301 741.318385 742.172954 745.451671
## ASCA 851.282950 1578.8300719    0.0000 850.272197 847.900202 845.982136
## ELEM   5.428640  741.3183851  850.2722   0.000000   6.387587   4.290803
## INTR   3.436971  742.1729536  847.9002   6.387587   0.000000   6.143302
## SOCC   7.453898  745.4516715  845.9821   4.290803   6.143302   0.000000
## CAME 739.395861    0.3726235 1579.1814 741.683316 742.537228 745.816485
##              CAME
## BART  739.3958607
## ROBE    0.3726235
## ASCA 1579.1814492
## ELEM  741.6833158
## INTR  742.5372283
## SOCC  745.8164850
## CAME    0.0000000
range(inv_geo_dists[!inv_geo_dists == 0]/1000)
## [1]    0.3726235 1579.1814492

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[2]. 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.

# 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)
# 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.

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
##  [1] "NAT-UM5"  "NAT-UM1"  "NAT-AAT"  "NAT-RAW"  "NAT-UM3"  "INV-UM17"
##  [7] "NAT-ZW8"  "INV-UM9"  "INV-UM10" "INV-UM16" "NAT-UM4"  "NAT-UM2" 
## [13] "INV-UM7"
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)
##  num [1:64, 1:64] 0 69.8 46 22.5 31.7 ...
##  - attr(*, "dimnames")=List of 2
##   ..$ : chr [1:64] "2017_08_21_CHAC_INDIV-UNMARKED-BIRD5_1242_1.WAV" "2017_07_28_1145-01_INDIV-UNMARKED-BIRD1_1193_22.WAV" "2017_07_29_1145-02_INDIV-AAT_1224_1.WAV" "2017_07_17_EMBR_INDIV-RAW_MZ000199_1.WAV" ...
##   ..$ : chr [1:64] "2017_08_21_CHAC_INDIV-UNMARKED-BIRD5_1242_1.WAV" "2017_07_28_1145-01_INDIV-UNMARKED-BIRD1_1193_22.WAV" "2017_07_29_1145-02_INDIV-AAT_1224_1.WAV" "2017_07_17_EMBR_INDIV-RAW_MZ000199_1.WAV" ...

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.

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.

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.

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()
range type mean upper_CI lower_CI
Native Single site 15.46 15.66 15.27
Native Three sites 14.76 14.94 14.58
Invasive Three sites 15.45 15.70 15.21

Figure A2

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.

# 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.

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)
  )
## # A tibble: 5 x 2
##   Bird_ID n_calls
##   <chr>     <int>
## 1 NAT-AAT       5
## 2 NAT-UM1       5
## 3 NAT-UM2       5
## 4 NAT-UM3       5
## 5 NAT-UM4       5
# 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)
  )
## # A tibble: 5 x 2
##   Bird_ID  n_calls
##   <chr>      <int>
## 1 INV-UM10       5
## 2 INV-UM16       5
## 3 INV-UM17       5
## 4 INV-UM7        5
## 5 INV-UM9        5
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()
range measurement num_indivs num_calls calls_per_indiv vars_for_PCA pcs HS N_sigs
Native Frequency contours 5 25 5 90 25 2.05 4.20
Invasive Frequency contours 5 25 5 90 25 1.09 1.19
Native MFCC 5 25 5 88 25 2.77 7.67
Invasive MFCC 5 25 5 88 25 2.37 5.62

Figure 2C

Beecher’s statistic graphic for main manuscript, Figure 2C.

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).

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
##  [1] "NAT-UM1"  "NAT-AAT"  "NAT-UM3"  "NAT-UM4"  "NAT-UM2"  "INV-UM17"
##  [7] "INV-UM9"  "INV-UM10" "INV-UM16" "INV-UM7"
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)
##  num [1:50, 1:50] 0 104.2 56.4 39.8 59.6 ...
##  - attr(*, "dimnames")=List of 2
##   ..$ : chr [1:50] "NAT-UM1" "NAT-AAT" "NAT-UM3" "NAT-UM1" ...
##   ..$ : chr [1:50] "NAT-UM1" "NAT-AAT" "NAT-UM3" "NAT-UM1" ...

Perform MDS, make a data frame to generate a 2D acoustic space plot.

# 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.

# 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)
    )

Nice separation of individuals in acoustic space using manually traced frequency contours, note the separation by range as well.

References

1. Linhart P., Osiejuk T.S., Budka M., Salek M., Spinka M., Policht R., Syrova M. and D.T. Blumstein. 2019. Measuring individual identity information in animal signals: Overview and performance of available identity metrics. Methods in Ecology and Evolution 10(9), 1558–1570.

2. Smith-Vidaurre, G., Araya-Salas, M., and T.F. Wright. 2020. Individual signatures outweigh social group identity in contact calls of a communally nesting parrot. Behavioral Ecology 31(2), 448-458.

The session info printed here represents the environment used for the final RMarkdown knitting. The software and package versions employed for main results are reported in the appendix of the associated article.

sessionInfo()
## R version 4.1.0 (2021-05-18)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 18.04.5 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
##  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
##  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
## [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
## 
## attached base packages:
## [1] grid      parallel  stats     graphics  grDevices utils     datasets 
## [8] methods   base     
## 
## other attached packages:
##  [1] caret_6.0-88           Rmisc_1.5              lattice_0.20-44       
##  [4] facetscales_0.1.0.9000 rgdal_1.5-23           rgeos_0.5-5           
##  [7] sp_1.4-5               ggplotify_0.0.7        egg_0.4.5             
## [10] gridExtra_2.3          knitr_1.33             IDmeasurer_1.0.0      
## [13] scales_1.1.1           data.table_1.14.0      pbapply_1.4-3         
## [16] forcats_0.5.1          stringr_1.4.0          dplyr_1.0.6           
## [19] purrr_0.3.4            readr_1.4.0            tidyr_1.1.3           
## [22] tibble_3.1.2           ggplot2_3.3.3          tidyverse_1.3.1       
## [25] plyr_1.8.6            
## 
## loaded via a namespace (and not attached):
##  [1] nlme_3.1-152         fs_1.5.0             lubridate_1.7.10    
##  [4] httr_1.4.2           tools_4.1.0          backports_1.2.1     
##  [7] utf8_1.2.1           R6_2.5.0             rpart_4.1-15        
## [10] DBI_1.1.1            colorspace_2.0-1     nnet_7.3-16         
## [13] withr_2.4.2          tidyselect_1.1.1     compiler_4.1.0      
## [16] cli_2.5.0            rvest_1.0.0          xml2_1.3.2          
## [19] labeling_0.4.2       digest_0.6.27        rmarkdown_2.8       
## [22] pkgconfig_2.0.3      htmltools_0.5.1.1    highr_0.9           
## [25] dbplyr_2.1.1         rlang_0.4.11         readxl_1.3.1        
## [28] rstudioapi_0.13      farver_2.1.0         gridGraphics_0.5-1  
## [31] generics_0.1.0       jsonlite_1.7.2       ModelMetrics_1.2.2.2
## [34] magrittr_2.0.1       Matrix_1.3-4         Rcpp_1.0.6          
## [37] munsell_0.5.0        fansi_0.5.0          lifecycle_1.0.0     
## [40] pROC_1.17.0.1        stringi_1.6.2        yaml_2.2.1          
## [43] MASS_7.3-54          recipes_0.1.16       crayon_1.4.1        
## [46] haven_2.4.1          splines_4.1.0        hms_1.1.0           
## [49] pillar_1.6.1         stats4_4.1.0         reshape2_1.4.4      
## [52] codetools_0.2-18     reprex_2.0.0         glue_1.4.2          
## [55] evaluate_0.14        BiocManager_1.30.15  modelr_0.1.8        
## [58] vctrs_0.3.8          foreach_1.5.1        cellranger_1.1.0    
## [61] gtable_0.3.0         assertthat_0.2.1     xfun_0.23           
## [64] gower_0.2.2          prodlim_2019.11.13   broom_0.7.6         
## [67] class_7.3-19         survival_3.2-11      timeDate_3043.102   
## [70] iterators_1.0.13     rvcheck_0.1.8        lava_1.6.9          
## [73] ellipsis_0.3.2       ipred_0.9-11