# ---------------------------------------------------------------------------------------------------
# GWAS on early sexual maturation across freshwater and seawater environments in domesticated Lochy strain of Atlantic Salmon 
# AUTORS: Rivera et.al.,2025
# ---------------------------------------------------------------------------------------------------

# Load libraries

if (!require("BiocManager", quietly = TRUE))
  install.packages("BiocManager")

BiocManager::install("SeqArray")

if (!require("BiocManager", quietly = TRUE))
  install.packages("BiocManager")

BiocManager::install("SeqVarTools")

library(GMMAT)
library(readxl)
library(statgenGWAS)
library(dplyr)
library(tidyr)
library(ggplot2)
library(AGHmatrix)
library(FactoMineR)
library(factoextra)
library(BGLR)
library(qqman)
library(gtable)
library(DescTools)
library(car)
library(reshape2)
library(cowplot)
library(openxlsx)
library(gridExtra)
library(knitr)
library(pander)
library(lmtest)
library(ggstatsplot)
library(dunn.test)
library(ggpubr)

windowsFonts(TNR = windowsFont("Times New Roman"))

# ------------------------------------------------------------------------
#                     SEA ENVIRONMENT
# ------------------------------------------------------------------------
# Phenotypic Analysis
# Load phenotypic data 
Data_pheno <- read_excel("Adittional file 2.xlsx", 
                         sheet = "Table S1", na = "NA")

Data_pheno <- Data_pheno %>%
  mutate(SEX = as.factor(SEX),
         CENTER = as.factor(CENTER),
         ENVIRONMENT = as.factor(ENVIRONMENT),
         SAMPLING_DATE = as.Date(SAMPLING_DATE),
         MATURATION_STATE = as.factor(MATURATION_STATE))

Pheno_mat_714 <- Data_pheno%>%
  filter(ENVIRONMENT=="Sea")

# Set rownames from the ANIMAL column
rownames(Pheno_mat_714) <- Pheno_mat_714$ANIMAL

Pheno_mat_707 <- Data_pheno%>%
  filter(ENVIRONMENT=="Freshwater",TYPE_DATA=="GWAS")

# Set rownames from the ANIMAL column
rownames(Pheno_mat_707) <- Pheno_mat_707$ANIMAL

data <- rbind(Pheno_mat_714,Pheno_mat_707)

pheno1<-subset(Data_pheno,SAMPLING_DATE =="2019-04-01")
pheno2<-subset(Data_pheno,SAMPLING_DATE =="2019-07-01")
pheno3<-subset(Data_pheno,SAMPLING_DATE =="2021-06-01")

phen<-rbind(pheno1, pheno2, pheno3)

sea_phen<- data %>%
  filter(ENVIRONMENT=="Sea")

freq_mat_env<- data%>%
  group_by(MATURATION_STATE, ENVIRONMENT)%>%
  count()

# Calculate the mean by MATURATION_STATE and ENVIRONMENT with aggregate
data_freq <- aggregate(n ~ MATURATION_STATE + ENVIRONMENT, data=freq_mat_env, FUN = mean)
names(data_freq)=c("Maturation_state","Environment","Count")

# Graphs

## Maturation frequencies for GWAS data for both groups, Group-SA and Group-FN

tiff("Fig1.tiff", width = 5, height = 5, units = "in", res = 300)
ggplot(data_freq, aes(x = Maturation_state, y = Count, fill = Maturation_state)) +
  geom_col() +
  scale_fill_manual(values = c("coral", "royalblue4")) +
  labs(y = "Frequency", x = "Maturation state") +
  facet_wrap(~ Environment) +
  theme_classic() +
  geom_text(aes(label = Count, y = Count),vjust = -0.5, position = position_dodge(width = 0.9), size = 4, color = "black", fontface = "bold", family = 'A') +
  theme(
    legend.position = "none",
    strip.text = element_text(face = 'bold', size = 12, color = 'black', family = 'A'),
    axis.title.x = element_text(face = 'bold', size = 12, family = 'A'),
    axis.title.y = element_text(face = 'bold', size = 12, family = 'A'),
    axis.text = element_text(size = 11, family = 'A'),
    plot.title = element_text(hjust = 0.5, family = 'A', size = 12),
    axis.text.y = element_text(family = 'A', size = 12)
  ) +
  ylim(0, 700) 
dev.off()

## Length for all data of Group-SA and for 40 subsampled data employed for the characterization for Group-FN

tiff("Fig2.tiff", width = 5, height = 5, units = "in", res = 300)
ggplot(phen, aes(x=MATURATION_STATE, y= LENGTH_cm, fill=MATURATION_STATE))+geom_boxplot() +labs(y= "Length (cm)", x= "Maturation state")+ facet_wrap(~CENTER+ENVIRONMENT)+theme_classic()+ theme(
  legend.position = "none",
  strip.text = element_text(face = 'bold', size = 12, color = 'black', family = 'A'),
  axis.title.x = element_text(face = 'bold', size = 12, family = 'A'),
  axis.title.y = element_text(face = 'bold', size = 12, family = 'A'),
  axis.text = element_text(size = 11, family = 'A'),
  plot.title = element_text(hjust = 0.5, family = 'A', size = 12),
  axis.text.y = element_text(family = 'A', size = 12))+
  scale_fill_manual(values = c("coral", "royalblue4"))
dev.off()

## Live weight for Group-SA and for 40 subsampled data employed for the characterization for Group-FN

tiff("Fig3.tiff", width = 5, height = 5, units = "in", res = 300)
ggplot(phen, aes(x=MATURATION_STATE, y= LIVE_WEIGHT_g, fill=MATURATION_STATE))+
  geom_boxplot() +labs(y= "Live weight (g)", x= "Maturation state")+ 
  facet_wrap(~CENTER+ENVIRONMENT)+theme_classic()+
  theme(
    legend.position = "none",
    strip.text = element_text(face = 'bold', size = 12, color = 'black', family = 'A'),
    axis.title.x = element_text(face = 'bold', size = 12, family = 'A'),
    axis.title.y = element_text(face = 'bold', size = 12, family = 'A'),
    axis.text = element_text(size = 11, family = 'A'),
    plot.title = element_text(hjust = 0.5, family = 'A', size = 12),
    axis.text.y = element_text(family = 'A', size = 12))+
  scale_fill_manual(values = c("coral", "royalblue4"))
dev.off()

## Whole fish equivalent weight (WFE) only for Group-SA

