# TITLE : Evaluating the potential of white pine tree-ring proxies for fine-scale dendroprovenancing

####### Libraries #######
library(dplR)
library(dplyr)
library(ggplot2)
library(stringr)
library(viridis)
library(paletteer)
library(gridExtra)
library(grid)
library(caret)
library(egg)
library(ggpubr)
library(cowplot)
library(shadowtext)



####### Data recollection #######

# Tree-ring width (TRW)
K03TRW.rwl <- read.rwl("K03_TRW.rwl")
K06TRW.rwl <- read.rwl("K06_TRW.rwl")
K08TRW.rwl <- read.rwl("K08_TRW.rwl")
K10TRW.rwl <- read.rwl("K10_TRW.rwl")
K12TRW.rwl <- read.rwl("K12_TRW.rwl")

# Latewood blue intensity (LWBI)
read.LWBI <- function(LWBI.filename) {
  LWBI.rwl <- read.rwl(LWBI.filename)
  core_names <- colnames(LWBI.rwl)
  new_names <- substr(core_names,1,nchar(core_names)-2)
  colnames(LWBI.rwl) <- new_names
  return(LWBI.rwl)
}

K03LWBI.rwl <- read.LWBI("K03_LWBI.rwl")
K06LWBI.rwl <- read.LWBI("K06_LWBI.rwl")
K08LWBI.rwl <- read.LWBI("K08_LWBI.rwl")
K10LWBI.rwl <- read.LWBI("K10_LWBI.rwl")
K12LWBI.rwl <- read.LWBI("K12_LWBI.rwl")

# Rings to remove in LWBI
bad.rings <- read.csv("LWBI_BadRings.csv")

# Drave logs
logs.rwl <- read.rwl("LogDrive_samples.csv")
colnames(logs.rwl) <- c("S3.01", "S3.02", "S3.03", "B.01", "B.02", "B.03", "H.01", "H.02", "H.03")

# Site name
sites <- c("K03", "K06", "K08", "K10", "K12") # K03=LAN, K06=BEL, K08=FOR, K10=JAR, K12=POM




####### Standardization, Chronology and descriptive statistics #######

### Standardization, chronology, and stats functions

# Tree-ring width function
chrono.TRW <- function(TRW.rwl){ #TRW.rwl=K03TRW.rwl
  # Core identity as dplR object
  core.ids <- read.ids(TRW.rwl, stc = c(3,2,1))
  site <- unique(substr(colnames(TRW.rwl),1,3))
  
  # Series average by trees
  rwl.trees <- treeMean(TRW.rwl, core.ids, na.rm = TRUE) ; colnames(rwl.trees) <- str_c(site,unique(core.ids$tree))
  
  # Standardization by spline and AR for a high-frequency signal
  rwi.spline <- detrend(rwl.trees, method="Spline", nyrs = 30)
  list.arima <- apply(rwi.spline, 2,function(x) arima(x, c(1,0,0)))
  list.residuals <- lapply(list.arima, function(z) {
    data.frame(residuals = z$residuals, row.names = rownames(rwi.spline))
  })
  rwi <- combine.rwl(list.residuals); colnames(rwi) <- colnames(rwi.spline)
  rwi.positif <- rwi+2 # Rbar, EPS and SSS doesn't like negative values; Used only for those analyses
  
  # Site chronology and SSS
  tree.ids <- read.ids(rwi, stc = c(3,2,0))
  crn.df <- chron(rwi)
  crn.df$sss <- sss(rwi.positif)
  crn.df$yr <- as.numeric(rownames(crn.df))

  # Chronology statistics
  stats <- rwi.stats(rwi.positif, tree.ids, round.decimals = NA)
  stats$n.cores <- nrow(core.ids)
  stats$fst.yr <- min(crn.df$yr)
  stats$lst.yr <- max(crn.df$yr)
  stats$yr.sss <- crn.df$yr[which(crn.df$sss >= 0.85)[1]]
  
  return(list(rwl = rwl.trees, rwi.nocutoff = rwi, crn = crn.df, ids = tree.ids, stats = stats))
}

# LWBI function 
# Includes LWBI correction
chrono.LWBI <- function(LWBI.rwl) {  #LWBI.rwl=K03LWBI.rwl
  # Core identity and primary keys
  LWBI.ids <- data.frame(site = substr(colnames(LWBI.rwl),1,3), 
                        tree = as.numeric(substr(colnames(LWBI.rwl),4,5)), 
                        core = as.numeric(substr(colnames(LWBI.rwl),6,6)), 
                        coreID = colnames(LWBI.rwl))
  site <- unique(LWBI.ids$site)
  
  # Core identity as dplR object
  core.ids <- read.ids(LWBI.rwl, stc = c(3,2,1))
  
  # Extracting colored rings associated with the current samples
  site.bad.rings <- inner_join(subset(bad.rings, select = Site:Cerne), LWBI.ids, 
                               by = join_by(Site == site, Arbre == tree, 
                                            Echantillon == core))
  
  # Assigning ring numbers to dating years
  last.year <- as.data.frame(as.numeric(rownames(LWBI.rwl)[sapply(LWBI.rwl, 
                                                                 function(x) max(which(!is.na(x))))]))
  colnames(last.year) <- "lastYear"
  last.year$coreID <- colnames(LWBI.rwl)
  
  site.bad.rings <- left_join(site.bad.rings, last.year, by = join_by(coreID))
  
  site.bad.rings$Year <- site.bad.rings$lastYear-site.bad.rings$Cerne
  site.bad.rings <- site.bad.rings[order(site.bad.rings$Site, 
                                         site.bad.rings$Arbre, 
                                         site.bad.rings$Echantillon, 
                                         site.bad.rings$Year),]
  
  # Removing LWBI bad_rings from rwl 
  for(i in 1: nrow(site.bad.rings)) {
    LWBI.rwl[as.character(site.bad.rings[i,"Year"]), site.bad.rings[i,"coreID"]] <- NA
    
  }
  # Averaging tree series 
  rwl.trees <- treeMean(LWBI.rwl, core.ids, na.rm = TRUE) ; colnames(rwl.trees) <- str_c(site,unique(core.ids$tree))
  tree.ids <- data.frame(site = substr(colnames(rwl.trees),1,3), 
                         tree = as.numeric(substr(colnames(rwl.trees),4,5)),
                         treeID = colnames(rwl.trees))
  site.bad.rings <- inner_join(site.bad.rings, tree.ids, 
                               by = join_by(Site == site, Arbre == tree))
  
  # Replacing LWBI bad_rings by mean of the neighbors when NAs are still present after averaging tree series
  rwl.trees.filled <- rwl.trees
  for(i in 1: nrow(site.bad.rings)) {
    if(is.na(rwl.trees[as.character(site.bad.rings[i,"Year"]), site.bad.rings[i,"treeID"]])) {
      rwl.trees.filled[as.character(site.bad.rings[i,"Year"]), site.bad.rings[i,"treeID"]] <-  
        mean(c(rwl.trees.filled[as.character(site.bad.rings[i,"Year"]-1), site.bad.rings[i,"treeID"]], 
               rwl.trees.filled[as.character(site.bad.rings[i,"Year"]+1), site.bad.rings[i,"treeID"]]), na.rm = TRUE) 
    }
  }
  
  # Standardization by spline and AR for a high-frequency signal
  rwi.spline <- detrend(rwl.trees.filled, method="Spline", nyrs = 30)
  list.arima <- apply(rwi.spline, 2,function(x) arima(x, c(1,0,0)))
  list.residuals <- lapply(list.arima, function(z) {
    data.frame(residuals = z$residuals, row.names = rownames(rwi.spline))
  })
  rwi <- combine.rwl(list.residuals); colnames(rwi) <- colnames(rwi.spline)
  
  # Adding back NAs for colored rings
  rwi[is.na(rwl.trees) == TRUE] <- NA
  
  rwi.positif <- rwi+2 # Rbar, EPS and SSS doesn't like negative values; Used only for those analyses
  
  # Site chronology and SSS
  tree.ids <- read.ids(rwi, stc = c(3,2,0))
  crn.df <- chron(rwi)
  crn.df$sss <- sss(rwi.positif)
  crn.df$yr <- as.numeric(rownames(crn.df))
  
  # Chronology statistics
  stats <- rwi.stats(rwi.positif, tree.ids, round.decimals = NA)
  stats$n.cores <- nrow(core.ids)
  stats$fst.yr <- min(crn.df$yr)
  stats$lst.yr <- max(crn.df$yr)
  stats$yr.sss <- crn.df$yr[which(crn.df$sss >= 0.85)[1]]
  
  return(list(rwl = rwl.trees, rwi.nocutoff = rwi, crn = crn.df, ids = tree.ids, stats = stats))
}

