# Theme: serotonin-related genes polymorphisms, cortical activity, and impulsivity 
# Author: Dr. Florian Javelle 
# Date last update: 25/01/2022

########################################################################### 
#                       PREPARE WORKSPACE                                 #
###########################################################################  

### Clear workspace
rm(list = ls())

### Clear console
cat("\014")

### Charge required libraries
# Name the libraries
requiredlibraries <- c("tidyr", "dplyr","readr", "data.table", "stringr", "ggplot2", "reshape2", "car", "tidyverse", 
                       "ggpubr", "rstatix", "corrplot", "lm.beta", "DescTools", "ggpmisc")

# Loop over required libraries and install if not present (dependencies might have to be installed manually)
for (i in requiredlibraries) {
  if (!(i %in% rownames(installed.packages()))) install.packages(i, dependencies = TRUE)
}

# Loop over required libraries to load
for (i in requiredlibraries) {
  current_lib <- i
  if (!i=="tidyverse"){
    library(current_lib, character.only=TRUE)}
}

########################################################################### 
#                       GATHER DATA                                       #
###########################################################################  

### Set the working directory
setwd("C:/Users/Florian/Downloads")

### Charge the dataset
# What's the name of the data file to read?
data_file_name <- "Supp_Material_B_MN_bis.csv"

# Read in csv file of data input
fullData <- read.csv(file = data_file_name, header=TRUE, sep=";",
                     stringsAsFactors = FALSE)

########################################################################### 
#                        DATA PRE-CHECK                                   #
###########################################################################  
### Rmq 
# This step, the univariate analysis, and the correlational analysis were performed 
# using SPSS and thus only a brief summary is presented below

### z transformation and winsorization
fullData$z_FTA_screening<-scale(fullData$FTA_screening, center=TRUE, scale=TRUE)
fullData$z_FTA<-scale(fullData$FTA, center=TRUE, scale=TRUE)
fullData$z_PIF<-scale(fullData$PIF, center=TRUE, scale=TRUE)
fullData$z_LFT<-scale(fullData$LFT, center=TRUE, scale=TRUE)
fullData$z_age<-scale(fullData$age, center=TRUE, scale=TRUE)
fullData$z_alpha_mean <-scale (fullData$alpha_mean, center=TRUE, scale=TRUE)
fullData$z_frontal_score <- scale(fullData$frontal_score, center=TRUE, scale=TRUE)
fullData$z_prefrontal_score<-scale(fullData$prefrontal_score, center=TRUE, scale=TRUE)
fullData$z_FP2_FP1_score<-scale(fullData$FP2_FP1_score, center=TRUE, scale=TRUE)
fullData$z_F2_F1_score<-scale(fullData$F2_F1_score, center=TRUE, scale=TRUE)
fullData$z_F4_F3_score<-scale(fullData$F4_F3_score, center=TRUE, scale=TRUE)
fullData$z_F8_F7_score<-scale(fullData$F8_F7_score, center=TRUE, scale=TRUE)

# 1 value in FP2/FP1 score is out of the +-3z boundaries
fullData$z_FP2_FP1_score<-Winsorize(fullData$z_FP2_FP1_score,minval=-3, maxval = 3, na.rm=TRUE)
# 1 value in FP2/FP1 score is out of the +-3z boundaries
fullData$z_F2_F1_score<-Winsorize(fullData$z_F2_F1_score,minval=-3, maxval = 3, na.rm=TRUE)
# 1 value in F4/F3 score is out of the +-3z boundaries
fullData$z_F4_F3_score<-Winsorize(fullData$z_F4_F3_score,minval=-3, maxval = 3, na.rm=TRUE)

### Set variables properly
fullData$stin2<-as.factor(fullData$stin2)
fullData$MAO<-as.factor(fullData$MAO)
fullData$HTTLPR<-as.factor(fullData$HTTLPR)

### Label the variables properly 
# Add labels to 5-HTTLPR categories 
fullData$HTTLPR <- factor(fullData$HTTLPR, levels = c("1", "2", "3"), 
                          labels = c("Low", "Moderate", "High"))

# Add labels to MAO-A categories 
fullData$MAO <- factor(fullData$MAO, levels = c("1", "2"), 
                       labels = c("Low", "High"))

# Add labels to Stin2 categories 
fullData$stin2 <- factor(fullData$stin2, levels = c("1", "2", "3"), 
                         labels = c("Low", "Moderate", "High"))

# Add labels to Stin2 categories 
fullData$gender <- factor(fullData$gender, levels = c("1", "2"), 
                         labels = c("Female", "Male"))

### Linearity with qq plots
# QQ-plot of scaled data against the standard normal distribution

