Packages

packages <- c("phyloseq","stringr","dplyr","tidyr","ggplot2","patchwork","ggpubr",
  "forcats","vegan","ade4","adespatial","ComplexHeatmap","circlize",
  "tibble","readr","partykit","metagMisc","tseries","rio","lme4",
  "sjPlot","ggridges","FactoMineR","ggside","factoextra","corrplot",
  "microbiome","rdacca.hp","UpSetVP")

invisible(lapply(packages, library, character.only = TRUE))

data.frame(
  Package = packages,
  Version = sapply(packages, function(x) as.character(packageVersion(x)))
)
##                       Package    Version
## phyloseq             phyloseq     1.52.0
## stringr               stringr      1.6.0
## dplyr                   dplyr      1.1.4
## tidyr                   tidyr      1.3.1
## ggplot2               ggplot2      4.0.1
## patchwork           patchwork      1.3.2
## ggpubr                 ggpubr      0.6.2
## forcats               forcats      1.0.1
## vegan                   vegan      2.7.2
## ade4                     ade4     1.7.23
## adespatial         adespatial     0.3.28
## ComplexHeatmap ComplexHeatmap     2.24.1
## circlize             circlize     0.4.17
## tibble                 tibble      3.3.0
## readr                   readr      2.1.5
## partykit             partykit     1.2.25
## metagMisc           metagMisc 0.6.0.9000
## tseries               tseries    0.10.59
## rio                       rio      1.2.4
## lme4                     lme4     1.1.38
## sjPlot                 sjPlot      2.9.0
## ggridges             ggridges      0.5.7
## FactoMineR         FactoMineR       2.13
## ggside                 ggside      0.4.1
## factoextra         factoextra      1.0.7
## corrplot             corrplot       0.95
## microbiome         microbiome     1.30.0
## rdacca.hp           rdacca.hp      1.1.1
## UpSetVP               UpSetVP      1.0.0

Import data

env_df <- read.csv("rawdata/data_env.csv", header = TRUE, dec = ",", sep = ";", stringsAsFactors = FALSE)
foram_df <- read.csv("rawdata/Foram_table.csv", header = TRUE, sep = ";", stringsAsFactors = FALSE)
ps_alpha <- readRDS("metaB_clean/ps_alpha.rds")
ps_rarefied <- readRDS("metaB_clean/ps_rarefied.rds")
ps_rs_rarefied <- readRDS("metaB_clean/ps_rs_rarefied.rds")
rs_db_df <- read.csv("rawdata/database_RestSt.csv", header = TRUE, sep = ";", stringsAsFactors = FALSE)

#Al and Ni as representative metals of ultramafic and vulcanosedimentary sources As highlighted by PMF 5.0 model (see method ans supplementary information)

metaux <- c("Li","Al","V","Cr","Mn","Fe","Co","Ni","Cu","Zn","As","Mo","Ag","Cd","Sn","Sb","Ba","Pb","U","Hg")

env_metaux <- env_df %>%
  select(all_of(metaux))

env_metaux_nonzero <- env_metaux %>%
  filter(rowSums(., na.rm = TRUE) > 0)

mcor_metaux <- cor(env_metaux_nonzero,
                   method = "spearman",
                   use = "complete.obs")

cor_mtest <- function(mat, method = "spearman") {
  mat <- as.matrix(mat)
  n <- ncol(mat)
  p.mat <- matrix(NA, n, n)
  diag(p.mat) <- 0
  
  for (i in 1:(n - 1)) {
    for (j in (i + 1):n) {
      test <- cor.test(mat[, i], mat[, j], method = method)
      p.mat[i, j] <- p.mat[j, i] <- test$p.value
    }
  }
  
  colnames(p.mat) <- rownames(p.mat) <- colnames(mat)
  return(p.mat)
}

p_mat_metaux <- cor_mtest(env_metaux_nonzero,
                          method = "spearman")

col_palette <- colorRampPalette(c("#BB4444", "#EE9988", "#FFFFFF",
                                  "#77AADD", "#4477AA"))

corrplot(mcor_metaux,
         method = "color",
         col = col_palette(200),
         type = "upper",
         order = "hclust",
         addCoef.col = "black",
         tl.col = "black",
         tl.srt = 45,
         p.mat = p_mat_metaux,
         sig.level = 0.05,
         insig = "blank",
         diag = FALSE,
         number.cex = 0.50)

#PCA
Col_unit <- c("#782208","#DC7242","#FBCE64","#94BB67","#3D785F")

df_metaux_pca <- env_df %>%
  select(Unite, all_of(metaux)) %>%
  na.omit()

res_pca_all <- PCA(df_metaux_pca[, metaux], scale.unit = TRUE, graph = FALSE)

# Extraire les scores des individus
scores_all <- as.data.frame(res_pca_all$ind$coord)
scores_all$Unite <- df_metaux_pca$Unite
perc_var_comp1 <- res_pca_all$eig[1,2]
perc_var_comp2 <- res_pca_all$eig[2,2]

# Plot avec ggplot, avec ellipses pour chaque unité
pca_all_plot <- ggplot(scores_all, aes(x = Dim.1, y = Dim.2, color = Unite, fill = Unite)) +
  geom_point(size = 3) +
  #stat_ellipse(alpha = 0.2, geom = "polygon") +
  geom_ysidedensity(aes(y=Dim.2, yfill = Unite), alpha = 0.4) +
  geom_xsidedensity(aes(x=Dim.1, xfill = Unite), alpha = 0.4) +
  labs(x = paste("PC1 -",round(perc_var_comp1,1),"%"), 
       y = paste("PC2 -",round(perc_var_comp2,1),"%"), 
       color = "Unit", fill = "Unit") +
   theme_classic() + 
  theme(ggside.panel.scale = .2) +
  theme_ggside_void() +
  scale_color_manual(values =  Col_unit)+
  scale_fill_manual(values =  Col_unit)+
  scale_xfill_manual(values = Col_unit)+
  scale_yfill_manual(values = Col_unit)

#Keeping only An and Ni
df_al_ni <- env_df %>%
  select(Unite, Al, Ni) %>%
  na.omit()

res_pca_alni <- PCA(df_al_ni[, c("Al","Ni")], scale.unit = TRUE, graph = FALSE)

scores_al_ni <- as.data.frame(res_pca_alni$ind$coord)
scores_al_ni$Unite <- df_al_ni$Unite
perc_var_alni_comp1 <- res_pca_alni$eig[1,2]
perc_var_alni_comp2 <- res_pca_alni$eig[2,2]

pca_alni_plot <- ggplot(scores_al_ni, aes(x = -Dim.1, y = Dim.2, color = Unite, fill = Unite)) +
  geom_point(size = 3) +
  #stat_ellipse(alpha = 0.2, geom = "polygon") +
  geom_ysidedensity(aes(y=Dim.2, yfill = Unite,), alpha = 0.4) +
  geom_xsidedensity(aes(x=-Dim.1, xfill = Unite), alpha = 0.4) +
  labs(x = paste("PC1 -",round(perc_var_alni_comp1,1),"%"), 
       y = paste("PC2 -",round(perc_var_alni_comp2,1),"%"), 
       color = "Unit", fill = "Unit") +
   theme_classic() + 
  theme(ggside.panel.scale = .2) +
  theme_ggside_void() +
  scale_color_manual(values =  Col_unit)+
  scale_fill_manual(values =  Col_unit)+
  scale_xfill_manual(values = Col_unit)+
  scale_yfill_manual(values = Col_unit)

combined_plot <- pca_all_plot + pca_alni_plot + 
  plot_layout(guides = "collect") & theme(legend.position = "bottom")

combined_plot

ggsave("Outputs/Figure_suppl_double_PCA_metals.pdf", plot = combined_plot,
       width = 200, height = 100, units = "mm", dpi = 400)

Identification of sedimentary units based on these two metals

# Select relevant environmental variables 
env_subset <- env_df %>%
  select(Codification, Depth, Ni, Al)

#  Filter out rows with no sediment or metal data
env_subset <- env_subset %>%
  mutate(env_sum = rowSums(across(Ni:Al), na.rm = TRUE)) %>%
  filter(env_sum > 0) %>%
  select(-env_sum)

env_subset <- env_subset %>%
  mutate(Depth_neg = -Depth)  

#  Conditional Inference Tree (ctree)
# Model depth partitioning based on Ni and Al concentration
env_ctree <- ctree(
  Depth_neg ~ Ni + Al,
  data = env_subset,
  control = ctree_control(mincriterion = 0.995)  # strict split criterion
)

