NewResults

#Drivers of EFN plant richness

library(sf)
Linking to GEOS 3.11.2, GDAL 3.6.2, PROJ 9.2.0; sf_use_s2() is TRUE
library(raster)
Loading required package: sp
The legacy packages maptools, rgdal, and rgeos, underpinning the sp package,
which was just loaded, will retire in October 2023.
Please refer to R-spatial evolution reports for details, especially
https://r-spatial.org/r/2023/05/15/evolution4.html.
It may be desirable to make the sf package available;
package maintainers should consider adding sf to Suggests:.
The sp package is now running under evolution status 2
     (status 2 uses the sf package in place of rgdal)
library(dplyr)

Attaching package: 'dplyr'
The following objects are masked from 'package:raster':

    intersect, select, union
The following objects are masked from 'package:stats':

    filter, lag
The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union
library(tidyr)

Attaching package: 'tidyr'
The following object is masked from 'package:raster':

    extract
library(ggplot2)
Warning: package 'ggplot2' was built under R version 4.3.3
#stack the prediction rasters

efnlist<- raster::stack("data/output/predictions/mean_pred_CA.grd", "data/output/predictions/mean_pred_CE.grd", "data/output/predictions/mean_pred_AG.grd", "data/output/predictions/mean_pred_FS.grd", "data/output/predictions/mean_pred_CL.grd", "data/output/predictions/mean_pred_OB.grd", "data/output/predictions/mean_pred_OBIG.grd", "data/output/predictions/mean_pred_FA.grd", "data/output/predictions/mean_pred_PJ.grd", "data/output/predictions/mean_pred_PFA.grd", "data/output/predictions/mean_pred_PFREM.grd")

names(efnlist) <- c("CA", "CE", "AG", "FS", "CL", "OB", "OBIG", "FA", "PJ", "PFA", "PFREM")

plot(efnlist)

EFN_sum <- sum(efnlist, na.rm = TRUE)
plot(EFN_sum)

#clip to mojave
r <- brick("na_rasters.grd")

crs <- st_crs(r)
moj <- read_sf("data/mojavescol.shp")
moj <- st_transform(moj, crs)

EFN_sum <- mask(EFN_sum, moj)
efnlist <- mask(efnlist, moj)
plot(EFN_sum)

plot(efnlist)

clim <- stack(
      "data/output/predictions/mean_pred_CAMPFRA.grd",
      "data/output/predictions/mean_pred_CAMPOC.grd",
      "data/output/predictions/mean_pred_CAMPSEM.grd",
      "data/output/predictions/mean_pred_MYRMIM.grd",
      "data/output/predictions/mean_pred_CREMD.grd",
      "data/output/predictions/mean_pred_DORBI.grd", 
      "data/output/predictions/mean_pred_DORIN.grd",
      "data/output/predictions/mean_pred_MYRFLA.grd",
      "data/output/predictions/mean_pred_MYRKEN.grd",
      "data/output/predictions/mean_pred_MYRTES.grd",      
      "data/output/predictions/mean_pred_SX.grd",
      "data/output/predictions/mean_pred_LIOLUC.grd",
      "data/output/predictions/mean_pred_PHEVIS.grd",      
      "data/output/predictions/mean_pred_FM.grd")

names <- c(
      "CAMPFRA.grd",
      "CAMPOC.grd",
      "CAMPSEM.grd",
      "MYRMIM.grd",
      "CREMD.grd",
      "DORBI.grd", 
      "DORIN.grd",
      "MYRFLA.grd",
      "MYRKEN.grd",
      "MYRTES.grd",      
      "SX.grd",
      "LIOLUC.grd",
      "PHEVIS.grd",
      "FM.grd")

names(clim) <- names

ants <- sum(clim)
ants <- mask(ants, moj)
clim <- mask(clim, moj)
plot(ants)

plot(clim)

Evaluate models

#ants 
filenames <- list.files("predictions/ants", full.names = TRUE, pattern = "csv$")


ants <- purrr::map_df(filenames, 
              ~read.csv(.x, stringsAsFactors = FALSE) %>% mutate(filename = .x))


ants_mods <- ants %>% group_by(filename) %>% summarise(auc = mean(test_auc), aucsd = sd(test_auc), tss = mean(test_tss), tsssd = sd(test_tss))

ants_mods[,2:5] <- round(ants_mods[,2:5], 2)




filenames <- list.files("predictions/antcontrasts", full.names = TRUE, pattern = "csv$")


ants_contrasts <- purrr::map_df(filenames, 
              ~read.csv(.x, stringsAsFactors = FALSE) %>% mutate(filename = .x))



#plants 
filenames <- list.files("predictions/", full.names = TRUE, pattern = "csv$")


plants <- purrr::map_df(filenames, 
              ~read.csv(.x, stringsAsFactors = FALSE) %>% mutate(filename = .x))


plants_mods <- plants %>% group_by(filename) %>% summarise(auc = mean(test_auc), aucsd = sd(test_auc), tss = mean(test_tss), tsssd = sd(test_tss))

plants_mods[,2:5] <- round(plants_mods[,2:5], 3)


write.csv(plants_mods, "plantCV.csv")

Collect EFN models

#ants is clim only models

ants$type <- "clim"
ants <- rename(ants, species = filename)
ants$species <- gsub("predictions/ants/CV_Results_", "", ants$species) 
ants$species <- gsub(".csv", "", ants$species) 


#ants_contrasts
ants_contrasts$filename <- gsub("predictions/antcontrasts/CV_Results_", "", ants_contrasts$filename) 
ants_contrasts$filename <- gsub(".csv", "", ants_contrasts$filename) 
ants_contrasts <- separate(ants_contrasts, filename, into = c("species", "type", "bin"), sep = "_")
Warning: Expected 3 pieces. Missing pieces filled with `NA` in 600 rows [1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...].
ants_contrasts$bin[is.na(ants_contrasts$bin)] <- "con"

ants_contrasts <- filter(ants_contrasts, bin != "bin")
ants_contrasts <- filter(ants_contrasts, type == "EFN" | type == "EFN-only" | type == "EFN_only")




ants_contrasts <- mutate(ants_contrasts, treat = ifelse(bin == "only", "EFN-only", type))


ants_contrasts <- select(ants_contrasts, -bin, - type)

ants_contrasts <- rename(ants_contrasts, type = treat)

dfcomp <- rbind(ants, ants_contrasts)
dfcomp <- filter(dfcomp, species != "CAMPSAY" & species != "FP")

Compare model performance

library(glmmTMB)
library(ggplot2)
library(performance)
dfcomp2 <- filter(dfcomp, type != "EFN-only")

m1 <- glmmTMB(test_auc ~ type + (1|species), data = dfcomp)
model_performance(m1)
# Indices of model performance

AIC       |      AICc |       BIC | R2 (cond.) | R2 (marg.) |   ICC |  RMSE | Sigma
-----------------------------------------------------------------------------------
-5082.941 | -5082.903 | -5056.179 |      0.679 |      0.081 | 0.650 | 0.046 | 0.046
summary(m1)
 Family: gaussian  ( identity )
Formula:          test_auc ~ type + (1 | species)
Data: dfcomp

     AIC      BIC   logLik deviance df.resid 
 -5082.9  -5056.2   2546.5  -5092.9     1555 

Random effects:

Conditional model:
 Groups   Name        Variance Std.Dev.
 species  (Intercept) 0.003966 0.06297 
 Residual             0.002133 0.04618 
Number of obs: 1560, groups:  species, 14