# FTA at screening 
fullData %>%
  ggplot(aes(sample = scale(fullData$z_FTA_screening))) +
  geom_qq() +
  geom_abline()

# FTA at T0
fullData %>%
  ggplot(aes(sample = scale(z_FTA))) +
  geom_qq() +
  geom_abline()

# PIF at T0
fullData %>%
  ggplot(aes(sample = scale(z_PIF))) +
  geom_qq() +
  geom_abline()

# LFT at T0
fullData %>%
  ggplot(aes(sample = scale(z_LFT))) +
  geom_qq() +
  geom_abline()

### Quick tests to evaluate gender differences: t-tests
fullData %>% cohens_d(z_FTA_screening ~ gender, paired = FALSE)

fullData %>% cohens_d(z_FTA ~ gender, paired = FALSE)

fullData %>% cohens_d(z_PIF ~ gender, paired = FALSE)

fullData %>% cohens_d(z_LFT ~ gender, paired = FALSE)

########################################################################### 
#                        Univariate analysis                              #
########################################################################### 
### Rmq
# Brief code for the univariate analysis. The full analysis, including assumptions 
# check and post-hoc tests, was realized on SPSS

### FTA SCREENING
## 5-HTTLPR
# Visualisation by subgroups
fullData %>% filter (!is.na(HTTLPR)) %>% 
  ggscatter(x = "age", y = "z_FTA_screening",
  facet.by  = c("gender", "HTTLPR"), na.rm=TRUE, 
  short.panel.labs = FALSE)+
  stat_smooth(method = "loess", span = 0.9)

# Ancova controlled for age and gender 
ano_HTTLPR_scre<-lm(z_FTA_screening ~ gender + age + HTTLPR, data=fullData)
anova(ano_HTTLPR_scre)

## MAO-A
# Visualisation by subgroups
fullData %>% filter (!is.na(MAO)) %>%  
  ggscatter(x = "age", y = "z_FTA_screening",
    facet.by  = c("gender", "MAO"), na.rm=TRUE, 
    short.panel.labs = FALSE) +
    stat_smooth(method = "loess", span = 0.9)

# Ancova controlled for age and gender 
ano_MAOA_scre<-lm(z_FTA_screening ~ gender + age + MAO, data=fullData)
anova(ano_MAOA_scre)

## STin2
# Linearity by subgroups
fullData %>% filter (!is.na(stin2)) %>% 
  ggscatter(x = "age", y = "z_FTA_screening",
    facet.by  = c("gender", "stin2"), na.rm=TRUE, 
    short.panel.labs = FALSE)+  
    stat_smooth(method = "loess", span = 0.9)

# Ancova controlled for age and gender 
ano_Stin2_scre<-lm(z_FTA_screening ~ gender + age + stin2, data=fullData)
anova(ano_Stin2_scre)

### FTA T0
## 5-HTTLPR
# Visualisation by subgroups
fullData %>% filter (!is.na(HTTLPR)) %>% 
  ggscatter(x = "age", y = "z_FTA",
    facet.by  = c("gender", "HTTLPR"), na.rm=TRUE, 
    short.panel.labs = FALSE)+
    stat_smooth(method = "loess", span = 0.9)

# Ancova controlled for age and gender
ano_HTTLPR_T0<-lm(z_FTA ~ gender + age + HTTLPR, data=fullData)
anova(ano_HTTLPR_T0)
summary(ano_HTTLPR_T0)

## MAO-A 
# Visualisation by subgroups
fullData %>% filter (!is.na(MAO)) %>% 
  ggscatter(x = "age", y = "z_FTA",
    facet.by  = c("gender", "MAO"), na.rm=TRUE, 
    short.panel.labs = FALSE)+
    stat_smooth(method = "loess", span = 0.9)

# Ancova controlled for age and gender
ano_MAOA_T0<-lm(z_FTA ~ gender + age + MAO, data=fullData)
anova(ano_MAOA_T0)

## STin2 
# Visualisation by subgroups
fullData %>% filter (!is.na(stin2)) %>% 
  ggscatter(x = "age", y = "z_FTA",
    facet.by  = c("gender", "stin2"), na.rm=TRUE, 
    short.panel.labs = FALSE)+
    stat_smooth(method = "loess", span = 0.9)

# Ancova controlled for age and gender
ano_Stin2_T0<-lm(z_FTA ~ gender + age + stin2, data=fullData)
anova(ano_Stin2_T0)