# Print tree summary
print(env_ctree)
## 
## Model formula:
## Depth_neg ~ Ni + Al
## 
## Fitted party:
## [1] root
## |   [2] Al <= 31846
## |   |   [3] Ni <= 5676: -24.765 (n = 17, err = 10819.1)
## |   |   [4] Ni > 5676: -73.538 (n = 13, err = 4241.2)
## |   [5] Al > 31846
## |   |   [6] Ni <= 2243
## |   |   |   [7] Ni <= 1920: -168.800 (n = 15, err = 5094.4)
## |   |   |   [8] Ni > 1920: -210.286 (n = 7, err = 859.4)
## |   |   [9] Ni > 2243: -116.444 (n = 9, err = 1742.2)
## 
## Number of inner nodes:    4
## Number of terminal nodes: 5
#  Plot the tree 
tree_plot <- plot(env_ctree, gp = gpar(fontsize = 10))

# Inspect samples matching a specific node rule
# (e.g. Unit IV)
env_subset_IV <- env_subset %>%
  filter(Al > 31846) %>%
  filter(Ni <= 1920)

print(env_subset_IV)
##    Codification Depth   Ni    Al Depth_neg
## 1          B-72   140 1845 38088      -140
## 2          B-76   144 1777 38186      -144
## 3          B-80   148 1690 33186      -148
## 4          B-84   152 1721 34174      -152
## 5          C-02   156 1767 33713      -156
## 6          C-06   160 1877 34565      -160
## 7          C-10   164 1920 35453      -164
## 8          C-14   168 1827 36436      -168
## 9          C-18   172 1851 42010      -172
## 10         C-22   176 1855 40606      -176
## 11         C-26   180 1896 42933      -180
## 12         C-30   184 1843 33613      -184
## 13         C-38   192 1840 37920      -192
## 14         C-42   196 1750 38262      -196
## 15         C-46   200 1868 36654      -200

Environmental changes along core

Sharp changes in chemical and physical parameters

# Prepare long format for selected variables
env_vars <- c("Clay","Sand","Ni","Al")
env_long <- env_df %>%
  select(Codification, Depth, all_of(env_vars)) %>%
  pivot_longer(cols = all_of(env_vars), names_to = "Variable", values_to = "Value") %>%
  mutate(Category = case_when(
    Variable %in% c("Clay", "Sand") ~ "Grain size",
    Variable == "Ni" ~ "Nickel",
    Variable == "Al" ~ "Aluminium",
    TRUE ~ "Other"
  )) %>%
  filter(!is.na(Value) & Value > 0) %>%
  mutate(Depth_neg = -Depth)

env_long$Category <- factor(env_long$Category, levels = c("Nickel","Aluminium","Grain size"))
env_long$Variable <- factor(env_long$Variable, levels = c("Ni","Al","Clay","Sand"))
color_variable <- c("#FF794D","#59BDC0","#BB593E","#D9AB37")

fig1_env_profile <- ggplot(env_long, aes(x = Depth_neg, y = Value, color = Variable, fill = Variable)) +
  geom_vline(xintercept = c(-46, -94, -138, -202), linetype = "dashed", color = "grey") + #sedimentary units
  facet_grid(~Category, scales = "free", space = "free_y") +
  geom_line(aes(group = Variable), linewidth = 0.8, alpha = 0.6) +
  geom_point(size = 1) +
  scale_fill_manual(values = color_variable) + scale_color_manual(values = color_variable) +
  labs(x = "Depth (cm)", y = "Value") + coord_flip() +
  theme_pubr(base_size = 9)

# Source composition (UB, VS)
source_long <- env_df %>% select(Codification, Depth, UB, VS) %>%
  pivot_longer(cols = c("UB","VS"), names_to = "Source", values_to = "Value") %>%
  mutate(Depth_neg = -Depth) %>%
  filter(!is.na(Value) & Value > 0)
color_source <- c("#E75A1E","#2AADB6")

fig1_source <- ggplot(source_long, aes(x = Depth_neg, y = Value, fill = Source)) +
  geom_vline(xintercept = c(-46, -94, -138, -202), linetype = "dashed", color = "grey") +
  geom_area(alpha = 0.6, color = "white") +
  scale_fill_manual(values = color_source) +
  labs(y = "Value") + coord_flip() + theme_pubr(base_size = 9) +
  theme(axis.title.y = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank())

fig1_combined <- fig1_env_profile + fig1_source + plot_layout(widths = c(3,1))
fig1_combined

ggsave("Outputs/Figure1_environment_profiles.pdf", plot = fig1_combined,
       width = 180, height = 140, units = "mm", dpi = 600)

Diversity patterns corrected by sedimentation rates

# Foraminifera
foram_df <- foram_df %>%
  mutate(
    Sed_rate = case_when(
      Unit == "I"   ~ 0.9,
      Unit == "II"  ~ 1.0,
      Unit == "III" ~ 0.2,
      Unit == "IV"  ~ 0.2,
      Unit == "V"   ~ 0.1,
      TRUE ~ NA_real_
    )
  )

# log-transform
foram_df2 <- foram_df %>%
  filter(!is.na(Sum_genus), !is.na(Sed_rate)) %>%
  mutate(
    log_div = log(Sum_genus + 1),
    log_sed = log(Sed_rate)
  )

# Modele : diversity ~ sedimentation rate
mod_foram <- lm(log_div ~ log_sed, data = foram_df2)
summary(mod_foram)
## 
## Call:
## lm(formula = log_div ~ log_sed, data = foram_df2)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1.46771 -0.16888  0.04241  0.32858  1.09724 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  1.41957    0.07739  18.343  < 2e-16 ***
## log_sed     -0.45683    0.05970  -7.652 4.78e-12 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.5781 on 124 degrees of freedom
## Multiple R-squared:  0.3208, Adjusted R-squared:  0.3153 
## F-statistic: 58.56 on 1 and 124 DF,  p-value: 4.778e-12
# Corrected diversity = residual
foram_df2$div_corr <- resid(mod_foram)

summary_foram_df2 <- foram_df2 %>%
  group_by(Unit) %>%
  summarise(mean_div_corr = mean(div_corr, na.rm = TRUE),
            sd_div_corr = sd(div_corr, na.rm = TRUE),
            min_date = min(date_median, na.rm = TRUE),
            max_date = max(date_median, na.rm = TRUE)) %>%
  mutate(med_date = (min_date + max_date)/2) %>% ungroup()

summary_foram_df2
## # A tibble: 5 × 6
##   Unit  mean_div_corr sd_div_corr min_date max_date med_date
##   <chr>         <dbl>       <dbl>    <int>    <int>    <dbl>
## 1 I           -0.227        0.866     1976     2022    1999 
## 2 II           0.233        0.675     1960     1975    1968.
## 3 III         -0.0505       0.233     1757     1960    1858.
## 4 IV           0.166        0.133     1301     1738    1520.
## 5 V           -0.208        0.137     1163     1279    1221
# Visualisation
sed_rate_foram <- ggplot(foram_df2, aes(y = div_corr, x = date_median)) +
  geom_vline(xintercept = c(1976, 1960, 1757, 1301), linetype = "dashed", color = "grey") +
  geom_ribbon(aes(ymin = 0, ymax = div_corr), alpha = 0.25) +
  geom_point(data = summary_foram_df2, aes(x = med_date, y = mean_div_corr), inherit.aes = FALSE, size = 2) +
  geom_line(data = summary_foram_df2, aes(x = med_date, y = mean_div_corr), inherit.aes = FALSE, size = 0.8) +
  geom_linerange(data = summary_foram_df2, aes(x = med_date, ymin = mean_div_corr - sd_div_corr, ymax = mean_div_corr + sd_div_corr), inherit.aes = FALSE) +
  labs(x = "Median date", y = "Corrected diversity") + xlim(1140,2030) +
  theme_pubr(base_size = 12) + coord_flip()

# Microeukaryote
alpha_richness_df <- estimate_richness(ps_alpha, measures = c("Observed"))
alpha_richness_df$SampleID <- rownames(alpha_richness_df)
# Merge with sample metadata (ensure columns exist)
meta_alpha <- as.data.frame(sample_data(ps_alpha))
meta_alpha$SampleID <- rownames(meta_alpha)
meta_alpha <- as.matrix(meta_alpha)
meta_alpha <- as.data.frame(meta_alpha)
alpha_meta_df <- left_join(alpha_richness_df, meta_alpha, by = "SampleID")
# Ensure numeric columns
alpha_meta_df$Date_mean <- as.numeric(alpha_meta_df$Date_mean)
alpha_meta_df$Depth_reel <- as.numeric(alpha_meta_df$Depth_reel)
alpha_meta_df$alpha_observed <- as.numeric(alpha_meta_df$Observed)

alpha_meta_df <- alpha_meta_df %>%
  mutate(
    Sed_rate = case_when(
      Unit == "I"   ~ 0.9,
      Unit == "II"  ~ 1.0,
      Unit == "III" ~ 0.2,
      Unit == "IV"  ~ 0.2,
      Unit == "V"   ~ 0.1,
      TRUE ~ NA_real_
    )
  )