tiff("Fig4.tiff", width = 5, height = 5, units = "in", res = 300)
ggplot(sea_phen, aes(x=MATURATION_STATE, y= WFE_g, fill=MATURATION_STATE ))+
  geom_boxplot() +
  labs(y= "WFE (g)", x= "Maturation state")+ 
  facet_wrap(~ CENTER)+
  theme_classic()+
  theme(legend.position = "none",
        strip.text = element_text(face = 'bold', size = 12, color = 'black', family = 'A'),
        axis.title.x = element_text(face = 'bold', size = 12, family = 'A'),
        axis.title.y = element_text(face = 'bold', size = 12, family = 'A'),
        axis.text = element_text(size = 11, family = 'A'),
        plot.title = element_text(hjust = 0.5, family = 'A', size = 12),
        axis.text.y = element_text(family = 'A', size = 12))+
  scale_fill_manual(values = c("coral", "royalblue4"))
dev.off()

## Gonadosomatic index (GSI) for Group-SA and for 40 subsampled data employed for the characterization for Group-FN

tiff("Fig5.tiff", width = 5, height = 5, units = "in", res = 300)
ggplot(phen, aes(x=MATURATION_STATE, y= GSI, fill=MATURATION_STATE))+
  geom_boxplot() +
  labs(y= "GSI %", x= "Maturation state")+ 
  facet_wrap(~CENTER+ENVIRONMENT)+
  theme_classic()+
  theme(legend.position = "none",
        strip.text = element_text(face = 'bold', size = 12, color = 'black', family = 'A'),
        axis.title.x = element_text(face = 'bold', size = 12, family = 'A'),
        axis.title.y = element_text(face = 'bold', size = 12, family = 'A'),
        axis.text = element_text(size = 11, family = 'A'),
        plot.title = element_text(hjust = 0.5, family = 'A', size = 12),
        axis.text.y = element_text(family = 'A', size = 12))+
  scale_fill_manual(values = c("coral", "royalblue4"))
dev.off()

# SERNAPESCA Counts for euthanized salmonid fishes for maturation in Chile

data_1 <- read_excel("Adittional file 2.xlsx",sheet = "Table S5")

data_1$Species <- as.factor(data_1$Species)
data_1$Year <- as.factor(data_1$Year)

tiff("Fig6.tiff", width = 10, height = 7, units = "in", res = 300)
ggplot(data_1, aes(x = Year, y = Euthanized, fill = Species)) +
  geom_col() +
  scale_fill_manual(values = c("coral", "lightblue2","darkolivegreen1")) +
  labs(y = "Euthanized mature salmon", x = "Year") +
  facet_wrap(~ Species) +
  theme_classic() +
  geom_text(aes(label = Euthanized), vjust = -0.5, position = position_dodge(width = 0.9), size = 5, color = "black", fontface = "bold",family = 'A') +
  theme(
    legend.position = "none",
    strip.text = element_text(face = 'bold', size = 12, color = 'black', family = 'A'),
    axis.title.x = element_text(face = 'bold', size = 12, family = 'A'),
    axis.title.y = element_text(face = 'bold', size = 12, family = 'A'),
    axis.text = element_text(size = 12, family = 'A',face = 'bold'),
    plot.title = element_text(hjust = 0.5, family = 'A', size = 12,face = 'bold'),
    axis.text.y = element_text(family = 'A', size = 12)
  )
dev.off()

# Summary statistic for Group-SA

## Table 1: Fish production and maturation data for GWAS of Group-SA

Table1 <- sea_phen %>%
  group_by(CENTER, MATURATION_STATE) %>%
  summarize(
    n = n(),
    Length_mean = round(mean(LENGTH_cm, na.rm = TRUE), 2),
    Length_sd = round(sd(LENGTH_cm, na.rm = TRUE), 2),
    WFE_mean = round(mean(WFE_g, na.rm = TRUE), 2),
    WFE_sd = round(sd(WFE_g, na.rm = TRUE), 2),
    Gonad_weight_mean = round(mean(GONAD_WEIGHT_g, na.rm = TRUE), 2),
    Gonad_weight_sd = round(sd(GONAD_WEIGHT_g, na.rm = TRUE), 2),
    GSI_mean = round(mean(GSI, na.rm = TRUE), 2),
    GSI_sd = round(sd(GSI, na.rm = TRUE), 2)
  ) %>%
  mutate(
    Length_sum = paste(Length_mean, "±", Length_sd),
    WFE_sum = paste(WFE_mean, "±", WFE_sd),
    Gonad_weight_sum = paste(Gonad_weight_mean, "±", Gonad_weight_sd),
    GSI_sum = paste(GSI_mean, "±", GSI_sd)
  )

# Select only the columns you want to display in the table
Table1 <- Table1[,c("CENTER", "MATURATION_STATE", "n", "Length_sum", "WFE_sum", "Gonad_weight_sum", "GSI_sum")]
colnames(Table1) <- c("Center", "Maturity", "Fishes for GWAS",
                      "Length (cm)", "WFE (g)", "Gonad Weight (g)", "GSI (%)")

Table1

# Generate the table with the sums of means and standard deviations
pander(Table1, 
       caption = "1: Fish production and maturation data for GWAS of Group-SA, by center and maturation state",
       format = "latex",
       booktabs = TRUE)

## Table 2:Fish production and maturation data for Group-FN

Table2 <- pheno3 %>%
  group_by(MATURATION_STATE) %>%
  summarize(
    n=n(), Live_weight_mean=round(mean(LIVE_WEIGHT_g,na.rm = TRUE),2),
    Live_weight_sd=round(sd(LIVE_WEIGHT_g,na.rm = TRUE),2),
    Length_mean=round(mean(LENGTH_cm,na.rm = TRUE),2),
    Length_sd=round(sd(LENGTH_cm,na.rm = TRUE),2),
    Gonad_weight_mean=round(mean(GONAD_WEIGHT_g,na.rm = TRUE),2),
    Gonad_weight_sd=round(sd(GONAD_WEIGHT_g,na.rm = TRUE),2),
    GSI_mean=round(mean(GSI,na.rm = TRUE),2),
    GSI_sd=round(sd(GSI,na.rm = TRUE),2)) %>%
  mutate(
    Live_weight_sum = paste(Live_weight_mean, "±", Live_weight_sd),
    Length_sum = paste(Length_mean, "±", Length_sd),
    Gonad_weight_sum = paste(Gonad_weight_mean, "±", Gonad_weight_sd),
    GSI_sum = paste(GSI_mean, "±", GSI_sd)
  )

# Select only the columns you want to display in the table
Table2 <- Table2[,c("MATURATION_STATE", "n", "Live_weight_sum", "Length_sum", "Gonad_weight_sum", "GSI_sum")]
colnames(Table2) <- c("Maturity", "Subsampled fishes",
                      "Live Weight (g)", "Length (cm)", "Gonad Weight (g)", "GSI (%)")

Table2

# Generate the table with the sums of means and standard deviations
pander(Table2, 
       caption = "2: Fish production and maturation data for GWAS of Group-FN by maturation state",
       format = "latex",
       booktabs = TRUE)

# Significance tests for productive variables of Group-SA and Group-FN