### Application of the standardization, chronology building and description ###

K03TRW <- chrono.TRW(TRW.rwl = K03TRW.rwl)
K06TRW <- chrono.TRW(K06TRW.rwl)
K08TRW <- chrono.TRW(K08TRW.rwl)
K10TRW <- chrono.TRW(K10TRW.rwl)
K12TRW <- chrono.TRW(K12TRW.rwl)

K03LWBI <- chrono.LWBI(LWBI.rwl = K03LWBI.rwl)
K06LWBI <- chrono.LWBI(K06LWBI.rwl)
K08LWBI <- chrono.LWBI(K08LWBI.rwl)
K10LWBI <- chrono.LWBI(K10LWBI.rwl)
K12LWBI <- chrono.LWBI(K12LWBI.rwl)

# Table 1 - descriptive statistics
list.crn <- list(K03TRW=K03TRW, K06TRW=K06TRW, K08TRW=K08TRW, K10TRW=K10TRW, K12TRW=K12TRW, K03LWBI=K03LWBI, K06LWBI=K06LWBI, K08LWBI=K08LWBI, K10LWBI=K10LWBI, K12LWBI=K12LWBI)

crn.stats.list <- lapply(list.crn, function(x){x$stats[,c("n.trees","n.cores","fst.yr","lst.yr","rbar.eff","eps","yr.sss")]})
table1 <- do.call(rbind,crn.stats.list)


# Cutting off all series by the most recent year with an SSS >= 0.85 across all chronologies
all.cutoffs <- sapply(list.crn, function(x){x$stats$yr.sss})
cutoff <- max(all.cutoffs)

K03TRW$rwi <- K03TRW$rwi.nocutoff[which(rownames(K03TRW$rwi.nocutoff) == cutoff):nrow(K03TRW$rwi.nocutoff),]
K06TRW$rwi <- K06TRW$rwi.nocutoff[which(rownames(K06TRW$rwi.nocutoff) == cutoff):nrow(K06TRW$rwi.nocutoff),]
K08TRW$rwi <- K08TRW$rwi.nocutoff[which(rownames(K08TRW$rwi.nocutoff) == cutoff):nrow(K08TRW$rwi.nocutoff),]
K10TRW$rwi <- K10TRW$rwi.nocutoff[which(rownames(K10TRW$rwi.nocutoff) == cutoff):nrow(K10TRW$rwi.nocutoff),]
K12TRW$rwi <- K12TRW$rwi.nocutoff[which(rownames(K12TRW$rwi.nocutoff) == cutoff):nrow(K12TRW$rwi.nocutoff),]
K03LWBI$rwi <- K03LWBI$rwi.nocutoff[which(rownames(K03LWBI$rwi.nocutoff) == cutoff):nrow(K03LWBI$rwi.nocutoff),]
K06LWBI$rwi <- K06LWBI$rwi.nocutoff[which(rownames(K06LWBI$rwi.nocutoff) == cutoff):nrow(K06LWBI$rwi.nocutoff),]
K08LWBI$rwi <- K08LWBI$rwi.nocutoff[which(rownames(K08LWBI$rwi.nocutoff) == cutoff):nrow(K08LWBI$rwi.nocutoff),]
K10LWBI$rwi <- K10LWBI$rwi.nocutoff[which(rownames(K10LWBI$rwi.nocutoff) == cutoff):nrow(K10LWBI$rwi.nocutoff),]
K12LWBI$rwi <- K12LWBI$rwi.nocutoff[which(rownames(K12LWBI$rwi.nocutoff) == cutoff):nrow(K12LWBI$rwi.nocutoff),]


### Chronologies figures ###

# Limits of the y-axis for RW and LWBI
allmins <- sapply(list.crn, function(x){min(x$rwi, na.rm = TRUE)})
allmaxs <- sapply(list.crn, function(x){max(x$rwi, na.rm = TRUE)})
ylims.TRW <- c(min(allmins[1:5]), max(allmaxs[1:5]))
ylims.LWBI <- c(min(allmins[6:10]), max(allmaxs[6:10]))

# Limits of the x-axis
min.yrs <- sapply(list.crn, function(x){min(x$crn$yr)})
max.yrs <- sapply(list.crn, function(x){max(x$crn$yr)})
xlims <- c(min(min.yrs), max(max.yrs))
  
# Plot function
chron.plot <- function(crn.list, colnb, ylim = NA, xlim = NA, cutoff) { #crn.list=K03TRW; colnb=1; xlim=xlims; ylim=ylims.TRW; cutoff=cutoff
  rwi <- crn.list$rwi.nocutoff
  crn.df <- crn.list$crn
  
  if(any(is.na(ylim))) {
    ylim <- c(min(rwi, na.rm = TRUE), max(rwi, na.rm = TRUE))
  }
  
  if(any(is.na(xlim))) {
    x1 <- min(crn.df$yr)
    x2 <- max(crn.df$yr)
  } else {
    x1 <- xlim[1]
    x2 <- xlim[2]
  }
  
  mycolor <- paletteer_d("lisa::GeneDavis")
  
  # Creation of the base plot and the cutoff area
  crn.plot <- ggplot(crn.df,aes(x=yr)) +
    annotate(geom = "rect", xmin = -Inf, xmax = cutoff, ymin = -Inf, ymax = Inf, fill = mycolor[colnb], alpha = 0.15) +
    scale_y_continuous(limits = ylim, labels = function(x) format(x, nsmall = 1)) +
    theme_bw(base_rect_size = 0.75) +
    xlim(x1,x2) +
    xlab("") + ylab("")+
    theme(panel.grid = element_blank(), 
          axis.text = element_text(colour = "black"),
          panel.border = element_rect(fill=NA, colour = "black", linewidth=1),
          panel.background = element_rect(fill = "transparent",colour = NA_character_), 
          plot.background = element_rect(fill = "transparent", colour = NA_character_),
          text = element_text(size = 17),
          plot.margin = unit(c(0, 0.4, 0, 0.4), "cm"))
  
  # Adding series to the plot
  nseries <- ncol(rwi)
  for (col in colnames(rwi)) {
    crn.plot <- crn.plot + geom_line(data = rwi, aes(y = .data[[col]], x = crn.df$yr), col = mycolor[colnb], alpha = 0.1)
  }
  
  # Adding the site chronology
  crn.plot <- crn.plot + 
    geom_line(aes(y=std), linewidth = 0.7, col = mycolor[colnb])
  return(crn.plot)
}