alpha_df2 <- alpha_meta_df %>%
  filter(!is.na(alpha_observed), !is.na(Sed_rate)) %>%
  mutate(
    log_div = log(alpha_observed + 1),
    log_sed = log(Sed_rate)
  )

mod_alpha <- lm(log_div ~ log_sed, data = alpha_df2)
summary(mod_alpha)
## 
## Call:
## lm(formula = log_div ~ log_sed, data = alpha_df2)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -2.4080 -0.4208  0.1263  0.4524  1.0375 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  6.61270    0.11578  57.116  < 2e-16 ***
## log_sed      0.48187    0.08955   5.381 9.31e-07 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.6604 on 70 degrees of freedom
## Multiple R-squared:  0.2926, Adjusted R-squared:  0.2825 
## F-statistic: 28.96 on 1 and 70 DF,  p-value: 9.309e-07
alpha_df2$div_corr <- resid(mod_alpha)

summary_alpha_df2 <- alpha_df2 %>%
  group_by(Unit) %>%
  summarise(mean_div_corr = mean(div_corr, na.rm = TRUE),
            sd_div_corr = sd(div_corr, na.rm = TRUE),
            min_date = min(Date_mean, na.rm = TRUE),
            max_date = max(Date_mean, na.rm = TRUE)) %>%
  mutate(med_date = (min_date + max_date)/2) %>% ungroup()

summary_alpha_df2
## # A tibble: 5 × 6
##   Unit  mean_div_corr sd_div_corr min_date max_date med_date
##   <chr>         <dbl>       <dbl>    <dbl>    <dbl>    <dbl>
## 1 I             0.464       0.365     1977     2022    2000.
## 2 II           -0.790       0.717     1961     1976    1968.
## 3 III           0.601       0.190     1824     1960    1892 
## 4 IV           -0.180       0.399     1348     1803    1576.
## 5 V            -0.335       0.218     1146     1309    1228.
sed_rate_alpha <- ggplot(alpha_df2, aes(y = div_corr, x = Date_mean)) +
  geom_vline(xintercept = c(1976, 1960, 1757, 1301), linetype = "dashed", color = "grey") +
  geom_ribbon(aes(ymin = 0, ymax = div_corr), alpha = 0.25) +
  geom_point(data = summary_alpha_df2, aes(x = med_date, y = mean_div_corr), inherit.aes = FALSE, size = 2) +
  geom_line(data = summary_alpha_df2, aes(x = med_date, y = mean_div_corr), inherit.aes = FALSE, size = 0.8) +
  geom_linerange(data = summary_alpha_df2, aes(x = med_date, ymin = mean_div_corr - sd_div_corr, ymax = mean_div_corr + sd_div_corr), inherit.aes = FALSE) +
  labs(x = "Median date", y = "Corrected diversity")+ xlim(1140,2030) +
  theme_pubr(base_size = 12) + coord_flip() 

# Podani partitioning (moving window) using ps_alpha abundance table
otu_alpha_mat <- t(as.data.frame(otu_table(ps_alpha))) # samples as rows
otu_alpha_mat <- otu_alpha_mat[order(rownames(otu_alpha_mat), decreasing = TRUE), ]

window_size <- 2
df_podani <- data.frame()
for(i in 1:(nrow(otu_alpha_mat) - window_size)) {
  tmp <- otu_alpha_mat[i:(i + window_size), ]
  tmp_beta <- adespatial::beta.div.comp(tmp, coef = "J", quant = FALSE)
  tmp_beta <- data.frame(start = rownames(tmp)[1], end = rownames(tmp)[nrow(tmp)], tmp_beta$part) %>%
    tibble::rownames_to_column("component")
  df_podani <- dplyr::bind_rows(df_podani, tmp_beta)
}

# Merge with depth
df_podani<- df_podani %>%
  mutate(period = paste(start, end, sep = "-")) %>%
  mutate(Sample_ID = paste(end)) 

sample_depth <- select(alpha_meta_df, "Sample_ID","Depth_sampling", "Unit")

df_podani <- merge(df_podani, sample_depth, by = "Sample_ID")
df_podani$Depth_sampling <- as.numeric(df_podani$Depth_sampling)

# Plot data
comp_plot <- c("BDtotal","Repl","RichDif")

fig2_podani_plot <- ggplot(df_podani %>% filter(component %in% comp_plot), aes(x = -Depth_sampling, y = tmp_beta.part, color = component, fill = component)) +
  geom_vline(xintercept = c(-41,-93,-137,-202,-226), linetype = "dashed", color = "grey") +
  geom_line(size = 0.9, alpha = 0.6) +
  scale_color_manual(values = c("#616161", "#72B678", "#407B7B")) +
  geom_point(size = 1) +
  coord_flip() + theme_pubr(base_size = 9) + 
  labs(
    x = "Depth (cm)",
    y = "Podani's indices"
  )

# Combine Figure 2 panels
fig2_combined <- sed_rate_foram + sed_rate_alpha + fig2_podani_plot + plot_layout(ncol = 3)
fig2_combined

ggsave(filename = "Outputs/Figure2_alpha_diversity.pdf", plot = fig2_combined,
       width = 200, height = 180, units = "mm", dpi = 600)

#Link DNA concentration, diversity and grain size

#DNA concentration profil
alpha_meta_df$ADN <- as.numeric(alpha_meta_df$ADN)

dna_conc <- ggplot(alpha_meta_df, aes(x = -Depth_reel, y = ADN, color = Part)) +
  geom_point(size = 1) +
  geom_vline(xintercept = c(-41, -93, -137, -202, -226), linetype = "dashed", color = "grey") +
  geom_line(size = 0.9, alpha = 0.6) +
  scale_color_manual(values = Col_unit) +
  coord_flip() +
  theme_pubr(base_size = 9) +
  theme(legend.position = "none") +
  labs(
    x = "Depth (cm)",
    y = "DNA concentration (ng/L)"
  )

alpha_meta_df$Clay <- as.numeric(alpha_meta_df$Clay)

clay_dna <- ggplot(alpha_meta_df, aes(x = Clay, y = ADN, color = Part)) +
  geom_point(size = 1) +
  geom_smooth(aes(group = 1), method = "lm", se = TRUE, color = "black") +
  stat_regline_equation(aes(label = paste(..rr.label..)), 
                        formula = y ~ x, 
                        label.x.npc = "left", 
                        label.y.npc = 0.95, 
                        color = "black") +
  scale_color_manual(values = Col_unit) +
  theme_pubr(base_size = 9) +
  labs(
    x = "Clay proportion (%)",
    y = "DNA concentration (ng/L)"
  )

asv_dna <- ggplot(alpha_meta_df, aes(x = Observed, y = ADN, color = Part)) +
  geom_point(size = 1) +
  geom_smooth(aes(group = 1), method = "lm", se = TRUE, color = "black") +
  stat_regline_equation(aes(label = paste(..rr.label..)), 
                        formula = y ~ x, 
                        label.x.npc = "left", 
                        label.y.npc = 0.95, 
                        color = "black") +
  scale_color_manual(values = Col_unit) +
  theme_pubr(base_size = 9) +
  labs(
    x = "ASV number",
    y = "DNA concentration (ng/L)"
  )

plot_dna <- clay_dna / asv_dna
combined_plot_dna <- dna_conc + plot_dna +
  plot_layout(guides = "collect") & 
  theme(legend.position = "bottom") 
combined_plot_dna

Compare with microeukaryote rarefied dataset

# Microeukaryote
alpha_richness_df <- estimate_richness(ps_rarefied, measures = c("Observed"))
alpha_richness_df$SampleID <- rownames(alpha_richness_df)
# Merge with sample metadata (ensure columns exist)
meta_alpha <- as.data.frame(sample_data(ps_rarefied))
meta_alpha$SampleID <- rownames(meta_alpha)
meta_alpha <- as.matrix(meta_alpha)
meta_alpha <- as.data.frame(meta_alpha)
alpha_meta_df <- left_join(alpha_richness_df, meta_alpha, by = "SampleID")
# Ensure numeric columns
alpha_meta_df$Date_mean <- as.numeric(alpha_meta_df$Date_mean)
alpha_meta_df$Depth_reel <- as.numeric(alpha_meta_df$Depth_reel)
alpha_meta_df$alpha_observed <- as.numeric(alpha_meta_df$Observed)

alpha_meta_df <- alpha_meta_df %>%
  mutate(
    Sed_rate = case_when(
      Unit == "I"   ~ 0.9,
      Unit == "II"  ~ 1.0,
      Unit == "III" ~ 0.2,
      Unit == "IV"  ~ 0.2,
      Unit == "V"   ~ 0.1,
      TRUE ~ NA_real_
    )
  )