#Parametric assumptions for GSI in Group-SA
# Two-way ANOVA with interaction
LM_GSI<-aov(GSI~ CENTER*MATURATION_STATE, data=sea_phen);LM_GSI

# Assumption of Independence (No)
dwtest(LM_GSI)

# Anova 
result_anova_gsi <- Anova(LM_GSI, type = "III");result_anova_gsi

# Assumption of Homoscedasticity (No)
lv_sea<-leveneTest(GSI ~ MATURATION_STATE*CENTER, data=sea_phen);lv_sea

# Assumption of Normality (No)
mat_sea<-aov(GSI ~ MATURATION_STATE*CENTER, data=sea_phen)
aov_residuals_sea <- residuals(mat_sea)
shapiro.test(x= aov_residuals_sea)

#conclusion: In this case, considering that none of the assumptions for a two-way ANOVA with interaction are met, 
#            it is recommended to apply a non-parametric test to analyze the GSI data in the sea dataset. 
#            Non-parametric tests do not rely on the assumptions of normality, homogeneity of variances, and independence and can be more appropriate when these assumptions are not met. 
#            One common non-parametric alternative to consider is the Kruskal-Wallis test, which can be used to compare the GSI values across different levels of the categorical variables while accommodating the lack of normality and other assumptions.

#Non-parametric test for GSI in Group-SA by maturation state
new_mutate_date_SA<-sea_phen%>%mutate(Center_Maturity= paste(CENTER, MATURATION_STATE, sep = "_"))

tiff("Fig7.tiff", width = 10, height = 7, units = "in", res = 300)
ggbetweenstats(new_mutate_date_SA,x = Center_Maturity,
               y = GSI,
               type = "nonparametric",  
               p.adjust.method = "bonferroni",
               pairwise.display = "significant", xlab = "Center - Maturation State",
               ylab="GSI (%)")
dev.off()

# Perform Kruskal-Wallis' test
KW_GSI_Sea <- kruskal.test(GSI~Center_Maturity, data=new_mutate_date_SA)
print(KW_GSI_Sea)

# Perform Dunn's test
DT_GSI_Sea <- DunnTest(GSI~Center_Maturity, data=new_mutate_date_SA,method="bonferroni")
print(DT_GSI_Sea)

#Evaluation graph for group-SA
tiff("Fig8.tiff", width = 10, height = 7, units = "in", res = 300)
ggbetweenstats(sea_phen,x = MATURATION_STATE,
               y = GSI,
               type = "nonparametric",  
               p.adjust.method = "bonferroni", ylab="GSI (%)",
               pairwise.display = "significant", xlab = "Maturation State")
dev.off()

# Parametric assumptions for WFE weight only for Group-SA

# Two-way ANOVA with interaction
LM_WFE<-aov(WFE_g~ CENTER*MATURATION_STATE, data=sea_phen);LM_WFE

# Assumption of Independence (Yes)
dwtest(LM_WFE)

# Anova 
result_anova_wfe <- Anova(LM_WFE, type = "III");result_anova_wfe

plot(LM_WFE)

# Assumption of Homoscedasticity (No)
result_levene_wfe <- leveneTest(WFE_g ~ MATURATION_STATE*CENTER, data=sea_phen);result_levene_wfe 

# Assumption of Normality (Yes)
mat_sea_wfe<-aov(WFE_g~ CENTER*MATURATION_STATE, data=sea_phen)
aov_residuals_sea_wfe <- residuals(mat_sea_wfe)
shapiro.test(x= aov_residuals_sea_wfe)

## Nonparametric test for WFE in group-SA
new_mutate_date_wfe<-sea_phen%>%mutate(Center_Maturity= paste(CENTER, MATURATION_STATE, sep = "_"))

tiff("Fig9.tiff", width = 10, height = 7, units = "in", res = 300)
ggbetweenstats(new_mutate_date_wfe,x = Center_Maturity,
               y = WFE_g,
               type = "nonparametric",  
               p.adjust.method = "bonferroni",
               pairwise.display = "significant", ylab = "WFE (g)", xlab = "Center - Maturation State")
dev.off()

tiff("Fig10.tiff", width = 10, height = 7, units = "in", res = 300)
ggbetweenstats(sea_phen,x = MATURATION_STATE,
               y = WFE_g,
               type = "nonparametric",  
               p.adjust.method = "bonferroni",
               pairwise.display = "significant", xlab = "Maturation State",ylab = "WFE (g)")
dev.off()

# Perform Kruskal-Wallis' test
KW_WFE_Sea <- kruskal.test(WFE_g~Center_Maturity, data=new_mutate_date_wfe)
print(KW_WFE_Sea)

# Perform Dunn's test
DT_WFE_Sea <- DunnTest(WFE_g~Center_Maturity, data=new_mutate_date_wfe,method="bonferroni")
print(DT_WFE_Sea)

#Parametric assumptions for Length only for Group-SA
# Two-way ANOVA with interaction
LM_Length<-aov(LENGTH_cm~ CENTER*MATURATION_STATE, data=sea_phen)

# Assumption of Independence (Yes)
dwtest(LM_Length)

#Anova 
result_anova_length_SA <- Anova(LM_Length, type = "III");result_anova_length_SA

plot(LM_Length)

# Assumption of Homoscedasticity (No)
result_levene_length_SA <- leveneTest(WFE_g ~ MATURATION_STATE*CENTER, data=sea_phen);result_levene_length_SA

# Assumption of Normality (No)
mat_sea_length_SA<- aov(LENGTH_cm~ CENTER*MATURATION_STATE, data=sea_phen)
aov_residuals_length_SA <- residuals(mat_sea_length_SA)
shapiro.test(x= aov_residuals_length_SA)

## Nonparametric test for Length in group-SA

new_mutate_date_length_SA<-sea_phen%>%mutate(Center_Maturity= paste(CENTER, MATURATION_STATE, sep = "_"))

tiff("Fig11.tiff", width = 10, height = 7, units = "in", res = 300)
ggbetweenstats(new_mutate_date_length_SA,x = Center_Maturity,
               y = LENGTH_cm,
               type = "nonparametric",  
               p.adjust.method = "bonferroni",
               pairwise.display = "significant", ylab = "Length (cm)", xlab = "Center - Maturation State")

dev.off()

tiff("Fig12.tiff", width = 10, height = 7, units = "in", res = 300)
ggbetweenstats(sea_phen,x = MATURATION_STATE,
               y = LENGTH_cm,
               type = "nonparametric",  
               p.adjust.method = "bonferroni",
               pairwise.display = "significant", xlab = "Maturation State",ylab = "Length (cm)")
dev.off()

# Perform Kruskal-Wallis' test
KW_LENGTH_Sea <- kruskal.test(LENGTH_cm~Center_Maturity, data=new_mutate_date_length_SA)
print(KW_LENGTH_Sea)