# Plotting each site chronology for all proxies
K03TRW.plot <- chron.plot(K03TRW, colnb = 1, xlim = xlims, ylim = ylims.TRW, cutoff = cutoff) +
  annotate("text",  x= 1777, y = Inf, label = "Laniel (LAN)", vjust = 1.5, hjust= 0, size = 7) +
  labs(title = "Tree-ring width", y = "TRW") +
  theme(axis.title.x = element_blank(),
        plot.title = element_text(hjust = 0.5),
        axis.text.x = element_blank()) +
  coord_cartesian(ylim = c(-1,1))

K06TRW.plot <- chron.plot(K06TRW, colnb = 2, xlim = xlims, ylim = ylims.TRW, cutoff = cutoff) +
  annotate("text",  x= 1777, y = Inf, label = "Belleterre (BEL)", vjust = 1.5, hjust = 0, size = 7) +
  labs(y = "TRW") +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_blank()) +
  coord_cartesian(ylim = c(-1,1))

K08TRW.plot <- chron.plot(K08TRW, colnb = 3, xlim = xlims, ylim = ylims.TRW, cutoff = cutoff) +
  annotate("text",  x= 1777, y = Inf, label = "Lac aux Foins (FOI)", vjust = 1.5, hjust = 0, size = 7) +
  labs(y = "TRW") +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_blank()) +
  coord_cartesian(ylim = c(-1,1))

K10TRW.plot <- chron.plot(K10TRW, colnb = 4, xlim = xlims, ylim = ylims.TRW, cutoff = cutoff) +
  annotate("text",  x= 1777, y = Inf, label = "Lac des Jardins (JAR)", vjust = 1.5, hjust = 0, size = 7) +
  labs(y = "TRW") +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_blank()) +
  coord_cartesian(ylim = c(-1,1))

K12TRW.plot <- chron.plot(K12TRW, colnb = 5, xlim = xlims, ylim = ylims.TRW, cutoff = cutoff) +
  annotate("text",  x= 1777, y = Inf, label = "Lac Pommeroy (POM)", vjust = 1.5, hjust = 0, size = 7) +
  labs(x="Year", y = "TRW") +
  coord_cartesian(ylim = c(-1,1))

K03LWBI.plot <- chron.plot(K03LWBI, colnb = 1, xlim = xlims, ylim = ylims.LWBI, cutoff = cutoff) +
  labs(title = "Latewood blue intensity", y = "LWBI") +
  theme(plot.title = element_text(hjust = 0.5),
        axis.title.x = element_blank(),
        axis.text.x = element_blank()) +
  coord_cartesian(ylim = c(-0.25,0.25))

K06LWBI.plot <- chron.plot(K06LWBI, colnb = 2, xlim = xlims, ylim = ylims.LWBI, cutoff = cutoff) +
  labs(y = "LWBI") +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_blank()) +
  coord_cartesian(ylim = c(-0.25,0.25))

K08LWBI.plot <- chron.plot(K08LWBI, colnb = 3, xlim = xlims, ylim = ylims.LWBI, cutoff = cutoff) +
  labs(y = "LWBI") +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_blank()) +
  coord_cartesian(ylim = c(-0.25,0.25))

K10LWBI.plot <- chron.plot(K10LWBI, colnb = 4, xlim = xlims, ylim = ylims.LWBI, cutoff = cutoff) +
  labs(y = "LWBI") +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_blank()) +
  coord_cartesian(ylim = c(-0.25,0.25))

K12LWBI.plot <- chron.plot(K12LWBI, colnb = 5, xlim = xlims, ylim = ylims.LWBI, cutoff = cutoff) +
  labs(x="Year", y = "LWBI") +
  coord_cartesian(ylim = c(-0.25,0.25))


# Combining all plots into one figure (Figure 3)
plot_grid(K03TRW.plot,K03LWBI.plot,NULL,NULL,K06TRW.plot, K06LWBI.plot,NULL,NULL,K08TRW.plot, 
          K08LWBI.plot,NULL,NULL,K10TRW.plot, K10LWBI.plot,NULL,NULL,K12TRW.plot, K12LWBI.plot, 
          ncol = 2, align="hv", rel_heights = c(1, -0.25, 1, -0.25, 1, -0.25, 1, -0.25, 1)) +
  theme(plot.background = element_rect(fill = "white", colour = NA_character_))
# The warnings are for the NAs in shorter series and chronologies

# ggsave("Figure3.svg", width = 26, height = 32, units = "cm")



####### Leave-one-out cross validation analysis ########
# LOOCV

# Combining all series in one data frame for the next analyses
allTRW <- combine.rwl(list(K03TRW$rwi, K06TRW$rwi, K08TRW$rwi, K10TRW$rwi, K12TRW$rwi))
allLWBI <- combine.rwl(list(K03LWBI$rwi, K06LWBI$rwi, K08LWBI$rwi, K10LWBI$rwi, K12LWBI$rwi))

# Tree ID's and primary keys
allIDs <- data.frame(IDtree = colnames(allTRW), 
                     site = str_sub(colnames(allTRW), 1,3), 
                     tree = as.numeric(str_sub(colnames(allTRW), 4,5)))

### LOOCV functions ###

# Confusion matrix plot
cm.plot.fun <- function(cm) { 
  # Grouping the confusion matrix results for ggplot use
  plt <- as.data.frame(cm$table)
  plt$Prediction <- factor(plt$Prediction, levels=rev(levels(plt$Prediction)))
  plt <- plt %>% 
    group_by(Reference) %>% mutate(Percent = Freq/sum(Freq)*100) #Frequency was compute for the color gradient
  
  # Plotting confusion matrix results
  cm.plot <- ggplot(plt, aes(Reference,Prediction, fill= Percent)) +
    geom_tile(width = 1, color = "black") + 
    geom_shadowtext(aes(label=Freq), size = 6, color = "black", fontface = "bold", bg.colour = "white", bg.r = .1) +
    scale_fill_gradient(low="white", high="#293757", limits = c(0,100)) +
    labs(x = "Original site",y = "Reassign site", fill = "Percent") +
    scale_x_discrete(expand=c(0,0), labels=c("LAN","BEL","FOI","JAR","POM")) +
    scale_y_discrete(expand=c(0,0), labels=c("POM","JAR","FOI","BEL","LAN")) +
    theme_bw(base_rect_size = 0.75) +
    theme(axis.text = element_text(colour = "black"),
          axis.ticks = element_blank(),
          axis.title.y = element_blank(),
          axis.title.x = element_text(margin = margin(t = 7, r = 0, b = 0, l = 0)),
          panel.grid = element_blank(),
          text = element_text(size = 17),
          legend.title = element_text(margin = margin(0, 13, 16, 0, "pt")))
  
  return(cm.plot)
}