alpha_df2 <- alpha_meta_df %>%
  filter(!is.na(alpha_observed), !is.na(Sed_rate)) %>%
  mutate(
    log_div = log(alpha_observed + 1),
    log_sed = log(Sed_rate)
  )

mod_alpha <- lm(log_div ~ log_sed, data = alpha_df2)
summary(mod_alpha)
## 
## Call:
## lm(formula = log_div ~ log_sed, data = alpha_df2)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -2.31547 -0.25423  0.03362  0.43310  1.02832 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   6.5350     0.1151  56.773   <2e-16 ***
## log_sed       0.1950     0.1139   1.712   0.0926 .  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.6436 on 54 degrees of freedom
## Multiple R-squared:  0.05151,    Adjusted R-squared:  0.03394 
## F-statistic: 2.932 on 1 and 54 DF,  p-value: 0.09255
alpha_df2$div_corr <- resid(mod_alpha)

summary_alpha_df2 <- alpha_df2 %>%
  group_by(Unit) %>%
  summarise(mean_div_corr = mean(div_corr, na.rm = TRUE),
            sd_div_corr = sd(div_corr, na.rm = TRUE),
            min_date = min(Date_mean, na.rm = TRUE),
            max_date = max(Date_mean, na.rm = TRUE)) %>%
  mutate(med_date = (min_date + max_date)/2) %>% ungroup()

sed_rate_alpha <- ggplot(alpha_df2, aes(y = div_corr, x = Date_mean)) +
  geom_vline(xintercept = c(1976, 1960, 1757), linetype = "dashed", color = "grey") +
  geom_ribbon(aes(ymin = 0, ymax = div_corr), alpha = 0.25) +
  geom_point(data = summary_alpha_df2, aes(x = med_date, y = mean_div_corr), inherit.aes = FALSE, size = 2) +
  geom_line(data = summary_alpha_df2, aes(x = med_date, y = mean_div_corr), inherit.aes = FALSE, size = 0.8) +
  geom_linerange(data = summary_alpha_df2, aes(x = med_date, ymin = mean_div_corr - sd_div_corr, ymax = mean_div_corr + sd_div_corr), inherit.aes = FALSE) +
  labs(x = "Median date", y = "Corrected diversity") +
  theme_pubr(base_size = 12) + coord_flip() 

# Podani partitioning (moving window) using ps_alpha abundance table
otu_alpha_mat <- t(as.data.frame(otu_table(ps_rarefied))) # samples as rows
otu_alpha_mat <- otu_alpha_mat[order(rownames(otu_alpha_mat), decreasing = TRUE), ]

window_size <- 2
df_podani <- data.frame()
for(i in 1:(nrow(otu_alpha_mat) - window_size)) {
  tmp <- otu_alpha_mat[i:(i + window_size), ]
  tmp_beta <- adespatial::beta.div.comp(tmp, coef = "J", quant = FALSE)
  tmp_beta <- data.frame(start = rownames(tmp)[1], end = rownames(tmp)[nrow(tmp)], tmp_beta$part) %>%
    tibble::rownames_to_column("component")
  df_podani <- dplyr::bind_rows(df_podani, tmp_beta)
}

# Merge with depth
df_podani<- df_podani %>%
  mutate(period = paste(start, end, sep = "-")) %>%
  mutate(Sample_ID = paste(end)) 

sample_depth <- select(alpha_meta_df, "Sample_ID","Depth_sampling", "Unit")

df_podani <- merge(df_podani, sample_depth, by = "Sample_ID")
df_podani$Depth_sampling <- as.numeric(df_podani$Depth_sampling)

# Plot data
comp_plot <- c("BDtotal","Repl","RichDif")

fig2_podani_plot <- ggplot(df_podani %>% filter(component %in% comp_plot), aes(x = -Depth_sampling, y = tmp_beta.part, color = component, fill = component)) +
  geom_vline(xintercept = c(-41,-93,-137), linetype = "dashed", color = "grey") +
  geom_line(size = 0.9, alpha = 0.6) +
  scale_color_manual(values = c("#616161", "#72B678", "#407B7B")) +
  geom_point(size = 1) +
  coord_flip() + theme_pubr(base_size = 12) + 
  labs(
    x = "Depth (cm)",
    y = "Podani's indices"
  )

fig2_rarefied_combined <- sed_rate_alpha + fig2_podani_plot
fig2_rarefied_combined

ggsave(filename = "Outputs/Fig2_rarefied.pdf", plot = fig2_combined,
       width = 200, height = 180, units = "mm", dpi = 600)
## Warning: Removed 2 rows containing missing values or values outside the scale range
## (`geom_ribbon()`).
# Pairwise Wilcoxon among units
pairwise_result_asv <- pairwise.wilcox.test(
  x = alpha_meta_df$alpha_observed,
  g = alpha_meta_df$Unit,
  p.adjust.method = "bonferroni")

pval_asv <- as.data.frame(pairwise_result_asv$p.value)
pval_asv$type <- "ASV"
pval_asv
##                I         II          III type
## II  3.879378e-07         NA           NA  ASV
## III 1.085375e-04 0.02336884           NA  ASV
## IV  1.116067e-06 1.00000000 0.0005103256  ASV
pairwise_result_foram <- pairwise.wilcox.test(
  x = foram_df$Sum_genus,
  g = foram_df$Unit,
  p.adjust.method = "bonferroni")

pval_foram <- as.data.frame(pairwise_result_foram$p.value) 
pval_foram$type <- "Foram" 
pval_foram
##                I           II         III IV  type
## II  6.586559e-01           NA          NA NA Foram
## III 1.059947e-03 7.158574e-02          NA NA Foram
## IV  2.574194e-07 4.666828e-07 0.003762026 NA Foram
## V   8.257217e-04 1.463566e-03 0.343871053  1 Foram

Composition of microeukaryote community

# Resting-stage and unknown-genus subsets (using rs_db_df)
asv_rs_all <- rs_db_df %>% filter(RestingStage == 1) %>% pull(1) %>% na.omit() #based on functional database of Ramond et al., 2018 and additional literature when necessary
asv_unk <- rs_db_df %>% filter(is.na(RestingStage) & Unk_genus == 1) %>% pull(1) %>% na.omit() # i.e., no genus assignment

ps_rs_rar <- prune_taxa(taxa_names(ps_rarefied) %in% asv_rs_all, ps_rarefied)
ps_rs_unk_rar <- prune_taxa(taxa_names(ps_rarefied) %in% asv_unk, ps_rarefied)

# Richness observed
rich_rs <- estimate_richness(ps_rs_rar, measures = "Observed")
rich_rs$SampleID <- rownames(rich_rs)
colnames(rich_rs)[1] <- "Observed_rs"

reads_rs <- colSums(otu_table(ps_rs_rar))
reads_rs_df <- data.frame(SampleID = names(reads_rs), TotalReads_rs = reads_rs, stringsAsFactors = FALSE)

rich_tot <- estimate_richness(ps_rarefied, measures = "Observed")
rich_tot$SampleID <- rownames(rich_tot)
colnames(rich_tot)[1] <- "Observed_tot"
reads_tot <- colSums(otu_table(ps_rarefied))
reads_tot_df <- data.frame(SampleID = names(reads_tot), TotalReads_tot = reads_tot, stringsAsFactors = FALSE)

rich_unk <- estimate_richness(ps_rs_unk_rar, measures = "Observed")
rich_unk$SampleID <- rownames(rich_unk); colnames(rich_unk)[1] <- "Observed_rs_unk"
reads_unk <- colSums(otu_table(ps_rs_unk_rar))
reads_unk_df <- data.frame(SampleID = names(reads_unk), TotalReads_rs_unk = reads_unk, stringsAsFactors = FALSE)

# Merge richness/read summaries
rich_merge <- purrr::reduce(list(rich_tot[,c("Observed_tot","SampleID")], rich_rs[,c("Observed_rs","SampleID")],
                          rich_unk[,c("Observed_rs_unk","SampleID")], reads_tot_df, reads_rs_df, reads_unk_df),
                     function(x,y) full_join(x,y, by = "SampleID"))

# Add sample depth
colnames(sample_depth) <- c("SampleID","Depth_sampling","Unit")
rich_merge <- merge(rich_merge, sample_depth, by = "SampleID")

# Compute percentages
rich_merge <- rich_merge %>%
  mutate(Observed_add = coalesce(Observed_rs,0) + coalesce(Observed_rs_unk,0),
         TotalReads_add = coalesce(TotalReads_rs,0) + coalesce(TotalReads_rs_unk,0),
         perc_asv_rs = Observed_rs_unk / Observed_tot * 100,
         perc_read_rs = TotalReads_rs_unk / TotalReads_tot * 100)