# Perform Dunn's test
DT_LENGTH_Sea <- DunnTest(LENGTH_cm~Center_Maturity, data=new_mutate_date_length_SA,method="bonferroni")
print(DT_LENGTH_Sea)

#Parametric assumptions for GSI in Group-FN (Polcura Center)

# One-way ANOVA
LM_GSI_FN<-aov(GSI~ MATURATION_STATE, data=pheno3)
summary(LM_GSI_FN)

### Assumption of Independence (Yes)
dwtest(GSI ~ MATURATION_STATE, data=pheno3)

## Assumption of Homoscedasticity (No)
lv<-leveneTest(GSI ~ MATURATION_STATE, data=pheno3);lv

### Assumption of Normality (No)
mat<- aov(GSI ~ MATURATION_STATE, data=pheno3)
aov_residuals <- residuals(mat)
shapiro.test(x= aov_residuals)

##conclusion: The results of the analysis indicate that the assumptions of homoscedasticity and normality required for one-way ANOVA are not met. Therefore, it is not appropriate to use a parametric one-way ANOVA to compare GSI values across different levels of "MATURATION_STATE". Furthermore, we practice the data transformation (ln, log, sqrt, acos) of variable and the assumptions were not met either

# Non-parametric test for GSI in Group-FN (Polcura Center) by maturation state
mature_polcura<- pheno3[pheno3$MATURATION_STATE=="Mature", c("GSI","MATURATION_STATE")]
immature_polcura<-pheno3[pheno3$MATURATION_STATE=="Immature", c("GSI","MATURATION_STATE")]
wilcox.test(mature_polcura$GSI, immature_polcura$GSI, alternative = "g",exact = FALSE)
## Conclusion non-parametric GSI test for Group-FN: alternative hypotesis is accepted, that is to say, the GSI in mature male is greater than the gonadosomatic index of immature fish.

# Graph of non-parametric test in GSI in group-FN
tiff("Fig13.tiff", width = 10, height = 7, units = "in", res = 300)
ggbetweenstats(pheno3,x = MATURATION_STATE,
               y = GSI,
               type = "nonparametric",  
               p.adjust.method = "bonferroni",
               pairwise.display = "significant", ylab = "GSI (%)", xlab = "Maturation State")
dev.off()

#Parametric assumptions for live weight in Group-FN (Polcura Center)

# One-way ANOVA
LM_WG_FN<-aov(LIVE_WEIGHT_g ~ MATURATION_STATE, data=pheno3)
summary(LM_WG_FN)

### Assumption of Independence (Yes)
dwtest(LIVE_WEIGHT_g ~ MATURATION_STATE, data=pheno3)

## Assumption of Homoscedasticity (Yes)
lv_wg_fn<-leveneTest(LIVE_WEIGHT_g ~ MATURATION_STATE, data=pheno3);lv_wg_fn

### Assumption of Normality (Yes)
mat_wg_fn<- aov(LIVE_WEIGHT_g ~ MATURATION_STATE, data=pheno3)
aov_residuals_wg_fn <- residuals(mat_wg_fn)
shapiro.test(x= aov_residuals_wg_fn)

#  The assumptions for parametric test met

# Graph of parametric test in Live weight (g) in group-FN

tiff("Fig14.tiff", width = 10, height = 7, units = "in", res = 300)
ggbetweenstats(pheno3,x = MATURATION_STATE,
               y = LIVE_WEIGHT_g,
               type = "parametric",
               pairwise.display = "significant", ylab = "Live weight (g)", xlab = "Maturation State")
dev.off()

# Conduct a two-sample Student's t-test
t.test(LIVE_WEIGHT_g ~ MATURATION_STATE, data = pheno3,alternative = "greater")

#Parametric assumptions for Length (cm) in Group-FN (Polcura Center)

# One-way ANOVA
LM_lth_FN<-aov(LENGTH_cm~ MATURATION_STATE, data=pheno3)
summary(LM_lth_FN)

# Conclusion: we fail to reject the null hypothesis, suggesting that MATURATION_STATE does not have a significant effect on the response variable, as the p-value is greater than the commonly used significance level of 0.05.

### Assumption of Independence (Yes)
dwtest(LENGTH_cm~ MATURATION_STATE, data=pheno3)

## Assumption of Homoscedasticity (Yes)
lv_lth<-leveneTest(LENGTH_cm~ MATURATION_STATE, data=pheno3);lv_lth

### Assumption of Normality (Yes)
mat_lth<- aov(LENGTH_cm~ MATURATION_STATE, data=pheno3)
aov_residuals_lth <- residuals(mat_lth)
shapiro.test(x= aov_residuals_lth)

# Genetic Analysis and GWAS

# Load the Molecular Matrix
MM_Sea<- read.table("Geno_714_QC2_imputed.txt",sep = "\t", dec="." , na.strings = "NA",header=TRUE)
row.names(MM_Sea)<-MM_Sea$ANIMAL
MM_Sea<- MM_Sea[,-1]

# Load the Genetic Map QC2
G_MAP_QC2_Sea <- read.table("map_714_QC2_imputed.txt",sep = "\t", dec="." , na.strings = "NA",header=TRUE)

# Count the SNPs per chromosome
count_chr_Sea <- G_MAP_QC2_Sea%>%
  group_by(CHR)%>%
  summarise(nchr= n())

# Estimate average number of SNPs per chromosome
Thres_mean_Sea <- count_chr_Sea%>%
  summarise(umb= mean(nchr))

# Round the estimate average number of SNPs per chromosome to a number
Thres_mean_Sea <- as.numeric(round(Thres_mean_Sea,0))

# Calculate G Matrix
MM_mat_Sea <- as.matrix(MM_Sea)
Gmatrix.VanRaden_Sea <- Gmatrix(MM_mat_Sea, method="VanRaden",maf=0.05)
Gmatrix.VanRaden_Sea <-Gmatrix.VanRaden_Sea[rownames(Pheno_mat_714), rownames(Pheno_mat_714)]

###BGLR PACKAGE####
# Load and prepare the input data
Y_Sea <- data.frame(Pheno_mat_714)
y_Maturation <- Y_Sea[,"MATURITY"]
class(y_Maturation)

# Check the levels of the CENTER variable
levels_CENTER <- levels(as.factor(Pheno_mat_714$CENTER))
n_levels_CENTER <- length(levels_CENTER)

# Display the levels of CENTER
print(n_levels_CENTER)    # Shows the number of levels

# Alternatively, if you only want the number of unique levels
length(unique(Pheno_mat_714$CENTER))

# Fit the model using BGLR package
set.seed(1234)
ETA_Sea <- list(list(~ 1 + CENTER + WFE_g, data=Pheno_mat_714, model= "FIXED"),
                list(K=Gmatrix.VanRaden_Sea,model="RKHS"))