Dispersion estimate for gaussian family (sigma^2): 0.00213 

Conditional model:
              Estimate Std. Error z value Pr(>|z|)    
(Intercept)   0.784801   0.016943   46.32  < 2e-16 ***
typeEFN       0.014303   0.002760    5.18 2.19e-07 ***
typeEFN-only -0.042497   0.003028  -14.03  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
plot(resid(m1))

ggplot(dfcomp2, aes(type, test_auc)) + geom_boxplot()

ggplot(dfcomp, aes(species, test_auc)) + geom_boxplot(aes(fill = type)) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black")) + ylab("Test AUC (predictive accuracy)") + xlab("Ant Species") + scale_fill_manual(values = c("gray", "black", "white"), labels = c("Climate Only", "EFN + Climate", "EFN Only")) + stat_summary(fun.y=mean, aes(group = type, fill = type), geom="point", size=1, color = "red", position=position_dodge(width=0.75)) +
scale_x_discrete(labels = c("Camponotus \nfragilis", "Camponotus \nocreatus", "Camponotus \nsemitestaceus", "Crematogaster \ndepilis", "Dorymyrmex \nbicolor", "Dorymyrmex \ninsanus", "Forelius \nmccooki", "Liometopum \nluctuosum", "Myrmecocystus \nflaviceps", "Myrmecocystus \nkennedyi", "Myrmecocystus \nmimicus", "Myrmecocystus \ntestaceus", "Pheidole \nvistana", "Solenopsis \nxyloni")) +
  theme(legend.title=element_blank()) + theme(axis.text.x = element_text(angle = 90, hjust = 1))
Warning: The `fun.y` argument of `stat_summary()` is deprecated as of ggplot2 3.3.0.
ℹ Please use the `fun` argument instead.

dfcomp %>% group_by(species, type) %>% summarize(mean = mean(test_auc))
`summarise()` has grouped output by 'species'. You can override using the
`.groups` argument.
# A tibble: 39 × 3
# Groups:   species [14]
   species type      mean
   <chr>   <chr>    <dbl>
 1 CAMPFRA EFN      0.841
 2 CAMPFRA clim     0.815
 3 CAMPOC  EFN      0.837
 4 CAMPOC  EFN-only 0.837
 5 CAMPOC  clim     0.809
 6 CAMPSEM EFN      0.818
 7 CAMPSEM EFN-only 0.818
 8 CAMPSEM clim     0.828
 9 CREMD   EFN      0.789
10 CREMD   EFN-only 0.826
# ℹ 29 more rows

plot(efnlist[[1]]) plot(ca_thin, add = TRUE)

plot(efnlist)

Environmental Rasters

r <- brick("na_rasters.grd")
# #
# #
crs <- st_crs(r)
moj <- read_sf("data/mojavescol.shp")
moj <- st_transform(moj, crs)
e = terra::ext(moj)

env.nopca <- crop(r, extent(moj))


#check occurrences using mcp
env.nopca <- mask(env.nopca, moj)
env.nopca <- terra::rast(env.nopca)

Plant Future

efn245<- raster::stack("data/output/predictions/Future/ssp245/mean_pred_CA_ssp245.grd", "data/output/predictions/Future/ssp245/mean_pred_CE_ssp245.grd", "data/output/predictions/Future/ssp245/mean_pred_AG_ssp245.grd", "data/output/predictions/Future/ssp245/mean_pred_FS_ssp245.grd", "data/output/predictions/Future/ssp245/mean_pred_CL_ssp245.grd", "data/output/predictions/Future/ssp245/mean_pred_OB_ssp245.grd", "data/output/predictions/Future/ssp245/mean_pred_OBIG_ssp245.grd", "data/output/predictions/Future/ssp245/mean_pred_FA_ssp245.grd", "data/output/predictions/Future/ssp245/mean_pred_PJ_ssp245.grd", "data/output/predictions/Future/ssp245/mean_pred_PFA_ssp245.grd", "data/output/predictions/Future/ssp245/mean_pred_PFREM_ssp245.grd")

plot(efn245)

efn245_sum <- sum(efn245)

efn370<- raster::stack("data/output/predictions/Future/ssp370/mean_pred_CA_ssp370.grd", "data/output/predictions/Future/ssp370/mean_pred_CE_ssp370.grd", "data/output/predictions/Future/ssp370/mean_pred_AG_ssp370.grd", "data/output/predictions/Future/ssp370/mean_pred_FS_ssp370.grd", "data/output/predictions/Future/ssp370/mean_pred_CL_ssp370.grd", "data/output/predictions/Future/ssp370/mean_pred_OB_ssp370.grd", "data/output/predictions/Future/ssp370/mean_pred_OBIG_ssp370.grd", "data/output/predictions/Future/ssp370/mean_pred_FA_ssp370.grd", "data/output/predictions/Future/ssp370/mean_pred_PJ_ssp370.grd", "data/output/predictions/Future/ssp370/mean_pred_PFA_ssp370.grd", "data/output/predictions/Future/ssp370/mean_pred_PFREM_ssp370.grd")

plot(efn370)

efn370_sum <- sum(efn370)

Ant Future

ant245 <- stack(
      "data/output/predictions/Future/ssp245/mean_pred_CAMPFRA_ssp245.grd",
      "data/output/predictions/Future/ssp245/mean_pred_CAMPOC_ssp245.grd",
      "data/output/predictions/Future/ssp245/mean_pred_CAMPSEM_ssp245.grd",
      "data/output/predictions/Future/ssp245/mean_pred_MYRMIM_ssp245.grd",
      "data/output/predictions/Future/ssp245/mean_pred_CREMD_ssp245.grd",
      "data/output/predictions/Future/ssp245/mean_pred_DORBI_ssp245.grd", 
      "data/output/predictions/Future/ssp245/mean_pred_DORIN_ssp245.grd",
      "data/output/predictions/Future/ssp245/mean_pred_MYRFLA_ssp245.grd",
      "data/output/predictions/Future/ssp245/mean_pred_MYRKEN_ssp245.grd",
      "data/output/predictions/Future/ssp245/mean_pred_MYRTES_ssp245.grd",      
      "data/output/predictions/Future/ssp245/mean_pred_SX_ssp245.grd",
      "data/output/predictions/Future/ssp245/mean_pred_LIOLUC_ssp245.grd",
      "data/output/predictions/Future/ssp245/mean_pred_PHEVIS_ssp245.grd",
      "data/output/predictions/Future/ssp245/mean_pred_FM_ssp245.grd")


plot(ant245)

ant245_sum <- sum(ant245)

ant370 <- stack(
      "data/output/predictions/Future/ssp370/mean_pred_CAMPFRA_ssp370.grd",
      "data/output/predictions/Future/ssp370/mean_pred_CAMPOC_ssp370.grd",
      "data/output/predictions/Future/ssp370/mean_pred_CAMPSEM_ssp370.grd",
      "data/output/predictions/Future/ssp370/mean_pred_MYRMIM_ssp370.grd",
      "data/output/predictions/Future/ssp370/mean_pred_CREMD_ssp370.grd",
      "data/output/predictions/Future/ssp370/mean_pred_DORBI_ssp370.grd", 
      "data/output/predictions/Future/ssp370/mean_pred_DORIN_ssp370.grd",
      "data/output/predictions/Future/ssp370/mean_pred_MYRFLA_ssp370.grd",
      "data/output/predictions/Future/ssp370/mean_pred_MYRKEN_ssp370.grd",
      "data/output/predictions/Future/ssp370/mean_pred_MYRTES_ssp370.grd",      
      "data/output/predictions/Future/ssp370/mean_pred_SX_ssp370.grd",
      "data/output/predictions/Future/ssp370/mean_pred_LIOLUC_ssp370.grd",
      "data/output/predictions/Future/ssp370/mean_pred_PHEVIS_ssp370.grd",
      "data/output/predictions/Future/ssp370/mean_pred_FM_ssp370.grd")