# Visual panels (observed ASV numbers)
rich_merge <- rich_merge %>%
  arrange(Depth_sampling) %>%  # tri par profondeur croissante
  mutate(SampleID = factor(SampleID, levels = SampleID))  # fixe l’ordre pour ggplot

rich_long <- data.frame(SampleID = factor(rep(rich_merge$SampleID, 3), levels = rich_merge$SampleID),
                        Value = c(rich_merge$Observed_tot, rich_merge$Observed_rs, rich_merge$Observed_add),
                        Depth = rep(rich_merge$Depth_sampling, 3),
                        Type = factor(rep(c("Observed_tot","Observed_rs","Observed_rs_unk_add"), each = nrow(rich_merge))))
rich_long$Lower <- 0
rich_long$Depth <- as.numeric(rich_long$Depth)
rich_long$Type <- factor(rich_long$Type, levels = c("Observed_tot","Observed_rs_unk_add","Observed_rs"))

fig3_obs_plot <- ggplot(rich_long, aes(y = Value, x = -Depth, group = Type, color = Type, fill = Type)) +
  geom_ribbon(aes(ymin = Lower, ymax = Value), alpha = 1) +
  geom_line(alpha = 1, size = 1) +
  geom_vline(xintercept = c(-41,-93,-137), linetype = "dashed", color = "grey") +
  ylab("Number of ASV") + xlab("Depth (cm)") + coord_flip() + theme_pubr(base_size = 9) +
  scale_color_manual(values = c("black","#636363","#69C9C9")) +
  scale_fill_manual(values = c("white","#9C9C9C","#95DCDC")) + 
  theme(legend.position = "none")

# Reads panel
reads_long <- data.frame(SampleID = factor(rep(rich_merge$SampleID, 3), levels = rich_merge$SampleID),
                         Value = c(rich_merge$TotalReads_tot, rich_merge$TotalReads_rs, rich_merge$TotalReads_add),
                         Depth = rep(rich_merge$Depth_sampling, 3),
                         Type = factor(rep(c("TotalReads_tot","TotalReads_rs","TotalRead_rs_unk_add"), each = nrow(rich_merge))))
reads_long$Lower <- 0
reads_long$Depth <- as.numeric(reads_long$Depth)
reads_long$Type <- factor(reads_long$Type, levels = c("TotalReads_tot","TotalRead_rs_unk_add","TotalReads_rs"))

fig3_read_plot <- ggplot(reads_long, aes(y = Value, x = -Depth, group = Type, color = Type, fill = Type)) +
  geom_ribbon(aes(ymin = Lower, ymax = Value), alpha = 1) +
  geom_line(alpha = 1, size = 1) +
  geom_vline(xintercept = c(-41,-93,-137), linetype = "dashed", color = "grey") +
  ylab("Number of reads") + coord_flip() + theme_pubr(base_size = 9) +
  scale_color_manual(values = c("black","#636363","#69C9C9")) +
  scale_fill_manual(values = c("white","#9C9C9C","#95DCDC"))+
  theme(axis.title.y = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank())

# Composition of resting-stage taxa (relative abundance)
ps_rs_rel <- transform_sample_counts(ps_rs_rar, function(x) x * 100 / sum(x))
rs_melt <- psmelt(ps_rs_rel)

rs_melt <- rs_melt %>%
  mutate(Subdivision = if_else(Subdivision == "", paste0(.$Division, "_X"), .$Subdivision))%>%
  mutate(Subdivision = if_else(Subdivision == "_X", " Eukaryota_X", .$Subdivision))

rs_agg <- rs_melt %>%
  group_by(Sample, Depth_sampling, Subdivision, Part) %>%
  summarise(Abundance_per_Subdivision = sum(Abundance), .groups = "drop")

# Collapse rare subdivisions into "Others"
rare_subs <- rs_agg %>% 
  group_by(Subdivision) %>% 
  summarise(maxA = max(Abundance_per_Subdivision, na.rm = TRUE)) %>% 
  filter(maxA < 1) %>% pull(Subdivision)

rs_agg <- rs_agg %>% 
  mutate(Subdivision = fct_collapse(as.factor(Subdivision), Others = rare_subs))

# Add filler rows to get nice depth scale (only visualisation purpose)
filler_samples <- data.frame(Sample = c("A40", "A44", "A48", "A52", "A57", "A62", "A66", "A74", "A80", "A86", 
                                        "A108", "A112", "A117", "A122", "A126", "A130", "A134", "A138", "A142",
                                        "A150", "A156", "A162", "A166", "A170", "A174"),
                             Depth_sampling = c(40,44,48,52,57,62,66,74,80,86,108,112,117,122,126,130,134,138,142,150,156,162,166,170,174),
                             Subdivision = "", Part = "None", Abundance_per_Subdivision = 100,
                             stringsAsFactors = FALSE)
filler_samples$Depth_sampling <- as.numeric(filler_samples$Depth_sampling)
rs_agg$Depth_sampling <- as.numeric(rs_agg$Depth_sampling)
rs_plot_df <- bind_rows(rs_agg, filler_samples)

# Factor ordering by depth values (adjust levels if needed)
unique_depths <- sort(unique(as.numeric(rs_plot_df$Depth_sampling)))
rs_plot_df$Depth_sampling <- factor(rs_plot_df$Depth_sampling, levels = as.character(unique_depths))

# Color vector - adjust as desired
col_vector_rs <- c("#F3EB51","#EAE289","#FFA54B","#931C0F","#824600","#F5C17D",
                   "#6373DB","#01579E","#1F91B6","#7DD9F8","#BAF2E9","#FAACEB",
                   "#5A9451","#6BDB57","#979797","white")

rs_plot_df$Subdivision <- factor(rs_plot_df$Subdivision, 
                                   levels=c(" Evosea_X"," Tubulinea_X",
                                            " Chlorophyta_X",
                                            " Haptophyta_X",
                                            " Fungi"," Ichthyosporea",
                                            " Apicomplexa"," Chrompodellids"," Ciliophora"," Dinoflagellata"," Perkinsea",
                                            " Cercozoa",
                                            " Bigyra"," Gyrista",
                                            "Others",""
                                   ))

fig3_compo_rs_plot <- ggplot(rs_plot_df, aes(x = Abundance_per_Subdivision, y = fct_rev(Depth_sampling), fill = Subdivision)) +
  geom_bar(stat = "identity", position = "stack") +
  scale_fill_manual(values = col_vector_rs, guide = guide_legend(ncol = 1)) +
  theme_minimal(base_size = 9) + labs(x = "Relative abundance (%)", y = "Depth") + theme(panel.grid = element_blank())

# For the complete community composition (rarefied)
ps_complet_rel <- transform_sample_counts(ps_rarefied, function(x) x * 100 / sum(x))
complet_melt <- psmelt(ps_complet_rel)

complet_melt <- complet_melt %>%
  mutate(Subdivision = if_else(Subdivision == "", paste0(.$Division, "_X"), .$Subdivision))%>%
  mutate(Subdivision = if_else(Subdivision == "_X", " Eukaryota_X", .$Subdivision))

complet_agg <- complet_melt %>%
  group_by(Sample, Depth_sampling, Subdivision, Part) %>%
  summarise(Abundance_per_Subdivision = sum(Abundance), .groups = "drop")

rare_subs2 <- complet_agg %>% 
  group_by(Subdivision) %>% 
  summarise(maxA = max(Abundance_per_Subdivision, na.rm = TRUE)) %>% 
  filter(maxA < 2) %>% 
  pull(Subdivision)

complet_agg <- complet_agg %>% 
  mutate(Subdivision = fct_collapse(as.factor(Subdivision), Others = rare_subs2))

filler_big <- data.frame(Sample = c("A40", "A44", "A48", "A52", "A57", "A62", "A66", "A74", "A80", "A86", 
                                        "A108", "A112", "A117", "A122", "A126", "A130", "A134", "A138", "A142",
                                        "A150", "A156", "A162", "A166", "A170", "A174"),
                             Depth_sampling = c(40,44,48,52,57,62,66,74,80,86,108,112,117,122,126,130,134,138,142,150,156,162,166,170,174),
                             Subdivision = "", Part = "None", Abundance_per_Subdivision = 100,
                             stringsAsFactors = FALSE)

complet_agg$Depth_sampling <- as.numeric(complet_agg$Depth_sampling)
filler_big$Depth_sampling <- as.numeric(filler_big$Depth_sampling)
complet_plot_df <- bind_rows(complet_agg, filler_big)

unique_depths2 <- sort(unique(as.numeric(complet_plot_df$Depth_sampling)))
complet_plot_df$Depth_sampling <- factor(as.character(complet_plot_df$Depth_sampling), levels = as.character(unique_depths2))