Model_Sea <-BGLR(y=y_Maturation,response_type = "ordinal", ETA=ETA_Sea, nIter=30000, burnIn=15000, thin=10,saveAt="GBLUP_Sea_" )

Var_g_Sea <- scan('GBLUP_Sea_ETA_2_varU.dat')
Var_E_Sea <- scan('GBLUP_Sea_varE.dat')
Var_P_Sea = Var_g_Sea  + Var_E_Sea
h2_Sea_initial = Var_g_Sea/(Var_P_Sea)

# Estimation of Heritability and Its Standard Deviation
h2_Sea<- round(mean(h2_Sea_initial[1501:3000]),2)
sd_h2_Sea <- round(sd(h2_Sea_initial[1501:3000]),2)

# Data preparation
data_h2_Sea <- data.frame(
  Iteration = seq_along(h2_Sea_initial),
  h2 = h2_Sea_initial)

data_h2_Sea_filtered <- subset(data_h2_Sea, Iteration >= 1501 & Iteration <= 3000)

# Fit GLMM (GWAS)
Mod_maturity_714 <- glmmkin(MATURITY ~ 1 + CENTER + WFE_g , data = Pheno_mat_714, 
                            kins = Gmatrix.VanRaden_Sea,
                            id = "ANIMAL", family = binomial(link = "logit"))

# Estimate genotype variance component
var_g_Sea_new <- round(Mod_maturity_714$theta[[2]],2)

# fixed the residual variance component
var_res_Sea_new <- Mod_maturity_714$theta[[1]]

# Estimate heritability
h2_Sea_new <- round(var_g_Sea_new/(var_g_Sea_new+var_res_Sea_new),2)

# Run score test
glmm.score(Mod_maturity_714,infile = "mat_714_QC2_imputed", 
           outfile ="glmm.score.maturity_sea.txt")

# Dataset with score test results
glmm.score.maturity_714 <- read.delim("glmm.score.maturity_sea.txt")
glmm.score.maturity_714 <- data.frame(glmm.score.maturity_714)

# Calculate LOD score for the SNPs, defined as -log10(p-value)
glmm.score.maturity_714 <- glmm.score.maturity_714%>%
  mutate(LOD= -log10(glmm.score.maturity_714$PVAL))

# Estimate bonferroni threshold
LOD_Bonf_Sea <- -log10(0.05/34492);LOD_Bonf_Sea

# Select significant snps considering of bonferroni threshold 
snps_sign_bonf_Sea <- glmm.score.maturity_714%>%
  filter(LOD>LOD_Bonf_Sea)

# Average Threshold per Chromosome 
LOD_mean_Sea <- -log10(0.05/Thres_mean_Sea)

# Select significant snps considering Average Threshold per Chromosome
snps_sign_def_Sea <- glmm.score.maturity_714%>%
  filter(LOD>LOD_mean_Sea)

snpsOfInterest_Sea <- c("Lochy_SNP_Chr_25_Pos_27034108_C")

# Build the manhathan plot
glmm_score_714 <- data.frame(glmm.score.maturity_714)
gwasResults_Sea <- data.frame(glmm_score_714[,c(2,1,4,11)])
colnames(gwasResults_Sea) <- c("SNP", "CHR", "BP","P")

# Significant SNPs 
snps_Sea <- c("Lochy_SNP_Chr_25_Pos_27034108_C")

# Calculate Wald Test
wald_test_maturity_714 <- glmm.wald(MATURITY ~ 1+ CENTER + WFE_g, data = Pheno_mat_714, 
                                    kins = Gmatrix.VanRaden_Sea, id = "ANIMAL",
                                    family = binomial(link = "logit"), infile = "mat_714_QC2_imputed", snps = snps_Sea)

# Estimate proportion of genetic and phenotypic variances (Muhammad et.al., 2020)
VP_per_Sea <- round(2*(wald_test_maturity_714$AF)*(1-wald_test_maturity_714$AF)*(wald_test_maturity_714$BETA)^2/(var_g_Sea_new+var_res_Sea_new),3)*100
VG_per_Sea <- round(2*(wald_test_maturity_714$AF)*(1-wald_test_maturity_714$AF)*(wald_test_maturity_714$BETA)^2/(var_g_Sea_new),3)*100
table_Sea <- data.frame(wald_test_maturity_714$SNP,wald_test_maturity_714,VG_per_Sea, VP_per_Sea)
table_Sea <- table_Sea[,-c(3,4,8,13)]
colnames(table_Sea)<- c("SNP", "Ssa","Pos(bp)", "A1", "A2", "AF", "Effect", "SE", "P", "varG(%)", "varP(%)")
table_Sea

#write.xlsx(table_Sea, "Table_Sea.xlsx", colNames = TRUE, rowNames = FALSE)

# ------------------------------------------------------------------------
#                     FRESH WATER ENVIRONMENT
# ------------------------------------------------------------------------

# Load phenotypic data 
Pheno_mat_707 <- Data_pheno%>%
  filter(ENVIRONMENT=="Freshwater",TYPE_DATA=="GWAS")

# Set rownames from the ANIMAL column
rownames(Pheno_mat_707) <- Pheno_mat_707$ANIMAL

# Load the Molecular Matrix
MM_FW<- read.table("Geno_707_QC2_imputed.txt",sep = "\t", dec="." , na.strings = "NA",header=TRUE)
row.names(MM_FW)<-MM_FW$ANIMAL
MM_FW<- MM_FW[,-1]

# Load the Genetic Map QC2
G_MAP_QC2_FW <- read.table("map_707_QC2_imputed.txt",sep = "\t", dec="." , na.strings = "NA",header=TRUE)

# Count the SNPs per chromosome
count_chr_FW <- G_MAP_QC2_FW%>%
  group_by(CHR)%>%
  summarise(nchr= n())

# Estimate average number of SNPs per chromosome
Thres_mean_FW <- count_chr_FW%>%
  summarise(umb= mean(nchr))

# Round the estimate average number of SNPs per chromosome to a number
Thres_mean_FW <- as.numeric(round(Thres_mean_FW,0))

# Calculate G Matrix
MM_mat_FW <- as.matrix(MM_FW)
Gmatrix.VanRaden_FW <- Gmatrix(MM_mat_FW, method="VanRaden",maf=0.05)
Gmatrix.VanRaden_FW <-Gmatrix.VanRaden_FW[rownames(Pheno_mat_707), rownames(Pheno_mat_707)]

# Identify overlapping SNPs
overlapping_snps <- intersect(colnames(MM_mat_Sea), colnames(MM_mat_FW))

# Count the number of overlapping SNPs
num_overlapping_snps <- length(overlapping_snps)

# Display the result
cat("Answer:", num_overlapping_snps, "SNPs\n")