plot(ant370)

ant370_sum <- sum(ant370)
plot(ant370)
plot(ant370_sum)

Env Future

ssp245 <- brick("ssp245.grd")

ssp245 <- terra::rast(ssp245)
ssp370 <- brick("ssp370.grd")
ssp370 <- terra::rast(ssp370)
plot(ssp245)

plot(ssp370)

Environmental Shifts

PC1 and PC2 Shifts

envs <- brick("envs.grd")
plot(envs)

env <- mask(envs, moj)
plot(env)

pc1pres <- env[[1]]
plot(pc1pres)

ssp245 <- mask(ssp245, moj)
ssp370 <- mask(ssp370, moj)
pc1245 <- ssp245[[1]]
pc1pres <- terra::rast(pc1pres)
plot(pc1pres)

plot(pc1245)

pc1change <- pc1pres - pc1245
plot(pc1change)

pc2pres <- env[[2]]
pc2pres <- terra::rast(pc2pres)
pc2245 <- ssp245[[2]]
pc2change <- pc2pres - pc2245
plot(pc2change)

plot(pc2pres)

shift <- terra::rast(env) - ssp245
plot(shift)

shift2<- ssp370
plot(shift2)

plot(ssp370[[4]])

plot(env)

Richness sampling

ants <- sum(clim)
ants <- mask(ants, moj)
plot(ants)

env <- mask(envs, moj)
plot(env)

all <- stack(EFN_sum, ants, env)
names(all)
[1] "layer.1" "layer.2" "PC1"     "PC2"     "PC3"     "PC4"    
names(all) <- c("EFN", "ants", "PC1", "PC2", "PC3", "PC4")



plot(all)

#par(mfrow = c(1, 2))
plot(ants)

plot(EFN_sum)

# 
# val <- values(all)
# val <- as.data.frame(all)
# val <- drop_na(val)

pts <- dismo::randomPoints(all, 5000)
df <- raster::extract(all, pts)
df <- as.data.frame(df)

dfenv <- df[,3:6]



library(vegan)
Loading required package: permute
Loading required package: lattice
This is vegan 2.6-4
v1 <- varpart(df$ants, df$EFN, dfenv)
plot(v1)

Change Analyses

EFN_sum <- mask(EFN_sum, moj)
plot(EFN_sum)

efn245_sum <- mask(efn245_sum, moj)
plot(efn245_sum)

efn370_sum <- mask(efn370_sum, moj)
plot(efn370_sum)

efnchange <- stack(EFN_sum, efn245_sum, efn370_sum)
names(efnchange) <- c("EFN", "245", "370")


# 
# val <- values(all)
# val <- as.data.frame(all)
# val <- drop_na(val)

pts <- dismo::randomPoints(efnchange, 5000)
df <- raster::extract(efnchange, pts)
df <- as.data.frame(df)
df$row <- row.names(df)

dfefn <- pivot_longer(df, 1:3, names_to = "scenario", values_to = "rich")

library(glmmTMB)
m1 <- glmmTMB(rich ~ scenario + (1|row), data = dfefn)
summary(m1)
 Family: gaussian  ( identity )
Formula:          rich ~ scenario + (1 | row)
Data: dfefn

     AIC      BIC   logLik deviance df.resid 
 37114.1  37152.2 -18552.1  37104.1    14995 

Random effects:

Conditional model:
 Groups   Name        Variance Std.Dev.
 row      (Intercept) 2.1887   1.4794  
 Residual             0.2222   0.4714  
Number of obs: 15000, groups:  row, 5000

Dispersion estimate for gaussian family (sigma^2): 0.222 

Conditional model:
              Estimate Std. Error z value Pr(>|z|)    
(Intercept)   2.832552   0.021959  128.99   <2e-16 ***
scenarioX245 -0.337055   0.009428  -35.75   <2e-16 ***
scenarioX370 -0.379453   0.009428  -40.25   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
car::Anova(m1)
Analysis of Deviance Table (Type II Wald chisquare tests)

Response: rich
          Chisq Df Pr(>Chisq)    
scenario 1945.3  2  < 2.2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
library(emmeans)

emmeans(m1, pairwise ~ scenario)
$emmeans
 scenario emmean    SE    df lower.CL upper.CL
 EFN        2.83 0.022 14995     2.79     2.88
 X245       2.50 0.022 14995     2.45     2.54
 X370       2.45 0.022 14995     2.41     2.50

Confidence level used: 0.95 

$contrasts
 contrast    estimate      SE    df t.ratio p.value
 EFN - X245    0.3371 0.00943 14995  35.749  <.0001
 EFN - X370    0.3795 0.00943 14995  40.245  <.0001
 X245 - X370   0.0424 0.00943 14995   4.497  <.0001

P value adjustment: tukey method for comparing a family of 3 estimates 
ggplot(dfefn, aes())

plot(ants)

ant245_sum <- mask(ant245_sum, moj)
plot(ant245_sum)

ant370_sum <- mask(ant370_sum, moj)
plot(ant370_sum)

antchange <- stack(ants, ant245_sum, ant370_sum)
names(antchange) <- c("ant", "245", "370")

plot(antchange)

# 
# val <- values(all)
# val <- as.data.frame(all)
# val <- drop_na(val)

pts <- dismo::randomPoints(antchange, 5000)
df <- raster::extract(antchange, pts)
df <- as.data.frame(df)
df$row <- row.names(df)

dfant <- pivot_longer(df, 1:3, names_to = "scenario", values_to = "rich")

library(glmmTMB)
m1 <- glmmTMB(rich ~ scenario + (1|row), data = dfant)
summary(m1)
 Family: gaussian  ( identity )
Formula:          rich ~ scenario + (1 | row)
Data: dfant

     AIC      BIC   logLik deviance df.resid 
 32207.4  32245.4 -16098.7  32197.4    14995 

Random effects:

Conditional model:
 Groups   Name        Variance Std.Dev.
 row      (Intercept) 2.1095   1.4524  
 Residual             0.1394   0.3733  
Number of obs: 15000, groups:  row, 5000

Dispersion estimate for gaussian family (sigma^2): 0.139 

Conditional model:
              Estimate Std. Error z value Pr(>|z|)    
(Intercept)   4.551944   0.021208  214.64   <2e-16 ***
scenarioX245 -0.235480   0.007467  -31.54   <2e-16 ***
scenarioX370 -0.273844   0.007467  -36.67   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
emmeans(m1, pairwise ~ scenario)
$emmeans
 scenario emmean     SE    df lower.CL upper.CL
 ant        4.55 0.0212 14995     4.51     4.59
 X245       4.32 0.0212 14995     4.27     4.36
 X370       4.28 0.0212 14995     4.24     4.32

Confidence level used: 0.95 

$contrasts
 contrast    estimate      SE    df t.ratio p.value
 ant - X245    0.2355 0.00747 14995  31.536  <.0001
 ant - X370    0.2738 0.00747 14995  36.674  <.0001
 X245 - X370   0.0384 0.00747 14995   5.138  <.0001

P value adjustment: tukey method for comparing a family of 3 estimates 
library(ggplot2)