col_vector_complet <- c("#F3EB51","#FFA54B","#DD5757","#931C0F","#740B97","#824600","#F5C17D", "#573000",
                        "#6373DB","#01579E","#1F91B6","#7DD9F8","#023667","#FAACEB","#5A9451","#6BDB57",
                        "#096306","#000000","#979797","white")

complet_plot_df$Subdivision <- factor(complet_plot_df$Subdivision, 
                                    levels=c(" Evosea_X",
                                             " Chlorophyta_X",
                                             " Cryptophyta_X"," Haptophyta_X",
                                             " Breviatea_X",
                                             " Fungi"," Ichthyosporea"," Opisthokonta_X",
                                             " Apicomplexa"," Chrompodellids"," Ciliophora"," Dinoflagellata"," Alveolata_X",
                                             " Cercozoa",
                                             " Bigyra"," Gyrista"," Stramenopiles_X",
                                             " Eukaryota_X","Others",""
                                    ))

fig3_compo_rar_plot <- ggplot(complet_plot_df, aes(x = Abundance_per_Subdivision, y = fct_rev(Depth_sampling), fill = Subdivision)) +
  geom_bar(stat = "identity", position = "stack") +
  scale_fill_manual(values = col_vector_complet, guide = guide_legend(ncol = 1)) +
  theme_minimal(base_size = 9) + labs(x = "Relative abundance (%)", y = "Depth") + theme(panel.grid = element_blank())

fig3_combined <- fig3_obs_plot + fig3_read_plot + fig3_compo_rs_plot + fig3_compo_rar_plot + plot_layout(ncol = 4,nrow=1, heights = c(1,1,1,1))
fig3_combined

ggsave(filename = "Outputs/Figure3_rarefied_composition.pdf", plot = fig3_combined,
       width = 250, height = 200, units = "mm", dpi = 600)

Structure changes in each community

#All aggregate at the genus level for homogeneity

#microeukaryote community: ps_rarefied / ps_alpha
ps_genus <- aggregate_taxa(ps_alpha, 'Genus')

#resting stage subcommunity: ps_rs_rar
physeq_rs <- prune_taxa(taxa_names(ps_alpha) %in% asv_rs_all, ps_alpha)
physeq_rs_genus <- aggregate_taxa(physeq_rs, 'Genus')

#foram: foram_df
foram_df$Sample <- sub("_F$", "", foram_df$Sample)
rownames(foram_df) <- foram_df$Sample
foram_df[is.na(foram_df)] <- 0
foram_sup0 <- foram_df %>%
  filter(Sum_genus > 0) #remove 10 samples with 0 individual found
foram <- foram_sup0[,c(9:33)]

#Microeuk
microeuk_df <- t(as.data.frame(otu_table(ps_genus)))
rs_df <- t(as.data.frame(otu_table(physeq_rs_genus)))

microeuk_df <- ifelse(microeuk_df > 0, 1, 0)
rs_df <- ifelse(rs_df > 0, 1, 0)

mat_microeuk <- vegdist(microeuk_df, method = "jaccard")
mat_rs <- vegdist(rs_df, method = "jaccard")
mat_foram <- vegdist(foram, method = "jaccard")

pcoa_microeuk <- wcmdscale(mat_microeuk, k=2, eig = TRUE)
pcoa_rs <- wcmdscale(mat_rs, k=2, eig = TRUE)
pcoa_foram <- wcmdscale(mat_foram, k=2, eig = TRUE)

point_microeuk <- as.data.frame(pcoa_microeuk$points)
point_rs <- as.data.frame(pcoa_rs$points)
point_foram <- as.data.frame(pcoa_foram$points)

point_microeuk$unit <- sample_data(ps_genus)$Part
point_rs$unit <- sample_data(physeq_rs_genus)$Part
point_foram$unit <- foram_sup0$Unit

plot_microeuk <- ggplot(data = point_microeuk, aes(x = Dim1, y = Dim2, color = unit)) +
  geom_point(size = 2) +
  geom_ysidedensity(aes(y=Dim2, yfill = unit,), alpha = 0.4) +
  geom_xsidedensity(aes(x=Dim1, xfill = unit), alpha = 0.4) +
  scale_xfill_manual(values = Col_unit)+
  scale_yfill_manual(values = Col_unit) +
  scale_color_manual(values = Col_unit)+
  xlab(paste(format((pcoa_microeuk$eig[1]*10), digit = 3),"%")) + 
  ylab(paste(format((pcoa_microeuk$eig[2]*10), digit = 3),"%"))+
  labs(title = "Microeukaryote community")+
  theme_classic() + 
  theme(ggside.panel.scale = .2) +
  theme_ggside_void() 

plot_rs <- ggplot(data = point_rs, aes(x = Dim1, y = Dim2, color = unit)) +
  geom_point(size = 2) +
  geom_ysidedensity(aes(y=Dim2, yfill = unit,), alpha = 0.4) +
  geom_xsidedensity(aes(x=Dim1, xfill = unit), alpha = 0.4) +
  scale_color_manual(values =  Col_unit)+
  scale_xfill_manual(values = Col_unit)+
  scale_yfill_manual(values = Col_unit) +
  xlab(paste(format((pcoa_rs$eig[1]*10), digit = 3),"%")) + 
  ylab(paste(format((pcoa_rs$eig[2]*10), digit = 3),"%"))+
  labs(title = "Resting stage")+
  theme_classic() + 
  theme(ggside.panel.scale = .2) +
  theme_ggside_void() 

plot_foram <- ggplot(data = point_foram, aes(x = Dim1, y = Dim2, color = unit)) +
  geom_point(size = 2) +
  geom_ysidedensity(aes(y=Dim2, yfill = unit,), alpha = 0.4) +
  geom_xsidedensity(aes(x=Dim1, xfill = unit), alpha = 0.4) +
  scale_color_manual(values =  Col_unit)+
  scale_xfill_manual(values = Col_unit)+
  scale_yfill_manual(values = Col_unit) +
  xlab(paste(format((pcoa_foram$eig[1]*10), digit = 3),"%")) + 
  ylab(paste(format((pcoa_foram$eig[2]*10), digit = 3),"%"))+
  labs(title = "Foraminifera")+
  theme_classic() + 
  theme(ggside.panel.scale = .2) +
  theme_ggside_void() 

combined_pcoa <- plot_microeuk + plot_rs + plot_foram + plot_layout(guides = "collect") & theme(legend.position = "bottom")
combined_pcoa

ggsave(filename = "Outputs/Figure4_pcoax3.pdf", plot = combined_pcoa,
       width = 200, height = 85, units = "mm", dpi = 600)

Influence of several group of parameters on this structure

#First need interpolation to compare biological and environmental data at the same depth
env <- env_df %>% mutate(across(c(UB, VS, Clay, Silt, Sand, Ni, Al, COP_perc, NT_perc), 
                             ~as.numeric(gsub(",", ".", .))))

variables_to_interpolate <- c("UB", "VS", "Ni", "Al", "COP_perc", "NT_perc", "Clay", "Silt", "Sand")

env_long_status <- env %>%
  pivot_longer(cols = all_of(variables_to_interpolate), names_to = "variable", values_to = "value") %>%
  mutate(status = ifelse(is.na(value), "interpolated", "measured")) %>%
  select(Codification, Depth, variable, status)

interpolate_full_cm <- function(df, variables) {
  
  full_depth <- seq(min(df$Depth, na.rm = TRUE),
                    max(df$Depth, na.rm = TRUE),
                    by = 0.5)
  
  df_full <- data.frame(Depth = full_depth)
  
  for (var in variables) {
    
    interp_values <- approx(
      x = df$Depth[!is.na(df[[var]])],
      y = df[[var]][!is.na(df[[var]])],
      xout = full_depth,
      method = "linear",
      rule = 2
    )$y
    
    df_full[[var]] <- interp_values
  }
  
  return(df_full)
}

df_interp <- interpolate_full_cm(env, variables_to_interpolate)

#visual check
env_measured_long <- env %>%
  pivot_longer(cols = all_of(variables_to_interpolate),
               names_to = "variable",
               values_to = "measured_value") %>%
  filter(!is.na(measured_value))


df_long <- df_interp %>%
  pivot_longer(cols = all_of(variables_to_interpolate),
               names_to = "variable",
               values_to = "value") %>%
  left_join(env_measured_long,
            by = c("Depth", "variable")) %>%
  mutate(status = ifelse(!is.na(measured_value),
                         "measured",
                         "interpolated"))

ggplot(df_long, aes(x = Depth, y = value)) +
  geom_line(color = "black") +
  geom_point(aes(color = status), size = 2) +
  scale_y_reverse() +
  facet_wrap(~variable, scales = "free_x", nrow = 1) +
  scale_color_manual(values = c("measured" = "black",
                                "interpolated" = "red")) +
  labs(title = "Measured vs interpolated",
       x = "Value",
       y = "Depth (cm)") +
  theme_minimal(base_size = 8) +
  coord_flip()