# LOOCV function fo single proxies
jackknife <- function (all.rwi, all.ids, sites, cm = FALSE) { #all.rwi=allLWBI; all.ids=allIDs; sites=sites; cm=TRUE
  # Scaling all series for euclidean distance
  all.rwi <- scale(all.rwi)
  
  # Empty dataframe for leave-one-out assignment results
  res <- data.frame(matrix(ncol=length(sites), nrow = nrow(all.ids), dimnames = list(all.ids$IDtree, sites)))
  
  # leave-one-out
  for(i in 1: ncol(all.rwi)) {
    sample <- all.rwi[,i, drop = FALSE]
    rest <- all.rwi[,-i]
    rest.ids <- all.ids[-i,]
    
    # Recalculation of the site chronologies whitout the expelled sample
    crn <- as.data.frame(sapply(sites, function(x) { rowMeans(rest[, subset(rest.ids, site %in% x, IDtree, drop = TRUE)], na.rm = TRUE)}))
    
    # Euclidean distance between the sample and the site chronologies
    diff.sq <- (crn-as.vector(sample))^2
    res[i,] <- apply(diff.sq, 2, function(x) sum(x, na.rm = TRUE) * length(x)/sum(!is.na(x)))
  }
  
  # Assigned site and reference site
  res$best.value <- apply(res[,sites], 1, min)
  res$best.site <- colnames(res)[apply(res[,sites], 1, which.min)]
  res$true.site <- all.ids$site
  
  if(cm == TRUE) {
    # Confusion matrix
    cm <- confusionMatrix(factor(res$best.site), factor(res$true.site), dnn = c("Prediction", "Reference"), mode="everything")
    
    # Plot
    cm.plot <- cm.plot.fun(cm)
    
    return(list(res = res, plot = cm.plot, cm.stats = cm))
  } else {
    return(res)
  }
}

# Function merging RW and LWBI
jackknife.merge <- function(res.trw, res.LWBI, cm = FALSE) { #res.trw=cm.TRW$res; res.LWBI=cm.LWBI$res; cm=TRUE
  # adding a weight by the proxies success rates
  weight1 <- sum(res.trw$best.site == res.trw$true.site)/nrow(res.trw)
  weight2 <- sum(res.LWBI$best.site == res.LWBI$true.site)/nrow(res.LWBI)
  
  # Average Euclidean distance of TRW and LWBI for each excluded sample
  res <- (weight1*res.trw[,1:length(sites)] + weight2*res.LWBI[,1:length(sites)])/(weight1+weight2)
  
  # Assigned site and reference site
  res$best.value <- apply(res[,sites], 1, min)
  res$best.site <- colnames(res)[apply(res[,sites], 1, which.min)]
  res$true.site <- str_sub(rownames(res), 1,3)
  
  if(cm == TRUE) {
    # Confusion matrix
    cm <- confusionMatrix(factor(res$best.site), factor(res$true.site), dnn = c("Prediction", "Reference"), mode="everything")
    
    # Plot
    cm.plot <- cm.plot.fun(cm)
    
    return(list(res = res, plot = cm.plot, cm.stats = cm))
  } else {
    return(res)
  }
}


### Leave-one-out cross-validation results ###

# TRW only
cm.TRW <- jackknife(allTRW, allIDs, sites, cm = TRUE)
cm.TRW$plot <- cm.TRW$plot + 
  labs(subtitle = "TRW") +
  theme(plot.margin = unit(c(0.2,0.8,0.2,0), 'lines'),
        axis.text.y = element_text(angle = 90, hjust = 0.5, vjust=1),
        axis.title.x = element_blank())

# LWBI only
cm.LWBI <- jackknife(allLWBI, allIDs, sites, cm = TRUE)
cm.LWBI$plot <- cm.LWBI$plot + 
  labs(x = "Original site", y = "Reassign site", fill = "Percent", subtitle = "LWBI") +
  theme(axis.title.y = element_blank(),
        axis.text.y = element_blank(),
        plot.margin = unit(c(0.2,0.8,0.2,0), 'lines'))

# Combination of TRW and LWBI
cm.TRWLWBI <- jackknife.merge(cm.TRW$res, cm.LWBI$res, cm = TRUE)
cm.TRWLWBI$plot <- cm.TRWLWBI$plot +
  labs(x = "Original site", y = "Reassign site", fill = "Percent", subtitle = "TRW and LWBI") +
  theme(axis.title.y = element_blank(),
        axis.text.y = element_blank(),
        axis.title.x = element_blank(),
        plot.margin = unit(c(0.2,0.8,0.2,0), 'lines'))

# Combining all plots into one figure (Figure 4)
figure4 <- ggarrange(cm.TRW$plot, cm.LWBI$plot, cm.TRWLWBI$plot, common.legend = TRUE, legend = "bottom", align="hv", nrow = 1) +
  theme(plot.margin = unit(c(0,0,0,0.7), 'lines'))
annotate_figure(figure4, left = textGrob("Reassign Site", rot = 90, vjust = 0.7, hjust = 0.23, gp = gpar(fontsize = 17))) +
  theme(plot.background = element_rect(fill = "white", colour = NA_character_),
        plot.margin = unit(c(0,0,0,-0.3), 'lines'))

# ggsave("Figure4.svg", width = 32, height = 13.7, units = "cm")


# Table2 by class
cm.TRW.stats <- cm.TRW[["cm.stats"]][["byClass"]][,c("Precision","Recall","F1")]; colnames(cm.TRW.stats) <- paste("TRW_",colnames(cm.TRW.stats), sep="")
cm.LWBI.stats <- cm.LWBI[["cm.stats"]][["byClass"]][,c("Precision","Recall","F1")]; colnames(cm.LWBI.stats) <- paste("LWBI_",colnames(cm.LWBI.stats), sep="")
cm.TRWLWBI.stats <- cm.TRWLWBI[["cm.stats"]][["byClass"]][,c("Precision","Recall","F1")]; colnames(cm.TRWLWBI.stats) <- paste("TRWLWBI_",colnames(cm.TRWLWBI.stats), sep="")

table2.byclass <- cbind(cm.TRW.stats, cm.LWBI.stats, cm.TRWLWBI.stats)
table2.byclass

# Table2 overall
cm.TRW.ovall <- cm.TRW[["cm.stats"]][["overall"]][c("Accuracy", "Kappa", "AccuracyLower", "AccuracyUpper")]
cm.LWBI.ovall <- cm.LWBI[["cm.stats"]][["overall"]][c("Accuracy", "Kappa", "AccuracyLower", "AccuracyUpper")]
cm.TRWLWBI.ovall <- cm.TRWLWBI[["cm.stats"]][["overall"]][c("Accuracy", "Kappa", "AccuracyLower", "AccuracyUpper")]

table2.ovall <- rbind(cm.TRW.ovall, cm.LWBI.ovall, cm.TRWLWBI.ovall); rownames(table2.ovall) <- c("TRW","LWBI","TRWLWBI")
table2.ovall