dfefn$type <- "EFN"
dfant$type <- "ants"

all <- rbind(dfefn, dfant)
ggplot(all, aes(type, rich, fill = scenario)) + geom_boxplot()

m1 <- glmmTMB(rich ~ scenario*type + (1|row), data = all)
Warning in .checkRankX(TMBStruc, control$rank_check): fixed effects in
conditional model are rank deficient
Warning in fitTMB(TMBStruc): Model convergence problem; non-positive-definite
Hessian matrix. See vignette('troubleshooting')
#maps for losses
antloss <- ant370_sum - ants
par(mfrow=c(1,1))
plot(antloss)

efnloss <- efn370_sum - EFN_sum
pal <- colorRampPalette(c("white","black"))

df = as.data.frame(efnloss, xy=TRUE)

dfantloss = as.data.frame(antloss, xy=TRUE)

par(mfrow=c(2,2))
#, values = c(-4.381, 0, 3.2908)
ggplot(df) + geom_raster(aes(y=y, x=x, fill=layer)) + scale_fill_gradient2(low = "red",high = "darkgreen") +  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black")) + xlab("Longitude") + ylab("Latitude") + labs(fill = "Absolute change in richness")

ggplot(dfantloss) + geom_raster(aes(y=y, x=x, fill=layer)) + scale_fill_gradient2(low = "red",high = "darkgreen") +  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black")) + xlab("Longitude") + ylab("Latitude") + labs(fill = "Absolute change in richness")

par(mfrow=c(1,1))

Suitability shifts

ant245 <- mask(ant245, moj)
efn245 <- mask(efn245, moj)
ant370 <- mask(ant370, moj)
efn370 <- mask(efn370, moj)
plot(clim)

plot(efnlist)

plot(efn370)

diff_ants_245 <- ant245 - clim
diff_efn_245 <- efn245 - efnlist

plot(diff_ants_245)

plot(diff_efn_245)

clim
class      : RasterBrick 
dimensions : 631, 662, 417722, 14  (nrow, ncol, ncell, nlayers)
resolution : 0.008333333, 0.008333333  (x, y)
extent     : -118.4667, -112.95, 32.23333, 37.49167  (xmin, xmax, ymin, ymax)
crs        : +proj=longlat +datum=WGS84 +no_defs 
source     : memory
names      :  CAMPFRA.grd,   CAMPOC.grd,  CAMPSEM.grd,   MYRMIM.grd,    CREMD.grd,    DORBI.grd,    DORIN.grd,   MYRFLA.grd,   MYRKEN.grd,   MYRTES.grd,       SX.grd,   LIOLUC.grd,   PHEVIS.grd,       FM.grd 
min values : 7.888647e-03, 2.802870e-03, 6.433448e-03, 4.179693e-02, 8.764294e-05, 1.865301e-05, 2.246685e-04, 9.579646e-03, 1.436905e-02, 3.796399e-04, 4.943804e-04, 6.429036e-03, 1.343334e-04, 2.657017e-02 
max values :    0.9990820,    0.9999954,    0.9649383,    0.9999545,    0.9819332,    0.9997110,    0.9942368,    0.9759405,    0.9533707,    0.9981019,    0.9997969,    0.9999999,    0.9882129,    0.9986585 
cellStats(diff_ants_245, "mean")
     layer.1      layer.2      layer.3      layer.4      layer.5      layer.6 
 0.010643809 -0.057551136 -0.107946291  0.065819174 -0.089674631  0.003932822 
     layer.7      layer.8      layer.9     layer.10     layer.11     layer.12 
-0.009356478  0.014683791  0.081386405 -0.062089297 -0.011707559 -0.044671622 
    layer.13     layer.14 
-0.042465869  0.027127553 
efnlist
class      : RasterBrick 
dimensions : 631, 662, 417722, 11  (nrow, ncol, ncell, nlayers)
resolution : 0.008333333, 0.008333333  (x, y)
extent     : -118.4667, -112.95, 32.23333, 37.49167  (xmin, xmax, ymin, ymax)
crs        : +proj=longlat +datum=WGS84 +no_defs 
source     : memory
names      :           CA,           CE,           AG,           FS,           CL,           OB,         OBIG,           FA,           PJ,          PFA,        PFREM 
min values : 6.326828e-10, 2.157394e-05, 7.432635e-05, 5.026921e-04, 2.818367e-03, 2.177272e-04, 8.527404e-06, 8.992705e-05, 1.772955e-02, 8.693415e-04, 2.386375e-08 
max values :    0.9990322,    0.9999747,    0.9999039,    0.9667128,    0.9960869,    0.9999986,    0.9994834,    0.9999981,    0.9864241,    0.9978565,    0.8362184 
cellStats(diff_efn_245, "mean")
      mean.1       mean.2       mean.3       mean.4       mean.5       mean.6 
-0.049431260 -0.074366853 -0.032725881 -0.023702277 -0.025314433 -0.060333097 
      mean.7       mean.8       mean.9      mean.10      mean.11 
-0.030555636 -0.057198631  0.113127780 -0.091007301 -0.003061824 
names(efnlist)
 [1] "CA"    "CE"    "AG"    "FS"    "CL"    "OB"    "OBIG"  "FA"    "PJ"   
[10] "PFA"   "PFREM"
names(efn245)
 [1] "mean.1"  "mean.2"  "mean.3"  "mean.4"  "mean.5"  "mean.6"  "mean.7" 
 [8] "mean.8"  "mean.9"  "mean.10" "mean.11"
diff_ants_370 <- ant370 - clim
diff_efn_370 <- efn370 - efnlist

plot(diff_ants_370)

plot(diff_efn_370)

clim
class      : RasterBrick 
dimensions : 631, 662, 417722, 14  (nrow, ncol, ncell, nlayers)
resolution : 0.008333333, 0.008333333  (x, y)
extent     : -118.4667, -112.95, 32.23333, 37.49167  (xmin, xmax, ymin, ymax)
crs        : +proj=longlat +datum=WGS84 +no_defs 
source     : memory
names      :  CAMPFRA.grd,   CAMPOC.grd,  CAMPSEM.grd,   MYRMIM.grd,    CREMD.grd,    DORBI.grd,    DORIN.grd,   MYRFLA.grd,   MYRKEN.grd,   MYRTES.grd,       SX.grd,   LIOLUC.grd,   PHEVIS.grd,       FM.grd 
min values : 7.888647e-03, 2.802870e-03, 6.433448e-03, 4.179693e-02, 8.764294e-05, 1.865301e-05, 2.246685e-04, 9.579646e-03, 1.436905e-02, 3.796399e-04, 4.943804e-04, 6.429036e-03, 1.343334e-04, 2.657017e-02 
max values :    0.9990820,    0.9999954,    0.9649383,    0.9999545,    0.9819332,    0.9997110,    0.9942368,    0.9759405,    0.9533707,    0.9981019,    0.9997969,    0.9999999,    0.9882129,    0.9986585 
cellStats(diff_ants_370, "mean")
     layer.1      layer.2      layer.3      layer.4      layer.5      layer.6 
 0.016514546 -0.062574115 -0.119294563  0.070101608 -0.099504321  0.003760421 
     layer.7      layer.8      layer.9     layer.10     layer.11     layer.12 
-0.013071080  0.010015764  0.087884336 -0.068017098 -0.023481086 -0.048126861 
    layer.13     layer.14 
-0.045895252  0.032735155 
cellStats(diff_efn_370, "mean")
      mean.1       mean.2       mean.3       mean.4       mean.5       mean.6 