### PIF T0
## 5-HTTLPR
# Visualisation by subgroups
fullData %>% filter (!is.na(HTTLPR)) %>% 
    ggscatter(x = "age", y = "z_PIF",
    facet.by  = c("gender", "HTTLPR"), na.rm=TRUE, 
    short.panel.labs = FALSE)+
    stat_smooth(method = "loess", span = 0.9)

# Ancova controlled for age and gender
ano_HTTLPR_T0<-lm(z_PIF ~ gender + age + HTTLPR, data=fullData)
anova(ano_HTTLPR_T0)

## MAO-A
# Visualisation by subgroups
fullData %>% filter (!is.na(MAO)) %>% 
  ggscatter(x = "age", y = "z_PIF",
    facet.by  = c("gender", "MAO"), na.rm=TRUE, 
    short.panel.labs = FALSE)+
    stat_smooth(method = "loess", span = 0.9)

# Ancova controlled for age and gender
ano_MAOA_T0<-lm(z_PIF ~ gender + age + MAO, data=fullData)
anova(ano_MAOA_T0)

## STin2
# Visualisation by subgroups
fullData %>% filter (!is.na(stin2)) %>% 
  ggscatter(x = "age", y = "z_PIF",
            facet.by  = c("gender", "stin2"), na.rm=TRUE, 
            short.panel.labs = FALSE)+
            stat_smooth(method = "loess", span = 0.9)

# Ancova controlled for age and gender
ano_Stin2_T0<-lm(z_PIF ~ gender + age + stin2, data=fullData)
anova(ano_Stin2_T0)

### LFT T0
## 5-HTTLPR
# Visualisation by subgroups
fullData %>% filter (!is.na(HTTLPR)) %>% 
  ggscatter(x = "age", y = "z_LFT",
            facet.by  = c("gender", "HTTLPR"), na.rm=TRUE, 
            short.panel.labs = FALSE)+
  stat_smooth(method = "loess", span = 0.9)

# Ancova controlled for age and gender
ano_HTTLPR_T0<-lm(z_LFT ~ gender + age + HTTLPR, data=fullData)
anova(ano_HTTLPR_T0)

## MAO-A
# Visualisation by subgroups
fullData %>% filter (!is.na(MAO)) %>% 
  ggscatter(x = "age", y = "z_LFT",
            facet.by  = c("gender", "MAO"), na.rm=TRUE, 
            short.panel.labs = FALSE)+
            stat_smooth(method = "loess", span = 0.9)

ano_MAOA_T0<-lm(z_LFT ~ gender + age + MAO, data=fullData)
anova(ano_MAOA_T0)

## STin2
# Visualisation by subgroups
fullData %>% filter (!is.na(stin2)) %>% 
  ggscatter(x = "age", y = "z_LFT",
            facet.by  = c("gender", "stin2"), na.rm=TRUE, 
            short.panel.labs = FALSE)+
            stat_smooth(method = "loess", span = 0.9)

ano_Stin2_T0<-lm(z_LFT ~ gender + age + stin2, data=fullData)
anova(ano_Stin2_T0)

########################################################################### 
#                        CORRELATION ANALYSES                             #
########################################################################### 
### Select T0 data (n=67)
eeg<- fullData%>% filter(T0=="YES")%>% select("z_PIF", "z_LFT","z_FTA", "z_alpha_mean", "z_frontal_score", "z_prefrontal_score",
                         "z_FP2_FP1_score", "z_F2_F1_score","z_F4_F3_score", "z_F8_F7_score")
                   
### Do the pearson's correlations
mcor <- cor(eeg, use="pairwise.complete.obs", method="pearson")

### Create the correlation table  
# Create the Colored palette
col <- colorRampPalette(c("#BB4444", "#EE9988", "#FFFFFF", "#77AADD", "#4477AA"))
# Create the Table
corrplot(mcor, method = "color", col = col(200),number.digits=3,
         type = "upper", order = "original", number.cex = .7, tl.cex=0.8,
         addCoef.col = "black", # Add coefficient of correlation
         tl.col = "black", tl.srt = 90, # Text label color and rotation
         diag = FALSE)

########################################################################### 
#                               MLR Models                                #
########################################################################### 
### Model for FTA at screening  
model1<-lm(z_FTA_screening ~  HTTLPR + MAO + stin2 + gender + z_age, data=fullData)
summary(model1)


## Assumptions
vif(model1)
1/vif(model1)
durbinWatsonTest(model1)

## To get standardized Beta scores
model1_bis<-lm.beta(model1)
summary(model1_bis)

### Model for FTA at T0
## First let's just do the same model than at T0 and compare the results
model2<-lm(z_FTA ~  HTTLPR + MAO + stin2 + z_alpha_mean + z_F4_F3_score + gender + z_age, data=fullData)
summary(model2)