####### Leave-one-out analyses with overlap and periods effects #######

### LOOCVA overlap + period functions ###

# LOOCVA overlap + period analyses for all approaches
jackknife.op <- function(all.trw, all.LWBI, all.ids, sites) { #all.trw=allTRW; all.LWBI=allLWBI; all.ids=allIDs; sites=sites
  # Variations of overlap length by 10 years increments
  ovlap.length <- seq(30, 110, by = 10)
  
  # Empty dataframe ready for success rates results
  success.res.trw <- data.frame(matrix(ncol=4,nrow=0)) ; colnames(success.res.trw) <- c("Year.min", "Year.max", "ovlap.length", "SuccessRate")
  success.res.LWBI <- data.frame(matrix(ncol=4,nrow=0)) ; colnames(success.res.LWBI) <- c("Year.min", "Year.max", "ovlap.length", "SuccessRate")
  success.res.trwLWBI <- data.frame(matrix(ncol=4,nrow=0)) ; colnames(success.res.trwLWBI) <- c("Year.min", "Year.max", "ovlap.length", "SuccessRate")
  
  # first and last year of the complete time window available
  rwi.yr.min <- as.numeric(rownames(all.trw)[1])
  rwi.yr.max <- as.numeric(rownames(all.trw)[nrow(all.trw)])
  
  # Looping LOOCVA with each overlap lengths and time periods
  for(o in 1:length(ovlap.length)) { #o for overlap
    # Getting all the time windows that could be tested for that overlap
    yr.min <- rwi.yr.min+ovlap.length[o]
    yr.increment <- seq(from = rwi.yr.max, to = yr.min, by = -5)
    
    for (p in 1:length(yr.increment)) { #p for period
      # Truncating the series by the specific time window and overlap
      max.yr <- yr.increment[p]
      min.yr <- yr.increment[p] - ovlap.length[o] + 1
      cut.trw <- subset(all.trw, rownames(all.trw) %in% min.yr:max.yr)
      cut.LWBI <- subset(all.LWBI, rownames(all.LWBI) %in% min.yr:max.yr)
      
      #Removing all series that hold less then 10 measures in that specific overlap
      cut.trw <- cut.trw[, colSums(!is.na(cut.trw)) >= 10]
      cut.LWBI <- cut.LWBI[, colSums(!is.na(cut.LWBI)) >= 10]
      if(any(colnames(cut.trw) != colnames(cut.LWBI))){
        common.samples <- intersect(colnames(cut.trw), colnames(cut.LWBI))
        cut.trw <- cut.trw[,common.samples]
        cut.LWBI <- cut.LWBI[,common.samples]
      }
      cut.ids <- all.ids[all.ids$IDtree %in% colnames(cut.trw),]
      
      # LOOCVA
      res.trw <- jackknife(all.rwi = cut.trw, all.ids = cut.ids, sites = sites)
      res.LWBI <- jackknife(all.rwi = cut.LWBI, all.ids = cut.ids, sites = sites)
      res.trwLWBI <- jackknife.merge(res.trw = res.trw, res.LWBI = res.LWBI)
      
      # TRW LOOCV success rate
      nb.true <- sum(res.trw$best.site == res.trw$true.site)
      nb.tree <- nrow(res.trw)
      success.res.trw[nrow(success.res.trw)+1,] <- c(min.yr, max.yr, ovlap.length[o], nb.true/nb.tree)
      
      # LWBI LOOCV success rate
      nb.true <- sum(res.LWBI$best.site == res.LWBI$true.site)
      nb.tree <- nrow(res.LWBI)
      success.res.LWBI[nrow(success.res.LWBI)+1,] <- c(min.yr, max.yr, ovlap.length[o], nb.true/nb.tree)
      
      # TRW and LWBI combined LOOCV success rate
      nb.true <- sum(res.trwLWBI$best.site == res.trwLWBI$true.site)
      nb.tree <- nrow(res.trwLWBI)
      success.res.trwLWBI[nrow(success.res.trwLWBI)+1,] <- c(min.yr, max.yr, ovlap.length[o], nb.true/nb.tree)
    }
  }
  
  return(list(success.res.trw = success.res.trw, success.res.LWBI = success.res.LWBI, success.res.trwLWBI = success.res.trwLWBI))
}

# Plot function
plot.op <- function(rwi.successrate){ #rwi.successrate=TRW.successrate
  rwi.successrate$ovlap.length <- as.factor(rwi.successrate$ovlap.length)
  op.plot <- ggplot(rwi.successrate, aes(y = SuccessRate)) +
    geom_errorbar(aes(xmax = Year.max, xmin = Year.min, colour = ovlap.length), alpha = 0.3, linewidth = 1, show.legend=FALSE) +
    geom_point(aes(x = Year.max, fill = ovlap.length), colour = "black", pch=21, size = 2.5) +
    scale_color_viridis(discrete = TRUE, option = "D", direction = -1, guide=guide_legend(nrow=1)) +
    scale_fill_viridis(discrete = TRUE, option = "D", direction = -1, guide=guide_legend(nrow=1)) +
    labs(x = "Year", y = "Success rate", fill = "Overlap length") +
    ylim(0,1) +
    theme_bw(base_rect_size = 0.75) +
    theme(axis.text = element_text(colour = "black"),
          panel.grid = element_blank(),
          text = element_text(size = 17),
          plot.margin = unit(c(0.2,0.8,0.2,0), 'lines')) +
    guides(fill = guide_legend(nrow = 1))
  
  return(op.plot)
}


### LOOCVA overlap + period results ###

LOOCV.op <- jackknife.op(allTRW, allLWBI, allIDs, sites)

# TRW
TRW.successrate <- LOOCV.op$success.res.trw
TRW.op.plot <- plot.op(TRW.successrate) +
  labs(subtitle = "TRW") +
  theme(axis.text.y = element_text(angle = 90, vjust = 1, hjust = 0.5),
        axis.title.y = element_blank(),
        axis.title.x = element_blank())

# LWBI
LWBI.successrate <- LOOCV.op$success.res.LWBI
LWBI.op.plot <- plot.op(LWBI.successrate) +
  labs(subtitle = "LWBI") +
  theme(axis.text.y = element_blank(),
        axis.title.y = element_blank(),
        axis.title.x = element_text(margin = margin(t = 7, r = 0, b = 0, l = 0)))

# TRW and LWBI combined
TRWLWBI.successrate <- LOOCV.op$success.res.trwLWBI
TRWLWBI.op.plot <- plot.op(TRWLWBI.successrate) +
  labs(subtitle = "TRW and LWBI") +
  theme(axis.text.y = element_blank(),
        axis.title.y = element_blank(),
        axis.title.x = element_blank())

# Combining all plots into one figure (Figure 5)
figure5 <- ggarrange(TRW.op.plot, LWBI.op.plot, TRWLWBI.op.plot, common.legend = TRUE, legend = "bottom", align="hv", nrow = 1) +
  theme(plot.margin = unit(c(0,0,0,0.7), 'lines'),
        legend.direction = "horizontal",
        legend.key.height = unit(1, "null")) + 
  guides(fill = guide_legend(nrow = 1), colour = guide_legend(nrow = 1))