-0.052474480 -0.081744406 -0.041294843 -0.023408825 -0.030617617 -0.071073177 
      mean.7       mean.8       mean.9      mean.10      mean.11 
-0.028247793 -0.062429900  0.122373207 -0.098536777 -0.004193281 
ant_diff <- rbind(names(clim), cellStats(diff_ants_245, "mean"),  cellStats(diff_ants_370, "mean")) 

row.names(ant_diff) <- c("names", "diff245", "diff370")


efn_diff <- rbind(names(efnlist), cellStats(diff_efn_245, "mean"), cellStats(diff_efn_370, "mean")) 

row.names(efn_diff) <- c("names", "diff245", "diff370")

Suitability shift map

shift370 <- ant370_sum - ants
plot(shift370)

df = as.data.frame(shift370, xy=TRUE)
ggplot(df) + geom_raster(aes(y=y, x=x, fill=layer)) + scale_fill_gradient2(low = "red",high = "darkgreen", name="Change in \nSpecies Richness") +  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"))

efn_change_370 <- efn370_sum - EFN_sum
df = as.data.frame(efn_change_370, xy=TRUE)
ggplot(df) + geom_raster(aes(y=y, x=x, fill=layer)) + scale_fill_gradient2(low = "red",high = "darkgreen", name="Change in \nSpecies Richness") + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black")) 

plot(EFN_sum)

plot(ants)

plot(efn370_sum)

plot(ant370_sum)

Phylogeny

#install.packages("phytools")
#install.packages("picante")
library(picante)
Loading required package: ape

Attaching package: 'ape'
The following object is masked from 'package:dplyr':

    where
The following objects are masked from 'package:raster':

    rotate, zoom
Loading required package: nlme

Attaching package: 'nlme'
The following object is masked from 'package:dplyr':

    collapse
The following object is masked from 'package:raster':

    getData
library(phytools)
Warning: package 'phytools' was built under R version 4.3.2
Loading required package: maps

Attaching package: 'phytools'
The following object is masked from 'package:vegan':

    scores
library(tidyr)
genusv <- c("Camponotus", "Crematogaster", "Dorymyrmex", "Forelius", "Liometopum", "Myrmecocystus", "Pheidole", "Solenopsis")

#import nexus tree
tree <- read.nexus("data/moreaubeast.nex")
str(tree)
List of 4
 $ edge       : int [1:550, 1:2] 277 278 279 280 281 282 283 284 285 286 ...
 $ edge.length: num [1:550] 31.17 8.86 16.31 12.32 13.82 ...
 $ Nnode      : int 275
 $ tip.label  : chr [1:276] "Eutetramorium_sp._CSM" "Proatta_butteli_CSM" "Lophomyrmex_striatulus_CSM" "Mayriella_transfuga_CSM" ...
 - attr(*, "class")= chr "phylo"
 - attr(*, "order")= chr "cladewise"
plot(tree)

tree

Phylogenetic tree with 276 tips and 275 internal nodes.

Tip labels:
  Eutetramorium_sp._CSM, Proatta_butteli_CSM, Lophomyrmex_striatulus_CSM, Mayriella_transfuga_CSM, Mayriella_ebbei, Dilobocondyla_sp._CSM, ...

Rooted; includes branch lengths.
labels <- tree[["tip.label"]]
labels <- as.data.frame(labels)
full <- labels$labels
labels <- separate_wider_delim(labels, cols = 1, delim ="_", names = c("genus", "sp", "csm"), too_few = "align_start", too_many = "merge")
labels <- cbind(full, labels)
labels <- subset(labels, genus %in% genusv)
keep <- labels$full
df <- data.frame(matrix(ncol = 21, nrow = 1))
colnames(df) <- keep
df[is.na(df)] <- 1
df <- dplyr::select(df, 1, 4, 7, 10, 13, 16, 18, 21)
pruned <- prune.sample(df, tree)
pruned <- add.species.to.genus(pruned, "Myrmecocystus_kennedyi")
pruned <- add.species.to.genus(pruned, "Myrmecocystus_testaceus")
pruned <- add.species.to.genus(pruned, "Myrmecocystus_mimicus")
pruned <- add.species.to.genus(pruned, "Camponotus_fragilis")
pruned <- add.species.to.genus(pruned, "Camponotus_semitestaceus")
pruned <- add.species.to.genus(pruned, "Dorymyrmex_insanus")

pruned

Phylogenetic tree with 14 tips and 10 internal nodes.

Tip labels:
  Crematogaster_navajoa_CSM, Pheidole_hyatti, Solenopsis_xyloni, Myrmecocystus_mimicus, Myrmecocystus_testaceus, Myrmecocystus_flaviceps, ...

Rooted; includes branch lengths.
pruned[["tip.label"]]
 [1] "Crematogaster_navajoa_CSM" "Pheidole_hyatti"          
 [3] "Solenopsis_xyloni"         "Myrmecocystus_mimicus"    
 [5] "Myrmecocystus_testaceus"   "Myrmecocystus_flaviceps"  
 [7] "Myrmecocystus_kennedyi"    "Camponotus_semitestaceus" 
 [9] "Camponotus_ocreatus_CSM"   "Camponotus_fragilis"      
[11] "Dorymyrmex_bicolor"        "Dorymyrmex_insanus"       
[13] "Forelius_sp._CSM"          "Liometopum_luctuosum_CSM" 
pruned[["tip.label"]] <- c("CREMD", "PHEVIS", "SX", "MYRMIM", "MYRTES", "MYRFLA", "MYRKEN", "CAMPSEM", "CAMPOC", "CAMPFRA", "DORBI", "DORIN", "FM", "LIOLUC") 
plot(pruned)

labelorder <- c("CREMD", "PHEVIS", "SX", "MYRMIM", "MYRTES", "MYRFLA", "MYRKEN", "CAMPSEM", "CAMPOC", "CAMPFRA", "DORBI", "DORIN", "FM", "LIOLUC")
plot(pruned)

is.ultrametric(pruned)
[1] TRUE

Schoener’s D Calculations

library(ENMeval)
Loading required package: magrittr

Attaching package: 'magrittr'
The following object is masked from 'package:tidyr':

    extract
The following object is masked from 'package:raster':

    extract
This is ENMeval version 2.0.4. 
For worked examples, please consult the vignette: <https://jamiemkass.github.io/ENMeval/articles/ENMeval-2.0-vignette.html>.
all_present <- stack(clim, efnlist)
names(all_present)
 [1] "CAMPFRA.grd" "CAMPOC.grd"  "CAMPSEM.grd" "MYRMIM.grd"  "CREMD.grd"  
 [6] "DORBI.grd"   "DORIN.grd"   "MYRFLA.grd"  "MYRKEN.grd"  "MYRTES.grd" 
[11] "SX.grd"      "LIOLUC.grd"  "PHEVIS.grd"  "FM.grd"      "CA"         
[16] "CE"          "AG"          "FS"          "CL"          "OB"         
[21] "OBIG"        "FA"          "PJ"          "PFA"         "PFREM"      
over_present <- calc.niche.overlap(all_present, "D")

  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |==================                                                    |  25%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |============================================                          |  62%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |=============================================================         |  88%
  |                                                                            
  |================================================================      |  92%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |======================================================================| 100%
names(efn245) <- names(efnlist)
efn245 <- mask(efn245, moj)
plot(efn245)

names(ant245) <- names(clim)
ant245 <- mask(ant245, moj)
plot(ant245)

names(ant370) <- names(clim)
ant370 <- mask(ant370, moj)
plot(ant370)