#Hierarchical partitioning 
hp_function <- function(otutable, env_data) {
  
  env_data <- env_data[match(rownames(otutable), env_data$SampleID), ]
  
  otu_pa <- ifelse(otutable > 0, 1, 0)
  otu.jacc <- vegdist(otu_pa, method = "jaccard")
  
  env.list <- list(
    Grain_size = env_data[,c("Clay","Sand")],
    Metal = env_data[,c("Ni","Al")],
    OM = env_data[,c("COP_perc","NT_perc")],
    Sources = env_data["UB"],
    Depth = env_data["Depth"],
    Unit = env_data["Unite"]
  )
  
  dbRDA.vp <- rdacca.hp(
    otu.jacc,
    env.list,
    method = "dbRDA",
    var.part = TRUE,
    type = "adjR2"
  )
  
  summary(dbRDA.vp)
  
  barplot_hp(dbRDA.vp, col.fill = "var")
  return(dbRDA.vp)
}

env_inter <- df_interp %>% left_join(env_df[, c("SampleID","Depth","Unite")], by = "Depth")
env_inter$Unite <- as.factor(env_inter$Unite)

env_microeuk <- env_inter %>% filter(SampleID %in% rownames(sample_data(ps_genus)))
env_foram <- env_inter %>%  filter(SampleID %in% foram_df$Sample[foram_df$Sum_genus > 0])

micro_all <- t(as.data.frame(otu_table(ps_genus)))
micro_rs <- t(as.data.frame(otu_table(physeq_rs_genus)))

plot1_microeuk <- hp_function(micro_all, env_microeuk)
plot2_rs_microeuk <- hp_function(micro_rs, env_microeuk)
plot3_foram <- hp_function(foram, env_foram)

# total explained variance for each group of parameter
make_hp_table <- function(hp_obj) {
  df <- data.frame(
    Factor = rownames(hp_obj$Hier.part),
    Perc_total = hp_obj$Hier.part[,"I.perc(%)"]
  )
  return(df)
}

# Tables
hp_table_microeuk <- make_hp_table(plot1_microeuk)
hp_table_rs_microeuk <- make_hp_table(plot2_rs_microeuk)
hp_table_foram <- make_hp_table(plot3_foram)

plot_hp <- function(df, title) {
  df$Factor <- factor(df$Factor, levels = c("Unit","Depth","Metal","Sources", "OM","Grain_size")) # same order
  ggplot(df, aes(x = Factor, y = Perc_total)) +
    geom_bar(stat = "identity", fill = "black") +
    coord_flip() +
    labs(x = "Factor", y = "Total contribution (%)", title = title) +
    theme_bw() +
    theme(
      legend.position = "none",
      text = element_text(size = 11),
      axis.line = element_line(color = "black"),
      panel.border = element_blank(),
      panel.background = element_blank()
    ) +
    scale_y_continuous(limits = c(0, 45)) # même échelle
}

p1 <- plot_hp(hp_table_microeuk, "Microeukaryote")
p2 <- plot_hp(hp_table_rs_microeuk, "Resting stage")
p3 <- plot_hp(hp_table_foram, "Foraminifera")

# Combine
combined_hp_plot <- p1 + p2 + p3 + plot_layout(ncol = 3, guides = "collect")
combined_hp_plot

ggsave(filename = "Outputs/Figure4B_hpx3.pdf", plot = combined_hp_plot,
       width = 200, height = 70, units = "mm", dpi = 600)

Genus dynamics

# Prepare foram data
foram_df[is.na(foram_df)] <- 0
rownames(foram_df) <- foram_df$Sample
foram_div <- foram_df[, c(9:33)]   # select relevant columns (species presence/absence)

# Identify non-random distribution patterns using runs test 
# Convert abundance to presence/absence
abundance_data <- foram_div

# Identify ubiquitous taxa present in all samples
genus_all <- colnames(abundance_data)[colSums(abundance_data) == nrow(abundance_data)]

# Remove these columns temporarily to test only the variable taxa
abundance_data2 <- abundance_data[, !(colnames(abundance_data) %in% genus_all)]

# Identify taxa with significantly non-random distributions (p < 0.05)
significant_species <- c()
for (i in 1:ncol(abundance_data2)) {
  species_data <- abundance_data2[, i]
  test_result <- runs.test(as.factor(species_data > 0), alternative = "less")
  if (test_result$p.value < 0.05) {
    significant_species <- c(significant_species, colnames(abundance_data2)[i])
  }
}

# Subset abundance matrix to keep significant + ubiquitous species
subset_abundance_data <- abundance_data[, colnames(abundance_data) %in% c(significant_species, genus_all)]
rownames(subset_abundance_data) <- as.factor(foram_df$Depth)  # use depth as row labels

# Convert to long format for ggplot heatmap 
abundance_data_long <- subset_abundance_data %>%
  as.data.frame() %>%
  rownames_to_column("Row") %>%
  pivot_longer(cols = -Row, names_to = "Column", values_to = "Value")

# Order rows (depths) and columns (taxa)
abundance_data_long$Row <- factor(abundance_data_long$Row, levels = rev(rownames(subset_abundance_data)))
abundance_data_long$Column <- factor(abundance_data_long$Column, levels = c(
  "Ammonia","Quinqueloculina", "Nonion", "Haynesina",
  "Triloculina","Spiroloculina","Wiesnerella","Eggerella",
  "Amphistegina","Planorbulinella"
))

# Color scale
col_fun <- colorRamp2(c(-1, 0, 1), c("#662141", "#FBFBFB", "#524657"))

# Plot heatmap of selected foraminiferal genera
fig5_foram <- ggplot(abundance_data_long, aes(x = Column, y = Row, fill = Value)) +
  geom_tile(color = "white", linewidth = 0.1) +
  scale_fill_gradientn(colors = col_fun(seq(min(abundance_data_long$Value), max(abundance_data_long$Value), length.out = 100))) +
  labs(fill = "Foraminifera presence") +
  theme_minimal(base_size = 10) +
  theme(
    axis.text.x = element_text(angle = 90, vjust = 0.5, size = 10),
    axis.text.y = element_text(size = 7),
    axis.title = element_blank(),
    legend.position = "none"
  )

### Barpolts of filtered microeukaryote genera

# Collapse ASVs to genus level: ps_rs_rarefied
physeq_rs_rar_genus <- aggregate_taxa(ps_rs_rarefied, 'Genus')

# Relative abundance per sample
physeq_rs_genus_rel <- transform_sample_counts(physeq_rs_rar_genus, function(x) x * 100 / sum(x))

# Filter genera: present in >4 samples 
physeq_rs_genus_rel_n4 <- filter_taxa(
  physeq_rs_genus_rel,
  function(x) sum(x > 0) > ((1/56*4)*length(x)),
  TRUE
)

# Convert to long format for tests
genus_n4 <- psmelt(physeq_rs_genus_rel_n4)

# Aggregate data by genus, depth, and stratigraphic unit (Part2)
df_genus <- aggregate(
  Abundance ~ Sample + Genus + OTU + Unit + Depth_sampling,
  data = genus_n4,
  sum
)

# Wilcoxon non-parametric analysis

genus.all <- levels(factor(df_genus$OTU))
tmp <- df_genus[-which(df_genus$Abundance==0),] # remove null values
genus.non.null <- table(tmp$OTU)
#table(tmp$OTU, tmp$Unit) # non null samples per genus and periods

# We want to test differences between periods III and IV (shovel vs. pristine); II and III (tractor vs. shovel); I and II (Regulation effect)

df.test <- NULL

for(i in 1:length(genus.all)){
  
  # Select a genius
  genus.i <- df_genus[which(df_genus$OTU == genus.all[i]),]
  
  # define the periods
  genus.i.period.1 <- genus.i[which(genus.i$Unit == "I"),]
  genus.i.period.2 <- genus.i[which(genus.i$Unit == "II"),]
  genus.i.period.3 <- genus.i[which(genus.i$Unit == "III"),]
  genus.i.period.4 <- genus.i[which(genus.i$Unit == "IV"),]
  
  # Proportion of non null samples in each period
  prop.non.null <- tapply(genus.i$Abundance, genus.i$Unit, function(x)length(which(x==0))/length(x))
  
  # Proportion of non null samples in all sample
  prop.non.null.tot <- length(which(genus.i$Abundance==0))/length(genus.i$Abundance)
  
  # Average abundance in each period 
  avg.abd <- tapply(genus.i$Abundance, genus.i$Unit, mean)
  
  #---- test 1 (shovel vs. pristine)
  test1 <- wilcox.test(genus.i.period.3$Abundance, genus.i.period.4$Abundance)
  rel.chge1 <- ((avg.abd[3]+1) - (avg.abd[4]+1))/(avg.abd[4]+1)*100
  pval1 <- test1$p.value
  
  #---- test 2 (tractor vs. shovel)
  test2 <- wilcox.test(genus.i.period.2$Abundance, genus.i.period.3$Abundance)
  rel.chge2 <- ((avg.abd[2]+1) - (avg.abd[3]+1))/(avg.abd[3]+1)*100
  pval2 <- test2$p.value
  
  #---- test 3 (Regulation effect)
  test3 <- wilcox.test(genus.i.period.1$Abundance, genus.i.period.2$Abundance)
  rel.chge3 <- ((avg.abd[1]+1) - (avg.abd[2]+1))/(avg.abd[2]+1)*100
  pval3 <- test3$p.value
  
  # Store results
  out <- c(genus.all[i], prop.non.null, prop.non.null.tot, avg.abd, rel.chge1, pval1, rel.chge2, pval2, rel.chge3, pval2)
  df.test <- rbind(df.test, out)
  
}