# Assumptions
vif(model2)
1/vif(model2)
durbinWatsonTest(model2)

# To get standardized Beta scores
model2<-lm.beta(model2)
summary(model2)

## Then, let's add the EEG terms and interactions terms 
model2_opt<-lm(z_FTA ~  HTTLPR + MAO + stin2 + z_alpha_mean + z_F4_F3_score + gender + z_age + HTTLPR:z_alpha_mean + 
                 HTTLPR:z_F4_F3_score, data=fullData)
summary(model2_opt)

# Assumptions
vif(model2_opt)
1/vif(model2_opt)
durbinWatsonTest(model2_opt)

# To get standardized Beta scores
model2_opt<-lm.beta(model2_opt)
summary(model2_opt)

## Plotting of model 2's results 
my.formula <- y ~ x

# Plot 1
plot1<-fullData %>%  filter (!is.na(HTTLPR)) %>% 
  ggplot(aes(z_alpha_mean, z_FTA, color=HTTLPR)) +
  geom_point(size=2) + xlab("Individual alpha peak frequency (z score)") + ylab("Feelings Trigger Action (z score)") + 
  geom_smooth(method='lm', formula= my.formula, se=FALSE, fullrange=TRUE) +
  stat_poly_eq(formula = my.formula, aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")), 
             rr.digits = 2, parse = TRUE)+ geom_point()

plot1 + scale_color_manual(values=c("red", "blue", "green"), name="5-HTTLPR phenotypes")


### Model for PIF at T0
model3<-lm(z_PIF ~  HTTLPR + MAO + stin2 + z_alpha_mean + z_F4_F3_score + gender + age + HTTLPR:z_alpha_mean + HTTLPR:z_F4_F3_score, data=fullData)
summary(model3)

# Assumptions
vif(model3)
1/vif(model3)
durbinWatsonTest(model3)

# To get standardized Beta scores
model3<-lm.beta(model3)
summary(model3)


### Model for LFT at T0
model4<-lm(z_LFT ~  HTTLPR + MAO + stin2 + z_alpha_mean + z_F4_F3_score + gender + age + HTTLPR:z_alpha_mean + HTTLPR:z_F4_F3_score, data=fullData)
summary(model4)

# Assumptions
vif(model4)
1/vif(model4)
durbinWatsonTest(model4)

# To get standardized Beta scores
model4<-lm.beta(model4)
summary(model4)

########################################################################### 
#                       SUBGROUPS CORRELATIONS                            #
########################################################################### 

### Correlations between FTA and iAPF for the low transcriptional activity 5-HTTLPR phenotype
# Select the low transcriptional activity 5-HTTLPR phenotype
sub<-fullData  %>%  filter (HTTLPR=="low")
# Select the data of interest 
sub<-sub%>%select("z_FTA", "z_F4_F3_score", "z_alpha_mean")
# Do the correlations 
mcor2 <- cor(sub, use="pairwise.complete.obs", method="pearson")
print(mcor2)
# Plot the results 
corrplot(mcor2, method = c("number"),type="upper",bg="white", diag=FALSE, insig="label_sig", pch="*", sig.level=0.05, order="hclust", tl.col="black", tl.srt=45)


### Correlations between FTA and iAPF for the moderate transcriptional activity 5HTTLPR phenotype
# Select the moderate transcriptional activity 5-HTTLPR phenotype
sub1<-fullData  %>%  filter (HTTLPR=="moderate")
# Select the data of interest 
sub1<-sub1%>%select("z_FTA", "z_F4_F3_score", "z_alpha_mean")
# Do the correlations 
mcor3 <- cor(sub1, use="pairwise.complete.obs", method="pearson")
print(mcor3)
# Plot the results
corrplot(mcor3, method = c("number"),type="upper",bg="white", diag=FALSE, insig="label_sig", pch="*", sig.level=0.05, order="hclust", tl.col="black", tl.srt=45)


### Correlations between FTA and iAPF for high transcriptional activity 5HTTLPR phenotype
# Select the high transcriptional activity 5-HTTLPR phenotype
sub2<-fullData  %>%  filter (HTTLPR=="high")
# Select the data of interest 
sub2<-sub2%>%select("z_FTA", "z_F4_F3_score", "z_alpha_mean")
# Do the correlations 
mcor4 <- cor(sub2, use="pairwise.complete.obs", method="pearson")
print(mcor4)
# Plot the results
corrplot(mcor4, method = c("number"),type="upper",bg="white", diag=FALSE, insig="label_sig", pch="*", sig.level=0.05, order="hclust", tl.col="black", tl.srt=45)