all_245 <- stack(ant245, efn245)
over_245 <- calc.niche.overlap(all_245, "D")

  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |==================                                                    |  25%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |============================================                          |  62%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |=============================================================         |  88%
  |                                                                            
  |================================================================      |  92%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |======================================================================| 100%
all_370 <- stack(ant370, efn370)
over_370 <- calc.niche.overlap(all_370, "D")

  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |==================                                                    |  25%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |============================================                          |  62%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |=============================================================         |  88%
  |                                                                            
  |================================================================      |  92%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |======================================================================| 100%
mean(over_245, na.omit = TRUE)
[1] NA
over_present <- as.data.frame(over_present)
ap_present <- dplyr::select(over_present, 1:14)
ap_present <- ap_present[15:25,]

over_245 <- as.data.frame(over_245)
ap_245 <- dplyr::select(over_245, 1:14)
ap_245 <- ap_245[15:25,]

over_370 <- as.data.frame(over_370)
ap_370 <- dplyr::select(over_370, 1:14)
ap_370 <- ap_370[15:25,]


ap_present$plant <- row.names(ap_present)
ap_present <- pivot_longer(ap_present, 1:14, names_to = "ant", values_to = "overlap")

ap_245$plant <- row.names(ap_245)
ap_245 <- pivot_longer(ap_245, 1:14, names_to = "ant", values_to = "overlap")

ap_370$plant <- row.names(ap_370)
ap_370 <- pivot_longer(ap_370, 1:14, names_to = "ant", values_to = "overlap")

mean(ap_present$overlap)
[1] 0.571394
mean(ap_245$overlap)
[1] 0.5456761
mean(ap_370$overlap)
[1] 0.5415881
t.test(ap_present$overlap,ap_245$overlap, paired = TRUE)

    Paired t-test

data:  ap_present$overlap and ap_245$overlap
t = 6.2477, df = 153, p-value = 3.935e-09
alternative hypothesis: true mean difference is not equal to 0
95 percent confidence interval:
 0.01758567 0.03385025
sample estimates:
mean difference 
     0.02571796 
t.test(ap_present$overlap,ap_370$overlap, paired = TRUE)

    Paired t-test

data:  ap_present$overlap and ap_370$overlap
t = 6.7092, df = 153, p-value = 3.575e-10
alternative hypothesis: true mean difference is not equal to 0
95 percent confidence interval:
 0.02102931 0.03858260
sample estimates:
mean difference 
     0.02980595 
ap_present$scen <- "pres"
ap_370$scen <- "370"
ap <- cbind(ap_present, ap_370) 
colnames(ap) <- make.unique(names(ap))
ggplot(ap, aes(overlap, overlap.1)) + geom_point() + geom_abline(slope = 1) + xlim(0, 1) + ylim(0,1) + xlab("Present overlap") + ylab("Predicted overlap SSP 370")  + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"))

#370
rel <- mutate(ap, diff = (overlap.1 - overlap)/overlap)
rel <- select(rel, plant, ant, diff)

rel <- pivot_wider(rel, names_from = ant, values_from = diff)
row.names(rel) <- rel$plant
Warning: Setting row names on a tibble is deprecated.
rel$plant
 [1] "CA"    "CE"    "AG"    "FS"    "CL"    "OB"    "OBIG"  "FA"    "PJ"   
[10] "PFA"   "PFREM"
rel <- rel[,-1]
plantnames <- c("Cylindropuntia acanthocarpa", "Cylindropuntia echinocarpa", "Senegalia greggi", "Fouquieria splendens", "Chilopsis linearis", "Opuntia basilaris", "Cylindropuntia bigelovii", "Ferocactus cylindraceus", "Prosopis juliflora", "Prunus fascilata", "Prunus fremonti")
antnames <- c("Camponotus fragilis", "Camponotus ocreatus", "Camponotus semitestaceus", "Myrmecocystus mimicus", "Crematogaster depilis", "Dorymyrmex bicolor", "Dorymrymex insanus", "Myrmecocystus flaviceps", "Myrmecocystus kennedyi", "Myrmecocystus testaceus", "Solenopsis xyloni", "Liometopum luctuosum", "Pheidole vistana", "Forelius mccooki")
library(corrplot)
corrplot 0.92 loaded
rel <- as.matrix(rel)
row.names(rel) <- plantnames
colnames(rel) <- antnames


ap245 <- cbind(ap_present, ap_245)
colnames(ap245) <- make.unique(names(ap245))
rel245 <- mutate(ap245, diff = (overlap.1 - overlap)/overlap)
rel245 <- select(rel245, plant, ant, diff)
rel245 <- pivot_wider(rel245, names_from = ant, values_from = diff)
rel245 <- rel245[,-1]
rel245 <- as.matrix(rel245)
row.names(rel245) <- plantnames
colnames(rel245) <- antnames



corrplot(rel, method = "circle", is.corr = FALSE, tl.srt = 45, tl.col = 'black', col.lim = c(-0.35, 0.35))

corrplot(rel245, method = "circle", is.corr = FALSE, tl.srt = 45, tl.col = 'black', col.lim = c(-0.35, 0.35))

phydist <- cophenetic(pruned)
ant_overlap <- select(over_present, 1:14)
ant_overlap <- ant_overlap[1:14,]
names_overlap <- c("CAMPFRA", "CAMPOC", "CAMPSEM", "MYRMIM", "CREMD", "DORBI", "DORIN", "MYRFLA", "MYRKEN", "MYRTES", "SX", "LIOLUC", "PHEVIS", "FM")
colnames(ant_overlap) <- names_overlap  
row.names(ant_overlap) <- names_overlap             
phydist <- as.data.frame(phydist)
ant_overlap <- ant_overlap[names(phydist)]
ant_overlap <- 1 - ant_overlap 

ants <- ant_overlap[rownames(phydist), ]
mantel(phydist, ants, na.rm = TRUE)

Mantel statistic based on Pearson's product-moment correlation 

Call:
mantel(xdis = phydist, ydis = ants, na.rm = TRUE) 

Mantel statistic r: 0.1519 
      Significance: 0.132 

Upper quantiles of permutations (null model):
  90%   95% 97.5%   99% 
0.183 0.247 0.314 0.392 
Permutation: free
Number of permutations: 999
ant_over370 <- select(over_370, 1:14)
ant_over370 <- ant_over370[1:14,]
colnames(ant_over370) <- names_overlap  
row.names(ant_over370) <- names_overlap

ant_over370 <- ant_over370[names(phydist)]
ant_over370 <- 1 - ant_over370
ants <- ant_over370[rownames(phydist), ]
mantel(phydist, ants, na.rm = TRUE)

Mantel statistic based on Pearson's product-moment correlation 

Call:
mantel(xdis = phydist, ydis = ants, na.rm = TRUE) 

Mantel statistic r: 0.2072 
      Significance: 0.094 

Upper quantiles of permutations (null model):
  90%   95% 97.5%   99% 
0.197 0.272 0.340 0.412 
Permutation: free
Number of permutations: 999

Levin’s B Niche Breadth

library(ENMTools)
Warning: package 'ENMTools' was built under R version 4.3.3
Loading required package: dismo
climstack <- terra::rast(clim)





ants_breath <- data.frame(name = character(0), b1 = numeric(0), b2 = numeric(0))
for (i in 1:14){
  print(i)
  print(names(climstack[[i]]))
  plot(climstack[[i]])
  b <- raster.breadth(climstack[[i]])
  ants_breath[[i,1]] <- names(climstack[[i]])
  ants_breath[[i,2]] <- b$B1
  ants_breath[[i,3]] <- b$B2
}
[1] 1
[1] "CAMPFRA.grd"