annotate_figure(figure5, left = textGrob("Success rate", rot = 90, vjust = 0.7, hjust = 0.30, gp = gpar(fontsize = 17))) +
  theme(plot.background = element_rect(fill = "white", colour = NA_character_),
        plot.margin = unit(c(0,0,0,-0.3), 'lines'))

# ggsave("Figure5.svg", width = 32, height = 12.5, units = "cm")



####### Leave-one-out cross-validation with number of trees effect #######

### LOOCV bootstrap functions ###

# LOOCV with sampled chronologies
jackknife.sampled <- function(all.rwi, all.ids, samples.ids, sites){
  # Scaling all series for euclidean distance
  all.rwi <- scale(all.rwi)
  
  # Empty dataframe for leave-one-out assignment results
  res <- data.frame(matrix(ncol=length(sites), nrow = nrow(all.ids), dimnames = list(all.ids$IDtree, sites)))
  
  # leave-one-out
  for(i in 1: nrow(all.ids)){
    sample <- all.rwi[,i, drop = FALSE] #the drop=FALSE keeps it as a matrix
    # Removing all the duplicate of the removed tree in the bootstrap selection
    rest.ids <- samples.ids[samples.ids$IDtree != colnames(sample),]
    
    # Making sure that there is at least 5 trees in each chronology after removing the sample's duplicates
    nb.trees.crn <- table(rest.ids$site)
    if(any(nb.trees.crn < 5)){
      res[i,] <- NA
    } else {
      # Creating the chronologies with the selected trees
      rest <- all.rwi[,rest.ids$IDtree]; colnames(rest) <- make.unique(colnames(rest))
      rest.ids$newIDtree <- colnames(rest)
      
      crn <- as.data.frame(sapply(sites, function(x) { rowMeans(rest[, subset(rest.ids, site %in% x, newIDtree, drop = TRUE)], na.rm = TRUE)}))
      
      # Euclidean distance between the sample and the site chronologies
      diff.sq <- (crn-as.vector(sample))^2
      res[i,] <- apply(diff.sq, 2, function(x) sum(x, na.rm = TRUE) * length(x)/sum(!is.na(x)))
    }
  }
  
  # Removing the Na's caused by lack of trees in the site chronologies
  res <- res[rowSums(is.na(res)) != ncol(res),]
  
  # Assigned site and reference site
  res$best.value <- apply(res[,sites], 1, min)
  res$best.site <- colnames(res)[apply(res[,sites], 1, which.min)]
  res$true.site <- all.ids$site[all.ids$IDtree %in% rownames(res)]
  
  return(res)
}

# Bootstrapping the LOOCV
jackknife.boot <- function(all.trw, all.LWBI, all.ids, sites, overlap, period, nboot) { #all.trw=allTRW; all.LWBI=allLWBI; all.ids=allIDs; sites=sites; overlap=NA; period=NA; nboot=10
  # Truncating the series by the time window and overlap specified if specified
  if(is.na(period)) {
    max.yr <- as.numeric(rownames(all.trw)[nrow(all.trw)])
  } else {
    max.yr <- period
  }
  
  if(is.na(overlap)) {
    min.yr <- as.numeric(rownames(all.trw)[1])
  } else {
    min.yr <- max.yr - overlap + 1
  }
  
  cut.trw <- subset(all.trw, rownames(all.trw) %in% min.yr:max.yr)
  cut.LWBI <- subset(all.LWBI, rownames(all.LWBI) %in% min.yr:max.yr)
  
  #Removing all series that hold less then 10 measures in that specific overlap
  cut.trw <- cut.trw[, colSums(!is.na(cut.trw)) >= 10]
  cut.LWBI <- cut.LWBI[, colSums(!is.na(cut.LWBI)) >= 10]
  if(any(colnames(cut.trw) != colnames(cut.LWBI))){
    common.samples <- intersect(colnames(cut.trw), colnames(cut.LWBI))
    cut.trw <- cut.trw[,common.samples]
    cut.LWBI <- cut.LWBI[,common.samples]
  }
  cut.ids <- all.ids[all.ids$IDtree %in% colnames(cut.trw),]
  
  # bootstrap LOOCV
  success.boot <- function(s){ #s=cut.ids %>% group_by(site) %>% slice_sample(n = 27, replace = TRUE)
    res.trw <- jackknife.sampled(cut.trw, cut.ids, s, sites) #all.rwi=cut.trw; all.ids=cut.ids; samples.ids=s; sites=sites
    res.LWBI <- jackknife.sampled(cut.LWBI, cut.ids, s, sites)
    res.trwLWBI <- jackknife.merge(res.trw, res.LWBI)
    
    rate.trw <- sum(res.trw$best.site == res.trw$true.site)/nrow(res.trw)
    rate.LWBI <- sum(res.LWBI$best.site == res.LWBI$true.site)/nrow(res.LWBI)
    rate.trwLWBI <- sum(res.trwLWBI$best.site == res.trwLWBI$true.site)/nrow(res.trwLWBI)
    
    c(nb, rate.trw, rate.LWBI, rate.trwLWBI)
  }
  
  # Empty dataframe for the results
  success.res.tot <- data.frame(matrix(ncol=4,nrow=0)) ; colnames(success.res.tot) <- c("n.arbres", "SuccessRate_TRW", "SuccessRate_LWBI", "SuccessRate_TRW_LWBI")
  
  # Max trees available
  nb.trees <- table(cut.ids$site)
  
  # Bootstrap nb trees in each site for each number of trees
  for(nb in 6: max(nb.trees)){
    success.res <- replicate(n=nboot, success.boot(s=cut.ids %>% group_by(site) %>% slice_sample(n = nb, replace = TRUE)))
    success.res <- as.data.frame(t(success.res))
    success.res.tot[nrow(success.res.tot)+1:nrow(success.res),] <- success.res
  }
  
  return(success.res.tot)
}

# Plot function
plot.robust <- function(rwi.robust){ #rwi.robust=TRW.robust
  robust.plot <- ggplot(rwi.robust, aes(x = n.arbres, y = SuccessRate)) +
    geom_point() +
    labs(x = "Number of trees", y = "Success rate") +
    ylim(0,1)  +
    theme_bw(base_rect_size = 0.75) +
    theme(axis.text = element_text(colour = "black"),
          panel.grid = element_blank(),
          text = element_text(size = 17),
          plot.margin = unit(c(0.2,0.8,0.2,0), 'lines'))
  return(robust.plot)
}


### LOOCV bootstrap results ###

robustness <- jackknife.boot(allTRW, allLWBI, allIDs, sites, overlap = NA, period = NA, nboot = 100)

# TRW only
TRW.robust <- robustness[,c("n.arbres", "SuccessRate_TRW")]; colnames(TRW.robust) <- c("n.arbres", "SuccessRate")
TRW.plot.robust <- plot.robust(TRW.robust) +
  labs(subtitle = "TRW") +
  theme(axis.text.y = element_text(angle = 90, vjust = 1, hjust = 0.5),
        axis.title.y = element_blank(),
        axis.title.x = element_blank())