df.test <- as.data.frame(df.test)
colnames(df.test) <- c("genus", 
                       "prop0.I", "prop0.II", "prop0.III", "prop0.IV","prop0.tot",
                       "avgAbd.I", "avgAbd.II", "avgAbd.III", "avgAbd.IV",
                       "rel.chge.test1", "pval.test1", "rel.chge.test2", "pval.test2", "rel.chge.test3", "pval.test3")

df.test[,-1] <- apply(df.test[,-1], 2, function(x)round(as.numeric(x), 3))
rownames(df.test) <- NULL

# FDR Benjamini-Hochberg
df.test$pval.test1.fdr <- p.adjust(df.test$pval.test1, method = "BH")
df.test$pval.test2.fdr <- p.adjust(df.test$pval.test2, method = "BH")
df.test$pval.test3.fdr <- p.adjust(df.test$pval.test3, method = "BH")

#--- Some summary statistics
tmp <- as.matrix(df.test[c("rel.chge.test1", "rel.chge.test2", "rel.chge.test3")])
rownames(tmp) <- df.test$genus

prop.signif <- apply(df.test[c("pval.test1.fdr", "pval.test2.fdr", "pval.test3.fdr")], 2, function(x)length(which(x<0.1))/length(x)) # proportion of species with significant effects
prop.decline <- apply(tmp, 2, function(x)length(which(x<0))/length(x)) # proportion of species declining regardless of significance
prop.increase <- apply(tmp, 2, function(x)length(which(x>0))/length(x)) # proportion of species increasing regardless of significance

n.signif <- apply(df.test[c("pval.test1.fdr", "pval.test2.fdr", "pval.test3.fdr")], 2, function(x) length(which(x < 0.1)))  
n.decline <- apply(tmp, 2, function(x) length(which(x < 0))) 
n.increase <- apply(tmp, 2, function(x) length(which(x > 0)))  

# Créer des matrices logiques pour significativité
sig1 <- df.test$pval.test1.fdr < 0.1
sig2 <- df.test$pval.test2.fdr < 0.1
sig3 <- df.test$pval.test3.fdr < 0.1

# Nombre de genres en déclin significatif
n.decline.sig <- c(
  sum(tmp[,1] < 0 & sig1),
  sum(tmp[,2] < 0 & sig2),
  sum(tmp[,3] < 0 & sig3)
)

# Proportion de genres en déclin significatif
prop.decline.sig <- n.decline.sig / nrow(df.test)

# Nombre de genres en augmentation significative
n.increase.sig <- c(
  sum(tmp[,1] > 0 & sig1, na.rm = TRUE),
  sum(tmp[,2] > 0 & sig2, na.rm = TRUE),
  sum(tmp[,3] > 0 & sig3, na.rm = TRUE)
)

# Proportion de genres en augmentation significative
prop.increase.sig <- n.increase.sig / nrow(df.test)

#--- add Genus 
taxo <- select(genus_n4, "Genus", "OTU")
colnames(df.test)[1] <- "OTU"
df.test2 <- merge(df.test,taxo,  by = "OTU") 
df.test2 <- df.test2 %>% distinct(OTU, .keep_all = TRUE)

# --- Filter significant genera ---
df_filtered <- df.test2 %>% 
  filter(
  pval.test1.fdr < 0.05 |
  pval.test2.fdr < 0.05 |
  pval.test3.fdr < 0.05 |
  prop0.tot < 0.25)


selection_genera <- df_filtered$OTU

genera_filtered <- df_genus %>%
  filter(OTU %in% selection_genera)

genera_filtered$Depth_sampling <- as.numeric(genera_filtered$Depth_sampling) # 23 genera

# Visualisation of some of these genera (based on theur temporal distribution and bibliographic information) 
genera_selected <- c(" Desmodesmus"," Amoebogregarina", " Colpodella",
                " Fungi_XXXX", " Selenidium1"," Paracercomonas", " Scrippsiella",
                " Eocercomonas"," Polyplicarium")

genera_figure <- df_genus %>% filter(Genus %in% genera_selected)

genera_figure$Genus <- factor(genera_figure$Genus,
                                 levels = c(" Paracercomonas", " Amoebogregarina"," Colpodella"," Scrippsiella",
                                            " Selenidium1"," Eocercomonas"," Desmodesmus"," Polyplicarium",
                                            " Fungi_XXXX" ))

col_vector_genus <- c("#FAACEB","#6376DB","#01579E","#7DD9F8",
                      "#6376DB","#FAACEB","#FFA54B","#6376DB",
                      "#824600")

genera_figure$Depth_sampling <- as.numeric(genera_figure$Depth_sampling)

fig5_genus <- ggplot(genera_figure, aes(x = -Depth_sampling, y = Abundance, fill = Genus)) +
  geom_vline(aes(xintercept = -41), linetype = "dashed", color = "grey", size = 0.5) +
  geom_vline(aes(xintercept = -93), linetype = "dashed", color = "grey", size = 0.5) +
  geom_vline(aes(xintercept = -137), linetype = "dashed", color = "grey", size = 0.5) +
  geom_bar(stat = "identity", position = "stack") +
  scale_fill_manual(values = col_vector_genus, guide = guide_legend(ncol = 1)) +
  geom_point(
    data = subset(genera_figure, Abundance == 0),
    aes(x = -Depth_sampling, y = 0),  # y = 0 to highlight absence in the sample
    shape = 21,   
    size = 1,
    fill = "white"
  ) +
  facet_grid(. ~ Genus, scales = "free_x") +
  theme_pubr(base_size = 8) +
  labs(
    x = "Depth (cm)",
    y = "Relative Abundance among resting stage taxa"
  ) +
  theme(
    axis.text.x = element_text(angle = 0, hjust = 1),
    strip.text.y = element_text(angle = 0, size = 10),
    legend.position = "none",
    panel.grid.minor.y = element_blank()
  ) +
  coord_flip()

#Panel of Nickel concentration along the core 

# Define a helper function to linearly interpolate missing values (to create a continuous visualisation)
interpolate_na <- function(df, variables) {
  df <- df %>% 
    mutate(across(
      all_of(variables),
      ~ approx(
        Depth[!is.na(.)], 
        .[!is.na(.)], 
        xout = Depth, 
        method = "linear", 
        rule = 2
      )$y
    )) %>%
    ungroup()
  
  return(df)
}

# --- Apply interpolation to selected variables ---
variables_to_interpolate <- "Ni" #possible to select several variables
df_interpolated <- interpolate_na(env_df, variables_to_interpolate)
df_interpolated <- interpolate_na(env_df, variables_to_interpolate)

# --- Plot Nickel concentration as a vertical gradient ---
fig5_nickel <- ggplot(df_interpolated, aes(x = as.factor(rev(Depth)) , y = 1, fill = Ni)) +
  geom_tile() +
  scale_fill_gradientn(colours = c("#023436", "#FFC65C", "#FF5416")) +
  labs(x = "Depth (cm)", y = NULL, fill = "Nickel (mg kg -1)") +
  coord_flip() +
  theme_minimal() +
  theme(
    axis.text.x = element_text(angle = 90, vjust = 0.5, size = 6),
    axis.title.y = element_blank(),
    axis.text.y = element_text(size = 4),
    panel.grid = element_blank(),
    legend.position = "bottom"
  )

panel_genus <- fig5_genus / plot_spacer() + plot_layout(heights = c(4,0.8))
fig5_combined <- fig5_nickel + fig5_foram + panel_genus + plot_layout(ncol = 3,nrow=1, width = c(0.2,2,3))
fig5_combined

ggsave(filename = "Outputs/Figure5_genus.pdf", plot = fig5_combined,
       width = 200, height = 300, units = "mm", dpi = 600)