[1] 2
[1] "CAMPOC.grd"

[1] 3
[1] "CAMPSEM.grd"

[1] 4
[1] "MYRMIM.grd"

[1] 5
[1] "CREMD.grd"

[1] 6
[1] "DORBI.grd"

[1] 7
[1] "DORIN.grd"

[1] 8
[1] "MYRFLA.grd"

[1] 9
[1] "MYRKEN.grd"

[1] 10
[1] "MYRTES.grd"

[1] 11
[1] "SX.grd"

[1] 12
[1] "LIOLUC.grd"

[1] 13
[1] "PHEVIS.grd"

[1] 14
[1] "FM.grd"

efn_breath <- data.frame(name = character(0), b1 = numeric(0), b2 = numeric(0))

climstack <- terra::rast(efnlist)
for (i in 1:11){
  print(i)
  print(names(climstack[[i]]))
  plot(climstack[[i]])
  b <- raster.breadth(climstack[[i]])
  efn_breath[[i,1]] <- names(climstack[[i]])
  efn_breath[[i,2]] <- b$B1
  efn_breath[[i,3]] <- b$B2
}
[1] 1
[1] "CA"

[1] 2
[1] "CE"

[1] 3
[1] "AG"

[1] 4
[1] "FS"

[1] 5
[1] "CL"

[1] 6
[1] "OB"

[1] 7
[1] "OBIG"

[1] 8
[1] "FA"

[1] 9
[1] "PJ"

[1] 10
[1] "PFA"

[1] 11
[1] "PFREM"

check <- filter(efn_breath, name != "PFREM")
t.test(ants_breath$b2, efn_breath$b2)

    Welch Two Sample t-test

data:  ants_breath$b2 and efn_breath$b2
t = 1.3749, df = 20.117, p-value = 0.1843
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -0.05731581  0.27922217
sample estimates:
mean of x mean of y 
0.6314036 0.5204504 
t.test(ants_breath$b2, check$b2)

    Welch Two Sample t-test

data:  ants_breath$b2 and check$b2
t = 0.92635, df = 21.817, p-value = 0.3644
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -0.07708354  0.20142695
sample estimates:
mean of x mean of y 
0.6314036 0.5692319 
sd(ants_breath$b2)
[1] 0.1855284
sd(efn_breath$b2)
[1] 0.2111581
sd(check$b2)
[1] 0.1430299

Breadth * suitability

ant_diff <- t(ant_diff)
ant_diff <- as.data.frame(ant_diff)
row.names(ant_diff) <- ant_diff$names
ant_diff[] <- lapply(ant_diff, as.numeric)
Warning in lapply(ant_diff, as.numeric): NAs introduced by coercion
cor.test(ant_diff$diff245, ants_breath$b2)

    Pearson's product-moment correlation

data:  ant_diff$diff245 and ants_breath$b2
t = 2.721, df = 12, p-value = 0.01857
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
 0.1296150 0.8648439
sample estimates:
      cor 
0.6177137 
cor.test(ant_diff$diff370, ants_breath$b2)

    Pearson's product-moment correlation

data:  ant_diff$diff370 and ants_breath$b2
t = 2.5821, df = 12, p-value = 0.024
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
 0.0981921 0.8565947
sample estimates:
      cor 
0.5976356 
ggplot(ant_diff, aes(diff370, ants_breath$b2)) + geom_smooth(method = "lm")
`geom_smooth()` using formula = 'y ~ x'

efn_diff <- t(efn_diff)
efn_diff <- as.data.frame(efn_diff)
row.names(efn_diff) <- efn_diff$names
efn_diff[] <- lapply(efn_diff, as.numeric)
Warning in lapply(efn_diff, as.numeric): NAs introduced by coercion
cor.test(efn_diff$diff245, efn_breath$b2)

    Pearson's product-moment correlation

data:  efn_diff$diff245 and efn_breath$b2
t = 0.35017, df = 9, p-value = 0.7343
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
 -0.5201118  0.6692651
sample estimates:
      cor 
0.1159353 
cor.test(efn_diff$diff370, efn_breath$b2)

    Pearson's product-moment correlation

data:  efn_diff$diff370 and efn_breath$b2
t = 0.28771, df = 9, p-value = 0.7801
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
 -0.5350500  0.6576774
sample estimates:
       cor 
0.09546607 
ggplot(efn_diff, aes(diff370, efn_breath$b2)) + geom_smooth(method = "lm")
`geom_smooth()` using formula = 'y ~ x'

efn_bre <- cbind(efn_diff, efn_breath$b2)
efn_bre$type <- "EFN"
efn_bre <- rename(efn_bre, breadth = 'efn_breath$b2')

ant_bre <- cbind(ant_diff, ants_breath$b2)
ant_bre$type <- "ANT"
ant_bre <- rename(ant_bre, breadth = 'ants_breath$b2')

all_bre <- rbind(efn_bre, ant_bre)

Breadth figure