# LWBI only
LWBI.robust <- robustness[,c("n.arbres", "SuccessRate_LWBI")]; colnames(LWBI.robust) <- c("n.arbres", "SuccessRate")
LWBI.plot.robust <- plot.robust(LWBI.robust) +
  labs(subtitle = "LWBI") +
  theme(axis.text.y = element_blank(),
        axis.title.y = element_blank(),
        axis.title.x = element_text(margin = margin(t = 7, r = 0, b = 0, l = 0)))

# TRW and LWBI combined
TRWLWBI.robust <- robustness[,c("n.arbres", "SuccessRate_TRW_LWBI")]; colnames(TRWLWBI.robust) <- c("n.arbres", "SuccessRate")
TRWLWBI.plot.robust <- plot.robust(TRWLWBI.robust) +
  labs(subtitle = "TRW and LWBI") +
  theme(axis.text.y = element_blank(),
        axis.title.y = element_blank(),
        axis.title.x = element_blank())

# Combining all plots into one figure (Figure 6)
figure6 <- ggarrange(TRW.plot.robust, LWBI.plot.robust, TRWLWBI.plot.robust, align="hv", nrow = 1) +
  theme(plot.margin = unit(c(0,0,0,0.7), 'lines'))
annotate_figure(figure6, left = textGrob("Success rate", rot = 90, vjust = 0.7, hjust = 0.30, gp = gpar(fontsize = 17))) +
  theme(plot.background = element_rect(fill = "white", colour = NA_character_),
        plot.margin = unit(c(0,0,0,-0.3), 'lines'))

# ggsave("Figure6.svg", width = 32, height = 12.5, units = "cm")



####### Drive logs assignation #######

### Assignation functions ###

# Standardization funcion
log.detrend <- function(rwl) { #rwl=logs.rwl
  # Standardization by spline and AR for a high-frequency signal
  rwi.noAR <- detrend(rwl, method="Spline", nyrs = 30)
  list.arima <- apply(rwi.noAR, 2,function(x) arima(x, c(1,0,0)))
  list.residuals <- lapply(list.arima, function(z) 
  {data.frame(residuals = z$residuals, row.names = rownames(rwi.noAR))
  })
  rwi <- combine.rwl(list.residuals); colnames(rwi) <- colnames(rwi.noAR)
  
  spag.plot(rwi)
  
  return(rwi)
}

# Assignation function
assign <- function(samples, all.rwi, all.ids, sites){ #samples=H; all.rwi=allTRW; all.ids=allIDs; sites=sites
  # Scaling all series for euclidean distance
  all.rwi <- scale(all.rwi)
  samples <- scale(samples)
  
  # Site chronologies
  crn <- as.data.frame(sapply(sites, function(x) { rowMeans(all.rwi[, subset(all.ids, site %in% x, IDtree, drop = TRUE)], na.rm = TRUE)}))
  
  # Common overlap between the samples and the chronologies
  crn.yrs <- rownames(crn)[complete.cases(crn)]
  samples.yrs <- rownames(samples)[complete.cases(samples)]
  overlap <- intersect(samples.yrs, crn.yrs)
  cut.crn <- crn[rownames(crn) %in% overlap,]
  cut.samples <- samples[rownames(samples) %in% overlap,]
  cut.rwi <- all.rwi[rownames(all.rwi) %in% overlap,]
  
  # Assignation by Euclidean distance
  dist <- as.data.frame(t(apply(cut.samples, 2, function(s) apply((cut.crn-as.vector(s))^2, 2, function(x) sum(x, na.rm = TRUE) * length(x)/sum(!is.na(x))))))
  dist$best.value <- apply(dist[,sites],1,min)
  dist$best.site <- colnames(dist)[apply(dist[,sites], 1, which.min)]
  
  # Reassignation accuracy of the provenance dataset with the common overlap and euclidean distance intervals
  # LOOCV
  jackknife.res <- jackknife(all.rwi = cut.rwi, all.ids = all.ids, sites = sites)
  
  # Reassignation accuracy
  nb.true <- sum(jackknife.res$best.site == jackknife.res$true.site)
  nb.tree <- nrow(jackknife.res)
  
  # Intervals
  res.dist <- jackknife.res[,!colnames(jackknife.res) %in% c("best.value", "best.site", "true.site")]
  conf <- data.frame(min = min(res.dist), max = max(res.dist), SR = nb.true/nb.tree)
  
  return(list(dist = dist, conf = conf)) 
}

# Plot function
assign.plot <- function(logs.res, log.sample) { #logs.res=logs.results; log.sample="B.01"
  # Limits
  best.site <- which.min(logs.res[,log.sample])
  best.dist <- min(logs.res[,log.sample])
  worst.dist <- max(logs.res[,log.sample])
  
  # Color palette
  mycolor <- paletteer_d("lisa::GeneDavis")
  
  # Plot
  plot.log <- ggplot(logs.res, aes(x = Sites, y = .data[[log.sample]], color = Sites)) +
    geom_point(show.legend = FALSE, size = 3) +
    scale_color_paletteer_d("lisa::GeneDavis") +
    annotate("rect", xmin = -0.5 + best.site, xmax = 0.5 + best.site, ymin = best.dist - best.dist * 0.05, ymax = worst.dist + worst.dist * 0.05,
             alpha = 0, color = mycolor[best.site], linewidth = 0.8) +
    theme_bw(base_rect_size = 0.75) +
    theme(axis.text = element_text(colour = "black"),
          axis.title.x = element_text(margin = margin(t = 7, r = 0, b = 0, l = 0)),
          panel.grid = element_blank(),
          text = element_text(size = 17),
          plot.margin = unit(c(0,0.8,0,0), 'lines'))
  plot.log
  
  return(plot.log)
}


### Assignation results ###

# Standardization
logs.TRW <- log.detrend(logs.rwl)
spag.plot(logs.TRW)

# Separation by stamp
S3 <- logs.TRW[,c("S3.01", "S3.02", "S3.03")]
B <- logs.TRW[,c("B.01", "B.02", "B.03")]
H <- logs.TRW[,c("H.01", "H.02", "H.03")]

# Drive logs assignation
H.res <- assign(H, allTRW, allIDs, sites)
B.res <- assign(B, allTRW, allIDs, sites)
S3.res <- assign(S3, allTRW, allIDs, sites)

# Compiling results in one dataframe
logs.results <- as.data.frame(cbind(t(H.res$dist[,!colnames(H.res$dist) %in% c("best.value", "best.site")]), 
                                    t(B.res$dist[,!colnames(B.res$dist) %in% c("best.value", "best.site")]), 
                                    t(S3.res$dist[,!colnames(S3.res$dist) %in% c("best.value", "best.site")])))
logs.results$Sites <- as.character(c("LAN", "BEL", "FOI", "JAR", "POM"))
logs.results$Sites <- factor(logs.results$Sites, levels=unique(logs.results$Sites))

# Provenance dataset reassignment and confidence intervals
logs.conf <- rbind(H.res$conf, B.res$conf, S3.res$conf); row.names(logs.conf) <- c("H", "B", "S3")

# Plotting assignation results of each log
B.01 <- assign.plot(logs.results, "B.01") +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.title.y = element_blank())
B.02 <- assign.plot(logs.results, "B.02") +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.title.y = element_blank())
B.03 <- assign.plot(logs.results, "B.03") + 
  theme(axis.title.x = element_blank(),
        axis.title.y = element_blank())