###BGLR PACKAGE####
# Load and prepare the input data
Y_FW <- data.frame(Pheno_mat_707)
y_Maturation_FW <- Y_FW[,"MATURITY"]
class(y_Maturation_FW)

# Fit the model using BGLR package
set.seed(1234)
Pheno_mat_707$Intercept <- 1
ETA_FW <- list(list(X = Pheno_mat_707[, "Intercept", drop = FALSE], model = "FIXED"),
               list(K=Gmatrix.VanRaden_FW,model="RKHS"))

Model_FW <-BGLR(y=y_Maturation_FW,response_type = "ordinal", ETA=ETA_FW, nIter=30000, burnIn=15000, thin=10,saveAt="GBLUP_FW_" )

Var_g_FW <- scan('GBLUP_FW_ETA_2_varU.dat')
Var_E_FW <- scan('GBLUP_FW_varE.dat')
Var_P_FW = Var_g_FW  + Var_E_FW
h2_FW_initial = Var_g_FW/(Var_P_FW)

# Estimation of Heritability and Its Standard Deviation
h2_FW<- round(mean(h2_FW_initial[1501:3000]),2)
sd_h2_FW <- round(sd(h2_FW_initial[1501:3000]),2)

# Data preparation
data_h2_FW <- data.frame(
  Iteration = seq_along(h2_FW_initial),
  h2 = h2_FW_initial)

data_h2_FW_filtered <- subset(data_h2_FW, Iteration >= 1501 & Iteration <= 3000)

tiff("h2.tiff", width = 15, height = 8, units = "in", res = 300)
# Plotting
h2_Sea_plot <- ggplot(data_h2_Sea_filtered, aes(x = Iteration, y = h2)) +
  geom_line(color = "blue") +  
  geom_point(size = 1, color = "blue") +  
  geom_hline(yintercept = h2_Sea, linetype = "dashed", color = "red", linewidth = 1) + # 
  labs(
    x = "Iterations",
    y = expression(h^2)) +
  theme_bw()+
  theme(plot.title = element_text(hjust = 0.5, family = 'A', size = 12),
        axis.text = element_text(family = 'A', size = 12),
        axis.title.x = element_text(family = 'A', size = 12),
        axis.text.x = element_text(family = 'A', size = 12),
        axis.title.y = element_text(family = 'A', size = 12),
        axis.text.y = element_text(family = 'A', size = 12),
        legend.justification = c(1, 1),
        legend.position = c(1, 1),
        legend.title = element_text(family = 'A', size = 12), 
        legend.text = element_text(family = 'A', size = 12),
        legend.background = element_rect(fill = "white", size = 0.1, linetype = "solid", colour = "black")) +
  scale_y_continuous(limits = c(0, 1), breaks = seq(0, 1, by = 0.1)) 


h2_FW_plot <- ggplot(data_h2_FW_filtered, aes(x = Iteration, y = h2)) +
  geom_line(color = "blue") +  
  geom_point(size = 1, color = "blue") +  
  geom_hline(yintercept = h2_FW, linetype = "dashed", color = "red", linewidth = 1) + # 
  labs(x = "Iterations",
       y = expression(h^2)) +
  theme_bw() +
  theme(plot.title = element_text(hjust = 0.5, family = 'A', size = 12),
        axis.text = element_text(family = 'A', size = 12),
        axis.title.x = element_text(family = 'A', size = 12),
        axis.text.x = element_text(family = 'A', size = 12),
        axis.title.y = element_text(family = 'A', size = 12),
        axis.text.y = element_text(family = 'A', size = 12),
        legend.justification = c(1, 1),
        legend.position = c(1, 1),
        legend.title = element_text(family = 'A', size = 12), 
        legend.text = element_text(family = 'A', size = 12),
        legend.background = element_rect(fill = "white", size = 0.1, linetype = "solid", colour = "black")) +
  scale_y_continuous(limits = c(0, 1), breaks = seq(0, 1, by = 0.1)) 

h2_Sea_A_labeled <- h2_Sea_plot + 
  annotate("text", x = -Inf, y = Inf, label = "A", hjust = -0.5, vjust = 1.5, size = 6, fontface = "bold")

h2_FW_B_labeled <- h2_FW_plot + 
  annotate("text", x = -Inf, y = Inf, label = "B", hjust = -0.5, vjust = 1.5, size = 6, fontface = "bold")

# Combine Plots
combined_plot_h2 <- plot_grid(h2_Sea_A_labeled, h2_FW_B_labeled, labels = NULL, ncol = 1, align = "h")

print(combined_plot_h2)

dev.off()

# Fit GLMM
Mod_maturity_707 <- glmmkin(MATURITY ~ 1, data = Pheno_mat_707, 
                            kins = Gmatrix.VanRaden_FW,
                            id = "ANIMAL", family = binomial(link = "logit"))


# Estimate genotype variance component
var_g_FW_new <- round(Mod_maturity_707$theta[[2]],2)

# fixed the residual variance component
var_res_FW_new <- Mod_maturity_707$theta[[1]]

# Estimate heritability
h2_FW_new <- round(var_g_FW_new/(var_g_FW_new+var_res_FW_new),2)

# Run score test
glmm.score(Mod_maturity_707,infile = "Lochy_2022_707_QC2_imputed", 
           outfile ="glmm.score.maturity_707.txt")

# Dataset with score test results
glmm.score.maturity_707 <- read.delim("glmm.score.maturity_707.txt")
glmm.score.maturity_707 <- data.frame(glmm.score.maturity_707)

# Calculate LOD score for the SNPs, defined as -log10(p-value)
glmm.score.maturity_707 <- glmm.score.maturity_707%>%
  mutate(LOD= -log10(glmm.score.maturity_707$PVAL))

# Estimate bonferroni threshold
LOD_Bonf_FW <- -log10(0.05/49253);LOD_Bonf_FW

# Select significant snps considering of bonferroni threshold 
snps_sign_FW <- glmm.score.maturity_707%>%
  filter(LOD>LOD_Bonf_FW)

# Average Threshold per Chromosome 
LOD_mean_FW <- -log10(0.05/Thres_mean_FW)

# Select significant snps considering Average Threshold per Chromosome
snps_sign_def_FW <- glmm.score.maturity_707%>%
  filter(LOD>LOD_mean_FW)

#write.xlsx(snps_sign_def_FW, "snps_sign_def_FW.xlsx", colNames = TRUE, rowNames = FALSE)