a <- ggplot(efn_bre, aes(diff370, breadth)) + geom_smooth(method = "lm", linetype = "dashed", se = FALSE) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black")) + geom_point() + ylab("Environmental Breadth (Levin's B)") + xlab("Mean difference in suitability for EFN plants")

b <- ggplot(ant_bre, aes(diff370, breadth)) + geom_smooth(method = "lm") + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black")) + geom_point() + ylab("Environmental Breadth (Levin's B)") + xlab("Mean difference in suitability for ants")

library(cowplot)

plot_grid(a, b)
`geom_smooth()` using formula = 'y ~ x'
`geom_smooth()` using formula = 'y ~ x'

traitphy <- ants_breath
traitphy$species <- c("CAMPFRA", "CAMPOC", "CAMPSEM", "MYRMIM", "CREMD", "DORBI", "DORIN", "MYRFLA", "MYRKEN", "MYRTES", "SX", "LIOLUC", "PHEVIS", "FM")




labelorder <- pruned[["tip.label"]]
labelorder
 [1] "CREMD"   "PHEVIS"  "SX"      "MYRMIM"  "MYRTES"  "MYRFLA"  "MYRKEN" 
 [8] "CAMPSEM" "CAMPOC"  "CAMPFRA" "DORBI"   "DORIN"   "FM"      "LIOLUC" 
tp <- traitphy[match(labelorder, traitphy$species),]
row.names(tp) <- tp$species

traitphy <- select(tp, b2)
pruned[["tip.label"]]
 [1] "CREMD"   "PHEVIS"  "SX"      "MYRMIM"  "MYRTES"  "MYRFLA"  "MYRKEN" 
 [8] "CAMPSEM" "CAMPOC"  "CAMPFRA" "DORBI"   "DORIN"   "FM"      "LIOLUC" 
#par(mfrow=c(2,2))
for (i in names(traitphy)) {
plot(pruned, show.tip.label=FALSE, main=i)
tiplabels(pch=22, col=traitphy[,i]+1, bg=traitphy[,i]+1, cex=1.5)
}

pruned <- multi2di(pruned)
multiPhylosignal(traitphy, pruned, reps = 999)
           K PIC.variance.obs PIC.variance.rnd.mean PIC.variance.P
b2 0.5689796     0.0007183247          0.0008020777          0.327
   PIC.variance.Z
b2     -0.4492286
traitphy
               b2
CREMD   0.6409228
PHEVIS  0.4265022
SX      0.7543873
MYRMIM  0.6624083
MYRTES  0.2738310
MYRFLA  0.8487579
MYRKEN  0.7724676
CAMPSEM 0.5124577
CAMPOC  0.4865961
CAMPFRA 0.6353246
DORBI   0.7656886
DORIN   0.8184338
FM      0.8510931
LIOLUC  0.3907799
trait <- traitphy$b2
picante::phylosignal(trait, pruned)
Warning in match.phylo.data(phy, x): Data set lacks taxa names, these are
required to match phylogeny and data. Data are returned unsorted. Assuming that
data and phy$tip.label are in the same order!
          K PIC.variance.obs PIC.variance.rnd.mean PIC.variance.P
1 0.5689796     0.0007183247          0.0007928857          0.356
  PIC.variance.Z
1     -0.3966779
ps <- multiPhylosignal(traitphy, pruned)

ps
           K PIC.variance.obs PIC.variance.rnd.mean PIC.variance.P
b2 0.5689796     0.0007183247          0.0007984785          0.354
   PIC.variance.Z
b2     -0.4249376
library(adephylo)
Loading required package: ade4
library(phylosignal)
Warning: package 'phylosignal' was built under R version 4.3.2

Attaching package: 'phylosignal'
The following object is masked from 'package:lattice':

    dotplot
library(phylobase)

Attaching package: 'phylobase'
The following object is masked from 'package:phytools':

    readNexus
The following object is masked from 'package:ape':

    edges
p4d <- phylo4d(pruned, trait)
barplot.phylo4d(p4d, tree.type = "phylo", tree.ladderize = TRUE)

phyloSignal(p4d = p4d, method = "all")
$stat
         Cmean           I         K    K.star       Lambda
dt 0.002372566 -0.05393321 0.5689796 0.5822231 7.812707e-05

$pvalue
   Cmean     I     K K.star Lambda
dt  0.33 0.307 0.317  0.337      1
ant_diff <- as.data.frame(ant_diff)
ant_diff$species <- c("CAMPFRA", "CAMPOC", "CAMPSEM", "MYRMIM", "CREMD", "DORBI", "DORIN", "MYRFLA", "MYRKEN", "MYRTES", "SX", "LIOLUC", "PHEVIS", "FM")
row.names(ant_diff) <- c("CAMPFRA", "CAMPOC", "CAMPSEM", "MYRMIM", "CREMD", "DORBI", "DORIN", "MYRFLA", "MYRKEN", "MYRTES", "SX", "LIOLUC", "PHEVIS", "FM") 


traitphy <- ant_diff



traitphy <- traitphy[match(labelorder, traitphy$species),]
traitphy <- select(traitphy, diff370)





trait <- traitphy$diff370
picante::phylosignal(trait, pruned)
Warning in match.phylo.data(phy, x): Data set lacks taxa names, these are
required to match phylogeny and data. Data are returned unsorted. Assuming that
data and phy$tip.label are in the same order!
          K PIC.variance.obs PIC.variance.rnd.mean PIC.variance.P
1 0.5960402     7.329368e-05          8.469956e-05          0.288
  PIC.variance.Z
1     -0.5700467
traitphy <- ant_diff



traitphy <- traitphy[match(labelorder, traitphy$species),]
traitphy <- select(traitphy, diff245)
trait <- traitphy$diff245
picante::phylosignal(trait, pruned)
Warning in match.phylo.data(phy, x): Data set lacks taxa names, these are
required to match phylogeny and data. Data are returned unsorted. Assuming that
data and phy$tip.label are in the same order!
          K PIC.variance.obs PIC.variance.rnd.mean PIC.variance.P
1 0.6065459       6.0185e-05          7.080005e-05          0.256
  PIC.variance.Z
1     -0.6397591
viantlist <- list.files(path = "data/output/vi_ants/", pattern='.csv', all.files=TRUE, full.names=TRUE)

vi <- purrr::map_df(viantlist, 
              ~read.csv(.x, stringsAsFactors = FALSE) %>% mutate(filename = .x))
vi$filename <- gsub("data/output/vi_ants/", "", vi$filename)
vi <- separate(vi, filename, into = c("vi", "species", "end"), sep = "_")
Warning: Expected 3 pieces. Missing pieces filled with `NA` in 56 rows [1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...].
vi$end <- replace_na(vi$end,"clim")
vi <- filter(vi, end == "clim")

#remove the two excluded ant species (due to poor AUC performance)
vi <- filter(vi, species != "fp.csv" & species != "campsay.csv")

ggplot(vi, aes(Variable, Permutation_importance)) + geom_boxplot()

pltvilist <-  list.files(path = "data/output/vi/", pattern='.csv', all.files=TRUE, full.names=TRUE)
pltvi <- purrr::map_df(pltvilist, 
              ~read.csv(.x, stringsAsFactors = FALSE) %>% mutate(filename = .x))
pltvi$filename <-  gsub("data/output/vi/", "", pltvi$filename)
pltvi$filename <-  gsub(".csv", "", pltvi$filename)
pltvi$filename <-  gsub("vi_", "", pltvi$filename)

pltvi <- filter(pltvi, filename == "ag" |filename == "ca" | filename == "ce" | filename == "cl" | filename == "fa" | filename == "ob" | filename == "obig" | filename == "pfrem" | filename == "fa" | filename == "fs" | filename == "pj")


pltvi$type <- "EFN"
vi$type <- "ant"
pltvi <- select(pltvi, -sd)
vi <- select(vi, 1:3, 6, 8)
pltvi <- rename(pltvi, species = filename)
bothvi <- rbind(pltvi, vi)

ggplot(bothvi, aes(Variable, Permutation_importance, fill = type)) + geom_boxplot()

pc1 <- filter(bothvi, Variable == "PC1")
t.test(Permutation_importance ~ type, data = pc1)

    Welch Two Sample t-test

data:  Permutation_importance by type
t = 2.3156, df = 16.276, p-value = 0.03394
alternative hypothesis: true difference in means between group ant and group EFN is not equal to 0
95 percent confidence interval:
  1.637086 36.540057
sample estimates:
mean in group ant mean in group EFN 
         33.12857          14.04000 
pc2 <- filter(bothvi, Variable == "PC2")
t.test(Permutation_importance ~ type, data = pc2)

    Welch Two Sample t-test

data:  Permutation_importance by type
t = -2.6649, df = 14.193, p-value = 0.01831
alternative hypothesis: true difference in means between group ant and group EFN is not equal to 0
95 percent confidence interval:
 -36.794846  -4.002296
sample estimates:
mean in group ant mean in group EFN 
         23.17143          43.57000 
pc3 <- filter(bothvi, Variable == "PC3")
t.test(Permutation_importance ~ type, data = pc3)

    Welch Two Sample t-test

data:  Permutation_importance by type
t = -0.39714, df = 20.85, p-value = 0.6953
alternative hypothesis: true difference in means between group ant and group EFN is not equal to 0
95 percent confidence interval:
 -15.70397  10.66968
sample estimates:
mean in group ant mean in group EFN 
         20.84286          23.36000 
pc4 <- filter(bothvi, Variable == "PC4")
t.test(Permutation_importance ~ type, data = pc4)

    Welch Two Sample t-test

data:  Permutation_importance by type
t = 0.97102, df = 18.416, p-value = 0.3441
alternative hypothesis: true difference in means between group ant and group EFN is not equal to 0
95 percent confidence interval:
 -4.38028 11.93171
sample estimates:
mean in group ant mean in group EFN 
         22.83571          19.06000