#install.packages("ape")
#install.packages("seqinr")
#install.packages ("ggplot2")
#install.packages(tidyverse)

library(ape)
library(seqinr)
library(ggplot2)
library(tidyverse)

# Charge FASTA alignment
alignment <- read.alignment("filename", format = "fasta")
# Convertir l'alignement en objet DNAbin
dna_bin <- as.DNAbin(alignment)

# Calculate genetic distance matrix
dist_matrix <- dist.dna(dna_bin, model = "K80")

# Convert distance matrix into data frame
dist_df <- as.data.frame(as.matrix(dist_matrix))

# compare all our sequence to a reference sequence
reference_sequence <- "choose the reference sequence of interest"

# Filter to only keep comparisons between reference sequence and all the other sequences
long_data <- dist_df %>%
  rownames_to_column(var = "Sequence1") %>%
  pivot_longer(cols = -Sequence1, names_to = "Sequence2", values_to = "Distance") %>%
  filter(Sequence1 == reference_sequence & Sequence2 != reference_sequence) %>%
  mutate(Type = "Reference Comparison")

# print the total number of comparisons
total_comparisons <- nrow(long_data)
print(paste("Nombre total de comparaisons :", total_comparisons))

# print a summary of the genetic distance
print(summary(long_data$Distance))

# generate a graph
ggplot(long_data, aes(x = Distance, fill = Type)) +
  geom_histogram(binwidth = 0.0005, position = "dodge", alpha = 1) +
  labs(title = "Title name", 
       x = "Genetic distance", 
       y = "Frequency") +
  theme_minimal() +
  scale_fill_manual(values = c("darkgreen"), labels = c("Reference Comparison")) +
  theme(
    plot.title = element_text(family = "Arial", face = "bold", size = 14, color = "black", hjust = 1),
    axis.title.x = element_text(family = "Arial", face = "bold", size = 14, color = "black"),
    axis.title.y = element_text(family = "Arial", face = "bold", size = 14, color = "black"),
    legend.title = element_text(family = "Arial", face = "bold", size = 12, color = "black"),
    legend.text = element_text(family = "Arial", size = 10, color = "black")
  )