snpsOfInterest_FW <- c("Lochy_SNP_Chr_5_Pos_12841139_C",
                       "Lochy_SNP_Chr_7_Pos_22343952_C",
                       "Lochy_SNP_Chr_7_Pos_22994015_G",
                       "Lochy_SNP_Chr_7_Pos_23669948_T",
                       "Lochy_SNP_Chr_7_Pos_23681850_G",
                       "Lochy_SNP_Chr_7_Pos_26530462_G",
                       "Lochy_SNP_Chr_7_Pos_26540372_C",
                       "Lochy_SNP_Chr_7_Pos_26547695_G",
                       "Lochy_SNP_Chr_7_Pos_26548131_C",
                       "Lochy_SNP_Chr_7_Pos_26653132_C",
                       "Lochy_SNP_Chr_7_Pos_27467174_C",
                       "Lochy_SNP_Chr_7_Pos_27530775_C",
                       "Lochy_SNP_Chr_7_Pos_27531483_C",
                       "Lochy_SNP_Chr_7_Pos_27622831_T",
                       "Lochy_SNP_Chr_7_Pos_27694530_A",
                       "Lochy_SNP_Chr_7_Pos_27789256_T",
                       "Lochy_SNP_Chr_7_Pos_28015283_G",
                       "Lochy_SNP_Chr_7_Pos_32617491_C",
                       "Lochy_SNP_Chr_7_Pos_33011351_A",
                       "Lochy_SNP_Chr_7_Pos_33011447_C",
                       "Lochy_SNP_Chr_7_Pos_33013514_C",
                       "Lochy_SNP_Chr_7_Pos_33280174_A",
                       "Lochy_SNP_Chr_7_Pos_33383270_G",
                       "Lochy_SNP_Chr_7_Pos_33489327_T",
                       "Lochy_SNP_Chr_7_Pos_34703260_T",
                       "Lochy_SNP_Chr_7_Pos_36484833_T",
                       "Lochy_SNP_Chr_25_Pos_22306614_T",
                       "Lochy_SNP_Chr_25_Pos_26329622_T",
                       "Lochy_SNP_Chr_25_Pos_26366278_A",
                       "Lochy_SNP_Chr_25_Pos_26494220_C",
                       "Lochy_SNP_Chr_25_Pos_26726343_C",
                       "Lochy_SNP_Chr_25_Pos_26768024_A",
                       "Lochy_SNP_Chr_25_Pos_26802824_T",
                       "Lochy_SNP_Chr_25_Pos_26860109_G",
                       "Lochy_SNP_Chr_25_Pos_26860561_A",
                       "Lochy_SNP_Chr_25_Pos_26891186_T",
                       "Lochy_SNP_Chr_25_Pos_27137530_T",
                       "Lochy_SNP_Chr_25_Pos_27551406_A",
                       "Lochy_SNP_Chr_25_Pos_27559073_G",
                       "Lochy_SNP_Chr_25_Pos_27565409_G",
                       "Lochy_SNP_Chr_25_Pos_28050348_T",
                       "Lochy_SNP_Chr_25_Pos_28128370_A",
                       "Lochy_SNP_Chr_25_Pos_28161328_A",
                       "Lochy_SNP_Chr_25_Pos_28510872_A",
                       "Lochy_SNP_Chr_25_Pos_28562906_C",
                       "Lochy_SNP_Chr_25_Pos_28567380_C",
                       "Lochy_SNP_Chr_25_Pos_28578694_C",
                       "Lochy_SNP_Chr_25_Pos_28617926_T",
                       "Lochy_SNP_Chr_25_Pos_28623473_G",
                       "Lochy_SNP_Chr_25_Pos_28623749_C",
                       "Lochy_SNP_Chr_25_Pos_28623897_C",
                       "Lochy_SNP_Chr_25_Pos_28656101_T",
                       "Lochy_SNP_Chr_25_Pos_28658151_C",
                       "Lochy_SNP_Chr_25_Pos_28666061_T",
                       "Lochy_SNP_Chr_25_Pos_28667099_T",
                       "Lochy_SNP_Chr_25_Pos_28819973_G",
                       "Lochy_SNP_Chr_25_Pos_29451789_C",
                       "Lochy_SNP_Chr_25_Pos_29453674_A",
                       "Lochy_SNP_Chr_25_Pos_29697092_G",
                       "Lochy_SNP_Chr_25_Pos_31844782_C")


# Build the manhathan plot
glmm_score_707 <- data.frame(glmm.score.maturity_707)
gwasResults_FW <- data.frame(glmm_score_707[,c(2,1,4,11)])
colnames(gwasResults_FW) <- c("SNP", "CHR", "BP","P")

# Manhattan Plot Sea and Fresh Water environment (Bonferroni threshold)
tiff("Manhattan_plot.tiff", width = 20, height = 15, units = "in", res = 300)
par(mfrow = c(2, 1), mar = c(5, 5, 6, 2)) 
manhattan(gwasResults_Sea, chr = "CHR", bp = "BP", p = "P", snp = "SNP",
          col = c("blue4", "orange3"),ylim = c(0, 10),
          chrlabs = c("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29"),
          suggestiveline = LOD_mean_Sea,genomewideline =-log10(0.05/34492),
          highlight = snpsOfInterest_Sea,logp = TRUE, annotatePval = NULL,
          annotateTop = TRUE,family = 'TNR', font.lab = 2, cex.main = 1.5,   
          cex.lab = 1.5,     
          cex.axis = 1)
mtext("a", side = 3, line = 2, adj = -0.02, font = 2, cex = 2, family = "TNR")

manhattan(gwasResults_FW, chr = "CHR", bp = "BP", p = "P", snp = "SNP",
          col = c("blue4", "orange3"),ylim = c(0, 10),
          chrlabs = c("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29"),
          suggestiveline = LOD_mean_FW,genomewideline = -log10(0.05/49253),
          highlight = snpsOfInterest_FW,logp = TRUE, annotatePval = NULL,
          annotateTop = TRUE,family = 'TNR', font.lab = 2, cex.main = 1.5,   
          cex.lab = 1.5,     
          cex.axis = 1)
mtext("b", side = 3, line = 2, adj = -0.02, font = 2, cex = 2, family = "TNR")
dev.off()

# Q-Q plot of GWAS p-values (Sea and Fresh Water environment)
tiff("QQ_plot.tiff", width = 15, height = 12, units = "in", res = 300)
par(mfrow = c(2, 1), mar = c(5, 5, 4, 2)) 

qq(gwasResults_Sea$P, xlim = c(0, 7),
   ylim = c(0, 12), pch = 19, col = "blue4", cex = 0.3, las = 1, family = "TNR", font.lab = 2, cex.main = 1,cex.lab = 1,cex.axis = 1)

# Calculation of lambda
observed_qq_sea <- -log10(gwasResults_Sea$P)
expected_qq_sea <- qchisq((1:length(gwasResults_Sea$P))/(length(gwasResults_Sea$P) + 1), df = 1)
lambda_value_sea <- round(median(observed_qq_sea) / median(expected_qq_sea), 2)