H.01 <- assign.plot(logs.results, "H.01") +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.title.y = element_blank())
H.02 <- assign.plot(logs.results, "H.02") +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.title.y = element_blank())
H.03 <- assign.plot(logs.results, "H.03") +
  theme(axis.title.x = element_blank(),
        axis.title.y = element_blank())

S3.01 <- assign.plot(logs.results, "S3.01") +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.title.y = element_blank())
S3.02 <- assign.plot(logs.results, "S3.02") +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.title.y = element_blank())
S3.03 <- assign.plot(logs.results, "S3.03") +
  theme(axis.title.x = element_blank(),
        axis.title.y = element_blank())

# Combining all plots into one figure (Figure 7)
figure7 <- ggarrange(B.01, H.01, S3.01, B.02, H.02, S3.02, B.03, H.03, S3.03, nrow = 3, ncol = 3, align = "hv") +
  theme(plot.margin = unit(c(0.1,0,0.7,0.7), 'lines'))
figure7 <- annotate_figure(figure7, left = textGrob("Euclidean distance", rot = 90, vjust = 0.7, hjust = 0.30, gp = gpar(fontsize = 17)),
                               bottom = textGrob("Potential site", vjust = 0, hjust = 0.4, gp = gpar(fontsize = 17)),
                               top = textGrob("H - 1949", vjust = 0.7, hjust = 0.4, gp = gpar(fontsize = 17))) +
  theme(plot.background = element_rect(fill = "white", colour = NA_character_),
        plot.margin = unit(c(0,0,-0.3,-0.3), 'lines'))

figure7 <- annotate_figure(figure7, top = textGrob("B - 1941", vjust = 2.25, hjust = 3.3, gp = gpar(fontsize = 17)))
annotate_figure(figure7, top = textGrob("S3 - 1959", vjust = 3.75, hjust = -2.33, gp = gpar(fontsize = 17))) +
  theme(plot.background = element_rect(fill = "white", colour = NA_character_),
        plot.margin = unit(c(-2.9,0,0,0), 'lines'))

# ggsave("Figure7.svg", width = 21, height = 10.5, units = "cm")


####### Additionnal statistics #######

### Confidence intervals for Rbar
library(boot)

more.stats <- function(crn.list) {
  set.seed(412)
  ids <- crn.list$ids; ids$IDtree <- rownames(crn.list$ids)
  rwi.positif <- crn.list$rwi.nocutoff + 2
  rbar.boot.fun <- function(x,i) {
    samples.ids <- x[i,]
    
    rwi.samples <- rwi.positif[,samples.ids$IDtree]; colnames(rwi.samples) <- make.unique(colnames(rwi.samples))
    
    stats.b <- rwi.stats(rwi.samples, round.decimals = NA)
    stats.b$rbar.bt
  }
  
  boot.rbar <- boot(ids, rbar.boot.fun, R=1000)
  

  crn.list$rbar.ci <- boot.ci(boot.rbar) #Not enough samples for Bca intervals, using Basic intervals instead
  crn.list$stats$rbar.bt.lci <- crn.list$rbar.ci$basic[4]
  crn.list$stats$rbar.bt.uci <- crn.list$rbar.ci$basic[5]
  return(crn.list)
}

K03TRW <- more.stats(crn.list = K03TRW)
K06TRW <- more.stats(K06TRW)
K08TRW <- more.stats(K08TRW)
K10TRW <- more.stats(K10TRW)
K12TRW <- more.stats(K12TRW)

K03LWBI <- more.stats(crn.list = K03LWBI)
K06LWBI <- more.stats(K06LWBI)
K08LWBI <- more.stats(K08LWBI)
K10LWBI <- more.stats(K10LWBI)
K12LWBI <- more.stats(K12LWBI)


### Confidence intervals for precision and recall
library(binom)
cm.ci.fun <- function(cm.list){
  ci.res <- data.frame(matrix(ncol=7, nrow = length(sites), dimnames = list(sites, c("TP","Nobs","Npred","prec_lw","prec_up","rec_lw","rec_up"))))
  for(i in 1:length(sites)){
    ci.res[i,1] <- cm.list[["cm.stats"]][["table"]][i,i]
    ci.res[i,2] <- sum(cm.list[["cm.stats"]][["table"]][,i])
    ci.res[i,3] <- sum(cm.list[["cm.stats"]][["table"]][i,])
    ci.res[i,c(4,5)] <- binom.confint(ci.res[i,1], ci.res[i,3], methods = "bayes")[c(5,6)]
    ci.res[i,c(6,7)] <- binom.confint(ci.res[i,1], ci.res[i,2], methods = "bayes")[c(5,6)]
  }
  return(ci.res)
}

cm.ci.TRW <- cm.ci.fun(cm.TRW); colnames(cm.ci.TRW) <- paste("TRW_",colnames(cm.ci.TRW), sep="")
cm.ci.LWBI <- cm.ci.fun(cm.LWBI); colnames(cm.ci.LWBI) <- paste("LWBI_",colnames(cm.ci.LWBI), sep="")
cm.ci.TRWLWBI <- cm.ci.fun(cm.TRWLWBI); colnames(cm.ci.TRWLWBI) <- paste("TRWLWBI_",colnames(cm.ci.LWBI), sep="")

table2.byclass.ci <- cbind(cm.ci.TRW, cm.ci.LWBI, cm.ci.TRWLWBI)
table2.byclass.ci

### Confidence intervals for overall accuracy
accuracy.ci.fun <- function(cm.list){
  ci.res <- data.frame(matrix(ncol=4, nrow = 1, dimnames = list("",c("TP","Ntot","acc_lw","acc_up"))))
  ci.res[1,1] <- 0
  for(i in 1:length(sites)){
    ci.res[1,1] <- ci.res[1,1] + cm.list[["cm.stats"]][["table"]][i,i]
  }
  ci.res[1,2] <- sum(cm.list[["cm.stats"]][["table"]])
  ci.res[1,c(3,4)] <- binom.confint(ci.res[1,1], ci.res[1,2], methods = "bayes")[c(5,6)]
  return(ci.res)
}

cm.TRW.ovall.ci <- accuracy.ci.fun(cm.TRW)
cm.LWBI.ovall.ci <- accuracy.ci.fun(cm.LWBI)
cm.TRWLWBI.ovall.ci <- accuracy.ci.fun(cm.TRWLWBI)

table2.ovall.ci <- rbind(cm.TRW.ovall.ci, cm.LWBI.ovall.ci, cm.TRWLWBI.ovall.ci); rownames(table2.ovall.ci) <- c("TRW","LWBI","TRWLWBI")
table2.ovall.ci


### Pairwise cross-correlations table among the site chronologies

crn.TRW <- as.data.frame(sapply(sites, function(x) { rowMeans(allTRW[, subset(allIDs, site %in% x, IDtree, drop = TRUE)], na.rm = TRUE)}))
cor.TRW <- cor(crn, use = "pairwise.complete.obs")
cor.TRW

crn.LWBI <- as.data.frame(sapply(sites, function(x) { rowMeans(allLWBI[, subset(allIDs, site %in% x, IDtree, drop = TRUE)], na.rm = TRUE)}))
cor.LWBI <- cor(crn, use = "pairwise.complete.obs")
cor.LWBI