# Print the lambda symbol and value
text(0.5, 11, expression(paste(lambda, "Value: 0.66")), pos = 4, col = "black", cex = 1.5, font = 2)

mtext("A", side = 3, line = -1.5, adj = 0.01, font = 2, cex = 1.5)

qq(gwasResults_FW$P, xlim = c(0, 7),
   ylim = c(0, 12), pch = 19, col = "blue4", cex = 0.3, las = 1, family = "TNR", font.lab = 2, cex.main = 1,cex.lab = 1,cex.axis = 1)

# Calculation of lambda
observed_qq_FW <- -log10(gwasResults_FW$P)
expected_qq_FW <- qchisq((1:length(gwasResults_FW$P))/(length(gwasResults_FW$P) + 1), df = 1)
lambda_value_FW <- round(median(observed_qq_FW) / median(expected_qq_FW), 2)

# Print the lambda symbol and value
text(0.5, 11, expression(paste(lambda, "Value: 0.63")), pos = 4, col = "black", cex = 1.5, font = 2)
mtext("B", side = 3, line = -1.5, adj = 0.01, font = 2, cex = 1.5)

dev.off()

snps_FW <- c("Lochy_SNP_Chr_5_Pos_12841139_C",
             "Lochy_SNP_Chr_7_Pos_22343952_C",
             "Lochy_SNP_Chr_7_Pos_22994015_G",
             "Lochy_SNP_Chr_7_Pos_23669948_T",
             "Lochy_SNP_Chr_7_Pos_23681850_G",
             "Lochy_SNP_Chr_7_Pos_26530462_G",
             "Lochy_SNP_Chr_7_Pos_26540372_C",
             "Lochy_SNP_Chr_7_Pos_26547695_G",
             "Lochy_SNP_Chr_7_Pos_26548131_C",
             "Lochy_SNP_Chr_7_Pos_26653132_C",
             "Lochy_SNP_Chr_7_Pos_27467174_C",
             "Lochy_SNP_Chr_7_Pos_27530775_C",
             "Lochy_SNP_Chr_7_Pos_27531483_C",
             "Lochy_SNP_Chr_7_Pos_27622831_T",
             "Lochy_SNP_Chr_7_Pos_27694530_A",
             "Lochy_SNP_Chr_7_Pos_27789256_T",
             "Lochy_SNP_Chr_7_Pos_28015283_G",
             "Lochy_SNP_Chr_7_Pos_32617491_C",
             "Lochy_SNP_Chr_7_Pos_33011351_A",
             "Lochy_SNP_Chr_7_Pos_33011447_C",
             "Lochy_SNP_Chr_7_Pos_33013514_C",
             "Lochy_SNP_Chr_7_Pos_33280174_A",
             "Lochy_SNP_Chr_7_Pos_33383270_G",
             "Lochy_SNP_Chr_7_Pos_33489327_T",
             "Lochy_SNP_Chr_7_Pos_34703260_T",
             "Lochy_SNP_Chr_7_Pos_36484833_T",
             "Lochy_SNP_Chr_25_Pos_22306614_T",
             "Lochy_SNP_Chr_25_Pos_26329622_T",
             "Lochy_SNP_Chr_25_Pos_26366278_A",
             "Lochy_SNP_Chr_25_Pos_26494220_C",
             "Lochy_SNP_Chr_25_Pos_26726343_C",
             "Lochy_SNP_Chr_25_Pos_26768024_A",
             "Lochy_SNP_Chr_25_Pos_26802824_T",
             "Lochy_SNP_Chr_25_Pos_26860109_G",
             "Lochy_SNP_Chr_25_Pos_26860561_A",
             "Lochy_SNP_Chr_25_Pos_26891186_T",
             "Lochy_SNP_Chr_25_Pos_27137530_T",
             "Lochy_SNP_Chr_25_Pos_27551406_A",
             "Lochy_SNP_Chr_25_Pos_27559073_G",
             "Lochy_SNP_Chr_25_Pos_27565409_G",
             "Lochy_SNP_Chr_25_Pos_28050348_T",
             "Lochy_SNP_Chr_25_Pos_28128370_A",
             "Lochy_SNP_Chr_25_Pos_28161328_A",
             "Lochy_SNP_Chr_25_Pos_28510872_A",
             "Lochy_SNP_Chr_25_Pos_28562906_C",
             "Lochy_SNP_Chr_25_Pos_28567380_C",
             "Lochy_SNP_Chr_25_Pos_28578694_C",
             "Lochy_SNP_Chr_25_Pos_28617926_T",
             "Lochy_SNP_Chr_25_Pos_28623473_G",
             "Lochy_SNP_Chr_25_Pos_28623749_C",
             "Lochy_SNP_Chr_25_Pos_28623897_C",
             "Lochy_SNP_Chr_25_Pos_28656101_T",
             "Lochy_SNP_Chr_25_Pos_28658151_C",
             "Lochy_SNP_Chr_25_Pos_28666061_T",
             "Lochy_SNP_Chr_25_Pos_28667099_T",
             "Lochy_SNP_Chr_25_Pos_28819973_G",
             "Lochy_SNP_Chr_25_Pos_29451789_C",
             "Lochy_SNP_Chr_25_Pos_29453674_A",
             "Lochy_SNP_Chr_25_Pos_29697092_G",
             "Lochy_SNP_Chr_25_Pos_31844782_C")

# Calculate Wald Test
wald_test_maturity_707 <- glmm.wald(fixed = MATURITY ~ 1, data = Pheno_mat_707, kins = Gmatrix.VanRaden_FW, id = "ANIMAL",
                                    family = binomial(link = "logit"), infile = "Lochy_2022_707_QC2_imputed", snps = snps_FW)

# Estimate proportion of genetic and phenotypic variances (Aslam et.al., 2020)
VP_per_FW <- round(2*(wald_test_maturity_707$AF)*(1-wald_test_maturity_707$AF)*(wald_test_maturity_707$BETA)^2/(var_g_FW_new+var_res_FW_new),3)*100
VG_per_FW <- round(2*(wald_test_maturity_707$AF)*(1-wald_test_maturity_707$AF)*(wald_test_maturity_707$BETA)^2/(var_g_FW_new),3)*100
table_FW <- data.frame(wald_test_maturity_707$SNP,wald_test_maturity_707,VG_per_FW, VP_per_FW)
table_FW <- table_FW[,-c(3,4,8,13)]
colnames(table_FW)<- c("SNP", "Ssa","Pos(bp)", "A1", "A2", "AF", "Effect", "SE", "P", "varG(%)", "varP(%)")
table_FW

#write.xlsx(table_FW, "Table_FW.xlsx", colNames = TRUE, rowNames = FALSE)

# Save objects
save.image("Rivera_et_al_2025_Suplementary_Material.RData")

# Load objects
#load("Rivera_et_al_2025_Suplementary_Material.RData")
